How to make cycle over cycles in Java?

Posted by Roman on Stack Overflow See other posts from Stack Overflow or by Roman
Published on 2010-03-24T13:06:47Z Indexed on 2010/03/24 13:23 UTC
Read the original article Hit count: 214

Filed under:
|
|

I would like to make a cycle over the following elements:

[1,2,11,12,21,22,111,112,121,122,....,222222]

or for example

[1,2,3,11,12,13,21,22,23,31,32,33,111,112,113,... 333333333]

How can I make it in Java? In my particular case I use 4 digits (1,2,3,4) and the length of the last number can be from 1 to 10.

I managed to do it in Python and PHP. In the first case I used list over lists. I started from [[1],[2],] then for every element of the list I added 1 and 2, so I got [[1,1],[1,2],[2,1],[2,2]] and so on:

nchips = sum(chips)
traj = [[]]
last = [[]]    
while len(last[0]) < nchips:
    newlast = []
    for tr in last:
        for d in [1,2,3,4]:
        newlast.append(tr + [d])
    last = newlast
    traj += last

When I did it in PHP I used number with base 3. But it was a tricky and non elegant solution.

    for ($i=-1; $i<=$n; $i+=1) {

    if ($i>-1) {
        $n5 = base_convert($i,10,5);
        $n5_str = strval($n5);
        $tr = array();
        $found = 0;
        for ($j=0; $j<strlen($n5_str); $j+=1) {
        $k = $n5_str[$j];
        if ($k==0) {
            $found = 1;
            break;
        }
        array_push($tr,$k);
        }
        if ($found==1)
        continue;
    } else {
        $tr = array();
    }
}

Can it be done easily in Java?

© Stack Overflow or respective owner

Related posts about java

Related posts about loops