Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
710 views
in Technique[技术] by (71.8m points)

algorithm - Fill a nested structure with values from a linear supply stream

I got stuck in the resolution of the next problem:

Imagine we have an array structure, any structure, but for this example let's use:

[
    [ [1, 2], [3, 4], [5, 6] ],
    [ 7, 8, 9, 10 ]
]

For convenience, I transform this structure into a flat array like:

[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

Imagine that after certain operations our array looks like this:

[ 1, 2, 3, 4, 12515, 25125, 12512, 8, 9, 10]

NOTE: those values are a result of some operation, I just want to point out that is independent from the structure or their positions.

What I would like to know is... given the first array structure, how can I transform the last flat array into the same structure as the first? So it will look like:

[ 
   [ [1, 2], [3, 4] , [12515, 25125] ],
   [ 12512, 8, 9, 10] 
]

Any suggestions? I was just hardcoding the positions in to the given structure. But that's not dynamic.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just recurse through the structure, and use an iterator to generate the values in order:

function fillWithStream(structure, iterator) {
    for (var i=0; i<structure.length; i++)
        if (Array.isArray(structure[i]))
            fillWithStream(structure[i], iterator);
        else
            structure[i] = getNext(iterator);
}
function getNext(iterator) {
    const res = iterator.next();
    if (res.done) throw new Error("not enough elements in the iterator");
    return res.value;
}

var structure = [
    [ [1, 2], [3, 4], [5, 6] ],
    [ 7, 8, 9, 10 ]
];
var seq = [1, 2, 3, 4, 12515, 25125, 12512, 8, 9, 10];
fillWithStream(structure, seq[Symbol.iterator]())
console.log(JSON.stringify(structure));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...