Reputation: 83
I've read about using ofdim to make multidimensional arrays in scala but what if I don't want all the arrays to be of the same size?. I'm wanting to be able to make an array of arrays of various sizes such as the following but haven't been able to find anything.
dist = [[1,2,3],
[10, 11, 13, 15, 16, 17, 19],
[25]]
Upvotes: 1
Views: 127
Reputation: 20405
If considering in binning values from a collection for building a histogram consider a repetitive use of partition
(see my full, related, answer in https://stackoverflow.com/a/24540089/3189923 ), like this,
def histo(bounds: Array[Int], data: Array[Int]): Array[Array[Int]] = {
bounds match {
case Array(h) => Array(data)
case Array(h, t @ _*) => val (l,r) = data.partition( _ < h)
l +: histo(t.toArray,r)
}
}
Thus for
val bounds = Array(10, 20, 30)
val dist = Array(1, 2, 3, 10, 11, 13, 15, 16, 17, 19, 25)
we have that
histo(bounds, dist)
res: Array[Array[Int]] = Array(Array(1, 2, 3),
Array(10, 11, 13, 15, 16, 17, 19),
Array(25))
Upvotes: 0
Reputation: 1599
Better to go for Array of List like this Array[List[Int]]. Inner list can be of variable length satisfying your need. Or List of List, if you are not sure of the outer array length upfront.
Upvotes: 0
Reputation: 167871
You can always use tabulate
and then build the size you need on the basis of index, or map from a list of sizes to the arrays themselves:
Array.tabulate(4)(i => Array.range(0,i))
// Array[Array[Int]] = Array(Array(), Array(0), Array(0, 1), Array(0, 1, 2))
Array(3,7,1).map(i => Array.range(0,i))
// Array[Array[Int]] = Array(Array(0, 1, 2), Array(0, 1, 2, 3, 4, 5, 6), Array(0))
The JVM doesn't have true multidimensional arrays, just arrays of arrays--so Scala doesn't either. Feel free to build them up however you can.
Upvotes: 1