Initialize a seq of seqs
Asked Answered
C

2

6

I am brand new to Nim and am bumping into some issues. The following code results in SIGSEGV: Illegal storage access. (Attempt to read from nil?). I can't seem to figure out how to populate a sequence of sequences with values.

const
  a = @[ 0,  1,  2,  3,  4,  5]
  b = @[10, 11, 12, 13, 14, 15]

var
  matrix: seq[seq[int]]

for i, aa in a:
  for j, bb in b:
    matrix[i][j] = aa+bb

Other approaches I've attempted seem to be closer...

var
  matrix = newSeq[seq[int]]()

for i, aa in a:
  var row = newSeq[int]()
  for j, bb in b:
    row[i] = aa+bb
  matrix[i] = row

...but now I'm hitting out of bounds [IndexError]...

var
  matrix = newSeq[seq[int]](5)

for i, aa in a:
  var row = newSeq[int](5)
  for j, bb in b:
    row[i] = aa+bb
  matrix[i] = row

...what am I doing wrong?

Cohbath answered 18/5, 2015 at 9:0 Comment(0)
H
9

If you don't want to resize the seq, an easier solution is to preallocate it:

import sequtils

const
  a = @[ 0,  1,  2,  3,  4,  5]
  b = @[10, 11, 12, 13, 14, 15]

var matrix = newSeqWith(a.len, newSeq[int](b.len))

for i, aa in a:
  for j, bb in b:
    matrix[i][j] = aa + bb

echo matrix
Hypognathous answered 18/5, 2015 at 9:27 Comment(1)
Awesome. Thanks for taking the time to answer! I knew there would be something out there!Cohbath
C
6

Success!

It turns out, Nim really doesn't like you using square brackets in places where data doesn't exist yet. That is matrix[i] = item will blow up. However, matrix.add(item) will work well.

Here is how I ended up creating a 2D array in Nim:

var
  matrix: seq[seq[int]]
  row: seq[int]

matrix = newSeq[seq[int]]()

for i, aa in a:
  row = newSeq[int]()
  matrix.add(row)
  for j, bb in b:
    matrix[i].add(aa+bb)

echo matrix
Cohbath answered 18/5, 2015 at 9:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.