Skip to content

Instantly share code, notes, and snippets.

@quangnd
Last active June 4, 2022 19:27
Show Gist options
  • Save quangnd/07aa74a5ee3544375e05b69d93817511 to your computer and use it in GitHub Desktop.
Save quangnd/07aa74a5ee3544375e05b69d93817511 to your computer and use it in GitHub Desktop.
JS Learning: Arrays - Water flow
/*
Coding in function infiniteLoop. function accept 3 parameters. The 1st parameter is arr, it's a 2D array, it contains three 1D array. The 2nd parameter is d ,it's a string. The 3rd parameter is n, it's a number.
You can think of arr as a moat, the elements of arr like water constantly flow in. The direction of flow is controlled by the parameter d. The value of d can be "left" or "right". "left" means the "river" moves to the left. All elements in the 1D array are to the left moving n position, if beyond the bounds of the array and the element is moved to the tail on the left side of the array; if it exceeds the left boundary element would be moved to the tail of 3rd array(like a circle). Right is also similar to the operation, but it is moving to the right.
Finally, return arr.
Example:
infiniteLoop( [[1,2,3],[4,5,6],[7,8,9]],"left",1)
should return [[2,3,4],[5,6,7],[8,9,1]]
infiniteLoop( [[1,2,3],[4,5,6],[7,8,9]],"right",1)
should return [[9,1,2],[3,4,5],[6,7,8]]
infiniteLoop( [[1,2],[3,4,5,6],[7,8,9,10]],"left",2)
should return [[3,4],[5,6,7,8],[9,10,1,2]]
*/
/**Pass test case 1 & 2 **/
function infiniteLoop(arr,d,n){
let moatArr = [];
let flowedArr = [];
let firstElements = [];
for (let i=0; i < arr.length; i++) {
if (d === "left") {
if (n === 1) {
firstElements[i] = arr[i].shift();
moatArr[0] = arr[i][0];
moatArr[1] = arr[i][1];
if (i == arr.length - 1) {
moatArr[2] = firstElements[0];
}
else {
moatArr[2] = arr[i+1][0];
}
flowedArr.push(moatArr);
moatArr = [];
console.log(flowedArr);
}
}
}
//
for (let i=arr.length - 1; i >= 0; i--)
{
if (d === "right") {
if (n === 1) {
firstElements[i] = arr[i].pop();
if (i === 0)
moatArr[0] = firstElements[firstElements.length-1]
else {
moatArr[0] = arr[i-1][2];
}
moatArr[1] = arr[i][0];
moatArr[2] = arr[i][1];
flowedArr.push(moatArr);
moatArr = [];
console.log(flowedArr);
}
}
}
if (d === "left")
return flowedArr;
return flowedArr.reverse();
}
/*Finish code */
function infiniteLoop(arr,d,n){
for (var i = 1; i <= n; i++){
if (d === "left"){
arr[2].push(arr[0].shift());
arr[1].push(arr[2].shift());
arr[0].push(arr[1].shift());
}
if (d === "right"){
arr[0].unshift(arr[2].pop());
arr[1].unshift(arr[0].pop());
arr[2].unshift(arr[1].pop());
}
}
return arr;
}
//SOlutions link
http://www.codewars.com/kata/572af273a3af3836660014a1/solutions/javascript
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment