Skip to content

Commit 652e1bf

Browse files
author
Olcay Taner YILDIZ
committed
Added Dart game as an example to Queue data structure.
1 parent d7b65aa commit 652e1bf

File tree

4 files changed

+109
-0
lines changed

4 files changed

+109
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package Array.DartsGame;
2+
3+
public class Element {
4+
private State data;
5+
6+
public Element(State data){
7+
this.data = data;
8+
}
9+
10+
public State getData(){
11+
return data;
12+
}
13+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package Array.DartsGame;
2+
3+
public class Queue {
4+
5+
private Element array[];
6+
7+
private int first;
8+
9+
private int last;
10+
11+
private int N;
12+
13+
public Queue(int N){
14+
this.N = N;
15+
array = new Element[N];
16+
first = 0;
17+
last = 0;
18+
}
19+
20+
boolean isFull(){
21+
return (last + 1) % N == first;
22+
}
23+
24+
boolean isEmpty(){
25+
return first == last;
26+
}
27+
28+
void enqueue(Element element){
29+
if (!isFull()){
30+
array[last] = element;
31+
last = (last + 1) % N;
32+
}
33+
}
34+
35+
Element dequeue(){
36+
if (!isEmpty()){
37+
Element tmp = array[first];
38+
first = (first + 1) % N;
39+
return tmp;
40+
}
41+
return null;
42+
}
43+
44+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package Array.DartsGame;
2+
3+
public class State {
4+
5+
private int total;
6+
private String darts;
7+
8+
State(int total, String darts){
9+
this.total = total;
10+
this.darts = darts;
11+
}
12+
13+
public int getTotal() {
14+
return total;
15+
}
16+
17+
public String getDarts() {
18+
return darts;
19+
}
20+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package Array.DartsGame;
2+
3+
public class Test {
4+
5+
static String dartGame(int[] board, int target){
6+
Queue k;
7+
State s;
8+
s = new State(0, "");
9+
k = new Queue(10000);
10+
k.enqueue(new Element(s));
11+
while (!k.isEmpty()){
12+
s = k.dequeue().getData();
13+
if (s.getTotal() == target){
14+
return s.getDarts();
15+
}
16+
for (int i = 0; i < board.length; i++){
17+
if (s.getTotal() + board[i] <= target){
18+
int newTotal = s.getTotal() + board[i];
19+
String newDarts = s.getDarts() + " " + board[i];
20+
Element child = new Element(new State(newTotal, newDarts));
21+
k.enqueue(child);
22+
}
23+
}
24+
}
25+
return "";
26+
}
27+
28+
public static void main(String[] args){
29+
int[] board = {11, 21, 27, 33, 36};
30+
System.out.println(dartGame(board, 100));
31+
}
32+
}

0 commit comments

Comments
 (0)