This question already has answers here:
Getting a random value from a JavaScript array
(28 answers)
Closed 4 months ago.
Make sentences from the three arrays. Firt index with first index form each array so on..
10 sentences. (This I have figured out and managed)
Use Math.random to mix the words from the arrays randomly to make new sentences, doesnt matter if a word get used two times.
Question: where do i best put the Math.random in my code?
let substantiv = ['Daddy', 'Jag', 'Hästen', 'Mamma', 'Glaset', 'Gameboy', 'Pelle','Blondie', 'Sängen', 'Bilen']
let verb = ['cyklar', 'rider', 'bakar', 'springer', 'hoppar', 'äter', 'dricker', 'går', 'läser', 'sover']
let adj = ['bra', 'dåligt', 'roligt', 'inte', 'alltid', 'på Söndag', 'aldrig', 'imorgon', 'idag', 'snabbt']
let cont = document.createElement('div')
document.body.append(cont)
for(let i=0; i<10; i++){
const el1 = document.createElement('div')
el1.textContent = `${substantiv[i]} `+`${verb[i]} `+`${adj[i]}`
cont.append(el1)
}
I found this solution;
for(let i=0; i<10; i++){
const random1 = Math.floor(Math.random()* substantiv.length)
const random2 = Math.floor(Math.random()* verb.length)
const random3 = Math.floor(Math.random()* adj.length)
const el2 = document.createElement('div')
el2.textContent = `${substantiv[random1]} ${verb[random2]} ${adj[random3]}`
cont.append(el2)
}
Related
This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 2 years ago.
First let me say am a novice at Javascript so this may be more obvious than I think. But what I'm trying to do is create a new Javascript array from two existing arrays. My thinking is to create a for loop, test if they are equal and if not push that number into a new array. For example.
var allArr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
var myArr = [7,8,9,10,14,17];
var fnlArr = [];
What I would like to end up with is fnlArr = [1,2,3,4,5,6,11,12,13,15,16,18,19,20];
Something like:
for (n = 0; n < myArr.length; n++){
for (p = 0; p < allArr.length; p++){
if (p!==myArr[n]){
fnlArr.push(p);}
}
}
I was also thinking maybe to grep to see if they are the same???
Any help would be appreciated.
You can use .filter:
const allArr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
const myArr = [7,8,9,10,14,17];
const set = new Set(myArr);
const fnlArr = allArr.filter(e => !set.has(e));
console.log(fnlArr);
This question already has answers here:
How to count duplicate value in an array in javascript
(35 answers)
Closed 2 years ago.
How can I count how many times wordToCount are in the phrasesToCheck. And how to put this number to counter variable ?
let counter = [];
let wordToCount = ["tomato","cat"];
let phrasesToCheck = ['my cat like potatoes','cat like apple','my golden fish like tomato'];
counter[0] = 1; //tomato
counter[1] = 2; //cat
let wordToCount = ["tomato","cat"];
let phrasesToCheck = ['my cat like potatoes','my cat like apple','my golden fish like tomato'];
let allwords = phrasesToCheck.join(' ').split(' ');
let counter = wordToCount.map(word => allwords.reduce((acc, v) => acc += v === word, 0));
console.log(counter);
This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 5 years ago.
I want to optimize my javascript code with a FOR by i can't do this and i don't know why.
My code :
let pokemon1 = 'premier';
let pokemon2 = 'second';
let pokemon3 = 'troisieme';
for (var i = 1; i < 4; i++) {
console.log(pokemon[i]);
}
Do you know why it doesn't work ?
Thank you very much and sorry if i am a noob.
You should place the pokemon in an array:
let pokemon = [];
pokemon[0] = "premier";
pokemon[1] = "second";
pokemon[2] = "troisieme";
for(var i = 0; i < pokemon.length; i++){
console.log(pokemon[i])
};
Followed by some reading time: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration
Since you are using a list, you should use [] to define an array :
let pokemons = ['premier', 'second', 'troisième'];
for (let i = 0; i < pokemons.length; i++) {
console.log(pokemons[i]);
}
See https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array for more information.
Also you should note that the first element of a list is 0.
So basically pokemons[0] === 'premier and pokemons[2] === 'troisième'
This question already has answers here:
How can I shuffle an array? [duplicate]
(2 answers)
Closed 8 years ago.
My exact requirement is to return all numbers from 1 to 2000 randomly and shouldn't repeat a number twice. So we can say if i have
function generateRnNumber(){
var arr = [1,2,3,4,5,6,7,8,9,10,...2000];
randomNumber = Math.floor((Math.random()*2000));
return randomNUmber;
}
So if i call generateRnNumber a number between 1 - 2000 which is not returned before, or a unique number so if i call 2000 times i should get all the numbers but in random order. I don't want to keep an array with 2000 elements. Please help me in writing this function.
Keep an array with all possible values and randomize the order. When you need a random value, pop the array (removing the value the "possible values"-array).
To do this otherwise, you would anyway need an array to hold the "taken" values so i don't think you can get around keeping an array of the size of your "value range".
You can shuffle the array like this:
function shuffle(o){
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
usage:
var myArray = [];
for(var i = 1; i <= 2000; i++) {
myArray.push(i);
}
var randomArray = shuffle(myArray).splice(0, 10); // an array with 10 random numbers varrying from 1-2000
source: How can I shuffle an array?
This question already has answers here:
How to randomize (shuffle) a JavaScript array?
(69 answers)
Closed 9 years ago.
I am trying to make a script which is outputting every number from 1-10.
Using a random number generator, in JavaScript.
I want every number to be unique.
Here is an example of what i would like the script to output:
5 9 7 6 1 3 4 8 2 10
This is my attempt:
var test = [];
var amountOfNumbers = 10;
var inArray = false;
var useNumbers = [];
for(var i=0; useNumbers.length<=amountOfNumbers; i++){
var rng = Math.floor((Math.random()*amountOfNumbers)+1);
for(var a=0; a<=test.length; a++){
if(rng == test[a]){
inArray == true;
}
}
if(!inArray){
document.write(rng);
test.push(rng);
useNumbers.push(rng);
}
}
Hope you can help.
for the record I am not interested in jQuery og any other library :)
1) How to fix your code
You have a few errors, among them the fact you don't reset inArray to false and that you don't iterate over the whole test array (use <, not <=). But using a loop to see if you already have the number isn't efficient, it's better to use an object as a map :
var test = [];
var amountOfNumbers = 10;
var useNumbers = {};
for(var i=0; test.length<amountOfNumbers; i++){
var rng = Math.floor((Math.random()*amountOfNumbers)+1);
if(!useNumbers[rng]){
document.write(rng);
test.push(rng);
useNumbers[rng] = true;
}
}
2) How to do it properly
Your algorithm will loop until it is lucky enough to find the remaining numbers. This isn't efficient and isn't predictable. The normal reliable practice is
to generate the array [1..10]
to shuffle it
Generating an array of the integers from 1 to N can be done with a simple loop or in a fancier way :
var arr = Array.apply(0,new Array(N)).map(function(_,i){ return i+1 });
Shuffling an array is usually done with the Fisher-Yates algorithm, for which you'll easily find JS implementations (it's easy to write anyway). A fast (theoretically not guaranteed to work with all future sort implementations) alternative is this one :
arr = arr.sort(function(a,b){ return Math.random()>0.5 });
The whole program
Your approach means to check over all the array in each step, looking if your random number is already inside the array, which means a lot lost time.
Best approach is disordering an ordered array. In each loop, we generate a random number (in the example, a number between 0 and 1) and with a 50% probability we change the item in the current position for other item in a random position (between 0 and the length of the array).
Hope it helps.
function disorder(arg) {
for (var i = 0; i < arg.length; i++) {
if (Math.random() < 0.5) {
var aux = arg[i];
var rndPos = Math.floor(Math.random()) * arg.length;
arg[i] = arg[rndPos];
arg[rndPos] = aux;
}
}
return arg;
}
var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var myNewArray = disorder(myArray);
myNewArray.forEach(function(item) {
console.log(item);
});