So... this is a bit hard to explain, but I want to print with Javascript this result:
I manage to generate a random function with different characters but they are printing in all rows and always in the same place. What do I have to do to make sure that a random character is printed only once and in a random row every time?
My code:
const characters = '&%$*';
function generateRandomCode() {
let result = ""
let charactersLength = characters.length;
for (let i = 0; i < 1; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result
}
let string = "";
for (let i = 1; i <= 5; i++) {
for (j = 1; j <= 5; j++) {
string += "#";
}
string += generateRandomCode();
generateRandomCode();
string += "<br>";
}
document.write(string);
This is what my code prints:
Try something like below. I created 3 random integers outside the loop, one for character, one for row, and one for the position to insert characters. Use these integers inside the loop
const characters = '&%$*';
let string = "";
let rand = generateRandomCode(); // generate an array of 3 random numbers.
console.log(rand);
for (let i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
string += rand[1] === i && rand[2] === j ? characters[rand[0]] : "#";
}
string += "<br>";
}
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
}
function generateRandomCode() {
return [randomIntFromInterval(0, 3), randomIntFromInterval(0, 4), randomIntFromInterval(0, 4)]
}
document.write(string);
The question doesn't specifically say that the code is restricted to a loop only, just that you want to create that particular output and that it needs to be changed on every load (at least how I read it)
So if you are free not using a loop, you could also try this option :)
const characters = '&$*';
const size = 5;
// create an array with all entries
const set = new Array(size).fill().map( _ => new Array(size).fill('#') );
// choose the row based on the size of the array
const row = Math.floor( Math.random() * set.length );
// choose a column based on the size of the row selected
const col = Math.floor( Math.random() * set[row].length );
// choose a character based on the size of the string
const char = Math.floor( Math.random() * characters.length );
// overwrite the pre-existing # with the random char
set[row][col] = characters[char];
// map the rows to a string and join everything with <br />
document.querySelector('#container').innerHTML = set.map( row => row.join('') ).join('<br />');
#container {
font-family: 'Courier New';
}
<div id="container"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With