JS - Convert nested forloops into single loop - javascript

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; }

Related

Why this code printing wrong prime numbers?

"I think problem is in for loop. Because i have used same "j" to iteration in both function's loop."
I wanted to print all prime number from 1-100.
I think all code is good. But it kept showing output other than prime numbers.
I can't find answers myself . And no other places has written answer. Please help me out here. I want to understand this problem.
var n = 100;
var prime1 = new Array();
//producing prime number upto 97
function primeNumber() {
for (j = 1; j <= n; j++) {
if (countRemainder(j) == 2) {
prime1.push(j);
}
}
}
primeNumber();
console.log(prime1);
function countRemainder(n) {
var count = 0;
for (j = 1; j <= n; j++) {
if (n % j == 0) {
count++;
}
}
return count;
}
The problem was indeed happening because you were using the same variable in both for loops.
When you declare a variable like j = 0; and not like var j = 0; the variable will be added to global scope (instead of the scope you are in, so every other scope can see and alter that variable).
If your script is running in strict mode, then this will throw an error, instead of adding the variable to the global scope.
So just add var before each j declaration.
var n = 100;
var prime1 = new Array();
//producing prime number upto 97
function primeNumber() {
for (var j = 1; j <= n; j++) {
if (countRemainder(j) == 2) {
prime1.push(j);
}
}
}
primeNumber();
console.log(prime1);
function countRemainder(n) {
var count = 0;
for (var j = 1; j <= n; j++) {
if (n % j == 0) {
count++;
}
}
return count;
}
Use "let" to declare "j" correctly.
function primeNumber() {
for (let j = 1; j <= n; j++) {
if (countRemainder(j) == 2) {
prime1.push(j);
}
}
}
Try this
var n = 100;
var prime1 = new Array();
//producing prime number upto 97
function primeNumber() {
for (var j = 1; j <= n; j++) {
if (countRemainder(j) == 2) {
prime1.push(j);
}
}
}
primeNumber();
console.log(prime1);
function countRemainder(n) {
var count = 0;
for (var j = 1; j <= n; j++) {
if (n % j == 0) {
count++;
}
}
return count;
}

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();

Reversing loop javascript

I have a problem with my exercise. I have to draw something like this:
https://screenshots.firefox.com/3qaHB7dcr3n610hi/jsbin.com
And this is my code
var empty = "";
for(var i=0; i < 5; i++) {
empty += "*";
console.log(empty)
}
but with this code I can only make this:
*
**
***
****
*****
I have no idea how to reverse this loop to start it from top from 5 stars, i tried something like this:
var empty = "";
for (i = 5; i <= 0;i--) {
empty+="*";
console.log(empty);
}
But doesn't work. Anybody know how to do this? I will be grateful :)
Your approach builds the first part.
The second part can be accomplished using the function slice in descending direction.
var empty = "";
var i = 0;
// Build the first part
for (; i < 5; i++) {
empty += "*";
console.log(empty)
}
// Here i = 5, so this is the initialization for the following loop.
// Loop in descending direction using the function slice.
for (; i > 0; i--) {
console.log(empty.slice(0, i))
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Your condition was wrong. Check this.
for(let i = 1; i <= 5; i++) {
console.log('\"' + '*'.repeat(i) + '\"');
}
for(let i = 5; i > 0; i--) {
console.log('\"' + '*'.repeat(i) + '\"');
}
Instead of a for/loop you could use a while loop to change the direction:
let stars = 0;
let count = 0;
while (count < 9) {
if (count < 5) stars++;
if (count >= 5) stars--;
const line = Array(stars).fill('*').join('');
console.log(line);
count++;
}
Just in case you need a nested for loop. (As some exercises sometimes do)
var k = 0;
for(var i = 1; i < 12; i++){
var stx = "";
for(var j = k; j < i; j++){
stx += "*";
}
if(i > 5) k += 2
if(i == 6) continue
console.log(stx);
}

How to make a triangle using for loop javascript

I have a simple question although i cannot manage to resolve this problem. Hope you can help. I need to make triangle using for loop and from this 4 exercises I don't know what to do with the third one. I haven't used Javascript before, so any help would be appreciated.
# # # # #
# # # #
# # # <----- here is triangle i need to make. Just in case
# #
#
var i;
var j;
for (i = 0; i <= 5; i++ )
{
document.write("</br>");
for ( j = 0; j < 6-i; j++ )
{
document.write( "&nbsp&nbsp" );
}
for ( j = 6-i; j <= 5; j++ )
{
document.write( "*" );
}
}
This is code I wrote for D in photo.
And I'm sorry i did not add it at first.
for (let line = "*"; line.length < 8; line += "*")
console.log(line);
this question came in this book: http://eloquentjavascript.net
I don't know why there are so bad answers on google for this one.
function leftTriangle(rows){
let result = '';
for(let i=rows;i>0;i--){
if(i===rows) {
result += '*'.repeat(i) + '\n';
}else{
let empty = rows-i
result+= ' '.repeat(empty) + '*'.repeat(i)+ '\n'
}
}
return result;
}
console.log(leftTriangle(5))
I'm sure there are better solutions (simply left-padding with spaces comes to mind), but here's the quick and dirty one I created from your own solution.
for (var i = 0; i < 5; i++) {
for (var j = 0; j < i; j++) {
document.write(" ");
}
for (var j = 5; j > i; j--) {
document.write("#");
if (j > i + 1) document.write(" ");
}
document.write('<br/>')
}
https://js.do/code/diamondsinthesky
Something like this?
var rows = 5;
for (var i = rows; i--;) {
var columns = 0;
while (columns <= i) {
document.write('#');
columns++
}
document.write('<br />\n');
}
Thank you for your help. I did it. It was too obvious but somehow I couldn't find it. Thank you one more time. Here is how i did it.
for (i = 5; i > 0; i--) {
document.write("</br>");
for (j = 0; j < 6 - i; j++) {
document.write("&nbsp&nbsp");
}
for (j = 6 - i; j <= 5; j++) {
document.write("*");
}
}
var rows = 5;
for (var i = rows; i--;) {
var columns = 0;
while (columns <= i) {
document.write('#');
columns++
}
document.write('<br />\n');
}
You can also do this if you are looking for something different.
This code is for a triangle of 7 lines.
let size = 8;
let y = "#";
for (let x = 0; x < size; x++)
{
console.log(y);
y += "#";
}
// Second method
for (let i = 1; i < size;i++)
{
let me ="#".repeat(`${i}`)
console.log(me);
}
var size = 5;
for (var i = 0; i < size; i++) {
for (var j = 0; j <= i; j++) {
document.write("*");
}
document.write("<br />\n");
}

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

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);
}
}

Categories