I have been working on codingbat problems for java and have come across a problem in array-2 which I cannot solve using only one loop. The problem is as follows :
Given a non-empty array of ints, return a new array containing the elements from the original array that come before the first 4 in the original array. The original array will contain at least one 4. Note that it is valid in java to create an array of length 0.
I looked at other solutions but they all use two loops, and the Array-2 problem set should be done using only one loop. I am not sure how to approach this, here is my solution with two loops :
public int[] pre4(int[] nums) {
int[] notnums = new int[0];
for(int i = 0; i<nums.length;i++)
if(nums[i]==4){
notnums = new int[i];
for(int j = 0;j<i;j++)
notnums[j] = nums[j];
return notnums;
}
return notnums;
}
As it's a coding challenge, I won't answer with code, instead, here's how you should approach it:
Declare another array
Start iterating first array, element by element
If the element is 4, break out of loop
If the element is not 4, add it into another array
In the end, second array should have all the elements that are present before first 4.
my solution for 1 loop:
public int[] pre4(int[] nums) {
int[] res = new int[0];
for(int i = nums.length - 1; i >= 0; i--){
if (nums[i] == 4)
res = new int[i];
else
if (res.length > 0)
res[i] = nums[i];
}
return res;
}
Related
This question already has answers here:
Trying to find all occurrences of an object in Arraylist, in java
(6 answers)
Closed 3 years ago.
Assumed
ArrayList<Integer> list = Arrays.asList(new Integer[] {1,2,3,4,5,6,1,8,9});
Find second occurence
I want to get the index of the second finding of the (multiple) contained element "1" but list.indexOf(1) will always return 0 (as it's the first finding).
Performance
I want to do this without using loops like for or while.
Since I need it for a game, using loops wouldn't be efficient at all.
EDIT: Is there any way to get "indexOf" some element without iterator ?
You cannot do this without iterating.
indexOf iterates, for example.
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
Same is valid for lastIndexOf.
As you can see no Iterator<Integer> is used at all, if that is what worries you.
And, btw, this isn't a performance concern.
Do you have arrays with millions of elements? If you have, consider changing data structure type.
If you are very much concerned about performance, use a HashMap<Integer, List<Integer>>. Then if your want n'th occurence of an element m, you can do map.get(m).get(n). Your map contains elements and their corresponding indexes.
Once your map is built, the time complexity for your query would be O(1)
Example:
public static void main(String[] args){
int[] a = {1, 2, 1, 3, 4, 1};
Map<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
for(int i = 0; i < a.length; i++){
if(map.containsKey(a[i])){
map.get(a[i]).add(i);
}else{
map.put(a[i], new ArrayList<Integer>());
map.get(a[i]).add(i);
}
}
// second index of 1. Note that index starts from 0.
System.out.println(map.get(1).get(1));
}
Result:
2
list.subList(list.indexOf(1) + 1, list.size()).indexOf(1)
list.indexOf(1, list.indexOf(1) + 1);
The first parameter 1 being the object to be searched.
The second parameter list.indexOf(1) + 1 being the starting index for the search.
Can I re-declare an Array that is already declared?
So I am trying to go through a LinkedList and get every index which includes "null" as an Element and add those indexes to an array of ints.
The problem I have is : The array is already declared as:
int[] solution = new int[0];
Can i redeclare it once again like lets say:
int newSize = 10;
solution = [newSize];
Does that work?
int k = 0;
int counter = 0;
if(!isEmpty())
{
for(int j = 0 ; j < size(); j++)
{
if(current.getContent().equals(null))
{
counter++;
}
}
result = new int[counter];
for(int i = 0 ; i < size(); i++)
{
if(current.getContent().equals(null))
{
result[k++] = i ;
}
}
}
I tried printing out the elements of Result but all i get is well... an empty array.
Short answer (as mentionned on java documentation => link)
The length of an array is established when the array is created. After creation, its length is fixed.
Some more details:
When you use :
int[] solution = new int[0]
you create an array that can hold 0 element and ask "solution" to refert to it.
If later on your code you use solution = new int[10] you will create an array that can hold 10 elements and ask "solution" to refer this new array.
The previous array still exists somewhere in the memory.
Search for "java memory management" if you want a full explanation.
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Consider input [3,2,4] and target is 6. I added (3,0) and (2,1) to the map and when I come to 4 and calculate value as 6 - 4 as 2 and when I check if 2 is a key present in map or not, it does not go in if loop.
I should get output as [1,2] which are the indices for 2 and 4 respectively
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
int[] arr = new int[2];
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0;i < len; i++)
{
int value = nums[i] - target;
if(map.containsKey(value))
{
System.out.println("Hello");
arr[0] = value;
arr[1] = map.get(value);
return arr;
}
else
{
map.put(nums[i],i);
}
}
return null;
}
I don't get where the problem is, please help me out
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice. Consider input [3,2,4] and target is 6. I added (3,0) and (2,1) to the map and when I come to 4 and calculate value as 6 - 4 as 2 and when I check if 2 is a key present in map or not, it does not go in if loop.
Okay, let's take a step back for a second.
You have a list of values, [3,2,4]. You need to know which two will add up 6, well, by looking at it we know that the answer should be [1,2] (values 2 and 4)
The question now is, how do you do that programmatically
The solution is (to be honest), very simple, you need two loops, this allows you to compare each element in the list with every other element in the list
for (int outter = 0; outter < values.length; outter++) {
int outterValue = values[outter];
for (int inner = 0; inner < values.length; inner++) {
if (inner != outter) { // Don't want to compare the same index
int innerValue = values[inner];
if (innerValue + outterValue == targetValue) {
// The outter and inner indices now form the answer
}
}
}
}
While not highly efficient (yes, it would be easy to optimise the inner loop, but given the OP's current attempt, I forewent it), this is VERY simple example of how you might achieve what is actually a very common problem
int value = nums[i] - target;
Your subtraction is backwards, as nums[i] is probably smaller than target. So value is getting set to a negative number. The following would be better:
int value = target - nums[i];
(Fixing this won't fix your whole program, but it explains why you're getting the behavior that you are.)
This code for twoSum might help you. For the inputs of integer array, it will return the indices of the array if the sum of the values = target.
public static int[] twoSum(int[] nums, int target) {
int[] indices = new int[2];
outerloop:
for(int i = 0; i < nums.length; i++){
for(int j = 0; j < nums.length; j++){
if((nums[i]+nums[j]) == target){
indices[0] = i;
indices[1] = j;
break outerloop;
}
}
}
return indices;
}
You can call the function using
int[] num = {1,2,3};
int[] out = twoSum(num,4);
System.out.println(out[0]);
System.out.println(out[1]);
Output:
0
2
You should update the way you compute for the value as follows:
int value = target - nums[i];
You can also check this video if you want to better visualize it. It includes Brute force and Linear approach:
My code so far:
public int[] arrayCreation1(int n) {
int[] a = new int[0];{}
int i = 0;
for (int i = 0) i<size.length) i++); {
}
return i;
}
How would I go about completing this?
the variable i is defined twice. If the variable "i" is for the for loop, you can initialise the variable in the loop itself just like you did "int i = 0".
the question stated that you are trying to fill in array with integers starting from 0 to n. You have accept a console input or hard code the value n.
Look up array initialisation and how to assign values.
I think this should get you started atleast.
I am new to programming too and this is what I felt was wrong.
As the comments have stated, your code has many issues:
You are defining a as an array of length 0
You define i as 0 twice
Your for loop is malformed
You have a semicolon after your for loop, which is seen as an empty stament and will prevent the loop from iterating over the block.
Size is not defined anywhere
You return i, which is an int not an array
Here's some code that will work, but I suggest you spend some time with a book or tutorial:
public int[] createArray(int n){
int[] out = new int[n];
for(int i = 0; i < n; i++){
out[i] = i;
}
return out;
}
class ArrayApp{
public static void main(final String[] args){
long [] arr;
arr= new long[100];
int i;
arr[0]=112;
arr[1]=111;
for(i=0;i<arr;i++) {
System.out.println(arr[i]);
}
}
}
I get this error,
ArrayApp.java:10: operator < cannot be applied to int,long[]
for(i=0;i<arr;i++) {
^
You need to use the size of the array, which would be arr.length.
for (int i = 0; i < arr.length; ++i)
As of Java 1.5, you can also use the for each loop if you just need access to the array data.
for ( long l : arr )
{
System.out.println(l);
}
arr is an object of long[] , you can't compare int with it.
Try arr.length
Alternatively You should go for
for(long item:arr){
System.out.println(item);
}
You want arr.length
The question has to be seen in the context of a previous question!
From this former question I remember that you actually have a logical array inside a physical array. The last element of the logical array is not arr.length but 2, because you've "added" two values to the logical array.
In this case, you can't use array.length for the iteration but again need another variable that store the actual position of "the last value" (1, in your case):
long[] arr;
arr= new long[100];
int i;
arr[0]=112;
arr[1]=111;
int nElem = 2; // you added 2 values to your "logical" array
for(i=0; i<=nElem; i++) {
System.out.println(arr[i]);
}
Note - I guess, you're actually learning the Java language and/or programming. Later on you'll find it much easier to not use arrays for this task but List objects. An equaivalent with List will look like this:
List<Integer> values = new ArrayList<Integer>();
values.add(112);
values.add(111);
for (Integer value:values)
System.out.println(value);
Long arr = new Long[100];
arr[0]=112;
arr[1]=111;
for(int i=0;i<arr.length;i++) {
if (arr[i] != null ) {
System.out.println(arr[i]);
}
}
if you want to show only those which are filled.
You can solve your problem using one line of code:
Arrays.asList(arr).toString().replace("[", "").replace("]", "").replace(", ", "\n");
See http://java.dzone.com/articles/useful-abuse for more similar tricks.