I have the following sequence of numbers:
S1 = N, S2 = S1 + 1, S3 = 2*S1 + 1, S4 = S1 + 2, S5 = S2 + 1, S6 = 2*S2 + 1, S7 = S2 + 2 ...
Using the ArrayDeque<E>
class, I have to write a program to print its first 50
members for given N
.
Examples:
input 2
output 2 3 5 4 4 7 5 6 11 7 5 9 6 ...
This is my code. The problem is that I can't update next S
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Scanner;
public class p04 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numN = scanner.nextInt();
scanner.close();
int counter = 1;
int nexS = numN;
Queue<Integer> fifty = new ArrayDeque<>();
for (int i = 0; i < 50; i++) {
if (i == 0){
fifty.add(numN);
}else {
if (counter == 1){
counter++;
numN = nexS + 1;
fifty.add(numN);
}else if (counter == 2){
counter++;
numN = (nexS * 2) + 1;
fifty.add(numN);
}else {
counter = 1;
numN = nexS +2;
fifty.add(numN);
nexS = nexS + 1;
}
}
}
for (Integer integer : fifty) {
System.out.print(integer + " ");
}
}
}
The way you solve this problem it's easier to solve It with ArrayList. I think that my solution is more queue oriented and that was your task. So this is my take:
import java.util.ArrayDeque;
import java.util.Scanner;
public class SequenceQuestion {
public static void constructSequence(int start, int seqLength) {
ArrayDeque<Integer> queue = new ArrayDeque<>();
queue.add(start);
System.out.print(start);
for (int i = 0; i < seqLength - 1; i++) {
int print = 0;
if (i % 3 == 0 && i != 0) queue.remove();
if (i % 3 == 0) {
print = queue.peek() + 1;
queue.add(print);
} else if (i % 3 == 1) {
print = queue.peek() * 2 + 1;
queue.add(print);
} else if (i % 3 == 2) {
print = queue.peek() + 2;
queue.add(print);
}
System.out.print(", " + print);
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
constructSequence(s.nextInt(), 50);
}
}
You don't need counters because you already have one (i
) and if you always check for mod 3 at the beginning and if equals to 0, remove the first element from queue. I see that this is the place you had trouble with.