Tagged Questions
Loops are a type of control flow structure in programming in which a series of statements may be executed repeatedly until some condition is met.
2
votes
3answers
118 views
Decrease CPU usage in while loop
I've a application which runs with two threads. The main thread runs in one infinity-while-loop:
while (true) {
try {
ArrayList<Info> infoList = zabbixHandler.APIRequest();
...
2
votes
1answer
41 views
Math Skills Game Advice
I think my code works pretty well, although I'm biased: http://jsfiddle.net/AHKb4/2/
Basic Overview: I'm working on building a math skill game, where the objective is to drag and drop div's to a ...
0
votes
1answer
34 views
How can I remove this for-loop in this competitive FizzBuzz code?
I'v written this code snippet that's part of a code competition.
I want to do the trick without the for-loop, or simply find a way to optimize this code for speed.
for ( i=1; i<=N; i++ )
...
4
votes
3answers
93 views
Do-While loop in Python, with limit on the amount of 'do's
I'm in a location with poor Internet access. In order to ensure that a call to an external service succeeds, I am wrapping the call in a pseudo-do-while in Python. Additionally, I am limiting the call ...
4
votes
1answer
40 views
Locating empty field groups for saving data
The aim of the code below is to see if selected fields are empty so data can be saved in that field. Since I'm making a library system, I wanted to record the basic info on one record (all the books ...
4
votes
1answer
62 views
Optimize MySQL double select inside for-loop
I want to get the number if items with state 4 and 1 from my database for each day between a certain date. Is there a smarter and more performative way than this one?
I am aware that I should use ...
3
votes
2answers
98 views
7 for loops, 9 variables, 7 if statements, and one function
I have a large js function to calculate the number of chips, and which denomination of chips to show as the players chip stack. It's done on the base of 10.
I have chip denominations worth 1, 10, ...
4
votes
1answer
67 views
Optimising Funny Marbles
Problem statement is at http://www.codechef.com/DEC13/problems/MARBLEGF
Lira is given array A, which contains elements between 1000 and 2000.
Three types of queries can be performed on this ...
3
votes
2answers
60 views
Removing redundant lines from script
Context: I've been learning Python for a few months and I'm able to write codes which do work, but they normally look very ugly and contain a lot of unnecessary code. But I normally struggle to find ...
1
vote
2answers
34 views
Better way to display list of categories
I need to display a list of category links, like so:
Category 1, Category 2, Category 3
I've got it working already but the code seems pretty repetitive and a bit of a mess, I was wondering if there ...
28
votes
10answers
1k views
Perform instruction in loop every time except the last time?
The specific issue is this: I am writing to a file and want to output a new line after each line written. If I use a normal loop without any further checks, this will create a blank line at the very ...
2
votes
3answers
79 views
Make code more memory efficient, or shorter
//rename files
if(!empty($_FILES[$desktop_fieldname_1280x800]['name'])){
file_exists($desktop_filename_1280x800 = mb_strtolower($desktop_dir_1280x800 . 'wall_desktop_1280x800_' ...
3
votes
1answer
42 views
Simplifying loop for Incidence Matrix
I had to work in the Transport Problem and we're asked to try to make the fastest code for big matrices, so we're advised to try to avoid loops. And the only one I've got and I cannot imagine how to ...
7
votes
4answers
134 views
Looping Strategy: Change behaviour after first iteration
I have often encountered the following situation. I want to call a method in a Loop, but want to skip the call at the first run. It do not have to be a method, it also can be some lines of code that I ...
19
votes
7answers
973 views
Is it bad practice to increment more than one variable in a for loop declaration?
While coding today, I came across the following loop in C#:
for(int x = 0; x < max_x_index; x++){
for(int y = 0; y < max_y_index; y++, count++){
some2DarrayRepresentedBy1D[count] = ...
5
votes
1answer
79 views
Running a block of code on every interval except the first iteration
I am working with an encryption algorithm that looks like this
The key is a number stored in 4 bytes.
For each byte in the message, XOR it with the corresponding byte in the key
When you reach the ...
1
vote
1answer
83 views
foreach loop too slow?
I have a nested array that returns objects which are then traversed to retrirve the ids, which are then used to retrieve another array, which is traversed and the values returned are echoed out.
The ...
1
vote
1answer
55 views
Getting limited user input, with echo
I've written a code snippet that will get a (max.) 14 character string from the user input, and while the user is typing, simultaneously echo it out to the screen.
It seems a bit long and ugly, so I ...
17
votes
6answers
946 views
How can I make this mess of Java for-loops faster?
I'm trying to find all the 3, 4, 5, and 6 letter words given 6 letters. I am finding them by comparing every combination of the 6 letters to an ArrayList of words called sortedDictionary. I have ...
-1
votes
1answer
58 views
How would I improve this class in terms of responsiveness and performance?
I'm about to release this application as a hobby and I'm wondering how would I improve the speed of the calculations and overall responsiveness of the class?
I have covered a module briefly in data ...
2
votes
1answer
68 views
Drawing a table in Python3
I have created a module to draw text tables. The relevant parts are below and here's the full code for txtable).
class Row(Txtable):
[...]
def format(self, col_widths):
"""Return the ...
2
votes
1answer
92 views
how to test if for loop executed all iterations successfully
This method finds the smallest positive number that is evenly divisible by all of the numbers from 1 to 20. But I am wondering if there is a better way to test if all iterations of a for loop ...
1
vote
2answers
141 views
Calculating a total price by using switch statement and sentinel controlled loop
My homework is to make a program that calculates the total value of products sold. It works, but I use the if statement because it was asking for the quantity on the output before ending the loop. ...
1
vote
2answers
80 views
How to refract a while loop with a necessary initial setting?
I put the readable version into the gist file -> link
Please ignore the print and comment in the following code.
I often have to write this sort of logic: init the conditions, and deep into loop ...
0
votes
1answer
35 views
Connect Four in Ruby - trouble with conditional return value [closed]
I'm writing a 'Connect Four` game in Ruby, and while I've been using Rails for some time, I've never used only Ruby - so you could say I'm a Ruby Noobie. The following method takes an array (the game ...
0
votes
2answers
125 views
Which loop code is better practice?
def minval(xs):
minum = xs[0]
for i in range(len(xs)):
if xs[i] < minum: #difference in code: xs[i]
minum = xs[i]
return minum
or
def minval(xs):
minum = ...
1
vote
1answer
38 views
Approximating square root (loops and functions exercise)
Just looking for some feedback on my solution for Tour of Go Exercise 24 - Loops and Functions. Is there anything that looks like a wrong way to do things in go? anything I could have done better?
...
4
votes
6answers
136 views
which of these 2 blocks is better?
I am looking for some opinions about these two block of code. They do the same thing, they are just written differently. Which one you recon is "better", "faster", more "readable", gives you more ...
3
votes
0answers
50 views
Copying folder contents from several folders
I have a file directory which contains folders for every month, and within those folders are several text files. In this context I would like to copy all of the text files from my January folder into ...
4
votes
2answers
235 views
Please look at this for-loop
I have made a for-loop for a certain task.
I have a listbox and drag items to it (.png image file, in my case).
The for-loop will the go through each item and convert it to .webp through a command ...
2
votes
5answers
151 views
Can I make this VB code run faster?
I need help making this code run faster. I am using it to import a CSV file into Excel. It works, but it is very slow. The file is almost 20MB. Any help is appreciated.
{Sub OpenTextFile()
Dim ...
0
votes
1answer
52 views
Filtering a long list of files through a set of ignore patterns using iterators
I have a backup job that walks across a huge directory with potentially millions of files. Python's os.walk() works just fine.
Now, I have implemented a feature to ignore files based in a black list ...
2
votes
2answers
73 views
Lots of Continues in an Inner Loop and Dictionary of Actions
I'm using ABCPDF (Version 8) to update an existing PDF document and I believe its API is hurting me in this situation and was curious whether anyone had any comments on how this looks as it appears ...
2
votes
2answers
26 views
How to make the end of loop more readable in Ruby
There are some blocks in my code.
To make it easier to read, I often append comment after the end
such as
end # end upto
end # fileopen
Because sometimes the indentation still not easy for ...
0
votes
2answers
109 views
Create nested named object using variables as key
I am trying to create a new object with nested value pairs. My initial challenge is that I have a huge object containing lots of junk data, and I'd like to strip away the value pairs that I do not ...
1
vote
4answers
134 views
Optimal way of skipping certain values in a for loop
What would be the fastest way of skipping certain values in a for loop? This is what I intend to do in its most basic form, with about 20 more keys to omit.
for (var key in arr ) {
if ( key != ...
2
votes
3answers
176 views
Improve nested loop for bio-statistics calculation
I am doing a bio-statistics calculation and the following code works. However, can someone help to improve the messy nested loop?
for(int i=0; i<NN; i++) {
for (int j=0; j<NN; j++) {
...
3
votes
2answers
166 views
Differences between using a do-while vs. while and initializing variables
When I use a do-while loop, I can create a variable userInput, but don't need to initialize it until the do-while loop because it is not used until then.
import java.io.*;
public class Bla
{
...
1
vote
2answers
115 views
Is there a more efficient way of executing PDO statements?
I am working on a small method that saves uploaded images and records the images in a database.
public function setEventImages($event_id){
foreach($_FILES['event-images']['tmp_name'] as ...
0
votes
1answer
145 views
How can I iterate cell value of csv file using Python? [closed]
import csv
ifile=csv.reader(open('C:\Users\BKA4ABT\Desktop\Test_Specification\RDBI.csv','rb'),delimiter=';')
for line in ifile:
row = line
if [True for cell in row if cell=='']:
...
5
votes
1answer
268 views
Reducing cyclomatic complexity
I ran a sonar analysis on my code and it told me the cyclomatic complexity is too high (sonar's limit is ten branches).
Here is my code:
public void myMethod(){
try{
// do something
...
6
votes
1answer
203 views
How to avoid duplication and to keep code clean
Here is my C# code that draws scanline of the image to System.Drawing.Graphics. It's quite simple and it's optimized in order to merge neigbour samples with the same color into single rectangle ...
3
votes
4answers
302 views
Detecting Tic-Tac-Toe win: Enumerate all possibilities or use nested loops?
Currently I have a game that does this and then checks for victory conditions in victoryTable
victoryTable[0] = rows[0][0] + rows[0][1] + rows[0][2];
victoryTable[1] = rows[1][0] + rows[1][1] + ...
4
votes
2answers
109 views
Optimizing if-statement with for-loop
I have been staring at this code for awhile now and I am thinking there is a way to optimize it (namely the if-else statement with the for-loops). Any advice would be greatly appreciated.
...
5
votes
2answers
442 views
Can this foreach loop be improved?
Can the below foreach loop be improved? Since I use the same method twice, maybe use continue or break?
int? index = null;
int count = 0;
foreach (Break b in breaks)
{
if (index.HasValue)
{
...
9
votes
3answers
339 views
Try-catch inside while(true)
I have a situation in which a program, communicating over the network, can timeout or otherwise fail to establish a connection through no fault of my application or its user. If and when this happens, ...
4
votes
3answers
159 views
Does this loop unrolling make sense?
I am coding a Hanning filter which is a recursive relation:
y[i] = 0.25*(x[i] + 2*x[i-1] + x[i-2])
And here is my code were I attempt to unroll 3 times:
public void HanningFilter(float[] array) { ...
0
votes
1answer
65 views
Looping over a list [closed]
I'm new to Python, and I have a small section of code which works fine when outside of a function:
list = [["M4342","Joe"],["M4343","Melanie"],["M4344","Alex"],["","David"]]
for value in list:
...
4
votes
2answers
101 views
Idiomatic loop and break condition
I am calling a C library via P/Invoke. That library needs to be called in sucession with an increasing unsigned int, and returns a pointer. That pointer is then mapped to a managed type, until it ...
1
vote
2answers
96 views
Optimization of a while-loop searching for words in a dictionary
This is my first question here. I'm using an open source program called MElt which lemmatize (give the lemma example:giving-->give) of words. MElt works on Linux and its programmed in Perl and ...