-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path14mar23SnakesLadders.ts
91 lines (62 loc) · 2.55 KB
/
14mar23SnakesLadders.ts
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
This Kata is like the game of Snakes & Ladders
There is an array representing the squares on the game board.
The starting square is at array element 0. The final square is the last array element.
At each "turn" you move forward a number of places (according to the next dice throw).
The value at the square you end up on determines what happens next:
0 Stay where you are (until next turn)
+n This is a "ladder". Go forward n places
-n This is a "snake". Go back n places
Each snake or ladder will always end on a square with a 0, so you will only go up or down one at a time.
Rules
You are given a number of dice throws. The game continues until either:
You have no throws left, OR
You end up exactly on the final square
At each turn, make your move, then go up the "ladders" and down the "snakes" as appropriate.
If the dice roll overshoots the final square then you cannot move. Roll the dice again.
Task
Return the index of the array element that you ended up on at the end of the game.
Example
Start
Dice: [2, 1, 5, 1, 5, 4]
Board: [0, 0, 3, 0, 0, 0, 0, -2, 0, 0, 0]
Roll a 2. Move forward 2 squares, then go up the ladder (+3)
Dice: [2, 1, 5, 1, 5, 4]
Board: [0, 0, 3, 0, 0, 0, 0, -2, 0, 0, 0]
Board: [0, 0, 3, 0, 0, 0, 0, -2, 0, 0, 0]
Roll a 1. Move forward 1 square
Dice: [2, 1, 5, 1, 5, 4]
Board: [0, 0, 3, 0, 0, 0, 0, -2, 0, 0, 0]
Roll a 5. Can't move
Dice: [2, 1, 5, 1, 5, 4]
Board: [0, 0, 3, 0, 0, 0, 0, -2, 0, 0, 0]
Roll a 1. Move forward 1 square, then go down the snake (-2)
Dice: [2, 1, 5, 1, 5, 4]
Board: [0, 0, 3, 0, 0, 0, 0, -2, 0, 0, 0]
Board: [0, 0, 3, 0, 0, 0, 0, -2, 0, 0, 0]
Roll a 5. Move forward 5 squares
Dice: [2, 1, 5, 1, 5, 4]
Board: [0, 0, 3, 0, 0, 0, 0, -2, 0, 0, 0]
You are on the final square so the game ends. Return 10
:-)
var snakesLadder = (board, dice) => {
//board is an arr with negatives included
//dice is an arr b/w 1 and 6, the number of times player threw dice.
//return the position of the piece with respect of the board
//use a for of loop with the dice, initialize a var 'square' and add. compare it with board position
let square = 0;
for(let die of dice){
if(square + die >= board.length){
continue;
}
square += die;
//0 += 1;
//1+=2;
//3+=4;
//7+=5;
//12+=6;
//square = 18
square += board[square]
//18+= board[18]
}
return square; //18+= board[square]
}