Last active
March 14, 2018 03:19
-
-
Save UXnomaan/884b5d395311e9c78f289e3308cf5abf to your computer and use it in GitHub Desktop.
Compresses a sequence
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Assuming that someone dictates you a sequence of numbers and you need to write it down. | |
| // For brevity, he dictates it as follows: first says the number of consecutive identical numbers and then | |
| // says the number itself. E.g. The sequence 1 1 3 3 3 2 2 2 2 14 14 14 11 11 11 2 will be dictated as | |
| // "Two times one, three times three, four times two, three times fourteen, three times eleven, one time two", | |
| // so you will write down the sequence 2 1 3 3 4 2 3 14 3 11 1 2. | |
| // Compresses a given sequence using this approach | |
| const compressSequence = seq => { | |
| let counter = 1; | |
| let result = ""; | |
| for (let i = 1; i <= seq.length; i++) { | |
| const current = seq[i]; | |
| const prev = seq[i - 1]; | |
| if (prev !== current) { | |
| result += counter + " " + prev + " "; | |
| counter = 1; | |
| } else { | |
| counter++; | |
| } | |
| } | |
| return result; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment