-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprompt3.txt
53 lines (37 loc) · 1.12 KB
/
prompt3.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
Write an algorithm that takes a string with repeated characters and compresses them, using a number to show how many times the repeated character has been compressed. For instance, aaa would be written as 3a. Solve the problem with and without recursion.
Example
Input: "aaabccdddda"
Output: "3ab2c4da"
__________________________________________________________________
input - string of letters
special characters or numbers?
output - string of numbers & letters
w recursion
w.o recursion
for loop
string > array.from > string .join
empty result string > .concat +
WITHOUT RECURSION:
const stringCompression = (input) => {
const string = input.toLowerCase();
let result = "";
let counter = 1;
for (let i=0; i < string.length; i++) {
let currentChar = string[i];
let nextChar = string[i + 1];
if (currentChar === nextChar) {
counter++;
} else if (counter === 1) {
result += currentChar;
} else {
result += counter + currentChar;
counter = 1;
}
}
return result;
};
WITH RECURSION:
const stringCompression = (string) => {
};
string = "aaabccdddda";
result = "3ab2c4da";