Java remove odd number from an mixed array - java

why isn't this code working?
I'm supposed to write a function which removes the odd numbers from an array. here is my code but I don't know where it went wrong. It's giving me an error.
public class Test{
public static int [] removeOdd(int[] input){
int c = 0;
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
c++;
}
}
int [] a = new int[c];
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
a[i] = input[i];
}
}
return a;
}
public static void main(String [] args){
int [] mixedArray = {21, 33, 44, 66, 11, 1, 88, 45, 10, 9};
for (int i = 0; i < mixedArray.length; i++) {
System.out.print(mixedArray[i] + " ");
}
System.out.println();
int [] noOdd = Test.removeOdd(mixedArray);
for (int i = 0; i < noOdd.length; i++) {
System.out.print(noOdd[i] + " ");
}
}
Thanks in advance :)

You need another index variable to access the items of a and not use i:
public static int [] removeOdd(int[] input){
int c = 0;
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
c++;
}
}
int [] a = new int[c];
int k = 0;
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
a[k] = input[i];
k++;
}
}
return a;
}
The index variable i iterates through input and its values do not match and will exceed the permitted values of the indexes of a so I have used k.

The problem is here:
int [] a = new int[c];
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
a[i] = input[i];
}
}
This loop will iterate through the whole input array, and try to insert just the even ones into a, but a is smaller than input, because you allocated space equal to the amount of just the even numbers in input.
In your test case, your a will have size 4, but will try to access the position 6, giving you an out of bound exception.

The problem is that you are trying to insert at a[i] which you could visualise like this:
index: 0 1 2 3 4
input: [1 2 3 4 5]
a: [ 2 4 ]
However, your a array is smaller than your input array, because you have reduced the size to account for the lack of odd numbers. You actually want to do this:
index: 0 1 2 3 4
input [1 2 3 4 5]
a [2 4]
Notice how the index of both even numbers has changed. You were trying to keep it the same.
One way to solve this would be to keep a separate counter variable which tracks where you're up when inserting into a.
int[] a = new int[c];
int sizeOfA = 0;
for (int i = 0; i < input.length; i++)
{
if (input[i] % 2 == 0)
{
a[sizeOfA] = input[i];
sizeOfA++;
}
}

You can simplify the method removeOdd using Streams:
import java.util.Arrays;
public class Test {
public static int[] removeOdd(int[] input) {
return Arrays.stream(input).filter(i -> i % 2 == 0).toArray();
}
public static void main(String[] args) {
int[] mixedArray = { 21, 33, 44, 66, 11, 1, 88, 45, 10, 9 };
for (int i = 0; i < mixedArray.length; i++) {
System.out.print(mixedArray[i] + " ");
}
System.out.println();
int[] noOdd = Test.removeOdd(mixedArray);
for (int i = 0; i < noOdd.length; i++) {
System.out.print(noOdd[i] + " ");
}
}
}

Related

How to add comms after every number from array using for loop in Java

I am trying to bring this output: 65, 3, 10 (no comma at the end)
but with my code, I am getting this: 65, 3, , 10
Can anyone help me to write the correct code, please?
Here is my code:
static void printArray(int[] validInput, int arrayFill){ //validInput[] = {65, 3, 10}; arrayFill = 3;(size of array)
for(int i = 0; i < arrayFill; i++)
{
for(int j = 0; j < i; j++)
{
System.out.print(", ");
}
System.out.print(validInput[i]);
}
}
i dont' know why you used a double for but with this solution (a for with an if condition that stops to print ',' when index is equal to the last cycle) you have the desired output
static void printArray(int[] validInput, int arrayFill){ //validInput[] = {65, 3, 10}; arrayFill = 3;(size of array)
for(int i = 0; i < arrayFill; i++)
{
System.out.print(validInput[i]);
if(i!=arrayFill-1) {
System.out.print(", ");
}
}
}
Result:
65, 3, 10

Get the maximum summation of 2D array

There is a 2D array. int[][] arr= {{1,3,4,1},{5,7,8,9},{6,1,2,1}} . I want to get summation of each columns and get the maximum number. Finally it should be returned {5,7,8,9} . Because it has the maximum summation. I have mentioned i tried code below and it not return correct value. Help me to solve this
Your k is supposed to track the index with the greatest sum. So when you are resetting max you need to say k=i. You said i=k by mistake. Changing it makes your program run as desired.
EDIT: There was once code in the original question, to which this solution referred.
If the max column is expected, then I might have a solution:
import java.util.Arrays;
public class ArrayTest {
public static void main(String args[]) {
/*
* 1 3 4 1
* 5 7 8 9
* 6 1 2 1
*
*/
int[][] arr = {{1, 3, 4, 1}, {5, 7, 8, 9}, {6, 1, 2, 1}};
int m = arr.length;
int n = arr[0].length;
int[] arr2 = new int[n];
int p = 0;
int[][] colArray = new int[n][m];
for (int i = 0; i < n; i++) {
int[] arr_i = new int[m];
//System.out.println("i = " + i);
//System.out.println("p = " + p);
int sum = 0;
for (int j = 0; j < m; j++) {
arr_i[j] = arr[j][p];
sum += arr_i[j];
}
//System.out.println("Col: " + p + " : " + Arrays.toString(arr_i));
colArray[i] = arr_i;
arr2[p] = sum;
p++;
}
System.out.println("Sum: " + Arrays.toString(arr2));
int k = 0;
int max = arr2[0];
for (int i = 0; i < 3; i++) {
if (arr2[i] > max) {
max = arr2[i];
k = i;
}
}
System.out.println("Column index for max: " + k);
System.out.println("Column: " + Arrays.toString(colArray[k]));
}
}
Output:
Sum: [12, 11, 14, 11]
Column index for max: 2
Column: [4, 8, 2]
I recommend you find a way to break down your problem into smaller parts, solve each part with a function, then combine everything into a solution.
Example solution below:
public class Main {
public static long sum(int[] a){
long sum = 0;
for (int i : a) {
sum = sum + i;
}
return sum;
}
public static int[] withMaxSumOf(int[][] as){
// keep one sum for each array
long[] sums = new long[as.length];
// calculate sums
for (int i = 0; i < as.length; i++) {
int[] a = as[i];
sums[i] = sum(a);
}
// find the biggest one
int maxIndex = 0;
long maxSum = sums[0];
for (int i=1;i<sums.length;i++){
if (sums[i] > maxSum){
maxSum = sums[i];
maxIndex = i;
}
}
// return array that had biggest sum
return as[maxIndex];
}
public static void main(String[] args){
int[][] arr= {{1,3,4,1},{5,7,8,9},{6,1,2,1}};
// find the one with max sum
int[] max = withMaxSumOf(arr);
// print it
for (int i = 0; i < max.length; i++) {
int x = max[i];
if (i > 0) System.out.print(", ");
System.out.print(x);
}
System.out.println();
}
}
I think this might be your problem:
for(int i=0;i<3;i++) {
if(arr2[i]>max) {
max=arr2[i];
i=k;
}
}
I think that i=k really needs to be k=i.
Note also that it's worthwhile using better variable names. index instead of i, for instance. What is k? Call it "indexForHighestSum" or something like that. It doesn't have to be that long, but k is a meaningless name.
Also, you can combine the summation loop with the find-highest loop.
In the end, I might write it like this:
public class twoDMax {
public static void main(String args[]) {
int[][] arr= { {1,3,4,1}, {5,7,8,9}, {6,1,2,1} };
int indexForMaxRow = 0;
int previousMax = 0;
for(int index = 0; index < 4; ++index) {
int sum = 0;
for(int innerIndex = 0; innerIndex < 4; ++innerIndex) {
sum += arr[index][innerIndex];
}
if (sum > previousMax) {
previousMax = sum;
indexForMaxRow = index;
}
System.out.println(indexForMaxRow);
for(int index = 0; index < 4; ++index) {
System.out.println(arr[indexForMaxRow][index]);
}
}
}
I did a few other stylish things. I made use of more obvious variable names. And I am a little nicer about whitespace, which makes the code easier to read.
public static void main( String args[] ) {
int[][] arr = { { 1, 3, 4, 1 }, { 5, 7, 8, 9 }, { 6, 1, 2, 1 } };
int indexOfMaxSum = 0;
int maxSum = 0;
for ( int i = 0; i < arr.length; i++ ) {
int[] innerArr = arr[ i ]; // grab inner array
int sum = 0; // start sum at 0
for ( int j : innerArr ) {
// iterate over each int in array
sum += j; // add each int to sum
}
if ( sum > maxSum ) {
// if this sum is greater than the old max, store it
maxSum = sum;
indexOfMaxSum = i;
}
}
System.out.println( String.format( "Index %d has the highest sum with a sum of %d", indexOfMaxSum, maxSum ) );
int [] arrayWithLargestSum = arr[indexOfMaxSum]; // return me
}

Fill 2D array square and print in specific patterns

Ive been working on this assignment question for about 4 days now and I'm about to go crazy. We have specific directions to follow for this code;
"Your program should proceed as follows:
Display a welcome message.
Prompt the user for an integer which is 3. If the number entered is < 3. keep prompting the user until they enter a number 3 (use a do/while). This number will determine the size of the square array.
Fill the array as per pattern 1 and display it using printf to format the array.
Fill the same array as per pattern 2 and display it using printf t0 format the array.
Display a closing message."
Pattern:
I'm still stuck on pattern one. I tried to do first do a for loop which in it there's an if statement that checks if the column number is even or not, if it is, to print out the code backwards. The question also recommends using a while loop and a do/while loop...?
Also any tips on to how to go about the second patterns.
Here is my code.
import java.util.Scanner;
public class a3q33
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int n;
do
{
System.out.println("How many rows/columns do you want your array to have? (Must be at least 3)");
n=keyboard.nextInt();
} while(n < 3);
int [][] arr = new int [n][n];
int i, j, k=1;
for(i=0;i<n;i++)
{
if(i % 2 != 0)
{
for(j=n;j>0;j--)
{
k = k+n;
arr[i][j]=k;
k--;
}
}
else
{
for(j=0;j<n;j++)
{
arr[i][j]=k;
k++;
}
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
System.out.printf(arr[i][j]+" ");
}
System.out.printf("");
System.out.println();
}
}
}
Any help would be greatly appreciated!
I assume that you meant "row" instead of "column" for the condition check given that the convention is arr[row][column]?
Also, the for loop in your code:
for(j=n;j>0;j--)
This will decrement the row/column index down to 1 and not 0. So you will miss one element at arr[0][...] or arr[...][0].
Also, j=n will be out of bound.
Instead, try using:
for(j=n-1;j>-1;j--)
It would be a good first steps to look into.
import java.util.Scanner;
public class a3q33{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int n;
do{
System.out.println("How many rows/columns do you want your array to have? (Must be at least 3)");
n=keyboard.nextInt();
} while(n < 3);
int count = 1;
int [][] arr = new int [n][n];
for(int i = 0;i<n; i++){
if(i%2==0){
for(int j = 0;j<n; j++){
arr [i][j] = count;
count++;
}
}
else{
for(int j = n-1;j>=0; j--){
arr [i][j] = count;
count++;
}
}
}
System.out.println("\nPattern 1 \n");
// print the array
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
System.out.printf("%d\t",arr[i][j]);
}
System.out.println();
}
// reset count back to 1 and fill the array in the same way only without the if/else
// for n = 5 for example this will produce [1, 2, 3, 4, 5 ]
// [6, 7, 8, 9, 10]
// [11,12, 13, 14, 15]
// [16,17, 18, 19, 20]
// [21,22, 23, 24, 25]
count = 1;
for(int i = 0;i<n; i++){
for(int j = 0;j<n; j++){
arr [i][j] = count;
count++;
}
}
// rotate arrays using arraycopy; for array at index 1 rotate by one, at index 2 by 2 and so on see
//http://stackoverflow.com/questions/31174840/how-to-rotate-an-array
//
for (int i = 1; i<n; i++){
int [] temp = new int [n];
for (int j = 0; j < n; j++) {
temp[(j + i) % n] = arr[i][j];
}
System.arraycopy(temp, 0, arr[i], 0, n);
arr[i]=temp;
}
System.out.println("\nPattern 2 \n");
// print the array
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
System.out.printf("%d\t",arr[i][j]);
}
System.out.println();
}
}
}
You can achieve this by checking the modulo:
for (int i = 0; i < n; i++) {
int start = i * n;
for (int j = 0; j < n; j++) {
arr[i][j] = i * n + ((i % 2 === 0) ? (j + 1) : (n - j));
}
}

Count how many integers were displayed in an array

I got an 100 random elements array, each element is in range of 0-10, and i need to count each integer how many times it was typed (e.g. 1,2,2,3,8,8,4...)
OUTPUT:
1 - 1
2 - 2
3 - 1
8 - 2
4 - 1
My code so far is:
import java.util.Random;
public class Asses1 {
public static void main(String[] args) {
getNumbers();
}
private static int randInt() {
int max = 10;
int min = 0;
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static int[] getNumbers() {
int number = 100;
int[] array = new int[number];
for (int i = 0; i < array.length; i++) {
System.out.println(randInt());
}
System.out.println(number+" random numbers were displayed");
return array;
}
}
Add this method, which will do the counting:
public static void count(int[] x) {
int[] c=new int[11];
for(int i=0; i<x.length; i++)
c[x[i]]++;
for(int i=0; i<c.length; i++)
System.out.println(i+" - "+c[i]);
}
and change the main into this so that you call the previous method:
public static void main(String[] args) {
count(getNumbers());
}
Also, change the for loop in getNumbers into this in order to fill array with the generated numbers, not just printing them:
for (int i = 0; i < array.length; i++) {
array[i] = randInt();
System.out.println(array[i]);
}
Here is how it can be done in java 8
// Retrieve the random generated numbers
int[] numbers = getNumbers();
// Create an array of counters of size 11 as your values go from 0 to 10
// which means 11 different possible values.
int[] counters = new int[11];
// Iterate over the generated numbers and for each number increment
// the counter that matches with the number
Arrays.stream(numbers).forEach(value -> counters[value]++);
// Print the content of my array of counters
System.out.println(Arrays.toString(counters));
Output:
[12, 11, 7, 6, 9, 12, 8, 8, 10, 9, 8]
NB: Your method getNumbers is not correct you should fix it as next:
public static int[] getNumbers() {
int number = 100;
int[] array = new int[number];
for (int i = 0; i < array.length; i++) {
array[i] = randInt();
}
System.out.println(number+" random numbers were displayed");
return array;
}
int[] array2 = new int[11];
for (int i = 0; i < array.length; i++){
array2[randInt()]++
}
for (int i = 0; i < array.length; i++)
System.out.println(String.valueOf(i) + " - " + String.valueOf(array2[i]));
What I have done is:
Create an helping array array2 for storing number of occurences of each number.
When generating numbers increment number of occurences in helping array.
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
int temp;
for (int i = 0; i < array.length; i++) {
temp=randInt();
if(map.containsKey(temp)){
map.put(temp, map.get(temp)+1);
}else{
map.put(temp, 1);
}
}

Sort an array such a way that First half should be in ascending order Second half should be in descending order in java

I have searched a lot in google but I didnt get any kind of solution I could use. Suppose input of array is:
{3,1,2,4,9,8,7,6,5,10}
then output must be like this:
{1,2,3,4,5,10,9,8,7,6}
by using Basic Java .
Your array: {3,1,2,4,9,8,7,6,5,10}
Sort it in ascending order: {1,2,3,4,5,6,7,8,9,10}
Break this array into two half arrays: {1,2,3,4,5}{6,7,8,9,10}
Sort the second array in descending order or reverse it: {10, 9,8,7,6}
Add the second array to the first array & you get: {1,2,3,4,5,10,9,8,7,6}
This would be the minimal code which uses an array of primitive ints:
static final int[] xs = {3,1,2,4,9,8,7,6,5,10};
static void sortAndReverse() {
Arrays.sort(xs);
for (int i = xs.length/2; i < dest(i); i++) {
int tmp = xs[i]; xs[i] = xs[dest(i)]; xs[dest(i)] = tmp;
}
System.out.println(Arrays.toString(xs));
}
static int dest(int i) { return 3*xs.length/2-i-1; }
If you're not ashamed of using wrapper objects, then this is unbeatable:
final Integer[] xs = {3,1,2,4,9,8,7,6,5,10};
final List<Integer> list = Arrays.asList(xs);
Collections.sort(list);
Collections.reverse(list.subList(list.size()/2, list.size()));
System.out.println(Arrays.toString(xs));
Please find the below code
import java.util.Arrays;
public class fre {
public static void main(String[] args) {
int[] vals = { 3, 1, 2, 4, 9, 8, 7, 6, 5, 10 };
Arrays.sort(vals); // Sorts the basic first array
int[] vals2 = Arrays.copyOfRange(vals, vals.length / 2, vals.length); // Gets the las values of the arrays i.e. it devies the array in multiple same part and another array is created
// Below loop will reverse the second array
for (int i = 0; i < vals2.length / 2; i++) {
int temp = vals2[i];
vals2[i] = vals2[vals2.length - 1 - i];
vals2[vals2.length - 1 - i] = temp;
}
vals = Arrays.copyOfRange(vals, 0, vals.length / 2);
// Final array array1and2 will be created where we will append first array with second array
int[] array1and2 = new int[vals.length + vals2.length];
System.arraycopy(vals, 0, array1and2, 0, vals.length);
System.arraycopy(vals2, 0, array1and2, vals.length, vals2.length);
// Prints the final result array
System.out.println(Arrays.toString(array1and2));
}
}
Output
[1, 2, 3, 4, 5, 10, 9, 8, 7, 6]
You can use the java features to do this too ... Use
public static <T> void sort(T[] a,
int fromIndex,
int toIndex,
Comparator<? super T> c)
But the elements need to be objects ... The comparator needs to be changed while sorting the first half and second half of the array.
Should be a bit simpler than manually reversing each item in the second half.
Integer [] array = { 3,1,2,4,9,8,7,6,5,10 };
Arrays.sort(array);
Arrays.sort(array, array.length/2, array.length, new Comparator<Integer>(){
#Override
public int compare(Integer o1, Integer o2)
{
return -o1.compareTo(o2);
}
});
System.out.println(Arrays.toString(array));
[1, 2, 3, 4, 5, 10, 9, 8, 7, 6]
IPSOS isn't it?
int m;
if(array.length%2==0)
m=array.length/2;
else
m=(array.length+1)/2;
for(int i=0; i<array.length; ++i){
if(i<m){
int min = i;
for(int j=i+1; j<m;++j){
if(array[min]>array[j]){
min=j;
}
int tem = array[i];
array[i]=array[min];
array[min]=tem;
}
}
else {
int max = i;
for(int k=i+1; k<array.length; ++k){
if(array[max]<array[k]){
max=k;
}
int te = array[i];
array[i]=array[max];
array[max]=te;
}
}
}
for(int i=0;i<array.length;++i){
System.out.print(array[i] + " ");
}
1. Sort the array input_Array[]
2. j = lenght(input_Array)-1
3. loop i = lenght(input_Array)/2 to j
swap(input_Array[i] , input_Array[j-i])
input: 3,1,2,4,9,8,7,6,5,10
output: 1 3 5 7 9 10 8 6 4 2 (uniform acceding and descending )
public class AscendingDecending {
public static void main(String[]args) {
int a[]= {2,3,2,5,7,5,6,3};
int i,j,temp;
//Traverse the element of array
System.out.println("Input:");
for(i=0; i<a.length; i++) {
System.out.print(" "+ a[i]);
}
//lets move for ascending function
System.out.println("");
System.out.println("Output:");
//Create a Swap Function for sorting
for(i=0; i<a.length; i++) {
for(j=i+1; j<a.length; j++) {
if(a[i]>a[j]) {
temp= a[i];
a[i]= a[j];
a[j]= temp;
}
}
}
// Now the input is in sorted order
for(i=0; i<a.length/2; i++) {
System.out.print(" "+ a[i]);
}
//For Descending
for(i=0; i<a.length; i++) {
for(int j=i+1; j<a.length; j++) {
if(a[i]<a[j]) {
temp= a[i];
a[i]= a[j];
a[j]= temp;
}
}
}
// Now the input is in sorted order
System.out.println(" ");
for(i=0; i<a.length/2; i++) {
System.out.print(" "+ a[i]);
}
}
}
I hope this piece of code will help:
static void printarray(int[] arr, int len)
{
Arrays.sort(arr);
for (int i = 0; i < len / 2; i++)
System.out.println(arr[i]);
for (int j = len - 1; j >= len / 2; j--)
System.out.println(arr[j]);
}

Categories

Resources