Counter not working in array of ints - java

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)

Related

How to find the second highest number in an array [duplicate]

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

Understanding the logic of a increase max element by 1 method

The duty of this method is to increment or add 1 to, the largest element in the array arr. If the same largest element is present more than once in the array, the last occurrence should be incremented. ("Last" means the one in the row with the largest subscript, and the one with the largest column subscript if there is more than one occurrence of the largest element in that row.) The method should not do any unnecessary work or computation. Note that the array's rows may have different numbers of elements.
Solution:
public static void incrMax(int[][] arr) {
int maxRow = 0;
int maxCol = 0;
boolean found = false;
for(int row = 0; row < arr.length; row++) {
for(int col = 0; col < arr[row].length; col++) {
if(!found || arr[row][col] >= arr[maxRow][maxCol] {
maxRow = row;
maxCol = col;
found = true;
}
if(found) {
arr[maxRow][maxCol] += 1;
}
}
}
}
What I understand is that we would want to create two int's to store the maximum elements for horizontal rows and vertical columns. In order to seek those values out we need to loop the 2D-array. I am particularly confused by nested for-loops and 2d arrays. And the line:
if(!found || arr[row][col] >= arr[maxRow][maxCol]
Can someone please walk through the logic of this code?
Thank you
void increment(int[][] mat) {
//increment the max of every row by one
for (int i = 0; i < mat.length; i++) {
int maxRow = 0, maxIndex = -1;
for (int j = 0; j < mat[i].length; j++) {
if (maxRow <= mat[i][j]) { // to allow multiple occurences of the same value i used <=
maxRow = mat[i][j];
maxIndex = j;
}
}
//we check if a max is found
if (maxIndex != -1) {
mat[i][maxIndex]++;
}
}
}
this will do the work you are asking for

assigning array index number to variable in for loop java

First Day with Java and I am getting an error in the for loop when I add the array index to the variable minIndex. I'm not sure exactly what to put in as the value in the (). I tried i but that didn't work and with my lack of knowledge in java, I am unsure. May I have some guidance please.
public static int minPosition(double[] list) {
double leastNum;
leastNum = list[0];
// leastNum starts at first number in array
int minIndex;
minIndex = 1;
// minIndex starts at 1 as if first number in Array happens to be the lowest, its index will be one
for ( int i = 0; i < list.length; i++)
if (list[i] < leastNum)
leastNum = list[i];
minIndex = list.indexof(i);
return minIndex;
i is the index.
change
minIndex = list.indexof(i);
to
minIndex = i;
You should also change
minIndex = 1;
to
minIndex = 0;
since the first index of an array is 0.
As commented, you have some missing curly braces. Here's the full code :
public static int minPosition(double[] list) {
double leastNum = list[0];
// leastNum starts at first number in array
int minIndex = 0;
// minIndex starts at 0 as if first number in Array happens to be the lowest, its index will be one
for ( int i = 0; i < list.length; i++) // you can also start with i = 1
// since you initialize leastNum
// with the first element
if (list[i] < leastNum) {
leastNum = list[i];
minIndex = i;
}
return minIndex;
}
There is no such method in primitive array indexof():
public static int minPosition(double[] list) {
int minIndex = 0;//replaced
double leastNum = list[minIndex];//replaced
for ( int i = 1; i < list.length; i++) {//braces recommended, also `i` starts with `1`
if (list[i] < leastNum) {//braces required, since you have more than one line to execute
leastNum = list[i];
minIndex = i;//replaced
}
}
return minIndex;
}

Average of integers not counting 0 as a number

I am trying to find the average of an array of numbers, whose value is taken from a JTextfield. My problem is that zero is counted in with the average. How is it possible to find the average but not include zero.
int[] numbers = new int[]{Integer.parseInt(math1.getText()),0 };
int sum =0;
if(numbers != 0){
for(int i=0; i < numbers.length ; i++)
sum = sum + numbers[i];
//calculate average value
int average = sum / numbers.length;
totdata2.setText(Integer.toString(average));
}
Don't count the numbers whose values are zero in the denominator when calculating the average:
int tally = 0;
for ( int i = 0; i < numbers.length; i++ ){
if (numbers[i] != 0 ){
sum = sum + numbers[i];
tally++;
}
}
int average = sum / tally;
I am not sure what you are trying to accomplish with the following syntax:
if(numbers != 0)
int[] numbers // numbers is an array.
You cannot do if(numbers != 0).
Inside the for loop you should check that the actual integer number is not zero.
int counter=0; // counts not zero elements
for(int i=0; i < numbers.length ; i++)
if(numbers[i]!=0){
sum = sum + numbers[i]; // numbers[i] is an int (a number)
counter ++;
}
Second: You should not do this:
int average = sum / numbers.length;
In the above code you are counting the zeros you are dividing for the arrays original length.
You should keep a counter of elements not zero and divide by that counter.
Check the updated code above.
It should be:
int average = sum / counter;
I think it will work
int countOfZero = 0 ;
for(int i=0; i < numbers.length ; i++)
{
sum = sum + numbers[i];
if(numbers[i]==0)
{
countOfZero++;
}
}
int average = sum / (numbers.length-countOfZero);

Finding the largest number in a column using 2D arrays

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

Categories