jeudi 17 juin 2021

How could I transform this random image picker function into one that splices the selected image?

I'm very new to coding (wrote my first line of html like 3 weeks ago) and for my first own project, I wanted to create a small gallery that displays random images.

First I only managed to display the same image every time the function was called, then I managed to make it so that the images were rolled separately, but there could have been repetition. Finally, with some help, I got to the current version:

//Images array and global vars
let theImages = [];
for (let i = 0; i <= 25; i++) {
    theImages[i] = "stevejohnson_" + i + ".jpg";
}

let l = theImages.length;
let generated = [];


//Function to pick a random image and display it
function showImage() {
    let whichImage;
    let newImage;
    do {
        whichImage = Math.round(Math.random() * (l - 1));
        newImage = true;
        for (let i = 0; i < generated.length; i++) {
            if (generated[i] === whichImage) {
                newImage = false;
                break;
            }
        }
        if (newImage) {
            console.log("new: " + whichImage);
            generated.push(whichImage);
        } else {
            console.log("already was generated: " + whichImage); //just to see if it works
        }
    } while (!newImage);
    document.write('<img src="' + theImages[whichImage] + '" alt="A random painting of Steve Johnson"' + '>');
}

Now while this works well if I have 200 images and want to display 5, if I want to display 9 images and I only have 10, it can easily end up like this:

new: 8
paint.js:25 new: 0
paint.js:25 new: 7
paint.js:25 new: 5
paint.js:28 already generated: 8
paint.js:28 already generated: 5
paint.js:25 new: 3
paint.js:25 new: 9
paint.js:28 already generated: 8
paint.js:28 already generated: 3
paint.js:25 new: 6
paint.js:28 already generated: 7
paint.js:28 already generated: 3
paint.js:28 already generated: 6
paint.js:28 already generated: 5
paint.js:25 new: 1
paint.js:28 already generated: 6
paint.js:28 already generated: 5
paint.js:28 already generated: 6
paint.js:28 already generated: 7
paint.js:28 already generated: 3
paint.js:25 new: 2

Which is not optimal.

How could I change the function so that it removes the picked images from the array instead of rerolling whenit picks an already used one? My idea to fix this was to splice the "used image" from the array, but anything I try ends up breaking something. Thanks in advance for any help!




Aucun commentaire:

Enregistrer un commentaire