Home > Back-end >  How can I print the longest sequence of the same element?
How can I print the longest sequence of the same element?

Time:09-17

I'm working on this homework assignment which asks to write a method called longestEqualSequence that determines the longest sequence of numbers that are equal. For example, in [6, 7, 4, 4, 4, 7, 1, 3, 3, 4, 1, 4, 3, 4, 2, 9, 1, 8, 2, 7], the longest sequence is length three: 4, 4, 4. When I run the code below my output is "The longest sequence is length: 3" I want to also print the longest sequence which is [4, 4, 4]. How would I print the sequence along with the length of it?

import java.util.Arrays;

public class Q3 {
    public static void main(String[] args) {
        int[] y = { 6, 7, 4, 4, 4, 4, 7, 1, 3, 3, 4, 1, 4, 3, 4, 2, 9, 1, 8, 2, 7 };
        System.out.println(Arrays.toString(y));
        System.out.println("The longest sequence is length: "   longestEqualSequence(y));
        
    }

    public static int longestEqualSequence(int[] array) {
        int currentSequence = 1;
        int maxSequence = 1;

        for (int i = 1; i < array.length; i  ) {
            if (array[i] == array[i - 1]) {
                currentSequence  ;
            } else {
                if (currentSequence > maxSequence) {
                    maxSequence = currentSequence;
                }
                currentSequence = 1;
            }
        }

        if (currentSequence > maxSequence)
            return currentSequence;
        else
            return maxSequence;
    }
}

CodePudding user response:

Use a sequence_number variable and set it when currentSequence is greater than maxSequence.

if (currentSequence > maxSequence) {
       maxSequence = currentSequence;
       sequence_number = array[i-1]
}

Then, print the sequence_number variable maxSequence times.

CodePudding user response:

You can add a current value variable:

public static int[] longestEqualSequence(int[] array) {
    int currentSequence = 1;
    int maxSequence = 1;
    int currentValue = array[0];

    for (int i = 1; i < array.length; i  ) {
        if (array[i] == array[i - 1]) {
            currentSequence  ;
        } else {
            if (currentSequence > maxSequence) {
                maxSequence = currentSequence;
                currentValue = array[i - 1];
            }
            currentSequence = 1;
        }
    }

    int[] sequence = new int[currentSequence > maxSequence ? currentSequence : maxSequence];
    Arrays.fill(sequence, currentValue);
    return sequence;
}

Then:

int[] y = { 6, 7, 4, 4, 4, 4, 7, 1, 3, 3, 4, 1, 4, 3, 4, 2, 9, 1, 8, 2, 7 };

int[] sequence = longestEqualSequence(y);

System.out.println("sequence="   Arrays.toString(sequence)   ", size="   sequence.length);

Output:

sequence=[4, 4, 4, 4], size=4
  • Related