Cannot iterate while statement - javascript

NEWB question. Be patient.
As an exercise I am trying to create a grid simply by appending to innerHTML.
I cannot get the loop to repeat beyond its first iteration. I'm sure it's something basic but I have to start somewhere.
I've tried "let" instead of "var", console.log instead of document..., hours of googling.....
var originalSize = 8;
var sizeGrid = 0;
var heightGrid = 0;
var switchChar = 2;
var switchCharTwo = 1;
var charOne = "x";
var charTwo = "#";
while (heightGrid <= originalSize){
document.getElementById("el").innerHTML+="<br>";
if (switchChar % 2 === 0){
switchCharTwo = 1;
}
else {
switchCharTwo = 2;
}
while (sizeGrid <= originalSize){
if (switchCharTwo % 2 === 0){
document.getElementById("el").innerHTML+=charOne;
}
else {
document.getElementById("el").innerHTML+=charTwo;
}
sizeGrid = sizeGrid + 1;
switchCharTwo = switchCharTwo + 1;
}
heightGrid = heightGrid + 1;
switchChar = switchChar + 1;
}
<html>
<body>
<p id="el"></p>
</body>
</html>
What I want is:
#*#*#*#*#
*#*#*#*#*
#*#*#*#*#
etc. depending on the size of the grid.
All I get is one line of the above.

The problem is in the sizeGrid which is stopping the inner loop by doing this it will work fine.
while (heightGrid <= originalSize){
sizeGrid = 0;
document.getElementById("el").innerHTML+="<br>";
if (switchChar % 2 === 0){
switchCharTwo = 1;
}
else {
switchCharTwo = 2;
}
while (sizeGrid <= originalSize){
if (switchCharTwo % 2 === 0){
document.getElementById("el").innerHTML+=charOne;
}
else {
document.getElementById("el").innerHTML+=charTwo;
}
sizeGrid = sizeGrid + 1;
switchCharTwo = switchCharTwo + 1;
}
heightGrid = heightGrid + 1;
switchChar = switchChar + 1;
}

Your code contains two loops with one nested inside of the other.
Your nested loop is going to run on the first iteration while it meets the given condition, sizeGrid <= originalSize. On all subsequent iterations of the main loop however, the given condition has already been met. The value wasn't reset between loops therefore the nested loop doesn't run again.
This could be resolved with a quick update by moving the sizeGrid variable declaration within the main loop:
while (heightGrid <= originalSize) {
var sizeGrid = 0;
Given what you're looking to achieve however, you could condense this down with a different loop type.
You've essentially manually written a for loop. You set the starting counter value, run the loop, and then increment your counter. Here's the approach I'd suggest:
for (let heightGrid = 0; heightGrid <= originalSize; heightGrid++) {
... logic here
// nested loop
for (let sizeGrid = 0; sizeGrid <= originalSize; sizeGrid++) {
// nested logic
}
}
You'll have to be careful with the comparisons however. Your original loop iterates 10 times despite originalSize being 8. The for loop above will actually run 9 times which seems to match the output you're looking for. I'd be inclined to adjust your numbering so that it's clearer though.
Here's a rough approach I came up with:
const gridSize = 9;
const gridChars = ['x', '#'];
let gridCharCounter = 0;
for (let rows = 0; rows < gridSize; rows++) {
for (let columns = 0; columns < gridSize; columns++) {
const charKey = gridCharCounter % gridChars.length;
document.getElementById("el").innerHTML += gridChars[ charKey ];
gridCharCounter++;
}
document.getElementById("el").innerHTML += '<br />';
}

Related

Why is the loop not iterating for compounding investment calculation in JS

I'm writing a function to calculate investment return over period of years. However, the function seems to be only able to calculate for one year. If the totalyears is more than 1, the loop as shown below is not iterating and it returns wrong value.
const calc = (initial, monthlyContribution, totalyears, annualisedReturn) => {
let sum = initial;
for (i = 0; i < totalyears; i++) { // ISSUE: THIS NOT LOOPING WHEN totalyears > 1
let balance = sum;
let totalBalance = 0;
for (i = 0; i < 12; i++) {
totalBalance = totalBalance + balance;
balance = balance + monthlyContribution;
}
sum = balance + (totalBalance / 12) * (annualisedReturn / 100);
}
return sum;
};
console.log(calc(0, 100, 2, 10)); // This return 1255 which is wrong
You're using the same global variable for both loops. i will have the value 12 when leaving the inner loop, thus the condition of the outer loop will be false
You are using the same variable "i" in the inner loop and you are not declaring it again.
So when you start the loop with i=0, your inner loop will first make i=0 again, then it will increase until i=12, and then the same variable is used in the first loop, so it will go from 0 to 12, skipping iterations. Use "i, j,k" for nested loops.
Something like this:
for (let i = 0; i < 10; i++) {
for (let j = 0; j < 10; j++) {
}
}

Put a line break in a for loop that is generating html content

I have a for loop that is generating some HTML content:
var boxes = "";
for (i = 0; i < 11; i ++) {
boxes += "<div class=\"box\"><img src=\"unlkd.png\"/></div>";
}
document.getElementById("id").innerHTML = boxes;
I want to display 3 boxes in one row, then below them 2 boxes in one row, then 1, then 3 again, 2, and 1.
First i thought of using the if statement to check whether i > 2 to add a line break, but it will also add a line break after every box past the third one. Nothing comes to mind, and my basic knowledge of javascript tells me I'll have to make a loop for each row I want to make. Any advice?
I would use a different approch :
Use a array to store the number of item per row :
var array = [3, 2, 1, 3, 2];
Then, using two loops to iterate this
for(var i = 0; i < array.length; i++){
//Start the row
for(var j = 0; j < array[i]; ++j){
//create the item inline
}
//End the row
}
And you have a pretty system that will be dynamic if you load/update the array.
PS : not write javascript in a while, might be some syntax error
Edit :
To generate an id, this would be simple.
create a variable that will be used as a counter.
var counter = 0;
On each creating of an item, set the id like
var id = 'boxes_inline_' + counter++;
And add this value to the item you are generating.
Note : This is a small part of the algorithm I used to build a form generator. Of course the array contained much more values (properties). But this gave a really nice solution to build form depending on JSON
You can try something like this:
Idea
Keep an array of batch size
Loop over array and check if iterator is at par with position
If yes, update position and index to fetch next position
var boxes = "";
var intervals = [3, 2, 1];
var position = intervals[0];
var index = 0;
for (i = 0; i < 11; i++) {
boxes += "<div class=\"box\"><img src=\"unlkd.png\"/></div>";
if ((position-1) === i) {
boxes += "<br/>";
index = (index + 1) % intervals.length;
position += intervals[index]
}
}
document.getElementById("content").innerHTML = boxes;
.box{
display: inline-block;
}
<div id="content"></div>
var boxes = "",
boxesInRow = 3,
count = 0;
for (i = 0; i < 11; i ++) {
boxes += "<div class=\"box\"><img src=\"unlkd.png\"/></div>";
count++;
if(count === boxesInRow) {
boxes += "<br/>";
boxesInRow -= 1;
count = 0;
if (boxesInRow === 0) {
boxesInRow = 3;
}
}
}
document.getElementById("id").innerHTML = boxes;
var i;
var boxes = "";
for (i = 0; i < boxes.length; i++) {
boxes += "<div class=""><img src=""/></div>";
function displayboxes() {
"use strict";
for (i = 0; i < boxes.length; i++) {
out.appendChild(document.createTextNode(boxes[i] + "<br>"));
}
}
displayboxes(boxes);

Javascript: an array in While loop isn't changing when it should

I have a while loop that's working fine. Inside it is an array push. yes this part works perfectly until the while loops completes. All of this is inside another while loop what has an increment change. the increment affects the array in hopes to re-write it completely. what ends up happening is that it stays stuck on the first version of the array, and everything else in later coding can't call on the second version of the array.
var arrayname = [];
var increment = 0;
var var1 = 0;
var x = 0;
var y = 0;
var z = 0;
outerloop == 0;
while(outerloop == 0){
endloop = 0;
while (endloop == 0) {
arrayname.length = 0;
randomFunctionThatCreatesThe123variables();//in here 'increment' changes output.
x = (1 + 2 + 3); //above function's summed result
y = 25; //static base number
alert(increment);
z = (increment + y);
if (x == z)
arrayname[array.length] = [1,2,3];
if (x == 500)
endloop = 1;
}
testloop = 0;
while (testloop == 0){
otherRandomFunctionsThatTestArray();//this loops the same functions on each subarray
if (var1 == arrayname.length) {
testloop = 1;
var1 = 0;
tar = ++increment;
}
}
if((increment + y) == 700)
outerloop = 1;
}
my goal is that the testloop functions test the array, then when endloop recreates the array on the next cycle, it will use the newly incremented affected array. but all that happens is:
if array not cleared:it keeps cycling the tests throught the same array.
if cleared with arrayname.length = 0; the tests use the new increment to find the new array and but finds it undefined.
the alert proves the increment is being properly read.

"Look and say sequence" in javascript

1
11
12
1121
122111
112213
122211
....
I was trying to solve this problem. It goes like this.
I need to check the former line and write: the number and how many time it was repeated.
ex. 1 -> 1(number)1(time)
var antsArr = [[1]];
var n = 10;
for (var row = 1; row < n; row++) {
var lastCheckedNumber = 0;
var count = 1;
antsArr[row] = [];
for (var col = 0; col < antsArr[row-1].length; col++) {
if (lastCheckedNumber == 0) {
lastCheckedNumber = 1;
antsArr[row].push(lastCheckedNumber);
} else {
if (antsArr[row-1][col] == lastCheckedNumber) {
count++;
} else {
lastCheckedNumber = antsArr[row-1][col];
}
}
}
antsArr[row].push(count);
antsArr[row].push(lastCheckedNumber);
}
for (var i = 0; i < antsArr.length; i++) {
console.log(antsArr[i]);
}
I have been on this since 2 days ago.
It it so hard to solve by myself. I know it is really basic code to you guys.
But still if someone who has a really warm heart help me out, I will be so happy! :>
Try this:
JSFiddle Sample
function lookAndSay(seq){
var prev = seq[0];
var freq = 0;
var output = [];
seq.forEach(function(s){
if (s==prev){
freq++;
}
else{
output.push(prev);
output.push(freq);
prev = s;
freq = 1;
}
});
output.push(prev);
output.push(freq);
console.log(output);
return output;
}
// Sample: try on the first 11 sequences
var seq = [1];
for (var n=0; n<11; n++){
seq = lookAndSay(seq);
}
Quick explanation
The input sequence is a simple array containing all numbers in the sequence. The function iterates through the element in the sequence, count the frequency of the current occurring number. When it encounters a new number, it pushes the previously occurring number along with the frequency to the output.
Keep the iteration goes until it reaches the end, make sure the last occurring number and the frequency are added to the output and that's it.
I am not sure if this is right,as i didnt know about this sequence before.Please check and let me know if it works.
var hh=0;
function ls(j,j1)
{
var l1=j.length;
var fer=j.split('');
var str='';
var counter=1;
for(var t=0;t<fer.length;t++)
{
if(fer[t]==fer[t+1])
{
counter++;
}
else
{
str=str+""+""+fer[t]+counter;
counter=1;
}
}
console.log(str);
while(hh<5) //REPLACE THE NUMBER HERE TO CHANGE NUMBER OF COUNTS!
{
hh++;
//console.log(hh);
ls(str);
}
}
ls("1");
You can check out the working solution for in this fiddle here
You can solve this by splitting your logic into different modules.
So primarily you have 2 tasks -
For a give sequence of numbers(say [1,1,2]), you need to find the frequency distribution - something like - [1,2,2,1] which is the main logic.
Keep generating new distribution lists until a given number(say n).
So split them into 2 different functions and test them independently.
For task 1, code would look something like this -
/*
This takes an input [1,1,2] and return is freq - [1,2,2,1]
*/
function find_num_freq(arr){
var freq_list = [];
var val = arr[0];
var freq = 1;
for(i=1; i<arr.length; i++){
var curr_val = arr[i];
if(curr_val === val){
freq += 1;
}else{
//Add the values to the freq_list
freq_list.push([val, freq]);
val = curr_val;
freq = 1;
}
}
freq_list.push([val, freq]);
return freq_list;
}
For task 2, it keeps calling the above function for each line of results.
It's code would look something like this -
function look_n_say(n){
//Starting number
var seed = 1;
var antsArr = [[seed]];
for(var i = 0; i < n; i++){
var content = antsArr[i];
var freq_list = find_num_freq(content);
//freq_list give an array of [[ele, freq],[ele,freq]...]
//Flatten so that it's of the form - [ele,freq,ele,freq]
var freq_list_flat = flatten_list(freq_list);
antsArr.push(freq_list_flat);
}
return antsArr;
}
/**
This is used for flattening a list.
Eg - [[1],[1,1],[1,2]] => [1,1,1,1,2]
basically removes only first level nesting
**/
function flatten_list(li){
var flat_li = [];
li.forEach(
function(val){
for(ind in val){
flat_li.push(val[ind]);
}
}
);
return flat_li;
}
The output of this for the first 10 n values -
OUTPUT
n = 1:
[[1],[1,1]]
n = 2:
[[1],[1,1],[1,2]]
n = 3:
[[1],[1,1],[1,2],[1,1,2,1]]
n = 4:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1]]
n = 5:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3]]
n = 6:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1]]
n = 7:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1],[1,1,2,3,1,2,3,1,1,1]]
n = 8:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1],[1,1,2,3,1,2,3,1,1,1],[1,2,2,1,3,1,1,1,2,1,3,1,1,3]]
n = 9:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1],[1,1,2,3,1,2,3,1,1,1],[1,2,2,1,3,1,1,1,2,1,3,1,1,3],[1,1,2,2,1,1,3,1,1,3,2,1,1,1,3,1,1,2,3,1]]

how to check which elements of an array match relative to position

Trying to create a function or two that will be able to check the elements of an array and output wheater the elements of the two arrays are identical (ie same number and identical position is present), or the number is present but does not match the same position as the other array. Basically, I'm attempting to recreate a simple game called mastermind. The main problem im having is a case senarior when say the right answer is [1,2,3,4] and the user will guess [0,1,1,1], my function will out put that the number 1 is present 3 times, and I need to figure out how to just have it say the number 1 is present 1 time. Here is the function that checks the arrays:
function make_move(guess, answ){
var myguess = document.getElementById("mymoves");
var correct_number_correct_spot= 0;
var correct_number_wrong_spot= 0;
for(var i = 0; i < 4; ++i)
{
if(answ[i] == guess[i]){
++correct_number_correct_spot;
}
else if(answ[i] !== guess[i] && $.inArray(guess[i], answ) !== -1){
++correct_number_wrong_spot;
}
}
console.log(answ);
console.log(guess);
myguess.innerHTML += correct_number_correct_spot + " were right!" +correct_number_wrong_spot+ "there but not in the right order";
}
You can keep the count of missed numbers in an object, and subtract the guessed ones that appear in the answer. Then you can calculate the correct_number_wrong_spot subtracting the number of correct_number_correct_spot and the missed ones.
function make_move(guess, answ){
var myguess = document.getElementById("mymoves");
var correct_number_correct_spot = 0;
// Initialize missed counts to the numbers in the answer.
var correct_number_wrong_spot = answ.length;
var missed = {};
for (var j = 0; j < answ.length; j++) {
missed[answ[j]] = (missed[answ[j]] || 0) + 1;
}
for(var i = 0; i < answ.length; ++i)
{
if(answ[i] == guess[i]){
++correct_number_correct_spot;
}
// Subtract the guessed numbers from the missed counts.
if (guess[i] in missed) {
missed[guess[i]] = Math.max(0, missed[guess[i]] - 1);
}
}
// Subtract the correctly spotted numbers.
correct_number_wrong_spot -= correct_number_correct_spot;
// Subtract the remaining missed numbers.
for (var number in missed) {
correct_number_wrong_spot -= missed[number];
}
console.log(answ);
console.log(guess);
myguess.innerHTML += correct_number_correct_spot + " were right!" +correct_number_wrong_spot+ "there but not in the right order";
}
Check demo
EDIT: My try to explain doubts exposed in the comments:
would you mind explining how this code works: for (var j = 0; j < answ.length; j++) { missed[answ[j]] = (missed[answ[j]] || 0) + 1; }
missed[answ[j]] = (missed[answ[j]] || 0) + 1;
This is a quick way to increment the count for a number or initialize it to 0 if it doesn't exists yet. More or less the statement works like this:
If missed[answ[j]] is undefined then it is falsy and hence the || (or operator) evaluates to the 0. Otherwise, if we already have a value greater than 0, then it is truthy and the || evaluates to the contained number.
If it looks weird, you can replace this line with:
if (!(answ[j] in missed)) {
missed[answ[j]] = 0;
}
missed[answ[j]] += 1;
also if (guess[i] in missed) { missed[guess[i]] = Math.max(0, missed[guess[i]] - 1);
missed[guess[i]] = Math.max(0, missed[guess[i]] - 1);
In this case I use Math.max to make sure we don't subtract below 0. We don't want repeated numbers in the guess that exceeds the number of those present in the answer count. I mean, we subtract at most until the number of repeated numbers in the answer.
if (missed[guess[i]] > 0) {
missed[guess[i]] -= 1;
}
Try this fiddle!
Without changing your original function too much, you can use an object as a map to keep track of which numbers you have already matched.
var number_matched = {};
// ...
if(!number_matched[guess[i]]) {
number_matched[guess[i]] = true;
}

Categories

Resources