| 1 | import java.awt.Color; |
| 2 | import java.util.Arrays; |
| 3 | |
| 4 | public class Eye implements Comparable<Eye> { |
| 5 | private String strColor; |
| 6 | private Color color; |
| 7 | private String[] colorsList = {"black", "blue", "brown", "green"}; |
| 8 | |
| 9 | Eye() { |
| 10 | sortColorList(); |
| 11 | } |
| 12 | |
| 13 | /** |
| 14 | * @param color |
| 15 | */ |
| 16 | Eye(String color) { |
| 17 | setStrColor(color); |
| 18 | setColor(color); |
| 19 | sortColorList(); |
| 20 | } |
| 21 | |
| 22 | public String getStrColor() { |
| 23 | return strColor; |
| 24 | } |
| 25 | |
| 26 | public void setStrColor(String strColor) { |
| 27 | if (validateColor(strColor)) { |
| 28 | this.strColor = strColor; |
| 29 | } else { |
| 30 | throw new IllegalArgumentException("Color must be" + this.colorListToString()); |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | public String[] getColorsList() { |
| 35 | return colorsList; |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * @return |
| 40 | */ |
| 41 | public Color getColor() { |
| 42 | return color; |
| 43 | } |
| 44 | |
| 45 | /** |
| 46 | * @param color |
| 47 | */ |
| 48 | public void setColor(String color) { |
| 49 | if (validateColor(color)) { |
| 50 | if (color.equals("brown")) |
| 51 | this.color = new Color(88, 41, 0); |
| 52 | else |
| 53 | this.color = Color.getColor(color); |
| 54 | } else { |
| 55 | throw new IllegalArgumentException("Color must be" + this.colorListToString()); |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * @param color |
| 61 | * @return |
| 62 | */ |
| 63 | private boolean validateColor(String color) { |
| 64 | for (String c : colorsList) { |
| 65 | if (color.equals(c)) { |
| 66 | return true; |
| 67 | } |
| 68 | } |
| 69 | return false; |
| 70 | } |
| 71 | |
| 72 | private void sortColorList() { |
| 73 | Arrays.sort(this.colorsList); |
| 74 | } |
| 75 | |
| 76 | /** |
| 77 | * @param eye |
| 78 | * @return |
| 79 | */ |
| 80 | @Override |
| 81 | public int compareTo(Eye eye) { |
| 82 | double r_diff = this.getColor().getRed() - eye.getColor().getRed(); |
| 83 | double g_diff = this.getColor().getGreen() - eye.getColor().getGreen(); |
| 84 | double b_diff = this.getColor().getBlue() - eye.getColor().getBlue(); |
| 85 | //See https://en.wikipedia.org/wiki/Color_difference |
| 86 | Double distance = Math.sqrt(2 * Math.pow(r_diff, 2) + 4 * Math.pow(g_diff, 2) + 3 * Math.pow(b_diff, 2)); |
| 87 | return distance.intValue(); |
| 88 | } |
| 89 | |
| 90 | private String colorListToString() { |
| 91 | StringBuilder stringBuilder = new StringBuilder(); |
| 92 | for (String c : colorsList) { |
| 93 | stringBuilder.append(" "); |
| 94 | stringBuilder.append(c); |
| 95 | } |
| 96 | return stringBuilder.toString(); |
| 97 | } |
| 98 | } |