Combine two arrays into one - java

I am trying to combine two arrays into one big array.
But I don't understand why it wont work.
Here's my code:
public class TestaCombine {
private int[] arrayX = new int[20];
private int[] arrayY = new int[6];
private int[] ratings;
public void getRanks(){
arrayX[0] = 3;
arrayX[1] = 4;
arrayX[2] = 2;
arrayX[3] = 6;
arrayX[4] = 2;
arrayX[5] = 5;
arrayY[0] = 9;
arrayY[1] = 7;
arrayY[2] = 5;
arrayY[3] = 10;
arrayY[4] = 6;
arrayY[5] = 8;
}
public void combine(){
ratings = new int[arrayX.length + arrayY.length];
System.arraycopy(arrayX, 0, ratings, 0, arrayX.length);
System.arraycopy(arrayY, 0, ratings, arrayX.length, arrayY.length);
Arrays.sort(ratings);
}
public void print(){
System.out.println(Arrays.toString(ratings));
}
public static void main(String[] args){
TestaCombine tc = new TestaCombine();
tc.getRanks();
tc.combine();
tc.print();
}
The output I am getting looks like this:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 3, 4, 5, 5, 6, 6, 7, 8, 9, 10]
Don't understand where all the 0s comes from.

Note that the size of arrayX is 20. By default, ints have 0 value in Java. See the JLS - 4.12.5. Initial Values of Variables:
For type int, the default value is zero, that is, 0.
So when you do:
System.arraycopy(arrayX, 0, ratings, 0, arrayX.length);
It copies the zeros as well.

You're combining an array of size 6 with an array of size 20. The resulting array therefore has a size of 26.
But you've only specified 12 values, so the rest are filled in with values of 0. As you're sorting the collections, this also puts all the 0s at the start of the array.

It is because you have created one array with size of 20 and you only initialized 6 values within it, the rest of values where initialized during array initialization and they were all populated to 0's. When you combined array of size 20 and array of size 6 you received array of size 26 where 14 values are 0's
I would also like to recommend you apache commons libraries which contains nice set of tools for managing different collections.

Related

Copy an array into the end of a larger array

I want to copy an array into a larger array, but instead of starting at the first element or a specified element, such as System.arraycopy(), I want it to start at the last element and move backward.
int [] ary1 = new int[5] {1,2,3,4,5};
int [] ary2 = new int [10];
and I want the elements in ary2 to equal
0,0,0,0,0,1,2,3,4,5
or
null,null,null,null,null,1,2,3,4,5
You can use the method System.arrayCopy() for that purpose. Since you use an array of primitive int type, the resulting array will be [0, 0, 0, 0, 0, 1, 2, 3, 4, 5]
System.arraycopy(ary1, 0, ary2, 5, ary1.length);
The arguments are:
Source-array
Start-position in source-array
Destination-array
Start-position in destination-array
Number of elements to copy
This will work
int [] ary1 = {1,2,3,4,5};
int [] ary2 = new int [10];
int y = ary2.length-1;
for (int i = ary1.length-1; i >=0; i--) {
ary2[y]=ary1[i];
y--;
}

Rewrite a Java array based on the values of another array

I've been working in a little Java project but I can't figure out how to overwrite the elements of an array based on the values on another array.
Basically I have two arrays: repeated[] = {1,4,0,0,0,3,0,0} and hand[] = {1,2,2,2,2,6,6,6} and I use repeated[] to count the amount of times a number appears on hand[], and if it is between 3 and 7 it should overwrite the corresponding element in hand[] with a zero but I keep getting this output {1,0,0,2,2,6,0,6} when it should give me {1,0,0,0,0,0,0,0}. What am I doing wrong?
public static void main(String[] args) {
int repeated[] = {1,4,0,0,0,3,0,0};
int hand[] = {1,2,2,2,2,6,6,6};
for(int z=0;z<repeated.length;z++){
if(repeated[z]>=3 && repeated[z]<8){
for(int f:hand){
if(hand[f]==(z+1)){
hand[f]=0;
} } } }
for(int e:hand){
System.out.print(e+",");
}
}
First, the value in repeated is offset by one (because Java arrays start at index zero). Next, you need to test if the value is >= 3 (because 6 only appears 3 times). And, you could use Arrays.toString(int[]) to print your array. Something like,
public static void main(String[] args) {
int repeated[] = { 1, 4, 0, 0, 0, 3, 0, 0 };
int hand[] = { 1, 2, 2, 2, 2, 6, 6, 6 };
for (int z = 0; z < repeated.length; z++) {
if (repeated[hand[z] - 1] >= 3) {
hand[z] = 0;
}
}
System.out.println(Arrays.toString(hand));
}
Output is
[1, 0, 0, 0, 0, 0, 0, 0]

How to store a 2D array in a regular array? Java

basically I want to be able to store a 2D array such as this
int [][] preferredMoves = {
{0,0}, {0, arrLength}, {length%2, arrLength},
{0, length%2}, {arrLength, 0}, {0, length%2},
{arrLength, arrLength}, {length%2, length%2},
{arrLength, length%2}, {length%2, 0}
};
In a single
int [] moves;
array.
I'm sure this is possible since I'm just storing a list..., but I can't seem to find information on this anywhere... or maybe its not possible?
EDIT
I am dealing with matrices.
I want to store the list in a single array to then return that array to use it elsewhere.
So then every time I call it, all I have to do is something like this...
int row = Computer.moves()[0];
int col = Computer.moves()[1];
I also need to loop through that single array, which contains the 2D array multiple times..
Not sure if this is what you meant,
but you could drop the internal { ... } to convert this to a one-dimensional array:
int [] moves = {
0, 0, 0, arrLength, length % 2, arrLength,
0, length % 2, arrLength, 0, 0, length % 2,
arrLength, arrLength, length % 2, length % 2,
arrLength, length % 2, length % 2, 0
};
And you can translate 2D indexes (i, j) to 1D index k using the formula:
k = i * 2 + j;
Janos' answer is probably what you want. Alternatively you could create a class, e.g. Pair, and store it in a Pair[] array.

Sorting algorithm which does not allow counting of elements

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.

how to order Arrays value as circular format in java?

i have array values as like
String[] value = {"1","2","3", "4","5","6","7","8","9","10"};
suppose if i pass value "5" to tat array, it should be ordered as like
{"5","6","7","8","9","10",1","2","3","4"};...
how to do?plz anyone help?
thank u
What you need is called rotation. You can use Collections.rotate() method. Convert the array to a list and pass it to the method. This will rotate the array in place since the list is backed by the array:
String[] value = {"1","2","3", "4","5","6","7","8","9","10"};
Collections.rotate(Arrays.asList(value), 5);
The above code will rotate the array by a distance of 5. The resulting value array:
[6, 7, 8, 9, 10, 1, 2, 3, 4, 5]
Your question has two interpretations:
Rotate 5 steps, or
rotate the array so that 5 is the first element (regardless of where it is in the array).
Here is a solution for both alternatives:
import java.util.Arrays;
public class Test {
public static String[] rotateArray(String[] arr, int n) {
String[] rotated = new String[arr.length];
System.arraycopy(arr, n-1, rotated, 0, arr.length-n+1);
System.arraycopy(arr, 0, rotated, arr.length-n+1, n-1);
return rotated;
}
public static String[] rotateArrayTo(String[] arr, String head) {
for (int i = 0; i < arr.length; i++)
if (arr[i].equals(head))
return rotateArray(arr, i + 1);
throw new IllegalArgumentException("Could not find " + head);
}
public static void main(String[] args) {
String[] value = {"1","2","3","4","5","6","7","8","9","10"};
// Rotate so that it starts at 5:th element
value = rotateArray(value, 5);
System.out.println(Arrays.toString(value));
// Rotate so that it starts with element "7"
value = rotateArrayTo(value, "7");
System.out.println(Arrays.toString(value));
}
}
Output:
[5, 6, 7, 8, 9, 10, 1, 2, 3, 4]
[7, 8, 9, 10, 1, 2, 3, 4, 5, 6]
(ideone.com link)
first find the index of the entered value from the array..
and then in a loop move from the index to the final position.. and store these values in a new array.
after that, in the same result array, store the values from index 0 to the index of the entered value - 1.
You really don't need to store the values in a different array. Just find the index [say idx] of the value passed. And then start a loop from the start of the array and swap the values starting from idx.
For example -
idx = [some-value]
while [idx < arr.length]
temp = arr[i]
arr[i] = arr[idx]
arr[idx] = t
idx += 1
i += 1
Update:
I stand corrected by #aioobe. I simply worked out something for the 5th index - my bad. Here's something that works, if in case, you want to stay away from library functions -
private void slideLeft(String[] arr)
{
String t = arr[arr.length - 1];
String temp = null;
int next = -1;
for (int i = arr.length - 1; i >= 0; i--)
{
next = ( i == 0 ) ? arr.length - 1 : i - 1;
temp = arr[next];
arr[next] = t;
t = temp;
}
}
you'll need to call this method the number of times you need to shift the array members.
note: O(n^2) alert. not suitable for large shifts/arrays.

Categories