0

I have an simple array of strings that looks like the one below and a corresponding new array. What I need to accomplish is to is to shuffle the the simple array with a simple shuffle algorithm (like the one below), but I need the corresponding new array to to be shuffled with the same exact shuffle, that is the result of each index would be identical. That may be confusing so look at the example output below and it should become clear. Is this type of algorithm even possible with Fisher-Yates shuffle?

Fiddle: here

Before:

var simple_arr = ["701", "702", "703", "704", "705", "706", "707", "708"];
var new_arr = ["A1","A2","A3","A4","A5","A6","A7","A8"];

After:

var after_simple_arr = ["701", "708", "702", "705", "703", "706", "704", "707"];
var after_new_arr = ["A1","A8","A2","A5","A3","A6","A4","A7"];

Fisher-Yates shuffle algorithm:

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }
  return array;
}

2 Answers 2

1

You could shuffle an index array then use it as the index for the two arrays you care about:

var ids = [];
for (var i = 0; i < simple_arr.length; i++) {
    ids.push(i);
}
ids = shuffle(ids);
var dat1 = [];
var dat2 = [];
for (var i = 0; i < ids.length; i++) {
    dat1.push(simple_arr[ids[i]]);
  dat2.push(new_arr[ids[i]]);
}
console.log("shuffled simple_arr: ", dat1);
console.log("shuffled new_arr: ", dat2);
Sign up to request clarification or add additional context in comments.

Comments

0

Just shuffle an index array indices = [0, 1, 2, ...] and then use it to access your to-be-shuffled-by-the-same-permutation arrays via array[indices[i]].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.