So I want a random number (picture) from a code below to appear as much time as I want. In this case I am dealing with pictures. Let' say I want to make a picture named 1.png just to be printed on screen 4 times excatly and then let's say pictures 5.png and 6.png all together to be returned 10 times (it can be 3 times 5.png, 7 times 6.png and other ways we can get to 10) and so on for other examples. How can I do it, since I have no idea at all ?
I hope I explained the right way what I want, and I hope anyone can help, thank you for your help.
function RandomImage() {
return (Math.ceil(Math.random() * 10)).toString() + ".png";
}
If you want to duplicate a string you could use a function like this
function repeat(item, number=1) {
return Array.from({length: number}).fill(item)
}
You can then call it like:
repeat(RandomImage(), 3) // -> ["1.jpeg", "1.jpeg", "1.jpeg"]
You can do this by setting up a datastructure which keeps track of how many times a specific number has already been returned. For this purpose we can utilize JavaScript's Map object.
So the basic idea is this:
Here's an example:
let randomNumbers = new Map();
let maxNumbers = 10;
for (let a = 0; a <= maxNumbers; a++) {
randomNumbers.set(a, 0);
}
function RandomImage() {
let failed = false;
let random;
do {
failed = false;
random = Math.ceil(Math.random() * maxNumbers);
switch (random) {
case 1:
if (randomNumbers.get(1) == 4) {
failed = true;
}
break;
case 5:
if (randomNumbers.get(5) + randomNumbers.get(6) == 10) {
failed = true;
}
break;
case 6:
if (randomNumbers.get(5) + randomNumbers.get(6) == 10) {
failed = true;
}
break;
}
}
while (failed);
randomNumbers.set(random, randomNumbers.get(random) + 1);
return random.toString() + ".png";
}
for (let a = 0; a < 50; a++) {
console.log(RandomImage());
}