Locate the largest element in a multidimensional arrays - java

I have to write a program using a method that returns the location of the largest element in a two dimensional array.
example
Enter the number of rows and columns of the array:
3 4
Enter the array:
23.5 35 2 10
4.5 3 45 3.5
35 44 5.5 9.6
the location of the largest element is at (1, 2)
I have finished my code but it isn't working. How can I fix it? All I got are the following errors:
symbol : variable maxvalue
location: class int[]
if (a[i][j] > largest.maxvalue)
^
homework1a.java:51: row is already defined in locateLargest(double[][])
double row = i;
^
homework1a.java:52: column is already defined in locateLargest(double[][])
double column = j;
^
homework1a.java:53: maxValue is already defined in locateLargest(double[][])
double maxValue = a[i][j];
^
homework1a.java:88: i is already defined in main(java.lang.String[])
for (int i = 0; i < 2; i++)
^
5 errors
My code
import java.util.Scanner;
public class hwm1 {
public static int[] locateLargest(double[][] a)
{
int[] largest = new int[2];
double row = 0;
double column = 0;
double maxValue = a[0][0];
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a.length; j++)
{
if (a[i][j] > largest.maxvalue)
{
double row = i;
double column = j;
double maxValue = a[i][j];
}
}
}
return largest;
}
public static void main(String[] args)
{
//Create Scanner
Scanner input = new Scanner(System.in);
//User input rows and columns
System.out.println("Enter the number of rows and columns in the array: ");
int numberOfRows = input.nextInt();
int numberOfColumns = input.nextInt();
//User input data in array
System.out.println("Enter numbers into array: ");
//Create array
double[][] a = new double[numberOfRows][numberOfColumns];
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
a[i][j] = input.nextDouble();
}
int[] largest = locateLargest(a);
System.out.println("The location of the largest element is at "+ "("+largest[0] +", " + largest[1] + ")");
for (int i = 0; i < 2; i++)
{
System.out.print(largest[i]);
}
}
}
}

You are declaring the variables row, column and maxValue twice.
Also, in the line:
if (a[i][j] > largest.maxvalue)
There is no such thing as maxvalue in your code, and neither is it a member of largest
In this part of your code:
Since i is already declared in the outer for-loop, you don't need to declare it again. Just use:
...
for(i = 0; i < 2; i++){
...
}

homework1a.java:51:, homework1a.java:52:, homework1a.java:53:
For these three, remove 'double'. If you state the type when referencing the variable, Java will assume you are trying to define the variable in question. Here you already have those three defined. Additionally, since you don't use row or column at all, I suggest that you simply remove them.
homework1a.java:88: i is already defined in main(java.lang.String[])
For this one, you have a nested for loop, but it uses i as well. You should use k for the second of the nested for loops (the one after the one using j).

. You don't need to post full code below code snippet is sufficient
double row = 0; //declaring first time
double column = 0;//declaring first time
double maxValue = a[0][0];//declaring first time
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a.length; j++)
{
if (a[i][j] > largest.maxvalue)// there is no variable maxvalue in Array class in java
{
double row = i; // declaring again
double column = j;// declaring again
double maxValue = a[i][j];// declaring again
}
}
}
return largest;

Issues:
Loop on j should be using a[i].length
the lines in if block is re-declaring the variables, remove the keyword 'double '
You are not declaring setting largest anywhere so you have a logic issue
Using a largest.maxValue is logically incorrect as it should contain the row and column number and not the actual max value
I would solve this by re-writing the code as follows which I believe is the most efficient way of achieving the goal:
public static int[] locateLargest(double[][] a)
{
int maxRow=-1,maxCol=-1;
double maxVal=-1;
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
if (a[i][j] > maxVal)
{
maxRow = i;
maxCol = j;
maxVal = a[i][j];
}
}
}
return new int[]{maxRow,maxCol};
}
Good luck!

Related

Modifying a static method to add two counters when comparing arrays using for loops in Java

Using this segment of code I already have, I want to modify the selectionSort method to have two counters, one for the number of comparisons, and one for the number of data swaps. Each time two data elements are compared (regardless of whether the items are in the correct order—we're interested in that a comparison is being done at all), increment the comparison counter. Each time two data items are actually swapped, increment the data swap counter.
So far this is what I have tried to add the counters. However, I receive an error "Unresolved compilation problem: counter cannot be resolved to a variable".
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length - 1; i++) {
// Find the minimum in the list[i..list.length-1]
double currentMin = list[i];
int currentMinIndex = i;
int counter = 0;
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
// Swap list[i] with list[currentMinIndex] if necessary;
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
counter += 1;
}
System.out.println("The size of the sorted array is " + list.length + " and the count is " + counter);
}
I have the main method prepared below.
public static void main(String[] args) {
final int NUM_ELEMENTS = 10;
double[] lo2Hi = new double[NUM_ELEMENTS];
for (int i = 0; i < NUM_ELEMENTS; i++) {
lo2Hi[i] = i + 1;
}
selectionSort(lo2Hi);
double[] hi2Lo = new double[NUM_ELEMENTS];
for (int i = 0; i < NUM_ELEMENTS; i++) {
hi2Lo[i] = 10 - i;
}
selectionSort(hi2Lo);
double[] random = new double[NUM_ELEMENTS];
for (int i = 0; i < random.length; i++) {
random[i] = Math.random();
}
selectionSort(random);
}
Your println() at the end of selectionSort() is trying to acces the variable counter, but counter is "out of scope" at that point. Variables only exist within the pair of {}'s they were declared inside (that's what "scope" is).
Move the int counter = 0; statement out of the for loop, and put it at top of the method. Then it will be in-scope for the print statement.

Retrieving second and third column from a 2d array to an array

I have a Java code that will output 3 column of double integer just like this (1 column, 2 column, 3 column):
( 0.09, 0.27, 0.01)
( 0.00, -0.00, 0.26)
( 0.02, -0.02, 0.24)
( 0.22, -0.11, -0.03)
Now, I wish to store all the values from the second column into an array and the values from the third column into another array. Is there a way I could modify it so that it will achieve that?
This is my partial code:
for (int i = 0; i < termVectors.length; ++i) {
System.out.print("(");
for (int k = 0; k < 3; ++k) {
if (k > 0) System.out.print(", ");
System.out.printf("% 5.2f",termVectors[i][k]);
}
System.out.print(") ");
}
Thanks!
Please try the following code.
int[] secondColVal = new int[termVectors.length];
int[] thirdColVal = new int[termVectors.length];
for (int i = 0; i < termVectors.length; ++i) {
System.out.print("(");
for (int k = 0; k < 3; ++k) {
if (k > 0) System.out.print(", ");
System.out.printf("% 5.2f",termVectors[i][k]);
if(k==1)
secondColVal[i] = termVectors[i][k];
if(k==2)
thirdColVal[i] = termVectors[i][k];
}
System.out.print(") ");
}
This should give you what you need :)
// since you're using the length multiple times, store it in a variable!
int len = termVectors.length;
// declare two arrays to represent your second and third columns
int[] secondColumn = new int[len];
int[] thirdColumn = new int[len];
for (int i=0;i<len;i++)
{
// populate your arrays
secondColumn[i] = termVectors[i][1];
thirdColumn[i] = termVectors[i][2];
}

JAVA displaying an array as matrix and random numbers are equal to the minimum

I have to write a JAVA program where a user set the number of columns and rows of a 2d array. Then he should choose a minimum and a maximum. After that, the array is filled randomly.
I writed this code:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class array2d
{
public static void main (String[] args) throws java.lang.Exception
{
int rows, col, min, max;
Scanner scan1 = new Scanner(System.in);
System.out.println("Enter number of rows and columns:");
rows = scan1.nextInt();
col = scan1.nextInt();
int[][] a = new int[rows][col];
System.out.println("Enter min and max:");
min = scan1.nextInt();
max = scan1.nextInt();
for(int i = 0; i<rows; i++)
{
for(int j = 0; j<col; j++)
{
a[i][j] = min - (int)Math.random()*(max-min+1);
}
}
//Display on the screen
for(int i = 0; i<rows; i++)
{
for(int j = 0; j<col; j++)
{
System.out.print(a[i][j]+ " ");
}
}
...
}
}
Then we should run a program to see if the first number of each row is a divisor of all the row:
for(int i = 0; i<rows; i++)
{
for(int j = 0; j<col; j++)
{
if(a[i][0]%a[i][j]==0)
{
System.out.println(a[i][j]);
}
else
System.out.println("None");
}
}
That's working properly, but the generated array on my computer is displayed like that (CMD output):
And as you see in the picture, all randomly filled random are equal to the minimum specified.
So how can I display this array as like matrix and why the random numbers are showing like this.
Math#random return a number between 0.0-1.0, but less then 1.0. This does in fact make your calculation look like the following min-0, since you are parsing it as int. Due to this you are allways saying 0*(max-min+1).
In order to achive what you want you need to add braces and add to min.
For your representation problem, add a System.out.println after you finished the inner loop.
for(int i = 0; i<rows; i++) {
for(int j = 0; j<col; j++) {
a[i][j] = min + (int)(Math.random()*(max-min+1)); // You need brackets and add it to min
}
}
//Display on the screen
for(int i = 0; i<rows; i++) {
for(int j = 0; j<col; j++){
System.out.print(a[i][j]+ " ");
}
System.out.println(); // You need a linebreak
}
All slots of your array get filled wit the 10 value in your example, min in general :
a[i][j] = min - (int)Math.random()*(max-min+1);
yields
a[i][j] = 10 - (int)Math.random()*(10);
Math.random() returns a double greater than or equal to 0.0 and less than 1.0 , so rounded to an int, it is 0 .
so
a[i][j] = 10 - (0*(10)); // this yields 10, the value of "min"
Where you have:
a[i][j] = min - (int)Math.random()*(max-min+1);
You actually mean:
a[i][j] = min + (int) (Math.random()*(max-min+1));
The first one casts Math.random() to an int (giving zero), then multiplies it by (max-min+1) (giving zero), then subtracts it from min (giving min).
The second one multiples Math.random() by an int (giving a random double in the range [0,max-min+1) ), then casts it to an int (giving a random int in the range [0,max-min] ), and then adds min (giving a random int in the range [min,max] ).

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);

Sum of the two dimentional array in Java

This is a homework question and im still a newbie to java.
Write a code segment that computes the sum of all the values in marks.
This is my answer and it has compilation errors. Please help
class myArray{
public static void main(String args []){
int [] [] marks = {{1,2,3,4,5}, {6,7,8,9}, {10,11,12}};
for(int i = 0; i<marks.length; i++){
int sum = 0;
for(int j = 0; j <marks[i].length; j++) {
sum = sum + makrs[j][i];
}
}
System.out.println(sum);
}
}
There are two syntactical errors and one type.
Move int sum =0; above for loop as you need it outside the loop to print the value
Correct marks reading index from marks[j][i] to marks[i][j]
Correct the typo in the same line as above (sum = sum + makrs[j][i];). You have typed makrs in place of marks
int [] [] marks = {{1,2,3,4,5}, {6,7,8,9}, {10,11,12}};
int sum = 0;
for(int i = 0; i<marks.length; i++){
for(int j = 0; j <marks[i].length; j++){
sum = sum + marks[i][j];
}
}
System.out.println(sum);

Categories

Resources