Scala Array declaration - unintuitive result for apply(0) - arrays

How is this possible? I have not created a new array...yet m(0) has a value of 10.
AND, m(1) is an ArrayIndexOutOfBounds exception...

val m = Array[Int](10) means an array of type Int with one element 10 bound the variable m. m(n) means the n-th element of m.
Thats why m(1) gives you a ArrayIndexOutOfBounds, m has only one element.
Are you mixing it up with the odd Java syntax for arrays? int[] m = new int[10]; Which is a 10 uninitialized elements array.

Array[Int](10) creates an array with one element, 10. Check it here
Still, in Scala you shouldn't access array elements directly without be aware of exceptions. I would prefer something like:
scala> val array = Array(10)
array: Array[Int] = Array(10)
scala> array.drop(5).headOption
res0: Option[Int] = None
to access the 5th element for instance

Related

Filling the array with array does not work as I expected

I want to make a multiple array whose entry is multiple array, and want to push some array one by one into the entry.
For example, I made 2 x 3 Matrix named arr and tried to fill [1,1] and [1,2] entries with 4 x 4 Matrix spawned by randn(4,4).
arr = fill(Matrix{Float64}[], 2, 3)
push!(arr[1,1],randn(4,4))
push!(arr[1,2],randn(4,4))
println(arr[1,1])
println(arr[1,2])
println(arr[1,3])
However, the result is all the entries of arr (other than [1,1] and [1,2]) were filled with the same randn(4,4), instead of just [1,1] and [1,2] filled with randn(4,4):
[[-0.15122805007483328 0.6132236453930502 -0.9090110366765862 1.2589924202099898; -1.120611384326006 -0.9083935218058066 0.7252290006516056 1.0970416725786256; -0.19173238706933265 1.3610525411901113 -0.05258697093572793 0.7776085390912448; 0.18491459001855373 -2.0537142669734934 0.3482557186126859 0.0047622478008474845], [0.23422967703060255 -0.51986351753462 0.45947166573674303 0.31316899298864387; 0.3704450103622709 -0.8186574197233013 -0.9990329964554037 -0.8345957519924763; 0.56641529964098 -0.8393435538481216 -0.6379336546939682 1.1843452368116358; 0.9435767553275002 0.0033471181565433127 -1.191611491619908 1.3970554854927264]]
[[-0.15122805007483328 0.6132236453930502 -0.9090110366765862 1.2589924202099898; -1.120611384326006 -0.9083935218058066 0.7252290006516056 1.0970416725786256; -0.19173238706933265 1.3610525411901113 -0.05258697093572793 0.7776085390912448; 0.18491459001855373 -2.0537142669734934 0.3482557186126859 0.0047622478008474845], [0.23422967703060255 -0.51986351753462 0.45947166573674303 0.31316899298864387; 0.3704450103622709 -0.8186574197233013 -0.9990329964554037 -0.8345957519924763; 0.56641529964098 -0.8393435538481216 -0.6379336546939682 1.1843452368116358; 0.9435767553275002 0.0033471181565433127 -1.191611491619908 1.3970554854927264]]
[[-0.15122805007483328 0.6132236453930502 -0.9090110366765862 1.2589924202099898; -1.120611384326006 -0.9083935218058066 0.7252290006516056 1.0970416725786256; -0.19173238706933265 1.3610525411901113 -0.05258697093572793 0.7776085390912448; 0.18491459001855373 -2.0537142669734934 0.3482557186126859 0.0047622478008474845], [0.23422967703060255 -0.51986351753462 0.45947166573674303 0.31316899298864387; 0.3704450103622709 -0.8186574197233013 -0.9990329964554037 -0.8345957519924763; 0.56641529964098 -0.8393435538481216 -0.6379336546939682 1.1843452368116358; 0.9435767553275002 0.0033471181565433127 -1.191611491619908 1.3970554854927264]]
What is wrong?
Any information would be appreciated.
When you do arr = fill(Matrix{Float64}[], 2, 3) all 6 elements point into exactly the same location in memory because fill does not make deep copy - it just copies the references. Basically, using fill when the first argument is mutable usually turns out not to be a good idea.
Hence what you actually want is:
arr = [Matrix{Float64}[] for i in 1:2, j in 1:3]
Now each of 6 slots will have its own address in the memory.
This way of creating the array implies that each element will be Float64, i.e. a scalar. You need to fix the type signature. So for instance you could do
D = Matrix{Array{Float64, 2}}(undef, 2, 3)
if you want it to have 2-dimensional arrays as elements (the Float64,2 does that)
and then allocate
D[1,1] = rand(4,4)
D[1,2] = rand(4,4)
to give you (or rather, me!):
julia> D[1,1]
4×4 Matrix{Float64}:
0.210019 0.528594 0.0566622 0.0547953
0.729212 0.40829 0.816365 0.804139
0.39524 0.940286 0.976152 0.128008
0.886597 0.379621 0.153302 0.798803
julia> D[1,2]
4×4 Matrix{Float64}:
0.640809 0.821668 0.627057 0.382058
0.532567 0.262311 0.916391 0.200024
0.0599815 0.17594 0.698521 0.517822
0.965279 0.804067 0.39408 0.105774

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.

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)

Store value in an array

I am fairly new to Go. I have coded in JavaScript where I could do this:
var x = [];
x[0] = 1;
This would work fine. But in Go, I am trying to implement the same thing with Go syntax. But that doesn't help. I need to have a array with unspecified index number.
I did this:
var x []string
x[0] = "name"
How do I accomplish that?
When you type:
var x []string
You create a slice, which is similar to an array in Javascript. But unlike Javascript, a slice has a set length and capacity. In this case, you get a nil slice which has the length and capacity of 0.
A few examples of how you can do it:
x := []string{"name"} // Creates a slice with length 1
y := make([]string, 10) // Creates a slice with length 10
y[0] = "name" // Set the first index to "name". The remaining 9 will be ""
var z []string // Create an empty nil slice
z = append(z, "name") // Appends "name" to the slice, creating a new slice if required
More indepth reading about slices:
Go slices usage and internals
In JavaScript arrays are dynamic in the sense that if you set the element of an array using an index which is greater than or equal to its length (current number of elements), the array will be automatically extended to have the required size to set the element (so the index you use will become the array's new length).
Arrays and slices in Go are not that dynamic. When setting elements of an array or slice, you use an index expression to designate the element you want to set. In Go you can only use index values that are in range, which means the index value must be 0 <= index < length.
In your code:
var x []string
x[0] = "name"
The first line declares a variable named x of type []string. This is a slice, and its value will be nil (the zero value of all slice types, because you did not provide an initialization value). It will have a length of 0, so the index value 0 is out of range as it is not less that the length.
If you know the length in advance, create your array or slice with that, e.g.:
var arr [3]string // An array with length of 3
var sli = make([]string, 3) // A slice with length of 3
After the above declarations, you can refer to (read or write) values at indicies 0, 1, and 2.
You may also use a composite literal to create and initialize the array or slice in one step, e.g.
var arr = [3]string{"one", "two", "three"} // Array
var sli = []string{"one", "two", "three"} // Slice
You can also use the builtin append() function to add a new element to the end of a slice. The append() function allocates a new, bigger array/slice under the hood if needed. You also need to assign the return value of append():
var x []string
x = append(x, "name")
If you want dynamic "arrays" similar to arrays of JavaScript, the map is a similar construct:
var x = map[int]string{}
x[0] = "name"
(But a map also needs initialization, in the above example I used a composite literal, but we could have also written var x = make(map[int]string).)
You may assign values to keys without having to declare the intent in prior. But know that maps are not slices or arrays, maps typically not hold values for contiguous ranges of index keys (but may do so), and maps do not maintain key or insertion order. See Why can't Go iterate maps in insertion order? for details.
Must read blog post about arrays and slices: Go Slices: usage and internals
Recommended questions / answers for a better understanding:
Why have arrays in Go?
How do I initialize an array without using a for loop in Go?
How do I find the size of the array in go
Keyed items in golang array initialization
Are golang slices pass by value?
Can you please use var x [length]string; (where length is size of the array you want) instead of var x []string; ?
In Go defining a variable like var x=[]int creates a slice of type integer. Slices are dynamic and when you want to add an integer to the slice, you have to append it like x = append(x, 1) (or x = append(x, 2, 3, 4) for multiple).
As srxf mentioned, have you done the Go tour? There is a page about slices.
I found out that the way to do it is through a dynamic array. Like this
type mytype struct {
a string
}
func main() {
a := []mytype{mytype{"name1"}}
a = append(a, mytype{"name 2"})
fmt.Println(a);
}
golang playground link: https://play.golang.org/p/owPHdQ6Y6e

Why is it not possible to fill an array using an each do loop in Ruby?

If I use an each do loop to fill an array, it will leave the array as it is (in this case it will be a nil array of size 4)
array = Array.new(4)
array.each do |i|
i = 5
end
I understand that I can initialize an array with my desired value using array = Array.new(4) {desired value} but there are situations in which I'm choosing between different values and I am trying to understand how the each do loop work exactly.
The current way I'm doing it is the following which fills in the array with my desired value
array = Array.new(4)
array.each_with_index do |val, i|
array[i] = 5
end
Solution
You need :
array = Array.new(4) do |i|
5
# or some logic depending on i (the index between 0 and 3)
end
Your code
array = Array.new(4)
array is now an Array with 4 elements (nil each time).
array.each iterates over those 4 elements (still nil), and sets i as block-local variable equal to nil.
Inside this block, you override i with 5, but you don't do anything with it. During the next iteration, i is set back to nil, and to 5, and so on...
You don't change the original array, you only change local variables that have been set equal to the array elements.
The difference is that
i = 5
is an assignment. It assigns the value 5 to the variable i.
In Ruby, assignments only affect the local scope, they don't change the variable in the caller's scope:
def change(i)
i = 5 # <- doesn't work as you might expect
end
x = nil
change(x)
x #=> nil
It is therefore impossible to replace an array element with another object by assigning to a variable.
On the other hand,
array[i] = 5
is not an assignment, but a disguised method invocation. It's equivalent to:
array.[]=(i, 5)
or
array.public_send(:[]=, i, 5)
It asks the array to set the element at index i to 5.

Resources