-3

I'm trying to implement a greedy algorithm below, So I'm trying to follow the gist of the algorithm details, but I'm getting an error at my IF statement: java.lang.IndexOutOfBoundsException: Index: 4, Size: 4 Does anyone know if the below method is how I should be approaching this?

  1. Color first vertex with first color.
  2. Do following for remaining V-1 vertices.

    a) Consider the currently picked vertex and color it with the lowest numbered color that has not been used on any previously colored vertices adjacent to it. If all previously used colors appear on vertices adjacent to v, assign a new color to it. */

public void greedy(LinkedHashMap<String, Node> nodes) {         
    ArrayList<Integer> colors = new ArrayList<Integer>();
    ArrayList<Integer> colorsUsed = new ArrayList<Integer>();

    nodes.entrySet().iterator().next().getValue().currentColor = 1; 
    colorsUsed.add(1);
    for (Map.Entry<String,Node> entry : nodes.entrySet()) {
        for (int i = 0; i < nodes.entrySet().size(); i++) {
            if(entry.getValue().edges.get(i).currentColor == 0) {
                //assign a color
                System.out.println(colors.get(i));
            }
        }
    }
}
dguay
  • 1,635
  • 15
  • 24
Josh123
  • 157
  • 3
  • 13

2 Answers2

2

Your nested loop doesn't make much sense and it's the cause of the exception (you stop i at the number of nodes instead of the number of edges per node, hence the index i is out of the bounds of the collection entry.getValue().edges).

You should probably replace

for (int i = 0; i < nodes.entrySet().size(); i++) {
                    ^^^^^^^^^^^^^^^^^^^^^^^
    if(entry.getValue().edges.get(i).currentColor == 0) {

With something like

for (int i = 0; i < entry.getValue().edges.size(); i++) {
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    if(entry.getValue().edges.get(i).currentColor == 0) {

(Supposing Node#edged implements java.util.List)

Also, colors.get(i) doesn't make much sense either...

zakinster
  • 10,508
  • 1
  • 41
  • 52
0

IndexOutOfBoundsException is telling you that your program is trying to get access to a position of your ArrayList where it can't access, because the size is smaller than the index. If you want more information about this exception, you should look here.

You should check into your code, especially into your loops.

xFunkyTImes
  • 117
  • 9