ushapreethi
ushapreethi

Reputation: 1

concatenation in array names

I want to store details of 100 nodes in 100 arrays. For example,

neighbors of node 1 should be stored in array1

In this, for each array the names should be changed like array1, array2, array3, ..., array100

I need the concatenation for array and ( 1 , 2 , 3 , ... , 100 ) using for loop.

How can I do this?

Upvotes: 0

Views: 188

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137577

It's usually recommended to use 2D arrays (really just composite element names) like this:

foreach x $listOf1to100 {
    foreach y $listOf1to100 {
        set ary($x,$y) "blah blah"
    }
}

However, if you really want to be creating those names then you can do it in several ways. One is like this:

foreach x $listOf1to100 {
    set ary${x}(...) "blah blah"
}

But that's ugly. It's even uglier when you come to read the arrays! A better choice is this:

foreach x $listOf1to100 {
    upvar 0 array$x a
    set a(...) "blah blah"
}

Mind you, if you're really doing 2D compact numeric indices then you're perhaps better to use nested lists to build a matrix:

# Create
set matrix [lrepeat 100 [lrepeat 100 "blah blah"]]
# Lookup
set value [lindex $matrix $x $y]
# Update
lset matrix $x $y $value

Upvotes: 1

jetru
jetru

Reputation: 1993

Not exactly sure what you want, but a two dimensional array sounds like the way to go

set a(1,1) neighbourof1_1;
set a(1,2) neighbourof1_2;
set a(2,1) neighbourof2_1;
...
...
set a(100,1) neighbourof100_1;

Upvotes: 5

Related Questions