I have created the following code that selects 10 random images from a selection of 59 without any duplicates.
The code works great but as a bit of a newbie to javascript, I’m sure the section where I am checking for duplicates could be made more efficient.
I was wondering if anyone could point me in the right direction in making the ‘check for duplicates’ section more ‘professional’.
Any help would be greatly appreciated, thanks.
Heres the code:
The code works great but as a bit of a newbie to javascript, I’m sure the section where I am checking for duplicates could be made more efficient.
I was wondering if anyone could point me in the right direction in making the ‘check for duplicates’ section more ‘professional’.
Any help would be greatly appreciated, thanks.
Heres the code:
Code:
addLoadListener(function() {
// set up array with numbers for each photo
imagenumber = new Array(58)
// create array for each image number
for (i = 0; i < 59; i++) {
imagenumber[i] = i;
}
// create new arrays for amount of images to be used on page
n = new Array(9)
train = new Array(9)
trainlink = new Array(9)
// create image and link for each number
for (i = 1; i < 11; i++) {
train[i] = 'train' + i;
trainlink[i] = 'trainlink' + i;
n[i] = Math.floor(Math.random() * imagenumber.length);
// check for duplicates
while (n[2] == n[1]) {
n[2] = Math.floor(Math.random() * imagenumber.length);
}
while (n[3] == n[1] || n[3] == n[2]) {
n[3] = Math.floor(Math.random() * imagenumber.length);
}
while (n[4] == n[1] || n[4] == n[2] || n[4] == n[3]) {
n[4] = Math.floor(Math.random() * imagenumber.length);
}
while (n[5] == n[1] || n[5] == n[2] || n[5] == n[3] || n[5] == n[4]) {
n[5] = Math.floor(Math.random() * imagenumber.length);
}
while (n[6] == n[1] || n[6] == n[2] || n[6] == n[3] || n[6] == n[4] || n[6] == n[5]) {
n[6] = Math.floor(Math.random() * imagenumber.length);
}
while (n[7] == n[1] || n[7] == n[2] || n[7] == n[3] || n[7] == n[4] || n[7] == n[5] || n[7] == n[6]) {
n[7] = Math.floor(Math.random() * imagenumber.length);
}
while (n[8] == n[1] || n[8] == n[2] || n[8] == n[3] || n[8] == n[4] || n[8] == n[5] || n[8] == n[6] || n[8] == n[7]) {
n[8] = Math.floor(Math.random() * imagenumber.length);
}
while (n[9] == n[1] || n[9] == n[2] || n[9] == n[3] || n[9] == n[4] || n[9] == n[5] || n[9] == n[6] || n[9] == n[7] || n[9] == n[8]) {
n[9] = Math.floor(Math.random() * imagenumber.length);
}
while (n[10] == n[1] || n[10] == n[2] || n[10] == n[3] || n[10] == n[4] || n[10] == n[5] || n[10] == n[6] || n[10] == n[7] || n[10] == n[8] || n[10] == n[9]) {
n[10] = Math.floor(Math.random() * imagenumber.length);
}
// place the images on the page
train[i] = document.getElementById(train[i]);
train[i].src = 'images/jpg/mainimages/rr_image_' + n[i] + '.jpg';
trainlink[i] = document.getElementById(trainlink[i]);
trainlink[i].href = 'images/jpg/mainimages/rr_image_' + n[i] + '_bp.jpg';
}
});