Generate a random number 4 times no repeating Javascript? - javascript

I am wanting to generate a random number between 1-100, but I am only wanting to generate those numbers once each time. I have a loop that runs 3 times to run the .Math and then push that into an array. But I dont want the situation where it generates the same number more than once.
I have put 21 in the allAnswers[] array as that is something that will stay consistent. Is there a way to generate and then check that array if that number exists and then run the .math again?
function buttonGenerator(){
var allAnswers = [21],
randomizer = [];
// Generates 3 random answers
for(a = 0 ; a < 3; a++) {
wrongAnswers = Math.floor((Math.random() * 100) + 1);
allAnswers.push(wrongAnswers);
}
// Generates random buttons while inputting the correct and incorrect answers randomly
for(i = 0 ; i < 4; i++) {
var buttonArea = $("#answerOptions");
input = $('<button class="col-xs-6 btn btn-primary"></button>');
input.appendTo(buttonArea);
}
shuffle(allAnswers);
console.log(allAnswers);
}
buttonGenerator();

Use indexOf to check if the array has the value before pushing:
if (allAnswers.indexOf(wrongAnswers) === -1) {
allAnswers.push(wrongAnswers);
}

Related

How to omit 0 from array of randomly generated numbers using Javascript?

I have done a code where it will generate 7 random numbers from 0 to 49.
HTML
<button id="btn_generate" onClick="getMyLuckyNumbers()">GENERATE NUMBERS</button>
<div id="display"></div>
JS
function getMyLuckyNumbers() {
for (var allNumbers=[],i=0;i<50;++i) allNumbers[i]=i;
function shuffle(array) {
var tmp, current, top = array.length;
if(top) while(--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
return array;
}
allNumbers = shuffle(allNumbers);
var luckyNumbers = "";
var g;
for (g = 0; g < 7; g++) {
luckyNumbers += allNumbers[g] + "<br>";
}
document.getElementById("display").innerHTML = luckyNumbers;
}
I would like to know how I can omit 0?
I attempted two ways, but both failed.
Attempt 1:
Changed the i=0 to i=1.
for (var allNumbers=[],i=1;i<50;++i)
allNumbers[i]=i;
This did omit 0 but when 0 was randomly supposed to appear, it shows as undefined.
Attempt 2:
I tried to do an if statement.
if(allNumbers != 0) {
allNumbers = shuffle(allNumbers);
}
But this still displays 0 if it happens to be randomly generated.
So, how do I omit 0?
The issue with starting i from 1 is that the 0th index will be empty, and so when accessed gives undefined.
So, if you want to avoid the number 0, you can make i start at 1, but you would need to change the way you add numbers to your array. Instead of adding your numbers to your array by placing them at a specific index, you can .push() them to the end of your array each iteration like so:
// \/------ start at i = 1, the 1st number to be added to your array
for (var allNumbers=[],i=1;i<50;++i)
allNumbers.push(i);
This way, you will fill up your array with numbers from 1 to 49 which can them be shuffled.

How can I make the unique random numbers from this code appear on my page?

Someone showed me the following code which generates 3 random numbers between 1 and 10:
var limit = 10,
amount = 3,
lower_bound = 1,
upper_bound = 10,
unique_random_numbers = [];
if (amount > limit) limit = amount; //Infinite loop if you want more unique
//Natural numbers than exist in a
// given range
while (unique_random_numbers.length < limit) {
var random_number = Math.floor(Math.random()*(upper_bound - lower_bound) + lower_bound);
if (unique_random_numbers.indexOf(random_number) == -1) {
// Yay! new random number
unique_random_numbers.push( random_number );
}
}
//
How could I make these numbers appear in place of elements with a corresponding class? The code below is clearly wrong, but hopefully it illustrates what I'm trying to achieve:
<script type='text/javascript'>
var random_number1 = random_number1();
$('.random_number1').html(random_number1);
var random_number2 = random_number2();
$('.random_number2').html(random_number2);
</script>
<span class="random_number1"></span> <span class = "random_number2"></span>
assuming you had a div with id of numbers and the array unique_random_numbers, you'd populate it this way, assuming you have jquery reference:
for ( i = 0; i < unique_random_numbers.length; i++)
{
$("#Numbers").html($("#Numbers").html() +"<span>" + unique_random_numbers[i] + "</span><br/>");
}

Calculating standard deviation not executing loop

I've just started learning coding on code academy and I'm really new to this.
I'm trying to make this program ask the user for values which it adds to an array from which it calculates the sample standard deviation.
// This array stores the values needed
var figures;
getStandardDeviation = function() {
// I need at least two figures for a standard deviation
figures[0] = prompt("Enter a number:");
figures[1] = prompt("Enter a number:");
// Checks whether user wishes to add more values to the array
var confirm = prompt("Would you like to add another? (Y or N)").toUpperCase();
// I can't figure out why the following if statement is not executed
// It checks whether the user wishes to add more values and adds them to the array
// If not it breaks the for loop
if (confirm === "Y"){
for ( i = 0; i === 100; i++){
figures[i + 2] = prompt("Enter a number:");
confirm = prompt("Would you like to add another figure? (Y or N)").toUpperCase();
if (confirm === "N"){
break;
}
}
}
// The rest of the code works fine from here onwards
var sumx = 0;
var n = figures.length;
for(var i = 0 ; i < n ; i++) {
sumx += figures[i];
}
console.log("Sum = " + sumx);
var sumXsq = 0;
for( i = 0 ; i < n ; i++) {
sumXsq += (figures[i] * figures[i]);
}
console.log("Sum x squared = " + sumXsq);
var sxx = (sumXsq - (sumx * sumx)/n);
console.log("Sxx = " + sxx);
var v = sxx/(n - 1);
console.log("Variance = " + v);
var standardDev = Math.sqrt(v);
console.log("Standard Deviation = " + standardDev);
};
getStandardDeviation();
The program is supposed to ask me if I want to add more values to the array, then when I confirm, it gives me a prompt to add more values.
Currently, when I execute the program I input the numbers 56 and 67. The code then asks me if I wish to add more values, I then confirm this. Instead of letting me add more values it ignores this and calculates the standard deviation with the first two values (56 and 67).
The output is:
Sum = 05667
Sum x squared = 7625
Sxx = -16049819.5
Variance = -16049819.5
Standard Deviation = NaN
for ( i = 0; i === 100; i++){[...]} means
Set i to 0
If it's not true that i === 100 (that is: if i is not 100), end the loop
Do whatever I put inside the {} braces, once
Do i++
Back to 2
As the initial value for i is 0 and not 100, the code inside the loop is never executed. If you want it to go from 0 to 99, it should be for ( i = 0; i < 100; i++).
You don't actually need a for loop, though. A while loop would be better. A loop like while (true){[...]} would run until it hit a break statement. As you wouldn't have the i in that case, you could use figures.push(parseFloat(prompt("Enter a number:"))) instead (you should use parseFloat, as per what Vincent Hogendoorn said) . push adds a new value at the end of an array, so it's exactly what you need. Something like:
if (confirm === "Y"){
while (true){
figures.push(parseFloat(prompt("Enter a number:")));
confirm = prompt("Would you like to add another figure? (Y or N)").toUpperCase();
if (confirm === "N"){
break;
}
}
}
You could also change it so it doesn't ask if you want to stop if you don't have at least two values. That way you would be able to leave out that first part:
figures[0] = prompt("Enter a number:");
figures[1] = prompt("Enter a number:");
indeed your figures variable isn't defined as an array, like #James Donnely says.
Keep in mind you also fill in strings, so if you want to add up values you have to convert them to values.
you can use something like parseFloat for this.
if you don't use it, you sum up strings. 3+4 will be 34 instead of 7.
Your figures variable isn't defined as an array. Because of this figure[1] = prompt(...) never gets hit and a TypeError is thrown on var n = figures.length;.
Change:
var figures;
To:
var figures = [];
JSFiddle demo.
You can then replace the for loop you're using after if (confirm === "Y") with a recursive function:
// Push a user input number into the figures array
figures.push(prompt("Enter a number:"));
// Function to add a new number and ask if we want to add more
function addNewNumber() {
// Push a new user input number into the figures array
figures.push(prompt("Enter a number:"));
// Ask if the user wants to add another number
if (confirm("Do you want to add another number?"))
// If they do, call this function again
addNewNumber();
}
// Trigger the function for the first time
addNewNumber();
JSFiddle demo with recursion.
function StandardDeviation(numbersArr) {
//--CALCULATE AVAREGE--
var total = 0;
for(var key in numbersArr)
total += numbersArr[key];
var meanVal = total / numbersArr.length;
//--CALCULATE AVAREGE--
//--CALCULATE STANDARD DEVIATION--
var SDprep = 0;
for(var key in numbersArr)
SDprep += Math.pow((parseFloat(numbersArr[key]) - meanVal),2);
var SDresult = Math.sqrt(SDprep/numbersArr.length);
//--CALCULATE STANDARD DEVIATION--
alert(SDresult);
}
var numbersArr = [10, 11, 12, 13, 14];
StandardDeviation(numbersArr);

find the mean of an array of 1000 random integers javascript

I am having trouble with calculating the mean value of an array of 1000 random numbers. The array holds 1000 random number between 1 and 30.
I also want to be able to count how many of each number occurred in the array and print the amount of each number in a frequency distribution table.
<script type = "text/javascript">
var arr = [];
function getRandom( num ){
return Math.round(Math.random() * num)+1;
}
for (var i = 0; i < 1000; i++) {
arr.push(getRandom( 30 ));
}
document.write(arr);
document.write("<br/>");
for (var i = 0; i <= 1000; i++){
sum += parseInt(arr[i]);
}
var mean = sum/arr.length;
document.write("The sum of all the elements is: " + sum + " The mean is: " + mean);
</script>
You don't have to run the cycle twice. Do everything on the fly:
var distrTable = {};
for (var i = 0; i < 1000; i++) {
var rnd = getRandom(30);
sum += rnd;
arr.push(rnd);
if (!distrTable[rnd]) {
distrTable[rnd] = 0;
}
distrTable[rnd]++;
}
Now the variables contain the following information:
arr - all random numbers.
distrTable - each random number with frequency.
sum - the sum of all random numbers.
jsFiddle example
By the way, if you're wondering why your code is not working... Here are the reasons:
First of define the variable sum. Before the loop just put sum = 0;
Second of all, while the array is long 1000 items, in the second for you loop for 1001 times. The declaration should be as follows:
for (var i = 0; i < 1000; i++) // not i <= 1000;
Then the code should work.
The trivial error in your code is that in your second loop you are running up to element 1001 instead of element 1000.
Since that element is undefined, it causes a sum of NaN and the mean, likewise.
To fix, change the <= 1000 to just < 1000
You should also remove the parseInt call - that's only necessary if your input values are strings, but your array already contains numbers.
Beware when you generate random numbers like this:
function getRandom( num ){
return Math.round(Math.random() * num)+1;
}
... this code can generate numbers from 1 to 31! It's because of the Math.round -- if Math.random() generates 0.99, 0.99 * 30 will equal 29.7, that will be rounded to 30, and then 1 will be added!
The solution is to replace Math.round with Math.floor.

JavaScript: how to stop a random number from appearing twice

How can you, in using a random number generator, stop a number from appearing if it has already appeared once?
Here is the current code:
var random = Math.ceil(Math.random() * 24);
But the numbers appear more than once.
You can use an array of possible values ( I think in your case it will be 24 ) :
var values = [];
for (var i = 1; i <= 24; ++i){
values.push(i);
}
When you want to pick a random number you just do:
var random = values.splice(Math.random()*values.length,1)[0];
If you know how many numbers you want then it's easy, first create an array:
var arr = [];
for (var i = 0; i <= 24; i++) arr.push(i);
Then you can shuffle it with this little function:
function shuffle(arr) {
return arr.map(function(val, i) {
return [Math.random(), i];
}).sort().map(function(val) {
return val[1];
});
}
And use it like so:
console.log(shuffle(arr)); //=> [2,10,15..] random array from 0 to 24
You can always use an hashtable and before using the new number, check if it is in there or not. That would work for bigger numbers. Now for 24, you can always shuffle an array.
You could put the numbers you generate in an array and then check against that. If the value is found, try again:
var RandomNumber = (function()
{
// Store used numbers here.
var _used = [];
return {
get: function()
{
var random = Math.ceil(Math.random() * 24);
for(var i = 0; i < _used.length; i++)
{
if(_used[i] === random)
{
// Do something here to prevent stack overflow occuring.
// For example, you could just reset the _used list when you
// hit a length of 24, or return something representing that.
return this.get();
}
}
_used.push(random);
return random;
}
}
})();
You can test being able to get all unique values like so:
for(var i = 0; i < 24; i++)
{
console.log( RandomNumber.get() );
}
The only issue currently is that you will get a stack overflow error if you try and get a random number more times than the amount of possible numbers you can get (in this case 24).

Categories