Scala allocate sequential index array - arrays

In scala I would like to dynamically allocate an array of sequential index values.
In R it is simply maxindex = 10 then array = 1:maxindex which returns 1,2,3,4,5,6,7,8,9,10
Is it possible to do this in scala?

You should try Range method:
Range(val start : Int, val end : Int, val step : Int)
You could use it like this:
var yourArray = range(1, 10, 1)
That will return an array like you want: 1,2,3,4,5,6,7,8,9,10
Or even more simple:
var yourArraySimpler = 1 until 11
Take a look at the documentation. From the link:
The Range class represents integer values in range [start;end) with
non-zero step value step. Sort of acts like a sequence also (supports
length and contains).

It is as simple as:
val arr = 1 to 10
which uses an implicit conversion to generate a Range as described in #cacho's answer. Range is a subclass of Seq, but you can call .toArray on it if you specifically need an array.

Related

How to initial a 2 Dimensions matrix with independent number of rows and columns in Scala?

I've seen something like:
def matInit(n:Int):Array[Array[Int]]={
val maxval=5
val rnd=new Random(100)
Array.tabulate(n){_=>Array.tabulate(n){_=>rnd.nextInt(maxval+1)+1}}
}
but in this template above, the way of initialization is complicated, and the number of rows and columns is equal. Is there an improved way based on it? Thanks.
Array.fill allows creating of 2D arrays and makes the logic a bit simpler.
def matInit(n: Int, m: Int): Array[Array[Int]] = {
val maxval = 5
val rnd = new Random(100)
Array.fill(n, m)(rnd.nextInt(maxval + 1) + 1)
}
This works because fill takes a by name argument which means that the expression is evaluated for each element in the new Array rather than being calculated once and passed as a value.

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

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

Is there any way to create dynamic array in scala? Means inserting values at run time?

var arr=Array.ofDim[Int](4,4)
arr(0)(0)(0)(0)=12
this is one way to insert elements in array.
but if i need to initialize size of array dynamically or at run time. How can we do it in scala?
Here
val n = StdIn.readInt
val m = StdIn.readInt
val arr = Array.ofDim[Int](n, m)
arr(5)(15) = 1
println(arr.deep.mkString("\n"))
I created 2-dimensional array with sizes known only in runtime (I entered 10 and 20).
Or maybe you need scala.collection.mutable.ArrayBuffer if you're going to change sizes.
ArrayBuffer[Int] is 1-dimensional, ArrayBuffer[ArrayBuffer[Int]] is 2-dimensional etc.
val arr: ArrayBuffer[ArrayBuffer[Int]] =
ArrayBuffer.fill(10)(ArrayBuffer.fill(20)(0))
arr(5)(15) = 1
println(arr.mkString("\n"))
println
arr(5) += 1
arr += ArrayBuffer.fill[Int](25)(0)
println(arr.mkString("\n"))

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

Resources