-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGravityFlip.js
More file actions
43 lines (34 loc) · 1.76 KB
/
GravityFlip.js
File metadata and controls
43 lines (34 loc) · 1.76 KB
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
/*
Task:
If you've completed this kata already and want a bigger challenge, here's the 3D version
Bob is bored during his physics lessons so he's built himself a toy box to help pass the time. The box is special because it has the ability to change gravity.
There are some columns of toy cubes in the box arranged in a line. The i-th column contains a_i cubes. At first, the gravity in the box is pulling the cubes downwards. When Bob switches the gravity, it begins to pull all the cubes to a certain side of the box, d, which can be either 'L' or 'R' (left or right). Below is an example of what a box of cubes might look like before and after switching gravity.
+---+ +---+
| | | |
+---+ +---+
+---++---+ +---+ +---++---++---+
| || | | | --> | || || |
+---++---+ +---+ +---++---++---+
+---++---++---++---+ +---++---++---++---+
| || || || | | || || || |
+---++---++---++---+ +---++---++---++---+
Given the initial configuration of the cubes in the box, find out how many cubes are in each of the n columns after Bob switches the gravity.
Examples (input -> output:
* 'R', [3, 2, 1, 2] -> [1, 2, 2, 3]
* 'L', [1, 4, 5, 3, 5 ] -> [5, 5, 4, 3, 1]
*/
//Answer
//P two arguments - one for the direction other for the array
//R if R asc, if L dsc
//E
//P
//use .sort method to sort array into sc if 'r' : 'l'
const flip = (d, a) => {
if (d === "R") {
return a.sort((x, y) => x - y);
} else if (d === "L") {
return a.sort((x, y) => y - x);
}
};
console.log(flip("R", [3, 2, 1, 2])); // [1, 2, 2, 3]);
console.log(flip("L", [1, 4, 5, 3, 5])); // [5, 5, 4, 3, 1]);