Finding minimum and maximum in Java 2D array - java

I have been trying to figure this out for a while and need some help. I need to find the min/max values and print them out for a multidimensional array. Here are the two ways that I have tried.
import java.util.*;
class MinMax {
public static void main(String[] args) {
int[][] data = {{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}};
Arrays.sort(data);
System.out.println("Minimum = " + data[0]);
System.out.println("Maximum = " + data[data.length - 1]);
}
}
This version complies but doesn't run.
import java.util.*;
class MinMax {
public static void main(String[] args) {
int[][] data = {{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}};
public static int getMaxValue(int[] numbers) {
int maxValue = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > maxValue) {
maxValue = numbers[i];
}
return maxValue;
{
public static int getMinValue (int[] numbers) {
int minValue = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < minValue) {
minValue = numbers[i];
}
}
return minValue;
}
This version just throws me a bunch of errors in compiling. Any help is greatly appreciated.

Ok, I've kinda fixed your code. Actually your mistake was that you have not been traversing all the cells of your multidimensional array.
So, I've added additional loop into getMinValue/getMinValue methods and fixed array elements addressing.
import java.util.*;
class MinMax {
public static void main(String[] args) {
int[][] data = {
{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}
};
System.out.println(getMaxValue(data));
System.out.println(getMinValue(data));
}
public static int getMaxValue(int[][] numbers) {
int maxValue = numbers[0][0];
for (int j = 0; j < numbers.length; j++) {
for (int i = 0; i < numbers[j].length; i++) {
if (numbers[j][i] > maxValue) {
maxValue = numbers[j][i];
}
}
}
return maxValue;
}
public static int getMinValue(int[][] numbers) {
int minValue = numbers[0][0];
for (int j = 0; j < numbers.length; j++) {
for (int i = 0; i < numbers[j].length; i++) {
if (numbers[j][i] < minValue ) {
minValue = numbers[j][i];
}
}
}
return minValue ;
}
}

I have a more fun solution using Java 8 :)
IntSummaryStatistics stats = Arrays.stream(data).flatMapToInt(Arrays::stream).collect(Collectors.summarizingInt(Integer::intValue));
int max = stats.getMax();
int min = stats.getMin();
It's a different solution than yours, obviously. But it does the same thing. To begin with, we convert the 2D array into a Stream of ints. In order to do this first we need to call flatMapToInt. We do this to stream all the elements in the array in a flat way. Imagine if we just start using a single index to iterate over the whole 2D array. It's something like that. Once we have converted the array into a stream, we will use IntSummaryStatistics in order to reuse the same stream for both min and max.

Your problem is: You are sorting the array of int arrays instead of sorting each individual int in each int array.
To solve this: Loop through each int array in the array of int arrays.
Instructions for finding the maximum and minimum of a 2D int array using Arrays.sort():
Declare a 2D int array to sort called data.
Declare two ints, one to hold the maximum value, the other the minimum value.
The initial value of the maximum should be Integer.MIN_VALUE and the initial value of the minimum should be Integer.MAX_VALUE to make sure that negative values are handled.
Loop through data from 0 to data.length:
Sort data[i]
Check if the first value of data[i] is less than the minimum and change it if it is.
Check if the last value of data[i] is greater than the maximum and change it if it is.
Output your result.
Example:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[][] data = {{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8} };
int maximum = Integer.MIN_VALUE;
int minimum = Integer.MAX_VALUE;
for(int i = 0; i < data.length; i++) {
Arrays.sort(data[i]);
if(data[i][0] < minimum) minimum = data[i][0];
if(data[i][data[i].length - 1] > maximum) maximum = data[i][data[i].length - 1];
}
System.out.println("Minimum = " + maximum);
System.out.println("Maximum = " + minimum);
}
}

package array;
public class Max_number {
// 2 5 7 9
// 3 6 8 1
public static void main (String[] arg) {
int a[][] = {{2,5,7,9},{3,6,8,1}};
int max=a[0][0];
for (int i=0; i<2; i++) //row
{
for (int j=0; j<4; j++) //coloum
{
if(a[i][j]>max)
{
max=a[i][j];
}
}
}
System.out.println("maximum number is"+max);
}
}

Related

How to implement a descending selection sort

The method I have to create should take as parameter an array of integers and return the integer array with its contents sorted in descending order — largest to smallest.
Note - no libraries should be used in your implementation for this method.
I've attempted to use a regular selection sort and using a swap at the end but syntax errors just occurred:
public static int[] reverseSelectionSort(int[] arrayToBeSorted) {
// implementation of Task 3 goes here
for(int i = 0; i < arrayToBeSorted.length; i++){
int maxPosition=i;
int minPosition=i;
for(int j = i+1; j < arrayToBeSorted.length - i; j++){
if(arrayToBeSorted[j] < arrayToBeSorted[minPosition]){
minPosition = j;
}
if(arrayToBeSorted[j] > arrayToBeSorted[maxPosition]){
maxPosition = j;
}
}
swap(arrayToBeSorted,minPosition,maxPosition);
swap(arrayToBeSorted,maxPosition,i);
swap(arrayToBeSorted,minPosition,arrayToBeSorted.length-i-1);
}
return arrayToBeSorted; // change this to return the sorted array
}
public static void main(String[] args) {
int[] array2 = {3, 6, 8, 3, 5, 7, 1};
int[] sorted = reverseSelectionSort(array2);
System.out.print("task: [");
for (int i = 0; i < sorted.length; i++) {
if (i > 0) {
System.out.print(", ");
}
System.out.print(sorted[i]);
}
System.out.println("]");
}
If you call the method on the array [3, 6, 8,
3, 5, 7, 1], then the method should return the array [8, 7, 6, 5, 3, 3, 1].
Once you add the implementation of swap to your code (and put it all inside a class), it produces exactly the output you wanted it to. Maybe you thought swap was a java uitl, which it is for Collections, but an array is not a Collection.
So very little has changed in the below:
public class soSelect{ //embed in class, added
public static int[] reverseSelectionSort(int[] arrayToBeSorted) {
// implementation of Task 3 goes here
for(int i = 0; i < arrayToBeSorted.length; i++){
int maxPosition=i;
int minPosition=i;
for(int j = i+1; j < arrayToBeSorted.length - i; j++){
if(arrayToBeSorted[j] < arrayToBeSorted[minPosition]){
minPosition = j;
}
if(arrayToBeSorted[j] > arrayToBeSorted[maxPosition]){
maxPosition = j;
}
}
swap(arrayToBeSorted,minPosition,maxPosition);
swap(arrayToBeSorted,maxPosition,i);
swap(arrayToBeSorted,minPosition,arrayToBeSorted.length-i-1);
}
return arrayToBeSorted; // change this to return the sorted array
}
public static void swap(int[] a, int i, int j){ //had to implement it
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void main(String[] args) {
int[] array2 = {3, 6, 8, 3, 5, 7, 1};
int[] sorted = reverseSelectionSort(array2);
System.out.print("task: [");
for (int i = 0; i < sorted.length; i++) {
if (i > 0) {
System.out.print(", ");
}
System.out.print(sorted[i]);
}
System.out.println("]");
}
}//added outer brace
I ran it in java doodle and it printed:
task: [8, 7, 6, 5, 3, 3, 1]
I did not test beyond that, but this should at least get you unstuck, or, at best, finished. For sure you could compare with the implementation to which the above comment points you.

To Find Leaders in an array

Write a program to print all the LEADERS in the array. An element is leader if it is greater than all the elements to its right side. And the rightmost element is always a leader. For example int the array {16, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2.
Let the input array be arr[] and size of the array be size.
o/p what i am getting is 2 5 17
Note: i want o/p in reverse order , also one below other(line break).
class LeadersInArray
{
/* Java Function to print leaders in an array */
void printLeaders(int arr[], int size)
{
int max_from_right = arr[size-1];
/* Rightmost element is always leader */
System.out.print(max_from_right + " ");
for (int i = size-2; i >= 0; i--)
{
if (max_from_right < arr[i])
{
max_from_right = arr[i];
System.out.print(max_from_right + " ");
}
}
}
public static void main(String[] args)
{
LeadersInArray lead = new LeadersInArray();
int arr[] = new int[]{16, 17, 4, 3, 5, 2};
int n = arr.length;
lead.printLeaders(arr, n);
}
}
Expected output:
17
5
2
Intead of printing those within the loop, add those to a list, and then print those separately.
Following are the changes in your code.
class LeadersInArray {
List<Integer> printLeaders(int[] arr, int size) {
List<Integer> list = new ArrayList<>();
int max_from_right = arr[size - 1];
list.add(max_from_right);
for (int i = size - 1; i >= 0; i--) {
if (max_from_right < arr[i]) {
max_from_right = arr[i];
list.add(max_from_right);
}
}
return list;
}
public static void main(String[] args) {
LeadersInArray lead = new LeadersInArray();
int arr[] = new int[]{16, 17, 4, 3, 5, 2};
List<Integer> integers = lead.printLeaders(arr, arr.length);
for(int i = integers.size()-1; i>=0 ;i--){
System.out.println(integers.get(i));
}
}
}

how to change negative number in array to their index slot

Im trying to change the negative numbers in the wholeNumbers array to their slot/index-number and then print out the array. Also I have to use a while loop. This is what Ive got so far, but now Im stuck. Am I on the right track copying the array? How do I proceed, is it correct that "change[counter]" be equal to "counter"? Or am my thinking wrong? When i run i get error
public class NegativeNumber {
public static void main(String[] args) {
int[] wholeNumbers = {1, 4, 5, -2, -4, 6, 10, 3, -2};
int counter = 0;
int negativeCounter = 0;
int sum = 0;
while(counter < wholeNumbers.length) {
if(wholeNumbers[counter] < 0)
{
sum += wholeNumbers[counter];
negativeCounter++;
}
counter++;
}
System.out.println("Negative numbers: "+negativeCounter);
int[] change = Arrays.copyOf(wholeNumbers, wholeNumbers.length);
while(counter < change.length) { //get error
if(change[counter] < 0){
change[counter]=counter;
System.out.println(change[counter]);
}
}
}
}
}
public static void main(String[] args) {
int[] wholeNumbers = {1, 4, 5, -2, -4, 6, 10, 3, -2};
int negativeCount;
for(int i = 0; i < wholeNumbers.length; i++) {
if(wholeNumbers[i] < 0) {
negativeCount++;
wholeNumbers[i] = i;
}
}
}
With a while
public static void main(String[] args) {
int[] wholeNumbers = {1, 4, 5, -2, -4, 6, 10, 3, -2};
int negativeCount;
int idx = 0;
while(idx < wholeNumbers.length) {
if(wholeNumbers[idx] < 0) {
negativeCount++;
wholeNumbers[idx] = idx;
}
idx++;
}
}
here is it:
import java.util.*;
public class NegativeNumber {
public static void main(String[] args)
{
int[] wholeNumbers = {1, 4, 5, -2, -4, 6, 10, 3, -2};
int counter = 0;
int negativeCounter = 0;
int sum = 0;
while(counter < wholeNumbers.length)
{
if(wholeNumbers[counter] < 0)
{
sum += wholeNumbers[counter];
negativeCounter++;
}
counter++;
}
System.out.println("Negative numbers: "+negativeCounter);
int[] change = Arrays.copyOf(wholeNumbers, wholeNumbers.length);
counter = 0; // You forgot to reset this
while(counter < change.length)
{
if(change[counter] < 0)
{
change[counter]=counter;
System.out.println(change[counter]);
}
counter++; // You forgot to increment this
}// while
}// main
}
There were two errors, the counter variable needed to be set back to zero, and into the second while you needed to increment it again (see the comments inside the code).
The output of your program now is:
Negative numbers: 3
3
4
8

Java filling in an array

How would one go about filling in an array so that, for example, if you had the following array.
int[] arr = new int[5];
arr[0] = 1;
arr[1] = 3;
arr[2] = 7;
arr[3] = 2;
arr[4] = -4;
so it would look like
arr = {1, 3, 7, 2, -4};
and you would pass it into your method to get a result of
arr = {1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4};
so that you essentially are filling in the numeric gaps. I'd like to make this under the assumption that I don't know how long the array passed in is going to be to make it a more universal method.
my current method looks like such right now...
public static void fillArray(int[] numbers){
int length = numbers.length;
for(int i = 0; i < numbers.length - 1; i ++){
if(numbers[i] <= numbers[i + 1]){
length += numbers[i + 1] - numbers[i];
}else if(numbers[i + 1] < numbers[i]){
length += numbers[i + 1] - numbers[i];
}
}
}
I have length to determine the size of my new array. I think it should work but I'm always down for some input and advice.
Looks like homework, providing algorithm only:
Navigate through the elements of the current array.
Get the distance (absolute difference) between the elements in the array.
Summarize the distances.
Create a new array whose length would be the sum of the distances.
Fill the new array using the elements of the first array and filling the gaps.
Return the array.
Like Luiggi Mendoza said, looks like HW, so here's another algorithm:
insert the first element into a list of integers.
loop on the rest of the elements.
for each two array elements X[i-1], X[i], insert the missing integers to the list
after the loop - use guava to turn the List to array.
This works. just check for array size < 2 for safety.
public static void main(String[] args) {
int[] arr = {1, 3, 7, 2, -4};
Integer[] result = fillArray(arr);
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
}
private static Integer[] fillArray(int[] arr) {
List<Integer> list = new ArrayList<Integer>();
list.add(arr[0]);
for (int i = 1; i < arr.length; i++) {
int prevItem = arr[i-1];
int gap = arr[i] - prevItem;
if(gap > 0){
fillGap(list, prevItem, gap, 1);
} else if(gap < 0){
fillGap(list, prevItem, gap, -1);
}
}
return list.toArray(new Integer[0]);
}
private static void fillGap(List<Integer> list, int start, int gap, int delta) {
int next = start+delta;
for (int j = 0; j < Math.abs(gap); j++) {
list.add(next);
next = next+delta;
}
}
Try
import java.util.ArrayList;
import java.util.List;
public class ArrayGap {
public static void main(String[] args) {
int[] arr = {1, 3, 7, 2, -4};
int high, low;
List<Integer> out = new ArrayList<Integer>();
for(int i=0; i<arr.length - 1; i++){
high = arr[i];
if(arr[i] < arr[i+1]){
for(int j=arr[i]; j<arr[i+1]; j++){
out.add(j);
}
} else {
for(int j=arr[i]; j>=arr[i+1]; j--){
out.add(j);
}
}
}
System.out.println(out);
}
}

Trying to find the sum of the last column

public class arsum
{
static int[][] myarray = {{1, 2, 3, 4}, {5, 6, 7, 8}, {1, 2, 3, 4}};
public int[] summing(int[][] array)
{
int index = 0;
int a[] = new int[array[index].length];
for (int i = 0; i < array[0].length; i++)
{
int sum = 0;
for (int j = 0; j < array.length; j++)
{
sum += array[j][i];
}
a[index] = sum;
System.out.println(sum);
}
return a;
}
public static void main(String[] args) {
new arsum().summing(myarray);
}
}
At the moment it prints out all 4 column sums, however I only want the last sum. I cannot figure out how to code it properly for any general array.
I am new to coding and have not totally figured everything out yet.
Try,
int[][] myarray = {{1, 2, 3, 4}, {5, 6, 7, 8}, {1, 2, 3, 4}};
int sum = 0;
for (int nums[] : myarray) {
sum += nums[nums.length - 1];
}
System.out.println(sum);
you can also use array indexing to print sum of last column as below:-
public static int summing(int[][] array)
{
int row = array.length;
int sum = 0;
for (int i = row - 1; i > row - 2; i--) {
int col = myarray[i].length;
for (int j = 0; j < col; j++) {
sum += array[i][j];
}
System.out.println(sum);
}
return sum;
}

Categories

Resources