Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
103 lines (86 loc) · 2.54 KB

File metadata and controls

103 lines (86 loc) · 2.54 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
92
93
94
95
96
97
98
99
100
101
102
103
package com.examples;
import java.util.*;
public class SnakeGame {
int width;
int height;
int[][] food;
int foodIndex;
Queue<Pair> snake;
Set<Pair> set;
Pair currentPosition;
class Pair{
int r;
int c;
public Pair(int r, int c){
this.r = r;
this.c = c;
}
@Override
public String toString(){
return "r: " + this.r + ", c: " + this.c;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
return r == pair.r && c == pair.c;
}
@Override
public int hashCode(){
return Objects.hash(r, c);
}
}
public SnakeGame(int width, int height, int[][] food) {
this.width = width;
this.height = height;
this.food = food;
foodIndex = 0;
snake = new LinkedList<>();
set = new HashSet<>();
currentPosition = new Pair(0,0);
snake.offer(new Pair(0,0));
set.add(new Pair(0,0));
}
public int move(String direction) {
switch (direction){
case "U":
this.currentPosition.r--;
break;
case "D":
this.currentPosition.r++;
break;
case "L":
this.currentPosition.c--;
break;
case "R":
this.currentPosition.c++;
break;
default:
System.out.println("Invalid move!!!");
}
int r = this.currentPosition.r;
int c = this.currentPosition.c;
if(r < 0 || r >= width || c < 0 || c >= height){
return -1;
}
if(r == food[foodIndex][0] && c == food[foodIndex][1]){
foodIndex++;
}else{
set.remove(snake.poll());
}
return 0;
}
public static void main(String[] args) {
SnakeGame obj = new SnakeGame(2, 3, new int[][]{{1,1}, {2,1}});
System.out.println(obj.set.iterator().next().equals(obj.snake.peek()));
}
}
/*
["SnakeGame","move","move"]
[[2,2,[[0,1]]],["R"],["D"]]
["SnakeGame","move","move","move","move","move"]
[[2,2,[[1,0]]],["R"],["D"],["L"],["U"],["R"]]
["SnakeGame","move","move","move","move","move","move","move","move","move","move","move","move"]
[[3,3,[[2,0],[0,0],[0,2],[2,2]]],["D"],["D"],["R"],["U"],["U"],["L"],["D"],["R"],["R"],["U"],["L"],["D"]]
*/
Morty Proxy This is a proxified and sanitized view of the page, visit original site.