JavaScript iterate loop every x number of times in same loop? - javascript

I am not sure how to phrase this, so please re-title this question if it doesn't make sense. Anyways, this is what I am trying to do.
I have a variable with the length of 9.
And then I have another variable with the length of 3.
How do I write a loop that iterates through all 9 but starts over every third time?
For example: I have this,
x = 3;
l = 9;
for ( var i = 0; i < l; i++)
{
console.log(i + 1);
}
output = 1,2,3,4,5,6,7,8,9
The output I want to create
output = 1,2,3,1,2,3,1,2,3
I was thinking there might be away to do this with an if statement or possibly modulus, but wasn't quite sure how to implement it. What would be a good way to do this? Thanks in advance.

Embrace the modulus:
function expand(length, loop_length) {
for (var i = 0; i < length; i++) {
console.log(i % loop_length + 1);
}
}
expand(9, 3) // => 1, 2, 3, 1, 2, 3, 1, 2, 3

x = 3;
l = 9;
for ( var i = 0; i < l; i++)
{
console.log(i % x + 1);
}
output = 1,2,3,1,2,3,1,2,3
See it in action here: http://jsfiddle.net/BgBGL/

If you want to loop from a min value to a max value a specific number of times, the easiest way is just to have 2 loops, like this:
var min = 1, max = 3, times = 3;
for (var i = 0; i < times; i++) {
for (var j = min; j <= max; j++) {
console.log(j);
}
}
Or if you want to fix total length of the sequence, then yes, you can do it with a single loop and a little bit of math:
var min = 1, max = 3, totalLength = 9;
for (var i = 0; i < totalLength; i++) {
console.log((i % (max - min + 1)) + min);
}

For that case, this works:
x = 3;
l = 9;
for ( var i = 0; i < l; i++)
{
var num=(i %(x+1)) || 1;
console.log(num);
}

You could go mad with following syntax:
var i = 0;
do {
console.log(i++ % 3 + 1);
} while (i < 9);
Alternative, you could define 3 and 9 as a variable also.
I took an advantage of the fact that calling i++ will display old variable and increases it by 1 after, so I saved some bits!
See: fiddle example

x = 3;
l = 9;
for ( var i = 0; i <= l; i++)
{
for ( var j = 1; j <= x; j++)
{
console.log(j);
}
}

Related

JS - Convert nested forloops into single loop

I need to convert this nested loop into a single loop.
This is the loop with the scenario:
First incrementer is i which starts from 0 and should run till 10
Second incrementer is j which starts from where i left off + 1 and runs till 10
.
.
My Nested Loop
for (var i = 0; i < 10; i++) {
for (var j = i + 1; j < 10; j++) {
if (some_condition) {
do_sth()
}
}
}
My Attempt at conversion
var i = 0;
while (i < 10){
var j = i + 1;
if (j < 10) {
if (some_condition) {
do_sth()
}
j++;
}
i++;
}
Unfortunately, my attempt doesn't produce the expected results.
The second snippet does not give the output which the first snippet delivers.
Can anyone please suggest me what my mistake is or provide me a better solution to achieve my target?
Thanks!
Not sure it improves readability complexity, but the following should produce the same.
var i = 0, j = 1;
while (i < 9) {
console.log(i, j);
j += 1;
if (j >= 10) {i += 1; j = i + 1}
}
You need to update i inside else statement or use continue. And declare j outside of the while body.
But keep in mind that this neither change "the order of complexity" nor "optimise" your code.
var i = 0;
var j = 1;
while (i < 10) {
if (j < 10) {
if (true) {
console.log(i, j)
}
j++;
} else {
i++;
j = i + 1;
}
}
You could adjust the loop lenght of i and check if j is greater or equal than 9, then increment i and start with fresh j.
var i = 0,
j = 1;
while (i < 9) {
console.log(i, j);
// do you stuff
if (j >= 9) j = ++i;
j++;
}
.as-console-wrapper { max-height: 100% !important; top: 0; }

misprinted number in prime function

function primeSieve() {
for(i = 0; i <= 100; i++){
let flag = true
for(let j = 2; j < i/2; j++){
if(i % j === 0){
flag = false
}
}
if(flag){
console.log(i)
}
}
}
primeSieve();
Hi,
I'm studying some algos and ran into a prime sieve problem. I'm trying to print all prime numbers between 0 and 100 and it's working for the most part. However, i realized that 4 slipped in somehow and i can't figure out why for the life of me. Wondering if i can get a few pairs of eyes and see how 4 ended up being logged to the console and why that's the case.
thank you!
Your condition in the inner loop:
for (let j = 2; j < i / 2; j++) {
is
j < i / 2
This means that when i is 4, once j gets to 2 (or, since j is always initialized to 2, before the first iteration), the loop breaks. So, without any iterations, there's never any chance for an i of 4 to get to flag = false.
Change to
for (let j = 2; j <= i / 2; j++) {
Also, per wikipedia:
A prime number (or a prime) is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers.
So you should probably start i at 2, not 0.
Also, just like your let j, it would be good to declare i with let as well so as not to implicitly pollute the global scope:
function primeSieve() {
for (let i = 2; i <= 100; i++) {
let flag = true
for (let j = 2; j <= i / 2; j++) {
if (i % j === 0) {
flag = false
}
}
if (flag) {
console.log(i)
}
}
}
primeSieve();
Beside the including the value for j to check with j <= i / 2, you could omit the use of a flag and use continue with a label for the outer loop.
function primeSieve() {
outer: for (var i = 2; i <= 100; i++) {
for (var j = 2; j <= i / 2; j++) {
if (i % j === 0) {
continue outer;
}
}
console.log(i);
}
}
primeSieve();

Sum of Primes using Sieve of Eratosthenes can't find bug

I'm working in JavaScript and this is a bit confusing because the code is returning the correct sum of primes. It is working with larger numbers. There is a bug where for 977 it returns the sum of primes for 976, which is 72179, instead of the sum for 977 which is 73156. Everything I've test so far has come back correctly.
function sumPrimes(num) {
var sum = 0;
var count = 0;
var array = [];
var upperLimit = Math.sqrt(num);
var output = [];
for (var i = 0; i < num; i++) {
array.push(true);
}
for (var j = 2; j <= upperLimit; j++) {
if (array[j]) {
for (var h = j * j; h < num; h += j) {
array[h] = false;
}
}
}
for (var k = 2; k < num; k++) {
if (array[k]) {
output.push(k);
}
}
for (var a = 0; a < output.length; a++) {
sum += output[a];
count++;
}
return sum;
}
sumPrimes(977);
The problem stems from the fact that your "seive" Array is indexed from 0, but your algorithm assumes that array[n] represents the number n.
Since you want array[n]===true to mean that n is prime, you need an Array of length 978 if you want the last item to be indexed as array[977] and mean the number 977.
The issue seems to be fixed when I change all instances of < num to < num+1.

How can you iterate through all the numbers in an array and either add or subtract them so they hit a predetermined value

Let's assume I have two variables. One an array of numbers and the other the number 3. The goal is to iterate through the array of numbers and figure out which pair of numbers can be used to equal the number 3 either by being added together or subtracted.
var numbers = [-1, -1, 4, 2, 3, 5, 0]
var target = 3
for(i = 0; i < numbers.length; i++) {
}
I understand the for loop is going to go through the array of numbers but once I do that I don't understand how I can check every pair and see if they add or subtract to hit the value of 3. Is there a JavaScript method that can help?
Not sure if I understood correctly, but maybe something like this?
var numbers = [-1, -1, 4, 2, 3, 5, 0];
var target = 3;
var pairs = [];
for (i = 0; i < numbers.length; i++) {
for (j = 0; j < numbers.length; j++) {
if (j != i) {
if ((numbers[i] + numbers[j]) == target) {
pairs.push([numbers[i], numbers[j]]);
document.write(numbers[i] + " + " + numbers[j] + " = " + target + "<br>");
}
}
}
}
Basically you go through each number in the array, then loop again through all the numbers and check if their sum equals to the target.
You can test it here.
I don't think there is a JavaScript method for this, but this should work:
for(i = 0; i < numbers.length; i++) {
// calculate the difference
var diff = target - numbers[i];
// now: numbers[i] + diff === target
// do whatever you want with diff
}
for (var i = 0; i < numbers.length-1; i++){
for (var j = i+1; j < numbers.length; j++){
if(numbers[i] + numbers[j] == target || Math.abs(numbers[i] - numbers[j]) == target){
console.log(numbers[i]+" , "+numbers[j]); //Do whatever you want
}
}
}

how to multiply and adding two dimensional arrays

I have variable with string values in two dimensional array format.
var arrayList=[["1","2"],["6","3600","11","60"],["1","2","3","4","5","6"]];
What I want,each odd position value multiply with next even position and finally adding that values
like.
["1","2"]=(1*2);
["6","3600","11","60"]=((6*3600)+(11*60));
["1","2","3","4","5","6"]=((1*2)+(3*4)+(5*6))
for this I written the following code,second and third cases are not working.
really sorry might be it's very basic question but I tested each and every line it's seems code is correct but in second and third cases getting Nan.
var result=[];
for (var index = 0; index < arrayList.length; index++) {
var innerResult=0;
for (var jndex = 0; jndex < arrayList[index].length; jndex++) {
var cali=parseInt(arrayList[index][jndex])*parseInt(arrayList[index][jndex+1]);
innerResult=innerResult+cali;
jndex=jndex+2;
};
result.push(innerResult);
};
result
I am getting like this [3,Nan,Nan].
please can anyone help me.
Thanks
You're incrementing jndex on each loop and then you are adding 2 more at the end of that loop. You have two options, changing this:
for (var jndex = 0; jndex < arrayList[index].length; jndex++) {
to:
for (var jndex = 0; jndex < arrayList[index].length; jndex+=2 ) {
or this:
jndex=jndex+2;
to:
jndex=jndex+1;
If you do the first one, you no longer need the increment within the loop.
I have written this algorithm that I believe might help you.
var array = [["1","2"],["6","3600","11","60"],["1","2","3","4","5","6"]];
array.map(function(subArray){
var total = 0;
for(var i = 1; i < subArray.length; i += 2)
total += parseInt(subArray[i], 10) * parseInt(subArray[i - 1], 10);
return total;
});
The jindex will be incremented by the loop as well. This will mean the jindex is incremented by 3 each loop.
Consider the case where jindex is arrayList[index].length - 1; when you parseInt(arrayList[index][jndex+1]) you will reach outside the bounds of the array, and get undefined (and parseInt(undefined) is NaN again).
If you fix those, you should find your code works;
var result = [];
for (var index = 0; index < arrayList.length; index++) {
var innerResult = 0;
for (var jndex = 0; jndex < arrayList[index].length - 1; jndex++) {
var cali = parseInt(arrayList[index][jndex]) * parseInt(arrayList[index][jndex + 1]);
innerResult = innerResult + cali;
jndex = jndex + 1;
};
}
http://jsfiddle.net/Bwx2g/
Try this:
var result = [];
for (var index = 0; index < arrayList.length; index++) {
var innerResult = 0;
for (var jndex = 0; jndex < arrayList[index].length;) {
var cali = (parseInt(arrayList[index][jndex]) * parseInt(arrayList[index][jndex + 1]));
innerResult = innerResult + cali;
jndex = jndex + 2;
}
result.push(innerResult);
}
Inner for loop changed to while loop (you have double increment in for loop):
var result = [];
for (var index = 0; index < arrayList.length; index++) {
var innerResult = 0;
var j = 0;
while (j < arrayList[index].length) {
var cali = parseInt(arrayList[index][j]) * parseInt(arrayList[index][j + 1]);
innerResult = innerResult + cali;
j += 2;
}
result.push(innerResult);
};

Categories