-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCode.java
More file actions
85 lines (72 loc) · 2.01 KB
/
Code.java
File metadata and controls
85 lines (72 loc) · 2.01 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
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
import java.util.*;
public class Code
{
//instance variables
private Peg[] code;
private int numPositions;
private int numColors;
//constructor to generate a random code from the computer using an array
public Code(int np, int nc)
{
numPositions = np;
numColors = nc;
code = new Peg[numPositions];
//adds numPositions random pegs into array of code
for(int i = 0; i < numPositions; i++){
Peg p1 = new Peg(numColors);
code[i] = p1;
}
}
//constructor to generates code based on string passed in
public Code(int np, int nc, String input)
{
numPositions = np;
numColors = nc;
if(input.length() != numPositions)
{
throw new IllegalArgumentException("Your input is not the correct length!");
}
this.code = new Peg[numPositions];
//add pegs with color and add them to code array
for(int i = 0; i < numPositions; i++)
{
Peg peg = new Peg(numColors, input.charAt(i));
code[i] = peg;
}
}
public Peg getPeg(int pos)
{
if(pos < 0 || pos >= numPositions)
{
throw new IllegalArgumentException("Violation of precondition: pos is out of bounds.");
}
return this.code[pos];
}
public boolean equals(Code other)
{
for(int i = 0; i < numPositions; i++)
{
if(!this.getPeg(i).equals(other.getPeg(i)))
{
return false;
}
}
return true;
}
public String toString()
{
String str = "";
//loop through Code, get Peg and get its color
for(int i = 0; i < numPositions; i++)
{
Peg p1 = this.getPeg(i);
char c = p1.getColor();
str += c;
}
return str;
}
public int size()
{
return numPositions;
}
}