-
Notifications
You must be signed in to change notification settings - Fork 0
/
InsertionLottery.java
82 lines (71 loc) · 1.91 KB
/
InsertionLottery.java
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
import java.util.Random;
class InsertionLottery{
/**
* Main method that initiates run of program
*/
public static void main(String[] args){
InsertionLottery instance = new InsertionLottery();
instance.run();
}
/**
* Controls the program
*/
public void run(){
int[] ticket = this.replaceSameNumbers(this.generateTicket());
this.outputTicket(this.insertionSort(ticket));
}
/**
* Generates ticket number and returns it as int array
*/
private int[] generateTicket(){
Random random = new Random();
int[] ticket = new int[6];
for(int i = 0; i < 6; i++){
ticket[i] = random.nextInt(48) + 1;
}
return ticket;
}
/**
* Accepts ticket as a parameter of type int array.
* Replaces same numbers and returns new ticket as int array.
*/
private int[] replaceSameNumbers(int[] ticket){
Random random = new Random();
for(int i = 0; i < ticket.length; i++){
for(int j = 0; j < ticket.length; j++){
if(ticket[i] == ticket[j]){
ticket[i] = random.nextInt(48) + 1;
}
}
}
return ticket;
}
/**
* Accepts ticket as a int array parameter and outputs it.
*/
private void outputTicket(int[] ticket){
System.out.print("Ticket: ");
for(int i = 0; i < ticket.length - 1; i++){
System.out.print(ticket[i] + " ");
}
System.out.println("");
}
/**
* Accepts ticket as int array parameter and sorts numbers in descending order.
* Returns sorted result as int array
*/
private int[] insertionSort(int[] ticket){
int tempItem;
int currentPosition;
for(int i = 1; i < ticket.length; i++){
tempItem = ticket[i];
currentPosition = i;
while(currentPosition > 0 && ticket[currentPosition - 1] > tempItem){
ticket[currentPosition] = ticket[currentPosition - 1];
currentPosition--;
}
ticket[currentPosition] = tempItem;
}
return ticket;
}
}