Array operations that changes the order of element in scala - arrays

In scala documentation it states that Lists are immutable and "you can rely on the fact that accessing the same collection value repeatedly at different points in time will always yield a collection with the same elements" On the other hand in arrays (mutable) some operations can change the element. Can you give me some array examples for those operations that changes element by comparing with example on lists?

val arr = Array(3,5,7)
arr(1) = 0 // arr is now Array(3,0,7)
val lst = List(3,5,7)
lst(1) = 0 // error: value update is not a member of List[Int]

Related

How to use contains method on a 2D array in scala

I have a 2d array and I want to check whether an array exists inside the 2d array.
I have tried:
var arr = Array(Array(2,1), Array(4,3))
var contain = arr.contains(Array(4, 3))
println(contain)
This should print true but it doesn't work.
Method contains doesn't work because it uses equals to determine equality and for arrays equals is using reference equality, so it will return true only for two references pointing the same object.
You could use find + sameElements:
var arr = Array(Array(2,1), Array(4,3))
var contain = arr.find(_.sameElements(Array(4, 3))).isDefined
println(contain)
Consider using ArrayBuffer instead of Array, if you need mutable collection, like so
val arr = ArrayBuffer(ArrayBuffer(2,1), ArrayBuffer(4,3))
val contain = arr.contains(ArrayBuffer(4, 3))
println(contain)
which outputs
true
Also consider question What is the difference between ArrayBuffer and Array
A more elegant solution would be the following
val array = Array(Array(2,1), Array(4,3))
val result = array.exists(_.sameElements(Array(4, 3)))
println(result)
Output
true

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.

Julia Lang: Error? Initializing Nullable Arrays

I am trying to initialize an array of Nullable Integers with a given size. My intend is to add elements to the array and to be able to count the number of Nullable elements in an array.
However I noticed the following behavior. Running the following code:
function main()
arr = Array{Nullable{Int}}(10)
res = 0
for i in 1:10
if isnull(arr[i])
res += 1
end
end
res
end
is expected to return 10, however the program returns different values almost every time that I run the code. Initializing just the array:
function main()
arr = Array{Nullable{Int}}(10)
end
this is the result:
Nullable{Int64}(7142821636481377634)
Nullable{Int64}(8803814271447229814)
Nullable{Int64}(7935455170894001012)
Nullable{Int64}(8247625210579135584)
Nullable{Int64}(7815275285807655200)
Nullable{Int64}()
Nullable{Int64}()
Nullable{Int64}()
Nullable{Int64}()
Nullable{Int64}()
Here one can see that not all elements are in fact not Null. Which would explain why the function isnull() does not recognize them as Null objects.
This is the desired effect:
function main()
arr = Array{Nullable{Int}}(10)
for i in 1:10
arr[i] = Nullable{Int}()
end
println(arr)
end
which indeed returns an array of Nullable elements. However, it seems a bit tedious to run this code for initialization.
Any ideas how this can be avoided?
In Julia 0.6 you can use arr = fill(Nullable{Int64}(),10).
Note however that Nullables are depreciated in Julia 0.7 (https://github.com/JuliaLang/julia/blob/master/NEWS.md), consider to use the Nothing or Missing types instead:
julia> vector_with_nothing_or_int = Vector{Union{Int64, Nothing}}(nothing,10)
10-element Array{Union{Nothing, Int64},1}:
nothing
nothing
[...]
julia> vector_with_missing_or_int = Vector{Union{Int64, Missing}}(missing,10)
10-element Array{Union{Missing, Int64},1}:
missing
missing
[...]
Check if a element is nothing or missing can be done with:
julia> vector_with_nothing_or_int[1] == nothing
true
julia> ismissing(vector_with_missing_or_int[1])
true
The Missing type also works in Julia 0.6 if you load the module Missings. This is the corresponding code for Julia 0.6:
using Missings
vector_with_missing_or_int = Vector{Union{Int64, Missing}}(10)
vector_with_missing_or_int .= missing
vector_with_nothing_or_int = Vector{Union{Int64, Nothing}}(10)
vector_with_nothing_or_int .= nothing
The operator .= replaces every element of the array with the element of the right. All these examples also work for multi-dimensional arrays if you replace Vector by Array when you specify also the number of dimensions.

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

What trouble could bring assining reversed() to a swift array?

I'm wondering about the reversed() method on a swift Array:
var items = ["a", "b", "c"]
items = items.reversed()
the signature of the reversed method from the Apple doc says that it returns a
ReversedRandomAccessCollection<Array<Element>>
could that be assigned back to items without doing what the apple doc say which is
For example, to get the reversed version of an array, initialize a new Array instance from the result of this reversed() method.
or would it give problem in the future? (since the compiler doesn't complain)
There are 3 overloads of reversed() for an Array in Swift 3:
Treating the Array as a RandomAccessCollection,func reversed() -> ReversedRandomAccessCollection<Self> (O(1))
Treating the Array as a BidirectionalCollection,func reversed() -> ReversedCollection<Self> (O(1))
Treating the Array as a Sequence,func reversed() -> [Self.Iterator.Element] (O(n))
By default, reversed() pick the RandomAccessCollection's overload and return a ReversedRandomAccessCollection. However, when you write
items = items.reversed()
you are forcing the RHS to return a type convertible to the LHS ([String]). Thus, only the 3rd overload that returns an array will be chosen.
That overload will copy the whole sequence (thus O(n)), so there is no problem overwriting the original array.
Instead of items = items.reversed(), which creates a copy of the array, reverse that and copy it back, you could reach the same effect using the mutating function items.reverse(), which does the reversion in-place without copying the array twice.

Resources