JavaScript - How can I change image src based on a random number? - javascript

I have a random number generator that gives me a value between 1 and 6 (N).
I want to change the image SRC based on what number I get.
for instance, I have 6 images named [image1, image2, image3, image4, image5, image6].
let N = Math.random() * 6;
N = Math.floor(N);
document.querySelector(".img").src = `images/image${N}.png `;
I think the problem is caused by JS parsing images/img${N}.png as a HTML code due to ${N} being JavaScript code and HTML not being able to assign a value to it.
is there another way of writing this without using if / else if for every value of N?
like so =>
let N = Math.random() * 6;
N = Math.floor(N);
if (N === 1) {
document.querySelector(".img1").src = "images/image1.png";
} else if (N === 2) {
document.querySelector(".img1").src = "images/image2.png";
} else if (N === 3) {
document.querySelector(".img1").src = "images/image3.png";
} else if (N === 4) {
document.querySelector(".img1").src = "images/image4.png";
} else if (N === 5) {
document.querySelector(".img1").src = "images/image5.png";
} else {
document.querySelector(".img1").src = "images/image6.png";
}

Your problem is a superfluous space at the end of the template/string
document.querySelector(".img").src = `images/image${N}.png `;
// ^
and missing one for one based counting.
Your actual random values are 0 ... 5, but you need 1 ... 6.
You could take a shorter approach by moving the random/flooring part into the expression.
document.querySelector(".img").src = `images/image${Math.floor(Math.random() * 6) + 1}.png`;
const n = Math.floor(Math.random() * 6) + 1;
console.log(`images/image${n}.png`);

You can use array index like this:
let N = Math.random() * 6;
N = Math.floor(N);
const imgs = [image1, image2, image3, image4, image5, image6]
document.querySelector(".img1").src = imgs[N];

You can use something like this :
let N = 6 // no of images
const imageBase='images/image';// relative or absolute url
document.querySelector(".img").src = `${imageBase}${Math.floor(Math.random() * N)}.png`;

Related

set input values in array and randomize content to display

I can't seem to find any solutions.
I want to create a form that collects 4 nicknames after submit a form and then displays them all randomly in html code using javascript
My 4 input values are now in an array.
I have to display them randomly in two different teams.
I'm trying to get a random index, and as long as it's different from the ones already assigned to avoid one person being on both teams.
This code works, but sometimes, one player is assigned to 2 teams. Then, the randomizer doesn't work... Do you have an idea ?
function getRandomNumber(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function getData() {
let joueur1 = document.querySelector("#player1").value;
let joueur2 = document.querySelector("#player2").value;
let joueur3 = document.querySelector("#player3").value;
let joueur4 = document.querySelector("#player4").value;
playerList.push(player1.value);
playerList.push(player2.value);
playerList.push(player3.value);
playerList.push(player4.value);
randomNumber1 = getRandomNumber(playerList.length);
last1 += randomNumber1;
random1.textContent = playerList[randomNumber1];
do {
randomNumber2 = getRandomNumber(playerList.length);
} while (randomNumber2 == last1 && last4 && last3);
last2 += randomNumber2
random2.textContent = playerList[randomNumber2];
do {
randomNumber3 = getRandomNumber(playerList.length);
} while (randomNumber3 == last1 && last2 && last4);
last3 += randomNumber3
random3.textContent = playerList[randomNumber3];
do {
randomNumber4 = getRandomNumber(playerList.length);
}while (randomNumber4 == last1 && last2 && last3)
random4.textContent = playerList[randomNumber4];
last4 += randomNumber4
}
Thanks for your help !
Here is a simple way of getting a random item from your array
Here you add your items into array
let joueur1 = document.querySelector("#player1").value;
let joueur2 = document.querySelector("#player2").value;
let joueur3 = document.querySelector("#player3").value;
let joueur4 = document.querySelector("#player4").value;
let playerList=[];
playerList.push(joueur1);
playerList.push(joueur2);
playerList.push(joueur3);
playerList.push(joueur4);
Then, Here is how you can get randomized content
let randomPlayer = playerList[Math.floor(Math.random() * playerList.length)];
Math.random() will never be 1. The largest index is always one less than the length of the array

I cant get my code to check if a number is already in a array | JavaScript

var usedNumbers = []
var counter = 0
while(counter < 9){
var math = Math.floor(Math.random() * 9)
if(math != usedNumbers){
usedNumbers[counter] = math
counter++
}
}
console.log(usedNumbers)
i am really bad at explaining and really new to coding but i will do my best
i want my piece of code to create a random number, check if that number is used before and then put it in the array so i can use it later.
but for some reason the if statement is always true so it doesnt check for duplicates
if someone can explain what i did wrong and how to fix it that would be great
You could take a Set and check only the size of it.
const numbers = new Set;
while (numbers.size < 9) numbers.add(Math.floor(Math.random() * 9));
console.log(...numbers);
You can use the array method .includes
var usedNumbers = []
var counter = 0
while(counter < 9){
var math = Math.floor(Math.random() * 9)
if(!usedNumbers.includes(math)){
usedNumbers[counter] = math
counter++
}
}
console.log(usedNumbers.sort())
Here is a functional and recursive way of doing it.
const saveNums = (currentNum, size, result) => {
if (result.length >= size) {
return result;
}
const newResult = result.includes(currentNum) ? result : [...result, currentNum];
return saveNums(Math.floor(Math.random() * size), size, newResult);
};
console.log(saveNums(Math.floor(Math.random() * 9), 9, []));

JavaScript - Generate a random number between 1 and 5, but never the same number twice consecutively

I have some simple code to generate a random number between 1 and 5.
Depending on what number is pulled, a certain sound file will play. However, how could I prevent this simple program from generating the same number twice in a row consequently making the same audio to play twice?
For example: a roll of the dice is never the same twice consecutively, meaning you cannot roll a 2 if you just rolled a 2 etc.
I was experimenting with if else statements and kind of backed myself into a corner. I know this may seem like a simple problem but I'm at my wits end on this one.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display a random number between 1 and 5.</p>
<button onclick="myFunction()">ROLL DICE</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = Math.floor((Math.random() * 5) + 1);
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
you need to get a new number and compare with the old one, if it's the same one, get a new one and repeat. a little recursuion could help here!
let lastNumber // start with undefined lastNumber
function getRandNumber() {
var x = Math.floor((Math.random() * 5) + 1); // get new random number
if (x === lastNumber) { // compare with last number
return getRandNumber() // if they are the same, call the function again to repeat the process
}
return x // if they're not the same, return it
}
function myFunction() {
const number = getRandNumber()
lastNumber = number
document.getElementById("demo").innerHTML = number;
}
How about creating a list to pick from with the last number removed?
lastNumber = 0; // Initialize it to a number outside the list so first pick is from full five.
sourceList = [1,2,3,4,5];
function noRepeatRandom(){
nextList = sourceList.filter(function(x){return x!=lastNumber});
randomIndex = Math.floor(Math.random() * nextList.length);
lastNumber = nextList[randomIndex]
return lastNumber
}
This should pick from the full five for the first call.
var lastRoll = null;
function myFunction() {
var thisRoll = lastRoll;
while (thisRoll === lastRoll) {
thisRoll = Math.floor((Math.random() * 5) + 1);
}
document.getElementById("demo").innerHTML = thisRoll;
lastRoll = thisRoll;
}
<p>Click the button to display a random number between 1 and 5.</p>
<button onclick="myFunction()">ROLL DICE</button>
<p id="demo"></p>
var curr = 0;
function myFunction() {
var x = Math.floor((Math.random() * 5) + 1);
if(x == curr) {
myFunction();
}
else {
curr = x;
document.getElementById("demo").innerHTML = x;
}
}
This should do it if you don't mind using a global variable.
Demo: http://jsfiddle.net/jkrb837p/1/
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display a random number between 1 and 5.</p>
<button onclick="myFunction()">ROLL DICE</button>
<span id="previousNumber" style="display:none"></span>
<p id="demo"></p>
<script>
function myFunction() {
var x = getRandomNum();
var temp = document.getElementById("previousNumber").innerHTML;
while(x == temp){
x = getRandomNum();
}
document.getElementById("demo").innerHTML = x;
document.getElementById("previousNumber").innerHTML = x;
}
function getRandomNum(){
var x = Math.floor((Math.random() * 5) + 1);
return x;
}
</script>
Simple math trick to exclude excessive random calls:
In the first time generate random in range 1..5
In the next times call random in range 1..4, add it to the current value and use modulo operation - to preserve result range 1..5 but exclude current value
Code (note it uses x in range 0..4 but output is shifted by one to simplify math)
var s = ""
var x = Math.floor((Math.random() * 5));
for (i = 0; i < 40; i++) {
s = s + (x + 1) + " "
x = (x + Math.floor((Math.random() * 4) + 1 )) % 5;
}
print(s)
1 4 3 2 1 5 4 5 2 1 4 2 4 5 1 4 3 1 4 5 2 1 3 5 2 4 5 3 1 5 3 5 4 5 1 5 3 5 4 2
Here is a function that you can use. It's quite simple:
min: minimum range;
max: maximum range;
length: how many numbers to generate.
Function and usage:
const randomUniqueNumbers = (min, max, length=1) =>
{
const limit = max-min+1;
if (min > max || max < min){
throw new Error(`Parameter "min" has to be smaller than "max" and vice-versa.`)
}
else if (length > limit){
throw new Error(`The length between ${min} and ${max} cannot exceed ${limit}.`)
}
let uniqueNumbers = [];
let number;
for(var i=0; i<length; i++){
do
number = Math.floor(Math.random() * limit) + min;
while(uniqueNumbers.indexOf(number) !== -1);
uniqueNumbers[i] = number;
}
return uniqueNumbers;
}
console.log(randomUniqueNumbers(20, 30, 3)); //[24, 27, 26]
console.log(randomUniqueNumbers(100, 1000, 5)) //[865, 438, 798, 247, 232]
console.log(randomUniqueNumbers(1, 5, 5)) //[5, 2, 1, 3, 4]

multiple if statements in javascript not acting as they should

I'm creating a random image generator that displays images when a button is clicked. I'm trying to prevent the same image being displayed twice in a row by having the random number connected to each image increase by 1 if duplicated (in other words the next image will be shown rather than the same image twice). I'm trying to use if statements to achieve this but there seems to be a glitch in my code as the same image is still being displayed more than once. Not sure where the problem is. Any solutions out there ?
Thanks
document.getElementById('ranImgBtn').onclick = function() {
var ranImgDis = document.getElementById('ranImgDis');
ranImgDis.style.width = '300px';
ranImgDis.style.height = '200px';
var pic1 = href="http://farm4.staticflickr.com/3691/11268502654_f28f05966c_m.jpg";
var pic2 = href="http://farm1.staticflickr.com/33/45336904_1aef569b30_n.jpg";
var pic3 = href="http://farm6.staticflickr.com/5211/5384592886_80a512e2c9.jpg";
var num = Math.floor(Math.random() * (3 - 1 +1)) + 1;
if(num !== 2 && num !== 3) {
if(ranImgDis.src !== pic1) {
ranImgDis.src = pic1;
} ranImgDis.src = pic2;
} else if (num !== 1 && num !== 3) {
if(ranImgDis.src !== pic2) {
ranImgDis.src = pic2;
} ranImgDis.src = pic3;
} else if (num !== 1 && num !== 2) {
if(ranImgDis.src !== pic3) {
ranImgDis.src = pic3;
} ranImgDis.src = pic1;
}
}
You are missing an else in all your inner if statements. The result is that even if the code in the if statement is executed, the code after it is always executed and replaces what the code inside the if statement did.
You code like this:
if(ranImgDis.src !== pic1) {
ranImgDis.src = pic1;
} ranImgDis.src = pic2;
should be:
if(ranImgDis.src !== pic1) {
ranImgDis.src = pic1;
} else {
ranImgDis.src = pic2;
}
You can make the code simpler and more flexible by putting the images in an array, and keep the index of the current image rather than checking the source of the image. You can use the length of the array when you create the random number, then you can just add more images to the array without changing anything else in the code.
var pics = [
"http://farm4.staticflickr.com/3691/11268502654_f28f05966c_m.jpg".
"http://farm1.staticflickr.com/33/45336904_1aef569b30_n.jpg",
"http://farm6.staticflickr.com/5211/5384592886_80a512e2c9.jpg"
];
var current = 0;
document.getElementById('ranImgBtn').onclick = function() {
var ranImgDis = document.getElementById('ranImgDis');
ranImgDis.style.width = '300px';
ranImgDis.style.height = '200px';
// get a random number within a range one less than the number of images
var num = Math.floor(Math.random() * (pics.length - 1)) + 1;
// use the random number to pick a different image from the current one
current = (current + num) % pics.length;
ranImgDis.src = pics[current];
}
This'll work, and let you expand the number of images beyond three.
document.getElementById('ranImgBtn').onclick = function() {
var ranImgDis = document.getElementById('ranImgDis');
ranImgDis.style.width = '300px';
ranImgDis.style.height = '200px';
var pics = [
"http://farm4.staticflickr.com/3691/11268502654_f28f05966c_m.jpg",
"http://farm1.staticflickr.com/33/45336904_1aef569b30_n.jpg",
"http://farm6.staticflickr.com/5211/5384592886_80a512e2c9.jpg"
]
var currentSrc = document.getElementById('ranImgDis').src
var newSrc = currentSrc
while (newSrc == currentSrc) {
newSrc = pics[Math.floor( Math.random() * pics.length )]
}
ranImgDis.src = newSrc
}
JSFiddle of it at http://jsfiddle.net/X7HM2/
Why dont you change the logic abit.
Rename the images to numbers from 1 to 3 .
Than generate the random number between 1 to 3 and if that random number is same as currently loaded image regenerate the number , this logic will help you even when you will add images from 3 to finite limit.
Your logic is a bit messy, and also there are some obvious problems like:
if(ranImgDis.src !== pic1) {
ranImgDis.src = pic1;
} ranImgDis.src = pic2;
This will unconditionally set ranImgDis.src to pic2 at the end of the day. So maybe you should think this over. I suggest you to maintain an array instead to avoid dupes.

javascript - generate a new random number

I have a variable that has a number between 1-3.
I need to randomly generate a new number between 1-3 but it must not be the same as the last one.
It happens in a loop hundreds of times.
What is the most efficient way of doing this?
May the powers of modular arithmetic help you!!
This function does what you want using the modulo operator:
/**
* generate(1) will produce 2 or 3 with probablity .5
* generate(2) will produce 1 or 3 with probablity .5
* ... you get the idea.
*/
function generate(nb) {
rnd = Math.round(Math.random())
return 1 + (nb + rnd) % 3
}
if you want to avoid a function call, you can inline the code.
Here is a jsFiddle that solves your problem : http://jsfiddle.net/AsMWG/
I've created an array containing 1,2,3 and first I select any number and swap it with the last element. Then I only pick elements from position 0 and 1, and swap them with last element.
var x = 1; // or 2 or 3
// this generates a new x out of [1,2,3] which is != x
x = (Math.floor(2*Math.random())+x) % 3 + 1;
You can randomly generate numbers with the random number generator built in to javascript. You need to use Math.random().
If you're push()-ing into an array, you can always check if the previously inserted one is the same number, thus you regenerate the number. Here is an example:
var randomArr = [];
var count = 100;
var max = 3;
var min = 1;
while (randomArr.length < count) {
var r = Math.floor(Math.random() * (max - min) + min);
if (randomArr.length == 0) {
// start condition
randomArr.push(r);
} else if (randomArr[randomArr.length-1] !== r) {
// if the previous value is not the same
// then push that value into the array
randomArr.push(r);
}
}
As Widor commented generating such a number is equivalent to generating a number with probability 0.5. So you can try something like this (not tested):
var x; /* your starting number: 1,2 or 3 */
var y = Math.round(Math.random()); /* generates 0 or 1 */
var i = 0;
var res = i+1;
while (i < y) {
res = i+1;
i++;
if (i+1 == x) i++;
}
The code is tested and it does for what you are after.
var RandomNumber = {
lastSelected: 0,
generate: function() {
var random = Math.floor(Math.random()*3)+1;
if(random == this.lastSelected) {
generateNumber();
}
else {
this.lastSelected = random;
return random;
}
}
}
RandomNumber.generate();

Categories

Resources