Country Code List= 92, 445, 445, 966, 92, 445, 966, 966, 92
Price List = 0.99, 0.91, 0.92, 0.97, 0.93, 0.97, 0.92, 0.97, 1.0
Operator List= A, C, A, B, C, B, A, C, A
I am supposed to find minimum price list and corresponding operator when user enter a country code.
Country Code data can be duplicated. It is not Unique. e.g. as we don’t know countrycode: 92 belongs to which operator, 92 can exist for operator A, B, or C in the countrycode List.
I have written the code below. but It has a problem,
Problem : i am able to sort CountryCode , but binarySearch in the following code can not figure out the minimum price list correspondingly. It always gives me random value which is not minimum price. Improvement for the following code will be appreciated.
class Dog implements Comparator<Dog>, Comparable<Dog>{
private int CountryCode;
private double Price;
private String Operator;
Dog(){
}
Dog( int c, double p, String o){
CountryCode= c;
Price= p;
Operator=o;
}
public int getCountryCode(){
return CountryCode;
}
public double getPrice(){
return Price;
}
public String getOperator(){
return Operator;
}
// Overriding the compareTo method
public int compareTo(Dog d){
return CountryCode- d.getCountryCode();
}
// Overriding the compare method to sort the age
public int compare(Dog d, Dog d1){
return d.CountryCode - d1.CountryCode;
}
}
public class Ser {
/**
* @param args
*/
public static void main(String[] args) {
// Takes a list o Dog objects
ArrayList <Dog> list1 = new ArrayList<Dog>();
list1.add(new Dog(92, 0.99 , "A"));
list1.add(new Dog(445, 0.91 , "C"));
list1.add(new Dog(445, 0.92 , "A"));
list1.add(new Dog(966, 0.97 , "B"));
list1.add(new Dog(92, 0.93 , "C"));
list1.add(new Dog(445, 0.97 , "B"));
list1.add(new Dog(966, 0.92, "A"));
list1.add(new Dog(966,0.97, "C"));
list1.add(new Dog(92,1.0, "A"));
// Sorts the array list using comparator
Collections.sort(list1, new Dog());
for(Dog a: list1)//printing the sorted list of ages
System.out.println(a.getCountryCode() +" : "+
a.getOperator()+" : "+ a.getPrice());
int index= Collections.binarySearch(list1, new Dog ( 92,null,null));
if (index>=0)
System.out.println( list1.get(index).getOperator()+ " " + list1.get(index).getPrice());
else
System.out.println("No operator is availible");
}}
You never sorted the list by price, so you should not expect to get the minimum price.
At first look, the list is sorted in order of the country code.
The order of the prices within each country code is random depending on both:
rolfl
Edit:
You ask what the right approach should be…. there are three that come to mind: