I'd like my output has 6 random numbers but my code only displays 4 numbers, and the numbers are the same.
var x = Math.floor(Math.random()*41);
for(var i=0; i<7; i++){
document.write(x + "</br>");
i++;
}
Could someone please help?
You need to move .random() inside your loop. Also, remove i++ from your loop, because that is already done by for().
Demo:
Script:
for( var i=0; i<6; i++ ){
var x = Math.floor(Math.random()*41);
document.write(x + "</br>");
}
You don't need the i++ inside the form, it's 6 not 7 and you need to calculate the random numbers inside the for loop.
for(var i=0; i<6; i++){
var x = Math.floor(Math.random()*41);
document.write(x + "</br>");
}
Why are you incrementing i twice? Also, if all the numbers are going to be random, you need to execute the Math function inside of the loop.
for(var i = 0; i < 6; i++) {
document.write(Math.floor(Math.random()*41) + "<br>");
}
You don't need to increment your counter twice. Also, the random() needs to be inside your loop.
var x = Math.floor(Math.random()*41);
for(var i=0; i<6; i++){
document.write(x + "</br>");
x = Math.floor(Math.random()*41);
}
you are assigning the var x with a random number before starting the loop, it remains same throughout the execution
try placing it inside the loop,also about incrementing the i, you are doing it in the for loop already so you do not need to do it inside the loop
var x = Math.floor(Math.random()*41);//place it inside the loop
for(var i=0; i<7; i++){
document.write(x + "</br>");
i++;//remove this
}
Related
I want to display a block of numbers of the input with input times
basic web pages
var j= "";
var n=prompt("Enter the size of the box");
for(var i=1; i<=n; i++)
{
document.write(i +"<br>");
}
if the given input is 5 the output should be as follows:
o/p
12345
12345
12345
12345
12345
prompt() method only returns a string. So, first you need to convert the string to a number using parseInt()
var num = prompt('Enter the size of the box: ');
num = parseInt(num);
for(let i = 1; i <= num; i++) {
for(let j = 1; j <= num; j++) {
document.write(j+' ');
}
document.write('</br>');
}
var j= "";
var n=prompt("Enter the size of the box");
var x = [ ...Array(n*1+1).keys() ].join('').substring(1);
for(var i=1; i<=n; i++)
{
document.write(x +"<br>");
}
This will solve your problem .
var j= "";
var n=prompt("Enter the size of the box");
for(var i=1; i<=n; i++)
{
for(var j = 1; j<=n ; j++ ){
document.write(j);
}
document.write("<br>");
}
I guess you are new to programming and this example wants to teach you nested loops.
You'll have to split up your task to the smallest possible steps and think about what is happening in your loops. The best way is to work "inside-out".
So first you think about what is a single step you want to do: printing a number.
After that you'll think about how often you want to print it in a row.
After that you'll think about how you want to separate the rows.
In the final step you'll think about how many rows you want to print.
The code above will work for you now, but if you don't think about it, you'll fail at the next similar problem.
Give a man a fish and you'll feed him for a day. Teach a man to fish, and you'll feed him for a lifetime! ;-)
I’m trying to convert text to binary but when my loop runs, it never ends. I cannot figure out why that is so.
Is there a better way to do this?
handleBinaryChange: function(e){
var friendsCopy = this.state.friendsArray;
for (var i = 0; i < friendsCopy.length; i++) {
for (var j = 0; j < friendsCopy[i].friendsName.length; j++) {
console.log(friendsCopy[i].friendsName += friendsCopy[i].friendsName[j].charCodeAt(0).toString(2) + " ");
}//End of 'j' for
}//End of 'i' for
this.setState({
friendsArray: friendsCopy //make friendsCopy contain the new value for friendsName
});
}
}
By using += in friendsCopy[i].friendsName += you are modifying friendsCopy[i].friendsName. On each iteration it gets longer, so it never stops.
If you only want to output it to the console change it to
friendsCopy[i].friendsName + friendsCopy[i].friendsName[j].charCodeAt(0).toString(2) + " ");
You are increasing friendsName value with +=
in each loop iteration
simple solution: use an auxiliary test parameter that stores the starting value:
this way, test value is fixed throughout the entire loop
e.g.:
for(var i=0; i<friendsCopy.length; i++){
var test = friendsCopy[i].friendsName.length; // added this param
for(var j=0; j<test; j++){ // used it here
console.log(friendsCopy[i].friendsName += friendsCopy[i].friendsName[j].charCodeAt(0).toString(2) + " ");
}//End of 'j' for
}//End of 'i' for
You are using the length of friendsName in your break condition, but you keep increasing the length of the string inside the loop:
for(var j=0; j<friendsCopy[i].friendsName.length; j++){
console.log(friendsCopy[i].friendsName += friendsCopy[i].friendsName[j].charCodeAt(0).toString(2) + " ");
}
Note that friendsCopy[i].friendsName.length will be executed for each iteration of the loop, not only once at the beginning.
I am trying to do an activity in my uni work and am having trouble getting the for loop to work. I have done the first stage using a while loop but I am getting stuck on the second stage.
My while loop -
var i=1;
while (i<=32) {
i = i*2;
document.writeln(+i +' ');
}
alert ('Wah-Lah!')
Your second part could be like that:
var sum = 0;
var k=1;
// 65 is too big !
for (i=1; i<30; i++)
{
sum += k;
k*=2;
document.writeln(+k +' ');
alert('Sum of all numbers = '+ sum);
document.writeln(' = ' + sum);
}
If you want to output the sum only, then you can just put the two lines, alert and doc.write outside the for loop
var sum = 0;
for (i=1; i<=64; i*=2) {
sum += i;
document.writeln(i);
}
document.writeln('sum: ' + sum);
You can modify your code the following way :
var sum=0;
for (i=1; i<65; i=i*2) {
sum += i;
document.writeln('' + i); //Displays values 1 2 4 8...
}
//Display Sum outside loop
document.writeln(' = ' + sum);
I'm not sure if I understand you well but in your for loop you are increasing you counter by 1, so in output you will get 1,2,3...,64. If you want to get output as 1,2,4,8... change your step argument to: i = i + 2. Finally your for loop should looks like:
for(i = 1; i < 65; i + 2)
var array = [];
var list = "<ul>";
for(var i = 0; i < parseInt(Math.random() * 20); i++){
array[i] = [parseInt(Math.random() * 10)];
list += "<li>" + array[i];
for(var j = 0; j < array[i].length; j++){
array[i][j] += parseInt(Math.random() * 10);
list += " " + array[i][j];
}
list += "</li>"
}
list += "</ul>"
document.getElementById("print").innerHTML += list;
<div id="print">
</div>
My goal is to create a jagged array.
I want to initialize an array and create random sets of array inside the initial array that also contains random numbers.
The output I'm looking for is something like this:
4 2 5
1 10 3 4 5 6
7 1 4 8
6 9
1
4 6 7
..but when I run the code I have so far I only receive two columns of random integers every time I run the program. How can I fix this?
When you do:
array[i] = [parseInt(Math.random() * 10)];
array[0] is assigned an array of length 1 and containing a single digit integer, assume it's 5 so that array looks like [[5]]. Then later:
for(var j = 0; j < array[i].length; j++){
Note here array[i].length is 1.
array[i][j] += parseInt(Math.random() * 10);
So this adds a number to the value at array[0][0], which was 5 and now might be say 8, so you have an array like:
[[8]]
Since the length of array is still only 1, and j is incremented to 1 also, the loop ends.
Note that if you use:
array[i][j].push(parseInt(Math.random() * 10));
you'll have an infinite loop since you will increment the length of the array at the same rate you increment j and it will always be j + 1. You need to set j to a static value, e.g.
for (var j=0, jLimt = parseInt(Math.random()*10); j<jLimt; j++)
This code should generate the type of array you are looking for.
function createRandomArray(){
//Create empty Array
var out=[];
//random element count for outer array
var outerLength=parseInt(Math.random()*20)+1;
//fill outer array with random arrays
for(var i=0;i<outerLength;i++){
//inner element count and initialisation
var innerLength=parseInt(Math.random()*10)+1;
var inner=[];
for(var j=0;j<innerLength;j++){
//fill the inner array with random numbers
inner.push(parseInt(Math.random()*10)+1);
}
//add the inner array to the outer array
out.push(inner);
}
return out;
}
Edit
I will try to explain why your code does not work
for(var i = 0; i < parseInt(Math.random() * 20); i++){
In every loop iteration the Math.random part is executed again. You should save it in an extra variable.
array[i] = [parseInt(Math.random() * 10)];
You initialize the sub-array with one random number
for(var j = 0; j < array[i].length; j++){
And iterate over this sub array(which has only one element). So this loop is only called once per sub-array. Because of this every Array has exactly 2 elements
I think you are running into trouble because your recalculating a random value every iteration of the for loop.
It's even easier. One thing I noticed is your code is doing too much. It's creating random arrays, creating a random array of random arrays, creating HTML, string concatenating the HTML, and mutating the DOM. That's a lot for one conceptual function to do. How about breaking up the logic into single responsibility functions and compose them together:
function randomValue(offset) {
return Math.floor(Math.random() * (offset || 10));
}
function randomArray(size, valueFn) {
var i, arr = [];
size = randomValue(size || 20) + 1;
for (i = 0; i < size; i++) {
arr.push(valueFn());
}
return arr;
}
function randomJaggedArray(size, offset) {
return randomArray(size, function() {
return randomArray(size, function() {
return randomValue(offset);
});
});
}
function toHTML(arr) {
var html = '<ul>';
html += arr.map(function(value) {
var li = '<li>';
if (typeof value === 'number') {
li += '' + value;
} else {
li += value.join(' ');
}
li += '</li>';
return li;
}).join('');
html += '</ul>';
return html;
}
document.getElementById('print').innerHTML = toHTML(randomJaggedArray(20, 10));
<div id="print"></div>
i have two simple regular for loops.
for (var i=0; i<images.xAxis.length; i++){
for (var x=0; x<images.yAxis.length; x++){
//return number from 0 to 9
imgNumber = images.xAxis.length*i+x;
addImage(imgNumber);
}
}
Well it is not returning number from 0 to 9.
instead it returning :
1
2
3
-
2
4
6
-
3
6
9
Assuming that i don't want to use helper variable like:
idx+=1;
i want to use x and i in some math expression.
Thanks!
What you are basically trying to do with those nested loops is, how to convert a number in base 3 to a number in base 10. The way to do it is:
for (var i=0; i<3; i++){
for (var x=0; x<3; x++){
//return number from 0 to 9
addImage(3*i+x);
}
}
EDIT
With your edit, the code becomes
for (var x=0; x<images.xAxis.length; x++){
for (var y=0; y<images.yAxis.length; y++){
//return number from 0 to 9
imgNumber = images.xAxis.length*i+x;
addImage(imgNumber);
}
}
You can try using:-
for (var i=0; i<3; i++){
for (var x=0; x<3; x++){
imgNumber = i * 3 + x;
addImage(imgNumber);
}
}