Solved

commonTwo  challenge

Posted on 2016-08-30
63
100 Views
Last Modified: 2016-09-07
Hi,
i am working one below challenge
http://codingbat.com/prob/p140485

i was not clear on below description



Start with two arrays of strings, a and b, each in alphabetical order, possibly with duplicates. Return the count of the number of strings which appear in both arrays. The best "linear" solution makes a single pass over both arrays, taking advantage of the fact that they are in alphabetical order.




how to approach this challenge. use two for loops and loop both arrays to see equality of elements and return count? please advise
0
Comment
Question by:gudii9
  • 28
  • 17
  • 17
  • +1
63 Comments
 
LVL 11

Expert Comment

by:tel2
ID: 41777588
Hi gudii9,

> 'Start with two arrays of strings, a and b, each in alphabetical order, possibly with duplicates. Return the count of the number of strings which appear in both arrays. The best "linear" solution makes a single pass over both arrays, taking advantage of the fact that they are in alphabetical order.'

Please explain why the above description differs from the one on the web page you have linked to.
0
 
LVL 7

Author Comment

by:gudii9
ID: 41778912
oops correct link is as below

http://codingbat.com/prob/p100369
0
 
LVL 7

Author Comment

by:gudii9
ID: 41778913
do i need 2 for loops to loop and compare each value from each array out of two?
0
 
LVL 7

Author Comment

by:gudii9
ID: 41782502
Pseudo code:
1. Loop through each element of Array A
2.Loop through each element of Array B
3, compare each element of A with every element of B
4. repeat till all elements finishes in A
5. if match increment count by1
6. return final count
0
 
LVL 7

Author Comment

by:gudii9
ID: 41782508
public int commonTwo(String[] a, String[] b) {
  int count=0;
  for(int i=0;i<a.length;i++){
  for(int j=0;i<b.length;j++){
   if( a[i].equals(b[j])){
     count++;
     i++;
   }
  }
  }
  
  return count;
}

Open in new window

Expected      Run            
commonTwo(["a", "c", "x"], ["b", "c", "d", "x"]) → 2      Exception:java.lang.ArrayIndexOutOfBoundsException: 4 (line number:5)      X      
commonTwo(["a", "c", "x"], ["a", "b", "c", "x", "z"]) → 3      Exception:java.lang.ArrayIndexOutOfBoundsException: 3 (line number:5)      X      
commonTwo(["a", "b", "c"], ["a", "b", "c"]) → 3      3      OK      
commonTwo(["a", "a", "b", "b", "c"], ["a", "b", "c"]) → 3      Exception:java.lang.ArrayIndexOutOfBoundsException: 3 (line number:5)      X      
commonTwo(["a", "a", "b", "b", "c"], ["a", "b", "b", "b", "c"]) → 3      Exception:java.lang.ArrayIndexOutOfBoundsException: 5 (line number:5)      X      
commonTwo(["a", "a", "b", "b", "c"], ["a", "b", "b", "c", "c"]) → 3      Exception:java.lang.ArrayIndexOutOfBoundsException: 5 (line number:5)      X      
commonTwo(["b", "b", "b", "b", "c"], ["a", "b", "b", "b", "c"]) → 2      Exception:java.lang.ArrayIndexOutOfBoundsException: 5 (line number:5)      X      
commonTwo(["a", "b", "c", "c", "d"], ["a", "b", "b", "c", "d", "d"]) → 4      Exception:java.lang.ArrayIndexOutOfBoundsException: 6 (line number:5)      X      
commonTwo(["a", "a", "b", "b", "c"], ["b", "b", "b"]) → 1      Exception:java.lang.ArrayIndexOutOfBoundsException: 3 (line number:5)      X      
commonTwo(["a", "a", "b", "b", "c"], ["c", "c"]) → 1      Exception:java.lang.ArrayIndexOutOfBoundsException: 2 (line number:5)      X      
commonTwo(["a", "a", "b", "b", "c"], ["b", "b", "b", "x"]) → 1      Exception:java.lang.ArrayIndexOutOfBoundsException: 4 (line number:5)      X      
commonTwo(["a", "a", "b", "b", "c"], ["b", "b"]) → 1      Exception:java.lang.ArrayIndexOutOfBoundsException: 2 (line number:5)      X      
commonTwo(["a"], ["a", "b"]) → 1      Exception:java.lang.ArrayIndexOutOfBoundsException: 1 (line number:5)      X      
commonTwo(["a"], ["b"]) → 0      Exception:java.lang.ArrayIndexOutOfBoundsException: 1 (line number:5)      X      
commonTwo(["a", "a"], ["b", "b"]) → 0      Exception:java.lang.ArrayIndexOutOfBoundsException: 2 (line number:5)      X      
commonTwo(["a", "b"], ["a", "b"]) → 2      2      OK      
other tests
X      
Your progress graph for this problem
i wrote as above failing some tests. please advise

if a and b same length passing others giving array index out of bound some reason?
0
 
LVL 11

Expert Comment

by:tel2
ID: 41782527
Hi gudii9,

Firstly, here's a couple of cosmetic suggestions:

Code indentation.  Indent things consistently (i.e. things within {braces}), so it's easier to understand the code when you (or the next person) has to read it.  For example:
public int commonTwo(String[] a, String[] b) {
  int count=0;
  for(int i=0;i<a.length;i++){
    for(int j=0;i<b.length;j++){
      if( a[i].equals(b[j])){
        count++;
        i++;
      }
    }
  }
  return count;
}

Open in new window


Don't make it unnecessarily complex.  Why are you using this long and confusing looking syntax:
   if( a[i].equals(b[j])){
instead of the simpler and more traditional:
      if(a[i] == b[j]){
Is there a reason?  I think both work, but why would you want to use the first option?

Now for some things with are causing your code to fail:

Why are you checking "i<b.length" here?:
  for(int j=0;i<b.length;j++){
why not "j<b.length"?

And inside this loop:
  for(int i=0; i<a.length; i++){
which increments i for you, why do you do this:
        i++;
So you're incrementing it in 2 places.

The above changes will not solve all the problems, but it's a start.

Here's another suggestion:

Your code has a loop within a loop (i.e. nested loops).  This means for every element of "a", you will compare every element of "b" to it.  This means it you had 1000 items in each array, it would do 1000 x 1000 = 1000,000 comparisons.  Sounds a bit inefficient to me, and this should not be necessary, especially since the arrays are sorted already.  But this nested loop strategy could still work, but you have to skip duplicates.
If you want to avoid the inefficiency of nesting the loops, for this situation maybe you could try to think about how a human would perform this task manually, and try to mimic that with your code.
0
 
LVL 7

Author Comment

by:gudii9
ID: 41783232
public int commonTwo(String[] a, String[] b) {
  int count=0;
  for(int i=0;i<a.length;i++){
  for(int j=0;i<b.length;j++){
   if( a[i]==b[j]){
     count++;
     i++;
   }
  }
  }
  
  return count;
}

Open in new window


i am passing if same elements both arrays failing other ones

Expected      Run            
commonTwo(["a", "c", "x"], ["b", "c", "d", "x"]) → 2      Exception:java.lang.ArrayIndexOutOfBoundsException: 4 (line number:5)      X      
commonTwo(["a", "c", "x"], ["a", "b", "c", "x", "z"]) → 3      Exception:java.lang.ArrayIndexOutOfBoundsException: 3 (line number:5)      X      
commonTwo(["a", "b", "c"], ["a", "b", "c"]) → 3      3      OK      
commonTwo(["a", "a", "b", "b", "c"], ["a", "b", "c"]) → 3      Exception:java.lang.ArrayIndexOutOfBoundsException: 3 (line number:5)      X      
commonTwo(["a", "a", "b", "b", "c"], ["a", "b", "b", "b", "c"]) → 3      Exception:java.lang.ArrayIndexOutOfBoundsException: 5 (line number:5)      X      
commonTwo(["a", "a", "b", "b", "c"], ["a", "b", "b", "c", "c"]) → 3      Exception:java.lang.ArrayIndexOutOfBoundsException: 5 (line number:5)      X      
commonTwo(["b", "b", "b", "b", "c"], ["a", "b", "b", "b", "c"]) → 2      Exception:java.lang.ArrayIndexOutOfBoundsException: 5 (line number:5)      X      
commonTwo(["a", "b", "c", "c", "d"], ["a", "b", "b", "c", "d", "d"]) → 4      Exception:java.lang.ArrayIndexOutOfBoundsException: 6 (line number:5)      X      
commonTwo(["a", "a", "b", "b", "c"], ["b", "b", "b"]) → 1      Exception:java.lang.ArrayIndexOutOfBoundsException: 3 (line number:5)      X      
commonTwo(["a", "a", "b", "b", "c"], ["c", "c"]) → 1      Exception:java.lang.ArrayIndexOutOfBoundsException: 2 (line number:5)      X      
commonTwo(["a", "a", "b", "b", "c"], ["b", "b", "b", "x"]) → 1      Exception:java.lang.ArrayIndexOutOfBoundsException: 4 (line number:5)      X      
commonTwo(["a", "a", "b", "b", "c"], ["b", "b"]) → 1      Exception:java.lang.ArrayIndexOutOfBoundsException: 2 (line number:5)      X      
commonTwo(["a"], ["a", "b"]) → 1      Exception:java.lang.ArrayIndexOutOfBoundsException: 1 (line number:5)      X      
commonTwo(["a"], ["b"]) → 0      Exception:java.lang.ArrayIndexOutOfBoundsException: 1 (line number:5)      X      
commonTwo(["a", "a"], ["b", "b"]) → 0      Exception:java.lang.ArrayIndexOutOfBoundsException: 2 (line number:5)      X      
commonTwo(["a", "b"], ["a", "b"]) → 2      2      OK      
other tests
X      
Your progress graph for this problem
0
 
LVL 7

Author Comment

by:gudii9
ID: 41783239
how to pass other tests
0
 
LVL 7

Author Comment

by:gudii9
ID: 41783254
public int commonTwo(String[] a, String[] b) {
		  int count=0;
		  String st="";
		  for(int i=0;i<a.length;i++){
		  for(int j=0;j<b.length;j++){
		   if( a[i]==b[j]){
		     count++;
		     i++;
		   }
		  }
		  }
		  
		  return count;
		}

Open in new window


passing more tests
Expected      Run            
commonTwo(["a", "c", "x"], ["b", "c", "d", "x"]) → 2      2      OK      
commonTwo(["a", "c", "x"], ["a", "b", "c", "x", "z"]) → 3      Exception:java.lang.ArrayIndexOutOfBoundsException: 3 (line number:6)      X      
commonTwo(["a", "b", "c"], ["a", "b", "c"]) → 3      3      OK      
commonTwo(["a", "a", "b", "b", "c"], ["a", "b", "c"]) → 3      3      OK      
commonTwo(["a", "a", "b", "b", "c"], ["a", "b", "b", "b", "c"]) → 3      4      X      
commonTwo(["a", "a", "b", "b", "c"], ["a", "b", "b", "c", "c"]) → 3      Exception:java.lang.ArrayIndexOutOfBoundsException: 5 (line number:6)      X      
commonTwo(["b", "b", "b", "b", "c"], ["a", "b", "b", "b", "c"]) → 2      4      X      
commonTwo(["a", "b", "c", "c", "d"], ["a", "b", "b", "c", "d", "d"]) → 4      Exception:java.lang.ArrayIndexOutOfBoundsException: 5 (line number:6)      X      
commonTwo(["a", "a", "b", "b", "c"], ["b", "b", "b"]) → 1      2      X      
commonTwo(["a", "a", "b", "b", "c"], ["c", "c"]) → 1      Exception:java.lang.ArrayIndexOutOfBoundsException: 5 (line number:6)      X      
commonTwo(["a", "a", "b", "b", "c"], ["b", "b", "b", "x"]) → 1      2      X      
commonTwo(["a", "a", "b", "b", "c"], ["b", "b"]) → 1      2      X      
commonTwo(["a"], ["a", "b"]) → 1      Exception:java.lang.ArrayIndexOutOfBoundsException: 1 (line number:6)      X      
commonTwo(["a"], ["b"]) → 0      0      OK      
commonTwo(["a", "a"], ["b", "b"]) → 0      0      OK      
commonTwo(["a", "b"], ["a", "b"]) → 2      2      OK      
other tests
X      
Your progress graph for this problem


package com.solution;

public class CommonTwo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String[] arr={"a", "c", "x"};
		String[] news= {"b", "c", "d", "x"};
		System.out.println("value is"+commonTwo(arr, news));

	}

	
	public static int commonTwo(String[] a, String[] b) {
		  int count=0;
		  String st="";
		  for(int i=0;i<a.length;i++){
		  for(int j=0;j<b.length;j++){
		   if( a[i]==b[j]){
		     count++;
		     i++;
		   }
		  }
		  }
		  
		  return count;
		}

}

Open in new window

value is2
0
 
LVL 7

Author Comment

by:gudii9
ID: 41783255
package com.solution;

public class CommonTwo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String[] arr={"a", "c", "x"};
		String[] news= {"b", "c", "d", "x","r"};
		System.out.println("value is"+commonTwo(arr, news));

	}

	
	public static int commonTwo(String[] a, String[] b) {
		  int count=0;
		  String st="";
		  for(int i=0;i<a.length;i++){
		  for(int j=0;j<b.length;j++){
		   if( a[i]==b[j]){
		     count++;
		     i++;
		   }
		  }
		  }
		  
		  return count;
		}

}

Open in new window


if b has 5 elements more getting below error

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
      at com.solution.CommonTwo.commonTwo(CommonTwo.java:19)
      at com.solution.CommonTwo.main(CommonTwo.java:9)
0
 
LVL 11

Expert Comment

by:tel2
ID: 41783326
You seem to have done the 2nd & 3rd thing that I suggested, but not the 1st or 4th.  Why are you asking for more help when you haven't even done all of those things yet?  Do you need me to tell you again?

Also, this layout is not very balanced looking:
    if( a[i]==b[j]){
I suggest this:
    if (a[i]==b[j]){

And instead of this:
    for(int i=0;i<a.length;i++){
consider spacing it out a bit like this:
    for (int i=0;i<a.length;i++){
or possibly even this:
    for (int i=0; i<a.length; i++){
Spacing can help with readability.

And why are you declaring/initialising this "st" variable if you aren't using it again for anything?
    String st="";
0
 
LVL 27

Expert Comment

by:rrz
ID: 41783710
Don't make it unnecessarily complex.  Why are you using this long and confusing looking syntax:
    if( a[i].equals(b[j])){
 instead of the simpler and more traditional:
       if(a[i] == b[j]){
 Is there a reason?  I think both work, but why would you want to use the first option?
That is bad advice.  Please look at the following code.
class Test{  
	public static void main(String args[]){  
		String me1 = "rrz";  
		String me2 = "rrz";  
		String me3 = new String("rrz");
		String me4 = new String("rrz");
		System.out.println(me1 == me2);  
		System.out.println(me3 == me4);
		System.out.println(me1 == me3);
		System.out.println(me2 == me4);
		String me5 = "RRZ".toLowerCase();
		System.out.println(" me5 is equal to " + me5);
		System.out.print(" Is " + me1 + " equal to " + me5 + " ? ");
		System.out.println(me1 == me5);
   }  
}  

Open in new window

The output:
true
false
false
false
 me5 is equal to rrz
 Is rrz equal to rrz ? false    

Also, you must consider the fact that there are duplicate elements in the arrays for this challenge .
Also, you should look at the code that ozo and zzynx posted at
https://www.experts-exchange.com/questions/28966734/mergeTwo-challenge.html  
 it will help you with this challenge.
0
 
LVL 27

Expert Comment

by:rrz
ID: 41783740
After you solve this using arrays, there is another(easier?) solution using HashSets.
0
 
LVL 11

Expert Comment

by:tel2
ID: 41784002
Thanks for that correction, rrz.  I'm a newbie to Java, as you can probably see.  I had just noticed gudii9's questions (because one topic area he had selected was Programming-Other), and it looked pretty simple, but it seems it was not as simple as I had thought.
However, despite the fact that it's probably not good practice, just out of interest, would you say that the use of "==" would give the correct results, in the context of the code I was putting it into?  I did test it before posting my suggestion, and it seemed to be working.
0
 
LVL 27

Expert Comment

by:rrz
ID: 41784125
@tel2, for this exercise, ==  would probably work.  As you can see in my code, me1 == me2 is true. But, we can't rely on it.  Google says
String comparison is a common scenario of using both == and equals method. Since java.lang.String class override equals method, It return true if two String object contains same content but == will only return true if two references are pointing to same object
You could research more about String pool and interning, but the bottom line: always use the equals method when comparing String content.
0
 
LVL 11

Expert Comment

by:tel2
ID: 41784175
OK, thanks rrz.
How about using '==' with integers, e.g.:
    if(nums[i]==3){
I first saw '==' used at this (highly authoritative) webpage: https://www.experts-exchange.com/questions/28962034/haveThree-challenge.html
0
 
LVL 27

Expert Comment

by:rrz
ID: 41784221
@tel2, in the haveThree challenge, nums was an array of ints. So, yes, the use of  ==  was appropriate.
0
 
LVL 11

Expert Comment

by:tel2
ID: 41784223
@rrz, was '==' appropriate because they are ints, or because they are ints in an array?
0
 
LVL 27

Expert Comment

by:rrz
ID: 41784251
'==' appropriate because they are ints
Yes.
0
 
LVL 11

Expert Comment

by:tel2
ID: 41784265
@rrz, OK, thanks.

@gudii9, pls disregard my question about using '.equals()' instead of '==' for comparing strings.  Although both should work in this particular example, the '==' wouldn't work in some cases (e.g. if the arrays were populated from a file).

Anyway, I see your EE Bio says you've been "Working in Java, J2EE development area for many years".  Doesn't that mean you would know how to handle these simple Java tasks?  Please explain.
0
 
LVL 7

Author Comment

by:gudii9
ID: 41785149
Also, this layout is not very balanced looking:
    if( a[i]==b[j]){
I suggest this:
    if (a[i]==b[j]){

And instead of this:
    for(int i=0;i<a.length;i++){
consider spacing it out a bit like this:
    for (int i=0;i<a.length;i++){
or possibly even this:
    for (int i=0; i<a.length; i++){
Spacing can help with readability.

Open in new window

i should put space after if and before ( for if and for loop and also after ; for traditional for loops.
0
 
LVL 7

Author Comment

by:gudii9
ID: 41785159
commonTwo(["a", "c", "x"], ["a", "b", "c", "x", "z"]) → 3	Exception:java.lang.ArrayIndexOutOfBoundsException: 3 (line number:6)

Open in new window


why i am getting ArrayIndexOutOfBoundsException for not equal length arrays?
How to avoid above error?
0
 
LVL 7

Author Comment

by:gudii9
ID: 41785167
lso, you should look at the code that ozo and zzynx posted at
https://www.experts-exchange.com/questions/28966734/mergeTwo-challenge.html  
 it will help you with this challenge.

that challenge is not yet
0
 
LVL 27

Expert Comment

by:rrz
ID: 41785211
tel2 posted:
So you're incrementing it in 2 places.
Are you still doing that?  
You should post your current code.  
that challenge is not yet
I am just thinking that the compareTo(as used by ozo) method might be useful here.
0
 
LVL 7

Author Comment

by:gudii9
ID: 41785470
how else we can solve without incrementing at both places since we need to compare each element of array A with each element of array B until array completes right?

public int commonTwo(String[] a, String[] b) {
		  int count=0;
		  String st="";
		  for(int i=0;i<a.length;i++){
		  for(int j=0;j<b.length;j++){
		   if( a[i]==b[j]){
		     count++;
		     i++;
		   }
		  }
		  }
		  return count;		}
/*Why are you checking "i<b.length" here?:
  for(int j=0;i<b.length;j++){
why not "j<b.length"?
And inside this loop:
  for(int i=0; i<a.length; i++){
which increments i for you, why do you do this:i++;
So you're incrementing it in 2 places.

The above changes will not solve all the problems, but it's a start.*/

Open in new window


my code looks as above still
0
 
LVL 11

Expert Comment

by:tel2
ID: 41785473
Sorry if I was unclear, but when I said this:
   And inside this loop:
      for(int i=0; i<a.length; i++){
    which increments i for you, why do you do this:
            i++;

I was (trying) to refer to these 2 places:
             for(int i=0;i<a.length;i++){            <= 1st place.  This is not what I meant by "inside the loop".
             for(int j=0;j<b.length;j++){            <= I was not referring to this place at all.  This is not 'i'.
              if( a[i]==b[j]){
                 count++;
                 i++;          
                                 <= 2nd place.  This is inside the loop.  Why are you doing this?

Next time, if you don't understand a bug fix that someone suggests, then please ask for clarification ASAP rather than ignoring them (twice) and then asking why your code still doesn't work.

I'm also sorry about the '==' advice I that gave you.
0
 
LVL 11

Expert Comment

by:tel2
ID: 41785478
Hi again gudii9,

I know I've asked this a few post ago, but I didn't get a response so I'll ask again:
   "Anyway, I see your EE Bio says you've been "Working in Java, J2EE development area for many years".  Doesn't that mean you would know how to handle these simple Java tasks?  Please explain."
0
 
LVL 7

Author Comment

by:gudii9
ID: 41785481
i do not think these are simple java tasks at-least to me
0
 
LVL 7

Author Comment

by:gudii9
ID: 41785483
All simple are not easy and all easy are not simple to me
0
 
LVL 11

Expert Comment

by:tel2
ID: 41785499
Have you read post #41785473, gudii9?
It is clear?
0
 
LVL 7

Author Comment

by:gudii9
ID: 41785501
public int commonTwo(String[] a, String[] b) {
		  int count=0;
		  String st="";
		  for(int i=0;i<a.length;i++){
		  for(int j=0;j<b.length;j++){
		   if( a[i]==b[j]){
		     count++;
		    // i++;
		   }
		  }
		  }
		  return count;		}
/*Why are you checking "i<b.length" here?:
  for(int j=0;i<b.length;j++){
why not "j<b.length"?
And inside this loop:
  for(int i=0; i<a.length; i++){
which increments i for you, why do you do this:i++;
So you're incrementing it in 2 places.

The above changes will not solve all the problems, but it's a start.*/

Open in new window


i commented additional i++.
I passed additioanal tests. Still failing some. please advise
Expected      Run            
commonTwo(["a", "c", "x"], ["b", "c", "d", "x"]) → 2      2      OK      
commonTwo(["a", "c", "x"], ["a", "b", "c", "x", "z"]) → 3      3      OK      
commonTwo(["a", "b", "c"], ["a", "b", "c"]) → 3      3      OK      
commonTwo(["a", "a", "b", "b", "c"], ["a", "b", "c"]) → 3      5      X      
commonTwo(["a", "a", "b", "b", "c"], ["a", "b", "b", "b", "c"]) → 3      9      X      
commonTwo(["a", "a", "b", "b", "c"], ["a", "b", "b", "c", "c"]) → 3      8      X      
commonTwo(["b", "b", "b", "b", "c"], ["a", "b", "b", "b", "c"]) → 2      13      X      
commonTwo(["a", "b", "c", "c", "d"], ["a", "b", "b", "c", "d", "d"]) → 4      7      X      
commonTwo(["a", "a", "b", "b", "c"], ["b", "b", "b"]) → 1      6      X      
commonTwo(["a", "a", "b", "b", "c"], ["c", "c"]) → 1      2      X      
commonTwo(["a", "a", "b", "b", "c"], ["b", "b", "b", "x"]) → 1      6      X      
commonTwo(["a", "a", "b", "b", "c"], ["b", "b"]) → 1      4      X      
commonTwo(["a"], ["a", "b"]) → 1      1      OK      
commonTwo(["a"], ["b"]) → 0      0      OK      
commonTwo(["a", "a"], ["b", "b"]) → 0      0      OK      
commonTwo(["a", "b"], ["a", "b"]) → 2      2      OK      
other tests
X
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 7

Author Comment

by:gudii9
ID: 41785502
repeat number of characters messing up the results looks like
0
 
LVL 27

Expert Comment

by:rrz
ID: 41785508
how else we can solve without incrementing at both places
You could use the "continue" statement. See second paragraph at
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html  
Your code would become
public int commonTwo(String[] a, String[] b) {
			int count=0;
		  String st="";
		  for(int i=0;i<a.length;i++){
		    for(int j=0;j<b.length;j++){
		      if( a[i]==b[j]){
		        count++;
		        continue;
		      }
		    }
	   }
		return count;	
}

Open in new window

If you plug that into CodingBat, then you will see that you are a little closer. You still haven't dealt with the fact that some tests have duplicate elements in the arrays.
we need to compare each element of array A with each element of array B until array completes right?
No. The challenge states
each in alphabetical order
 Let's look at the first example given by CodingBat
commonTwo(["a", "c", "x"], ["b", "c", "d", "x"]) → 2
By manually looking at the inputs, we can see the first element in the first array is "a" . If look at the first element of the second array, then we see that is "b".  Since the arrays are alphabetical order, we don't have to look at the rest of the second array. We already know that are no "a" in the second array.
0
 
LVL 11

Expert Comment

by:tel2
ID: 41785514
Hi rrz,

I don't think your placement of "continue" is achieving anything, because:
  a) "The continue statement skips the current iteration of a for, while , or do-while loop".
  b) There are no statements to skip after the "continue" line in that loop.

Don't you mean "break"?

I've never used "continue" or "break", but that's just because I haven't done Java programming apart from trying to help gudii9.
0
 
LVL 7

Author Comment

by:gudii9
ID: 41785518
By manually looking at the inputs, we can see the first element in the first array is "a" . If look at the first element of the second array, then we see that is "b".  Since the arrays are alphabetical order, we don't have to look at the rest of the second array. We already know that are no "a" in the second array.

above seems interesting hint. Not sure how to translate that to code?
public int commonTwo(String[] a, String[] b) {
		  int count=0;
		  String st="";
		  for(int i=0;i<a.length;i++){
		  for(int j=0;j<b.length;j++){
		   if( a[i]==b[j]){
		     count++;
		    // i++;
		    continue;
		   }
		  }
		  }
		  return count;		}
/*Why are you checking "i<b.length" here?:
  for(int j=0;i<b.length;j++){
why not "j<b.length"?
And inside this loop:
  for(int i=0; i<a.length; i++){
which increments i for you, why do you do this:i++;
So you're incrementing it in 2 places.

The above changes will not solve all the problems, but it's a start.*/

Open in new window


even after putting continue i still has same results
0
 
LVL 7

Author Comment

by:gudii9
ID: 41785519
public int commonTwo(String[] a, String[] b) {
		  int count=0;
		  String st="";
		  for(int i=0;i<a.length;i++){
		  for(int j=0;j<b.length;j++){
		   if( a[i]==b[j]){
		     count++;
		    // i++;
		    //continue;
		    break;
		   }
		  }
		  }
		  return count;		}
/*Why are you checking "i<b.length" here?:
  for(int j=0;i<b.length;j++){
why not "j<b.length"?
And inside this loop:
  for(int i=0; i<a.length; i++){
which increments i for you, why do you do this:i++;
So you're incrementing it in 2 places.

The above changes will not solve all the problems, but it's a start.*/

Open in new window


when i put break instead of continue i passed one other additional test
Expected      Run            
commonTwo(["a", "c", "x"], ["b", "c", "d", "x"]) → 2      2      OK      
commonTwo(["a", "c", "x"], ["a", "b", "c", "x", "z"]) → 3      3      OK      
commonTwo(["a", "b", "c"], ["a", "b", "c"]) → 3      3      OK      
commonTwo(["a", "a", "b", "b", "c"], ["a", "b", "c"]) → 3      5      X      
commonTwo(["a", "a", "b", "b", "c"], ["a", "b", "b", "b", "c"]) → 3      5      X      
commonTwo(["a", "a", "b", "b", "c"], ["a", "b", "b", "c", "c"]) → 3      5      X      
commonTwo(["b", "b", "b", "b", "c"], ["a", "b", "b", "b", "c"]) → 2      5      X      
commonTwo(["a", "b", "c", "c", "d"], ["a", "b", "b", "c", "d", "d"]) → 4      5      X      
commonTwo(["a", "a", "b", "b", "c"], ["b", "b", "b"]) → 1      2      X      
commonTwo(["a", "a", "b", "b", "c"], ["c", "c"]) → 1      1      OK      
commonTwo(["a", "a", "b", "b", "c"], ["b", "b", "b", "x"]) → 1      2      X      
commonTwo(["a", "a", "b", "b", "c"], ["b", "b"]) → 1      2      X      
commonTwo(["a"], ["a", "b"]) → 1      1      OK      
commonTwo(["a"], ["b"]) → 0      0      OK      
commonTwo(["a", "a"], ["b", "b"]) → 0      0      OK      
commonTwo(["a", "b"], ["a", "b"]) → 2      2      OK      
other tests
X
commonTwo(["a", "a", "b", "b", "c"], ["c", "c"]) → 1      1      OK      

not sure break passed above additional test alone?
0
 
LVL 27

Expert Comment

by:rrz
ID: 41785521
@tel2
I don't think your placement of "continue" is achieving anything

You may be right. But, I was just answering gudii9's question.
how else we can solve without incrementing at both places
  I don't know if it will lead him to a solution, but I did answer his question.
0
 
LVL 7

Author Comment

by:gudii9
ID: 41785523
i am bit confused when to use continue and when to use break both seems doing same similar things of breaking inner for loop?
0
 
LVL 11

Assisted Solution

by:tel2
tel2 earned 250 total points
ID: 41785526
Hi gudii9,

Please answer the following questions for me:

Q1. Are you planning to properly indent your code as per my 1st suggestion in post #41782527?

Q2. Did you see where rrz said my suggestion of using '==' to compare strings was bad?  And then did you see my responses to him and to you about that?  Why are you still using it?

Q3. Did you read the following from my post #41782527?

"The above changes will not solve all the problems, but it's a start.

Here's another suggestion:

Your code has a loop within a loop (i.e. nested loops).  This means for every element of "a", you will compare every element of "b" to it.  This means if you had 1000 items in each array, it would do 1000 x 1000 = 1000,000 comparisons.  Sounds a bit inefficient to me, and this should not be necessary, especially since the arrays are sorted already.  But this nested loop strategy could still work, but you have to skip duplicates.
If you want to avoid the inefficiency of nesting the loops, for this situation maybe you could try to think about how a human would perform this task manually, and try to mimic that with your code.
"

Q4. Why do you keep ignoring the suggestions we make, and then asking why your code doesn't work?  Our time is valuable.  We are helping you for free.  If you don't value our time then we might give up.

Please number your answers Q1 - Q4 for clarity.

Thanks.
tel2
0
 
LVL 11

Expert Comment

by:tel2
ID: 41785528
...and one more:
Q5. Did you see where I asked you:
And why are you declaring/initialising this "st" variable if you aren't using it again for anything?
    String st="";
Why do you still have that line?

I await your answers.

Thanks.
tel2
0
 
LVL 7

Author Comment

by:gudii9
ID: 41785531
i took care of point 1 and 2 and last comment

public int commonTwo(String[] a, String[] b) {
		  int count=0;
		  //String st="";
		  for (int i=0; i<a.length; i++){
		  for (int j=0; j<b.length; j++){
		   if (a[i].equals(b[j])){
		     count++;
		    // i++;
		    //continue;
		    break;
		   }
		  }
		  }
		  return count;		}
/*Why are you checking "i<b.length" here?:
  for(int j=0;i<b.length;j++){
why not "j<b.length"?
And inside this loop:
  for(int i=0; i<a.length; i++){
which increments i for you, why do you do this:i++;
So you're incrementing it in 2 places.

The above changes will not solve all the problems, but it's a start.*/

Open in new window


not clear on point 3 on how to proceed for solution?
0
 
LVL 27

Accepted Solution

by:
rrz earned 250 total points
ID: 41785538
i am bit confused when to use continue and when to use break both seems doing same similar things of breaking inner for loop?
It is explained at the link I gave above here.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html  
I posted "continue" as a direct answer to your question. "continue" is a way of jumping  to the next iteration. "break" breaks out of the loop.  
above seems interesting hint. Not sure how to translate that to code?

That is where the compareTo method will be useful to you.
http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#compareTo-java.lang.String-    
Instead of testing for just equality, the compareTo method will allow you decide what to do for three the three cases(see link).  For example,
if(a[aIndex].compareTo(b[bIndex]) < 0)

Open in new window

is true the you know that that element in the a array comes before the element in b array in the alphabet.
0
 
LVL 11

Expert Comment

by:tel2
ID: 41785539
Hi gudii9,

> "i took care of point 1 and 2 and last comment"
Q1 is still not taken care of.  Look at the example of code layout I gave you at the top of my post #41782527.  When your code is indented similarly, please post it here.

After that, please answer Q4 for me.

Thanks.
tel2
0
 
LVL 7

Author Comment

by:gudii9
ID: 41786209
package com.solution;

class BreakDemo {
	public static void main(String[] args) {

		int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 };
		int searchfor = 12;

		int i;
		boolean foundIt = false;

		for (i = 0; i < arrayOfInts.length; i++) {
			System.out.println("i is===>" + i);
			if (arrayOfInts[i] == searchfor) {
				foundIt = true;
				break;

			}
		}

		if (foundIt) {
			System.out.println("Found " + searchfor + " at index " + i);
		} else {
			System.out.println(searchfor + " not in the array");
		}
	}
}

Open in new window

i see break breaks the current loop here it is for loop as per that link
0
 
LVL 7

Author Comment

by:gudii9
ID: 41786310
package com.solution;

class BreakWithLabelDemo {
    public static void main(String[] args) {

        int[][] arrayOfInts = { 
            { 32, 87, 3, 589 },
            { 12, 1076, 2000, 8 },
            { 622, 127, 77, 955 }
        };
        int searchfor = 12;

        int i;
        int j = 0;
        boolean foundIt = false;

    search:
        for (i = 0; i < arrayOfInts.length; i++) {
            for (j = 0; j < arrayOfInts[i].length;
                 j++) {
            	System.out.println("i is--"+i+"---j is=="+j);
                if (arrayOfInts[i][j] == searchfor) {
                    foundIt = true;
                    break search;
                }
            }
        }

        if (foundIt) {
            System.out.println("Found " + searchfor + " at " + i + ", " + j);
        } else {
            System.out.println(searchfor + " not in the array");
        }
    }
}

Open in new window


labelled break breaking outer for loop instead
i is--0---j is==0
i is--0---j is==1
i is--0---j is==2
i is--0---j is==3
i is--1---j is==0
Found 12 at 1, 0

for this challenge do we need to break inner or outer loop?
0
 
LVL 7

Author Comment

by:gudii9
ID: 41786315
package com.solution;

class ContinueDemo {
    public static void main(String[] args) {

        String searchMe = "peter piper picked a " + "peck of pickled peppers";
        int max = searchMe.length();
        int numPs = 0;

        for (int i = 0; i < max; i++) {
            // interested only in p's
            if (searchMe.charAt(i) != 'p')
             //   continue;
            	

            // process p's
            numPs++;
        }
        System.out.println("Found " + numPs + " p's in the string.");
    }
}

Open in new window


Found 35 p's in the string.
package com.solution;

class ContinueDemo {
    public static void main(String[] args) {

        String searchMe = "peter piper picked a " + "peck of pickled peppers";
        int max = searchMe.length();
        int numPs = 0;

        for (int i = 0; i < max; i++) {
            // interested only in p's
            if (searchMe.charAt(i) != 'p')
                continue;

            // process p's
            numPs++;
        }
        System.out.println("Found " + numPs + " p's in the string.");
    }
}

Open in new window


Found 9 p's in the string.

when i comment continue i see 35 if i uncomment i get 9 as output(9 make sense but not 35

when i counted total characters below it is 49
peter piper picked a " + "peck of pickled peppers
0
 
LVL 7

Author Comment

by:gudii9
ID: 41786325
package com.solution;

class ContinueWithLabelDemo {
    public static void main(String[] args) {

        String searchMe = "Look for a substring in me";
        String substring = "sub";
        boolean foundIt = false;

        int max = searchMe.length() - 
                  substring.length();

    test:
        for (int i = 0; i <= max; i++) {
            int n = substring.length();
            int j = i;
            int k = 0;
            while (n-- != 0) {
                if (searchMe.charAt(j++) != substring.charAt(k++)) {
                    continue test;
                }
            }
            foundIt = true;
                break test;
        }
        System.out.println(foundIt ? "Found it" : "Didn't find it");
    }
}

Open in new window

Found it

labelled continue skips iteration of outer for loop
0
 
LVL 27

Expert Comment

by:rrz
ID: 41786407
for this challenge do we need to break inner or outer loop?
 I am not really sure which one. I will try to write out what I think you are trying to do in your code.
For each element of first array, check each element of the second array for equality.
So, I guess once you find an element in the second array that is beyond the first array's element in the alphabet, then you could break out of the inner loop because you know that it won't be found in the tail end of the array.  This is the case because the arrays are in alphabetical order.  
You still have to deal with duplicates.
In my solution, I only have one loop and I use "continue" not "break". But, I can't really say which approach is better.
0
 
LVL 7

Author Comment

by:gudii9
ID: 41786536
public int commonTwo(String[] a, String[] b) {
		
		  int count=0;
		  String st="";
		  for (int i=0; i<b.length; i++){
		    for (int j=0; j<a.length; j++){
		      if( (b[i].equals(a[j])) && (!st.contains(a[j])  )){
		        st=st+a[j];
		        count++;
		      }
		    }
		  }
		  return count;
		  }

Open in new window


above passes all tests
package com.solution;

public class CommonTwo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String[] arr = { "a", "c", "x", "a", "c", "x", "a", "c", "x" };
		String[] news = { "a", "c" };
		System.out.println("value is" + commonTwo(arr, news));

	}

	public static int commonTwo(String[] a, String[] b) {

		int count = 0;
		String st = "";
		for (int i = 0; i < b.length; i++) {
			for (int j = 0; j < a.length; j++) {
				if ((b[i].equals(a[j])) && (!st.contains(a[j]))) {
					st = st + a[j];
					count++;
				}
			}
		}
		return count;
	}
}

Open in new window

value is2

Basically after looping comparing each b element with each element of a we are also checking to see a element is not already counted for. continue till outer b loop ends with every element of a.
any improvements or alternate approaches? please advise
0
 
LVL 27

Expert Comment

by:rrz
ID: 41786575
above passes all tests
Great! I am glad that you stuck with your strategy and found a solution.
any improvements
You could consider what CodingBat stated.
The best "linear" solution makes a single pass over both arrays, taking advantage of the fact that they are in alphabetical order.
But, it is not necessary. Here is my array solution.
public int commonTwo(String[] a, String[] b) {
  	int count = 0;
    int aIndex = 0;
    int bIndex = 0;
    while(aIndex < a.length && bIndex < b.length){
        int comparison = a[aIndex].compareTo(b[bIndex]);
		if(comparison < 0 || (aIndex != 0 && a[aIndex].equals(a[aIndex - 1]))){
			aIndex++;
			continue;
	    }
		else if(comparison == 0){
			count++;
			aIndex++;
			bIndex++;
			continue;
		}
		else if(comparison > 0){
			bIndex++;
		  	continue;
		}
	}
	return count;
}

Open in new window

or alternate approaches?
 
public int commonTwo(String[] a, String[] b) {
  		int count=0;
  		HashSet setA = new HashSet(Arrays.asList(a));
  		HashSet setB = new HashSet(Arrays.asList(b));
  		Iterator iter = setA.iterator();
  		while(iter.hasNext()){
  		  if(setB.contains(iter.next()))count++;
  		}
		  return count;
}

Open in new window

0
 
LVL 7

Author Comment

by:gudii9
ID: 41786635
public int commonTwo(String[] a, String[] b) {
  		int count=0;
  		HashSet setA = new HashSet(Arrays.asList(a));
  		HashSet setB = new HashSet(Arrays.asList(b));
  		Iterator iter = setA.iterator();
  		while(iter.hasNext()){
  		  if(setB.contains(iter.next()))count++;
  		}
		  return count;
}

Open in new window

after creating 2 HashSets you are iteration setA to it has setB element if yes increment count? since HashSet duplicates removed?
0
 
LVL 27

Expert Comment

by:rrz
ID: 41786720
after creating 2 HashSets you are iteration setA to it has setB element if yes increment count?
Yes.
since HashSet duplicates removed?
Yes, look at
http://docs.oracle.com/javase/8/docs/api/java/util/Set.html
0
 
LVL 7

Author Comment

by:gudii9
ID: 41786915
public int commonTwo(String[] a, String[] b) {
  	int count = 0;
    int aIndex = 0;
    int bIndex = 0;
    while(aIndex < a.length && bIndex < b.length){
        int comparison = a[aIndex].compareTo(b[bIndex]);
		if(comparison < 0 || (aIndex != 0 && a[aIndex].equals(a[aIndex - 1]))){
			aIndex++;
			continue;
	    }
		else if(comparison == 0){
			count++;
			aIndex++;
			bIndex++;
			continue;
		}
		else if(comparison > 0){
			bIndex++;
		  	continue;
		}
	}
	return count;
}

Open in new window


can you please elaborate on above?

based on the comparison
int comparison = a[aIndex].compareTo(b[bIndex]);
greater than zero or equal to zero or less than zero incrementing and then using continue to skip current iteration?
0
 
LVL 11

Expert Comment

by:tel2
ID: 41786930
gudii9, I'll leave that explanation to rrz, but...

Well done both of you.

rrz, the 'continue' statements in your array solution are still not achieving anything.  This is because in each of the 3 places you put them, no further statements will be executed in that iteration of the loop even without them, so you're not skipping anything.  So, if you remove your 'continue' statements, you will get the same result.
0
 
LVL 27

Expert Comment

by:rrz
ID: 41787128
@tel2,
rrz, the 'continue' statements in your array solution are still not achieving anything.
You are right. I was wrong. I should have removed them, and have done so in the code below here.
can you please elaborate on above?
 Here is some demonstration code.
public class CT{
	public static void main(String[] args){
	    System.out.println(" First test ");
		String[] aFirst = new String[]{"a", "c", "x"};
		String[] bFirst = new String[]{"b", "b", "c", "d", "x"};
		System.out.println(" input ([a, c, x], [b, b, c, d, x]) ");
		System.out.println(" Gives output of " + commonTwo(aFirst, bFirst));
		System.out.println(" Second test ");
		String[] aSecond = new String[]{"a", "a", "b", "c", "c", "d", "d", "d"};
		String[] bSecond = new String[]{"a", "b", "b", "c", "c", "d", "d"};
		System.out.println(" input ([a, a, b, c, c, d, d, d], [a, b, b, c, c, d, d]) ");
		System.out.println(" Gives output of " + commonTwo(aSecond, bSecond));
	}
	public static int commonTwo(String[] a, String[] b) {
		int count = 0;
		int aIndex = 0;
		int bIndex = 0;
		while(aIndex < a.length && bIndex < b.length){
			int comparison = a[aIndex].compareTo(b[bIndex]);
			if(comparison < 0 || (aIndex != 0 && a[aIndex].equals(a[aIndex - 1]))){
				System.out.println(" comparison < 0: a[" + aIndex + "] is " 
				           + a[aIndex] + " and b[" + bIndex + "] is " + b[bIndex]);
				aIndex++;
			}
			else if(comparison == 0){
				System.out.println(" comparison ==0: a[" + aIndex + "] is " 
				           + a[aIndex] + " and b[" + bIndex + "] is " + b[bIndex]);
				count++;
				aIndex++;
				bIndex++;
			}
			else if(comparison > 0){
			    System.out.println(" comparison > 0: a[" + aIndex + "] is " 
				           + a[aIndex] + " and b[" + bIndex + "] is " + b[bIndex]);
				bIndex++;
			}
		}
		return count;
	}
}

Open in new window

The output:  
 First test
 input ([a, c, x], [b, b, c, d, x])
 comparison < 0: a[0] is a and b[0] is b
 comparison > 0: a[1] is c and b[0] is b
 comparison > 0: a[1] is c and b[1] is b
 comparison ==0: a[1] is c and b[2] is c
 comparison > 0: a[2] is x and b[3] is d
 comparison ==0: a[2] is x and b[4] is x
 Gives output of 2
 Second test
 input ([a, a, b, c, c, d, d, d], [a, b, b, c, c, d, d])
 comparison ==0: a[0] is a and b[0] is a
 comparison < 0: a[1] is a and b[1] is b
 comparison ==0: a[2] is b and b[1] is b
 comparison > 0: a[3] is c and b[2] is b
 comparison ==0: a[3] is c and b[3] is c
 comparison < 0: a[4] is c and b[4] is c
 comparison > 0: a[5] is d and b[4] is c
 comparison ==0: a[5] is d and b[5] is d
 comparison < 0: a[6] is d and b[6] is d
 comparison < 0: a[7] is d and b[6] is d
 Gives output of 4  
As you can see, the execution makes a single pass over both arrays.
0
 
LVL 11

Expert Comment

by:tel2
ID: 41787131
Thanks rrz.

Where/how can I run code like yours online?  Does codingbat.com have some facility to run code other than for their challenges?  I haven't found such a facility there yet.
0
 
LVL 27

Expert Comment

by:rrz
ID: 41787160
@tel2,
Where/how can I run code
Don't you have the  jdk on your computer?
0
 
LVL 7

Author Comment

by:gudii9
ID: 41787164
(aIndex != 0 && a[aIndex].equals(a[aIndex - 1]

why we are not doing this additional or check for comparison==0 and comparison<0 cases?(but doing only for comparison>0 case alone)
0
 
LVL 27

Expert Comment

by:rrz
ID: 41787197
why we are not doing this additional or check for comparison==0 and comparison<0 cases?
 It is only necessary to do that check(which is checking for duplicates) once because when a duplicate is found the code line  aIndex++;  is executed and the flow goes to the next iteration of the while loop.
Here is my pseudo code.
while( within array bounds){
   if(element in a array is before the element of b array in alphabet or duplicate is found)
        then go to next element in a array and continue to next iteration in while loop.  
   if(match is found)
      then increment count and go to next element in a array and go to next element in b array and continue to next iteration in while loop.
   if(element in b array is before the element of a array in alphabet)
      then go to next element in b array and continue to next iteration in while loop.  
}
0
 
LVL 11

Expert Comment

by:tel2
ID: 41787231
Hi rrz,
Don't you have the  jdk on your computer?
I don't think so.  Probably just JRE.  The only place I've done Java is on CodingBat trying to help gudii9 with a few of his challenges.
0
 
LVL 27

Expert Comment

by:rrz
ID: 41787932
0
 
LVL 31

Expert Comment

by:awking00
ID: 41788351
I didn't read all of these comments (way too many) but wanted to offer an alternative solution. If I've repeated someone's comment, please forgive me.
int count = 0;
Set<String> set = new HashSet<String>();
      for (String s : a) {
            set.add(s);  //this section removes dupes from String[] a
      }
      String[] c = set.toArray(new String[set.size()]); //set converted to String[]
      Arrays.sort(c); //sorted
      for (int i = 0; i < c.length; i++) {
            System.out.println(c[i]);
            if (ArrayUtils.contains(b,c[i])) { //checks to see if non-duplicated String exists in String[] b
                  count++;
            }
         return count;
      }
0
 
LVL 27

Expert Comment

by:rrz
ID: 41788580
@awking00  I did give a solution using HashSet.  Look at
https://www.experts-exchange.com/questions/28966735/commonTwo-challenge.html#a41786575    
Also, the challenge stated  
Start with two arrays of strings, a and b, each in alphabetical order,
No need to sort.
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

A short article about a problem I had getting the GPS LocationListener working.
Entering a date in Microsoft Access can be tricky. A typo can cause month and day to be shuffled, entering the day only causes an error, as does entering, say, day 31 in June. This article shows how an inputmask supported by code can help the user a…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now