I have an infinite for loop but I cant find which part of my code is causing it

90 Views Asked by At

I am trying to solve the Josephus problem with an ArrayList and for loops. I have created an infinite for loop within my circle.size for loop but I cant deduce which part of my code is causing it to happen.

public class project1 {
  public static int Josephus (int n, int k){                                     
    ArrayList<Integer> circle = new ArrayList<Integer>();                       
    for (int p = 1; p <= n; p++) {                                              
      circle.add(p);                                                            
    }
    System.out.println("There are " + n + " people in the circle.");            
    System.out.println(circle);                                                 

    ArrayList<Integer> kill_order = new ArrayList<Integer>();                   
    for (int index=1; circle.size()!=1; index++){                               
      if (circle.size() > 1){                                                   
        index = (index + k - 1) % circle.size();                                
        kill_order.add(index);                                                  
        circle.remove((Integer)index);
        System.out.println(kill_order);
      } else if (circle.size()==1){
        System.out.println("Execution Order: " + kill_order + " ");
        System.out.println(kill_order);
        index = 1;
      }
    }
    return circle.get(0);
  }

  public static void main(String[] args) {
    System.out.println("You should sit in seat " + Josephus(7, 2) + " if you want to survive!");
  }
}
2

There are 2 best solutions below

3
On

I think that the problem is related to this line of code circle.remove((Integer)index);

if you replace with circle.remove(index) the programs end without any infinite loop.

If you call the method circle.remove((Integer) index) it search an element inside the array with that value, the method circle.remove(index) it remove the element at the specified index.

See the javadoc for additional details remove(int index) remove(Object o)

0
On

Every next iteration of your main loop looks like:

index at the beginning of the loop index after assign new value circle array
1 2 1, 3, 4, 5, 6, 7
3 4 1, 3, 5, 6, 7
5 1 3, 5, 6, 7
2 3 5, 6, 7
4 2 5, 6, 7 - it cannot remove value 2 and array is not size 1
3 1 5, 6, 7
2 0 5, 6, 7
1 2 5, 6, 7
3 1 5, 6, 7 - cycle starts to repeat

So probably your algorithm is wrong, or you should remove element at index, not by value (circle.remove(index)) - without converting it to Integer