Arrays question


#1

Hi,

I’m a bit confused in how to create an array with let’s say 1024 elements , but all elements are known in advance.
I’m using a list now to do this , but according to David it can be up to 20 times faster to use an array.
So I want something like array = { 1,2,3,4,5).
array being a 1 dimensional array , and 1 to 5 the corresponding elements.

In the sodoku example I see a defvar is used , so what is the make-array then used for ?

Kind regards,
Ronny


#2

Hi Ronny,

Good question. With your example you could either create the array empty, and then populate it like this:

> (defvar ar (make-array 5))
ar

> ar
#(nil nil nil nil nil)

> (dotimes (x 5 ar) (setf (aref ar x) (1+ x)))
#(1 2 3 4 5)

or you could specify the contents of the array explicitly, in which case it will be made for you:

> (defvar ar #(1 2 3 4 5))
ar

> ar
#(1 2 3 4 5)

I suppose it depends on whether you know the contents of the array in advance, or you want to calculate them later.

Regards,
David


#3

Hi David,

So you don’t have to explicitly use ‘make-array’ for creating arrays apparently.
Thanks , this makes it more clear to me !

Regards,
Ronny