Page 1 of 1

comparing 2 arrays (ruby)

Posted: Fri Jan 03, 2014 12:14 am
by tester
I need to do one of two things:

a) compare 2 arrays of elements and get an output with 0's (element at index not equal) and 1's (element at index equal)
or
b) determine which elements on input array changed after single retrig, and get an output like described above.

I guess the (a) is easier to implement.
It would be like this:

array1:

11
9
3
40
5

array2 (= array1 after change)

11
25
34
40
7

output:

1
0
0
1
0

(no sorting, no duplicate removing). How to make it with ruby?

Re: comparing 2 arrays (ruby)

Posted: Fri Jan 03, 2014 12:41 am
by tester
I think I found something, but... How to push these values to output?

I mean - ruby window shows correct answers, but when I add "output..." then it outputs only 0's or nothing.

Re: comparing 2 arrays (ruby)

Posted: Fri Jan 03, 2014 1:20 am
by tester
...not what I expected. Right now I can get this - works only with output changed to "string". But how to get simple array of 0/1 integers instead?

Re: comparing 2 arrays (ruby)

Posted: Fri Jan 03, 2014 4:04 am
by TrojakEW
Now just simply convert them.

Re: comparing 2 arrays (ruby)

Posted: Fri Jan 03, 2014 9:09 am
by Nubeat7
it is possible with just one map command too
for comparing things with 2 options the ternary operator ( ? : ) always comes very handy

it works like this:
(condition) ? (when true) : (when false)

Code: Select all

output @in1.map.with_index { |x,i| x = x==@in2[i] ? 1 : 0 }

Re: comparing 2 arrays (ruby)

Posted: Fri Jan 03, 2014 11:36 am
by tester
Thanks!

Re: comparing 2 arrays (ruby)

Posted: Fri Jan 03, 2014 1:28 pm
by tester
So this little schematic will detect which values in input array have changed (per cycle).