Array length declaration using variable - java

I'm trying to create an array named positiveNumbersArray with the length of the variable positiveNumbers and then store the positive numbers from the array in it. I'm getting this error:
ArrayIndexOutOfBoundsException: 5
int positiveNumbers=0;
int[] array = {12, 0, -22, 0, 43, 545, -4, -55, 12, 43, 0, -999, -87};
for(int i = 0; i<array.length;i++)
if (array[i] > 0)
positiveNumbers++;
int[] positiveNumbersArray = new int[positiveNumbers];
for(int i =0; i<array.length;i++){
if (array[i] > 0)
positiveNumbersArray[i]=array[i];
}

The problem is that you need a separate index for positiveNumbersArray. The simplest fix is:
positiveNumbers = 0;
for(int i =0; i<array.length;i++) {
if(array[i] > 0)
positiveNumbersArray[positiveNumbers++]=array[i];
}
This will insert the numbers into their correct positions in the positiveNumbersArray.

The size of array "array" more then "positiveNumbersArray" and you use index of array "array" to access in array "positiveNumbersArray".
For example: size of "array" is 15 and positive values count are 6. What
happens if index of positive value in array "array" are 8?
Try it:
int positiveNumbers = 0;
int[] array = {12, 0, -22, 0, 43, 545, -4, -55, 12, 43, 0, -999, -87};
for (int i = 0; i < array.length; i++) {
if (array[i] > 0)
positiveNumbers++;
}
int[] positiveNumbersArray = new int[positiveNumbers];
for (int i = 0, index = 0; i < positiveNumbersArray.length; i++, index++) {
while (array[index] <= 0) {
index++;
}
positiveNumbersArray[i] = array[index];
}

Related

Trying to swap the maximum and the minimum numbers in an array

I'm trying to swap the maximum and minimum values in an array in my program.
Here is the code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int myArray[] = new int[25];
for (int i = 0; i < myArray.length; i++) {
System.out.println("Enter a number: ");
myArray[i] = in.nextInt();
}
int maximum = maxNumber(myArray);
int minimum = minNumber(myArray);
System.out.println(Arrays.toString(myArray));
}
public static int maxNumber(int[] arr) {
int maximumValue = arr[0];
//finds the maximum value in an array
for (int a = 1; a < arr.length; a++) {
if (arr[a] > maximumValue) {
maximumValue = arr[a];
}
}
return maximumValue;
}
public static int minNumber(int[] arr) {
int minimumValue = arr[0];
//finds the minimum value in an array
for (int a = 1; a < arr.length; a++) {
if (arr[a] < minimumValue) {
minimumValue = arr[a];
}
}
return minimumValue;
}
I have two separate functions to find the Maximum and Minimum values, but I'm stuck on the actual swapping of the values. The two functions work as I've used them for another program, but I'm not sure if they would work for this program.
At first I was thinking of finding them by setting them equal to each other in some way, but that led to nothing.
Any help would be appreciated.
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
int[] arr = new int[25];
System.out.format("Enter array int numbers (%d in total): ", arr.length);
for (int i = 0; i < arr.length; i++)
arr[i] = scan.nextInt();
System.out.println(Arrays.toString(arr));
swamMinMax(arr);
System.out.println(Arrays.toString(arr));
}
private static void swamMinMax(int[] arr) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
min = Math.min(min, arr[i]);
max = Math.max(max, arr[i]);
}
for (int i = 0; i < arr.length; i++) {
if (arr[i] == min)
arr[i] = max;
else if (arr[i] == max)
arr[i] = min;
}
}
Output:
Enter array int numbers (25 in total): 1 2 3 4 5 6 7 8 9 10 -1 -1 -1 14 15 16 17 18 19 20 21 22 23 66 66
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -1, -1, -1, 1, 1, 1, 17, 18, 19, 20, 21, 22, 23, 66, 66]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 66, 66, 66, 1, 1, 1, 17, 18, 19, 20, 21, 22, 23, -1, -1]
You were real close. I copied some of the code and commented where the changes need to be made. You can still use your existing code to populate the array from the console.
Also, kudos for assigning the first element in the array to min or max and starting your loop at 1. A lot of folks don't think about doing that.
int myArray[] = {1,10,-5,99,48,-22,43, 44,100,2};
System.out.println(Arrays.toString(myArray)); // print original array
int maxIdx = maxNumber(myArray); // get index of max
int minIdx = minNumber(myArray); // get index of min
// now swap max and min using the returned indices.
int save = myArray[maxIdx];
myArray[maxIdx] = myArray[minIdx];
myArray[minIdx] = save;
System.out.println(Arrays.toString(myArray)); // print the altered array
public static int maxNumber(int[] arr) {
int maximumValue = arr[0];
// finds the maximum value in an array
int idx = 0; //idx = 0 to start
for (int a = 1; a < arr.length; a++) {
if (arr[a] > maximumValue) {
idx = a; //save index of current max
maximumValue = arr[a];
}
}
return idx; // return index of max
}
public static int minNumber(int[] arr) {
int minimumValue = arr[0];
// finds the minimum value in an array
int idx = 0; // idx = 0 to start
for (int a = 1; a < arr.length; a++) {
if (arr[a] < minimumValue) {
idx = a; // save index of current min
minimumValue = arr[a];
}
}
return idx; // return index of min
}
This would print
[1, 10, -5, 99, 48, -22, 43, 44, 100, 2]
[1, 10, -5, 99, 48, 100, 43, 44, -22, 2]
You can use IntStream to find indexes of the maximum and minimum elements and then swap their values:
int[] arr = {1, 3, 5, 6, 4, 2, 8, 7, 9, -1, -3};
// indexes of the maximum and minimum elements
int max = IntStream.range(0, arr.length)
.boxed().max(Comparator.comparing(i -> arr[i])).orElse(-1);
int min = IntStream.range(0, arr.length)
.boxed().min(Comparator.comparing(i -> arr[i])).orElse(-1);
// swap the values
int temp = arr[max];
arr[max] = arr[min];
arr[min] = temp;
System.out.println(Arrays.toString(arr));
// [1, 3, 5, 6, 4, 2, 8, 7, -3, -1, 9]

Sort array of negative integers and find pair of Larger integer irrespective of sign

I have an array of integers as shown in the below code. I have to find pair of largest numbers in the array. But there is a small twist.
Please see the below code and output.
public class ArraySort {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = { -9, -2, -10, -1, -4 };
int[] b = null;
int n = a.length;
int temp = 0;
int k = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.println("Ascending Order:");
for (int i = 0; i < n; i++) {
System.out.print(a[i] + ",");
}
System.out.println("\nPair of larger numbers");
for (int i = 0; i < n; i++) {
if (k < 2) {
if (a[i] > a[n - 1 - i]) {
System.out.println(a[i]);
} else {
System.out.println(a[n-1-i]);
}
}
k++;
}
}
}
The output of which is displayed as
Ascending Order:
-10,-9,-4,-2,-1,
Pair of larger numbers
-1
-2
But instead of displaying the largest number as -1,-2. i have to display -10 and -9. the comparison should be without minus sign even though the array contains negative value.
Simply add this:
for(int i = 0; i < a.length; i++){
a[i] = Math.abs(a[i]);
}
This would convert the numbers to positive. Or you can follow what JF said. But that approach won't work if some of them are positive.
If all your integers are negative, why not just display the smallest two integers?
For the task to be meaningful ("difficult") the array should possibly contain both negative and positive numbers.
The candidates for absolute largest numbers reside either at the beginning or end of the array:
-13a, -7, -3, -2, -1, 9, 10b
-10b, -7, -3, -2, -1, 9, 13a
-13a, -11b, -3, -2, -1, 9, 10
-8, -7, -3, -2, -1, 9b, 13a
So you probably got two indices in one loop, one from the beginning, one from the end. No overlap (for -2, 4).
As this is home work, good luck.

Java - arrays - Flow control, looping and branching

In the code below you need to get a array of negative articles and a array of positive articles. How to get a arrays without zero.
package niz;
import java.util.HashSet;
public class Niz {
public static void main(String[] args)
{
int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
int array1[] = new int[array.length];
int array2[] = new int[array.length];
for (int i = 0; i < array.length; i++)
if (array[i] < 0)
array1[i] = array[i];
else
if (array[i] > 0)
array2[i] = array[i];
HashSet<Integer> notDupes = new HashSet<>();
HashSet<Integer> duplicates = new HashSet<>();
for (int i = 0; i < array.length; i++)
{
if (!notDupes.contains(array[i]))
{
notDupes.add(array[i]);
continue;
}
duplicates.add(array[i]);
}
System.out.println("negative members of the array: " + java.util.Arrays.toString(array1));
System.out.println("positive members of the array : " + java.util.Arrays.toString(array2));
System.out.println("number of duplicates : " + duplicates.size());
}
}
The following is the output:
run:
negative members of the array: [0, 0, -22, 0, 0, 0, -4, -55, 0, 0, 0, -999, -87]
positive members of the array : [12, 23, 0, 0, 43, 545, 0, 0, 43, 12, 0, 0, 0]
number of duplicates : 3
BUILD SUCCESSFUL (total time: 1 second)
When you initialize an array of integers, the default elements in the array are zero. Therefore, after filling these arrays, you will still have zero elements inside it corresponding to the numbers that you did not fill. To solve this you can use Lists instead for which you don't have to initialize to a fixed size. If you still would like to have arrays at the end, you can convert the List to an array.
List<Integer> list1 = new ArrayList<Integer>();
List<Integer> list2 = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++)
if (array[i] < 0)
list1.add(array[i]);
else if (array[i] > 0)
list2.add(array[i]);
Integer array1[] = list1.toArray(new Integer[list1.size()]);
Integer array2[] = list2.toArray(new Integer[list2.size()]);
By the way, it would not take much time at all to detect this with a debugger.
As a lazy person I would do following:
public static void main(String... args) {
int[] numbers = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
int[] positiveNumbers = Arrays.stream(numbers).filter(n -> n > 0).toArray();
int[] negativeNumbers = Arrays.stream(numbers).filter(n -> n <= 0).toArray();
int numOfDuplicates = numbers.length - (int)Arrays.stream(numbers).distinct().count();
System.out.println("negative members of the array: " + java.util.Arrays.toString(positiveNumbers));
System.out.println("positive members of the array : " + java.util.Arrays.toString(negativeNumbers));
System.out.println("number of duplicates : " + numOfDuplicates);
}
Java arrays are not dynamically sized. When you create the two arrays (one negative, and one positive) but both the same size as the original array; you will get entries that are 0 (because that's the default initial value for an int in an array). Use two List(s),
List<Integer> al1 = new ArrayList<>();
List<Integer> al2 = new ArrayList<>();
for (int i = 0; i < array.length; i++)
if (array[i] < 0)
al1.add(array[i]);
else if (array[i] > 0)
al2.add(array[i]);
Then to print the List(s),
System.out.println(al1);
System.out.println(al2);
Use List instead of arrays to leverage their power of shrinking, getting wider and smaller as long as you add new items and remove others.
Note that when you instantiate a new array Object, it will initialize all elements with default types, in you case the int items will be initialized to 0 thus you will have as much zeros as the array size.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class Niz
{
public static void main(String[] args)
{
int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
List<Integer> array1 = new ArrayList<Integer>();
List<Integer> array2 = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++)
if (array[i] < 0)
array1.add(array[i]);
else
array2.add(array[i]);
HashSet<Integer> notDupes = new HashSet<Integer>();
HashSet<Integer> duplicates = new HashSet<Integer>();
for (int i = 0; i < array.length; i++)
{
if (!notDupes.contains(array[i]))
{
notDupes.add(array[i]);
continue;
}
duplicates.add(array[i]);
}
System.out.println("negative members of the array: " + array1);
System.out.println("positive members of the array : " + array2);
System.out.println("number of duplicates : " + duplicates.size());
}
}
As a side note, you should avoid unnecessary condition block, such as else if statement since when an int literal is negative (if (array[i] < 0)), then it will be positive for sure thus no need for the (else if (array[i] < 0)) check.
You have maintain a counter while inserting data both for positive array and negative array. Otherwise your array will display 0 for places where you have not put data. This is because all the elements on an array of int will contain 0 by default. for eg
if(array[i] < 0)
array1[i] = array[i];
should be
if(array[i] < 0)
array1[negativeInde++] = array[i];
Also I am of the opinion that using primitive data types is more suited to your cause as using a wrapper like Integer will mean more overheads and incase you have a large array you will take too much time to execute.
Your code should be like this but you will still get zeros at the end as you have unwanted size.
int ctr1 =0;
int ctr2 =0;
for(int i=0;i<array.length;i++)
if(array[i] < 0)
array1[ctr1++] = array[i];
else
if(array[i] > 0)
array2[ctr2++] = array[i];
To get rid of them as well. Use the following code.
int ctr1 = 0;
int ctr2 = 0;
for (int i = 0; i < array.length; i++){
if (array[i] < 0) {
ctr1++;
} else if (array[i] > 0) {
ctr2++;
}
}
int array1[] = new int[ctr1];
int array2[] = new int[ctr2];
ctr1=ctr2=0;
for (int i = 0; i < array.length; i++){
if (array[i] < 0) {
array1[ctr1++] = array[i];
} else if (array[i] > 0) {
array2[ctr2++] = array[i];
}
}
I suggest to you an object-oriented approach, taking advance of the facilities of the Collections API. It is quite clearer:
Code an extension of ArrayList overriding the add() method, so that it only includes positive numbers. Code another extension for negatives.
Then, all you need is create four collections:
A List to include the original array items.
A positive ArrayList.
A negative ArrayList.
A Set for the not-duplicates.
... and just ONE loop, to iterate the original array adding an item to every collection.
After all, remove the not-duplicates from the original list through the removeAll method.

Method that takes an array and compacts it down

The assignment given was, write a program that reads numbers off of a file, construct an array from those numbers, and move all the zeroes to the end of the array.
For example.
Before: 0, 9, 7, 0, 0, 23, 4, 0
After: 9, 7, 23, 4, 0, 0, 0, 0
After toying with it for about 2 hours i came up with this.
import java.io.*;
import java.util.Scanner;
public class Compactor{
Scanner in;
private int numNum = 0;
public void calcNumNum(){
try{
in = new Scanner(new File("compact.txt"));
while(in.hasNext()){
int dumpVal = in.nextInt();
numNum++;
}
makeArray(numNum);
}catch(IOException i){
System.out.println("Error: " + i.getMessage());
}
}
private void makeArray(int x){
int i = 0;
int[] arrayName = new int[x];
try{
in = new Scanner(new File("compact.txt"));
while(i < x){
arrayName[i] = in.nextInt();
i++;
}
compact(arrayName);
}catch(IOException e){
System.out.println("Error: " + e.getMessage());
}
}
private void compact(int[] x){
int counter = 0;
int bCounter = (x.length - 1);
for(int j = 0; j < x.length; j++){
if(x[j]!=0){
x[counter] = x[j];
counter++;
}else{
x[bCounter] = x[j];
bCounter--;
}
}
printArray(x);
}
private void printArray(int[] m){
int count = 0;
while(count < m.length){
System.out.print(m[count] + " ");
count++;
}
}
}
The file that was given to us was: 0, 6, 13, 0, 0, 75, 33, 0, 0, 0, 4, 2,9 21, 0, 86, 0, 32, 66, 0, 0.
What i got was: 6, 13, 75, 33, 4, 29, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0. (without the commas of course, i just put those in for easier reading.)
Could anyone perhaps give me insight on how to fix this problem, or maybe i should just start my code over with a different approach, the whole,
if(x[j]!=0){
x[counter] = x[j];
counter++;
}else{
x[bCounter] = x[j];
bCounter--;
}
i just made it up on the fly, thinking it would work fine, obviously it kept on going after it got past the last value and kept setting more and more values counting backwards as zeroes, no idea how to make it work though, any help would be greatly appreciated.
You're almost there with compact():
private void compact(int[] x) {
int counter = 0;
for (int j = 0; j < x.length; j++) {
if (x[j] != 0) {
x[counter++] = x[j];
}
}
while (counter < x.length) {
x[counter++] = 0;
}
printArray(x);
}
Another way to solve this problem is to create a secondary array of the same size, then do this:
Iterate through the first array. If the number is non-zero, put it into the second array, keeping a counter for the second array starting from 0, increasing by 1 whenever you add an element into it.
Since int arrays initialize to 0, after you go through the initial array once, you'll be done. The second array will hold the answer.
// create your initial array x the same way as before
int[] y = new int[x.length];
int counter = 0;
for(int i = 0; i < x.length; i++) {
if(x[i] != 0) {
y[counter] = x[i];
counter++;
}
}
This part looks reasonable
for(int j = 0; j < x.length; j++){
if(x[j]!=0){
x[counter] = x[j];
counter++;
}
}
It puts all non-zero elements into the beginning of the array. The problem is the else-part, which overwrites elements at the end of the array. Since you already know that only zeros belong to the end of the array, just fill the array with zeros, beginning at counter.
You can do in following simple way also : (It consist of logic for changes in array. As reading from file and storing in array is pretty clear to u.)
package SO;
public class ZeroAtEnd {
public static void main(String[] args) {
int[] arr = new int[] { 0, 6, 13, 0, 0, 75, 33, 0, 0, 0, 4, 2, 9, 21, 0, 86, 0, 32, 66, 0, 0 };
arr = makeZeroAtEnd(arr);
}
private static int[] makeZeroAtEnd(int[] arr) {
int l = arr.length;
int leftCounter = 0;
int rightCounter = l - 1;
int[] finalArr = new int[l];
for (int i = 0; i < l; i++) {
if (arr[i] == 0) {
// put at end
finalArr[rightCounter] = arr[i];
rightCounter--;
} else {
// put at beginning.
finalArr[leftCounter] = arr[i];
leftCounter++;
}
}
for (int i : finalArr)
System.out.println(i);
return finalArr;
}
}
OUTPUT
6
13
75
33
4
2
9
21
86
32
66
0
0
0
0
0
0
0
0
0
0

Index of 2D array in java

Is it possible to get the index of a 2D array?
Suppose I have the following array
int[][] arr = {{41, 44, 51, 71, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
And I want to get the index of 88, how to do it?
for (int i = 0 ; i < size; i++)
for(int j = 0 ; j < size ; j++)
{
if ( arr[i][j] == 88)
{
`save this 2 indexes`
break;
}
}
If they are not sorted, you will have to loop through all indexes [using double loop] and check if it is a match.
int[][] arr = {{41, 44, 51, 71, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] == 88) {
System.out.println("i=" + i + " j=" + j);
}
}
}
will result in:
i=1 j=1
i=2 j=0
This is a primitive array, so it should be directly accessibly with the index:
int[] indexValue = arr[88];
EDIT:
Sorry, reading it again, if you mean the indices of the item 88 then there are multiple occurrences of 88 so you would need to iterate through each index and look for a match in each, and also have the size of the arrays stored somewhere. If it's possible and doesn't impact on performance, use an ArrayList or Vector and store Integers objects instead.
System.out.println(Arrays.toString(da(arr,88)));
}
static int[] da(int dt[][],int target){
for(int i=0;i<dt.length;i++){
for (int j = 0; j <dt[i].length ; j++) {
if(dt[i][j]==target){
return new int[]{i,j};
}
}
}
return new int[]{-1,-1};
}
}

Categories