Code Wars: Reverse or rotate?
The input is a string
str
of digits. Cut the string into chunks (a chunk here is a substring of the initial string) of size sz
(ignore the last chunk if its size is less than sz
).
If a chunk represents an integer such as the sum of the cubes of its digits is divisible by 2, reverse that chunk; otherwise rotate it to the left by one position. Put together these modified chunks and return the result as a string.
If
sz
is<= 0
or ifstr
isempty
return ""sz
is greater(>)
than the length ofstr
it is impossible to take a chunk of sizesz
hence return "".
function revrot(str, sz) {
if (sz <= 0 || str === "" || sz > str.length) {
return "";
}
let arr1 = str.split('').map(item => parseInt(item));
let arr2 = [];
let sumUp = function add(a, b) {
return a + b;
}
console.log(arr1);
while (arr1.length >= sz) {
arr2.push(arr1.splice(0, sz))
}
for (i = 0; i < arr2.length; i++) {
if ( arr2[i].reduce(sumUp) % 2 === 0) {
arr2[i].reverse();
}
else {
let goLeft = arr2[i].shift();
arr2[i].push(goLeft);
}
}
return arr2.map(item => item.join('')).join('');
}
Comments
Post a Comment