How to generate 3 names without the same name repeated [duplicate] - javascript

This question already has an answer here:
Math random to find Names in an Array while not duplicating
(1 answer)
Closed 1 year ago.
window.onload = start;
function start () {
var name = ["Hans","Ole","Nils","Olav","Per","Knut","Kari","Line","Pia"]
var random = Math.floor(Math.random()*8)
var random2 = Math.floor(Math.random()*8)
var random3 = Math.floor(Math.random()*8)
var name2 = []
name2.push(name[random])
name2.push(name[random2])
name2.push(name[random3])
for(i=0; i<3; i++) {
document.getElementById("par").innerHTML += name2[i] + "<br/>" ;
}
}
So far with this code i can generate 3 random names from the name array. But i want the 3 names not to be repeated, and I don't know how to make that happen.

Perhaps this could help. I randomized the order of the array and then just pick the first three elements. This allows for zero repeats of names and generating a new answer each time the function is ran. Not sure what your HTML looks like so I just added the id "demo".
var players = ["Hans","Ole","Nils","Olav","Per","Knut","Kari","Line","Pia"];
function tournament() {
var names = [];
players.sort(function(a,b){return 0.5 - Math.random()});
for (i=0; i<3; i++){
names.push(players[i]);
}
document.getElementById("demo").innerHTML = names;
}

I created a solution that uses recursion.
The function randomNames gets repeated three times. Each time it gets called count gets increased and names is an array without the names that are already taken. It returns an array that holds the three random names.
function start () {
var name = ["Hans","Ole","Nils","Olav","Per","Knut","Kari","Line","Pia"]
function randomNames(count, names) {
if(count >= 3) return [];
var random = Math.floor(Math.random()*(names.length-1));
// remove current name
var name = names.splice(random, 1);
return randomNames(++count, names).concat(name);
}
var random = randomNames(0, name);
}

You could use a hash table for the chosen items and check against until all wanted items are found.
window.onload = start;
function start() {
var name = ["Hans", "Ole", "Nils", "Olav", "Per", "Knut", "Kari", "Line", "Pia"],
hash = {},
random;
while (Object.keys(hash).length < 3) {
do {
random = Math.floor(Math.random() * name.length);
} while (hash[random])
hash[random] = true;
document.getElementById("par").innerHTML += name[random] + "<br/>";
}
}
<div id="par"></div>
ES6 with Set
window.onload = start;
function start() {
var name = ["Hans", "Ole", "Nils", "Olav", "Per", "Knut", "Kari", "Line", "Pia"],
hash = new Set,
random;
while (hash.size < 3) {
do {
random = Math.floor(Math.random() * name.length);
} while (hash.has(random))
hash.add(random);
document.getElementById("par").innerHTML += name[random] + "<br/>";
}
}
<div id="par"></div>

Related

How to display non-repetitive letter within 3 boxes?

The below code can display a single random letter in each box. However, a letter should not be able to appear on different boxes at the same time as one of the boxes. For example, box 1 displays "A", then box 2 and 3 cannot display "A" also.
function random() {
var letter = [];
for (var i = 65; i < 91; i++)
{
letter.push(String.fromCharCode(i));
}
return letter[Math.floor(Math.random() * letter.Length)];
}
function display()
{
document.getElementById("box1").textContent = random();
document.getElementById("box2").textContent = random();
document.getElementById("box3").textContent = random();
}
A good way to do this would be to overhaul your random function to generate all the letters at once, like so:
function randomN(n=3) {
const letters = new Set()
while (letters.size < 3) {
const i = Math.floor(Math.random() * (91-65)) + 65
letters.add(String.fromCharCode(i))
}
return [...letters]
}
function display() {
const [letter1, letter2, letter3] = randomN()
document.getElementById("box1").textContent = letter1
document.getElementById("box2").textContent = letter2
document.getElementById("box3").textContent = letter3
}
For a more modern approach you can utilize generators:
function* randomLetters() {
const letters = "QWERTYUIOPASDFGHJKLZXCVBNM".split('')
while (letters.length > 0) {
const i = Math.floor(Math.random() * letters.length)
yield letters[i]
letters.splice(i, 1)
}
}
function display() {
const letters = randomLetters()
document.getElementById("box1").textContent = letters.next()
document.getElementById("box2").textContent = letters.next()
document.getElementById("box3").textContent = letters.next()
/* and so on and so forth! */
}
function letterGenerator(n=1) {
var generated_letters = [];
var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
for (var i=0; i<n; i++){
var random = Math.floor(Math.random() * alphabet.length);
var letter = alphabet.splice(random, 1)[0];
generated_letters.push(letter)
}
return generated_letters;
}
var letters = letterGenerator(3)
gives Array(3) [ "Q", "T", "I" ], for example.
by using splice, we are making sure the randomly chosen letters are removed from the alphabet variable.
you can then go over the letters with for (letter of letters) or something like that, and add each one to the desired element.
by the way, maybe run a document.querySelectorAll('[id^="box"]'); to get all elements and add to them with a for loop.
this, alongside the n parameter, allows for any number of generated letters.
(if you really want it to be generic, create the box elements using js as well)
the solutions attached in the comments are certainly clever.
I especially liked this one

I would like to know how I can make the "namePrinter" loop function work well?

I was trying to get javascript to print the result of the "generateName" function at least 10 times when I press a button in the html, so i tried a loop inside the function that generates the names and but it didn't work then I separated the loop and wrote it in the function "namePrinter" and create the global variable "names" to store the results of the function "generateName"
but I don't know what part of this whole process is wrong, I already reviewed other questions that were made in this forum but I didn't find an answer either
JS:
//this run the funtion that prints the names
document.getElementById("elvenFemButton").onclick = namePrinter;
//cutting characters function
function capFirst(string){
return string.charAt(10).toUpperCase() + string.slice(1);
}
//Randomizer
function getRandomInt (min,max){
return Math.floor(Math.random() * (max-min)) + min;
}
//this function generates names using both "elfFemName" and "elfLastName" and the functions from above
function generateName(){
var elfFemName1 = ["Adaia","Alisaie","Allisara","Alengwan","Alglaranna","Alachia","Alysia","Amberle","Anethra","Anwen","Apolline","Arathel","Ariane","Arianni","Ariel","Arwen","Ashalle","Ashniel","Atara","Ayara","Brelyna","Briala","Celebrían","Clothild","Cullich","Cylia","Dalish","Dirael","Eldyra","Elanor","Elenwen","Elezen","Ellia","Elynea","Éowyn","Failla","Faralda","Fleur","Freyalise","Galadriel","Gheyna","Jenassa","Katriel","Kira","Laina","Laniatte","Lauriel","Liallan","Liriel","Liselle","Loriel","Lorian","Lúthien","Máire","Mayael","Merril","Miara","Mihris","Minaeve","Nadja","Niranye","Nirya","Raewyn","Selveni","Sera","Shaera","Siofra","Taarie","Tauriel","Valora","Valya","Vanadis","Vanora","Velanna","Ylthin","Ysayle","Yvraine","Zelda"];
var elfLastName2 = ["Aearonian"," Agaraen","Agarher","Agarvran","Aire","Airendil","Amamion","Amdirthor","Amathal","Amather","Amathuilos","Amatheldir ","Amlugol","Aessereg","Aupwe","Calear","Caranagar","Cemno","Duindaer","Duirro","Eilianther","Gaer","Galadher","Gollor","Gulduron","Guldur","Guldurion","Hithaerben","Holiilo","Ingolmondur","Lar","Leucandil","Lanthir","Loeg","Lo","Lumorndaer","Morguldir","Morgulon","Naur","Neithaor","Nullion","Olchanar","Othanar","Olerydon","Ranchon","Rimdor","Rodor","Roher","Rhovanion","Rhovanion","Ruina","Russarocco","Sir","Sirdhemion","Tawaren","Tawarenion","Tawarher","Tordil","Uirchanar","Urendur","Urucher","Yr"];
var elfFemNameGenerator = capFirst(elfFemName1[getRandomInt(0, elfFemName1.length + 2)]) + " " + capFirst(elfLastName2[getRandomInt(0,elfLastName2.length +2)]);
return elfFemNameGenerator;
}
//i want this to get the result's from "generateName" and it should be a global value so i can use it in the next function
var names = generateName();
// this should print the name at least ten times but no
function namePrinter(){
var text = document.getElementById("textArea");
for (var i = 0; i < 10; i++) {
text[i].innerHTML(`${names}`)
}
return namePrinter;
}
innerHTML is not a function, it's a property. So, in the loop use text.innerHTML += name
However, if it's a <textarea> element, then you need to use value property instead:
//this run the funtion that prints the names
document.getElementById("elvenFemButton").onclick = namePrinter;
document.getElementById("elvenFemButton2").onclick = namePrinter2;
//cutting characters function
function capFirst(string){
return string.charAt(10).toUpperCase() + string.slice(1);
}
//Randomizer
function getRandomInt (min,max){
return Math.floor(Math.random() * (max-min)) + min;
}
//this function generates names using both "elfFemName" and "elfLastName" and the functions from above
function generateName(){
var elfFemName1 = ["Adaia","Alisaie","Allisara","Alengwan","Alglaranna","Alachia","Alysia","Amberle","Anethra","Anwen","Apolline","Arathel","Ariane","Arianni","Ariel","Arwen","Ashalle","Ashniel","Atara","Ayara","Brelyna","Briala","Celebrían","Clothild","Cullich","Cylia","Dalish","Dirael","Eldyra","Elanor","Elenwen","Elezen","Ellia","Elynea","Éowyn","Failla","Faralda","Fleur","Freyalise","Galadriel","Gheyna","Jenassa","Katriel","Kira","Laina","Laniatte","Lauriel","Liallan","Liriel","Liselle","Loriel","Lorian","Lúthien","Máire","Mayael","Merril","Miara","Mihris","Minaeve","Nadja","Niranye","Nirya","Raewyn","Selveni","Sera","Shaera","Siofra","Taarie","Tauriel","Valora","Valya","Vanadis","Vanora","Velanna","Ylthin","Ysayle","Yvraine","Zelda"];
var elfLastName2 = ["Aearonian"," Agaraen","Agarher","Agarvran","Aire","Airendil","Amamion","Amdirthor","Amathal","Amather","Amathuilos","Amatheldir ","Amlugol","Aessereg","Aupwe","Calear","Caranagar","Cemno","Duindaer","Duirro","Eilianther","Gaer","Galadher","Gollor","Gulduron","Guldur","Guldurion","Hithaerben","Holiilo","Ingolmondur","Lar","Leucandil","Lanthir","Loeg","Lo","Lumorndaer","Morguldir","Morgulon","Naur","Neithaor","Nullion","Olchanar","Othanar","Olerydon","Ranchon","Rimdor","Rodor","Roher","Rhovanion","Rhovanion","Ruina","Russarocco","Sir","Sirdhemion","Tawaren","Tawarenion","Tawarher","Tordil","Uirchanar","Urendur","Urucher","Yr"];
var elfFemNameGenerator = capFirst(elfFemName1[getRandomInt(0, elfFemName1.length)]) + " " + capFirst(elfLastName2[getRandomInt(0,elfLastName2.length)]);
return elfFemNameGenerator;
}
//i want this to get the result's from "generateName" and it should be a global value so i can use it in the next function
var names = generateName();
var names2 = [];
// this should print the name at least ten times but no
function namePrinter(){
var text = document.getElementById("textArea");
text.value = ""; //clear previous result
for (var i = 0; i < 10; i++) {
text.value += names;
}
}
function namePrinter2(){
var text = document.getElementById("textArea");
names2.length = 0; //clear array
for (var i = 0; i < 10; i++) {
names2[names2.length] = generateName();
}
text.value = names2;
}
<textarea id="textArea"></textarea>
<button id="elvenFemButton">generate names</button>
<button id="elvenFemButton2">generate different names</button>
This however as you can see will print the same name 10 times, if you need generate 10 names and store them globally, than you'll need save them in the array instead.
P.S.
Unrelated, but elfLastName2[getRandomInt(0,elfLastName2.length +2)] is wrong, you can't get value from an index that is larger than length of the array (aka +2 is wrong)

Random Numbers using Arrays Javascript

I am trying to add 8 random numbers to my array and display them. Right now, it is only displaying one random number, and I can't figure out why.
Code:
var array = [ ];
window.onload = function () {
var rand = Math.floor(Math.random() * 101);
for (var i = 0; i < 9; i++) {
array.push(rand);
answer = 'Your array is this: ' + array[i];
}
document.getElementById('result').innerHTML = answer;
}
You are overwriting the value of answer in each iteration of your loop, and then writing the final value of answer to your document.
Further, you also need to generate the random number in the loop, or you'll end up with the same number every time.
Instead of assigning the new value to answer in the loop, append it to answer:
var array = [ ];
var answer = '';
for (var i = 0; i < 9; i++) {
var rand = Math.floor(Math.random() * 101);
array.push(rand);
answer = answer + 'Your array is this: ' + array[i] + '<br/>';
}
document.getElementById('result').innerHTML = answer;
<div id="result"></div>
JSFiddle

Javascript: randomly pair items from array without repeats

I am trying to make a very basic "secret santa" generator as one of my first Javascript projects. I have searched for hours for a solution to this problem but so far nothing has worked that I have found.
I have an array of names which need paired to each other. I successfully have them pairing to each other, but right now someone can be drawn twice. I am pushing the randomly chosen names to another array but I can't find a way to check the randomly chosen names against the ones already chosen.
var names = ["Sean","Kyle","Emily","Nick","Cotter","Brian","Jeremy","Kimmy","Pat","Johnny"];
var used = [];
var picks = [];
if (names.length % 2 != 0) {
alert("You must have an even number of names. You currently have " + names.length + " names.");
}
for( var i = 0; i < names.length; i++){
var random = Math.floor(Math.random()*names.length)
if(names[random] == names[i]) {
names[random] = names[random++];
picks.push(names[i] + " gets " + names[random]);
used.push(names[random]);
} else {
picks.push(names[i] + " gets " + names[random]);
used.push(names[random]);
}
}
console.log("picked array: ")
for(var k=0; k<picks.length; k++) {
console.log(picks[k]);
}
console.log("used array: " + used);
Thank you in advance for any help.
Create two arrays with the names, shuffle them, and make sure you don't pick the same name from both arrays :
var names = ["Sean","Kyle","Emily","Nick","Cotter","Brian","Jeremy","Kimmy","Pat","Johnny"];
if (names.length % 2 != 0) {
alert("You must have an even number of names. You currently have " + names.length + " names.");
} else {
var arr1 = names.slice(), // copy array
arr2 = names.slice(); // copy array again
arr1.sort(function() { return 0.5 - Math.random();}); // shuffle arrays
arr2.sort(function() { return 0.5 - Math.random();});
while (arr1.length) {
var name1 = arr1.pop(), // get the last value of arr1
name2 = arr2[0] == name1 ? arr2.pop() : arr2.shift();
// ^^ if the first value is the same as name1,
// get the last value, otherwise get the first
console.log(name1 + ' gets ' + name2);
}
}
FIDDLE
I would suggest a different approach. Shuffle, split, and zip, no mutation:
var splitAt = function(i, xs) {
var a = xs.slice(0, i);
var b = xs.slice(i, xs.length);
return [a, b];
};
var shuffle = function(xs) {
return xs.slice(0).sort(function() {
return .5 - Math.random();
});
};
var zip = function(xs) {
return xs[0].map(function(_,i) {
return xs.map(function(x) {
return x[i];
});
});
}
// Obviously assumes even array
var result = zip(splitAt(names.length/2, shuffle(names)));
//^
// [
// [ 'Nick', 'Kimmy' ],
// [ 'Sean', 'Johnny' ],
// [ 'Kyle', 'Brian' ],
// [ 'Cotter', 'Pat' ],
// [ 'Emily', 'Jeremy' ]
// ]
There is a multitude of ways you can achieve this.
The fastest to code, but not necessarily the randomest is:
var names = ["Sean","Kyle","Emily","Nick","Cotter","Brian","Jeremy","Kimmy","Pat","Johnny"];
function getPicks(names) {
return names.slice(0).sort(function(){ return Math.random()-0.5 }).map(function(name, index, arr){
return name + " gets " + arr[(index+1)%arr.length];
});
}
getPicks(names);
This is not very random because the shuffling isn't very good and also because you get a single cycle each time. There can be no two cycles A->B->C->A D->E->D.
If you want it to have a random number of cycles of variable length, you can split the names array in several arrays and do the above for each of them, then concatenate the results (see elclanrs).
Finally, the last solution is for each person to pick a person at random and if it's the same one, simply pick again. If the last name remaining in both arrays is the same, simply swap it with another pair.
var names = ["Sean","Kyle","Emily","Nick","Cotter","Brian","Jeremy","Kimmy","Pat","Johnny"];
var a = names.slice(0);
var b = names.slice(0);
var result = [];
while (a.length > 1) {
var i = extractRandomElement(a);
var j = extractRandomElement(b);
while (i===j) {
b.push(j);
j = extractRandomElement(b);
}
result.push({ a:i, b:j });
}
if (a[0] === b[0]) {
result.push({ a:a[0], b:result[0].b });
result[0].b = a[0];
} else {
result.push({ a:a[0], b:b[0] });
}
var pairs = result.map(function(item){ return item.a + ' gets ' + item.b});
function extractRandomElement(array) {
return array.splice(Math.floor(Math.random()*array.length),1)[0];
}
I'm a tad late, but thought I'd throw my answer in here. It essentially does the same thing #adeneo's does, but it uses the same basic code as OP:
var names = ["Sean","Kyle","Emily","Nick","Cotter","Brian","Jeremy","Kimmy","Pat","Johnny"];
pickpool = names.slice(0); // Slice the array at the first element to copy it by value
var used = [];
var picks = [];
if (names.length % 2 != 0) {
alert("You must have an even number of names. You currently have " + names.length + " names.");
}
for( var i = 0; i < names.length; i++){
var random = Math.floor(Math.random()*pickpool.length)
if(names[random] == names[i]) {
// names[random] = names[random++];
picks.push(names[i] + " gets " + pickpool[random++]);
pickpool.splice(random++,1);
} else {
picks.push(names[i] + " gets " + pickpool[random]);
pickpool.splice(random,1);
}
}
console.log("picked array: ");
for(var k=0; k<picks.length; k++) {
console.log(picks[k]);
}
http://jsfiddle.net/SNJpC/
If you don't need to keep the original array you can remove the names as they get selected and each time you pick a name check that it isn't an empty string before pushing it to the next array.
Another consideration...
If you are trying to make a 'Secret Santa' generator, by using random method you can get the same pair next year, and next...
This is another solution where you get all the possible pairs (without repeating a name itself or a pair) for multiple years.
var names = ["Sean", "Kyle", "Emily", "Nick", "Cotter", "Brian", "Jeremy", "Kimmy", "Pat", "Johnny"];
if (names.length % 2 != 0) {
alert("You must have an even number of names. You currently have " + names.length + " names.");
} else {
const arr1 = names.slice()
let arr2 = names.slice();
let countDown = number => {
if (number === 1) {
return;
}
const last = arr2.pop([number - 1]);
arr2.unshift(last);
let pairs = [];
arr1.map(item => {
const index = arr1.indexOf(item);
pairs.push(`${arr1[index]} gets ${arr2[index]}`)
})
console.log(pairs)
return countDown(number - 1);
}
countDown(names.length)
}

Javascript: Random number out of 5, no repeat until all have been used

I am using the below code to assign a random class (out of five) to each individual image on my page.
$(this).addClass('color-' + (Math.floor(Math.random() * 5) + 1));
It's working great but I want to make it so that there are never two of the same class in a row.
Even better would be if there were never two of the same in a row, and it also did not use any class more than once until all 5 had been used... As in, remove each used class from the array until all of them have been used, then start again, not allowing the last of the previous 5 and the first of the next 5 to be the same color.
Hope that makes sense, and thanks in advance for any help.
You need to create an array of the possible values and each time you retrieve a random index from the array to use one of the values, you remove it from the array.
Here's a general purpose random function that will not repeat until all values have been used. You can call this and then just add this index onto the end of your class name.
var uniqueRandoms = [];
var numRandoms = 5;
function makeUniqueRandom() {
// refill the array if needed
if (!uniqueRandoms.length) {
for (var i = 0; i < numRandoms; i++) {
uniqueRandoms.push(i);
}
}
var index = Math.floor(Math.random() * uniqueRandoms.length);
var val = uniqueRandoms[index];
// now remove that value from the array
uniqueRandoms.splice(index, 1);
return val;
}
Working demo: http://jsfiddle.net/jfriend00/H9bLH/
So, your code would just be this:
$(this).addClass('color-' + (makeUniqueRandom() + 1));
Here's an object oriented form that will allow more than one of these to be used in different places in your app:
// if only one argument is passed, it will assume that is the high
// limit and the low limit will be set to zero
// so you can use either r = new randomeGenerator(9);
// or r = new randomGenerator(0, 9);
function randomGenerator(low, high) {
if (arguments.length < 2) {
high = low;
low = 0;
}
this.low = low;
this.high = high;
this.reset();
}
randomGenerator.prototype = {
reset: function() {
this.remaining = [];
for (var i = this.low; i <= this.high; i++) {
this.remaining.push(i);
}
},
get: function() {
if (!this.remaining.length) {
this.reset();
}
var index = Math.floor(Math.random() * this.remaining.length);
var val = this.remaining[index];
this.remaining.splice(index, 1);
return val;
}
}
Sample Usage:
var r = new randomGenerator(1, 9);
var rand1 = r.get();
var rand2 = r.get();
Working demo: http://jsfiddle.net/jfriend00/q36Lk4hk/
You can do something like this using an array and the splice method:
var classes = ["color-1", "color-2", "color-3", "color-4", "color-5"];
for(i = 0;i < 5; i++){
var randomPosition = Math.floor(Math.random() * classes.length);
var selected = classes.splice(randomPosition,1);
console.log(selected);
alert(selected);
}
var used = [];
var range = [0, 5];
var generateColors = (function() {
var current;
for ( var i = range[0]; i < range[5]; i++ ) {
while ( used.indexOf(current = (Math.floor(Math.random() * 5) + 1)) != -1 ) ;
used.push(current);
$(" SELECTOR ").addClass('color-' + current);
}
});
Just to explain my comment to jfriend00's excellent answer, you can have a function that returns the members of a set in random order until all have been returned, then starts again, e.g.:
function RandomList(list) {
var original = list;
this.getOriginal = function() {
return original;
}
}
RandomList.prototype.getRandom = function() {
if (!(this.remainder && this.remainder.length)) {
this.remainder = this.getOriginal().slice();
}
return this.remainder.splice(Math.random() * this.remainder.length | 0,1);
}
var list = new RandomList([1,2,3]);
list.getRandom(); // returns a random member of list without repeating until all
// members have been returned.
If the list can be hard coded, you can keep the original in a closure, e.g.
var randomItem = (function() {
var original = [1,2,3];
var remainder;
return function() {
if (!(remainder && remainder.length)) {
remainder = original.slice();
}
return remainder.splice(Math.random() * remainder.length | 0, 1);
};
}());

Categories

Resources