A puzzle - nested for-loops

Quote:

> I have a frustrating little mathematical/logical challenge

> which I have solved but in a very (very) clumsy way

> Any ideas for a 'clever' solution

> I have an n-dimensional matrix for which I use an associative array.

> For instance, here is a 6 dimensional one and I point to any cell with

> statements like matrix[1,4,5,7,2,3]=1

> Each dimension has dim[] elements, eg dim[1]=4, means that the first

> subscript may take values of 1, 3 or 4

> My challenge is how to set each of the cells of the matrix to be '1'

> The conceptual way is to have 'n' nested for-loops, but since 'n' is

> variable this cant be hard-coded

I'd say a 'generic' solution (ok, maybe not a very clever one)

would be something like the recursive function below.

Of course, once existing all the needed elements in each dimension

the obvious approach would be for(n in arr)...

BEGIN{

numofdims=0

dims[++numofdims]=2

dims[++numofdims]=3

dims[++numofdims]=4

setfromdim(1,arr,numofdims,dims,"",1) ## THIS ONE

printfromdim(arr,numofdims,dims,"",1) ## THIS a test

setall(2,arr)

printfromdim(arr,numofdims,dims,"",1)

exit

Quote:

}

function setfromdim(value, arr, numofdims, dims, keysofar, thisdim \

, n){

if(thisdim > 1) {

keysofar = keysofar ","

}

if(thisdim < numofdims) {

for(n=1; n<=dims[thisdim]; n++) {

setfromdim(value, arr, numofdims, dims, keysofar n, thisdim+1)

}

} else {

for(n=1; n <= dims[thisdim]; n++) {

arr[keysofar n] = value

}

}

Quote:

}

function printfromdim(arr, numofdims, dims, keysofar, thisdim \

, n,key){

if(thisdim > 1) {

keysofar = keysofar ","

}

if(thisdim < numofdims) {

for(n=1; n<=dims[thisdim]; n++) {

printfromdim(arr, numofdims, dims, keysofar n, thisdim+1)

}

} else {

for(n=1; n <= dims[thisdim]; n++) {

key=keysofar n

print "arr["key"]=" arr[key]

}

}

Quote:

}

function setall(value, arr \

, n) {

for(n in arr) {

arr[n]=value

}

Quote:

}

--

All true believers shall break their eggs at the convenient end.