A list of puns related to "Block Nested Loop"
// 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!
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 β‘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.
class Main { public static void main(String[] args) {
int weeks = 3;
int days = 7;
// outer loop
for(int i = 1; i <= weeks; ++i) {
System.out.println("Week: " + i);
// inner loop
for(int j = 1; j <= days; ++j) {
// break inside the inner loop
if(i == 2) {
break;
}
System.out.println(" Day: " + j);
}
}
}
}
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 <- 0
for (i in 1:nrow(x)) {
for (g in 1:ncol(z)) {
sum <- 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!
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.
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 β‘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()));
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 >= 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!
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!
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
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
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?
I kind of get the concept but can anyone give a simple example? Thank you.
I am trying to solve the double loop integral in this Feynamn diagram:
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?
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.
I have this construction:
class Element
{
public:
T const & getT();
U const & getU();
V const & getV();
private:
T t;
U u;
V v;
};
std::vector<Element> collection = getCollection();
I have to do work on each T in the collection:
for(auto itr = collection.begin(); itr != collection.end; ++itr)
{
const auto & t = itr->getT();
//do work with t
}
I would very much like to replace it with a modern style loop
for(auto const & 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?
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
______________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:
def findTriplets(self, arr, n):
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
The new update allows you to convert page into markdown string. earlier it used to return list of markdown objects.
Hello everyone, I made a Notion to Markdown convert on top of notion-sdk-js.
at the moment it doesn't support video,embed and tables but will soon be added.Feel free to use it and all sort of feedback are welcomed :)
Github: https://github.com/souvikinator/notion-to-md
Feel free to drop a star β if you liked the project.
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.

