I was trying to write a method that finds the largest number in a column. However, it seems that I am having problem to find a way to return the highest number in a column rather than taking into consideration all numbers combined in the array. I would really appreciate any comments or feedback!
This is my code:
public static void max1(int[][] score) {
for (int i = 0; i < score.length; i++) {
int max = score[0][0];
for (int j = 0; j < score[i].length; j++)
if (score[i][j] > max)
max = score[i][j];
System.out.println(max + " ");
}
}
You are trying to find the max in row not in column. Do some changes in your code
public static void max1(int[][] score) {
for (int i = 0; i < score[0].length; i++) { // i should be your column
int max = score[0][i];// assign 1st value of the column as max
for (int j = 0; j < score.length; j++){ // j is your row
if (score[j][i] > max){ // check the column elements instead of row elements
max = score[j][i];// get the column values
}
}
System.out.println(max + " ");
}
}
Do int max = score[0][i]; instead of int max = score[0][0]; Because if you always intialize max with score[0][0] and this int is bigger then the biggest value in a column, you will get a wrong result.
And do:
if (score[innerloop][outerloop] > max)
max = score[innerloop][outerloop];
instead of:
if (score[outerloop][innerloop] > max)
max = score[outerloop][innerloop];
That was logical failure because the first index is the column and the secound is the row.
score[0][0] = 1;
score[0][1] = 2;
score[0][2] = 3;
score[1][0] = 4;
score[1][1] = 5;
score[1][2] = 6;
score[2][0] = 7;
score[2][1] = 8;
score[2][2] = 9;
The Array now look like this matrix:
1 2 3
4 5 6
7 8 9
You want compare for example 1,4,7 so you habe to compare score[0][0], score[0][1], score[0][2]. So the secound index must be the counter of the inner for-loop.
You need to specify the index of the column you want to find the max in and loop on rows:
public static int maxCol(int [][] score, int colIndex) {
int max = score[0][colIndex];
for(int i = 0 ; i < score.length ; ++i) {
max = Math.max(max, score[i][colIndex]);
}
return max;
}
public static void max1(int[][] score) {
for (int i = 0; i < score.length; i++) {
int max = -1;
for (int j = 0; j < score[i].length; j++)
if (score[i][j] > max)
max = score[i][j];
System.out.println("max: '" + max + "'");
}
}
And perhaps you switched your columns and rows, means you have to switch the code too, happened already a lot to me. Try to check if i is your rows and j is your columns.
The following code prints the Maximum Number in each column.
public static void max1(int[][] score) {
for (int i = 0; i < score.length; i++) {
int max = Integer.MIN_VALUE; // set max to minimum value before starting loop
for (int j = 0; j < score[i].length; j++)
{
if (score[i][j] > max)
max = score[i][j];
}
System.out.println(max + " ");
}
}
First you should change the int max = score[0][0]; into as int max = Integer.MIN_VALUE; as it might produce not valid result.
And the second is that you need to swap the index while compare
if (score[j][i] > max) {
max = score[j][i];
}
static int max1(int[][] score) {
int max = score[0][0]; // set initial value to the first index in array
for (int i = 0; i < score.length; i++) { // cycle through row
for (int j = 0; j < score[i].length; j++) { // cycle through colmn
if (score[i][j] > max) { // if the index value is greater than largest number
max = score[i][j]; // make it the new index value
}
}
} return max;
}
Related
This question already has answers here:
Finding the second highest number in array
(45 answers)
Closed 4 years ago.
Working on a program where we need separate methods to find the highest and second highest numbers. My code finds the highest number just fine but I can't figure out how to find the second highest number.
public static int highestNumber(int []array1) {
int max = -999999;
for (int i = 1; i < array1.length; i++) {
if (array1[i] > max) {
max = array1[i];
}
}
return max;
}
public static int secondHighest(int []array1) {
int highest= highestNumber(array1);
int secondHighest = array1[0];
for (int i=1; i<array1.length; i++){
if(array1[i]> highest && array1[i] secondHighest);
secondHighest=array1[i];
}
return secondHighest;
}
I'm not prefered using -9999999, use Integer.MIN_VALUE or use first index of array instead, but when use first index, make sure the length of array must greater or equals 1
public static int secondHighest(int[] array1)
{
int highest = highestNumber(array1);
int max = array[0];
for( int i = 1; i < array1.Length; i++)
{
if(array[i] > max && array[i] < highest){
max = array[i];
}
}
return max;
}
public static int secondHighest(int[] array1)
{
int highest = highestNumber(array1);
int max = -9999999;
for( int i = 0; i < array1.Length; i++)
{
if(array[i] > max && array[i] < highest) max = array[i];
}
return max;
}
To find the maximum integer value in a matrix I try to code some of that:
/*
* #param ints
* #return the max value in the array of chars
*/
public static int maxMatrix(int [][] ints) {
int max = ints[0][0];
for(int i = 0; i < ints.length; i++) {
for(int j = 0; j < ints.length){
max = inst[i][j];
}
}
return max;
}
My questions are:
Why am I assigning the variable to the next one in the array?
What are the conditions and why?
max = inst[i][j];
Should be max = Math.max(max, ints[i][j]);
and...
for(int j = 0; j < ints.length){
should be for(int j = 0; j < ints[i].length; j++){
So...
public static int maxMatrix(int [][] ints) {
int max = ints[0][0];
for(int i = 0; i < ints.length; i++) {
for(int j = 0; j < ints[i].length; j++){
max = Math.max(max, ints[i][j]);
}
}
return max;
}
You need to do Math.max. Otherwise you're just assigning the variable to the next in the array
Math.max(max, ints[i][j]) is equivalent to:
if (max > ints[i][j] {
return ints[i][j]; // or inline in your loop: max = ints[i][j];
} else {
return max; // or inline in your loop: max = max; which is a not needed
}
I suggest this
for (int[] a : ints) {
for (int e : a) {
if (e > max) {
max = e;
}
}
}
You need an if statement inside of your loop for that to work. Also you need to check the length of the second part of the array.
public static int maxMatrix(int [][] ints) {
int max = ints[0][0];
for(int i = 0; i < ints.length; i++) {
for(int j = 0; j < ints[].length){
if(inst[i][j] > max){
max = inst[i][j];
}
}
}
return max;
}
I'm practicing finding max and min values, but I want to keep track of how many instances of those values I have. The program does find the min and max values, but it doesn't give the number of times the value appears in the array, so my counter is not working. Can someone give me a hand please? Thanks!
int[] values = {222,34,56,222,45,1,3,222,56,10,15,56,1,222,12,23,1,222};
int minValue = values[0];
int maxValue = values[0];
int counterMinValue = 0;
int counterMaxValue = 0;
int i;
for(i = 0; i < values.length; i++){
if (values[i] < minValue){
minValue = values[i];
counterMinValue++;
}
}
for(i = 0; i < values.length; i++){
if(values[i] > maxValue){
maxValue = values[i];
counterMaxValue++;
}
}
System.out.printf("The min value of this array is%2d and is repeated%2d times(s)", minValue, counterMinValue);
System.out.printf("\nThe max value of this array is %2d and is repeated %2d time(s)", maxValue, counterMaxValue);
Here is the output:
The min value of this array is 1 and is repeated 2 times(s)
The max value of this array is 222 and is repeated 0 time(s)
I would do something like:
for (i = 1; i < values.length; i++) {
if (values[i] == minValue) {
counterMinValue++;
}
else if (values[i] < minValue) {
minValue = values[i];
counterMinValue = 1;
}
if (values[i] == maxValue) {
counterMaxValue++;
}
else if (values[i] > maxValue) {
maxValue = values[i];
counterMaxValue = 1;
}
}
Basically the same for loop that you have, except it checks to see if the current value is equal to the minValue, if it is, add to the counter, otherwise if the value is lower then set minValue to the current value and reset the counter, then do the same for the max value. I placed this in one for-loop since there is no point in iterating through the same list twice (with bigger sets of data that would greatly impact performance). I'm defaulting the counter to 1 so that you count the current element in the array and not just every element equal to it after.
Likewise, you'll probably want:
int counterMinValue = 1;
int counterMaxValue = 1;
EDIT:
In the case of your example where the largest (could also be smallest) value is the first in the array it gets counted twice due to this section:
if (values[i] == maxValue) {
counterMaxValue++;
}
To correct this you can change the for loop to start at 1 (since you already set the min and max value to the first item in the array you don't need to compare it to itself: for (i = 1; ...) which I have corrected in my above code.
int[] values = {222,34,56,222,45,1,3,222,56,10,15,56,1,222,12,23,1,222};
int minValue = values[0];
int maxValue = values[0];
int counterMinValue = 0;
int counterMaxValue = 0;
int i;
for(i = 0; i < values.length; i++){
if (values[i] == minValue) {
counterMinValue++;
}
else if (values[i] < minValue){
minValue = values[i];
}
}
for(i = 0; i < values.length; i++) {
if (values[i] > maxValue) {
maxValue = values[i];
} else if (values[i] == maxValue) {
counterMaxValue++;
}
}
System.out.printf("The min value of this array is%2d and is repeated%2d times(s)", minValue, counterMinValue);
System.out.printf("\nThe max value of this array is %2d and is repeated %2d time(s)", maxValue, counterMaxValue);
}
I got these results:
The min value of this array is 1 and is repeated 3 times(s)
The max value of this array is 222 and is repeated 5 time(s)
I am writing 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)
My code is working, but I'm getting the output wrong. Instead of numbers I am getting some weird output with letters and numbers. How can I fix it? Thanks!
My code
import java.util.Scanner;
public class homework1a {
public static int[] locateLargest(double[][] a)
{
int total = 0;
int maxRow = 0;
int maxColumn = 0;
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
maxRow = i;
maxColumn = j;
}
}
int[] largest = new int[2];
largest[0] = maxRow;
largest[1] = maxColumn;
return largest;
}
public static void main(String[] args)
{
//Create Scanner
Scanner input = new Scanner(System.in);
double b = 0;
//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();
}
}
System.out.println("The location of the largest element is at "+ locateLargest(a));
}
}
Your method locateLargest() returns an int-array, which you are implicitly converting to string while printing it.
I think you want to display the row and cell numbers inside the array:
int[] largest = locateLargest(a);
System.out.println(String.format("The location of the largest element is at %d,%d", largest[0], largest[1]));
locateLargest(a) returns an int[2]. Arrays cannot be converted to strings natively, so the default toString() implementation is invoked on the array. The returned string representation does not contain the array elements.
This question might help you to print a helpful representation of the array. You might also want to print both values independently, not the array as a whole, e.g. like this:
int[] pos = locateLargest(a);
System.out.println("The location of the largest element is at " + pos[0] + ":" + pos[1]);
To print Arrays use Arrays.toString(array) output will be like [x,y]
System.out.println("The location of the largest element is at "+ Arrays.toString(locateLargest(a)));
Your method locateLargest returns an int[] which will not be printed out nicely.
If you want to keep the signature of locateLargest as it is, you could change your code in main like this:
int[] positionOfLargest = locateLargest(a);
System.out.println("The location of the largest element is at " +
positionOfLargest[0] + "/" + positionOfLargest[1]);
This stores the result in positionOfLargest and then prints out x/y coordinates the way you want them.
Hey for finding largest you can have your method like this.
public static int[] locateLargest(double[][] a)
{
int maxValue = 0;
int maxRow = 0;
int maxColumn = 0;
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
If(a[i][j] > maxValue)
{
maxValue = a[i][j] ;
maxRow = i;
maxColumn = j;
}
}
}
int[] largest = new int[2];
largest[0] = maxRow;
largest[1] = maxColumn;
return largest;
}
u should edit your locateLargest as this:
public static int[] locateLargest(double[][] a)
{
//may be ur array is contain negative
//so u can not use zero as MAX it's better to use first array element
int MAX = a[0][0];
int maxRow = 0;
int maxColumn = 0;
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
if(MAx < a[i][j]){
maxRow = i;
maxColumn = j;
}
}
}
int[] largest = new int[2];
largest[0] = maxRow;
largest[1] = maxColumn;
String result="location of largest num =a["+maxRow+"]["+maxColumn+"]";
return largest;
}
So here's my problem. I have to write a program that will fill array with random numbers(and it's ok), then it's necessary to print only even index numbers or only odd value numbers(j). Tried like this but when i put if statement and it shows every even number (index and value-the second in array) so it wrong. What should i do so?
import java.util.Random;
public class Array {
public static void main(String[] args)
{
int rows = 5;
int colu = 2;
Random r = new Random();
int [][] array = new int [rows][colu];
for(int row = 0; row < array.length; row++)
{
for(int col = 0; col < array[row].length; col++)
{
array[row][col] = r.nextInt(10);
}
}
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
if(array[i][j]%2 == 0){
System.out.print(array[i][j] + " ");
}
}
}
System.out.println();
}
}
Thanks
I'm going to take a stab at this but I'm not sure if I quite understand yet.
int array[][] = new int[row][col];
// ... populate the array with random numbers, works fine...
// Let's traverse the first column.
for (int i = 0; i < row; i++) {
int value = array[i][0]; // col 0 means first column
if (value % 2 == 0) {
// ...
}
}
// Let's traverse the second column.
for (int i = 0; i < row; i++) {
int value = array[i][1]; // col 1 means second column
// ...
}
Is this what you mean? If it is, do you see the pattern and how you could generalize this and make the code a bit smaller?
Just implement this formula in your "if" statement :
(Number × 2 )/4 ==0. You will always get even numbers. You can handle the rest :D