settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Calculate Sequence with Queue - Java Task (Queues)

+13 votes

java task (with queues):

We are given 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, write a program to print its first 50 members for given N.

Examples:

Input

Output

2

2 3 5 4 4 7 5 6 11 7 5 9 6 …

-1

-1 0 -1 1 1 1 2 …

1000

1000 1001 2001 1002 1002 2003 1003 …

 

asked in Java category by user ak47seo
edited by user golearnweb

1 Answer

+1 vote
 
Best answer

Here is the solution:

import java.util.ArrayDeque;
import java.util.Scanner;

public class Pr_05_CalculateSequenceWithQueue {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        long n = sc.nextLong();

        ArrayDeque<Long> queue = new ArrayDeque<>();
        queue.add(n);

        for (int i = 0; i < 50; i++) {//50 NUMBERS: THIS IS THE LIMIT
            long current = queue.remove();

            System.out.printf("%s ", current);
            long s1 = current + 1;
            long s2 = 2 * current + 1;
            long s3 = current + 2;

            queue.add(s1);
            queue.add(s2);
            queue.add(s3);
        }
    }
}

 

answered by user nikole
selected by user golearnweb
...