Contents

Creating a Collatz Sequence (with.Java)

   Sep 4, 2023     2 min read

In this article, we learned how to create a Collatz sequence (with.Java).

We’re going to learn as we go by solving coding test problems, reflecting on the problems we solved, and exploring other ways to solve them. Let’s start with the problem.

Problem

The problem of asking whether, for any natural number x, if the current value is x, if we keep repeating the calculation of dividing by 2 if x is even and replacing it with 3 * x + 1 if x is odd, we will surely end up with x = 1 at some point is called the Collatz problem. And the sequence that records all the numbers we’ve gone through is called the Collatz sequence. We know that for any number less than or equal to 1,000, we will reach 1 at some point. Given an arbitrary positive integer n less than or equal to 1,000, complete the solution function to return the Collatz sequence with initial value n.

Example input and output

n: 10 result: [10, 5, 16, 8, 4, 2, 1]

My solution to the problem

import java.util.*;

class Solution {
    public int[] solution(int n) {
        ArrayList<Integer> temp = new ArrayList<Integer>();
        temp.add(n);

        while(n != 1){
            if(n % 2 == 0){
                n = n / 2;
            } else {
                n = 3 * n + 1;
            }
            temp.add(n);
        }

        int[] answer = new int[temp.size()];
        for(int i = 0; i < temp.size(); i++){
            answer[i] = temp.get(i);
        }

        } return answer;
    }
}
Solution

ArrayList temp = new ArrayList();: Create an ArrayList object temp to store the integers. temp.add(n);: Adds the initial integer n to the list temp. This list will store all the values from the guessing process. while(n != 1): Start a loop that iterates until n equals 1. Transform n according to the Collatz conjecture, and exit the loop when n equals 1. if(n % 2 == 0): Check if n is an even number. If it is, divide n by 2 to make it an odd number. else { n = 3 \* n + 1; }: If n is odd, multiply n by 3 and add 1 to make it even. temp.add(n);: Add the converted value of n to the temp list. int[] answer = new int[temp.size()];: Create an integer array answer that fits the size of the temp list. for(int i = 0; i < temp.size(); i++){ answer[i] = temp.get(i); }: Copy the values from the temp list into the array answer. return answer;: Return the array answer where the result of the Collatz guess is stored.