I am new here, and to programming as well. Anyway, to get in topic I wrote the following program with the purpose of generating a 2 dimensional array in JavaScript, and then displaying its elements in a table. However, in the place where the value of the i row array index was supposed to show (like 1 in first row, then 2 in the second row, etc), the number 10 shows instead. So, I'd appreciate if someone could explain what I did wrong. Here is the code:
<table border="1">
<script>
var array1 = [];
var array2 = [];
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
array2[j] = (i + 1) + "-" + (j + 1);
}
array1[i] = array2;
}
for (var i = 0; i < 10; i++) {
document.write("<tr>");
for (var j = 0; j < 10; j++) {
document.write("<td>" + array1[i][j] + "</td>");
}
document.write("</tr>");
}
</script>
</table>
You are adding the same array to array1, again and again. Instead you need to create new arrays every time.
var array1 = [];
for (var i = 0; i < 10; i++ ) {
var array2 = [];
for (var j = 0; j < 10; j++) {
array2[j] = (i+1) + "-" + (j+1);
}
array1[i]=array2;
}
But normally, this will be done with Array.prototype.push method, like this
var array1 = [];
for (var i = 0; i < 10; i++ ) {
var array2 = [];
for (var j = 0; j < 10; j++) {
array2.push((i+1) + "-" + (j+1));
}
array1.push(array2);
}
You can create new array each time after assigned array2 to array1, something like this
array2=[];
on
for (var i = 0; i < 10; i++ ) {
for (var j = 0; j < 10; j++) {
array2[j] = (i+1) + "-" + (j+1);
}
array1[i]=array2;
array2=[]; //created new array each time after array2 assigned
}
Related
const animal = "cat";
for (let i = 0; i < animal.length; i++) {
console.log(animal[i]);
for (let j = 1; j < 4; j++) {
console.log(j);
}
}
How do I output the answer going straight rather than going down.
Each console.log print in a new line
You can create a variable, assign what you want to display to it then, display it once.
Or
You can use multiple values in one console.log separateb by comma ,
const animal = "cat";
let result = ""
for (let i = 0; i < animal.length; i++) {
result += animal[i]
for (let j = 1; j < 4; j++) {
result += " " + j + " "
console.log(animal[i], j)
}
}
console.log(result)
This is my code:
// Population
var Gene = function(text){
if(text){
this.text = text;
}
};
Gene.fitness = 0;
Gene.generation = 0;
var word = new Gene('Hello');
// This is where it crashes!!
// Make elements
var genArr = [];
var population = 20;
var mutation = 0;
for(var i = 0; i < population; i++){
var gene = "";
var abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var j = 0; i < word.text.length; j++) {
var element = abc.charAt(Math.floor(Math.random() * abc.length));
gene += element;
}
genArr.push(gene);
}
// Divide them - fitness
// 1/20 - 0.05% each
var fitElements = [];
for (var i = 0; i < genArr.length; i++) {
var score = 0;
var curWord = Array.from(genArr[i]);
for (var j = 0; j < word.text.length; j++) {
if(genArr[j].substr(j, 1) == word.text.substr(j, 1)){
score += 1;
}
}
if(score > 0){
fitElements.push([genArr[i], (score * (1 / population)) ** 2]);
}
}
for (var i = 0; i < fitElements.length; i++) {
console.log('Element: ' + fitElements[i][0] + ', Score: ' + fitElements[i][1]);
}
My problem is that it crashes the page but doesn't gives errors. The idea is to create a simple word register in fitElements Array but I can't see what am I missing?
Thanks in advance.
In your code the nested for loop with variable j's end condition relies on i.
Take a the line:
// VVVV it relies on i instead of j
for (var j = 0; i < word.text.length; j++) {
var element = abc.charAt(Math.floor(Math.random() * abc.length));
gene += element;
}
The new code would look something like
for (var j = 0; j < word.text.length; j++)
var element = abc.charAt(Math.floor(Math.random() * abc.length));
gene += element;
}
The only difference in the entire sample is the i is changed to a j. Cheers!
I am have 2 arrays like [2,3] and [1000,1200,500,600,1600] .
I need to write a for loop for this like.
1.start index from 0 and end index at 2.
2.start time from 2 and end index with sum of first 2 element (2+3)= 5.
var arr = [2,3];
for(var i = 0; i<arr.length;i++)
{
//this loop runs 2 time
for(var j = 0 ; j < 2 ; j++)//for the first time
for(var j = 2 ; j < 5 ; j++)//for the second time
}
How to make this dynamic for loop? Can someone please help me code?
This would do what you want and would be extendible.
var arr = [2,3];
var sum = 0;
for(var i = 0; i<arr.length;i++)
{
sum += arr[i]
if (i === 0) {
for(var j = 0 ; j < arr[0] ; j++)
// Do first thing
}
if (i > 0) {
for(var j = arr[0] ; j < sum ; j++)
// Do second thing
}
}
Hope you are expecting this.
var arr = [2, 3];
for (var i = 0; i < arr.length; i++) {
//this loop runs 2 time
if (i == 0) {
//for the first time
for (var j = 0; j < arr[0]; j++) { }
} else if (i == 1) {
//for the second time
var totalSum = arr[0] + arr[1];
for (var j = arr[0]; j < totalSum; j++) //for the second time
{ }
}
}
If you want it to be generic, i.e. you have the array arr containing counts of elements to process, you could do it like this:
var arr = [2,3];
// k is the index into the second array, initialize to 0 here
for(var i = 0, k = 0; i < arr.length;i++)
{
//this loop runs for each element in the arr[] array
for(var j = 0 ; j < i; j++, k++) // increment k
{
// k is now the value you want:
// first time through the loop 0, 1
// second time through the loop 2, 3, 4
}
}
Another tweak would be to just keep track of the start element if it's important for j to be the value:
var arr = [2,3];
var start = 0;
for(var i = 0; i < arr.length; i++)
{
var end = start + arr[i]; // end is 2,5 in sample
for(var j = start ; j < end; j++)
{
// first time through the loop 0, 1
// second time through the loop 2, 3, 4
}
start = end; // now start at the next index, 0,2 in sample
}
Do something like this:
var k = 0;
for(var j = 0 ; j < 2 ; j++) {
k+=arr[j];
}//for the first time
for(var i = 2 ; i < k ; i++) {
//other code
}
I want to create a multidimensional array like this:
array[0][1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
array[1][21,22,23,24,25,26,27....]
array[.][....]
How can I do this in Javascript?
I have tried this:
var squares = new Array();
for(var i = 1; i <= 8; i++)
{
for(var j = 1; j <= 20; j++)
{
squares.push(i, j);
}
}
How can I accomplish this?
You can do something like this:
var squares = new Array();
for(var i = 0; i <= 8; i++)
{
squares[i] = new Array();
for(var j = (i * 20) + 1; j <= 20 * i + 20; j++)
if (squares[i] == null)
squares[i] = j;
else
squares[i].push(j);
}
Output comes like:
array[0][1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
array[1][21,22,23,24,25,26,27....]
var array = []; // Main array
var numArrays = 10, // Number of sub-arrays
numPerArray = 20; // Number of squares per sub-array
for(var i = 0; i < numArrays; i++){
var subArray = [];
// Number to start at
var start = i * numPerArray;
// Count up to start + numPerArray
for(var j = start; j < start + numPerArray; j++){
subArray.push(j);
}
// Add to main array
array.push(subArray);
}
Use modulus operand to limit the inner array's size
var limit = 80
var inner_limit = 20
var square=[]
var inner =[]
for(var i=1;i<=limit;i++){
inner.push(i)
if(i%inner_limit==0){
square.push(inner)
inner = []
}
}
You can do it with two "for" loops. In the first loop you go through the main array and for each element add the elements from the second loop.
var arrayLength = 10; // Main array length
var limit = 20; // Number of squares
var array = [];
for ( var i = 0; i < arrayLength; i++ )
{
array[i] = []; // Create subArray
for( var j = 1; j <= limit; j++ )
{
array[i].push(j);
}
}
I need to simulate rolling 3 die 50 times, storing each in an array, and displaying the results in a table. I also need to display the results of each instance added together. Ex on roll 1 for each I got 3+4+2 = 9. I have some code, but it won't display. I'm not sure what's wrong with it.
<!--
var array1 = new Array(50);
var array2 = new Array(50);
var array3 = new Array(50);
var array4 = new Array(50);
function roll()
{
var face = Math.floor( (Math.random() *6) + 1);
return face;
}
for( var i = 0; i < array.length; i++)
{
array1[i] = roll();
}
for( var i = 0; i < array.length; i++)
{
array2[i] = roll();
}
for( var i = 0; i < array.length; i++)
{
array3[i] = roll();
}
for( var i = 0; i < array.length; i++)
{
array4[i] = array1[i] + array2[i] + array3[i];
}
//Making table
document.write('<table border="1" cellspacing="1" cellpadding="5">')
//Loops through array object and writes values in appropriate table cells
for(var i = 0; i < 50; i++)
{
document.write('<tr>')
document.write('<td>' + i + '</td>');
document.write('<td>' + array1[i] + '</td>');
document.write('<td>' + array2[i] + '</td>');
document.write('<td>' + array3[i] + '</td>');
document.write('<td>' + array4[i] + '</td>');
document.write('</tr>')
}
document.write('</table>')
You have an error in for( var i = 0; i < array.length; i++) each time. replace them with for( var i = 0; i < array1.length; i++), for( var i = 0; i < array2.length; i++), for( var i = 0; i < array3.length; i++) and for( var i = 0; i < array4.length; i++)
Your array is not defined in each of the for statements. Change them accordingly:
for( var i = 0; i < array1.length; i++)
{
array1[i] = roll();
}
for( var i = 0; i < array2.length; i++)
{
array2[i] = roll();
}
for( var i = 0; i < array3.length; i++)
{
array3[i] = roll();
}
for( var i = 0; i < array4.length; i++)
{
array4[i] = array1[i] + array2[i] + array3[i];
}
Also, you're missing a bunch of semicolons in your code. Here's a working JSFiddle of your implementation.
Reading your browser's developer tool's console will have helped you notice the error in question.
Here's another way to possibly implement it: JSFiddle
I had fun with this, and made a more generalized version for many dice: JSFiddle