La suite de Conway - Solution

On se retrouve aujourd'hui pour la solution du précédent #KataOfTheWeek proposé par Lothaire en début de semaine !

Voici une proposition de solution en Java :

public class ConwaySequence {

    public List<String> getConwaySequence(int n) {
        if (n == 0) {
            throw new IllegalStateException();
        }

        List<String> conwaySequence = new ArrayList<>();

        // Add first term
        String FIRST_TERM = "1";
        conwaySequence.add(FIRST_TERM);

        // Add other terms
        for (int rowIndex = 0; rowIndex < n - 1; rowIndex++) {
            String previousRow = conwaySequence.get(rowIndex);
            int previousRowLength = previousRow.length();

            StringBuilder currentRow = new StringBuilder();

            int numberOfMatchingChars = 1; // Initialize count of matching chars
            char []arr = previousRow.toCharArray();

            // Process previous term to find the next term
            for (int i = 0; i < previousRowLength - 1; i++) {
                if (arr[i] == arr[i + 1]) { // If current char matches next char
                    numberOfMatchingChars++; // then increment count of matching characters
                } else { // If current char doesn't match next char
                    currentRow.append(numberOfMatchingChars); // Append number of matching chars
                    currentRow.append(arr[i]); // Append current char

                    numberOfMatchingChars = 1; // Reset counter
                }
            }
            // For the last char
            currentRow.append(numberOfMatchingChars); // Append number of matching chars
            currentRow.append(arr[previousRowLength - 1]); // Append current char

            conwaySequence.add(currentRow.toString());
        }

        return conwaySequence;
    }
}

A bientôt pour un nouveau #KataOfTheWeek !

TakiVeille

TakiVeille