How to generate random number each time - javascript

Does anyone know how do i generate a new random number so i can store them into different variables? (into temp1 and temp2) I want the program to rerun the "randomnumber" function each time for each new variable so i can store the new random value into them.
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function main()
{
totalscore()
leaderboard()
}
function randomnumber()
{
var randomnumber;
randomnumber = Math.random()*3;
return(Math.floor(randomnumber+0.2));
}
function totalscore()
{
var n;
var p;
var total;
var temp1;
var temp2;
var score;
score = 0;
total=0
for (n=0; n<10; n=n+1)
{
number = randomnumber();
if (number == 0)
{
score =score+0;
}
else if (number == 2)
{
score =score+2;
}
else if (number == 3)
{
score =score+3;
}
total=total+score;
}
temp1= total
temp2= total
document.write(total)
document.write(total)
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<SCRIPT LANGUAGE = "Javascript"> main() </SCRIPT>
<INPUT NAME = "dobutton" TYPE = "button" value = "Start game" on Click = "game()">
<INPUT NAME = "dobutton" TYPE = "button" value = "Leaderboard" on Click = "leader()">
</BODY>
</HTML>

I think I know what you are asking and I'll post working code below as well as an explanation of why you are getting the same random number.
You have a for loop is generating the score and and returning a value that you are storing into total. The problem is you are assigning that number to both temp1 AND temp 2, so they are now the same number, then you are writing both numbers to the page. What you need to do is have 2 different calculations. the below code will fix it and give you 2 different numbers for you totals...
function totalscore()
{
var total1 = 0;
var total2 = 0;
for (var n=0; n<10; n++)
{
total1 = total1 + randomnumber();
total2 = total2 + randomnumber();
}
document.write(total1);
document.write(total2);
}
Now I was a little confused at your code because the score is compounding on itself every time it recalculates in the for loop. (ie if the first 5 scores were 1, 2, 2, 1, 3, then the total score would be 24, and not the expected 9. If that was intentional, the put in this code instead.
function totalscore()
{
var total1 = 0;
var total2 = 0;
var score1 = 0;
var score2 = 0;
for (var n=0; n<10; n++)
{
score1 = score1 + randomnumber();
total1 = total1 + score1;
score2 = score2 + randomnumber();
total2 = total2 + score2;
}
document.write(total1);
document.write(total2);
}
Good luck with your project and learning coding!

Issues I am noticing
No semicolons behind most statements
You are returning Math.floor on randomnumber + 0.2, which makes + 0.2 do nothing.
You are calling onclick='game()' on button click, but there is no game(), but maybe that's in code we can't see.
You are setting both temp1 and temp2 = total, and using document.write on total twice
Now, the question is how to generate a random number. You are doing that correctly, although you could simplify it and use Math.floor(Math.random()*3) or return Math.floor(Math.random()*3). Of course, you can switch out 3 and replace it now with whatever cap you wish.

Related

Sorting and Median with Arrays in Javascript

I have been working on this code, and the goal is to sort out the numbers in the array, and then find the median. My median isn't outputting correctly, and when I try to just see what is in array[0], it never has the right value. I'm not exactly sure where I messed up.
Code:
var array = [];
window.onload = function (){
var answer = '';
var median = 0;
for (var i = 0; i < 8; i++) {
var rand = Math.floor(Math.random() * 101);
array.push(rand);
array.sort(function(a, b){return a-b});
answer = answer + array[i] + " ";
}
median = ((array[3] + array[4]) /2);
document.getElementById("result").innerHTML = answer + "<br />" + median;
}
I would suggest first moving your loops ending. Currently you are sorting every single time you add a new number to the array. This means two things : you are wasting computation power on something you should only do once and when you 'log' your result in the line answer = answer + array[i] + " "; its constantly changing since the order is changing. Your functions logic is correct so by making the change below you should get the result you want.
var array = [];
window.onload = function (){
var answer = '';
var median = 0;
//Loop is simplified to just push a random value
for (var i = 0; i < 8; i++) {
array.push(Math.floor(Math.random() * 101));
}
//Sort is outside of the loop;
array.sort(function(a, b){return a-b});
//Median is outside of the loop
median = ((array[3] + array[4]) /2);
//answer is outside of the loop (if you don't know reduce look at the link below)
answer = array.reduce( function ( answer , value ) {
return answer + ',' + value;
} );
// put into the dom
document.getElementById("result").innerHTML = answer + "<br />" + median;
}
If you need help with this feel free to message me, also checkout the documentation for reduce HERE.
Using purely SO posts, I came up with a solution.
Strategy
Shuffle
At first, the partial expression (Math.floor(Math.random() * 101)) came up with duplicates, that's weaksauce. Fisher-Yates (aka Knuth) Shuffle has an excellent algorithm.
Your var answer and reduce expression is now combined and out of the loop as per #hyphnKnight explained. There's no need to break it down any further because reduce return is everything you need to display a sorted array. I also used unshift instead of push, I read that it's faster to use the front of the array rather than the back, but you can't tell the difference, too small of a function and all.
Snippet
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>35469092</title>
</head>
<output id="result"></output>
<body>
<script>
// 1. Populate an array with the numbers 1 through 100.
var arr = [];
for(var i = 1; i <= 100; i++) {
arr.unshift(i);
}
median(arr);
function median(arr){
var median = 0;
// 2. Shuffle
var ran100 = shuffle(arr);
var ran8 = [];
for(var j = 0; j < 8; j++) {
// Take the first 8 elements of the resulting array.
ran8.unshift(ran100[j]);
}
var answer = ran8.sort(function(a, b){return a-b});
median = ((ran8[3] + ran8[4]) /2);
document.getElementById("result").innerHTML = answer + "<br />" + median;
}
function shuffle(arr) {
var curIdx = arr.length, tmpVal, randIdx;
while (0 !== curIdx) {
ranIdx = Math.floor(Math.random() * curIdx);
curIdx -= 1;
tmpVal = arr[curIdx];
arr[curIdx] = arr[ranIdx];
arr[ranIdx] = tmpVal;
}
return arr;
}
</script>
</body>
</html>

Finding average from input array with Javascript - not calculating correctly

I am trying to calculate the average of 3 values (each numbered from 1-10) that are selected by the user and then pass the results to an text input (for display as a graph).
It should be updating the new average every time one of the values is changed, but the averaging is not working correctly at all. I think that the loop is not resetting the values every time it runs- it's adding up the sum each time it runs, but not sure how to fix it.
Here is my code:
var sliders = $("#health1,#health2,#health3");
var elmt = [];
$(sliders).each(function () {
elmt.push($(this).attr('value'));
$("#health1,#health2,#health3").change(function () {
var sum = 0;
averageRisk();
});
});
function averageRisk() {
var sum = 0;
for (var i = 0; i < elmt.length; i++) {
sum += parseInt(elmt[i], 10);
}
var avg = sum / elmt.length;
document.getElementById('healthLevel').value = +avg;
elmt.push($(sliders).attr('value'));
$('#healthLevel').val(avg).trigger('change');
console.log("Sum: " + sum);
console.log("Average: " + avg);
}
Here is an example:
http://jsfiddle.net/pixelmix/783cfmnv/
Not sure but seems like a lot of extra work going. Main issue was you were building array of initial values and not getting the values each time they changed. That first .each got all the slider values and added them to elmt and continued to push new values on to after every change instead of just getting the current values every time. Did you want to accumulate all values over time?
Fiddle: http://jsfiddle.net/AtheistP3ace/783cfmnv/6/
$("#health1,#health2,#health3").on('change', function () {
averageRisk();
});
function averageRisk() {
var sum = 0;
var elmt = $("#health1,#health2,#health3");
for (var i = 0; i < elmt.length; i++) {
sum += parseInt(elmt[i].value, 10); //don't forget to add the base
}
var avg = sum / elmt.length;
document.getElementById('healthLevel').value = +avg;
$('#healthLevel').val(avg).trigger('change');
console.log("Sum: " + sum);
console.log("Average: " + avg);
}
And as pointed out if you want to ignore updating things when the sum is NaN you can do this:
function averageRisk() {
var sum = 0;
var elmt = $("#health1,#health2,#health3");
for (var i = 0; i < elmt.length; i++) {
sum += parseInt(elmt[i].value, 10); //don't forget to add the base
}
if (isNaN(sum)) {
return false;
}
var avg = sum / elmt.length;
document.getElementById('healthLevel').value = +avg;
$('#healthLevel').val(avg).trigger('change');
console.log("Sum: " + sum);
console.log("Average: " + avg);
}
The problem is that you fill the elmt array at page loading.
When user changes the values, you do not refresh the elmt array. So the array used to compute the average is always the same, empty.
You have to recover the input values each time they are modified.
function averageRisk() {
var sum = 0;
// Re make the loop for getting all inputs values
$(sliders).each(function() {
var value = parseInt($(this).val(), 10);
sum += value;
});
var avg = sum/$(sliders).length;
$('#healthLevel').val(avg);
}
Working example : http://jsfiddle.net/783cfmnv/7/
PS : You can use the css class healthInput to select your inputs. If you add later other fields, you will not have to add the new input id to your jQuery selector.
I did this work, check it .
http://jsfiddle.net/783cfmnv/10/
$("#health1,#health2,#health3").change(function() {
var val1 = +slider1.val();
var val2 = +slider2.val();
var val3 = +slider3.val();
var avg = (val1 + val2 + val3) /3;
$("#healthLevel").val(avg);
});

adding randomly generated number into array and summing them up

im currently doing an assignment where we have a certain amount of people play a game and each player have an attempt of scoring. The scores will be randomly generated from 1-3. The only problem i have is to store the randomly generated value into the array and then summing them up. This way, i can produce a leader board that say something like "congrats (player name) your total score is (total score)). Any suggestion on how to do these's would be great or better yet, any other alternatives would be appreciated as well. So far i've been using a incremental counter to generate the total score but it keeps generating the same number over and over again e.g. (2,2,2,2...) (1,1,1,1,....)
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function main()
{
randomnumber()
totalscore()
}
function randomnumber()
{
var randomnumber;
randomnumber = Math.random()*3;
return(Math.floor(randomnumber+0.5));
}
function totalscore()
{
var n;
var score = 0;
number = randomnumber();
for (n = 0 ; n < 11 ; ++n)
{
if (number == 0)
{
score = score + 0;
}
else if (number == 2)
{
score =score + 2;
}
else if (number == 3)
{
score =score + 3;
}
}
document.write(score)
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<SCRIPT LANGUAGE = "Javascript"> main() </SCRIPT>
<INPUT NAME = "dobutton" TYPE = "button" value = "Start game" on Click = "game()">
<INPUT NAME = "dobutton" TYPE = "button" value = "Leaderboard" on Click = "leader()">
</BODY>
</HTML>
This may help, although you should try first before posting for solutions.
Create an empty array:
var myArray = [];
Add values to array (from your randomnumber() generator):
myArray.push(randomnumber());
myArray.push(randomnumber());
myArray.push(randomnumber());
Function to sum the values of some array (this is perhaps the most primitive but faster/efficient way to do it):
var sumElements = function(someArray) {
if (someArray == null) return false;
var sum = 0;
for (var i = 0, len = someArray.length; i < len; i++) {
sum += someArray[i];
}
return sum;
}
Call sumElements to find the sum:
sumElements(myArray);
Here is the simplest way to do what you need
var randomArray = [];
var randomSum = 0;
randomArray.push(randomnumber());
randomArray.push(randomnumber());
randomArray.push(randomnumber());
for(var i=0; i<randomArray.lenth; i++){
randomSum += randomArray[i];
}

Checking random number variable against Javascript array values for match, not working

For the sake of learning (I am very much a beginner), I am trying to write a function with that will generate random numbers according to three user inputed variables. The user can input how many random numbers to generate
var count = 10;
which numbers to avoid generating (seperated by commas)
var doNotInclude = (document.getElementById("doNotIncludeInput").value).split(",");
and what the highest number possible should be
var highestNumber = 10;
In theory, if the user inputed "1,2" for the doNotInclude variable, the function should create an array containing those two numbers and then each time it generates a random number, check it against the array to see if the number it generated is one of the numbers it isn't supposed to generate.
Unfortunately, it doesn't work. It creates the array as it should which I verified via console.log(), but it will still generate the numbers it isn't supposed to. Here's the full script:
document.getElementById("button").onclick = function() {
var total = 0,
average = 0,
random = 0,
count = parseInt(document.getElementById("countInput").value),
doNotInclude = document.getElementById("doNotIncludeInput").value).split(","),
highestNumber = parseInt(document.getElementById("highestNumberInput").value);
document.getElementById("text1").innerHTML = "";
for (var i = 0; i < count; i++) {
var proceed = false;
for (random = Math.floor(((Math.random()) * (highestNumber + 1))); proceed == false;) {
if (doNotInclude.indexOf(random)===-1) {
proceed = true;
}
}
document.getElementById("text1").innerHTML = document.getElementById("text1").innerHTML + "<br />" + (i + 1) + ". " + random;
total = total + random;
if (i == (count - 1)) {
total / count;
document.getElementById("text").innerHTML = "Mean average = " + (Math.round(total / count));
}
}
}
The part that isn't working
if (doNotInclude.indexOf(random)===-1) {
proceed = true;
}
the indexOf function, is something I read about on here, but I guess I don't fully understand it. By my understanding, it should check to see if any of the array values are the same as the random variable, and if not, then return "-1" and execute my code. It doesn't seem to be doing that though. I am super confused...would love some help. Is it possible the array is storing the numbers as strings instead of integers, and that is the problem?
Your if statement doesn't work because of coercion.
===-1
The array doNotInclude contains strings, but random is an integer value, === always compares value and type both.
You should either use ==. Or have the both types same.
Try this Fiddle
HTML
Count: <input id="countInput" value="10" /><br />
Do not include: <input id="doNotIncludeInput" value="0,1,2,3,4,5" /><br />
Highest Number: <input id="highestNumberInput" value="10" /><br />
<br />
<button type="button" id="button">Click to Run!</button><br />
<br />
Results:<br />
<div id="text1"></div>
Js
document.getElementById("button").onclick = function() {
var currentCount = 0;
var randomNumbers = [];
var count = parseInt(document.getElementById("countInput").value);
var doNotIncludeInput = document.getElementById("doNotIncludeInput").value.split(",");
var highestNumberInput = parseInt(document.getElementById("highestNumberInput").value);
var resultsElement = document.getElementById("text1");
resultsElement.innerHTML = "";
while(currentCount < count) {
var random = -1;
while(random === -1){
random = Math.floor((Math.random()) * (highestNumberInput + 1));
for(var i in doNotIncludeInput) {
if(parseInt(doNotIncludeInput[i]) === random){
random = -1;
}
}
if(random !== -1){
randomNumbers.push(random);
}
}
currentCount += 1;
}
resultsElement.innerHTML = randomNumbers.join(', ');
}

Javascript - Trying count a sum from 1 to the number that user entered

I am very new to javascript, and have limited knowledge. I have just grasped the concept of hello world. At the moment, my code adds FirstNumber and SecondNumber together to give the result. I would like it to do the following:
I am trying to make a program where FirstNumber is pre-defined as 1 and SecondNumber is done by user input. The javascript should count a sum from 1 to the number that should be entered. For example, if the user entered 5, the program should count the sum from 1 to 5 (1 + 2 + 3 + 4 + 5) which will be 15. I was told to maybe use an array, although I'm not sure.
Here is my HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Sum of numbers</title>
<script type="text/javascript">
function sum()
{
var FirstNumber = 1;
var SecondNumber = document.getElementById('txtSecondNumber').value;
alert(parseInt(FirstNumber) + parseInt(SecondNumber));
}
</script>
</head>
<body>
Please enter a number:<input id="txtSecondNumber" type="text" />
<input id="btnAdd" type="button" value="Add" onclick="sum();"/>
</body>
</html>
Could someone help?
Thanks :)
What you're looking for is a for loop
for (var i = FirstNumber ;i < SecondNumber ; i++){
// do what ever you want in here
// like adding i to the total
}
For the simple case of adding sequential number you dont need to loop at all:
1+2+3+4+5+...+n = n(n+1)/2
Formula from: http://en.wikipedia.org/wiki/1_%2B_2_%2B_3_%2B_4_%2B_%E2%8B%AF
function sum() {
var num = document.getElementById('txtSecondNumber').value;
var sum = (num*(num+1))/2;
alert(sum);
}
While an array might help you with what you want, the important bit you're looking for is a for loop. You don't indicate your programming background or if JavaScript is your first language, but a for loop is a basic programming construct that has a starting condition, an ending condition, a way to change things (so something changes between start and end), and something to do while you're counting.
A simple for loop in JavaScript looks like this:
for( var i=0; i<10; i++ ){
alert( i );
}
This will pop-up an alert for each number from 0 to 9 inclusive.
In your case, you want to set your start condition to the first number, the end condition to check if you've done the last number (both of these can be variables - not just the constants as I've illustrated), and increment the number. Inside the loop, you'll want to be adding the number to a reference counter.
Try this, you want to loop through all the numbers in between the first and second number and add them to the result
var submit = document.getElementById('submit');
var input = document.getElementById('txtSecondNumber');
function sum() {
var FirstNumber = 1;
var SecondNumber = input.value;
var result = 0;
for (var i = FirstNumber; i <= SecondNumber; i++) {
result += i;
}
alert(result);
}
submit.addEventListener('click', sum);
jsFiddle - http://jsfiddle.net/et8t3bgd/
You can easily count a sum from 1 to any number with a for loop. If you will ever only sum up from 1, you do not need the FirstNumber variable. Otherwise, you can change i = 1 to i = FirstNumber.
var sum;
for (i = 1; i < SecondNumber+1; i++) {
sum += i;
}
function sum()
{
var SecondNumber = parseInt(document.getElementById('txtSecondNumber').value);
var result=(SecondNumber *(SecondNumber +1))/2;
alert(result);
}
Formula for sum to 1 to n number is n*(n+1)/2
As per Your Code
<!DOCTYPE html>
<html>
<head>
<title>Sum of numbers</title>
<script type="text/javascript">
function sum()
{
var SecondNumber = parseInt(document.getElementById('txtSecondNumber').value);
var result=(secondnumber*(secondnumber+1))/2;
alert(result);
}
</script>
</head>
<body>
Please enter a number:<input id="txtSecondNumber" type="text" />
<input id="btnAdd" type="button" value="Add" onclick="sum();"/>
</body>
</html>
DEMO
Here
function sum(n) {
var res = 0, total = 0;
while ((n--)>0) total += ++res;
return total;
}
Use a recursive program...
var num=Number(prompt("Enter a number"));
var sum=0;
for(var i=num;i!=0;i--){
sum+=i;
}
console.log(sum)
//print sum

Categories