I have a for loop with length 20.
I have a height of 800. I want to put a value 20 times separated by the same gap.
For example:
800 / 20 = 40
Every 40 I want to println the value. 40, 80, 120, 160... until 800.
I don't understand how to do this inside a loop. My approach is wrong and does not have the same gap between them.
for (int i = 0; i < array.size(); i++) {
int posY = (i != 0) ? 800/ i : 800;
println(posY);
}
you can use de Modulo Operador. more info
if(i % 40 == 0){
println(posY);
}
Math Explanation of Modulo here
Well there are imho three different aproaches. Which one depends on what else you need to do with i.
1) Use i directly:
for (int i = 40; i <= 800; i+=40) {
println(i);
}
This asumes that you don't need nothing else but the 20 numbers.
2) you need to count:
for (int i = 1; i <= 20; i++){
println(i*40);
}
2b) application eg. if 800 is in a variable:
for (int i = 1; i <= 800/40; i++){
println(i*40);
}
This assumes you need to track which step you are taking and want to do something with i.
3) you need the steps inbetween for something
for (int i = 1; i <= 800; i++) {
if(0 == i%40 ){ //if the rest of i/40 gives 0
println(i);
}
}
This last version prints the same numbers but still i goes over all values inbetween.
Plus if you have an array you need to iterate over:
replace the 800 with "array.length -1"
OR
replace the "<=" by "<" and use "array.length" above.
(And well there are a whole lot of variations of this)
Related
Lets assume n=20
so after every 6 iterations I will do some processing
int i=0
for (t=6;t<20;t=t+6){
while(i<=t){
will do some processing
i++;
}
}
In the above code it will terminate when t=18, but I want to continue until 20.
How to do that ?
You are increasing the t variable 6 units... the last condition that satisfies the t<20 is when t = 18.
instead of doing t+=6 do a normal t++ and play with the modulo %6
example:
public static void main(String[] args) {
int n = 20;
for (int i = 0; i < n; i++) {
//TODDY
insert your while in here depending on when that must be executed
if (i % 6 == 0) {
System.out.println("am on a 6 modulo step..." + i);
} else {
System.out.println("foo#" + i);
}
}
System.out.println("done");
}
The behaviour is correct only.. Still if you want to perform any operation, do it after the condition is met, try below snippet:
int i = 0, n = 20;
do{
i += 6;
System.out.println(i);
} while (i < n);
System.out.println(i);
your code is not doing something every 6th iteration, but instead you are doing (n - n%6) times. your "will do some processing" is inside the while. If you add a print (or debug) there you will notice it; on the n=20 example the while will be executed 18 times; it will do something 18 times.
if you want to execute every 6th iterations, and include one extra for the cases that are not exactly divisible by 6, then you could do:
if (n == 0) {
return;
}
int number_iterations = n/6 + (n%6!=0 ? 1:0);
for (int i=0; i<number_iterations; i++) {
// do something
}
That covers what you requested; if not, pls edit question to be more clear on your exact needs.
I want to loop infinitely using a for loop if a number equals 0, and loop until that number number if the number is greater than 0. Here's the code to help visual what I'm getting at.
for (int i = 0; i < this.getNumRounds(); i++) {
// 30 some lines of code
}
or
for ( ; ; ) {
// 30 some lines of code
}
if getNumRounds() is greater than 0, do the first loop, if it equals 0, do the second. I would prefer to do this without copying and pasting my 30 some lines of code twice and using an if statement seeing as the code is redundant, though I could use a function to take out that redundancy, but I'm looking to see if there's another option.
Use the powerful ternary operator:
for (int i = 0; this.getNumRounds() == 0 ? true : i < this.getNumRounds(); i++) {
// 30 some lines of code
}
As noted in the comments by yshavit, there is a shorter, cleaner way of expressing this:
for (int i = 0; this.getNumRounds() == 0 || i < this.getNumRounds(); i++) {
// 30 some lines of code
}
Have you thought about using a while loop instead?
int i = 0;
while(i < this.getNumRounds() || this.getNumRounds() == 0) {
//some 30 lines code
i++
}
So you want something like this:
int num = //whatever your number equals
if (num == 0) {
boolean running = true;
while (running) {
doLoop();
}
} else {
for (int i = 0; i < num; i++) {
doLoop();
}
}
private void doLoop() {
//some 30 lines of code
}
This code puts the contents of the loop in a separate method and checks if the number is equal to 0. If it is, the program runs the doLoop() method forever. Otherwise, it runs until i equals the number.
While it would be better to just create a method and use an if-statement you could add an if statement inside the for-loop to decrease i every iteration. It would look like:
for (int i = 0; i <= this.getNumRounds(); i++) {
if(this.getNumRounds() == 0){
i--;
}
// 30 some lines of code
}
Notice I changed i < this.getNumRounds() to i <= this.getNumRounds. This way if the number of rounds is zero then the loop will be called.
You could do the following.
for (int i = 0; i < this.getNumRounds() || i == 0; ++i) {
do {
// 30 lines of code
} while (this.getNumRounds() == 0);
}
If getNumRounds is non-trivial to compute, consider pulling it out of the loop and calling it only once.
for (int i = lo; i <= hi; i++)
{
boolean isPrime = true; // each value of i starts out assuming it IS prime
// Write a loop below that divides i by 2,3,4,5 etc upto i/2
// If at any time you find a divisor that evenly divides i
// Then set isPrime to false
/* your prime checking loop HERE */
for (int j = 2; j <= hi / 2; j++)
{
if (i % j == 0)
{
isPrime = false;
}
}
// DO NOT REMOVE OR MODIFY LINE BELOW
if ( isPrime )
System.out.print( i + " " );
}
Okay, here is the code I currently have and i'm assuming the problem lies within. The program takes a text input file and sets the first value as lo (in the text demo I have, the lo = 3 and hi = 73.) For whatever reason, the only numbers that are output as 'prime' start at 41 and then go totally fine after that. I have no idea why the first half of the numbers aren't being outputted at all.
Keep in mind I must use for loops for this project, methods and such are not in the 'vocabulary' at the moment. Trying to keep it simple. I'd appreciate the help guys.
Read the comment block again. It says to loop until i/2. You're looping until hi/2.
The issue is that you keep using modulus of the number on itself.
3 % 3 is zero, but 3 is prime.
the prime checking loop, choose one:
for (int j = 2; j < i / 2; j++)
or
for (int j = 2; j <= sqrt(i); j++)
I have a String array like this:
one
twoo
three
four
five
six
seven
eight
nine
For each 3 elements, I want to create a new object setting fields of that object to the elements. For example:
one
twoo
three
would be used like:
obj.setOne("one");
obj.setTwoo("twoo");
obj.setThree("three");
I think that I have to use one for inside other but I donĀ“t know how.
I have tried like this but bad result:
ArrayList<MyClass> myobjects;
MyClass my_object = new MyClass();
for (int z = 0; z < myarray.size(); z++) {
for (z = 0; z < (z + 3) && z < myarray.size(); i++) {
if (i == 0) {
mipartido.setAttributeOne(datos.get(i));
}
else if (i == 1) {
mipartido.setAttributteTwoo(datos.get(i));
}
else if (i == 2) {
mipartido.setAttributeThree(datos.get(i));
}
myobjects.add(mipartido);
}
}
The simplest approach is to use one loop but iterate by 3:
for (int i = 0; i < myarray.size() - 2; i+=3) {
mipartido.setAttributeOne(myarray.get(i));
mipartido.setAttributeTwoo(myarray.get(i+1));
mipartido.setAttributeThree(myarray.get(i+2));
}
FYI: The English word for the number 2 is spelled "two".
You should try to only use one loop iterated by 3 if you're sure that myarray will always have a size equals to x*3.
MyClass mipartido;
for (z=0; z< myarray.size(); z+=3){
Then on the beginning of each iteration, you have to recreate a new mipartido object ( but declare it before the loop)
mipartido = new MyClass();
mipartido.setAttributeOne(datos.get(i));
mipartido.setAttributteTwoo(datos.get(i+1));
mipartido.setAttributeThree(datos.get(i+2));
myobjects.add(mipartido);
}
By using this, your ArrayList should be filled with 3 mipartido objects, all diferents.
But remember that your "myarray" size must be a multiple of 3.
I really like Bohemain's answer, but I wanted to suggest an alternative using the Modulus operator (that I think OP was going for in the original post).
for (int i = 0; i < myarray.size(); i++) {
switch (i % 3) {
case 0:
mipartido.setAttributeOne(myarray.get(i));
case 1:
mipartido.setAttributeTwo(myarray.get(i));
case 2:
mipartido.setAttributeThree(myarray.get(i));
}
}
You could do it this way such that your for loop still increments by one each time, but you alternate the method call. As explained here, the operator simply gets the remainder.
So as you increment, the switch statement will work like this:
0 % 3 = 0, 1 % 3 = 1, 2 % 3 = 2, 3 % 3 = 0, etc
for (int i = 0; i < 3; ++i) {
for (int k = 0; k < 7; ++k) {
for (int h = i; h < 4 + i; ++h) {
result = state.getAt(k, h);
if (result == 1) {
++firstpl;
}
if (result == 2) {
++secondpl;
}
if (firstpl > 0 && secondpl > 0) {
break;
}
//y = k;
}
if (firstpl == 0 && secondpl == 0) {
break;
} else if (firstpl > secondpl) {
score += firstpl * firstpl;
//if(state.getHeightAt(y)-3 < 3) score += 3+firstpl*2;
} else {
score -= secondpl * secondpl;
//if(state.getHeightAt(y)-3 < 3) score -= 3+secondpl*2;
}
firstpl = 0;
secondpl = 0;
}
}
basically I have a 7 by 6 grid. I am going through 7 columns and looking at every 4 consecutive blocks vertically. Since there is 6 blocks upward. There is 3 four consecutive block for each column. State.getAt(k,h) takes in a x and y and returns a value.
I don't think you can improve on this, unless you can figure out an alternative representation for this "state" that allows this computation to be performed incrementally.
And since you have failed to properly explained what the state or the calculation actually mean, it is difficult for anyone but you to figure out whether an alternative approach is even feasible. (And I for one am not going to attempt to reverse engineer the meaning from your code.)
OK. For Connect4, the win / lose is a line of 4 checkers horizontally, vertically or diagonally in the 7x6 grid. So what you could do is represent the score-state as an array of counters, corresponding to each of the columns, rows and diagonals in which a winning line could be made. (7 + 5 + 4 + 4 = 20 of them => 20 counters) Then construct a static mapping from an (x,y) position to the indexes of lines that pass through that. When you add a checker at point (x,y) you look up the counters and increment them. When you remove a checker ... decrement.
I'm not sure how that relates to your existing scoring function ... but then I don't see how that function relates to a strategy that would win the game. Either way, you could potentially use the approach above to calculate scores incrementally.