summaryrefslogtreecommitdiff
path: root/src/Q7/HailstoneSequence.java
blob: 926665d9817d434c2e1a788fae4c15840f0f4a58 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
 * Assignment 1, COMP268 Class: HailstoneSequence.java
 *
 * @description Represents a hailstone sequence
 * @author: mo khan Student ID: 3431709
 * @date May 8, 2019
 * @version 1.0
 */
package Q7;

import java.util.ArrayList;
import java.util.Scanner;

public class HailstoneSequence {
  /**
   * Returns a hailstone sequence using the seed provided.
   *
   * @param n the seed value for the hailstone sequence
   * @return a list of integers that represents the hailstone sequence.
   */
  public static ArrayList<Integer> getHailstoneSequence(int n) {
    return getHailstoneSequence(n, new ArrayList<Integer>());
  }

  /**
   * Appends to the hailstone sequence starting from the seed value provided.
   *
   * @param n the seed value for the hailstone sequence
   * @param items the list of items to append the next set of hailstone sequence to.
   * @return a list of integers that represents the hailstone sequence.
   */
  public static ArrayList<Integer> getHailstoneSequence(int n, ArrayList<Integer> items) {
    items.add(n);

    if (n == 1) return items;
    else if (n % 2 == 0) return getHailstoneSequence(n / 2, items);
    else return getHailstoneSequence((n * 3) + 1, items);
  }

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    System.out.print("Please enter seed for hailstone sequence: ");
    ArrayList<Integer> sequence = HailstoneSequence.getHailstoneSequence(in.nextInt());
    for (Integer i : sequence) System.out.println(i);

    for (Integer i : sequence) System.out.print("-");
  }
}