I would like to remove a particular number from the array
Integer[] arr = new Integer[7];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
Collections.shuffle(Arrays.asList(arr));
This is creating numbers from 0-7
But I dont need 0,I need value from 1-7
The first value written into your array is 0 because you initialize i with 0 in the for loop.
Therefore your loop will only insert the values 0 - 6.
Change this initialisation to i = 1 and in addition you also need to change the condition of the for loop to arr.length + 1 or i <= arr.length, so it will count up to 7.
Integer[] arr = new Integer[7];
for (int i = 1; i < arr.length + 1; i++) {
arr[i] = i;
}
What you also can do instead of changing the loop itself, is to change the loop body. Just add 1 to i when assigning it to arr[i]:
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
In this case i will count from 0 to 6, and assign 1 to 7 to your array
Change your int i = 0 to int i = 1 like this:
Integer[] arr = new Integer[7];
for(int i = 1; i <8; i++){
int value = i-1;
arr[value] = i;
}
Collections.shuffle(Arrays.asList(arr));
for(int i = 0; i < arr.length; i++){
System.out.println("Result:"+arr[i]);
}
Console message:
Result:7
Result:2
Result:6
Result:5
Result:4
Result:1
Result:3
Related
I'm trying to invert and flip a two-dimensional array, but something goes wrong! Flipping works ok, but inverting is not.
Can't find a mistake right here:
public int[][] flipAndInvert(int[][] A) {
int row = -1;
int col = -1;
int[][] arr = A;
for (int i = 0; i < arr.length; i++) {
row++;
col = -1;
for (int j = arr[i].length - 1; j >= 0; j--) {
col++;
arr[row][col] = A[i][j];
}
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] == 1) {
arr[i][j] = 0;
} else {
arr[i][j] = 1;
}
}
}
return arr;
}
int[][] A = { { 0, 1, 1 },{ 0, 0, 1 },{ 0, 0, 0 } };
After proceeding the output should be:
After inverting:
{1,1,0},{1,0,0},{0,0,0}
After flipping:
{0,0,1,},{0,1,1},{1,1,1}
Thanks to all a lot, the problem was here:
int[][] arr = A;
The reference of the array is being passed to arr.
What I think is that since you are using this line:
int[][] arr = A;
The reference of the array is being passed to arr, and hence the line:
arr[row][col] = A[i][j];
is equivalent to:
A[row][col] = A[i][j];
as arr has an reference to A and they both now refer to the same memory location (or they are both different names to a single variable)
You can fix this by either using the new keyword with arr and then initializing it:
int[][] arr = new int[someRows][someCols];
//use for loop to assign the value to each element of arr
Or you can run the for loop till arr[i].length/2 - 1:
for (int i = 0; i < arr.length; i++) {
row++;
col = -1;
for (int j = arr[i].length / 2 - 1; j >= 0; j--) { //here changed arr[i].length to arr[i].length / 2
col++;
arr[row][col] = A[i][j]; //for this you do not need arr and you can directly work on A and return it
}
}
The problem of your code should be this line:
int[][] arr = A;
You are assigning the reference of array A to arr and from then when you modify one you modify both of the arrays or better they are modified together because they refer to the same address.
Using apache commons lang:
int[][] matrix = new int[3][3];
for (int i = 0; i < matrix.length; i++) {
matrix[i][0] = 3 * i;
matrix[i][1] = 3 * i + 1;
matrix[i][2] = 3 * i + 2;
}
System.out.println(Arrays.toString(matrix[0]));
System.out.println(Arrays.toString(matrix[1]));
System.out.println(Arrays.toString(matrix[2]));
ArrayUtils.reverse(matrix);
System.out.println(Arrays.toString(matrix[0]));
System.out.println(Arrays.toString(matrix[1]));
System.out.println(Arrays.toString(matrix[2]));
Hope this helps.
I have seen other solutions like this and wondering if there is anything wrong with my approach of using for loop. I don't want to use while loop as others have used in their solution.
package com.my.practice;
public class MedianOfTwoArrays {
public static void main(String[] args) {
// Given two sorted arrays of same size
int[] a1 = {1,2,3,4,5,6};
int[] a2 = {7,8,9,10,11,12};
int[] mergedArray = new int[a1.length + a2.length];
for(int i=0 ; i < a1.length; i++){
mergedArray[i] = a1[i];
}
//System.out.println("Length:"+2*(a1.length));
for(int i= a1.length; i < 2 * (a1.length); i++) {
mergedArray[i] = a2[i];
}
for(int i=0 ; i < 2*(a1.length); i++){
System.out.println("Part of Array: "+mergedArray[i]+ " Length is: "+mergedArray.length);
}
}
}
I am getting following error :
Length:12
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at com.my.practice.MedianOfTwoArrays.main(MedianOfTwoArrays.java:30)
In this line:
for (int i= a1.length; i < 2 * (a1.length); i++) {
mergedArray[i] = a2[i];
}
you are trying to access a2[i] for i from 6 to 11. Since a2 is an array of size 6, a2[6], a2[7] ... a2[11] do not exist.
In your case, you want to insert values a2[1] into mergedArray[6], a2[2] into mergedArray[7] etc.
You either need to substract a1.length on the right side:
for (int i = a1.length; i < 2 * (a1.length); i++) {
mergedArray[i] = a2[i - a1.length];
}
or add a1.length on the left side:
for (int i = 0; i < a1.length; i++) {
mergedArray[i + a1.length] = a2[i];
}
Choose the more convenient one.
Mistake (for ArrayOutOfBoundException):
for(int i= a1.length; i < 2 * (a1.length); i++) {
mergedArray[i] = a2[i]; //Using 'i' incorrectly to access a2[i]
}
Correcting above:
for(int i= 0; i < a2.length; i++) {
mergedArray[i+a1.length] = a2[i]; //Using 'i' incorrectly to access a2[i]
}
Reasons:
'i' here will ensure that a2 is not exceeded beyond its size because i's max limit is a2.length.
Do not assume that a2 and a1's size would be equal. While traversing a1 using a1.length and while traversing a2, use a2.length.
A safety (redundant) check can be added to ensure that (i+a1.length) does not exceed mergedArray size. Redundant in this case because the mergedArray's length = a1.size + a2.size.
Problem is your are using same index for arrays of different length:
for(int i= a1.length; i < 2 * (a1.length); i++)
mergedArray[i] = a2[i];
Here at initial, i = 6, array bounds for a2 is 0-5 however a2[i] is a2[6], out of bounds, which gives you the exception.
You can skip those loops, by using System.arraycopy()
System.arraycopy(a1, 0, mergedArray,0, a1.length);
System.arraycopy(a2, 0, mergedArray,a1.length, a2.length);
If you still wana use loop, simply use another index variable:
for(int i = 0, j = a1.length; i < (a2.length); i++, j++)
mergedArray[j] = a2[i];
The issue in your code is due to using i as an index for a2 in second loop. Its valid for mergedArray but not for a2
Either use i-a1.length as index in your second loop
for(int i= a1.length; i < 2 * (a1.length); i++) {
mergedArray[i] = a2[i-a1.length];
}
Or use three indices: i, j & k. Just to give you an idea
int i, j, k = 0;
for (i = 0; i<a1.length; i++){
mergedArray[k] = a1[i];
k++;
}
for (j=0; j<a2.length; j++){
mergedArray[k] = a2[j];
k++;
}
It's not a good idea to rely on the two arrays having the same length, so I wouldn't use a1.length * 2. In addition, you can't use the same index for the original arrays and the merged array, since the merged array is longer.
A suggested fix:
int[] mergedArray = new int[a1.length + a2.length];
for(int i=0 ; i < a1.length; i++){
mergedArray[i] = a1[i];
}
for(int i= 0 ; i < a2.length; i++){
mergedArray[a1.length + i] = a2[i];
}
for(int i=0 ; i < mergedArray.length; i++){
System.out.println("Part of Array: "+mergedArray[i]+ " Length is: "+mergedArray.length);
}
I had to write a method in Java, where having in input an array a of numbers and a number x returns an array of elements which follows the last occurrence of x in a.
For example with input {0,1,2,3,4,5,6,7,8,9} and x=6 the method must return {7,8,9} meanwhile with {4,1,4,2} and x=4 the method must return {2} and if the x is not in a then it must return empty array {} (or array with 0 length)
so I got this answer:
int idx = -1;
for (int i = 0; i < s.length; i++) {
if (s[i] == x)
idx = i;
}
/* After you found this index, create a new array starting
* from this element. It can be done with a second (not nested) for loop, or you can
* use Arrays.copyOfRange()
*/
//make sure idx != -1
int[] t = new int[s.length - idx - 1];
for (int i = idx + 1; i < s.length; i++)
t[i - idx - 1] = s[i];
which was very helpful but I could not understand why this works:(EDITED; Ok now I understand why this works but even if in my opinion the combined for loop ideea was more less complicated to read)
t[i - idx - 1] = s[i];
and this doesn't:
int[] t = new int[a.length - indx - 1];
for (int j = indx + 1; j < a.length; j++) {
for (int i = 0; i < t.length; i++) {
t[i]=a[j];
}
}
return t;
EDITED :
To clarify this is all the code
int[] dopoX(int[] a, int x) {
int n = a.length;
int[] c = new int[0];
int indx = 0;
int nrx = 0;
for (int j = 0; j < a.length; j++) {
if (a[j] == x)
nrx++;
if (a[j] == x)
indx=j;
}
if (nrx == 0)
return c;
int[] t = new int[n - indx - 1];
for (int j = indx + 1; j < n; j++) {
for (int i = 0; i < t.length; i++) {
t[i] = a[j]; /* it returns just 1 number of a[] like t{2,2,2,2,2,2,2,2} which is
not correct */
}
}
return t;
}
Well you want to copy all the remaining values, and create an array of index t. Thus you need to start with i=0. You can however perform a shift-operation: increase i somewhere, and when you use it, shift it back, so:
for (int i = idx+1; i < s.length; i++)
t[i-idx-1] = s[i];
is equvalent to:
for (int i = 0; i < t.length; i++)
t[i] = s[i+idx+1];
(which would have been more readable as well)
About your second question:
here you use a nested loop: the second for loop will be repeated each iteration of the first one.
The result is thus that in the second for-loop, j is always fixed, with input {1,2,...,9} and 6 in the first iteration, you would fill your array with 7s, next 8s and finally 9s.
You can however use a combined for loop:
int []t=new int[n-indx-1];
// /-- grouped initializers /-- grouped increments
// | |
for(int i=0, j= indx+1; i < t.length; i++, j++){
t[i]=a[j];
}
return t;
Let's suppose you take the case where a[] = {1,2,3,4,5,6,7,8,9} and x = 6.
Running this:
int idx = -1;
for (int i = 0; i < s.length; i++) {
if (s[i] == x) idx = i;
}
You got idx = 5 as s[5] == x.
Now we want to copy the array after the last instance of x into a new array t[].
Obviously, you have to start from the index idx + 1 as idx contained the last occurance of x.
Hence, this code:
int[] t = new int[s.length - idx - 1];
for (int i = idx+1; i < s.length; i++)
t[i-idx-1] = s[i];
What do you do here?
You construct a new array t[] having length s.length - idx - 1, in our case s.length = 9 and idx = 5 hence, we have the s.length - idx - 1 as 3 and we can check that is the number of elements after x = 6.
Now, we start the iterator i from idx + 1 (Reason explained above) to s.length
We have t[i - idx - 1] because when i = idx + 1, i - idx - 1 = 0. Hence as i increases, your i - idx - 1 also increases.
Hope it was convincing. Please comment if you still have any doubts.
The first line of code finds the last index of x inside of the array.
The second line uses the built-in function of Arrays to copy a range from an array to a new copy.
And we copy from the values after the last x until lenght of array a.
The first line could be rewritten to search from the end and backwards in the array with a break. This will give a performance boost but makes the code less easy to read.
for(int i=0; i<a.length;i++) if(a[i]==x) idx=i;
int[] b = Arrays.copyRangeTo(a, idx+1, a.length);
Try this:
int j=0;
int i=idx+1;
while (j<t.length) {
t[j] = s[i];
j++;
i++;
}
Didn't know how to call my Thread.
public NaturalNumberTuple(int[] numbers) {
int [] thisTuple = new int[numbers.length];
int count = 0;
for(int j = 0; j < numbers.length; j++){
if(numbers[j] > 0){
thisTuple[j] = numbers[j];
count++;
}
}
int[] newTuple = new int[count];
for(int i = 0; i < newTuple.length; i++){
int k = i;
while(thisTuple[k] <= 0){
k++;
}
newTuple[i] = thisTuple[k];
}
this.tuple = newTuple;
}
This is my code snippet to create a new NaturalNumberTuple.
So this is the Array I want to use: int[] tT2 = {1,2,4,-4,5,4,4};
I only want to use natural numbers greater than 0 and my problem isn't to cut out the negative number but it is that my console is giving me this: Tuple(Numbers:1,2,4,5,5,4).
The problem is if I jump over that value which is negative with my while loop to get the higher (k) I will have to pass the same (k) in my for loop which I don't want to because I already got it in my Array. I hope you understand my problem.
Sorry for the bad english..
Edit: Can't use any methods from java itself like System.arrayCopy
You have an error in the first loop. Fixing it makes the second loop much simpler :
public NaturalNumberTuple(int[] numbers) {
int [] thisTuple = new int[numbers.length];
int count = 0;
for(int j = 0; j < numbers.length; j++){
if(numbers[j] > 0){
thisTuple[count] = numbers[j]; // changed thisTuple[j] to thisTuple[count]
count++;
}
}
int[] newTuple = new int[count];
for(int i = 0; i < newTuple.length; i++) {
newTuple[i] = thisTuple[i];
}
this.tuple = newTuple;
}
Of course, the second loop can be replaced with a call to System.arrayCopy.
I would change your while loop to an if that simply restarts the for loop. Say from this:
while(thisTuple[k] <= 0){
k++;
}
To something like this:
if (thisTuple[k] <= 0)
continue;
This stops you from adding the same number twice when you encounter a negative or zero number.
This code will solve you issue. The code is checked in the following link Tuple Exampple
int [] thisTuple = new int[numbers.length];
int count = 0;
for(int j = 0; j < numbers.length; j++){
if(numbers[j] > 0){
thisTuple[count] = numbers[j]; //Change to thisTuple[count]
count++;
}
}
int[] newTuple = new int[count];
for(int i = 0; i < count; i++){
newTuple[i] = thisTuple[i];
}
I have an array called blockHeights, which contains 3 values inside of it, namely 1,2,3. So blockHeights[0] is equal to 1.
I also have a loop:
for (int i = 1; i <= blockHeights.length; i++)
In the first time around the loop, I want to create a variable called totalBlockHeights where it is
int totalBlockHeights = blockHeights[0] + blockHeights [1] + blockHeights [2];
However, in the next loop I want that variable to change, so that it only adds blockHeights[1] and blockHeights[2] together, ignoring blockHeights[0].
How would I go about doing this?
Try the following (I'm assuming the third iteration should only include blockHeights[2], following the pattern):
for (int i = 1; i <= blockHeights.length; i++) {
int totalBlockHeights;
for (int j = i - 1; j < blockHeights.length; j++) { // all block heights from here onwards
totalBlockHeights += blockHeights[j];
}
// do whatever
}
Well, if you want the sum of your array, and the sum of the array without first value
int totalBlockHeights = 0;
for(int i = 0; i < blockHeights.length; i++){
totalBlockHeights += blockHeights[i];
}
System.out.println(totalBlockHeights);
System.out.println("totalBlockHeights without first value = " + (totalBlockHeights - blockHeights[0]));
this way you only loop once
Try following code:
public class Loop {
public static void main(String[] argv) {
int[] blockHeights = new int[] {1, 2, 3};
int totalBlockHeights = 0;
for(int i = 0; i < blockHeights.length; i++) {
totalBlockHeights = 0;
for(int j = i; j < blockHeights.length; j++) {
totalBlockHeights += blockHeights[j];
}
System.out.println(totalBlockHeights);
}
}
}
int[] blockHeights = new int[] { 1, 2, 3 };
int totalBlockHeights = 0;
int customBlockHeights = 0;
for (int i = 0; i < blockHeights.length; i++) {
totalBlockHeights += blockHeights[i];
if (i == 0) {
continue;
}
customBlockHeights += blockHeights[i];
}
System.out.println(totalBlockHeights);
System.out.println(customBlockHeights);
This will print:
6
5
You dont need two for to achieve that.
you can perform this on two for loop outer loop for (int i = 1; i <= blockHeights.length; i++), and in inner loop (take a variable j) you can do like int totalBlockHeights = totalBlockHeights + blockHeights[j], and for i<j, you can just continue the for loop.
as answered by btrs20