How to Create Method for Finding Largest Element in Array - java

public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int numberOfRows, numberOfColumns;
double arrayElements[][] = null;
int index[] = null;
System.out.print("Enter number of rows in array: ");
numberOfRows = keyboard.nextInt();
System.out.print("Enter number of columns in array: ");
numberOfColumns = keyboard.nextInt();
arrayElements = new double[numberOfRows][numberOfColumns]; //this command allocates memory for the array arrayElements
for (int row = 0; row < numberOfRows; row++)
{
for (int column = 0; column < numberOfColumns; column++)
{
System.out.print("Enter the Value for Row [" + row + "], Column " + "[" + column + "]: ");
arrayElements[row][column] = keyboard.nextDouble();
}
}
System.out.printf("\n Two-Dimensional Array: %d rows x %d columns\n", numberOfRows, numberOfColumns);
for (int row = 0; row < numberOfRows; row++)
{
System.out.printf("Row %3d:", row);
for (int column = 0; column < numberOfColumns; column++)
{
System.out.printf("%7.1f", arrayElements[row][column] );
}
System.out.println();
index = locateLargest( arrayElements );
}
}
public static int[] locateLargest( double[][] arrayx2 ){
}
Hello all,
I am trying to write a method for finding the largest element in a two-dimensional array, and return the index of the element with the highest value to the single-dimensional array 'index'. I have the signature written, but can anyone please help me figure out how to actually write the method that will search each element of the two-dimensional array and find the index location of the largest number?
Thank you so much!

/*Finds max value in an Array*/
public int maxValue(int array[]){
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++) {
list.add(array[i]);
}
return Collections.max(list);
}
For 2 dimensional array use that:
int maxValue = 0;
System.out.println("\nMax values in 2D array: ");
for (int i = 0; i < twodArray.length; i++) {
for (int j = 0; j < twodArray[i].length; j++) {
if (twodArray[i][j] > maxValue) {
maxValue = twodArray[i][j];
}
}
System.out.println("Max value of row " + i + ": " + maxValue);
}
Reference: https://stackoverflow.com/a/5877271/1848929

Firstly, if you want the returned array of your method to contain the largest element as well as the index, the return type should be double[] and not int[] since the type of the elements of the matrix is double. The method bellow will return an array containing three elements. the first element is the row index, the second is the column index, and the third is the element value. if you are going to use the code bellow, make sure to change the return type and also the type of index in your code to double[]. I hope this is helpful.
// first we assume the largest element is the one located at row 0, and
//column 0, then we compare it with the other elements in the matrix
public static double[] locateLargest( double[][] arrayx2 ){
double max = arrayx2[0][0];
int row = 0, col = 0;
double[] indexAndMaxVal = new double[3];
for (int i = 0; i < arrayx2.length; i++) {
for (int j = 0; j < arrayx2[i].length; j++) {
if (arraux2[i][j] > max) {
maxValue = arrayx2[i][j];
row = i;
col = j
}
}
}
indexAndMaxVal[0] = row;
indexAndMaxVal[1] = col;
indexAndMaxVal[2] = max;
return indexAndMaxVal;
}

Related

How to write a method for a transposed matrix?

I am trying to create an application class MatrixApplication, in which the user first enters the number of rows and columns of the matrix.
This will be used to create an array object.
Then the elements of the Matrix are called up row by row and column by column. When all elements have been read in, they are assigned to the matrix object.
Next, the array is transposed and finally the transposed array is displayed.
How do I assign the elements to the Matrix object?
How do I display a transposed array?
package domain;
public class Matrix {
private int[][] numbers;
public Matrix(int rows, int columns) {
setNumbers(numbers);
if (rows < 1)
rows = 1;
else
rows = rows;
if (columns < 1)
columns = 1;
else
columns = columns;
numbers = new int[rows][columns];
}
public final void setNumbers(int[][] numbers) {
this.numbers = numbers;
}
public int[][] getNumbers() {
return numbers;
}
public int[][] transpose() {
int[][] transpose = new int[numbers[0].length][numbers.length];
for (int i = 0; i < numbers.length; ++i) {
for (int j = 0; j < numbers[0].length; ++j) {
transpose[j][i] = numbers[i][j];
}
}
return transpose;
}
}
package ui;
import java.util.Scanner;
import domain.Matrix;
public class MatrixApplication {
public static void main (String[]args)
{
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of rows of the matrix:");
int rows = input.nextInt();
System.out.print("nter the number of columns of the matrix:");
int colums = input.nextInt();
Matrix matrix = new Matrix(rows, colums);
final int[][] numbers = new int[rows][colums];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < colums; ++j) {
System.out.printf("Enter the element of row %d and column %d: ", i + 1, j + 1);
numbers[i][j] = input.nextInt();
}
}
}
System.out.printf("The transposed matrix: %d",matrix.transpose());
}
}
And if I want this form of transposed matrix:
example of a 4x2 array to a 2x4 array
Simply read the numbers into a two-dimensional array and call matrix.setNumbers.
final int[][] numbers = new int[rows][colums];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < colums; ++j) {
System.out.printf("Enter the element of row %d and column %d: ", i + 1, j + 1);
numbers[i][j] = input.nextInt();
}
}
matrix.setNumbers(numbers);
System.out.printf("The transposed matrix: %s", Arrays.deepToString(matrix.transpose()));

Need to print the max element column in java

Hello I am new in java and I want to write a program where I will print the max element from the column in 2D table. I am updating a picture to show what actually I want to print.
Here is the code:
import java.util.*;
public class MaxColumnElement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int col = sc.nextInt();
int row = sc.nextInt();
int[][] table = new int [col][row];
int max= 0;
for(int i=0; i<col; i++){
for(int j=0; j<row; j++){
max= table[i][0];
table[i][j]= sc.nextInt();
if(max<table[i][j]){
max= table[i][j];
}
}
System.out.println("Maximum number is "+ max);
System.out.println();
}
}
}
You can index a matrix (2D table) like this:
matrix[row][column]
where row and column are 0-based indexes.
You have to change the loop like this:
int max= 0;
for(int i=0; i<col; i++){
// select first element of a column as temp max
max= table[0][i];
for(int j=0; j<row; j++){
// cycle on rows
if(max<table[j][i]){
max= table[j][i];
}
}
System.out.println("Maximum number is "+ max);
System.out.println();
}
You have to cycle on column. Select the first element of a column as temporary maximum
You have to init the max when you end a row, not inside the nested loop
Side note: I suggest you to keep the code clean (because is a simple example and I assume you have a little file) and separate tasks:
First, read the file (perhaps print the file content to be sure the content it's ok)
Then, check the maximum of each column
In this way will be simpler for you to catch problems.
You need to separate the values insertion and finding the maximum value so you can iterate the array by columns
public class MaxColumnElement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int col = sc.nextInt();
int row = sc.nextInt();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
table[i][j] = sc.nextInt();
}
}
int[][] table = new int[col][row];
for (int i = 0; i < col; i++) {
int max = table[0][i];
for (int j = 0; j < row; j++) {
if (max < table[j][i]) {
max = table[j][i];
}
}
System.out.println("Maximum number is " + max);
System.out.println();
}
}
}
Output
Maximum number is 10
Maximum number is 5
Maximum number is -3
Maximum number is 9

Finding the mode of a 2D array

I'm trying to return the mode of a 2D array using a frequency array. I have an array, score, which is of length 10, and has 3 columns. Each column contains an int that is between 0 and 100.
I'm trying to find a way that will iterate through the array and return the modal value. What I have so far is:
int value = 0;
int[] freq = new int[100];
for (int row = 0; row < score.length; row++) {
for (int col = 0; col < score[row].length; col++) {
score[row][col] = value;
freq[value]++;
}
}
int largest = 0;
int mode = -1;
for (int i = 0; i < 100; i++) {
if (freq[i] > largest)
{
largest = freq[i];
mode = i;
}
}
System.out.println("modal score is: " +mode);
Problem is that this is just returning the modal score as 0, which it isn't.
You have a problem on generating the freq array. If I understand correctly, on the first double-for block you are trying to put the frequencies of the numbers inside the freq array.
But all you do is:
int value = 0;
.....
score[row][col] = value;
freq[value]++;`
firstly you are changing the score array,( which is a problem for you I guess...) and the you go to freq[0] and do ++. Obviously modal is 0, that number appears in all of the array.
SOLUTION: in the first double for block you should do:
value = score[row][col];
freq[value]++;
so I think you mixed up the order of the line, it should be the other way around.
private static void printMode(double[][] doubles) {
HashMap<Double , Double> map = new HashMap();
for (int i = 0; i < doubles.length; i++) {
for (int j = 0; j < doubles[i].length; j++) {
double temp = doubles[i][j];
if(map.get(temp)==null){
map.put(doubles[i][j],1.0);
}else {
double temp2 = (double) map.get(temp);
map.put(doubles[i][j],++temp2);
}
}
}
Object[] objects = map.values().stream().sorted().toArray();
Stream stream = map.entrySet().stream().filter(val-> val.getValue().equals(objects[objects.length-1]));
stream.forEach(System.out::println);
}
I think using Stream for finding mode is the best way.
use int instead of double doesn't cause any problems.
int value = 0;
int [] freq = new int [arr.length];
for (int i = 0; i < arr.length; i++){
for (int j = 0; j < arr[i].length; j++){
value = arr[i][j];
freq[value]++;
}
}
int largest = 0;
int mode = 0;
for (int i = 0; i < freq.length; i++) {
if (freq[i] > largest)
{
largest = freq[i];
mode = i;
}
}
System.out.println("modal score is: " +mode);

unable to return a 2-dimensional array from a method

I had to write a program that find the largest element in an array. The user is prompted to enter the number of rows and columns, then prompted to enter the numbers in the rows and columns.
This array is then passed to a method where each number in every column of every row is compared and when the largest number is found the location is then moved to a field which, hopefully, return from the method.
It is not working. Here is my code.. I am sure that it is something silly, but what I can't figure it out. I think that it might have to with the 'a' in calling the method.
I define 'a' with double[][] a = new double[r][c];
I call and pass to the method with int[] find = locateLargest(a);
I tried to use all 3 of these as the return statement:
// return largest;
return largest[indxrow][indxcol];
// return [indxrow][indxcol];
How can I fix my code?
void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Enter the number of rows and columns of the array");
int r = input.nextInt();
int c = input.nextInt();
double[][] rowCol = new double[r][c];
double[][] a = new double[r][c];
System.out.println("Enter the array");
for (int rows = 0; rows < rowCol.length; rows++) {
for (int cols = 0; cols < rowCol[rows].length; cols++) {
rowCol[rows][cols] = input.nextDouble();
a[rows][cols] = rowCol[rows][cols];
int[] find = locateLargest(a);
}
}
System.out.println("The location of the largest element is at (" + a[0] + ", " + a[1] + ")");
}
public static int[] locateLargest(double[][] a) {
double largest = 0;
int indxrow;
int indxcol;
for (int lcol = 0; lcol < a[0].length; lcol++ ) {
largest = a[0][lcol];
indxcol = lcol;
}
for (int lrow = 1; lrow < a.length; lrow++) {
for (int lcol = 0; lcol < a[lrow].length; lcol++)
if (a[lrow][lcol] > largest) {
largest = a[lrow][lcol];
indxrow = lrow;
}
}
// return largest;
return largest[indxrow][indxcol];
//return [indxrow][indxcol];
}
}
You are trying to return a double, when the actual return type of the method is an int[]
from how your code looks, it seems that you mean to return the largest number in the array.. In that case you should return a double, since your array you pass in is a double[][]
public static double locateLargest(double[][] a) {
double largest = 0;
for (int lcol = 0; lcol < a[0].length; lcol++) {
largest = a[0][lcol];
}
for (int lrow = 1; lrow < a.length; lrow++) {
for (int lcol = 0; lcol < a[lrow].length; lcol++)
if (a[lrow][lcol] > largest) {
largest = a[lrow][lcol];
}
}
return largest;
}
In order to return an int[] (as you specified in public static int[] locateLargest(double[][] a)) in your method, you should use
return a[lrow];
because a is an int[][], so a[a_certain_position] will be an int[], i.e. what you are looking for.
EDIT:
This assuming that a was an int[][], but I noticed you defined it as a double[][]. Keep in mind (int[])a[lrow] cast is not possible in Java, so I would suggest you to change your method to return a double[] instead, like this:
public static double[] locateLargest(double[][] a)

trouble with creating a method that returns the average of each column of a 2d array (this is in java)

Im having trouble creating this method because i just started on arrays and now i have to create a method that takes as an input an 2d array of inters and returns one single array that contains the average for each column? can anyone help?
public class Assigment4 {
public static void main(String[] args) {
int[][] a = new int[5][5];
a[0][0] = 1; //rows
a[0][1] = 2;
a[0][2] = 3;
a[0][3] = 4;
a[0][0] = 1; //columns
a[1][0]= 2;
a[2][0] = 3;
a[3][0] = 4;
double []summ =(averageForEachColumn(a));
}
public static double [] averageForEachColumn (int [][] numbers){
double ave [] = new double[numbers[0].length];
int count=0;
for (int i = 0; i < numbers[0].length; i++){
double sum = 0;
count= count+1;
for (int j = 0; j < numbers.length; j++){
count= count +1;
sum += numbers[j][i];
}
ave[i] = sum/count;
System.out.println (sum);
}
return ave;
}
}
Your count should be reset to 0 before the inner loop.
count= count+1; // change this to count = 0;
for (int j = 0; j < numbers.length; j++){
You haven't populated most of the values in the 2d array. There are 16 total values, you have populated 7 of them (one of them twice).
Get rid of count altogether, you don't need it.
Change:
ave[i] = sum/count;
To:
ave[i] = sum/a[i].length;
This is a simplified example of a 2x4 array. You can add more values at you leisure.
public static void main(String[] args)
{
int[][] array = {{1, 2, 3, 4},{5, 6, 7, 8}};
for(int col = 0; col < 4; col++)
{
double sum = 0;
int row = 0;
while (row < array.length)
{
sum+=array[row++][col];
}
System.out.println("Average of values stored in column " + col + " is " + sum / array.length);
}
}
Of course, you can add the result of sum/array.length to an array of averages instead of just displaying it.

Categories

Resources