I'm sure this is quite a simple programming question however, I cant seem to understand it...
I'm trying to make the console.log print out numbers like this - 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 - one for each line. I thought modulo could be used to make this happen, however, I cant seem to figure out how to use it.
Here is the code:
iteration = 16;
for (var i = 0; i < iteration; i++) {
if(i == iteration%4 )
console.log(i);
}
Yes, you need a single loop.
No, you do not need the remainder operator %. This would give you
0 1 2 3 0 1 2 3 ...
But instead you could divide the actual value by 4 and take the integer value for console.log.
const iteration = 16;
for (let i = 0; i < iteration; i++) {
console.log(Math.floor(i / 4) + 1); // offset for starting with 1
}
I suggest that you use two nested for loops, one for the rows and another one for the columns.
Here's an example of how i would do it:
const columns = 4;
const rows = 4;
//if you want to just console.log each number on a different line
for (let i = 1; i <= rows; i++) {
for (let j = 1; j <= columns; j++) {
console.log(i);
}
console.log("\n");
}
//if you want to add each number to an array, and then log the array
for (let i = 1; i <= rows; i++) {
let columnsArray = [];
columnsArray.length = columns;
columnsArray.fill(i);
console.log(columnsArray);
}
//if you want to just log the numbers, you can spread the array
for (let i = 1; i <= rows; i++) {
let columnsArray = [];
columnsArray.length = columns;
columnsArray.fill(i);
console.log(...columnsArray);
}
//or you could push the arrays in another one, and get a matrix!
const matrix = [];
for (let i = 1; i <= rows; i++) {
let columnsArray = [];
columnsArray.length = columns;
columnsArray.fill(i);
matrix.push(columnsArray);
}
console.log(matrix);
It was not clear the output that you wanted, so i got a little sidetracked and made an example for the different cases that came to my mind.
Related
I wasn't sure how to properly word the title.
I have 2 indexes from a 2D array (x and y) and need to multiply them together to get the index for a second array (1D), however it's not that simple 'cause if x or y equals zero, it'll return zero regardless of the other value.
I could get around this using nested loops shown below:
int count = 0;
for( int i = 0; i < x; i++ )
{
for( int j = 0; j < y; j++ )
{
count++;
}
}
//count now equals desired value
...but that seems awfully impractical.
To me this seems like something that should be incredibly simple and I've put off asking until now, thinking that might be the case.
Let’s use the following data to create an example:
var array_2d = [[0,1,2],[3,4,5]];
var array_1d = [0, 1, 2, 3, 4, 5];
If all of your sub arrays have the same size, you can simply multiply your i index by your sub array’s length, in order to find the corresponding “row” of your 1 dimensional array. Then you can simply add the “column” index of your array.
But this would only work if you are working with width-fixed matrixes.
var sub_dimensional_array_length = 3;
for (var i = 0; i < array_2d.length; i++) {
for (var j = 0; j < array_2d[i].length; j++) {
var array_1d_index = (sub_dimensional_array_length * i) + j;
console.log(array_2d[i][j], array_1d[array_1d_index]);
}
}
In JavaScript, is there a more efficient way of calculating perfect squares working from odd numbers than this (the last perfect square stored in the array perfectSqrs is console.logged):
let n = 999,
oddNums = [],
i;
for (i = 3; i < n; i += 1) {
if (i % 2 !== 0) {
oddNums.push(i);
}
}
let oddLength = oddNums.length;
let perfectSqrs = [1],
j = 0;
while (j < oddLength - 1) {
perfectSqrs[j + 1] = perfectSqrs[j] + oddNums[j];
j += 1;
}
console.log(perfectSqrs[perfectSqrs.length - 1]);
Looks like you just want to generate an array of perfect squares? Perhaps you can do something like this:
var squares = [1];
var numSquares = 100;
for (var i=3; i<numSquares*2; i+=2) {
squares.push(squares[squares.length - 1] + i);
}
console.log(squares);
For people unclear about this algorithm, basically:
1
4 (1+3)
9 (1+3+5)
16 (1+3+5+7)
25 (1+3+5+7+9)
Perfect square is essentially the sum of odd numbers
Nothing to do with JS more with algorithms and logic. You can totally avoid the first loop and also avoid storing (memory efficiency) odd numbers. Start your second loop with 1 and iterate by incrementing by 2 instead of 1 (1,3,5,7,...).
I am trying to do a simple factorial code challenge, but with Javascript, when I try to get the index position by looping of the indexes, I get NAN. I understand that NAN is of the typeOf number, just that Javascript doesn't know which number. I don't see why that is happening in this case. Also how can I use get the index of an array by looping over them in Javascript? Thanks!
// Input = 4 Output = 24
// Input = 8 Output = 40320
var total = 0;
var factor_Array = [];
function FirstFactorial(num) {
for (var i = 1; i <= num; i++){
factor_Array.unshift(i);
// console.log(factor_Array);
}
for (var j = 0; j < factor_Array.length; j++){
// Why does this work??? But not when I use 'j' to grab the index position? Seems like BOTH ways should work
total = factor_Array[0] * factor_Array[0+1];
total = factor_Array[j] * factor_Array[j+1];
}
console.log(total);
//return num;
}
FirstFactorial(4);
Because when j = (factor_Array.length-1) it tries to access the j+1 element, which doesn't exist.
The following would work as you expect
for (var j = 0; j < (factor_Array.length-1); j++){
total = factor_Array[j] * factor_Array[j+1];
}
When you loop
for (var j = 0; j < factor_Array.length; j++){
total = factor_Array[j] * factor_Array[j+1];
}
Then then on the last iteration you will be out of the array bounds since
j = factor_Array.length - 1
and you're accessing j + 1.
Let's say you have an array of length 20. You want to access 3 equally spaced indices: 0, 9, 19.
How can you do this with any length of array and any number of sections?
I feel like there must be an elegant way of doing it, but the only way I can think of is finding the section size (var len = 20 / (3 -1)), iterating over the total number of sections (for (var i = 0; i < 3; i++) { var row = data[len * i]; }), and then subtracting one for non-zero indices.
You could try something like this (where console.log is used now you can call your array):
var amount = 3;
var total = 20;
var size = (total - 1) / (amount - 1);
for(var i = 0; i < amount; i++) {
console.log(Math.floor(size * i));
}
There isn't realy a more elegant solution.
function Deal()
{
var suffledDeck:Array;
var playerOneCards: Array;
var playerTwoCards: Array;
var first:int =0;
var second:int = 1;
suffledDeck = new Array();
playerOneCards = new Array();
playerTwoCards = new Array();
//var CardLeft:int = Deck.length;
for(var i = 0; i < Deck.length; i++)
{
Debug.Log(Deck.length);
var ranNum = Random.Range(1,Deck.length);
suffledDeck.Add(Deck[ranNum]);
Debug.Log("suffled deck: " + suffledDeck.length);
}
//var halfDeck: int = (suffledDeck.length / 2);
for(var j = 0; j <=26 ; j++)
{
Debug.Log(first);
Debug.Log(second);
playerOneCards.Add(suffledDeck[first]);
playerTwoCards.Add(suffledDeck[second]);
Debug.Log(playerOneCards[first].img);
Debug.Log(playerTwoCards[second].img);
first += 2;
second += 2;
}
}
when i begin to split the array into 2 separate arrays it begins to ignore every element except the first element. the suffleDeck[] has 52 Card objects loaded in and im trying to split the array so that each player can have there own deck.
Console window for debug purpose: http://puu.sh/2dqZm
I believe the problem is var ranNum = Random.Range(1,Deck.length).
ranNum should be generating a random index between 0 to Deck.length - 1 because array indices start at 0 (not 1).
The problem is with these logging statements:
Debug.Log(playerOneCards[first].img);
Debug.Log(playerTwoCards[second].img);
first and second are valid indexes into suffledDeck, but each player's deck only has half as many cards. Try using j as the subscript in both logging statements instead of first or second.
You should also limit your loop to j < 26, not j <= 26. As it is, you are trying to put 27 cards in each player's deck.
because:
Debug.Log(playerTwoCards[second].img);
here second value us 1 while your array contains only one item that is at zero. causing ArgumentoutofRangeException.
so try:
for(var j = 0; j <=26 ; j++)
{
Debug.Log(first);
Debug.Log(second);
playerOneCards.Add(suffledDeck[first]);
playerTwoCards.Add(suffledDeck[second]);
Debug.Log(playerOneCards[j].img);
Debug.Log(playerTwoCards[j].img);
first += 2;
second += 2;
}