How to find all array elements that match both arrays - arrays

Is there an easy way to iterate through 2 arrays and find any element values that are exactly the same in both arrays and populate it into a new array?
For example:
arr_a = ["a","b","c","d"]
arr_b = ["123","456","b","d","c"]
The array I want to create would be:
new_arr = ["b","c","d"]
I tried this:
another_arr = [*arr_a, *arr_b] #combines the 2 arrays
another_arr.select { |e| another_arr.count(e) >1 }.uniq #then find all dupes
but I don't know how to push the results to an array.
Is this the right way of going about it? Are there any ideas how push the results to an array?

What you are attempting to do is a Set Intersection, which can be achieved in Ruby using the & operator.
arr_a = ["a","b","c","d"]
arr_b = ["123","456","b","d","c"]
new_array = arr_a & arr_b
Read more about this in "ary & other_ary".

You're looking for intersection of two sets. This is way simpler:
arr_a & arr_b

Related

Concatenate cell array in MATLAB

In Matlab you can concatenate arrays by saying:
a=[];
a=[a,1];
How do you do something similar with a cell array?
a={};
a={a,'asd'};
The code above keeps on nesting cells within cells. I just want to append elements to the cell array. How do I accomplish this?
If a and b are cell arrays, then you concatenate them in the same way you concatenate other arrays: using []:
>> a={1,'f'}
a =
1×2 cell array
{[1]} {'f'}
>> b={'q',5}
b =
1×2 cell array
{'q'} {[5]}
>> [a,b]
ans =
1×4 cell array
{[1]} {'f'} {'q'} {[5]}
You can also use the functional form, cat, in which you can select along which dimension you want to concatenate:
>> cat(3,a,b)
1×2×2 cell array
ans(:,:,1) =
{[1]} {'f'}
ans(:,:,2) =
{'q'} {[5]}
To append a single element, you can do a=[a,{1}], but this is not efficient (see this Q&A). Instead, do a{end+1}=1 or a(end+1)={1}.
Remember that a cell array is just an array, like any other. You use the same tools to manipulate them, including indexing, which you do with (). The () indexing returns the same type of array as the one you index into, so it returns a cell array, even if you index just a single element. Just about every value in MATLAB is an array, including 6, which is a 1x1 double array.
The {} syntax is used to create a cell array, and to extract its content: a{1} is not a cell array, it extracts the contents of the first element of the array.
{5, 8, 3} is the same as [{5}, {8}, {3}]. 5 is a double array, {5} is a cell array containing a double array.
a{5} = 0 is the same as a(5) = {0}.

check if any values in 2 arrays are equal

I'd like to check if any element (regardless of its position) of an array can be found in a second array.
For example
1st array: array([1,4,7,5,3])
2nd array: array([5,2,9,0,6])
Then I would want to find out, that 5 occurs in both arrays.
I guess that
array1 == array2
is not the right operation to check for this.
how can I test, if there are the same 2 elements in 2 arrays?
Thanks in advance!
You can use use np.isin(...) [numpy-doc] here to check if the value of an array is in another array, and then check with .any() [numpy-doc] if that is the case for at least one such item:
>>> np.isin(array1, array2).any()
True
Try getting intersection of 2 arrays:
list(set(arr_1) & set(arr_2))
or alternatively:
list(set(arr_1).intersection(set(arr_2)))
To count overlapping elements - just get length of the intersection:
len(list(set(arr_1) & set(arr_2)))
First thing that comes to mind is to use numpy.add.outer and check if there are zeros in the resulting array:
import numpy
a = numpy.random.randint(0, 10, 4)
b = numpy.random.randint(0, 10, 4)
print(a, b)
print(numpy.add.outer(a, -b))
has_dups = numpy.any(numpy.add.outer(a, -b) == 0)
print(has_dups)

How to merge 2 arrays of equal length into a single dictionary with key:value pairs in Godot?

I have been trying to randomize the values in an ordered array (ex:[0,1,2,3]) in Godot. There is supposed to be a shuffle() method for arrays, but it seems to be broken and always returns "null". I have found a workaround that uses a Fisher-Yates shuffle, but the resulting array is considered "unsorted" by the engine, and therefore when I try to use methods such as bsearch() to find a value by it's position, the results are unreliable at best.
My solution was to create a dictionary, comprised of an array containing the random values I have obtained, merged with a second array of equal length with (sorted) numbers (in numerical order) which I can then use as keys to access specific array positions when needed.
Question made simple...
In GDScript, how would you take 2 arrays..
ex: ARRAY1 = [0,1,2,3]
ARRAY2 = [a,b,c,d]
..and merge them to form a dictionary that looks like this:
MergedDictionary = {0:a, 1:b, 2:c, 3:d}
Any help would be greatly appreciated.
Godot does not support "zip" methodology for merging arrays such as Python does, so I am stuck merging them manually. However... there is little to no documentation about how to do this in GDScript, despite my many hours of searching.
Try this:
var a = [1, 2, 3]
var b = ["a", "b", "c"]
var c = {}
if a.size() == b.size():
var i = 0
for element in a:
c[element] = b[i]
i += 1
print("Dictionary c: ", c)
If you want to add elements to a dictionary, you can assign values to the keys like existing keys.

create a hash from an array in ruby

I have an array in a specific order, and wish to create a hash with the odd numbered entries of the array as indexes and the even as values. This code does it perfectly, but leaves out one pair of values from the array.
resolv_hash = Hash[*namerslv_array]
puts "values in hash"
resolv_hash.each do |key, array|
puts "#{key} " + array
end
can anyone help with this please?
I think you want:
resolv_hash = namerslv_array.each_slice(2).to_h
Illustration:
>> array = [1,2,3,4,5,6,7,8,9,0]
>> array.each_slice(2).to_h
=> {1=>2, 3=>4, 5=>6, 7=>8, 9=>0}

Assigning to a slice of a 3D array using the range operator

I have a 3 dimensional array. I want to set three elements of it like this:
$array[$x][$y][0 .. 2] = (0, 1, 2);
but perl tells me:
Useless use of a constant (1) in void context
In array context:
#array[$x][$y][0 .. 2] = (0, 1, 2);
but perl tells me:
syntax error near "]["
presumably meaning that it expects me to give it two indices and then assign to the third dimension as a separate array? However, on this page, under Example: Assignment Using Array Slices, it suggests that it is possible to assign to a slice using the range operator where it says:
#array1[1..3] = #array2[23..25];
How can I assign to a slice of the array like this, or do I have to assign each index individually?
You need to dereference the inner array:
#{ $arr[$x][$y] }[ 0 .. 2 ] = (0, 1, 2);
$array[$x][$y][0..2] isn't a slice; it's just an element lookup.
When you attempted to change it into a slice, you sliced the wrong array. You sliced #arr instead of #{ $arr[$x][$y] }.
The key here is to realize that there's no such thing as 3d arrays in Perl. What you have is an array of references to arrays of references to array, which is colloquially called array of array of array, and often abbreviated to AoAoA.
Array slices have the following syntax:
#NAME[LIST]
#BLOCK[LIST]
#$REF[LIST]
EXPR->#[LIST][1]
You could use any of the following:
The first syntax can't be used since the array to slice doesn't have a name.
#{ $array[$x][$y] }[0..2] = 0..2;
my $ref = $array[$x][$y]; #$ref[0..2] = 0..2;
$array[$x][$y]->#[0..2] = 0..2;[1]
See Dereferencing Syntax.
Requires Perl 5.24+. Available in Perl 5.20+ by adding both use feature qw( postderef ); and no warnings qw( experimental::postderef );.

Resources