Replacing integers in an array with Integers from another array - java

I am struggling with this problem where I have to take (i/2)+1 numbers from one array and then insert them into that back of a second array.
e.g. 1st array = {2, 5, 3, 4, 8, 9}
2nd array = {-1, -1, -1, -1, -1, -1, -1}
what i want to achieve = {-1, -1, -1, 4, 3, 5, 2}
So I want to take the 1st number in the 1st array and insert it into the last position of the 2nd array replacing the -1 and so on and so forth
What I have so far is:
for(int i = 2nd Array.length; i <2nd Array.length; i--){
int value = 1st Array[i];
2nd Array[i]= 2nd Array[i].replace(i, value);
}
for the moment i'm just trying to get it to insert one set of values into the array.
I have not attempted taking only (1st Array.length/2)+1 numbers from the array.
Can anyone give me some advice on how to do this?

For clarity, use one index for each array, i1 index for array1 and i2 for array2.
Assuming both arrays are already initialised:
int i2 = array2.length-1;
for (int i1 = 0; i1 < (array1.length/2+1) && i2 >=0 ; i1++) {
array2[i2] = array1[i1];
i2--;
}
Or you can put everything in the for:
int[] array1 = {1,2,3,4,5,6,7,8,9};
int[] array2 = {-1,-1,-1,-1,-1,-1,-1,-1,-1};
for (int i1 = 0, i2 = array2.length-1;
i1 < (array1.length/2+1) && i2 >=0 ;
i1++, i2--) {
array2[i2] = array1[i1];
}
System.out.println(Arrays.toString(array2));
Output:
[-1, -1, -1, -1, 5, 4, 3, 2, 1]
EDIT
If you want the otherway, just change the direction for index i1, e.g.
for (int i1 = array1.length/2+1, i2 = array2.length-1;
i1 >= 0 && i2 >=0 ;
i1--, i2--) {
array2[i2] = array1[i1];
}
System.out.println(Arrays.toString(array2));
Output:
[-1, -1, -1, 1, 2, 3, 4, 5, 6]

I think there is an problem in your "for" loop.
for(int i = 2nd Array.length; i <2nd Array.length; i--)
It will exit the loop because "i" starts from 2nd Array.length and it will not be less than 2nd Array.length.

to start in the middle of the array, you should set the initial value for i as (length/2 + 1), since arrays indexes starts on 0, you can use array2.length/2
for(int i = array2.length/2; i < array2.length; i++)
array1[i] = array2[i];

Related

How to merge two elements in an array together?

For example you have the 2d array Board as shown below:
{0, 2, 4, 2}
{0, 0, 2, 2}
{2, 2, 0, 0}
{0, 5, 0, 2}
You want it to become:
{0, 2, 4, 2}
{0, 0, 4, 0}
{4, 0, 0, 0}
{0, 5, 0, 2}
When there are 2 elements next to each other you need to merge them to make 4 into the left-most place out of those two elements and then make the 2nd element to be 0.
You want to do this with java.
forgot to show my existing loop, this is it below:
for (int row = 0; row < Board.length; row++){
for (int col = 0; col <= Board.length; col++){
if ((Board[row][col] == Board[row][col +1])){
Board[row][col] = 2 * Board[row][col];
Board[row][col + 1] = 0;
}
}
}
Well, I guess that should work. In the loop, you must be careful not to refer to the wrong ( or non-existing) array element.
public static void main(String[] args) {
int[][] arr = new int[][]{{0, 2, 4, 2}, {0, 0, 2, 2}, {2, 2, 0, 0}, {0, 5, 0, 2}, {2, 2, 2, 2}, {2, 2, 2, 0}};
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length - 1; j++) {
if (arr[i][j] == arr[i][j + 1]) {
arr[i][j] = arr[i][j] + arr[i][j + 1];
arr[i][j + 1] = 0;
}
}
}
System.out.println(Arrays.deepToString(arr));
}
Here is one way, focusing only array values that equal 2.
iterate the 2D array.
then iterate over each linear array, checking adjacent values and making the changes.
for(int[] arr : v) {
for(int i = 0; i < arr.length-1; i++) {
if (arr[i] == 2 && arr[i+1] == 2) {
arr[i]+= arr[i+1];
arr[i+1] = 0;
}
}
}
for(int arr[]: v) {
System.out.println(Arrays.toString(arr));
}
prints
[0, 2, 4, 2]
[0, 0, 4, 0]
[4, 0, 0, 0]
[0, 5, 0, 2]
Well I assume that Board variable holds array (quick tip, common convention is to name variable in camelCase (first letter lowercase, then each letter of next work upper, if that variable is constant, then convention is SNAKE_UPPER_CASE)
Your first for is pretty okay, the second one too but it assumes that matrix will be always NxN and will fail if thats not the case or it will not work properly (depending if amount of cols is lower or greater than length of array)
Inside it you dont want to check if the values are equal, you want to check if these values are both equal to 2. And you should check if thats not processing of last column of the row, in that case youll get IndexOutOfBoundException because you want to get value of matrix that is not present.
So with small changes, you will achieve what you want. This code will hopefuly shows my thoughts better
public class MergingTwos {
public static void main(String args[]) {
// Init a matrix
int[][] array = new int[][] { { 0, 2, 4, 2 }, { 0, 0, 2, 2 }, { 2, 2, 0, 0 }, { 2, 2, 0, 0 }, { 0, 5, 0, 2 }};
// Iterating over each row of matrix, in veriable i, the current X index is stored
for(int i = 0; i < array.length; i++) {
// Iterating over each column of row, in variable n, the current Y index is stored
for(int n = 0; n < array[i].length; n++) {
// To prevent index out of bound exception, last element of row wont be processed so as we dont want to proceed if given and next value on row are not 2
if(n == array[i].length -1 || array[i][n] != 2 || array[i][n+1] != 2) {
continue;
}
// To value at given coordinates [i,n] you add values of value on coordinates [i, n+1]
array[i][n] = array[i][n] + array[i][n+1];
// And setting next element to 0
array[i][n+1] = 0;
}
}
// Printing the result
for (int[] x : array) {
for (int y : x) {
System.out.print(y + " ");
}
System.out.println();
}
}
}

Square Value at Index without using a temp array

At 0th index value is 4, so I have to check the value at index 4 and square it and place the value at 0th index without using a temp array:
Index 0 1 2 3 4
Values 4 3 1 2 0
================
Result 0 4 9 1 16
Now I am getting the first two values right, but the last three are not right. My code is as below:
static void Index(int arr[], int n) {
for(int i=0;i<n;i++) {
int index = arr[i];
int value = arr[index];
arr[i]=value*value;
}
}
Below is the output that I am getting:
Original Array
4 3 1 2 0
Array after Squaring
0 4 16 256 0
Can anyone help me out here as to what am I doing wrong?
Assuming the numbers are within range [0, 46341), we can store both the old and the new values in the array during the process (as 32 bits are enough). Then after the first loop we do another one to discard the old values and square the new ones.
// assume array[i] is within range [0, 46341) for any i
static void f(int[] array) {
for (int i = 0; i < array.length; i++) {
int j = array[i] & 0xffff; // get old value
array[i] = array[j] << 16 | j; // put new and old values
}
for (int i = 0; i < array.length; i++) {
int j = array[i] >>> 16; // get new value
array[i] = j * j; // put new value squared
}
}
NOTE: This approach is valid only if length of array is less than 10.
I have completed this code using only one loop without using any extra space.
Although, I have set a flag to run the complete loop twice.
If you do not have any constraint of using one loop, you can avoid using the flag and simply use two loops.
Approach:
Index 0 1 2 3 4
Values 4 3 1 2 0
Updated value 04 23 31 12 40
You must have got the idea what I did here.
I put the values at tens place whose square is to be displayed.
Now you have to just have to iterate once more and put the square of tens place at that index
Here's the code:
void sq(int arr[], int n){
bool flag = false;
for(int i=0; i<n; i++){
if(!flag){
if(arr[arr[i]] < 10){
arr[i] += (arr[arr[i]] * 10);
}
else{
arr[i] += ((arr[arr[i]]%10) * 10);
}
}
if(i==n-1 && !flag){
i=0;
flag = true;
}
if(flag)
arr[i] = (arr[i]/10) * (arr[i]/10);
}
}
It is in C++.
The problem is you are changing the values in your original array. In you current implementation this is how your array changes on each iteration:
{4, 3, 1, 2, 0}
{0, 3, 1, 2, 0}
{0, 4, 1, 2, 0}
{0, 4, 16, 2, 0}
{0, 4, 16, 256, 0}
The problem is you still need the values stored in the original array for each iteration. So the solution is to leave the original array untouched and put your values into a new array.
public static void index(int arr[]) {
int[] arr2 = new int[arr.length];
for(int i=0;i<arr.length;i++) {
int index = arr[i];
int value = arr[index];
arr2[i]=value*value;
}
}
Values of arr2 in revised process:
{0, 0, 0, 0, 0}
{0, 0, 0, 0, 0}
{0, 4, 0, 0, 0}
{0, 4, 9, 0, 0}
{0, 4, 9, 1, 0}
{0, 4, 9, 1, 16}

Simple Java array syntax which i'm confused over

public static void main(String[] args) {
int[][] b = {{0, 0, 0, 1},
{0, 0, 1, 1},
{0, 1, 1, 1}};
int[] u = new int[b.length];
for (int i = 0; i < u.length; i++) {
for (int j = 0; j < b[i].length; j++) {
u[i] = u[i] +b[i][j];
}
System.out.println(u[i]);
}
}
What is the differences between written b[i].length; and b.length;
When i run this code with b[i].length; the output is 1,2,3.
When running with b.length; gives the output 0,1,2
Your array got 2 dimensions, thus it is an array of an array. If you use b.length you will get the amount of arrays that are stored within b
Your array could look like this:
int[][] b = {{1}, {1,2}, {1,2,3}};
So b is an array that contains 3 other arrays. b.length (in this case) will always be 3. If you use b[n].length, you will get the length of the array with index n within b. In my example above: b[0].length will be 1, b[1].length will be 2, b[2].length will be 3.
b.length gives you the length of array b which is 3 because it has three element: b[0] which is an array {0, 0, 0, 1}, b[1] which is an array {0, 0, 1, 1} and finally b[2] which is an array {0, 1, 1, 1}.
b[i].lenght gives you the length of element b[i] which is 4. The reason that you can use length method in b[i] is because b[i] is also array (b is an array of arrays so every element of b is an array of int's).
b[i].length will return 4 for every i because every element b[i] is an array of length 4 .However, note that b[i] doesn't need to have same length
for example if you had:
int[][] b = {{0, 0, 0, 1},{1, 1}};
Then here b.length returns you 2, b[0].length returns 4 and b[1].length returns 2.
In your code your have a 2d array.
/*This is an array of arrays*/
int[][] b = {
{0, 0, 0, 1},
{0, 0, 1, 1},
{0, 1, 1, 1}
};
This is an array to arrays.
b.length will return the amount of arrays in the main array
b[i].length will return the amount of elements in one specific array on index i
b.length return number all rows but b[i].length; return number column for row i
b.length is the number of rows in your matrix
b[i].length is the number of elements i-th row
b refers to an array of arrays.
b.length returns how many elements b has - in other words, how many "nested" arrays you have.
b[i].length returns how many elements b[i] has - in other words, the length of the nested array referred to by b[i].

How to implement deleteValues (int values) method for a custom ArrayList?

I am implementing my custom ArrayList class for integers with the help of an array, and I would like to be able to delete a certain value from my array. My problem is when there are many same delete-able value next to each other, I am getting two 0s next to each other which leads to a bug. i tried to solve it for a couple of hours without luck. Here is my code:
int max=10;
public int[] a = new int[max];
#Override
public void deleteValues(int value) {
int tempIndex=0;
for (int i = 0; i <50 ; i++) {
if (a[tempIndex] == value) {
a[tempIndex] = a[tempIndex + 1];
a[tempIndex + 1] = 0;
} else if (a[tempIndex] == 0) {
a[tempIndex] = a[tempIndex + 1];
a[tempIndex + 1] = 0;
} else {
tempIndex++;
}
}
}
My array looks like that before deleting the value (4):
[4, 2, 3, 4, 4, 4, 4, 1, 2, 3]
This is the wrong result after running the code:
[2, 3, 0, 0, 4, 4, 4, 1, 2, 3]
What I would like to achieve:[2, 3, 1, 2, 3, 0, 0, 0, 0, 0]
My question is: What would be the best approach to make the code work, using as few loop as possible?
One of the problems in your code is that you're always copying the element at index tempIndex+1 into tempIndex: it's always the next element.
In fact, after deleting let's say 5 elements from the array, you'll have to copy tempIndex+5 into tempIndex.
I think this is a good way of doing it:
public void deleteValues(int[] a, int value) {
int j=0;
for(int i=0; i<a.length; i++) {
if(a[i]!=value) {
a[j] = a[i];
j++;
}
}
// fill the rest of the array with zeros
while(j<a.length) {
a[j] = 0;
j++;
}
}
Basically, you keep two indices: i and j.
The index i follows the "original" array, while index j follows the "new" array (after deletion).
Index i loops over all the elements: if a[i] is not equal to value, copy it into its new position j and increment both j and i. If a[i] is equal to value, skip it and increment i without incrementing j.
After all the elements have been copied or skipped, fill the end of the array with zeros.
Sample input:
a = {4, 2, 3, 4, 4, 4, 4, 1, 2, 3}
value = 4
Output:
a = {2, 3, 1, 2, 3, 0, 0, 0, 0, 0}
public static void deleteValues(int[] a, int value) {
int newSize = a.length;
int current = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] != value) {
if (i != current) {
a[current] = a[i];
newSize--;
}
current++;
}
}
//use first newSize values, for example you can copy to new array
System.out.println("New size = " + newSize);
}
you can use iterator:
List<Integer> numbers = ....
Iterator<Integer> i = numbers.iterator();
while (i.hasNext()) {
Integer num = i.next();
// add here your custom code
i.remove();
}
int tempIndex,index;
for (index = 0, tempIndex = 0; index < valuesArray.length; index++) {
if (valuesArray[index] != valToDelete) {
valuesArray[tempIndex++]=valuesArray[index];
}
}
while(tempIndex<valuesArray.length){
valuesArray[tempIndex++]=0;
}

Why is my Java program to merge 2 integer arrays only giving correct output to a certain point?

I have these 2 arrays:
array A [-5, -4, -3, -2, -1, 6, 7, 8, 9, 10, 11]
array B [-33, -22, -11, 44, 55, 66, 77, 88]
As you can see, array A and array B are both sorted. I have to merge them into a third array (array C) which should be sorted. (I can't use any array sort function though)
Here is my while loop:
int[] c = new int[a.length + b.length];
int aCount = 0;
int bCount = 0;
int cIndex = 0;
while (aCount < a.length && bCount < b.length) {
if (a[aCount] < b[bCount]) {
c[cIndex] = a[aCount];
cIndex++;
aCount++;
}
else {
c[cIndex] = b[bCount];
cIndex++;
bCount++;
}
}
And this is my output:
[-33, -22, -11, -5, -4, -3, -2, -1, 6, 7, 8, 9, 10, 11, 0, 0, 0, 0, 0]
It is working correctly until it reaches 11, but then after that it only displays 0's when it should be 44,55,66,77,88.
What am I missing?
You only merge the two arrays to the point, where you reach the end of array a. Afterwards the while loop breaks off. You'll have to insert the remaining values of the other array.
int[] tmp = (aCount == a.length ? b : a);
int ct = (aCount == a.length ? bCount : aCount);
for(; ct < tmp.length ; ct++)
c[cIndex++] = temp[ct];
After you pick each element from a and b you increment the respective index. When you get to the last element of a (namely a[10]) you increment the index again, and now aCount is no longer less than a.length. So you skip the entire rest of the process.
The zeros are the default value of c before values are set. Since you're not setting the values, they remain 0.
Your loop condition (aCount < a.length && bCount < b.length) becomes false as soon as one of the indices reaches the end of the array. Since you only increment one of the indices in the loop, that means there is at least 1 element in the other array that needs to be inserted to c.
You can add the following code to add the missing elements too:
// add elements missing from first array
while (aCount < a.length) {
c[cIndex] = a[aCount];
cIndex++;
aCount++;
}
// add elements missing from second array
while (bCount < b.length) {
c[cIndex] = b[bCount];
cIndex++;
bCount++;
}

Categories