Multiple conditions in a for loop? - julia

I am trying to figure out what this pseudocode would be in Julia code:
Pseudocode:
for (i = 0; (i < 32) && (array[i] ≠ nil); i += 1) do
result := merge(array[i], result)
array[i] := nil
The multiple conditions seem to trip me up. I don't know how to format it in Julia. If anyone knows how I would appreciate it. I am new to the language.

There are multiple ways to do it in Julia. For example, you can use break statement
for i in 1:32 # in Julia we usually start numbering from 1
array[i] == nothing && break
result = merge(array[i], result)
array[i] = nothing
end
or while loop
i = 1
while i <= 32 && array[i] != nothing
result = merge(array[i], result)
array[i] = nothing
i += 1
end

You could do the looping and put the conditional inside:
nil = nothing #or any other sentinel value
for i in 1:32 #for i in eachindex(array)
if array[i] != nil #if cond1 & cond2 & cond3... &condn
result = merge(result, array[i])
array[i] = nil
end
end

Related

Comparison of pointers that contain the same address?

My function adds all elements of an array together and takes the "start" pointer and the "end" pointer(I know there are easier ways to get the sum). My problem is that my for-loop is skipped. But if I test the condition separately it works. Does that have anything to do with the order of execution of the for-loop?
My example:
int arr[]={3, 2, 1, 1}
int *start = &arr[0]
int *end = &arr[3]
printf("%d\n", (&start[0] == end)) //The result is 0(false)
printf("%d\n", (&start[3] == end)); // The result is 1(true)
for (int i = 0; (&start[i] == end); i++) // The for-loop dosen't get executed.
if i==0 then the condition is false, so the loop is not executed..
if you want to go through the array you should write &start[i] != end for the condition

switching produce() with put!()

i am trying to modify a code that was written in julia 0.4 and one of these modifications is replacing produce() with put!()but i don't really know how am i suppose to replace it knowing that put!()requires Channel
i have tried c=Channel(i); put!(c,v) but i don't know if it is the right way to replace it in this function below
function scan()
i = 1
init = 1
while i > 0
if i >= init
#objective(m, Max, x[i])
res = JuMP.solve(m, suppress_warnings=true)
if res==:Optimal || res==:Unbounded
ub[i] = round(Int, getvalue(x[i]))
setobjectivesense(m, :Min)
res = JuMP.solve(m, suppress_warnings=true)
#assert res==:Optimal || res==:Unbounded
lb[i] = round(Int, getvalue(x[i]))
v[i] = lb[i]
init += 1
else
#assert res==:Infeasible
i -= 1
continue
end
elseif v[i] < ub[i]
v[i] += 1
else
setupperbound(x[i], Inf)
setlowerbound(x[i], -Inf)
init -= 1
i -= 1
continue
end
if i >= level
produce(v) # the line to be replaced
continue
else
setupperbound(x[i], v[i])
setlowerbound(x[i], v[i])
i += 1
end
end
end

Remove ifs from Javascript code

Can i program without if statements in functional programming in JS?
In Haskell you can do pattern matching:
sign x | x > 0 = 1
| x == 0 = 0
in js:
sing = x => {
if (x > 0) return 1;
else if (x == 0) return 0
}
I can do shorthand if operator something like this:
sign = x => x > 0 ? 1 (x == 0 ? 0 : x)
Can I make the code shorter without library and ?: operator above ?
This might not be the answer your looking for but the shortest way to write this code is:
return !!x+0;
explanation
!!x casts x to a boolean: x>0 == true x = 0 == false;
+0 casts to integer: true = 1, false = 0.
But no there is no other style than using ?: operator.
javascript shorthand usefullness
In javascript you have other helpful tricks like:
Automatically casting things to thruties or falsies. (when boolean required)
Or operator returning the value, easy for null coalescing: var name = null || 'joel' // name = 'joel'

Why is this recursive function exceeding call stack size?

I'm trying to write a function to find the lowest number that all integers between 1 and 20 divide. (Let's call this Condition D)
Here's my solution, which is somehow exceeding the call stack size limit.
function findSmallest(num){
var count = 2
while (count<21){
count++
if (num % count !== 0){
// exit the loop
return findSmallest(num++)
}
}
return num
}
console.log(findSmallest(20))
Somewhere my reasoning on this is faulty but here's how I see it (please correct me where I'm wrong):
Calling this function with a number N that doesn't meet Condition D will result in the function being called again with N + 1. Eventually, when it reaches a number M that should satisfy Condition D, the while loop runs all the way through and the number M is returned by the function and there are no more recursive calls.
But I get this error on running it:
function findSmallest(num){
^
RangeError: Maximum call stack size exceeded
I know errors like this are almost always due to recursive functions not reaching a base case. Is this the problem here, and if so, where's the problem?
I found two bugs.
in your while loop, the value of count is 3 to 21.
the value of num is changed in loop. num++ should be num + 1
However, even if these bugs are fixed, the error will not be solved.
The answer is 232792560.
This recursion depth is too large, so stack memory exhausted.
For example, this code causes same error.
function foo (num) {
if (num === 0) return
else foo(num - 1)
}
foo(232792560)
Coding without recursion can avoid errors.
Your problem is that you enter the recursion more than 200 million times (plus the bug spotted in the previous answer). The number you are looking for is the multiple of all prime numbers times their max occurrences in each number of the defined range. So here is your solution:
function findSmallestDivisible(n) {
if(n < 2 || n > 100) {
throw "Numbers between 2 and 100 please";
}
var arr = new Array(n), res = 2;
arr[0] = 1;
arr[1] = 2;
for(var i = 2; i < arr.length; i++) {
arr[i] = fix(i, arr);
res *= arr[i];
}
return res;
}
function fix(idx, arr) {
var res = idx + 1;
for(var i = 1; i < idx; i++) {
if((res % arr[i]) == 0) {
res /= arr[i];
}
}
return res;
}
https://jsfiddle.net/7ewkeamL/

SQL Get Rows With A Similar Column Value

I have a database that sometimes stores duplicate rows, however the duplicate is not clear cut, e.g. the following two column values would be a duplicate:
G12345 & G1234 --> because they are very similar
(a string comparison shows that the characters match 83.3%).
I need some help writing an SQL query that would retrieve values that are very similar to a string sent as part of the query, e.g. over 50% of characters matched.
Can someone help with this? I have a C# method as follows but not quite sure how to accomplish this in SQL:
static double StringCompare(string a, string b)
{
if (a == b) //Same string, no iteration needed.
return 100;
if ((a.Length == 0) || (b.Length == 0)) //One is empty, second is not
{
return 0;
}
var maxLen = a.Length > b.Length ? a.Length : b.Length;
var minLen = a.Length < b.Length ? a.Length : b.Length;
var sameCharAtIndex = 0;
for (var i = 0; i < minLen; i++) //Compare char by char
{
if (a[i] == b[i])
{
sameCharAtIndex++;
}
}
return sameCharAtIndex / maxLen * 100;
}
Thanks in advance.
Not sure if your trying to use SQL-Server or MySQL, but you could create and use the following function in SQL-Server:
create function StringCompare
(#A nvarchar(200),
#B nvarchar(200)
)
returns float
as
begin
if (
#A = #B
or (#A is null and #B is null)
)
begin
return 100.0
end
if (
((#A is null or len(#A) = 0) and (#B is not null and len(#B) > 0))
or ((#B is null or len(#B) = 0) and (#A is not null and len(#A) > 0))
)
begin
return 0.0
end
declare #maxLen int
set #maxLen = case when len(#A) > len(#B) then len(#A) else len(#B) end
declare #minLen int
set #minLen = case when len(#A) < len(#B) then len(#A) else len(#B) end
declare #sameCharAtIndex int
set #sameCharAtIndex = 0
declare #count int
set #count = 1
while (#count <= #minLen)
begin
if (SUBSTRING(#A, #count, 1) = substring(#B, #count, 1))
begin
set #sameCharAtIndex = #sameCharAtIndex + 1
end
set #count = #count + 1
end
return cast(#sameCharAtIndex as float) / cast(#maxLen as float) * 100.0
end
which could be used in any statement as follows:
select dbo.StringCompare('test', 'test'), dbo.StringCompare('nope', 'test'), dbo.StringCompare('partial', 'parsomethingelse')
please note, having a loop like this in sql running on many records can be inefficient. And you may want to consider whether you really have to do it in sql.
Use Mysql Like Operator instead of doing in service layer.
SELECT * FROM table WHERE column LIKE 'G12___' or 'G12%'.
SELECT * FROM table WHERE column LIKE '%input string as parameter%'.
The "_" wildcard in LIKE predicates means "one of any character," equivalent to "." in regular expressions.
See this for reference.

Resources