Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created April 18, 2025 16:14
Show Gist options
  • Save tatsuyax25/1373782570b912d440531812a34f3858 to your computer and use it in GitHub Desktop.
Save tatsuyax25/1373782570b912d440531812a34f3858 to your computer and use it in GitHub Desktop.
The count-and-say sequence is a sequence of digit strings defined by the recursive formula: countAndSay(1) = "1" countAndSay(n) is the run-length encoding of countAndSay(n - 1). Run-length encoding (RLE) is a string compression method that works by
/**
* Generates the nth element of the count-and-say sequence.
*
* @param {number} n - The position in the sequence (1-based index).
* @return {string} - The nth element of the count-and-say sequence.
*/
var countAndSay = function(n) {
// Validate the input: must be between 1 and 30 (inclusive)
if (n < 1 || n > 30 || n == null) {
return 'ERROR'; // Return an error if input is invalid
}
// Initialize the first sequence in the count-and-say sequence
let previous_sequence = '1';
// Loop to generate the sequence for n iterations
for (let i = 1; i < n; i++) {
let current_num = previous_sequence.charAt(0); // Start with the first character
let count = 1; // Initialize the count for the first character
let current_sequence = ""; // Initialize the current sequence
// Process the previous sequence to generate the next one
for (let j = 1; j < previous_sequence.length; j++) {
let compare_num = previous_sequence.charAt(j); // Get the next character
// If the current character changes, append the count and character to the result
if (compare_num !== current_num) {
current_sequence += `${count}${current_num}`; // Append count and current character
current_num = compare_num; // Update current character
count = 1; // Reset count for the new character
} else {
count++; // Increment count for consecutive identical characters
}
}
// Append the last group (count and character) after finishing the loop
current_sequence += `${count}${current_num}`;
// Update the sequence for the next iteration
previous_sequence = current_sequence;
}
// Return the nth sequence
return previous_sequence;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment