Dreen
Dreen

Reputation: 7236

Generate a specific number sequence

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 but pseudocode or any non-esoteric language will do fine.

Upvotes: 1

Views: 329

Answers (6)

JasonD
JasonD

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

kb_sou
kb_sou

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

Marko Topolnik
Marko Topolnik

Reputation: 200296

Jut for the fun of it, this is how one does it in :

(for [a (reductions + 2 (apply concat (repeat [3 4])))
      b [1 3 5]] 
   [a b])

Upvotes: 1

hmatar
hmatar

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

mrab
mrab

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

TechSpellBound
TechSpellBound

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

Related Questions