Solved

pre4 challenge

Posted on 2016-08-08
19
99 Views
Last Modified: 2016-08-14
Hi,

I am working on below challenge
http://codingbat.com/prob/p100246

Psedo code description of approach :
1. create new arrray//not sure on size?
2. assign each element with new element arrays until not equal to 4
3. if above true return till there
 4 if false break for loop

I wrote my code as below

public int[] pre4(int[] nums) {
  
  
  
  int len =nums.length;
  int[] arr=new int[len];
  for(int i=0;i<len;i++){
    if(nums[i]!=4){
    arr[i]=nums[i];
    }
    else{
       break;
    }
  }
  return arr;



}

Open in new window

I am not passing all tests

Expected      Run            
pre4([1, 2, 4, 1]) → [1, 2]      [1, 2, 0, 0]      X      
pre4([3, 1, 4]) → [3, 1]      [3, 1, 0]      X      
pre4([1, 4, 4]) → [1]      [1, 0, 0]      X      
pre4([1, 4, 4, 2]) → [1]      [1, 0, 0, 0]      X      
pre4([1, 3, 4, 2, 4]) → [1, 3]      [1, 3, 0, 0, 0]      X      
pre4([4, 4]) → []      [0, 0]      X      
pre4([3, 3, 4]) → [3, 3]      [3, 3, 0]      X      
pre4([1, 2, 1, 4]) → [1, 2, 1]      [1, 2, 1, 0]      X      
pre4([2, 1, 4, 2]) → [2, 1]      [2, 1, 0, 0]      X      
pre4([2, 1, 2, 1, 4, 2]) → [2, 1, 2, 1]      [2, 1, 2, 1, 0, 0]      X      
other tests
X      
How to improve my design, approach, code? please advise
0
Comment
Question by:gudii9
  • 9
  • 6
  • 4
19 Comments
 
LVL 35

Accepted Solution

by:
mccarl earned 250 total points
ID: 41748235
You don't always have to try and do things in one go. Just use two loops.... the first to find the index of the first 4, now you can create your new array with the correct size, and then use a second loop to copy the elements from the original to new array.
0
 
LVL 7

Author Comment

by:gudii9
ID: 41749421
public int[] pre4(int[] nums) {
  int len =nums.length;
  int fourIndex=0;
  int[] arr=null;
  for(int i=0;i<fourIndex;i++){
    if(nums[i]==4){
      fourIndex=i;
         arr=new int[fourIndex];
    }
    if(nums[i]!=4){
    arr[i]=nums[i];
    }
    else{
       break;
    }
  }
  return arr;
}

Open in new window



i tried as above and getting errors as below

Expected      Run            
pre4([1, 2, 4, 1]) → [1, 2]      null      X      
pre4([3, 1, 4]) → [3, 1]      null      X      
pre4([1, 4, 4]) → [1]      null      X      
pre4([1, 4, 4, 2]) → [1]      null      X      
pre4([1, 3, 4, 2, 4]) → [1, 3]      null      X      
pre4([4, 4]) → []      null      X      
pre4([3, 3, 4]) → [3, 3]      null      X      
pre4([1, 2, 1, 4]) → [1, 2, 1]      null      X      
pre4([2, 1, 4, 2]) → [2, 1]      null      X      
pre4([2, 1, 2, 1, 4, 2]) → [2, 1, 2, 1]      null      X      
other tests
X      

how to get first 4 only not like second or third?
Also not able to properly initialize array and later to assign size in for loop?
0
 
LVL 35

Expert Comment

by:mccarl
ID: 41749642
I left the comment for a reason, I was hoping you might read it!
0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
LVL 7

Author Comment

by:gudii9
ID: 41751221
you mean below comment?
You don't always have to try and do things in one go. Just use two loops.... the first to find the index of the first 4, now you can create your new array with the correct size, and then use a second loop to copy the elements from the original to new array.
0
 
LVL 35

Expert Comment

by:mccarl
ID: 41751425
Given that I had only made ONE comment, then yes, that would be the one I was referring to!
0
 
LVL 7

Author Comment

by:gudii9
ID: 41751440
public class PreFour {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] ar = { 11, 21, 4, 38 };
		System.out.println("value===>" + pre4(ar));

	}

	public static int[] pre4(int[] nums) {
/*		You don't always have to try and do things in one go. Just use two loops....
		the first to find the index of the first 4, now you can create your new 
		array with the correct size, 
		and then use a second loop to copy the elements from the original to new array.*/
		int len = nums.length;
		
		int val=0;
		for (int i = 0; i < len; i++) {
			if (nums[i] == 4) {
				val=i;
			}
		}
		int[] arr = new int[val];
		for (int k = 0; k < val; k++) {
		arr[k] =nums[i];
			}
		}return arr;

}

}

Open in new window


how to copy old array to new array. I cannot refer i which is in first for loop inside second for loop which needs to be assigned. please advse
0
 
LVL 35

Expert Comment

by:mccarl
ID: 41751634
how to copy old array to new array. I cannot refer i which is in first for loop inside second for loop which needs to be assigned

You don't need i at that point. Line 25 of the above should be just (note: no i it just uses k)...

arr[k] = nums[k];

Open in new window


Also, note that in your first loop you can, and SHOULD, exit the loop when you find the first 4. Otherwise,  if there is another 4, you will update val to a different value and get the wrong result. So just add a       break;      statement between lines 20 and 21
0
 
LVL 7

Author Comment

by:gudii9
ID: 41752410
public int[] pre4(int[] nums) {
  int len = nums.length;
  int val=0;
		for (int i = 0; i < len; i++) {
			if (nums[i] == 4) {
				val=i;
				break;
			}
		}
		int[] arr = new int[val];
		for (int k = 0; k < val; k++) {
		arr[k] =nums[k];
			}
		
		return arr;
		}

Open in new window

Expected      Run            
pre4([1, 2, 4, 1]) → [1, 2]      [1, 2]      OK      
pre4([3, 1, 4]) → [3, 1]      [3, 1]      OK      
pre4([1, 4, 4]) → [1]      [1]      OK      
pre4([1, 4, 4, 2]) → [1]      [1]      OK      
pre4([1, 3, 4, 2, 4]) → [1, 3]      [1, 3]      OK      
pre4([4, 4]) → []      []      OK      
pre4([3, 3, 4]) → [3, 3]      [3, 3]      OK      
pre4([1, 2, 1, 4]) → [1, 2, 1]      [1, 2, 1]      OK      
pre4([2, 1, 4, 2]) → [2, 1]      [2, 1]      OK      
pre4([2, 1, 2, 1, 4, 2]) → [2, 1, 2, 1]      [2, 1, 2, 1]      OK      
other tests
OK      
import java.util.Arrays;

public class PreFour {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] ar = { 11, 21, 4, 38 };
		System.out.println("value===>" + Arrays.toString(pre4(ar)));

	}

	public static int[] pre4(int[] nums) {
/*		You don't always have to try and do things in one go. Just use two loops....
		the first to find the index of the first 4, now you can create your new 
		array with the correct size, 
		and then use a second loop to copy the elements from the original to new array.*/
		int len = nums.length;		
		int val=0;
		for (int i = 0; i < len; i++) {
			if (nums[i] == 4) {
				val=i;
				break;
			}
		}
		int[] arr = new int[val];
		
		for (int k = 0; k < val; k++) {
		arr[k] =nums[k];
			}
		return arr;

}

}

Open in new window


value===>[11, 21]

i passed all tests now
0
 
LVL 7

Author Comment

by:gudii9
ID: 41752414
any improvements or modifications?
0
 
LVL 27

Assisted Solution

by:rrz
rrz earned 250 total points
ID: 41752805
There is a convenience method to copy arrays. CodingBat doesn't allow it but it is very handy.
import java.util.Arrays;
public class PreFour {
	public static void main(String[] args) {
        int[] ar = { 5, 21, 11, 21, 4, 38, 4, 19, 88};
		System.out.println("original array ===> " + Arrays.toString(ar)); 
		System.out.println("new array ===> " + Arrays.toString(pre4(ar)));
	}
	public static int[] pre4(int[] nums) {
		int val=0;
		for (int i = 0; i < nums.length; i++) {
			if(nums[i] == 4){
				val = i;
				break;
			}
		}
		int[] arr = new int[val];
	    System.arraycopy(nums, 0, arr, 0, val);
		return arr;
    }
}

Open in new window

0
 
LVL 7

Author Comment

by:gudii9
ID: 41753326
  System.arraycopy(nums, 0, arr, 0, val);

why above takes 5 arguments what is meaning of above line? we copying from nums to arr right from position 0 to val? why we used 0 two times?
0
 
LVL 7

Author Comment

by:gudii9
ID: 41753328
i understood it

http://www.tutorialspoint.com/java/lang/system_arraycopy.htm
Parameters
src -- This is the source array.

srcPos -- This is the starting position in the source array.

dest -- This is the destination array.

destPos -- This is the starting position in the destination data.

length -- This is the number of array elements to be copied.

Return Value
0
 
LVL 27

Expert Comment

by:rrz
ID: 41753367
Good. You found that link. But, your best friend is the API. See  
http://docs.oracle.com/javase/8/docs/api/java/lang/System.html
0
 
LVL 35

Expert Comment

by:mccarl
ID: 41753818
Using built-in functions, this might be close to as short as possible (and works on CodingBat)...

for (int i = 0; i < nums.length; i++) {
    if (nums[i] == 4) {
        return Arrays.copyOf(nums, i);
    }
}
return null;

Open in new window

0
 
LVL 27

Expert Comment

by:rrz
ID: 41754042
@mccarl  yes, that is short and sweet.
0
 
LVL 7

Author Comment

by:gudii9
ID: 41755184
public int[] pre4(int[] nums) {for (int i = 0; i < nums.length; i++) {
    if (nums[i] == 4) {
        return Arrays.copyOf(nums, i);
    }
}
return null;
  
}

Open in new window


when does return null; is called. I do not see any test case where
nuns[i]!=4

Open in new window

??
0
 
LVL 27

Expert Comment

by:rrz
ID: 41755204
when does return null;
There won't be an event because they specified that
The original array will contain at least one 4.
But, if you remove
return null;

Open in new window

then you see "Compile problems:" message.
0
 
LVL 7

Author Comment

by:gudii9
ID: 41755532
got it
0
 
LVL 35

Expert Comment

by:mccarl
ID: 41755841
Or maybe a better way to code it (although it doesn't change the outcome because the last line never gets executed in the codingbat test cases)...

public int[] pre4(int[] nums) {
  for (int i = 0; i < nums.length; i++) {
    if (nums[i] == 4) {
        return Arrays.copyOf(nums, i);
    }
  }
  throw new IllegalArgumentException("The input array must contain at least one value of 4");
}

Open in new window

0

Featured Post

DevOps Toolchain Recommendations

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

Question has a verified solution.

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

Suggested Solutions

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.

813 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

16 Experts available now in Live!

Get 1:1 Help Now