How to get a number from an array? - java

question:
Suppose this is the number in my array {1,2,3,4,5,6,7,8}
and each number is a position like ::
1=1 ,2=2 , 3=3, 4=4, 5=5, 6=6, 7=7, 8=8
It is not an array position just the number position. Now i want to remove the number in odd position then it becomes
2,4,6,8 :: 2=1, 4=2, 6=3, 8=4,
Now again i want to remove from the odd position so it becomes 4,8 :: 4=1, 8=2
Now the answer is 8 so how to get this 8
Code:
int [] arr = new int [] {1, 2, 3, 4, 5, 6, 7, 8}; //I am taking certain number in array
System.out.println("Elements of given array present on even position:");
for (int i = 1; i < arr.length; i = i+2) {
System.out.println(arr[i]);
}
must get the value as 8 but in output i get:
2
2
2
2
4
4
4
4
and so on

This will print out even numbers:
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0)
{
System.out.println(arr[i]);
}
}
If you want to remove the odd position elements from the array, then make a new one and use the above code to exclude odd elements like so:
ArrayList<Integer> newArr = new ArrayList<>();
for (int i = 0; i < arr.length; i++)
{
if (i % 2 == 0)
{
newArr.add(arr[i]);
}
}

As I said in my comment, you want the greatest power of 2 :
int max=0;
for (int i=0;i<arr.length;i++) {
int pos = arr[i];
if((pos & (pos-1)) == 0) { // check if pos is a power of 2
max =java.lang.Math.max(max, pos);
}
}
System.out.println(max)
if arr = {1,2,3,4,5,6,7,8}; => output 8
if arr = {1,2,3,4,5,6,7,8,9} => output 8
if arr = {1,2,3,...,20} => output 16

You could use an ArrayList
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0; i<arr.length; i++){
if(i % 2 == 0){ //if divide by 2 gives remainder 0 it is even
list.add(arr[i]);
}
}
arr=list.toArray();//get the array version of the list
Then you could put it in a while loop to do it until there is only one left.
int [] arr = new int [] {1, 2, 3, 4, 5, 6, 7, 8};
while(arr.length>1){
...
}
System.out.println(arr[0]);
Remember that we start counting at 0 so the first position(i=0) would even and the second position(i=1) would be uneven.
Final Code:
int [] arr = new int [] {1, 2, 3, 4, 5, 6, 7, 8};
while(arr.length>1){
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0; i<arr.length; i++){
if(i % 2 == 0){ //if divide by 2 gives remainder 0 it is even
list.add(arr[i]);
}
}
arr=list.toArray();//get the array version of the list
}
System.out.println(arr[0]);

This should do it for you
int [] arr = new int [] {1, 2, 3, 4, 5, 6, 7, 10, 11, 12}; //I am taking certain
System.out.println("Elements of given array present on even position:");
int counter=2;
while(counter<=arr.length){
counter*=2;
}
System.out.println(arr[(counter/2)-1]);
Let me know if this works

Related

Is there a way to reverse specific arrays in a multidimensional array in java?

I know how to generally manipulate and create a multidimensional array but I don't know all the utils and features that arrays have. I want to know is if I have a 2D array the size of [5][4], can I print it where the first line is in order, second is in reverse, and the third is in order... and so on.
For example:
[1 2 3 4] //in order
[8 7 6 5] //reverse
[9 10 11 12] //in order
[16 15 14 13] //reverse
[17 18 19 20] //in order
as my teacher stated "Define a two-dimensional array of size m × n. Write a method to initialize this array with numbers from 1 to m × n in the way as below: the first row, initialize the elements from left to right; the second row, initialize from right to left; then switch order. For example, if m=5; and n = 4; the array should be initialized to:"
I’m not sure if it should be done using a temp method or some other loop method.
You cannot reverse it directly. But you can have a loop and reverse the alternative rows:
void reverseArray() {
Integer[][] arr = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16},
{17, 18, 19, 20}};
for (int i = 1; i < arr.length; i += 2) {
Collections.reverse(Arrays.asList(arr[i]));
}
}
if I have a 2D array the size of [5][4], can I print it where the
first line is in order, second is in reverse, and the third is in
order... and so on.
It's unclear how you want to use the output, but here is a literal way to do it:
public static void main(String[] args) {
int[][] values = new int[][]{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
for (int r = 0; r < values.length; r++) {
if (r % 2 == 0) {
// forwards
for (int c = 0; c < (values[r].length - 1); c++) {
System.out.print(values[r][c] + " ");
}
System.out.println(values[r][values[r].length - 1]);
} else {
// backwards
for (int c = (values[r].length - 1); c > 0; c--) {
System.out.print(values[r][c] + " ");
}
System.out.println(values[r][0]);
}
}
}
Output:
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13
int[][] arr = new int[][]{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
AtomicInteger counter = new AtomicInteger(0);
Arrays.stream(arr).forEach(ints -> {
System.out.println(Arrays.stream(ints)
.mapToObj(String::valueOf)
.reduce((a, b) ->
counter.get() % 2 == 0 ? a + " " + b : b + " " + a).get());
counter.incrementAndGet();
});
This code uses the Stream API to iterate over an array. The first stream iterates over single-level arrays, the second - their elements, and then forms a string. Also, according to the counter value, items are combined from left to right or from right to left.
You can create such an array with a "snake order" without sorting at all, using a stream in a stream or a loop in a loop:
int m = 5;
int n = 4;
int[][] arr = IntStream
// create rows of array
.range(0, m).mapToObj(row -> IntStream
// for each row create cells where
// values are numbers from 1 to [m * n]
.range(0, n).map(cell -> {
int val = row * n;
if (row % 2 == 0)
// even rows:
// straight order
val += cell + 1;
else
// odd rows:
// reverse order
val += n - cell;
return val;
})
// return int[] array
.toArray())
// return int[][] 2d array
.toArray(int[][]::new);
int m = 5;
int n = 4;
int[][] arr = new int[m][n];
// create rows of array
for (int row = 0; row < m; row++) {
// for each row create cells where
// values are numbers from 1 to [m * n]
for (int cell = 0; cell < n; cell++) {
int val = row * n;
if (row % 2 == 0)
// even rows:
// straight order
val += cell + 1;
else
// odd rows:
// reverse order
val += n - cell;
arr[row][cell] = val;
}
}
Arrays.stream(arr).map(Arrays::toString).forEach(System.out::println);
// [1, 2, 3, 4]
// [8, 7, 6, 5]
// [9, 10, 11, 12]
// [16, 15, 14, 13]
// [17, 18, 19, 20]
See also:
• How do I rotate a matrix 90 degrees counterclockwise in java?
• Is there any other way to remove all whitespaces in a string?
Not as efficient as nested loops, one can simply iterator from 1 to 20 and determine row i and column j.
final int M = 5;
final int N = 4;
int[][] matrix = new int[M][N];
IntStream.range(0, M*N)
.forEach(no -> { // no = 0, 1, 2, ... , M*N-1
int i = no / N; // Row.
int j = no % N; // Increasing column (for even row).
if (i % 2 == 1) { // Odd row.
j = N - 1 - j; // Decreasing column.
}
matrix[i][j] = no + 1;
});
i % 2 is the modulo 2, rest by division of 2, hence 0 for even, 1 for odd.
Or use a bit more language features:
IntStream.range(0, N)
.forEach(i -> {
int no = N * i;
IntUnaryOperator jToValue = i % 2 == 0
? j -> no + 1 + j
: j -> no + N - 1 -j;
Arrays.setAll(matrix[i], jToValue);
});
Here Arrays.setAll(int[], (int index) -> int) fills the array based on the index.
About the question of there being some nice function:
You probably saw List.reverse; there does not exist an Arrays.reverse, hence Arrays.setAll seems to be best. In this case where the values are increasing one theoretically could also sort all odd rows reversed. But only with a trick, and sorting costs.
It is interesting that there are so many solutions. Instead of waggling the dog's tail one can take the tail and waggle the dog.

How do I compare each corresponding index from three array of different random lengths from 1-5 without getting a possible out of bound exception

I have 3 arrays of random length. I want to create a new array that stores the largest value from comparing those 3 arrays at each index.
int size1=x.length;
int size2=y.length;
int size3=z.length;
int size=0;
if (size1>=size2 && size1>=size3)
size=size1;
else if (size2>=size1 &&size2>=size3) {
size=size2;
}
else if (size3>=size1 && size3>=size2) {
size=size3;
}
int[] largest= new int[size];
int[] x= {1, 4, 6}; // random array length from 1-5 and hypothetically each array hold these values
int[] y= {2, 4};
int[] z= {5, 6, 7, 8, 9};
// ideally after some sort of an algorithm largest[] should hold {5, 6, 7, 8, 9}
I initially thought of a for loop, but my loop will eventually throw me a out of bound exception, because of the random size length nature of the arrays and x/y/z won't hold a value at index [i]. Any other ways?
for (int i=0;i<size;i++) {
if (x[i]>y[i]) && t1[i]>t3[i]) {
largest[i]=x[i];
}
else if (y[i]>x[i]) && y[i]>z[i]) {
largest[i]=y[i];
}
else if (z[i]>x[i]) && z[i]>y[i]) {
largest[i]=z[i];
}
}
There are several ways of doing this. Here's one that avoids a ton of conditional statements at the cost of more memory.
int size = Math.max(x.length, Math.max(y.length, z.length));
int[] nooX = new int[size];
int[] nooY = new int[size];
int[] nooZ = new int[size];
// Copy over the values from x to the new array
for(int i = 0; i < x.length; i++){
nooX[i] = x[i];
}
// ... Copy paste the above and do the same for arrays nooY and nooZ
int[] largest = new int[size];
// ... Copy paste your code, using nooX, nooY, and nooZ instead of x, y, and z
A simpler approach without creating extra arrays to equalize size:
public static int[] getMaxValues(int[] x, int[] y, int[] z) {
int size = Math.max(x.length, Math.max(y.length, z.length));
int[] max = new int[size];
for (int i = 0; i < size; i++) {
int xi = i < x.length ? x[i] : Integer.MIN_VALUE;
int yi = i < y.length ? y[i] : Integer.MIN_VALUE;
int zi = i < z.length ? z[i] : Integer.MIN_VALUE;
max[i] = Math.max(xi, Math.max(yi, zi));
}
return max;
}
Test:
int[] x= {4, 4, 6}; // random array length from 1-5 and hypothetically each array hold these values
int[] y= {2, 10};
int[] z= {3, 6, 7, 8, 9};
System.out.println(Arrays.toString(getMaxValues(x, y, z)));
Output:
[4, 10, 7, 8, 9]
Update
Defining a couple of functions allows to create the following implementation using Stream API that would be able to handle non-hardcoded number of arrays:
private static int getAtIndex(int[] arr, int i) {
return i < arr.length ? arr[i] : Integer.MIN_VALUE;
}
private static int getMax(IntStream values) {
return values.max().getAsInt();
}
// use Supplier to be able to use stream of the arrays twice
public static int[] getMaxValues(Supplier<Stream<int[]>> arrs) {
return IntStream.range(0, getMax(arrs.get().mapToInt(arr -> arr.length)))
.map(i -> getMax(arrs.get().mapToInt(arr -> getAtIndex(arr, i))))
.toArray();
}
Test:
int[] maxValues = getMaxValues(() -> Stream.of(x, y, z)); // supply stream of arrays
System.out.println(Arrays.toString(maxValues));
I think we should think this way
array1 = 1, 2, 3, 4, 6, 7
array2 = 3, 4, 5, 6, 23, 4
array3 = 5, 5, 32, 3, 2, 43, 56
Like a matrix
1 2 3 4 6 7
3 4 5 6 23 4
5 5 32 3 2 43 56
We need is the greatest value in every column.
largestArr = 5, 5, 32, 6, 23, 43, 56 <-- Like this
I hope this code is the answer to your problem.
public static int[] largestColumnsArr(int arr1[], int arr2[], int arr3[]) {
int[][] arr = {arr1, arr2, arr3};
//The size of the largest sized array
int size = Math.max(arr3.length, Math.max(arr2.length, arr1.length));
int[] largestArr = new int[size];
/*
Takes the largest value in each column and assigns it to the array
If it is try catch, if the size of the arrays is exceeded, the program exit is blocked.
*/
for (int i = 0; i < size; i++) {
int largestColumnValue = 0;
try {
for (int j = 0; j < arr.length; j++) {
if (largestColumnValue < arr[j][i]) {
largestColumnValue = arr[j][i];
}
}
} catch (Exception e) {
}
largestArr[i] = largestColumnValue;
}
return largestArr;
}

Comparing two arrays and then making another array with common elements (and no duplicates)

Hi, I'm a newbie to Java and I was doing this lab assignment where we compare elements of two arrays to get the common elements. I am stuck on how to get rid of duplicates.
My current code is giving me the output [3, 0, 5, 6, 5, 0, 9, 0] and the desired output of common is [3, 5, 6, 9, 0, 0, 0, 0].
Also, since I am not that experienced, please do not post professional ways to do the problem or "experienced" answers to my question, as that would not help me at all :D.
Thanks!
public static void main (String[] args) {
int[] a1 = {3, 8, 5, 6, 5, 8, 9, 2};
int[] a2 = {5, 15, 4, 6, 7, 3, 9, 11, 9, 3, 12, 13, 14, 9, 5, 3, 13};
int[] common = new int[a1.length];
System.out.println("Exercise 3: ");
findCommon(a1,a2,common);
}
public static void findCommon(int[] a1, int[]a2, int[] common) {
int num = 0;
for (int i = 0; i < common.length; i++)
{
for (int j = 0; j < a2.length; j++)
{
if (a1[i] == a2[j]) // loops through every index of j, while keeping i at one index
num = a1[i];
for (int k = 0; k < common.length; k++) // makes sure there are no duplicates in common
{
if (num != common[k])
common[i] = num;
}
}
}
for (int elements : common)
System.out.print(elements + " ");
}
You should look into using Sets to do this kind of thing, but since this is an exercise I've provided a solution with some comments along the way in the code.
Basically you should break the problem down into pieces, each of which is its own method. That way you will have an easier time getting it straight.
arrayIntersect(int[], int[])
This method's job is to create an array from two arrays. The resulting array must have unique elements that are present in both arrays.
You can do n. 1 with a helper method (mentioned below).
inArray(int, int[])
This method returns true if an array contains the given element, false otherwise.
Example
public static void main (String[] args) {
int[] a1 = {3, 8, 5, 6, 5, 8, 9, 2};
int[] a2 = {5, 15, 4, 6, 7, 3, 9, 11, 9, 3, 12, 13, 14, 9, 5, 3, 13};
int[] a3 = arrayIntersect(a1, a2);
for (int a : a3) {
System.out.println(a);
}
}
private static int[] arrayIntersect(int[] a1, int[] a2) {
int[] intersect = new int[Math.min(a1.length, a2.length)];
int curIndex = 0;
for (int x : a1) {
if (inArray(x, a2) && !inArray(x, intersect)) {
intersect[curIndex] = x;
curIndex++;
}
}
// resize intersect array to not include unused indexes
int[] tmp = intersect;
intersect = new int[curIndex];
for (int i = 0; i < intersect.length; i++) {
intersect[i] = tmp[i];
}
return intersect;
}
private static boolean inArray(int element, int[] array) {
boolean result = false;
for (int a : array) {
if (element == a) {
result = true;
break;
}
}
return result;
}
You are very close to the correct anwser, but the for loop for (int k = 0; k < common.length; k++) is being executed for every element of a2. So, when an value exist for a1 but doesn't exist for a2, you are putting the old value of num at the common array. If you look at the elements printed, you will see that every time that an element just exist in a1, the element repeat.
The result of the code is
3 3 5 6 5 5 9 9
You put the right identation, but forgot the curly brackets. If you put the curly brackets at the if (a1[i] == a2[j]), this will be the result:
3 0 5 6 5 0 9 0
But why these 0 are there? Because when you create an int array in java, all elements start with the value of 0. And you are putting the common elements at the same position of the presence of this elements in the a1 array. You can correct this by populating the int array with an invalid number and them ignorin it. At this code, I assumed that -1 is an invalid value.
public static void findCommon(int[] a1, int[] a2, int[] common) {
int num = 0;
for (int i = 0; i < common.length; i++) {
common[i] = -1;
}
for (int i = 0; i < common.length; i++) {
for (int j = 0; j < a2.length; j++) {
if (a1[i] == a2[j]) { // loops through every index of j, while keeping i at one index
num = a1[i];
for (int k = 0; k < common.length; k++) // makes sure there are
// no duplicates in common
{
if (num != common[k])
common[i] = num;
}
}
}
}
for (int elements : common) {
if (elements != -1)
System.out.print(elements + " ");
}
}
If you see, At the if (elements != -1) I didn't put the curly brackets but it worked. If you don't put the curly brackets, it will just execute the next command.

Array Processing (stretching) Method

I'm looking for a hint on how to solve this or where I am going wrong.
The question is as follows: Write a static method named stretch that accepts an array of integers as a parameter and returns a new array twice as large as the original, replacing every integer from the original array with a pair of integers, each half the original. If a number in the original array is odd, then the first number in the new pair should be one higher than the second so that the sum equals the original number. For example, if a variable named list refers to an array storing the values {18, 7, 4, 24, 11}, the call of stretch(list) should return a new array containing {9, 9, 4, 3, 2, 2, 12, 12, 6, 5}. (The number 18 is stretched into the pair 9, 9, the number 7 is stretched into 4, 3, the number 4 is stretched into 2, 2, the number 24 is stretched into 12, 12 and the number 11 is stretched into 6, 5.)
Test your code with the following class:
import java.util.*;
public class TestStretch {
public static void main(String[] args) {
int[] list = {18, 7, 4, 14, 11};
int[] list2 = stretch(list);
System.out.println(Arrays.toString(list)); // [18, 7, 4, 24, 11]
System.out.println(Arrays.toString(list2)); // [9, 9, 4, 3, 2, 2, 7, 7, 6, 5]
}
// your code goes here
}
This is currently what I have, but it is not quite working correctly... I have a feeling it is how i'm using int i and int j, but i'm not sure what to do to fix it so that it works as intended.
import java.util.*;
public class TestStretch {
public static void main(String[] args) {
int[] list = {18, 7, 4, 14, 11};
int[] list2 = stretch(list);
System.out.println(Arrays.toString(list)); // [18, 7, 4, 24, 11]
System.out.println(Arrays.toString(list2)); // [9, 9, 4, 3, 2, 2, 7, 7, 6, 5]
}
public static int[] stretch(int[] array){
int length = array.length;
int[] newArray = new int[array.length*2];
for(int i = 0; i< length; i=i+2){
int j = 0;
if(array[i] % 2 == 0){
newArray[i] = (array[j]/2);
newArray[i+1] = newArray[i];
j++;
} else{
newArray[i] = (array[j]/2);
newArray[i+1] = (newArray[i] + 1);
j++;
}
}
return newArray;
}
}
The output I get is:
[18, 7, 4, 14, 11]
[9, 9, 9, 9, 9, 10, 0, 0, 0, 0]
Instead of:
[18, 7, 4, 24, 11]
[9, 9, 4, 3, 2, 2, 7, 7, 6, 5]
There are a couple of mistakes:
The loop iterates only until half of the array, skipping elements by 2
The value of j is reset to 0 in each iteration
Also, the algorithm can be simplified:
For each index i in the input, you want to set in the destination at position 2 * i and 2 * i + 1.
The second value to set is simply the original value divided by 2, with integer truncation
The first value to set is the same as the second, +1 if the division by 2 leaves a remainder
With the above issues corrected, and the implementation simplified:
int[] newArray = new int[array.length * 2];
for (int i = 0; i < array.length; i++) {
newArray[2 * i] = array[i] / 2 + array[i] % 2;
newArray[2 * i + 1] = array[i] / 2;
}
return newArray;
First of all, if you are looping to the old array's length, don't increment i by 2.
If i increases by 1 each time, we need to figure out how to map the old array's index i to the new array's index. It is quite simple: the new array's indices are just i*2 and i*2+1.
Now j seems redundant because it always holds the same value as i, so you can remove that.
This is the full code:
int length = array.length;
int[] newArray = new int[array.length*2];
for(int i = 0; i< length; i++){
if(array[i] % 2 == 0){
newArray[i*2] = (array[i]/2);
newArray[i*2+1] = newArray[i*2];
} else{
newArray[i*2] = (array[i]/2);
newArray[i*2+1] = (newArray[i*2] + 1);
}
}
return newArray;
Three mistakes:
j should be initialized outside the for-loop
we should use j to record the new value into the new array
we should increment j upon every iteration in 2 - and we should increment i only by 1 (since we're using j to insert two item while we use i to iterate the original array):
int j = 0;
for(int i = 0; i< length; i++){
if(array[i] % 2 == 0){
newArray[j] = newArray[j+1] = array[i]/2;
} else{
newArray[j] = array[i]/2 + 1;
newArray[j+1] = array[i]/2;
}
j += 2;
}
Note: giving a variable that holds an array the name "list" might create confusion!
for(int i = 0; i< length; i=i+2){
length is the length of the original array, so you iterate only over half of the values because you increase i by 2 each step.
if(array[i] % 2 == 0){
This should be
if(array[j] % 2 == 0){
And because you define j within your for-loop, array[j] always returns 18. Oh and you set the second element of the tuple to be the higher one while your comment in the code says the contrary should take place.
So a fixed version of your method would look like this:
public static int[] stretch(int[] array){
int length = array.length;
int[] newArray = new int[array.length*2];
int j = 0;
for(int i = 0; i< newArray.length; i=i+2){
if(array[j] % 2 == 0){
newArray[i] = (array[j]/2);
newArray[i+1] = newArray[i];
} else{
newArray[i+1] = (array[j]/2);
newArray[i] = (newArray[i+1] + 1);
}
j++;
}
return newArray;
}
Avoiding duplicate code:
public static int[] stretch(int[] array){
int[] newArray = new int[array.length*2];
int j = 0;
for(int i = 0; i< newArray.length; i=i+2){
int val = array[j];
newArray[i] = (val/2);
newArray[i+1] = newArray[i];
if(val % 2 != 0){
newArray[i]++;
}
j++;
}
return newArray;
}
Or using fancy streams:
public static int[] stretch(int[] array){
return Arrays.stream(array)
.flatMap(elem -> {
int half = elem / 2;
int otherHalf = half;
if (elem % 2 != 0) {
half++;
}
return IntStream.of(half, otherHalf);
}).toArray();
}
}

Reverse plus Even and Odd of an array

I am a newbie to programming. I am trying to create a program that would display an array in reverse. Plus also find the even and odd numbers of an array,sum the count and also display the even and odd numbers. The code works but the problem is that it also reverses the even and odd arrays and it shows this weird zero in those arrays. What am I doing wrong?
Please also provide explanation. Thanks!
import java.util.Arrays;
public class ArrayTest {
public static void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13};
for ( int i=0; i<array.length/2; i++ )
{
int temp = array[i];
array[i] = array[array.length-(1+i)];
array[array.length-(1+i)] = temp;
}
System.out.println("Array after reverse: \n" + Arrays.toString(array));
int even=0;
int odd=0;
int[] Even = new int[13];
int[] Odd = new int[13];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[i] = array[i];
even++;
}
else
{
Odd[i] = array[i];
odd++;
}
}
System.out.println("Even: "+even+" ");
System.out.println(Arrays.toString(Even));
System.out.println("Odd: "+odd+" ");
System.out.println(Arrays.toString(Odd));
}
}
The output is:
Array after reverse:
[13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Even: 6
[0, 12, 0, 10, 0, 8, 0, 6, 0, 4, 0, 2, 0]
Odd: 7
[13, 0, 11, 0, 9, 0, 7, 0, 5, 0, 3, 0, 1]
You need to correct your logic
int[] Even = new int[(array.length/2)+1];
int[] Odd = new int[(array.length/2)+1];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[even] = array[i];
even++;
}
else
{
Odd[odd] = array[i];
odd++;
}
}
As per you code, you are initializing array of size 13 for odd and even, which is not correct.
int[] Even = new int[13];
int[] Odd = new int[13];
So, by default, Even and Odd array will be initialized by 0 value. Then, you are setting value as per main array, which a size of 13 on alternate basis (even/odd).
==Updated==
Since, you don't want Even and Odd array in reverse order. Then, you can move the code up.
>>Demo<<
You faced 2 problems (I guess so)
The odd and even arrays are also in reverse order
Reason: The first For loop reverses the 'array' and stores the results in array itself. So, the next time when you try working with 'array' to find odd/even numbers, you are actually working with the reversed array.
Solution: You can assign the original array to a backup array and use that backup array to find odd and even nos.
Unnecessary zeros:
Reason: In your second for loop you used odd[i]=array[i] which seems to be a logical error in your code. Consider the case:
value of i : 0 1 2 3 4 5 ... 12
value of array[i]: 1 2 3 4 5 6 ... 13
value of odd[i] : 1 0 3 0 5 0 ... 13
value of even[i] : 0 2 0 4 0 6 ... 0
This means, the control inside for loop is made to flow either to if{} block or the else{} block and not the both. So, when if(condition) is satisfied, then even[i] array will be updated. But meanwhile what happens to the odd[i] array? It retains the inital value '0'. That's it!
I hope the following code helps you:
import java.util.Arrays;
public class A
{
public static void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int[] arr2 = new int[array.length]; // backup array
arr2=Arrays.copyOfRange(array,0,array.length);
for ( int i=0; i<arr2.length/2; i++ )
{
int temp = arr2[i];
arr2[i] = arr2[arr2.length-(1+i)];
arr2[arr2.length-(1+i)] = temp;
}
System.out.println("Array after reverse: \n" + Arrays.toString(arr2));
int even=0;
int odd=0;
int[] Even = new int[13];
int[] Odd = new int[13];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[even] = array[i];
even++;
}
else
{
Odd[odd] = array[i];
odd++;
}
}
Even=Arrays.copyOfRange(Even,0,even);
Odd=Arrays.copyOfRange(Odd,0,odd);
System.out.println("Even: "+even+" ");
System.out.println(Arrays.toString(Even));
System.out.println("Odd: "+odd+" ");
System.out.println(Arrays.toString(Odd));
}
}
Note: I have used Arrays.copyOfRange(array,start,end) function to copy a certain part of the array from start to end-1 position.
Output:
Array after reverse:
[13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Even: 6
[2, 4, 6, 8, 10, 12]
Odd: 7
[1, 3, 5, 7, 9, 11, 13]
Hope this helps :)
--Mathan Madhav
You select even and odd numbers from reversed array.
You use wrong index for even and odd arrays.
If you don't want to see zeros in output, use print in for statement. Another solution - firstly count odd and even numbers and create arrays with exact size.
import java.util.Arrays;
public class ArrayTest {
public static void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int even=0;
int odd=0;
int[] Even = new int[13];
int[] Odd = new int[13];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[even++] = array[i];
}
else
{
Odd[odd++] = array[i];
}
}
for ( int i=0; i<array.length/2; i++ )
{
int temp = array[i];
array[i] = array[array.length-(1+i)];
array[array.length-(1+i)] = temp;
}
System.out.println("Array after reverse: \n" + Arrays.toString(array));
System.out.println("Even: "+even+" ");
System.out.println(Arrays.toString(Even));
System.out.println("Odd: "+odd+" ");
System.out.println(Arrays.toString(Odd));
}
}

Categories