开发者

How do you (get around) dynamically naming variables?

I'm not sure if I'm using the right nomenclature, so I'll try to make my question as specific as possible. That said, I imagine this problem comes up all the time, and there are probably several different ways to deal with it.

Let's say I have an array (vector) called main of 1000 random years between 1980 and 2000 and that I want to make 20 separate arrays (vectors) out of it. These arrays would be named array1980, array1981, etc., would also have length 1000 but would contain 1s where the index in the name was equal to the corresponding element in main and 0s elsewhere. In other words:

for(int i=0; i<1000; i++){
    if(main[i]==1980){
       array1980[i]=1;
    } else {
       array1980[i]=0;
    }

Of course, I don't want to have to write twenty of these, so it'd be good if I could create new variable names inside a loop. The problem is that you can't generally assign variable names to expressions with operators, e.g.,

String("array"+ j)=... # returns an error

I'm currently using Matlab the most, but I can also do a little in Java, c++ and python, and I'm trying to get an idea for how people go about solving this problem in general. Ideally, I'd like to be able to manipulate the individual variables (or sub-arrays) in some way that the year remains in the variable name (or array index)开发者_C百科 to reduce the chance for error and to make things easier to deal with in general.

I'd appreciate any help.


boolean main[][] = new boolean[1000][20];
for (int i=0; i < 1000; i++) {
    array[i][main[i]-1980] = true;
}

In many cases a map will be a good solution, but here you could use a 2-dim array of booleans, since the size is known before (0-20) and continuous, and numerable.

Some languages will initialize an array of booleans to false for every element, so you would just need to set the values to true, to which main[i] points.

since main[i] returns numbers from 1980 to 2000, 1980-main[i] will return 1980-1980=0 to 2000-1980=20. To find your values, you have to add 1980 to the second index, of course.


The general solution to this is to not create variables with dynamic names, but to instead create a map. Exactly how that's done will vary by language.

For Java, it's worth looking at the map section of the Sun collections tutorial for a start.


Don Roby's answer is correct, but i would like to complete it.

You can use maps for this purpose, and it would look something like this:

Map<Integer,ArrayList<Integer>> yearMap = new HashMap<Integer,ArrayList<Integer>>();
yearMap.put(1980,new ArrayList<Integer>());
for (int i = 0; i < 1000; i++){
    yearMap.get(1980).add(0);
}
yearMap.get(1980).set(999,1);
System.out.println(yearMap.get(1980).get(999));

But there is probably a better way to solve the problem that you have. You should not ask how to use X to solve Y, but how to solve Y.

So, what is it, that you are trying to solve?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜