Java > AP-1 > matchUp (CodingBat Solution)

Problem:

Given 2 arrays that are the same length containing strings, compare the 1st string in one array to the 1st string in the other array, the 2nd to the 2nd and so on. Count the number of times that the 2 strings are non-empty and start with the same char. The strings may be any length, including 0.

matchUp({"aa", "bb", "cc"}, {"aaa", "xx", "bb"}) → 1
matchUp({"aa", "bb", "cc"}, {"aaa", "b", "bb"}) → 2
matchUp({"aa", "bb", "cc"}, {"", "", "ccc"}) → 1


Solution:

public int matchUp(String[] a, String[] b) {
  int count = 0;
  for (int i = 0; i < a.length; i++) {
    String tmp1 = a[i];
    String tmp2 = b[i];
    if (!tmp1.equals("") && !tmp2.equals("")) {
      if (tmp1.charAt(0) == tmp2.charAt(0))
        count++;
    }
    
  }
  return count;
}


4 comments :

  1. String tmp1 = a[i];
    String tmp2 = b[i];


    These string variables should be declared outside the for loop. Declare once, use over and over again.

    ReplyDelete
  2. int count = 0;

    for(int i=0; i<a.length; i++){
    if(!b[i].isEmpty() && !a[i].isEmpty() && a[i].substring(0, 1).equals(b[i].substring(0, 1))) count++;
    }

    return count;

    ReplyDelete
  3. public int matchUp(String[] a, String[] b) {
    int c = 0;
    for(int i = 0; i < a.length; i++){
    if(a[i].length() == 0 || b[i].length() == 0){
    continue;
    }
    if(a[i].charAt(0) == b[i].charAt(0)){
    c++;
    }
    }
    return c;
    }

    hopefully more understandable.

    ReplyDelete
  4. With Java Stream

    public int matchUp(String[] a, String[] b) {
    return (int)java.util.stream.IntStream.range(0, a.length)
    .filter(i -> !a[i].equals("") && !b[i].equals(""))
    .filter(i -> a[i].charAt(0) == b[i].charAt(0))
    .count();
    }

    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