Solved

pre4 challenge

Posted on 2016-08-08
19
87 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
Comment Utility
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
Comment Utility
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
Comment Utility
I left the comment for a reason, I was hoping you might read it!
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
any improvements or modifications?
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 27

Assisted Solution

by:rrz
rrz earned 250 total points
Comment Utility
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
Comment Utility
  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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
@mccarl  yes, that is short and sweet.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
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
Comment Utility
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
Comment Utility
got it
0
 
LVL 35

Expert Comment

by:mccarl
Comment Utility
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

771 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

12 Experts available now in Live!

Get 1:1 Help Now