-
Notifications
You must be signed in to change notification settings - Fork 13
/
disordered-first-contact.js
63 lines (55 loc) · 1.56 KB
/
disordered-first-contact.js
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
54
55
56
57
58
59
60
61
62
63
const iterateMsg = action => {
for (let start = 0, length = 1; start < msg.length; start += length++) {
let substr = msg.substr(start, length);
action(length, substr);
}
};
const encode = _ => {
let transformed = '';
iterateMsg(
(length, substr) =>
(transformed =
length % 2 === 0 ? substr + transformed : transformed + substr)
);
return transformed;
};
const decode = msg => {
let times, lastLength;
iterateMsg((length, substr) => {
times = length;
lastLength = substr.length;
});
// Initiate transformed from with LastLength
isLastAddedFromLeft = times % 2 === 0;
let strRef = {
transformed: isLastAddedFromLeft
? msg.substr(0, lastLength)
: msg.slice(-lastLength)
};
msg = isLastAddedFromLeft
? msg.slice(lastLength)
: msg.slice(0, -lastLength);
decodeAux(strRef, msg, times - 1, !isLastAddedFromLeft);
return strRef.transformed;
};
const decodeAux = (strRef, msg, times, addFromLeft) => {
if (times === 0) {
return;
}
strRef.transformed = addFromLeft
? msg.substr(0, times) + strRef.transformed
: msg.slice(-times) + strRef.transformed;
msg = addFromLeft ? msg.slice(times) : msg.slice(0, -times);
decodeAux(strRef, msg, times - 1, !addFromLeft);
};
const times = +readline();
let timesTrans = Math.abs(times);
let msg = readline();
while (timesTrans--) {
if (times < 0) {
msg = encode();
} else {
msg = decode(msg);
}
}
print(msg);