FAQ Database Discussion Community


R - How to show progress in nested loops?

r,progress-bar,nested-loops
I am performing two loops in R: the external one is over 5 directories and the internal one is over the 15 files existing in each directory. My question is: how to display the progress of the task in this scenario? Please see the following example: # these are the...

nested loops pattern java

java,nested-loops,bluej
I have been struggling with this pattern,trying to use only the code required for a nested FOR loop. I am required not to use patterns,just a nested for loop: 123454321 1234 4321 123 321 12 21 1 1 The code required is Java and I am using BlueJ compiler....

Trouble with loops in a program to find prime numbers

c#,loops,console-application,nested-loops
Hi I have been having a problem working out how to get this to work. It's intended to find the first x number of prime numbers using a user input to set x. It will then place any in an array before printing the results. I think I have made...

Avoid 'index not in range' on nested loops encrypting chunks of string

python,nested-loops
for i in range(n): for j in range(o): orderedList.append(newStringList[j][i]) I'm a beginner Python programmer I have an encryption problem to solve, in which I must split a string into chunks of n size, then add the first index of each to a list, then the second index of each, etc....

ColdFusion - Looping through a nested structure in an array

arrays,json,coldfusion,structure,nested-loops
I have a json retuned from an external API: { "data" : { "consignmentDetail" : [ { "consignmentNumber" : "5995600864", "parcelNumbers" : [ "15505995600864" ] } ], "consolidated" : false, "shipmentId" : "60764454" }, "error" : null } I can get the shipmentId value by deserializing the JSON and grabbing...

My Nested For Loop is not working [duplicate]

java,for-loop,nested-loops
This question already has an answer here: ArrayIndexOutOfBoundsException 7 answers So i am creating a deck constructor for a card game in which the for loop is not working. This is the code for it, and disregard the third integer variable in the constructor for it does not solve...

Java - Printing an unfilled diamond using nested for loops

java,loops,nested-loops
I am new to learning Java and I am trying to print an unfilled diamond using asterisks. The height of the diamond has to be based on user input. My code currently prints out a filled diamond based on user input but I cannot figure out how to print an...

Difference in two for nested loops.(C++)

c++,nested-loops
I tried to solve the following problem: Let x,y,z be integers in the domain [-5,5]. Display the number of solutions (x,y,z) that satisfy 3*x+y^3-z^2=0. My initial solution was this: int main() { int x=-6; int y=-6; int z=-6; int p=0; for(int i=-5; i<6; i++) { x++; for (int j=-5; j<6;...

Jquery getting nested inputs of Div, placing in Object

javascript,jquery,nested-loops
I am at my wits end with this nested loop. I am trying to create an object with nested objects in it grouped by the containing div id. So far this is what I have: $('#survey-submit').on('click', function (e) { var formData = {}; var item = {}; $("div[id^='question-']").each(function () {...

Nested foreach loops to get info from nested lists using C#

c#,xml,foreach,nested-loops,nested-lists
An object EmployeeInfoDocument contains a list of groups. Each group holds a list of employees. I am trying to use a nested foreach loop to write the values out to an XML file. It seems that I have the syntax wrong on the inner foreach loop. Visual Studio is giving...

Pull data from nested json loop php

php,json,foreach,nested-loops
Ok, I have been fighting this for two days now!! Here is my Json structure. [ { "uuid":"/random number==", "meeting_number":7196503037, "host_id":"random number", "topic":"My's Personal Meeting Room", "start_time":"2015-01-06T22:01:07Z", "timezone":"America/Denver", "duration":56, "total_size":378080, "recording_count":1, "recording_files":[ { "id":"long number", "meeting_id":"/NS90bsSTLeGzo6cT0nwXw==", "recording_start":"2015-01-06T22:01:09Z", "recording_end":"2015-01-06T22:01:14Z", "file_size":378080, "play_url":"https://myurl" } ] },...

How to flatten a 2-dimensional array into a 1-dimensional array

java,arrays,for-loop,multidimensional-array,nested-loops
How would i transfer a 2d array into a 1d array in java. I have the code for the 2d array but dont know where to start. The output of the 2d array is a 8 by 10 grid with the numbers going from 1-80. public class move { public...

nested while loops php mysql

php,mysql,nested-loops
I have this code: <?php if( isset($_POST['groups'])){ $groups = $_POST['groups']; $subject = $_POST['subject']; $sql="SELECT a.groupcode, a.groupstudents, a.studentid, b.groupcode, b.coursename, b.studentid, b.date, b.class1, b.attend, b.attendno FROM table_1 a, table_2 b WHERE b.groupcode = '$groups' AND b.coursename = '$subject' AND (a.studentid = b.studentid AND a.groupcode = b.groupcode)"; $result=mysqli_query($GLOBALS["___mysqli_ston"], $sql); ?> <table width="100%"...

I tried coding my own simple moving average in C++

c++,algorithm,while-loop,nested-loops,moving-average
I want a function that works. I believe my logic is correct, thus my (vector out of range error) must be coming from the lack of familiarity and using the code correctly. I do know that there is long code out there for this fairly simple algorithm. Please help...

Printing a checker board with nested loops. [Java]

java,nested-loops
I'm having issues with getting my code to print. I need to print a checker board with a grid the size of a user input. Example of what it should output. Input a size (must be larger than 1): 5 0 * * * 1 * * 2 * *...

javascript variable in array 2d in nested loop is missing

javascript,arrays,multidimensional-array,nested-loops
I create dynamic table then store value. But I found final array is mistake. I want to somebody help and expand problem. Why x in x before loop = [[]] not [["111", "0", "0"]]. x = []; $(document).on('click', '#save', function(event) { x.length = 0; var y = []; for (var...

How to process results, results of results , results of results of results etc with a single loop

bash,loops,if-statement,nested-loops
I need to create a certain loop which will to some extend describe a network with all its nodes. This loop will be part of something else which is not relevant to the topic. As you know in a network one node is connected to another and so on. I...

Inability to pass values in variable between inner and outer for loops python 3.3

for-loop,global-variables,pass-by-reference,nested-loops,python-3.3
I'm attempting utilizing TeamTreehouse learning subscription & this Starting Out With Programming Logic And Design book to attempt learning programming & python. Please don't shoot to kill me I'm having difficulty with repetition structures! Goal: I'm attempting to collect input from a user in the outer for loop. The inner...

For Loop error in r

r,for-loop,nested-loops,markov-chains,markov
I am trying to simulate a markov chain by using code that wasnt made for it. My for loop is not correct and I continue to get error messages but I kept track of the brackets and syntax but I cannot quite put my finger on the issue. The matrix...

What's the correct way to print a matrix with labels in a Django template?

django,django-templates,django-views,nested-loops
I want to do something very simple in Django: Print a matrix as an HTML table, and add labels for the rows and columns. These are the variables in my view: matrix = np.array([ [101, 102, 103], [201, 202, 203], ]) colnames = ['Foo', 'Bar', 'Barf'] rownames = ['Spam', 'Eggs']...

Tricky loop through database entries in a JAVA method

java,loops,nested-loops
I'd like to loop through the following table (this loop is not the problem) The method should return "success" to me, if one of the items with the same IDs (ID1 and ID2) is on success and all other items are also on success. See the picture above one 7...

Creating a Christmas Tree using for loops

java,for-loop,nested-loops
I am trying to make a christmas tree using for loops and nested for loops. For me to do that I need to be able to make a pyramids with *. I have tried countless times and I am having problems making one. Here is my code: for(int i=1;i<=10;i++){ for(int...

Python initializing variable in a nested loop

python,increment,nested-loops
i want the the variable genCounter to reset to zero when the iteration of the inner loops has completed. however it returns the first value of genreSet and does not go farther to increment the genCounter variable. kawa is a genrator object. Thanks in advance.. kawa = self.getFile() genList =...

Define the loops at run time

c++,algorithm,nested-loops
consider this arrays, e.g. #include <iostream> #include <vector> int main(int argc, char* argv[]) { std::vector<char> ls(3); ls[0] = 'a'; ls[1] = 'b'; ls[2] = 'c'; std::vector<char> us(3); us[0] = 'A'; us[1] = 'B'; us[2] = 'C'; std::vector<int> ns(3); ns[0] = 1; ns[1] = 2; ns[2] = 3; std::vector<char>::const_iterator lIt; std::vector<char>::const_iterator...

Alternatives to nested ifelse statements in R

r,loops,if-statement,nested-loops
Suppose we have the following data. The rows represent a country and the columns (in05:in09) indicate whether that country was present in a database of interest in the given year (2005:2009). id <- c("a", "b", "c", "d") in05 <- c(1, 0, 0, 1) in06 <- c(0, 0, 0, 1) in07...

jquery each loop through array with multiple objects

jquery,arrays,each,nested-loops,javascript-objects
I have a javascript array of multiple objects like the one bellow : var myArray = [{ year:'2015', model:'BMW', used:false, extras: [{buckets:'no',sportWheels:'yes'},{buckets:'no',sportWheels:'yes'}], color:'blue' ..... }]; What i am trying to do is to loop this array and pass the results into a list, something like this : $.each(myArray, function(i, e){...

Why does this loop return a value that's O(n log log n) and not O(n log n)?

loops,for-loop,time-complexity,nested-loops,asymptotic-complexity
Consider the following C function: int fun1 (int n) { int i, j, k, p, q = 0; for (i = 1; i<n; ++i) { p = 0; for (j=n; j>1; j=j/2) ++p; for (k=1; k<p; k=k*2) ++q; } return q; } The question is to decide which of the...

Scraping: scraped links - now unable to scrape and dump html files into a folder

python,html,selenium,for-loop,nested-loops
Using Python, Selenium, Sublime and Firefox: I am scraping the links off of this website and would like to save the scraped pages (as html files) into a folder. However, I have been working for days on trying to get the body of these html files to dump into a...

Draw a column chart using Google Charts for this JSON var_dump(); data

php,json,mysqli,google-visualization,nested-loops
How can I put the below PHP-JSON code into a column chart using Google-Visualization? <?php /* Connect to database */ $mysqli = new mysqli("localhost","root","123","charts"); if(mysqli_connect_errno()){ trigger_error('Connection failed: '.$mysqli->error); } /* Build the query */ $query = "SELECT a.item_code,a.total,a.date FROM chart_values a, (SELECT DISTINCT item_code FROM chart_values GROUP BY item_code,date) b...

Nested loops: Print seats in java

java,nested-loops
Given numRows and numCols, print a list of all seats in a theater. Rows are numbered, columns lettered, as in 1A or 3E. Print a space after each seat, including after the last. Use separate print statements to print the row and column. Ex: numRows = 2 and numCols =...

Nested Loop is skipped within Function

javascript,html5-canvas,nested-loops,keydown
In a basic HTML/Javascript game, when moving my character I want to adjust AI movement so their speed/position is relative to the character's, not the canvas. My code works fine but only for whichever key's function is listed last. //Left button if (37 in keysDown) { if (robot.x <= 400)...

C++ Loop will run at most once

c++,pointers,for-loop,iterator,nested-loops
I'm not sure why this loop won't run al the way through. I'm learning c++ and this is also the first time I've used pointers. Any feedback is appreciated. Goal of the program is to take two random numbers 0-200, take the difference, and add it to the vector. Then...

Calculation with Nested loops in R

r,nested-loops
I have a Geocode dataset with three columns: Latitude, Longitude and Cluster. I calculated the average center of the clusters and store the results in two lists Center_lat and Center_lon. Now I wanna calculate the distance from each observation(3000+) to each cluster center(30) with the Haversine formula. To get a...

Printing out multiplication table in python

python,multiple-columns,nested-loops
Currently I'm doing this problem and I've ran into errors. I decided to practice my nested for loop logic with somewhat of a more complicated strategy even though there are several easier methods. I'm a beginner coder so I hope my documentation is not confusing on my thought process. import...

Write a C++ program using nested loops to output the following numbers to the screen?

c++,nested-loops
I wrote a C++ program, but the output I got was unexpected (as shown below). #include<stdio.h> #include<iostream> #include<iomanip> using namespace std; main() { int a,b; for(a=3;a<=21;a+=2) { printf("\n"); for(b=1;b<a;b+=2) { cout<<setw(2)<<a+b-1<<" "; } } cout<<"\n"; } Can someone help me tweak it, so it runs like this: ...

Speed-efficient classification for complex vectors in MATLAB

matlab,optimization,vectorization,nested-loops,pdist
I am trying to optimize this piece of code and get rid of the nested loop implemented. I am finding difficulties in applying a matrix to pdist function For example, 1+j // -1+j // -1+j // -1-j are the initial points and i am trying to detect 0.5+0.7j to with...

Why are my nested for loops taking so long to compute?

algorithm,matlab,time,big-o,nested-loops
I have a code that generates all of the possible combinations of 4 integers between 0 and 36. This will be 37^4 numbers = 1874161. My code is written in MATLAB: i=0; for a = 0:36 for b= 0:36 for c = 0:36 for d = 0:36 i=i+1; combination(i,:) =...

matlab : vectorize 4D matrix sum

performance,matlab,matrix,vectorization,nested-loops
I need to perform in MATLAB the following calculation: where w and v are vectors with N elements and A is a four-dimensional matrix (N^4 elements). This can be achieved by the following pedantic code: N=10; A=rand(N,N,N,N); v=rand(N,1); w=zeros(N,1); for pp=1:N for ll=1:N for mm=1:N for nn=1:N w(pp)=w(pp)+A(pp,ll,mm,nn)*v(ll)*v(mm)*conj(v(nn)); end end...

Nested For-Loop Not working Java

java,for-loop,nested-loops,minecraft
I don't know if I'm right here, so if not, please feel free to delete this question. I want to iterate over a 2-Dimensional Plane of Blocks in a Minecraft Plugin written in Java. Therefore I want to go through every Block in every Row. The following is my code....

Findings letters that match in every sublist

python,for-loop,collections,nested-loops,nested-lists
candidates = ['A', 'B', 'C', 'D'] If a candidate appears in every sublist at least once they must be returned listOfData = [['B','C','B','A'], #D is no longer a candidate ['B', 'C', 'B', 'D'], #A is no loner a candidate ['A','D','C','B'], # B and C are still candidates ['D', 'C', 'B',...

Java Lambda Expression for Nested Loops with Conditional

java,lambda,java-8,nested-loops
I am new to lambda expressions and am trying to use them to reduce the following code to the lambda equivalent. I have looked into reduce and flatMap and forEach, as well as several other things, but I am obviously missing something because everything that I try is either syntactically...

Having issues with printing a nested loop

java,nested-loops
I am trying to print a nested loop that will print two islands and scale depending on what the input is. The goal is to make Exclamation points(!) to make the left island, a line diagonally of asterisks(*), question marks to make the right island and tildas(~) to make the...

increment $x across multiple nesting loops

php,loops,foreach,nested-loops
To list all categories on my website I iterate through category hierarchy with the following function: $x = 1; function list_categories($categories, $x) { foreach($categories as $category) { $cat_list .= '<li>'.$category['name'].'<li>'; if (count($category['children']) > 0) { $cat_list .= '<ul>' list_categories($category['children'], $x); $cat_list .= '</ul>' } $x++; // incremention of $x }...

Iteration loop inside another loop

java,iterator,nested-loops
Is there any way I can use an Iterator inside another loop? I am asking this because I can't find a way to bring the iterator at the start of the list again after the first loop is done and therefore at a second loop the iter.hasNext() will give me...

Asterisk in Nested loops, Java

java,eclipse,asterisk,nested-loops
I am trying to make my code print out the Asterisk in the image, you see below. The Asterisk are align to the right and they have blank spaces under them. I can't figure out, how to make it go to the right. Here is my code: public class Assn4...

6x6 Bingo game: When a drawn number is on the card, add +1 to the 7th column and row of the drawn number

php,arrays,multidimensional-array,nested-loops
I'm making a simplified bingo game with PHP filled with 6x6 random numbers between 10 and 70. Each row is in it's own range (e.g. 10-19, 20-29 etc.) The bingo game is supposed to play like this: The card gets filled with numbers Numbers get drawn randomly If the card...

Creating N nested for-loops

c++,algorithm,for-loop,recursion,nested-loops
Is there a way to create for-loops of a form for(int i = 0; i < 9; ++i) { for(int j = 0; j < 9; ++i) { //... for(int k = 0; k < 9; ++k) { //N-th loop without knowing N at the compile time. Ideally I'm trying...

How can I fix my issue with my nested for loop program?

c++,for-loop,nested-loops
The end of my program is supposed to show the amount of ways I can make change for a dollar using nickels, dimes, quarters, and fifty-cents. Whenever I run my program, it gives me a really huge number and I don't know why. It's supposed to be around 40 something...

Looping through a nested NSMutableDictionary and filtering some items

ios,objective-c,loops,nested-loops,nsmutabledictionary
I have been stuck here for a while trying many things without any success. So i have a nested dictionary that looks like this: {"Div 3 Mellersta G\u00f6taland, herrar": { "0": {"awayScore": "0", "homeTeam": "Hestrafors IF", "tempTime": "12:00", "homeScore": "0", "awayTeam": "Gunnilse IS", "time": "90'", "events": []}, "1": {"awayScore": "0",...

R: For Loop within a For Loop, rebuilding and exporting the output each round

r,csv,for-loop,nested-loops
So, I am new to R. I am trying to make something that reads a patient ID from a list of patients listx, extracts the corresponding column (column name = name of patient) in matrix 1 (genomicmatrix), and then runs a row-by-row statistical analysis between that column from genomicmatrix and...

Unable to return value from nested function in Javascript

javascript,function,return-value,nested-loops
Hey guys i prepare a project with html5 geolocation that will calculate the distance. I've got a problem with returning value from nested function in Javascript, can anyone help me ? Here is my code: /* DISTANCE CALCULATOR FUNCTION */ function distanceCalc(latitudeB,longitudeB) { var result; if (navigator.geolocation) { navigator.geolocation.watchPosition(showPosition); }...

why nr ∗ bs + br for block transfer in worst case Nested-Loop Join?

database,join,nested-loops
Considering the following join algorithm: For each r ∈ R do For each s ∈ S do if r.C = s.C then output r,s pair nr is the number of tuples in R, br is the number of blocks in R The textbook say that in worst case, the buffer...

Drawing a Vertical Pyramid in C

nested-loops,control-structure
I have to get the desired output as follows: 1 2 6 3 7 10 4 8 11 13 5 9 12 14 15 But I can't seem to figure out how to do it. All I get is: 1 2 6 3 7 6 4 8 7 6 5...

Traverse over a nested Dictionary using the nested dictionary as key in c# via Linq

c#,linq,dictionary,nested-loops
so I have the following situation: I have a Dictionary like this: Dictionary<Dictionary<string, string>, DateTime> expireDates = new Dictionary<Dictionary<string, string>, DateTime>(); where the inner dictionary'first string is filled by a value (lets call it articlenumber) and the second string is filled by a value named articleCode. Together, they are the...

Nesting aggregate within apply to aggregate multiple columns by multiple variables in R

r,aggregate,nested-loops,apply,summary
I have a dataframe with sets of scores, and sets of grouping variables, something like: s1 s2 s3 g1 g2 g3 4 3 7 F F T 6 2 2 T T T 2 4 9 G G F 1 3 1 T F G I want to run an...

Why will this only work with break;?

loops,nested-loops,break
1) Write a program that asks the user to enter the number of pancakes eaten for breakfast by 10 different people (Person 1, Person 2, ..., Person 10). Once the data has been entered, the program must analyze the data and output which person ate the most pancakes for breakfast....

Looping over pairs of values in bash

bash,for-loop,nested-loops,paste
I have 10 text files and I want to paste each file with its pair, such that I have 5 total files. I tried the following: for i in 4_1 5_1 6_1 7_1 8_1 do for j in 4_2 5_2 6_2 7_2 8_2 do paste ${i}.txt ${j}.txt > ${i}.${j}.txt done...

Java Finance Application Project [closed]

java,file,project,nested-loops,finance
I have a java project that is like the following, I am struggling with it when having the loop over the menus and putting the data in a file. that file must be read later to create a bar graph out of it. please please help, much appreciated A. Get...

How to add a Nested xml element

php,mysql,xml,multidimensional-array,nested-loops
I'm on the home stretch of putting together an xml property listing feed that a syndicator will use to publish our listings. I'm using Cakephp, but not using the Cakephp xml tools. Just couldn't get the output formatted how I need it. So I have a very simple query. (many...

parse Json and create html with similar content

jquery,arrays,json,multidimensional-array,nested-loops
I have a json file and need to generate html of it. <code>{ "Exhibitors": { "Exhibitor": [ { "LOGO": "logo1.jpg", "TYPE": "Exhibitor" }, { "LOGO": "logo2.jpg", "TYPE": "Exhibitor" }, { "LOGO": "logo3.jpg", "TYPE": "silver" }, { "LOGO": "logo4.jpg", "TYPE": "gold" } ] } }</code> I need to create 1 list...

JavaScript: How to push data in array, into subarrays with an array for each 16 items [duplicate]

javascript,arrays,nested-loops
This question already has an answer here: Split array into chunks 9 answers I have an example data set. I want to push this data into an array with a subarray for every 16 pieces of data. I got started, but am stuck. Any ideas? [ [16 names], [16...

How to make variable value available in a second nested while loop?

php,arrays,loops,while-loop,nested-loops
I currently have a while loop which has another while loop running inside of it, I want to reference a value which is changed by the first loop each time the second loop is run. $counter = 0; $counter2 = 2; while ($counter < 7) { $name = 0; while...

Implementation of nested summing in python

python,nested-loops
I want to implement summation from this publication which is denoted as formula 29. As you may see there are 5 nested summations. Now I struggle to implement that. According to what I understand from my teacher, I should nest it in following way: B=0. for beta in range(): coeff1=......