Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Random;
- public class Main {
- public static void main(String[] args) {
- Collatz tester = new Collatz();
- /*List<Integer> test = new ArrayList<Integer>();
- System.out.println("wtf");
- for(int i = 1;i < 11000;i++){
- test.add(i);
- }
- for(int x: test){
- System.out.println(x);
- }*/
- tester.fillArray(10);
- tester.iterateCollatz();
- System.out.println("length: " + tester.getLength() + " given by seed " + tester.getLongestSeed());
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.List;
- import java.util.Random;
- import javafx.css.Size;
- public class Collatz {
- private int longestChain; // Length of the current longest chain
- private int seed; // The current seed value, i.e. the value at which the current chain starts
- private int longestSeed; // Number which generates the longest Collatz sequence
- private List<Integer> array; // ArrayList on which the Collatz sequence operates
- public Collatz() {
- this.longestChain = 1;
- this.array = new ArrayList<>();
- this.seed = 1;
- this.longestSeed = 1;
- }
- // Create an ArrayList with entries 1...n
- public void fillArray(int n) {
- for (int i = (n-1)/2; i < n; i = i++) {
- if(!((n%2 ==0) && (n%3 == 1)))
- this.array.add(i);
- }
- }
- public void iterateCollatz() {
- int i = 1;
- while (this.array.size() > 0) {
- System.out.println("iteration " + i);
- this.setSeed();
- this.runCollatzOperation(this.seed);
- i++;
- }
- }
- public void runCollatzOperation(int n) {
- int m = n;
- int length = 1;
- while (n != 1) {
- if (this.array.contains(n)) {
- this.deleteEntry(n);
- }
- if (n % 2 == 0) {
- n = n / 2;
- }
- else {
- n = 3 * n + 1;
- }
- length++;
- }
- if (length > this.longestChain) {
- this.longestChain = length;
- this.longestSeed = m;
- }
- }
- //Deletes the value n from this.array, if it exists
- public void deleteEntry(int n) {
- this.array.remove(this.array.indexOf(n));
- }
- /*Generate a random number to serve as the seed of the next chain
- from the remaining numbers in this.array */
- public void setSeed() {
- Random generator = new Random();
- int random = generator.nextInt(this.array.size());
- this.seed = this.array.get(random);
- }
- public int getSeed() {
- return this.seed;
- }
- public int getLongestSeed() {
- return this.longestSeed;
- }
- public int getLength() {
- return this.longestChain;
- }
- public int getMax() {
- return Collections.max(this.array);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement