Search code examples
javacollectionsinfinite-loop

Java programming, encountered an infinite loop while solving. Image link to the question and the code is provided.


RoyalGame Problem

The Image link to the problem is given above. I'm stuck in an infinite loop after the first iteration, can someone help me please. I'm open for alternate solutions as well, thanks in advance.

 static void compute(List<Integer> a){
        boolean henrystatus=false;
        while(true){
           if(a.size()==0){
           break;
        }
      else if(a.size()==1){
          henrystatus=true;
          break;
      }

       int mindex = a.indexOf(Collections.min(a));

     List<Integer> temp=new ArrayList<Integer>();
       for(int i=0;i<a.size();i++)
        {
           if(a.get(i)-mindex>0){
               temp.add(a.get(i)-mindex);
           }

        } 
       a.clear();
       a=temp;


        }
        if(henrystatus)
            System.out.print("Henry");
        else
            System.out.print("garry");

    }

Solution

  • Small logical problem in your code because indexes in Java (or any programming language in general) start from zero, where naturally we count numbers from one. So when the minimum number was the first one, your mindex became zero due to which, zero (instead of actually one) was being subtracted in your array resulting into same array every time and was going in infinite loop.

    So you just need to add one in your index while finding min index from your array.

    Just change this line,

    int mindex = a.indexOf(Collections.min(a));
    

    to,

    int mindex = a.indexOf(Collections.min(a)) + 1;
    

    And your program will work just as you wanted and will no longer run into infinite loop.