How could I set an int[] array to another int[]?
Example:
int array[] = new int{1, 2, 3, 4, 5};
int array2[] = new int[]array;
or
int array[] = new int{1, 2, 3, 4, 5};
int array2[] = array[];
But it doesn't work!
Can somebody tell me how?
Why didn't you try with the most obvious:
int[] array2 = array;
You can try to use
array2 = Arrays.copyOf(array, array.length);
From the Java docs:
copyOf
Copies the specified array, truncating or padding with zeros (if
necessary) so the copy has the specified length. For all indices that
are valid in both the original array and the copy, the two arrays will
contain identical values. For any indices that are valid in the copy
but not the original, the copy will contain 0. Such indices will exist
if and only if the specified length is greater than that of the
original array.
Any shortcut to create a Java array of the first n integers without doing an explicit loop?
In R, it would be
intArray = c(1:n)
(and the resulting vector would be 1,2,...,n).
If you're using java-8, you could do:
int[] arr = IntStream.range(1, n).toArray();
This will create an array containing the integers from [0, n). You can use rangeClosed if you want to include n in the resulting array.
If you want to specify a step, you could iterate and then limit the stream to take the first n elements you want.
int[] arr = IntStream.iterate(0, i ->i + 2).limit(10).toArray(); //[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Otherwise I guess the simplest way to do is to use a loop and fill the array. You can create a helper method if you want.
static int[] fillArray(int from, int to, int step){
if(to < from || step <= 0)
throw new IllegalArgumentException("to < from or step <= 0");
int[] array = new int[(to-from)/step+1];
for(int i = 0; i < array.length; i++){
array[i] = from;
from += step;
}
return array;
}
...
int[] arr3 = fillArray(0, 10, 3); //[0, 3, 6, 9]
You can adapt this method as your needs to go per example from an upperbound to a lowerbound with a negative step.
I am trying to access an array based on a number. Let me explain:
stringBuilder.append(array1[i]);
but I have 4 arrays, I would like to access the array like this:
int i;
int aNum;
stringBuilder.append(array(aNum)[i]);
so the array number selected depends on the value of aNum (1 - 4) where [i] being the location of the array (0 - n)
This code however doesn't work. Any ideas? Tried looking on google but can't find the correct code I need. It does seem simple but can't find the solution. Hope it makes sense!
You are referring to a two-dimensional array, which is an array of arrays. Here is an example:
/**
<P>{#code java TwoDArray}</P>
**/
public class TwoDArray {
public static final void main(String[] ignored) {
//Setup
int[][] intArrArr = new int[4][];
intArrArr[0] = new int[] {1, 2, 3, 4};
intArrArr[1] = new int[] {5, 6, 7, 8};
intArrArr[2] = new int[] {9, 10, 11, 12};
intArrArr[3] = new int[] {13, 14, 15, 16};
StringBuilder stringBuilder = new StringBuilder();
//Go
int indexOfIntInSelectedArray = 1; //The second element...
int indexOfArray = 2; //...in the third array.
stringBuilder.append(intArrArr[indexOfArray][indexOfIntInSelectedArray]);
//Output
System.out.println("stringBuilder.toString()=" + stringBuilder.toString());
}
}
Output:
[C:\java_code\]java TwoDArray
stringBuilder.toString()=10
Arrays can contain theoretically contain any number of dimensions:
https://www.google.com/search?q=multi+dimensional+array+java
https://www.google.com/search?q=three+dimensional+array+java
https://www.google.com/search?q=four+dimensional+array+java
Your array is a two dimensional array (array of arrays). You need to index using two pairs of brackets:
int rows = 4;
int cols = 5;
int[][] myArray = new int[rows][cols];
int row;
int col;
stringBuilder.append(myArray[row][col]);
I have seen acrosss in a company interview test this question, but i am not clear about the question first. Could you people clarify my doubt ?
Question : Write a program to sort an integer array which contains Only 0's,1's and 2's. Counting of elements not allowed, you are expected to do it in O(n) time complexity.
Ex Array : {2, 0, 1, 2, 1, 2, 1, 0, 2, 0}
Output to a linked list.
Remember the beginning of the list.
Remember the position where the 1s start.
Remember the end of the list.
Run through the whole array.
If you encounter a 0, add it to the first position of the linked list.
If you encounter a 1, add it after the position of the 1.
If you encounter a 2, add it at the end of the list.
HTH
Raku
Instead of blasting you with yet another unintelligible pseudo-code, I’ll give you the name of the problem: this problem is known as the Dutch national flag problem (first proposed by Edsgar Dijkstra) and can be solved by a three-ways merge (see the PHP code in the first answer which solves this, albeit very inefficiently).
A more efficient in-place solution of the threeways merge is described in Bentley’s and McIlroy’s seminal paper Engineering a Sort Function. It uses four indices to delimit the ranges of the intermediate array, which has the unsorted values in the middle, the 1s at both edges, and the 0s and 2s in-between:
After having established this invariant, the = parts (i.e. the 1s) are swapped back into the middle.
It depends what you mean by "no counting allowed".
One simple way to do this would be to have a new empty array, then look for 0's, appending them to the new array. Repeat for 1's then 2's and it's sorted in O(n) time.
But this is more-or-less a radix sort. It's like we're counting the 0's then 1's then 2's, so I'm not sure if this fits your criteria.
Edit: we could do this with only O(1) extra memory by keeping a pointer for our insertion point (starting at the start of the array), and scanning through the array for 0's, swapping each 0 with the element where the pointer is, and incrementing the pointer. Then repeat for 1's, 2's and it's still O(n).
Java implementation:
import java.util.Arrays;
public class Sort
{
public static void main(String[] args)
{
int[] array = {2, 0, 1, 2, 1, 2, 1, 0, 2, 0};
sort(array);
System.out.println(Arrays.toString(array));
}
public static void sort(int[] array)
{
int pointer = 0;
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < array.length; j++)
{
if(array[j] == i)
{
int temp = array[pointer];
array[pointer] = array[j];
array[j] = temp;
pointer++;
}
}
}
}
}
Gives output:
[0, 0, 0, 1, 1, 1, 2, 2, 2, 2]
Sorry, it's php, but it seems O(n) and could be easily written in java :)
$arr = array(2, 0, 1, 2, 1, 2, 1, 0, 2, 0);
$tmp = array(array(),array(),array());
foreach($arr as $i){
$tmp[$i][] = $i;
}
print_r(array_merge($tmp[0],$tmp[1],$tmp[2]));
In O(n), pseudo-code:
def sort (src):
# Create an empty array, and set pointer to its start.
def dest as array[sizeof src]
pto = 0
# For every possible value.
for val in 0, 1, 2:
# Check every position in the source.
for pfrom ranges from 0 to sizeof(src):
# And transfer if matching (includes update of dest pointer).
if src[pfrom] is val:
dest[pto] = val
pto = pto + 1
# Return the new array (or transfer it back to the source if desired).
return dest
This is basically iterating over the source list three times, adding the elements if they match the value desired on this pass. But it's still O(n).
The equivalent Java code would be:
class Test {
public static int [] mySort (int [] src) {
int [] dest = new int[src.length];
int pto = 0;
for (int val = 0; val < 3; val++)
for (int pfrom = 0; pfrom < src.length; pfrom++)
if (src[pfrom] == val)
dest[pto++] = val;
return dest;
}
public static void main(String args[]) {
int [] arr1 = {2, 0, 1, 2, 1, 2, 1, 0, 2, 0};
int [] arr2 = mySort (arr1);
for (int i = 0; i < arr2.length; i++)
System.out.println ("Array[" + i + "] = " + arr2[i]);
}
}
which outputs:
Array[0] = 0
Array[1] = 0
Array[2] = 0
Array[3] = 1
Array[4] = 1
Array[5] = 1
Array[6] = 2
Array[7] = 2
Array[8] = 2
Array[9] = 2
But seriously, if a potential employer gave me this question, I'd state straight out that I could answer the question if they wish, but that the correct answer is to just use Array.sort. Then if, and only if, there is a performance problem with that method and the specific data sets, you could investigate a faster way.
And that faster way would almost certainly involve counting, despite what the requirements were. You don't hamstring your developers with arbitrary limitations. Requirements should specify what is required, not how.
If you answered this question to me in this way, I'd hire you on the spot.
This answer doesn't count the elements.
Because there are so few values in the array, just count how many of each type there are and use that to repopulate your array. We also make use of the fact that the values are consecutive from 0 up - making it match the typical java int loop.
public static void main(String[] args) throws Exception
{
Integer[] array = { 2, 0, 1, 2, 1, 2, 1, 0, 2, 0 };
List<Integer>[] elements = new ArrayList[3]; // To store the different element types
// Initialize the array with new lists
for (int i = 0; i < elements.length; i++) elements[i] = new ArrayList<Integer>();
// Populate the lists
for (int i : array) elements[i].add(i);
for (int i = 0, start = 0; i < elements.length; start += elements[i++].size())
System.arraycopy(elements[i].toArray(), 0, array, start, elements[i].size());
System.out.println(Arrays.toString(array));
}
Output:
[0, 0, 0, 1, 1, 1, 2, 2, 2, 2]
Push and Pull have a constant complexity!
Push each element into a priority queue
Pull each element to indices 0...n
(:
You can do it in one pass, placing each encountered element to it's final position:
void sort012(int* array, int len) {
int* p0 = array;
int* p2 = array + len;
for (int* p = array; p <= p2; ) {
if (*p == 0) {
std::swap(*p, *p0);
p0++;
p++;
} else if (*p == 2) {
std::swap(*p, *p2);
p2--;
} else {
p++;
}
}
}
Because there are so few values in the array, just count how many of each type there are and use that to repopulate your array. We also make use of the fact that the values are consecutive from 0 up - making it match the typical java int loop.
The whole sorting algorithm requires only three lines of code:
public static void main(String[] args)
{
int[] array = { 2, 0, 1, 2, 1, 2, 1, 0, 2, 0 };
// Line 1: Define some space to hold the totals
int[] counts = new int[3]; // To store the (3) different totals
// Line 2: Get the total of each type
for (int i : array) counts[i]++;
// Line 3: Write the appropriate number of each type consecutively back into the array:
for (int i = 0, start = 0; i < counts.length; start += counts[i++]) Arrays.fill(array, start, start + counts[i], i);
System.out.println(Arrays.toString(array));
}
Output:
[0, 0, 0, 1, 1, 1, 2, 2, 2, 2]
At no time did we refer to array.length, no care how long the array was. It iterated through the array touching each element just once, making this algorithm O(n) as required.
This question already has answers here:
How can I concatenate two arrays in Java?
(66 answers)
Closed 9 years ago.
What is the best way (elegant/efficient) to copy two arrays into a new one ?
Regards,
F
My reputation doesn't allow me to comment on Adamski's answer, but there is an error on this line:
System.arraycopy(src2, 0, dest, src1.length - 1, src2.length);
With src1.length - 1 as an argument to destPos, you overwrite the last element copied from the src1 array. In this case you overwrite the element on index 4, which is the 5th element of the array.
This code might be easier to understand:
int[] array1 = { 1, 2, 3 };
int[] array2 = { 4, 5, 6, 7 };
int[] array3 = new int[ array1.length + array2.length ];
System.arraycopy( array1, 0, array3, 0, array1.length );
System.arraycopy( array2, 0, array3, array1.length, array2.length );
for (int i = 0; i < array3.length; i++) {
System.out.print( array3[i] + ", " );
}
You can use [System.arraycopy][1] as shown here.
[1]: http://download.oracle.com/javase/1.4.2/docs/api/java/lang/System.html#arraycopy(java.lang.Object, int, java.lang.Object, int, int)
Using System.arraycopy takes advantage of the underlying hardware to perform the array copy as efficiently as possible.
In the context of the question you would need to call System.arraycopy twice; e.g.
int[] dest = new int[10];
int[] src1 = new int[5];
int[] src2 = new int[5];
// Populate source arrays with test data.
for (int i=0; i<5; ++i) {
src1[i] = i;
src2[i] = i + 100;
}
System.arraycopy(src1, 0, dest, 0, src1.length);
System.arraycopy(src2, 0, dest, src1.length, src2.length);