Hey so I have just been using ArrayList for a particular problem but Here it is giving me an infinite loop still. According to logic the control should enter into one of the break statements after a few iterations but I just cannot figure out why I am getting this error . I have sorted the array b and I am comparing the contents of arraylist a with the maximum element of array b . for eg- a= 1 ,2 ,3 ,4 and maximum of element b=3
if the first element is lesser them max(b[]) then after removing that element the new arraylist becomes 2, 3 ,4 2 becomes the first element and so on and so forth .
package codechef;
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/*
5
3 1
4 3 5
6
3 3
2 4 7
2 3 7
3 3
2 7 4
2 7 3
4 4
2 6 5 1
4 6 5 2
2 2
7 4
7 4
*/
/* Name of the class has to be "Main" only if the class is public. */
class codechef2
{
public static void main (String[] args) throws java.lang.Exception
{
try
{
Scanner ob=new Scanner (System.in);
int t=ob.nextInt();
while(t-->0)
{
int n=ob.nextInt();
int m=ob.nextInt();
ArrayList <Integer> a=new ArrayList<Integer>();
int b[]=new int[m];
for(int i=0;i<n;i )
{
a.add(ob.nextInt());
}
for(int i=0;i<n;i )
{
System.out.println(a.get(i));
}
for(int i=0;i<m;i )
{
b[i]=ob.nextInt();
}
ob.close();
Arrays.sort(b);
int j=0;
String str="";
boolean flag=false;
while(true)
{
if(b[m-1]>a.get(0))
{
a.remove(0);
}
if(a.get(0)>=b[m-1])
{
flag=true;
str="NO";
break;
}
if(a.isEmpty())
{
str="YES";
break;
}
}
System.out.println("brej");
if(flag)
{
System.out.println(str);
}
else
{
for(int i:b)
{
System.out.print(i " ");
}
}
}
}
catch(Exception t)
{
return;
}
}
}
CodePudding user response:
Look here:
while(true)
{
if(b[m-1]<a.get(0))
{
a.remove(0);
}
if(a.get(0)>=b[m-1])
{
flag=true;
str="NO";
break;
}
if(a.isEmpty())
{
str="YES";
break;
}
}
See something wrong with the logic?
b[m-1] < a.get(0)
is the exact same condition as a.get(0) >= b[m-1]
. You need switch the logic to something like b[m-1]>=a.get(0)
to avoid an infinite loop, otherwise it won't break. I also suggest trying to use if / else if / else
for this kind of stuff.
CodePudding user response:
You can Fix your Programm with.
else { for(int i:b) { System.out.print(i " "); } break;
}
This will finish your doomsday Loop for while(True)