Javascript - adding random numbers generated in for loop - javascript

I'm trying to find the sum of all variables, dieRoll outputted in for loop after the images are displayed. Thanks in advance.
var out = '';
for(var i = 0; i < userSelect; i++){
dieRoll = Math.floor((Math.random() * 6) + 1);
out += "<img src=\"_images/die" + dieRoll + ".jpg\">";
}
return out;

var sum = 0;
var out = '';
for(var i = 0; i < userSelect; i++){
dieRoll = Math.floor((Math.random() * 6) + 1);
sum += dieRoll;
out += "<img src=\"_images/die" + dieRoll + ".jpg\">";
}
Based on the return statement in your example, your function is currently returning just HTML text. You may wish to refactor the code so that one function returns an array of integer die rolls, another function returns the sum of the array, and another function returns the desired HTML text.

Related

How do I make sure there are no repeated numbers when using random()?

I have this code that displays 100 random numbers, then adds a break for every 10 numbers. How would I ensure that these 100 random numbers do not have repeats? I know maybe there's something to do with more if statements?
Thanks,
J
<!DOCTYPE html>
<html>
<h1><font color = "blue">Random Numbers and Breaks (for loops)</font></h1>
<p><font color="red">This will display 100 numbers and insert a break in 10-number intervals:</font></p>
<div id="demo"> </div>
<body>
<script>
var text= '';
var i = 0;
var counter = 0;
for (; i < 100; i++ , counter++) {
var numbers = Math.floor((Math.random() * 100) + 1);
text += numbers + " " + "<br>";
if (i % 10 === 9) {
text += "<br>";
}
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
How would I ensure that these 100 random numbers do not have repeats?
You need to save returned values (by random number generator) so that same value is not returned again.
function randomNumberGenerator( min, max )
{
var returnedValues = [];
return function()
{
var num = null;
while( num == null || returnedValues.indexOf( num ) != -1 )
{
num = Math.floor((Math.random() * (max-min)) + min);
}
return num;
}
}
Now you can call this n number of times ( n < (max - min) )
var nRandomNumbers = 10;
var randomNumArr = [];
var ran1 = randomNumberGenerator(1,100); //initialize the randomNumberGenerator
for( var counter = 0; counter < nRandomNumbers; counter++ )
{
randomNumArr.push( ran1() );
}
You can use Fischer yates algorithm for shuffling an array and shuffle an array from 1 to 100.
// Returns num size random array from 1 to num
function getRandomArray(num) {
const arr = [];
for (let i = 0; i < num; i++) {
arr.push(i+1);
}
let temp, rIndex;
// swap random element
for (i = num - 1; i >= 0; i--) {
rIndex = Math.floor(Math.random()*i);
temp = arr[i];
arr[i] = arr[rIndex];
arr[rIndex] = temp;
}
return arr;
}
let text = '';
getRandomArray(100).forEach(function(item, index){
text += item + " <br />";
text += (index + 1)%10 === 0 ? "<br />" : "";
});
document.getElementById("demo").innerHTML = text;
I think this is what you want, if you don't know what something does, please research it. Do not simply copy and paste.
var text= '';
var i = 0;
var counter = 0;
var nums = []; // Created array
var numbers;
for (; i < 100; i++ , counter++) {
numbers = Math.floor((Math.random() * 100) + 1);
while (nums.includes(numbers))
numbers = Math.floor((Math.random() * 100) + 1);
// While nums array includes numbers, reroll.
nums.push(numbers); // Push the number to the array
text += numbers + " " + "<br>";
if (i % 10 === 9) text += "<br>"
// If the rightmost digit is a 9, add the br tag
}
document.getElementById("demo").innerHTML = text;
<!DOCTYPE html>
<html>
<h1><font color = "blue">Random Numbers and Breaks (for loops)</font></h1>
<p><font color="red">This will display 100 numbers and insert a break in 10-number intervals:</font></p>
<div id="demo"> </div>
<body>
</body>
</html>

All generated random value is same

This is the code that I wrote, I dont know why all the 50 rgbColor generate the same value even when I wrote the random function in randomRGBValue.
var html = '';
var valueArr = [];
var rgbColor;
function randomValue() {
for (var i = 0; i < 3; i += 1) {
valueArr.push(Math.floor(Math.random() * 256 ));
}
return valueArr;
}
function randomRGB() {
randomValue();
var color;
color = 'rgb(';
color += valueArr[0] + ',';
color += valueArr[1] + ',';
color += valueArr[2] + ')';
return color;
}
for (var i = 0; i < 50; i += 1) {
rgbColor = randomRGB();
html += '<div style="background-color:' + rgbColor + '"></div>';
}
document.write(html);
To ease understanding of my poor written code,
-> randomValue function is for generating random value from 1 to 255(3 sets) and is pushed into valueArr. valueArr is returned.
Example valueArr = (value1, value2, value3)
-> randomRGB function calls randomValue function and plugs in valueArr value into the color array.
Your problem is that you never reset your valueArr - you keep making it bigger and bigger. But in your randomRGB() function, you always access the first three elements of the array.
You can fix this by just adding var valueArr = [] inside of your randomValue() function and you should be fine.
hi you can shorten it like this
function randomRGB() {
return 'rgb(' + [
Math.random() * 256 | 0,
Math.random() * 256 | 0,
Math.random() * 256 | 0
].join(',') + ')';
}
var html = '';
for (var i = 0; i < 50; i++) {
html += '<div style="background-color:' + randomRGB() + '"></div>';
}
console.log(html);
Because valueArr is defined globally, it is not reset to [] each time randomValue() is called and the next three values are just pushed to the end of valueArr (not at all modifying the first three values).
As a result, when randomRGB() constructs its color string, it looks at the first three values in valueArr (which are always the same since the newly generated random values are being appended to the end of the array).
Two solutions:
(1) make valueArr a local variable defined inside randomValue()
function randomValue() {
var valueArr = [];
...
}
(2) keep valueArr where it is, but reset it to [] in randomValue()
var valueArr;
...
function randomValue() {
valueArr = [];
...
}
Hope this helps!
Move globally declared variables valueArr, rgbColor into the respective functions Check the working code here
Demo: https://codepen.io/karthikdivi/pen/ZJJeoa?editors=0010
var html = '';
//var valueArr = [];
//var rgbColor;
function randomValue() {
var valueArr = [];
for (var i = 0; i < 3; i += 1) {
valueArr.push(Math.floor(Math.random() * 256 ));
}
return valueArr;
}
function randomRGB() {
var valueArr = randomValue();
var color;
color = 'rgb(';
color += valueArr[0] + ',';
color += valueArr[1] + ',';
color += valueArr[2] + ')';
return color;
}
for (var i = 0; i < 50; i += 1) {
var rgbColor = randomRGB();
html += '<div style="background-color:' + rgbColor + '">foo</div>';
}
document.write(html);
Hex color can be a bit easier:
for (var i = 0; i < 10; i += 1)
document.write('<div style="background-color:#' +
('00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6) + '">.</div>');

Nested Loop to add numbers

I am currently trying to create a double nested loop that adds a number to itself, given the number of instances you want it to be added by.
So when you input something in the Number, for example "5" and you input "3" for the number of instances, then the following would be printed:
5=5
5+5=10
5+5+5=15
More information on my JsFiddle
<div>
<h2>Loop</h2>
Number
<input type='text' id='tbox'>
<br>
Number of Instances
<input type='text' id='theNumber'>
<button onclick=doubleLoop;>
Add Numbers.
</button>
</div>
<div id="content">
</div>
<script>
function doubleLoop(){
var theText = document.getElementById('tbox').value;
var theNumber = document.getElementById('theNumber').value;
var content = document.getElementById('content');
content.innerHTML = '';
for (var i = 0; i < theNumber; i++) {
content.innerHTML = content.innerHTML + (i + 1) + ')';
//start of the second part of the Double Loop
for (var j = 0; j < (i + 1); j++){
if (i === 0){
content.innerHTML = content.innerHTML + theText + '=' + theText + '<br>';
} else if (i > 0) {
content.innerHTML = content.innerHTML + theText.repeat(j) + '=' + (theText * (i+1));
}
}
}
}
</script>
Here you go
https://jsfiddle.net/mkarajohn/qkn2ef4L/
function createString(number, times) {
/*
* We will create each side of the equation separately and we will concatenate them at the end
*/
var leftSide = '',
rightSide = '',
i;
for (i = 1; i <= times; i++) {
leftSide += number.toString();
if ((times > 1) && (i < times)) {
leftSide += '+';
}
}
rightSide = number * times
return (leftSide + '=' + rightSide);
}
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
output += createString(theText, i);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
If there is something that is not clear feel free to ask.
EDIT: If you are hell bent on doing it with two nested loops, here's how it would go:
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
var leftSide = '',
rightSide = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
leftSide = '';
for (var j = 1; j <= i; j++) {
leftSide += theText.toString();
if ((i > 1) && (j < i)) {
leftSide += '+';
}
}
rightSide = theText * i;
output += (leftSide + '=' + rightSide);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
First things first: You're naming your variables very poorly, it's really difficult to understand what you're trying to do, specially when you don't say what you want directly in the question. doubleLoop says how your function works but not what it does. getMultiplicationProcess would have been a better name. Also, you could be passing the values as arguments and just returning the result, it would look A LOT better.
Anyway, I couldn't figure how you were trying to achieve this. I've renamed your variables and did everything my way. Never name a variable theNumber or theText because doing so says nothing about what information it holds. You could have named them firstInput and secondInput but even that way it would not be clear.
Here's the code, scroll down for explanation:
var submit = document.getElementById("submit"),
firstInput = document.getElementById("tbox"),
secondInput = document.getElementById("theNumber"),
answerField = document.getElementById("content");
submit.addEventListener("click", function () {
answerField.innerHTML = getMultiplicationProcess(Number(firstInput.value), Number(secondInput.value), "<br/>");
});
function getMultiplicationProcess(multiplicand, multiplier, lineBreak) {
var result = "";
for (var i = 0; i < multiplier; ++i) {
for (var j = 0; j < i + 1; ++j) {
if (i === j) {
result += multiplicand + " = " + (multiplicand * (i + 1));
} else result += multiplicand + " + ";
}
result += lineBreak || "\n";
}
return result;
}
JSFiddle
Explanation:
The outer for loop runs as many times as the second input, or multiplier. So if you input 5 and 3 respectively this loop will run three times. It represents each line of the resulting string.
The inner loop runs as many times as the current iteration number of the outer loop more one. So for our example inputs it will run like this:
0: 1; 1: 2; 2: 3;
I use it to place the multiplicand multiple times in the current line.
The first line will contain a single 5 (not including the answer for this multiplication) so j is i + 1 which is 1 because during the first iteration from the outer loop i equals 0:
5 = 5
The second line contains 2 5s and i is 1 because we're in the second iteration for the outer loop, so j = i + 1 = 2 which is how many fives we'll place in the string:
5 + 5 = 10
if it's the last iteration of the inner loop instead of adding "5 + " to the resulting string it places "5 = (i + 1) * multiplier" which will be the result for the current line. Then the inner loop ends, the outer loop adds a line break and restarts the process for the next line.

Javascript for loop sums

I want to find the sums of a set of numbers from a for loop
I currently have
var num = "";
for(var i = 1; i < 11; i +=1){
num = num + i;
}
console.log(num)
which gives me 12345678910 in the JS console
I want to produce 1+2+3+4+5+6+7+8+9+10=SUM
I have tried adding a "+" string:
num = num + i + "+";
but it gives me 1+2+3+4+5+6+7+8+9+10+
My question is how to add the "+" and "=" into the code and get the sum.
If you want the + to display AND the actual sum, then do this
var realSum = 0;
var num = "1";
for(var i = 2; i < 11; i +=1){
realSum = realSum + i;
num = num + "+" + i;
}
num = num + "=" + realSum;
Try this : http://jsfiddle.net/kx9b7qu7/2
Using Eval
var num = [];
for(var i = 1; i < 11; i +=1){
num.push(i)
}
var equation = num.join('+');
var sum = eval(equation);
console.log('Method 1: ',equation + '=' + sum)
Without using Eval
var num = [];
var sum = 0;
for(var i = 1; i < 11; i +=1){
num.push(i)
sum += i
}
var equation = num.join('+');
console.log('Method 2: ',equation + '=' + sum)
Make an util out of it for later use ;) There are also other ways that make use of functional approach (reduce, map) and things that aren't widely supported yet (generators, array comprehensions).
Here are some example functions for consideration and tweaking:
// kind of usual
var sumRange = function (from, to, step) {
var i,
sum = from,
str = from;
for (i = from + step; i <= to; i += step) {
sum += i;
str += '+' + i;
};
str += '=' + sum;
return str;
};
// sum of elements in arithmetic progression
var sumRangeAP = function (from, to, step) {
var i,
n,
str = from;
n = ((to - from) / step) + 1;
for (i = from + step; i <= to; i += step) {
str += '+' + i;
};
str += '=' + ((from + to) / 2) * n;
return str;
};
// memory efficiency (not creating hell a lot of strings) together with some functional stuff
// on the other hand it looks like assignment operators (+, +=) win with .join in terms of speed sometimes
// in many cases, I think, you may not give a shit about whether you use this or that
var sumRangeME = function (from, to, step) {
var i,
sum = from,
str = [from];
for (i = from + step; i <= to; i += step) {
str.push(i);
};
return str.join('+') + '=' + str.reduce(function (prevVal, curVal) { return prevVal + curVal; });
};
console.log(sumRange(0,20,1));
console.log(sumRangeAP(0,20,1));
console.log(sumRangeME(0,20,1));
console.log(sumRange(1,21,1));
console.log(sumRangeAP(1,21,1));
console.log(sumRangeME(1,21,1));
console.log(sumRange(7,36,1));
console.log(sumRangeAP(7,36,1));
console.log(sumRangeME(7,36,1));
In javascript + can also concatenate a string, if that's what seems best - it thinks you are putting two strings together so it concatenates them. Make num start as 0 instead, that should fix it.
Instead of var num="" try with var num=0, because this way the operator + is used as string concatenation. num=0 will do the job.
EDIT: I thought you wanted to see the "math" equation try the following:
var numbers = 0;
for (var i = 1; i < 11; i += 1){
numbers += i;
}
console.log(numbers);
Try this:
var numbers = [];
for (var i = 1; i < 11; i += 1){
numbers.push(i);
}
var string = numbers.join("+");
string += "=" + eval(numbers.join("+"));
console.log(string);
If you're really trying to concatenate then
num = num + "+" + i;

Javascript function to determine if array element already exists [duplicate]

This question already has answers here:
Determine whether an array contains a value [duplicate]
(18 answers)
Closed 7 years ago.
So I'm writing some code that will generate a random number between 1 and 20 ten times, add it to an array, then display it in a table. If a number occurs more than once, it will display red in the table. I'm having trouble creating the function that would evaluate the random number to determine if it is random or not and turn it red. Any help is greatly appreciated
var i;
var myarray = new Array();
document.writeln("<table>");
document.writeln("<th> Index </th>");
document.writeln("<th> Number </th>");
for (i = 1; i <= 10; i++){
//numberExists();
var min = 1;
var max = 20;
var randomnum = Math.floor(Math.random() * (max - min + 1)) + min;
var mynum = parseInt (randomnum );
myarray[i] = mynum;
document.writeln("<tr>");
document.writeln("<td>" + i + "</td>");
document.writeln("<td>" + myarray[i] + "</td>");
document.writeln("</tr>");
}
document.writeln("</table>");
//function numberExists(mynum, myarray){
// Can't figure out the code that goes here
//}
Here is how to you could test if mynum is already in myarray and change the color accordingly:
var i;
var myarray = new Array();
document.writeln("<table>");
document.writeln("<th> Index </th>");
document.writeln("<th> Number </th>");
for (i = 1; i <= 10; i++){
var min = 1;
var max = 20;
var randomnum = Math.floor(Math.random() * (max - min + 1)) + min;
var mynum = parseInt (randomnum );
var color="black";
if(myarray.indexOf(mynum) > -1){
color="red";
}
myarray[i] = mynum;
document.writeln("<tr>");
document.writeln("<td>" + i + "</td>");
document.writeln("<td><font color="+color+">" + myarray[i] + "</td>");
document.writeln("</tr>");
}
document.writeln("</table>");
EDIT: If you're looking for a pragmatic solution, use indexOf as suggested in the comments. If you're looking for the proper algorithmic way of doing it (that won't require linear lookup-time and result in an asymptotically faster algorithm, the follow my original advice below:
Store the number as the key in an object.
var myNumbers = {};
...
myNumbers[mynum] = true; // add it to the object
if (myNumbers[mynum]) {
console.log("The number has already been added");
} else {
console.log("This is a new number");
}

Categories