Kirkman14
Kirkman14

Reputation: 1676

How to sort two arrays with the same random sort

Okay, I'm building a quiz application in jQuery/javascript.

The following little function is intended to randomize a series of possible answers for a question, as well as a series of photos. Each photo corresponds to one of the answers.

Before I call this function, the photos and answers are in the same order in each respective wrapped set.

The function does randomize both sets. But each one is randomized separately. I need them both to have the SAME randomization.

I can't figure out how to achieve this. I thought might be able to chain them jQuery style, but that's not right. I also tried separating out the function within the sort(), but that didn't do the trick either.

Can anyone help?

function randomize() {
    var elemsPhotos = $('.photos').children('img').get();
    var elemsQuests = $('.answers').children('.answerLine').get();
    elemsPhotos.sort(function() { return (Math.round(Math.random())-0.5); });
    elemsQuests.sort(function() { return (Math.round(Math.random())-0.5); });
    $('.photos').remove('img');
    $('.answers').remove('.answerLine');
    for (var i=0; i < elemsQuests.length; i++) {
        $('.photos').append(elemsPhotos[i]);      
        $('.answers').append(elemsQuests[i]);      
    }
}

Upvotes: 4

Views: 1765

Answers (3)

Yanick Rochon
Yanick Rochon

Reputation: 53516

Why don't you just randomize an array with n values (where n is the number of questions/photos) and use that array to get the "random" index in each question/photo array?

var elemsPhotos = $('.photos').children('img').get();
var elemsQuests = $('.answers').children('.answerLine').get();
var n = elemsQuests.length;
var randomIndexes = [];
for (var i=0; i<n; i++) {
   randomIndexes[i] = i;
}
randomIndexes.sort(function() { return (Math.round(Math.random())-0.5); });

$('.photos').remove('img');
$('.answers').remove('.answerLine');
for (var i=0; i < n; i++) {
    $('.photos').append(elemsPhotos[randomIndexes[i]]);      
    $('.answers').append(elemsQuests[randomIndexes[i]]);      
}

Upvotes: 4

orip
orip

Reputation: 75427

You can randomize pairs of (photo, quest):

var photos = $('.photos').children('img').get();
var quests = $('.answers').children('.answerLine').get();

var pairs = [];
for (var i=0; i < quests.length; i++)
  pairs[i] = { photo: photos[i], quest: quests[i] };

// randomize 'pairs' any way you like

$.each(pairs, function(i, val) {
  $('.photos').append(val.photo);      
  $('.answers').append(val.quest);  
});

Upvotes: 0

Winfred
Winfred

Reputation: 895

If they comes in as pair, could you use a div to hold both of them and randomise the ordering of the divs instead?

otherwise, you can write a randomizer to generate a sequence . i.e. 1,4,2,3 as the indices, and then put the photos and answers in that order?

element 1->postion 1

element 2->postion 4

element 3->postion 2

element 4->postion 3

Upvotes: 5

Related Questions