Java > AP-1 > userCompare (CodingBat Solution)

Problem:

We have data for two users, A and B, each with a String name and an int id. The goal is to order the users such as for sorting. Return -1 if A comes before B, 1 if A comes after B, and 0 if they are the same. Order first by the string names, and then by the id numbers if the names are the same. Note: with Strings str1.compareTo(str2) returns an int value which is negative/0/positive to indicate how str1 is ordered to str2 (the value is not limited to -1/0/1). (On the AP, there would be two User objects, but here the code simply takes the two strings and two ints directly. The code logic is the same.)

userCompare("bb", 1, "zz", 2) → -1
userCompare("bb", 1, "aa", 2) → 1
userCompare("bb", 1, "bb", 1) → 0


Solution:

public int userCompare(String aName, int aId, String bName, int bId) {
  if (aName.equals(bName) && aId == bId)
    return 0;
  
  int result = aName.compareTo(bName);
  if (result < 0)
    return -1;
  else if (result > 0)
    return 1;
  else if (aId > bId)
    return 1;
  else
    return -1;
    
}


6 comments :

  1. public int userCompare(String aName, int aId, String bName, int bId) {
    int result = aName.compareTo(bName);
    if (result != 0) return result < 0 ? -1 : 1;

    result = aId - bId;
    if (result != 0) return result < 0 ? -1 : 1;

    return 0;
    }

    ReplyDelete
  2. int result=aName.compareTo(bName);

    if(result==0){
    if(aId==bId) return 0;
    return (aId>bId)? 1:-1;
    }
    return (result>0)? 1:-1;

    ReplyDelete
  3. public int userCompare(String aName, int aId, String bName, int bId) {

    if ( aName.compareTo(bName) == 0 ) {
    if (aId == bId){
    return 0;
    }
    return (aId < bId) ? -1 : 1;
    }
    return (aName.compareTo(bName) < 0) ? -1 : 1;
    }

    ReplyDelete
  4. public int userCompare(String aName, int aId, String bName, int bId) {
    if (aName.compareTo(bName) < 0) {
    return -1;
    }
    if (Objects.equals(aName, bName)) {
    return Integer.compare(aId, bId);
    }
    return 1;
    }

    ReplyDelete
  5. public int userCompare(String aName, int aId, String bName, int bId) {
    if (aName.compareTo(bName) < 0) {
    return -1;
    }
    return Objects.equals(aName, bName) ? Integer.compare(aId, bId) : 1;
    }

    ReplyDelete
  6. int s= !aName.equals(bName)?aName.compareTo(bName)/Math.abs(aName.compareTo(bName)):0;
    int ns = aId!=bId?(aId-bId)/Math.abs(aId-bId):0;
    return s==0?ns:s;

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact