Reputation: 7236
Lets say I have a simple for loop with an index i
that goes from 0
to n
. I want to be able to loop by i
and each loop generate two numbers in the following sequence:
i | a | b
=========
0 | 2 | 1
1 | 2 | 3
2 | 2 | 5
3 | 5 | 1
4 | 5 | 3
5 | 5 | 5
6 | 9 | 1
7 | 9 | 3
8 | 9 | 5
9 | 12| 1
10| 12| 3
11| 12| 5
12| 16| 1
...
Basically, the algorithm is, for a
it starts with 2
and increments by 3
and 4
in turns, whereas for b
it always goes through 1
, 3
and 5
and then starts over.
I have been trying to produce something without much result. I would prefer an answer in java but pseudocode or any non-esoteric language will do fine.
Upvotes: 1
Views: 329
Reputation: 16612
class Main
{
public static void main (String[] args)
{
for(int i = 0 ; i < 20 ; i++)
{
int a = (i / 6) * 7 + 2 + ((i / 3) & 1) * 3;
int b = (i % 3) * 2 + 1;
System.out.println(i + " | " + a + " | " + b);
}
}
}
Upvotes: 3
Reputation: 1057
Try (Answer in C)
int increments[3] = {2, 3, 4};
for(i = 0; i < limit; i++){
if((i/3) % 3 == 0) a += increments[(i/3) % 3];
b = 2 * (i % 3) + 1;
}
Upvotes: 0
Reputation: 200296
Jut for the fun of it, this is how one does it in clojure:
(for [a (reductions + 2 (apply concat (repeat [3 4])))
b [1 3 5]]
[a b])
Upvotes: 1
Reputation: 2429
In C it can be as follows this is easier to read and understand;
#include <stdio.h>
int main(void)
{
int i = 0;
int N = 10;
int a = 2;
int b = 1;
int odd = 1;
printf("i |a | b\n");
for(;i<N;i++) {
if(b == 5) {
if(odd) {
a += 3;
odd = 0;
}else{
a+=4;
odd = 1;
}
}
b +=2;
if(b >5) b = 1;
printf("%d |%d | %d \n", i, a, b);
}
return 0;
}
Upvotes: 0
Reputation: 2728
for(int i = 0; i < n; i++){
int a = ((i + 3) / 6) * 3 + ((i + 0) / 6) * 4 + 2;
int b = i % 3 * 2 + 1;
System.out.println(i++ + " | " + a + " | " + b);
}
Upvotes: 0
Reputation: 2555
Assuming n=20, I have the following solution :
public static void main(String[] args) {
int i = 0;
int n = 20;
for (int a = 2; a <= n; a += 3) {
for (int b = 1; b <= 5; b += 2) {
System.out.println(i++ + " | " + a + " | " + b);
}
}
}
Upvotes: 0