What is your solution to break from nested loops?
πŸ‘︎ 637
πŸ’¬︎
πŸ‘€︎ u/exander314
πŸ“…︎ Dec 10 2021
🚨︎ report
Java vs JS: Nested for loop scoping error?
// Java
public class test1
{
   public static void main(String [] args)
   {
      int j,k;
  
      for(j=0; j<4; j++)
      {
         for(k = 0; k < 10; k++)
         {
            
         }
      }
      System.out.println(k); 
   }
}

Compile error: variable k might not have been initialized
      System.out.println(k);


// similar code in JS 

let j,k

for(j = 0; j < 4; j++) {
  for(k = 0; k < 10; k++) {

  }
}

console.log(k)

Output: 10

So I come from JS. The code snippet was from a Java course practice question. I ran the equivalent code in JS which returns 10 as expected (console to the lower right), but I ran into this compilation error in Java that I don't know why is happening.

I think this is a scoping issue for Java, but I am not sure. B/c for JS because "k" is declared in the global scope it is accessible to the for loop. I understand blocked local variables declared inside for loops are not accessible outside the loop or block, etc.

In the Java example, if I run the "k" for loop by itself but NOT nested, it runs fine. But put inside another for loop, I get an initialization error. But this confuses me because to me k does get initialized. It is declared up top but initialized some time later in the initialization statement in the for statement. Same as the "j" variable, which gives no error. B/c the j for loop gives no initialization error yet it is declared and initialized similarly this leads me to believe there is something happening with scope and nesting that is different in Java.

Any clarification/explanation appreciated!

πŸ‘︎ 6
πŸ’¬︎
πŸ‘€︎ u/momu1990
πŸ“…︎ Jan 06 2022
🚨︎ report
rustc/llvm lowkey blew my mind with what it did to this nested loop

I was playing around, wondering how fast my computer could do a bunch of multiplications and additions of numbers from a couple of ranges in a nested loop so I wrote a little bit of code, the main portion of which was basically the following:

pub fn do_some_maths () -> u128
{
    let x_min: u128 = 1_000_000;
    let x_max: u128 = 3_500_000;
    let y_min: u128 = 5;
    let y_max: u128 = 9;
    let mut sum = 0;
    for x in x_min..x_max
    {
      for y in y_min..y_max
      {
        sum += x * y;
      }
    }
    sum
}

And I was measuring how long the function took to run when compiled in release mode, but I kept getting 0 ns as a result, which I could not understand. So I thought ok, maybe this loop completed running faster than the precision of the duration calculation allowed me to measure.

So I cranked up the numbers a whole bunch.

pub fn do_some_maths () -> u128
{
    let x_min: u128 = 1_000_000_000;
    let x_max: u128 = 3_500_000_000;
    let y_min: u128 = 5_000_000_000;
    let y_max: u128 = 9_000_000_000;
    let mut sum = 0;
    for x in x_min..x_max
    {
      for y in y_min..y_max
      {
        sum += x * y;
      }
    }
    sum
}

That should amount to 9,999,999,996,000,000,000 iterations. And yet I was still getting the result within the optimized binary in shorter time than I could measure.

Now, I know that the rustc/llvm compiler is clever, and I know it can calculate a lot of things at compile time when you write code that performs maths on values that are all given in the source.

But still I could not understand what was going on.

I also calculated a simple upper bound of what the result could be, and the result that my program was giving me seemed quite reasonable.

So I disassembled the release binary in Ghidra and I was extremely surprised to see that the whole nested loop and the calculation, had been reduced down to...

A compile time constant!

Here, you can see the disassembly for the program on Godbolt too, with all optimizations enabled, we get:

https://rust.godbolt.org/z/Trx5G5Wqn

example::do_some_maths:
        movabs  rax, 1318703772846391296
        movabs  rdx, 8538092105816129894
        ret

My mind was audibly blown at this point!

And the values we see here, 1318703772846391296 and 8538092105816129894, when combined (`(8538092105816129894 << 64) + 1318

... keep reading on reddit ➑

πŸ‘︎ 254
πŸ’¬︎
πŸ‘€︎ u/codetrotter
πŸ“…︎ Nov 13 2021
🚨︎ report
I am having trouble understanding nested loops (more importantly day 4 of 100 on the 100 days to code program).

Here is the code:

# 🚨 Don't change the code below πŸ‘‡
row1 = ["⬜️","⬜️","⬜️"]
row2 = ["⬜️","⬜️","⬜️"]
row3 = ["⬜️","⬜️","⬜"]
map = [row1, row2, row3]
print(f"{row1}\n{row2}\n{row3}")
position = input("Where do you want to put the treasure? ")
# 🚨 Don't change the code above πŸ‘†

#Write your code below this row πŸ‘‡
column = int(position[0])
row = int(position[1])

map[row - 1][column - 1] = "X"


#Write your code above this row πŸ‘†

# 🚨 Don't change the code below πŸ‘‡
print(f"{row1}\n{row2}\n{row3}")

I really am struggling to understand how putting the row and column variable into the map variable make the X print where it's desired. Any way of explanation is greatly appreciated. I have very limited python experience (one student taught college course). Thanks in advance.

πŸ‘︎ 5
πŸ’¬︎
πŸ‘€︎ u/gogreengowhite3
πŸ“…︎ Jan 10 2022
🚨︎ report
Currently struggling with nested loops and I am so confused at how this runs. It is seemingly really easy.
class Main {   public static void main(String[] args) {          
int weeks = 3;     
int days = 7;      
// outer loop 
for(int i = 1; i &lt;= weeks; ++i) {      
 System.out.println("Week: " + i);     
   // inner loop 
for(int j = 1; j &lt;= days; ++j) {               
   // break inside the inner loop
 if(i == 2) {         
  break;       
  }        
 System.out.println("  Day: " + j);    
   }   
  }   
} 
}
πŸ‘︎ 4
πŸ’¬︎
πŸ‘€︎ u/ranyewestt
πŸ“…︎ Dec 22 2021
🚨︎ report
My nested if loop "wiggity wack" appears to not be initializing.
πŸ‘︎ 206
πŸ’¬︎
πŸ‘€︎ u/BlackInformannt
πŸ“…︎ Oct 16 2021
🚨︎ report
Alternatives to Nested For Loops in R?

Hello! I am working on a project that is asking me to implement the EM algorithm for GMM, and so far, I have something like this:

  sum &lt;- 0
  for (i in 1:nrow(x)) {
    for (g in 1:ncol(z)) {
      sum &lt;- sum + z[i, g] * log(props[g] * dmvnorm(x[i,], means[g,], covs[[g]]))
    }
  }
  return (sum)

Although this works, I have many more of these nested for loops, which takes much too long. My question is: Is there an alternative way of writing like this that is shorter, cleaner, and will make the program run faster?

Any suggestion would be most appreciated! Thank you!

πŸ‘︎ 4
πŸ’¬︎
πŸ‘€︎ u/trustduhsystem
πŸ“…︎ Dec 18 2021
🚨︎ report
Nested loop to check two lists together that is also linear (o(n))

I'm driving myself crazy with this. I've written one that has the 'in' operator but I was told that it works like an inner loop so not linear.

I can't think of a way to do it without nested loops or the in operator. I would appreciate any advice.

πŸ‘︎ 12
πŸ’¬︎
πŸ‘€︎ u/donutaud15
πŸ“…︎ Nov 17 2021
🚨︎ report
How to speed up 7 nested loops?

I'm a mathematician. I'm wrote a small function to help me with calcluations that would be otherwise impossible to do by hand. There is a problem though: there are 7 nested loops that make it execute in minutes even for very small inputs.

The problem is the 2 deepest loops looks like this:

for i in N:
    for j in N:
        if int(a[j]) == i+1:
            x.append(str(j+1))
            continue

and:

 for j in b:
        i = int(j) - 1
        x.append(a[i])

I have no idea what to use to optimize this. I heard I'm supposed to replace loops with library functions that execute their code in C...

I will explain what the function does.

The functions takes (v,n), where v is a vector of permutations from the symetric group S_n. They are in string form, like this: "1234" - neutral element, "2134" = (12), etc. I don't care what form they are in, I can make them be a list of integers.

The function then takes each pair of elements (a,b) from the vector and tries to generate the group S_n. It outputs how many elements were generated by each pair.

The function tries to generate S_n by:

  • looping through all possible pairs of vectors (v,w) containing 0 and 1 of length range(d).

  • (in the first vector 0 means a, 1 means b)

  • (in the second vector 0 means nothing, 1 means reverse function)

  • inside the loop it combines (denoted with *) multiple copies of a and b in accordance with the 2 vectors. For example: v = [0,0,1] and w = [0,1,0] produces a * a^-1 * b.

    for k in range(d): w.append(0) v.append(0) for i in range(2**(k+1)): for j in range(2**(k+1)): x.add(compSet(a,b,v,w,k+1)) # <- combines a and b according to (v,w) w[0] += 1 for l in range(k+1): if w[l] > 1: w[l] = 0 w[l+1] += 1 v[0] += 1 for l in range(k+1): if v[l] > 1: v[l] = 0 v[l+1] += 1

I saw a video that showed it's thousands of times faster to use built-in numpy functions than for loops. I also found some complicated threads on 'how to make python run C code'.

Do you know how to optimize this function?

**Edit 2 XI 2021**
Newest code updated with all of the suggestions:

from functools import lru_cache
from itertools import permutations
from itertools import product
import time
impo
... keep reading on reddit ➑

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/PerfectSpeling
πŸ“…︎ Nov 11 2021
🚨︎ report
Nested for loop VS Iterator

I am trying to clean up some of my code and have found a lot of ugly 2d and 3d vectors. Suppose I have a 2d Vector of objects. Each object must run a "process" function. I have typically done this with the nested for loops but have recently considered an iterator instead.

After running the code with an iterator, some of my tests fail - which suggests that they are not working the same as the nested loops. What is the difference between the two methods below? are drawbacks to using iterators over loops?

[EDIT] I have found a working solution with your help. The bottom example shows it.

//DOES SOMETHING
for x in 0..self.network.read().unwrap().nodes().len() {
    for y in 0..self.network.read().unwrap().nodes()[x].len() {
        self.network.read().unwrap().nodes()[x][y].write().unwrap().process();
    }
}
//SHOULD DO THE SAME THING?
self.network.read().unwrap().nodes().iter().
    map(|column| column.iter().
        map(|node| node.write().unwrap().process()));

//WORKING SOLUTION
network.read().unwrap().nodes().iter().
    for_each(|column| column.iter().
        for_each( |node| node.write().unwrap().process()));
πŸ‘︎ 6
πŸ’¬︎
πŸ“…︎ Nov 26 2021
🚨︎ report
How to reduce the time complexity of nested loops dev.to/leandronsp/how-to-…
πŸ‘︎ 11
πŸ’¬︎
πŸ‘€︎ u/mmaksimovic
πŸ“…︎ Dec 06 2021
🚨︎ report
Having some trouble with nested loops.

Hello, I'm working on an assignment that involves starting a count that goes from 100 to 1 in increments of 1 and when it hits 11 or 29 its supposed to say Happy Birthday and if the count is a multiple of 7 its supposed to say favorite number instead. I have attempted to construct this with both for and while loops but I am having trouble. When I run my for loop I do not get any results at all not even a count, though the code runs.

for counter in range(100,1):
    if counter == 11 or 29:
        print "Happy Birthday"
    elif counter%7 == 0:
        print "Favorite Number"
    else:
        print counter

And in my while loop, it repeats happy birthday 100 times.

count = 100
while count &gt;= 1:
    if count == 11 or 29:
        print "Happy Birthday"
        count -= 1
    elif count%7 == 0:
        print "Favorite Number"
        count -= 1
    else:
        print count
        count -= 1

Could somebody let me know what im doing wrong and how I can fix my mistake?

Thank you!

πŸ‘︎ 7
πŸ’¬︎
πŸ‘€︎ u/MrWhiskers76
πŸ“…︎ Nov 22 2021
🚨︎ report
Should I be concerned about nested for loops in my draw function?

https://editor.p5js.org/CrummyBoy/full/1QkMikDAb

As you can see in my otherboxes() function, I have a couple nested for() loops for calculating the box()es being generated. Running this script on my computer immediately hogs 100% CPU/GPU, but I don't have a very nice computer. I'm wondering if it's just me because of my crappy computer, or if I need to consider optimizing the number of operations/math I'm doing each draw(). I have played with lowering frameRate() to less than 12, and that immediately helps performance but looks terrible...

Just looking for general advice from those of you more experienced than I am.

Thanks!

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/cobble_block
πŸ“…︎ Dec 21 2021
🚨︎ report
[PostgreSQL] How do I remove a nested loop while doing an inner join of a cross join?

I tried 3 approaches for this and the 3rd one has materialized views involved when it does a sequential scan. For the 1st 2 approaches, it always does a nested loop. Any suggestions are super appreciated https://stackoverflow.com/questions/49269518/how-do-i-remove-the-nested-loop-from-this-multiple-join-query-in-postgresql-10-3

πŸ‘︎ 8
πŸ’¬︎
πŸ‘€︎ u/mypirateapp
πŸ“…︎ Mar 14 2018
🚨︎ report
nested loops, upside down white triangle grid please help

could anyone sort me out with this I’m trying to make a grid of upside down white triangles exactly like

https://imgur.com/a/gatU3pF

with nested loops but so far I’ve only gotten

https://imgur.com/a/YdXjYnI

that has misaligned non grid triangles I’ve no idea what to change in the variables now, any help would be seriously appreciated

my current code

void setup() {

size(420, 420);

background(0, 255, 0);

noStroke(); }

void draw() { for (int x = 0; x <= 420; x += width/6) {

for (int y = 0; y <= 420; y += height/6)

triangle(x, y, x + 70, y, x += 35, y + 70 ); } }

thank you

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/dirgefortheplanet
πŸ“…︎ Dec 18 2021
🚨︎ report
Removing nested loops in Javascript spaceofmatej.com/removing…
πŸ‘︎ 9
πŸ’¬︎
πŸ‘€︎ u/SpiceyySoup
πŸ“…︎ Nov 29 2021
🚨︎ report
Nested loops and Arrays`

Hey there. Been having trouble understanding the logic behind how nested loops work in multidimensional arrays. I'm quite visual so if someone has any resources to help me understand the logic that would be great. I'm working on converting columns to rows and cubes to rows. I'm not looking for the solution just a way to grasp the logic behind it.

Thank you

πŸ‘︎ 5
πŸ’¬︎
πŸ‘€︎ u/Zen_Chameleon
πŸ“…︎ Nov 20 2021
🚨︎ report
Query optimizer choosing nested Loops join for large cardinality estimate?

I've got this rather complex query (20+ joins) I'm tuning. The query plan looks fine until towards the very end, where it decides to perform an indexed nested loops join for 8M+ iterations. Is this really more efficient than a hash join? Is memory grant a consideration for the query optimizer decision?

BTW on SQL2014 Enterprise, SP1 CU2

πŸ‘︎ 7
πŸ’¬︎
πŸ‘€︎ u/daanno2
πŸ“…︎ Feb 16 2017
🚨︎ report
nested loop and switch case

if I have the following: while(1)->switch(1) case-> while(2) -> switch (2) case

while on switch (2), how to break out of while (2) while being inside case?

πŸ‘︎ 5
πŸ’¬︎
πŸ“…︎ Oct 29 2021
🚨︎ report
What is an example of nested loop?

I kind of get the concept but can anyone give a simple example? Thank you.

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/DaikonAble2048
πŸ“…︎ Nov 21 2021
🚨︎ report
Nested Loop Join explained (reupload without background music) youtube.com/watch?v=cKVX_…
πŸ‘︎ 21
πŸ’¬︎
πŸ‘€︎ u/Rowward
πŸ“…︎ Jul 29 2018
🚨︎ report
Decorrelating SQL subqueries (i.e. compiling them without nested loops) scattered-thoughts.net/wr…
πŸ‘︎ 13
πŸ’¬︎
πŸ‘€︎ u/alexeyr
πŸ“…︎ Oct 24 2021
🚨︎ report
[QED] Lamb shift how to do nested two loop integral?

I am trying to solve the double loop integral in this Feynamn diagram:

https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.mdpi.com%2F2218-2004%2F7%2F1%2F28%2Fhtm&psig=AOvVaw3rnJm5AfCHQ9H2ULAMjqQk&ust=1639348468700000&source=images&cd=vfe&ved=0CAsQjRxqFwoTCKju35Pn3PQCFQAAAAAdAAAAABAD

It is the diagram on the right. The issue I have is that after writing down the integral using Feynman rules, I am always left with a 1 or more Dirac matrix in the numerator that I cannot get rid of. This seems to boil down to having an odd number of fermion propagators so I get terms such as q_slash * q_slash * q_slash which gives q^2 * q_slash. Does anyone know how to solve this or have a source for any similar examples please?

πŸ‘︎ 3
πŸ’¬︎
πŸ“…︎ Dec 11 2021
🚨︎ report
Is it worth unrolling two nested for loops that increment by 0.005 and have multiple nested if statements?

I'm trying to speed up performance on my program. When it gets to those two loops, it can take a good 20 seconds or more to finish running. I have it set up where it only needs to go through those loops once, but eventually, it will need to go through those loops a hundred or more so times. To get a feel for how long the loops are, those loops combined will increment at the most 6,304,360,000 times.

I have only done basic loop unrolling, but with integers. With floating points, I feel like it could make the numbers less accurate. With nested for loops with a bunch of nested if statements inside, I feel like the amount of time figuring out how to unroll that would be too much.

πŸ‘︎ 10
πŸ’¬︎
πŸ‘€︎ u/2Bit_Dev
πŸ“…︎ Oct 09 2021
🚨︎ report
Getting nested object in new style for loop

I have this construction:

class Element
{
    public:
        T const &amp; getT();
        U const &amp; getU();
        V const &amp; getV();
    private:
        T t;
        U u;
        V v;
};

std::vector&lt;Element&gt; collection = getCollection();

I have to do work on each T in the collection:

for(auto itr = collection.begin(); itr != collection.end; ++itr)
{
    const auto &amp;  t = itr-&gt;getT();
    //do work with t
}

I would very much like to replace it with a modern style loop

for(auto const &amp; t : collection)
{
    //do work with t
}

But I cannot for the life of me think how to pull that off; is there something I can do here?

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/Shieldfoss
πŸ“…︎ Oct 20 2021
🚨︎ report
A little confused about nested loops and how they break? Swift Playgrounds.

Hello! I’m doing swift playgrounds, I completed Learn to Code 1. I’m currently working on Learn to Code 2 but I keep getting stuck on β€œoptimally” exiting loops? I can solve the challenges in other ways but always look up multiple solutions and this seems to be the only aspect I’m getting hung up on.

I used quite a few nested while loops and I was able to either meet a condition to break the loop such as toggling the switch at the end or being blocked a specific way. I was also able to just use a break statement (not taught in LTC1).

In Learn to Code 2, Incrementing the Value, Apple’s solution is this:

var gemCounter = 0

while !isBlocked {

while !isBlocked {

if isOnGem {

collectGem()

gemCounter = gemCounter + 1

}

moveForward()

}

turnRight()

}

I apologize for the poor formatting as I’m on mobile. I’m just stuck on understanding how this loop is broken? Here is an image of the code and visual of the challenge: https://imgur.com/a/0L0uUGH

πŸ‘︎ 5
πŸ’¬︎
πŸ‘€︎ u/systemdylan
πŸ“…︎ Dec 02 2021
🚨︎ report
When nested for loops are all you know youtu.be/sZuWHlqyZFA
πŸ‘︎ 22
πŸ’¬︎
πŸ‘€︎ u/ZFudge
πŸ“…︎ Oct 23 2021
🚨︎ report
Can anyone tell me why my third nested loop is not working?

______________Question

Given an array arrl] of n integers. Check whether it contains a triplet that sums up to zero. Example 1: Input: n = 5, arrl] = {0, -1, 2, -3, 1} Output: 1 Explanation: 0, -1 and 1 forms a triplet with sum equal to 0. Example 2: Input: n = 3, arr[] = {1, 2, 3} Output: 0 Explanation: No triplet with zero sum exists.

β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”my solution

class Solution:

Function to find triplets with zero sum

def findTriplets(self, arr, n):

code here

for i in range(0,n-1,+1):
    for j in range(i+1,n-1,+1) :
        for k in range(j+1,n-1,+1):
            Γ—=arr[i]+arr[j]+arr[k]
            if x==0:
                print(x) 
                return 1
            else:
                return 0
πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/makesyoucurious
πŸ“…︎ Oct 19 2021
🚨︎ report
Figuring out a nested while loop

Hello! So I need to do a while loop in order to figure out how many rows in a file there are and the total count of numbers in that file and I figured it out mostly. I have two whiles that if I take away (delete) the other then will work but if i have two of them in at the same time only the first one works and the second wont even begin

#include <iostream>
#include <string>
#include <fstream>
int main() {
int count = 0;
int line_number = 0;
int number=0;
std::string line;
std::string copy;
std::ifstream infile("input1.txt");
while (std::getline(infile, line)) { // where the problem begins
line_number++;
}
while (infile >> number) {
count++;
}
std::cout << "count:" << count << std::endl;
std::cout << "Number of rows in text file: " << line_number << std::endl;
return 0;
}

the problem starts in while(std::getline(infile, line)). Ive been stuck on this for awhile, if anyone could explain to me how to make while loops function together without disrupting the other I would really appreciate it

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/MajiYama
πŸ“…︎ Oct 31 2021
🚨︎ report

Please note that this site uses cookies to personalise content and adverts, to provide social media features, and to analyse web traffic. Click here for more information.