check if any values in 2 arrays are equal - arrays

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)

Related

Julia Quick way to initialise an empty array that's the same size as another?

I have an array
array1 = Array{Int,2}(undef, 2, 3)
Is there a way to quickly make a new array that's the same size as the first one? E.g. something like
array2 = Array{Int,2}(undef, size(array1))
current I have to do this which is pretty cumbersome, and even worse for higher dimension arrays
array2 = Array{Int,2}(undef, size(array1)[1], size(array1)[2])
What you're looking for is similar(array1).
You can even change up the array type by passing in a type, e.g.
similar(array1, Float64)
similar(array1, Int64)
Using similar is a great solution. But the reason your original attempt doesn't work is the number 2 in the type parameter signature: Array{Int, 2}. The number 2 specifies that the array must have 2 dimensions. If you remove it you can have exactly as many dimensions as you like:
julia> a = rand(2,4,3,2);
julia> b = Array{Int}(undef, size(a));
julia> size(b)
(2, 4, 3, 2)
This works for other array constructors too:
zeros(size(a))
ones(size(a))
fill(5, size(a))
# etc.

Determine Size of Multidimensional Array in Swift

I am new to Swift and am struggling to work out how to determine the size of a multidimensional array.
I can use the count function for single arrays, however when i create a matrix/multidimensional array, the output for the count call just gives a single value.
var a = [[1,2,3],[3,4,5]]
var c: Int
c = a.count
print(c)
2
The above matrix 'a' clearly has 2 rows and 3 columns, is there any way to output this correct size.
In Matlab this is a simple task with the following line of code,
a = [1,2,3;3,4,5]
size(a)
ans =
2 3
Is there a simple equivalent in Swift
I have looked high and low for a solution and cant seem to find exactly what i am after.
Thanks
- HB
Because 2D arrays in swift can have subarrays with different lengths. There is no "matrix" type.
let arr = [
[1,2,3,4,5],
[1,2,3],
[2,3,4,5],
]
So the concept of "rows" and "columns" does not exist. There's only count.
If you want to count all the elements in the subarrays, (in the above case, 12), you can flat map it and then count:
arr.flatMap { $0 }.count
If you are sure that your array is a matrix, you can do this:
let rows = arr.count
let columns = arr[0].count // 0 is an arbitrary value
You must ask the size of a specific row of your array to get column sizes :
print("\(a.count) \(a[0].count)")
If you are trying to find the length of 2D array which in this case the number of rows (or # of subarrays Ex.[1,2,3]) you may use this trick: # of total elements that can be found using:
a.flatMap { $0 }.count //a is the array name
over # of elements in one row using:
a[0].count //so elemints has to be equal in each subarray
so your code to get the length of 2D array with equal number of element in each subarray and store it in constant arrayLength is:
let arrayLength = (((a.flatMap { $0 }.count ) / (a[0].count))) //a is the array name

How to find if any array elements are larger than a certain value using `arrayfun`

Let's say we have an array numbers. If any elements in the array are greater than 3, I want to make array equal nan.
array = [1 2 3 4 5];
if arrayfun(#greater than 3,array)
array = nan;
end
You don't really need arrayfun for this simple job. if any(array > 3); array = nan; end is all you need.

Efficient method of merging two neighboring indicies in Scala

What would be a most efficient method of merging two neighboring indicies in Scala? What I have in mind a nasty while loops with copying.
For example, there's a buffer array A, with length N. The new array need be generated such that for A(i) = A(i) + A(i+1), where i < N
For example, merging and summing the second and third element, and generate a new array.
ArrayBuffer(1,2,4,3) => ArrayBuffer(1,6,3)
UPDATE:
I think I come up with some solution, but doesn't like it much. Any suggestion to improve would be highly appreciated.
scala> val i = 1
i: Int = 1
scala> ArrayBuffer(1,2,4,3).zipWithIndex.foldLeft(ArrayBuffer[Int]())( (k,v)=> if(v._2==i+1){ k(k.length-1) =(k.last+v._1);k; }else k+= v._1 )
The simplest way to get neighbors is to use sliding method.
a.sliding(2, 1).map(_.sum)
where the first argument is a size and the second one is step.
If you want to keep the first and the last element intact something like this should work:
a.head +: a.drop(1).dropRight(1).sliding(2, 1).map(_.sum).toArray :+ a.last
If you want to avoid copying and array on append/prepend you can rewrite it as follows:
val aa = a.sliding(2, 1).map(_.sum).toArray
aa(0) = a.head
aa(aa.size - 1) = a
or use ListBuffer which provides constant time prepend and append.
It should be also possible to use Iterators:
val middle: Iterator[Int] = a.drop(1).dropRight(1).sliding(2, 1).map(_.sum)
(Iterator(a.head) ++ middle ++ Iterator(a.last)).toArray // or toBuffer

Getting the first and last element of an array in CoffeeScript

If say I have an array and I would to iterate through the array, but do something different to the first and last element. How should I do that?
Taking the below code as example, how do I alert element a and e?
array = [a,b,c,d,e]
for element in array
console.log(element)
Thanks.
You can retrieve the first and last elements by using array destructuring with a splat:
[first, ..., last] = array
This splat usage is supported in CoffeeScript >= 1.7.0.
The vanilla way of accessing the first and last element of an array is the same as in JS really: using the index 0 and length - 1:
console.log array[0], array[array.length - 1]
CoffeeScript lets you write some nice array destructuring expressions:
[first, mid..., last] = array
console.log first, last
But i don't think it's worth it if you're not going to use the middle elements.
Underscore.js has some helper first and last methods that can make this more English-like (i don't want to use the phrase "self-explanatory" as i think any programmer would understand array indexing). They are easy to add to the Array objects if you don't want to use Underscore and you don't mind polluting the global namespace (this is what other libraries, like Sugar.js, do):
Array::first ?= (n) ->
if n? then #[0...(Math.max 0, n)] else #[0]
Array::last ?= (n) ->
if n? then #[(Math.max #length - n, 0)...] else #[#length - 1]
console.log array.first(), array.last()
Update
This functions also allow you to get the n first or last elements in an array. If you don't need that functionality then the implementation would be much simpler (just the else branch basically).
Update 2
CoffeeScript >= 1.7 lets you write:
[first, ..., last] = array
without generating an unnecessary array with the middle elements :D
The shortest way is here
array[-1..]
See this thread
https://github.com/jashkenas/coffee-script/issues/156
You can use just:
[..., last] = array
You can use slice to get last element. In javascript, slice can pass negative number like -1 as arguments.
For example:
array = [1, 2, 3 ]
console.log "first: #{array[0]}"
console.log "last: #{array[-1..][0]}"
be compiled into
var array;
array = [1, 2, 3];
console.log("first: " + array[0]);
console.log("last: " + array.slice(-1)[0]);
You can get the element and the index of the current element when iterating through the array using Coffeescript's for...in. See the following code, replace the special_process_for_element and normal_process_for_element with your code.
array = [a, b, c, d]
FIRST_INDEX = 0
LAST_INDEX = array.length - 1
for element, index in array
switch index
when FIRST_INDEX, LAST_INDEX
special_process_for_element
else
normal_process_for_element
sample
Here's a working code

Resources