1

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]]
2
  • An array of arrays of various lengths, or dimensions? Commented Aug 31, 2014 at 0:30
  • An array of arrays of various lengths, something for placing items into a bin; like for making a histogram. Commented Aug 31, 2014 at 0:57

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

why when i do var hist = Array.tabulate(9)(i => Array(0)) and try to print hist i get something like [[I@5b895cb9
@vyruz - Array doesn't have a toString method that prints its contents. The REPL will call its own printing routine instead of just calling toString; you can println(hist.map(_.mkString(", ")).mkString("\n")) or somesuch to see the elements.
0

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.

Comments

0

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))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.