Solved

haveThree challenge

Posted on 2016-08-07
22
121 Views
Last Modified: 2016-08-09
Hi,

I am working on below challenge

http://codingbat.com/prob/p109783

Psedo code description of approach :
1. Loop throgh given array
2. check if there is element of 3
3. if yes increment count by 1
4. if count is 3 return true
5. if no return false
6. not sure how to avoid if 3 is adjacent case?

I wrote my code as below

public boolean haveThree(int[] nums) {
  int count=0;
  boolean result=false;
  for(int i=0;i<nums.length;i++){
    if(nums[i]==3){
      count++;
    }
    if(count==3){
      result=true;
      
    }
    else{
      result=false;
    }
    
  }
  return result;
}

Open in new window




I am not passing all tests
Expected      Run            
haveThree([3, 1, 3, 1, 3]) → true      true      OK      
haveThree([3, 1, 3, 3]) → false      true      X      
haveThree([3, 4, 3, 3, 4]) → false      true      X      
haveThree([1, 3, 1, 3, 1, 2]) → false      false      OK      
haveThree([1, 3, 1, 3, 1, 3]) → true      true      OK      
haveThree([1, 3, 3, 1, 3]) → false      true      X      
haveThree([1, 3, 1, 3, 1, 3, 4, 3]) → false      false      OK      
haveThree([3, 4, 3, 4, 3, 4, 4]) → true      true      OK      
haveThree([3, 3, 3]) → false      true      X      
haveThree([1, 3]) → false      false      OK      
haveThree([3]) → false      false      OK      
haveThree([1]) → false      false      OK      
other tests
X      
How to improve my design, approach, code? please advise
0
Comment
Question by:gudii9
  • 8
  • 4
  • 2
  • +2
22 Comments
 
LVL 4

Assisted Solution

by:Hammadh Abdul Rahman
Hammadh Abdul Rahman earned 250 total points
ID: 41746622
You could use a boolean to indicate whether the previous value was 3.

So if the current value is 3 you can set the boolean to true. And if not to false. In the next iteration of the loop, you will need to check whether the current value is 3 and previous value also was 3 and return false.
0
 
LVL 27

Expert Comment

by:d-glitch
ID: 41747151
I think it is inappropriate to post code or psuedo code on these homework-tyupe questions until the Asker has at least had a chance to respond to an initial hint.
0
 
LVL 7

Author Comment

by:gudii9
ID: 41747254
prev_num=nums[i];  // Remember current num for next time through loop

Open in new window



why we need to do this step? I was not clear on above step?Please advise
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 7

Author Comment

by:gudii9
ID: 41747370
i got it now.
count3s.png
0
 
LVL 7

Author Comment

by:gudii9
ID: 41747374
public class TestTwo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] ar = { 3, 1, 3, 2, 3,3 };
		System.out.println("value is-->" + haveThree(ar));
	}

	public static boolean haveThree(int[] nums) {
		int count = 0;
		int prev_num = 0;
		for (int i = 0; i < nums.length; i++) {
			// Increment count only if current num is 3 and previous num is not
			// 3
			if (nums[i] == 3 && prev_num != 3) {
				count++;
			}
			prev_num = nums[i]; // Remember current num for next time through
								// loop
		}
		return count == 3; // Returns "true" if count is 3, otherwise returns
							// false
	}

}

Open in new window


above gave true which is wrong
0
 
LVL 7

Author Comment

by:gudii9
ID: 41747434
public boolean haveThree(int[] nums) {
  int count=0;
  int prev_value=0;
 // boolean result=false;
  for(int i=0;i<nums.length;i++){
    if(nums[i]==3&&prev_value!=3){
      count++;
    }
    prev_value=nums[i];
  }
  return count==3;
}

Open in new window


what is difference between above approach and below approach

public boolean haveThree(int[] nums) {
  int count=0;
  int prev_num=0;
  for(int i=0;i<nums.length;i++){
    if(nums[i]==3){
      count++;
      if(nums[i]==prev_num){
        count=9; // Just some non-3 number to signify failure
        break;   // Break out of loop.  Optional (just to save time looping through rest of elements for nothing)
      }
    }
    prev_num=nums[i];  // Remember current num for next time through loop
  }
  return count==3;  // Return true if count is 3, otherwise return false
}

Open in new window

i see one aditional if loop for
if(nums[i]==prev_num){
		        count=9; // Just some non-3 number to signify failure
		        break;   // Break out of loop.  Optional (just to save time looping through rest of elements for nothing)
		      }

Open in new window


to my eyes both above approaches are same. please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 41747464
i got it. In later case
when it nums[i] is 3 count is incremented by 1.
Now you are checking if prev_value ==3 if yes put count as some dumy 9 value and breaking away from loop so that below tests also pass
{3,1,3,2,3,3}

other wise checking prev_value!=3 after num[i] with && is not 100 % case

Open in new window

0
 
LVL 7

Author Comment

by:gudii9
ID: 41747510
in first approach if array is  like {3.1.3.2.3.3} it is giving true even though it is false as it checks bothe below conditions ahead of time


   
 if(nums[i]==3&&prev_value!=3){

Open in new window


above is not incrementing count from 3 to 4 wrongly as prev_value!=3 false
0
 
LVL 7

Author Comment

by:gudii9
ID: 41747514
moral lesson is breaking to small if cases is better than writing big chunk of if with bunch of && in between i guess
0
 
LVL 7

Author Comment

by:gudii9
ID: 41747956
public class HaveThree {

	public static void main(String[] args) {
		int[] ar={3,1,3,3};
    // TODO Auto-generated method stub
    System.out.println("is-->"+haveThree(ar));
	}

	public static boolean haveThree(int[] nums) {
		int cnt = 0;
		if (nums[0] == 3) {
			cnt++;
		}
		for (int i = 1; i < nums.length; i++) {
			if (nums[i] == 3) {
				cnt++;
			}
			if (nums[i] == 3 && nums[i - 1] == 3) {
				return false;
			}
		}
		return cnt == 3;

	}
}

Open in new window


above gave false while debugging
0
 
LVL 32

Expert Comment

by:awking00
ID: 41749314
Just want to point out that gudii9 has been asking these type of questions practically forever. There is no way these are academic assignments (I'll refrain on stating why I believe that). I have frequently tried to offer logical suggestions for his approaches before including any exact code. I thoroughly understand that we are not to provide precise answers for academic assignments and strive to obey that rule. However, I think a review of his many asked questions would demonstrate that this is not a typical academic or self-studying individual.
1
 
LVL 32

Accepted Solution

by:
awking00 earned 250 total points
ID: 41749380
Pseudo code description of approach :
1) get value of first element, if = 3 increment counter
2) loop through array starting at second element
3) if element at current index = 3 and element at previous index = 3, return false (no sense worrying about the count)
4) if element at current index = 3 increment counter
5) upon completion of loop return counter == 3
0
 
LVL 12

Expert Comment

by:tel2
ID: 41749579
Hi thermoduric,

The code that I posted in this question a couple of days ago contained 3 comments (in the actual code) which were intended to help the asker to understand how it worked in the areas which I thought explanation may be needed.  I also started my 1st post with a note about a possible improvement to the asker's code (i.e. moving a test out of the loop).

You deleted my 2 posts, providing this as the reason for doing so:
"Please refrain in the future from providing full code solutions to self study academic type questions. In the future, if you wish to help students learn, then please provide hints and wait for feedback from the author.
I have deleted your colde solutions for this reason."

And now your ruling has changed to:
"b) if it's self study then I am less strict and have no real problem with full solutions as long as the expert has made a reasonable attempt to educate the asker (or, at least follow up with them).

It's my opinion that (b) applies here and I don't really see any attempt by you (or other experts who did the same) to explain full code solutions. [Are you saying you didn't see the comments in or above my code?  Look again if you can still access it, or ask me and I can show you.]  I am happy for you to have another attempt to this and post helpful code is you believe that will educate; [ I believed that about the code I posted, but you deleted it.] however, you also need to provide some guidance for the asker so that they might actually learn from it."

Can you spot any major differences in your requirements above, thermoduric?  Can you see why I'm finding it hard to follow this moving target of what you deem acceptable for self study questions and what you don't?  Please explain.

Personally, I find that sometimes I'll learn better from (understandable) sample code than from teaching myself to do it some long and unnecessarily complex way.  I could have spent days trying to help the asker to see how to do it in an efficient way, but without posting some code (e.g. the 1 liner way of returning the result), the asker may never have got there.

On the basis of the last sentence of yours that I quoted above, would you be able to reinstate my posts, please?

Thanks.
tel2
0
 
LVL 12

Expert Comment

by:tel2
ID: 41749624
Hi thermoduric,

I'm sorry for mixing you up with phoffric, who deleted my posts.

Questions:
Q1. Do you have access to the posts of mine that phoffric deleted?  (If not, I can repost them here now, if needed.)
Q2. How do they violate this requrement from you?:
b) if it's self study then I am less strict and have no real problem with full solutions as long as the expert has made a reasonable attempt to educate the asker (or, at least follow up with them).

It's my opinion that (b) applies here and I don't really see any attempt by you (or other experts who did the same) to explain full code solutions.  I am happy for you to have another attempt to this and post helpful code is you believe that will educate; however, you also need to provide some guidance for the asker so that they might actually learn from it."

Thanks.
tel2
0
 
LVL 12

Expert Comment

by:tel2
ID: 41749638
Hi thermoduric,

> "There was no real attempt at explaining the code you posted, what it does, how it works nor what the asker could expect to learn from it."

I know I've touched on this before, but maybe you missed it so I'll go into more detail here:
Just looking at my 1st post (which was deleted), my real attempt at explaining things was to:
a) Suggest a possible improvement to the asker's code (i.e. moving a test out of the loop).
b) Include 3 comments (in the actual code) which were intended to help the asker to understand how it worked in the areas which I thought explanation may be needed.

Not wanting to spend unnecessary time on going into detail which may not be required, I left it to the asker to ask questions if it was still unclear.  He asked a question (post #41747254), and within an hour seemed to retract it with "i got it now" (post #41747370).

What was lacking on my part?

tel2
0
 
LVL 12

Expert Comment

by:tel2
ID: 41749679
Thanks thermoduric for leaving me in confusion about what level of commenting (i.e. explaining/documenting) is acceptable for the future, because if commenting the key areas of my code which I believe may need explanation, is not good enough, then I don't know what is, even with the (conflicting) guidelines that you and phoffric have provided.  If I had explained my code much more than I did (especially without request) then I could be making it too easy for the asker, which could also be argued as being not a good way to aid the process of learning.

In future maybe I need to contact you or phoffric before I post my code, to see if I've commented it to your satisfaction, so it doesn't get deleted.

tel2
0

Featured Post

Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
If you’re thinking to yourself “That description sounds a lot like two people doing the work that one could accomplish,” you’re not alone.
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

821 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