Static methods and Jagged Arrays - java

I am trying to write a static method that returns an integer, takes a 2-dimensional array of integers as a parameter and return the index of the row in the 2-d array (jagged arrays) that has the largest sum of all its elements. Something went wrong along the line and im still trying to figure out. Help please?
Here is the code:
public static int findMaxRow(int[][] maxRows){
newI= 0;
newJ= 0;
for(int i=0; i< maxRows.length; i++) {
newI += i;
for(int j=0; j< maxRows.length; j++) {
newJ += j;
`` if( newI > newJ){
return newI;
else {
}
}
}
}

You never define the type for newI or newJ, that can be fixed by preceding their declaration with their intended type (i.e int). You also have two " ` " before your if statement, and your missing a closing bracket " } " before your else statement. But those are just syntactical errors. Once you fix those errors you're going to notice that your method is not returning the desired results.
Looking at your code, specifically the for loops.
for(int i=0; i< maxRows.length; i++) {
newI += i;
for(int j=0; j< maxRows.length; j++) {
newJ += j;
// other stuff
}
}
Let's say that maxRows.length equals 3. That means the outer loop is going to run from 0 to 2, so newI will equal 3. Meanwhile for each iteration the outer loop makes, the inner loop iterates 3 times. So newJ will end up equalling 9. Which is not the right way to go about summing the elements of an array. A better way to go about it, is to iterate over the arrays in the outer loop and sum the elements in the inner loop, then make a comparison completing the outer loop. Like so:
int largestRow = 0;
int largestSum = 0;
int sum;
// iterate over each array
for(int i=0; i< maxRows.length; i++) {
sum = 0; // set and reset sum to zero
// iterate over each element
for(int j=0; j< maxRows[i].length; j++) {
sum += maxRows[i][j];
}
// if sum is > the previous largest sum then set largest
// sum to this new sum and record which row
if(sum > largestSum) {
largestRow = i;
largestSum = sum;
}
}
return largestRow;
Here is an example of what you're trying to accomplish.
public class RowSums {
public static void main(String[] args) {
int[][] test = { {1, 5, 7, 0, 9} , {2, 4, 5, 6, 7} , {9, 2, 0, 12, 8, 3} };
System.out.println(printRows(test));
System.out.println("The row with the largest sum is row "
+ findMaxRow(test));
}
public static int findMaxRow(int[][] maxRows){
int largestRow = 0;
int largestSum = 0;
int sum;
// iterate over each array
for(int i=0; i< maxRows.length; i++) {
sum = 0; // set and reset sum to zero
// iterate over each element
for(int j=0; j< maxRows[i].length; j++) {
sum += maxRows[i][j];
}
// if sum is > the previous largest sum then set largest
// sum to this new sum and record which row
if(sum > largestSum) {
largestRow = i;
largestSum = sum;
}
}
return largestRow;
}
public static String printRows(int[][] rows) {
StringBuilder s = new StringBuilder("Rows and their sums:\n");
int sum;
for(int x = 0; x < rows.length; x++) {
s.append("Row [" + x + "] = [ ");
sum = 0;
for(int y = 0; y < rows[x].length; y++) {
s.append(rows[x][y] + " ");
sum += rows[x][y];
}
s.append("]\n");
s.append("Row [" + x + "]'s sum is " + sum + "\n");
}
return s.toString();
}
}
Output:
Rows and their sums:
Row [0] = [ 1 5 7 0 9 ]
Row [0]'s sum is 22
Row [1] = [ 2 4 5 6 7 ]
Row [1]'s sum is 24
Row [2] = [ 9 2 0 12 8 3 ]
Row [2]'s sum is 34
The row with the largest sum is row 2

Modifying your program, the following example will return the index of the row that has the largest sum of elements in it.
Let us suppose our array to be passed is:
int [][] maxRows = {{1,2,3}, {1,2,3,4,5}, {9,9,9,9}, {1,2}};
passing this array in the method
public static int findMaxRow(int[][] maxRows){
int sum = Integer.MIN_VALUE;
int biggestIndex= 0;
for(int i = 0; i<maxRows.length; i++){
int temp = 0;
for(int ir : maxRows[i]){
temp+=ir;
}
if(temp>sum){
sum = temp;
biggestIndex = i;
}
}
return biggestIndex;
}
The above program will return the index of the inner array which has the largest sum of elements, in above case, it will return 2 .

Related

How to find sum of elements above secondary diagonal in matrix?

I tried searching for the solution to this problem for a while now and couldn't find anything. How do I sum the elements above the secondary diagonal in a matrix (just with loops, nothing fancy) in Java?
This is what I tried:
public static void Page106Ex3$H(int[][] mat) {
int sum = 0;
for (int i = 1; i < mat.length; i++) {
for (int j = i-1; j >= 0; j--) {
sum += mat[i][j];
}
}
System.out.println("Sum: " + sum);
}
For square matrix of any order you can use this code,
This code has answer for both primary and secondary diagonals and are separated by comments in the code
private static void calcDiagonalSumMatrix(int[][] mat) {
int sum = 0, leftDiagonal = 0, rightDiagonal = mat[0].length - 1;
//This loop is for primary diagonal
for (int[] ints : mat) {
sum += ints[leftDiagonal++];
}
//This loop is for secondary diagonal
for(int [] intArray: mat) {
sum += intArray[rightDiagonal--];
}
//This loop is what you have to use
for(int x = 0; x < matrix.length; x++) {
rightDiagonal--;
for(int y = rightDiagonal; y >=0; y--) {
sum += mat[x][y];
}
}
System.out.println(sum);
}
Explanation :
Three integers variables are declared one to calculate sum then the leftDiagonal is to calculate the index of top left to bottom right diagonal and the rightDiagonal is used as index of top right to bottom left diagonal.
Then using the enhanced for loops or foreach loops, calculate the sum of the leftDiagonal and that same of right diagonal.
In each for loop for left diagonal the loop first picks the first set of array then the leftDiagonal variable which acts as the index will start from 0 and increase by one for each loops and the same goes for the rightDiagonal except the right diagonal starts from the order - 1 which is the index of the top right element.
Then the third loop actually has two loop, the outer loop will be taking the int array elements then the innermost loop will loop through the elements that the first loop took and adds up the elements from each int[] set excluding the secondary diagonal elements.
If the elements on the secondary are not included, the number of columns in the nested loop should be decremented with indexes starting from 0.
public static int sumOver2ndDiagonal(int[][] arr) {
int sum = 0;
for (int i = 0, n = arr.length - 1; i < n; i++) {
for (int j = 0, m = arr[i].length - 1 - i; j < m; j++) {
sum += arr[i][j];
}
}
return sum;
}
Test:
System.out.println(sumOver2ndDiagonal(
new int[][]{
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12},
{13, 14, 15, 16}
}
));
// 1 + 2 + 3 + 5 + 6 + 9
// -> 26
The secondary diagonal element in row i is present at (mat.length-i-1). In a row all the elements before the element present at secondary diagonal comes above the secondary diagonal we need to add them.
The below solution is considering indexing start from 0.
public static void Page106Ex3$H(int[][] mat) {
int sum = 0;
int n = mat.length;
for (int i = 0; i < n; i++) {
int j = n - i - 2; // index of element just before the
// secondary diagonal element in row i
while(j >= 0){
sum += mat[i][j];
j--;
}
}
System.out.println("Sum: " + sum);
}

How to display the row with the max value?

I am trying to display the current row that has the max value. So far I have the max value by adding the elements in the array but I am trying to display the specific row it is in. For example:
{4,4,4}
{5,5,5}
:25 is the biggest val possible going by row to row
The max value here would be 15 as my code looks and finds the maximum addition in each row in a 2D array. How would I get my code to display the row {5,5,5} as well as the actual maximum addition that is possible with the given rows.
Here is my current code:
public class review{
int largestRowsSum(int[][] arr){
int sum = 0;
int largest = 0;
for (int i = 0; i < arr.length; i++){
for(int j = 0; j < arr[i].length; j++){
sum += arr[i][j];
}
if(sum > largest){
largest = sum;
}
sum = 0;
}
return largest;
}
}
First, your current method could be simplified and static. Like,
static int largestRowsSum(int[][] arr) {
int sum = Arrays.stream(arr[0]).sum();
for (int i = 1; i < arr.length; i++) {
sum = Math.max(Arrays.stream(arr[i]).sum(), sum);
}
return sum;
}
Second, you could invoke that method and then iterate the array to find the index of the array with the matching sum. Like,
static int largestRowIndex(int[][] arr) {
int target = largestRowsSum(arr);
for (int i = 0; i < arr.length; i++) {
if (Arrays.stream(arr[i]).sum() == target) {
return i;
}
}
return -1;
}
Finally, call that method and use the returned index to display the row and correct sum. Like,
public static void main(String[] args) {
int[][] arr = { { 4, 4, 4 }, { 5, 5, 5 } };
int n = largestRowIndex(arr);
System.out.printf("The largest row is %s and the sum is %d.%n",
Arrays.toString(arr[n]), Arrays.stream(arr[n]).sum());
}
Outputs, the row {5,5,5} as well as the actual maximum, as requested
The largest row is [5, 5, 5] and the sum is 15.

Getting the most "popular" number from array

I need for homework to get the most "popular" number in an array (the number in the highest frequency), and if there are several numbers with the same number of shows, get some number randomly.
After more then three hours of trying, and either searching the web, this is what I got:
public int getPopularNumber(){
int count = 1, tempCount;
int popular = array[0];
int temp = 0;
for ( int i = 0; i < (array.length - 1); i++ ){
if ( _buses[i] != null )
temp = array[i];
tempCount = 0;
for ( int j = 1; j < _buses.length; j++ ){
if ( array[j] != null && temp == array[j] )
tempCount++;
}
if ( tempCount > count ){
popular = temp;
count = tempCount;
}
}
return popular;
}
This code work, but don't take into account an important case- if there is more than one number with the same count of shows. Then it just get the first one.
for example: int[]a = {1, 2, 3, 4, 4, ,5 ,4 ,5 ,5}; The code will grab 4 since it shown first, and it's not random as it should be.
Another thing- since it's homework I can't use ArrayList/maps and stuff that we still didn't learn.
Any help would be appreciated.
Since they didn't give you any time complexity boundary, you can "brute force" the problem by scanning the the array N^2 times. (disclaimer, this is the most intuitive way of doing it, not the fastest or the most efficient in terms of memory and cpu).
Here is some psuedo-code:
Create another array with the same size as the original array, this will be the "occurrence array"
Zero its elements
For each index i in the original array, iterate the original array, and increment the element in the occurrence array at i each time the scan finds duplicates of the value stored in i in the original array.
Find the maximum in the occurrence array
Return the value stored in that index in the original array
This way you mimic the use of maps with just another array.
If you are not allowed to use collection then you can try below code :
public int getPopularNumber(){
int inputArr[] = {1, 2, 3, 4, 4, 5 ,4 ,5 ,5}; // given input array
int[] tempArr = new int[inputArr.length];
int[] maxValArr = new int[inputArr.length];
// tempArr will have number as index and count as no of occurrence
for( int i = 0 ; i < inputArr.length ; i++){
tempArr[inputArr[i]]++;
}
int maValue = 0;
// find out max count of occurrence (in this case 3 for value 4 and 5)
for( int j = 0 ; j < tempArr.length ; j++){
maValue = Math.max(maValue, tempArr[j]);
}
int l =0;
// maxValArr contains all value having maximum occurrence (in this case 4 and 5)
for( int k = 0 ; k < tempArr.length ; k++){
if(tempArr[k] == maValue){
maxValArr[l] = k;
l++;
}
}
return maxValArr[(int)(Math.random() * getArraySize(maxValArr))];
}
private int getArraySize(int[] arr) {
int size = 0;
for( int i =0; i < arr.length ; i++){
if(arr[i] == 0){
break;
}
size++;
}
return size;
}
that's hard as hell :D
After some trying, I guess I have it (If there will be 2 numbers with same frequency, it will return first found):
int mostPopNumber =0;
int tmpLastCount =0;
for (int i = 0; i < array.length-1; i++) {
int tmpActual = array[i];
int tmpCount=0;
for (int j = 0; j < array.length; j++) {
if(tmpActual == array[j]){
tmpCount++;
}
}
// >= for the last one
if(tmpCount > tmpLastCount){
tmpLastCount = tmpCount;
mostPopNumber = tmpActual;
}
}
return mostPopNumber;
--
Hah your code give me idea- you cant just remember last most popular number, btw I've found it solved there Find the most popular element in int[] array
:)
EDIT- after many, and many years :D, that works well :)
I've used 2D int and Integer array - you can also use just int array, but you will have to make more length array and copy actual values, Integer has default value null, so that's faster
Enjoy
public static void main(String[] args) {
//income array
int[] array= {1,1,1,1,50,10,20,20,2,2,2,2,20,20};
//associated unique numbers with frequency
int[][] uniQFreqArr = getUniqValues(array);
//print uniq numbers with it's frequency
for (int i = 0; i < uniQFreqArr.length; i++) {
System.out.println("Number: " + uniQFreqArr[i][0] + " found : " + uniQFreqArr[i][1]);
}
//get just most frequency founded numbers
int[][] maxFreqArray = getMaxFreqArray(uniQFreqArr);
//print just most frequency founded numbers
System.out.println("Most freq. values");
for (int i = 0; i < maxFreqArray.length; i++) {
System.out.println("Number: " + maxFreqArray[i][0] + " found : " + maxFreqArray[i][1]);
}
//get some of found values and print
int[] result = getRandomResult(maxFreqArray);
System.out.println("Found most frequency number: " + result[0] + " with count: " + result[1]);
}
//get associated array with unique numbers and it's frequency
static int[][] getUniqValues(int[] inArray){
//first time sort array
Arrays.sort(inArray);
//default value is null, not zero as in int (used bellow)
Integer[][] uniqArr = new Integer[inArray.length][2];
//counter and temp variable
int currUniqNumbers=1;
int actualNum = inArray[currUniqNumbers-1];
uniqArr[currUniqNumbers-1][0]=currUniqNumbers;
uniqArr[currUniqNumbers-1][1]=1;
for (int i = 1; i < inArray.length; i++) {
if(actualNum != inArray[i]){
uniqArr[currUniqNumbers][0]=inArray[i];
uniqArr[currUniqNumbers][1]=1;
actualNum = inArray[i];
currUniqNumbers++;
}else{
uniqArr[currUniqNumbers-1][1]++;
}
}
//get correctly lengthed array
int[][] ret = new int[currUniqNumbers][2];
for (int i = 0; i < uniqArr.length; i++) {
if(uniqArr[i][0] != null){
ret[i][0] = uniqArr[i][0];
ret[i][1] = uniqArr[i][1];
}else{
break;
}
}
return ret;
}
//found and return most frequency numbers
static int[][] getMaxFreqArray(int[][] inArray){
int maxFreq =0;
int foundedMaxValues = 0;
//filter- used sorted array, so you can decision about actual and next value from array
for (int i = 0; i < inArray.length; i++) {
if(inArray[i][1] > maxFreq){
maxFreq = inArray[i][1];
foundedMaxValues=1;
}else if(inArray[i][1] == maxFreq){
foundedMaxValues++;
}
}
//and again copy to correctly lengthed array
int[][] mostFreqArr = new int[foundedMaxValues][2];
int inArr= 0;
for (int i = 0; i < inArray.length; i++) {
if(inArray[i][1] == maxFreq){
mostFreqArr[inArr][0] = inArray[i][0];
mostFreqArr[inArr][1] = inArray[i][1];
inArr++;
}
}
return mostFreqArr;
}
//generate number from interval and get result value and it's frequency
static int[] getRandomResult(int[][] inArray){
int[]ret=new int[2];
int random = new Random().nextInt(inArray.length);
ret[0] = inArray[random][0];
ret[1] = inArray[random][1];
return ret;
}

Can't find five lowest values in an array...max works while min array is not assigned values

I'm very close to completing this, all I need is help on finding the five lowest values from a text file by using arrays. I figured out how to find the five highest values, but my min array to find the lowest values always outputs five 0's.
Output: //obviously dependent on individual text file
Total amount of numbers in text file is 10
Sum is: 1832
1775 14 9 9 7 //max
0 0 0 0 0 //min
Any help is much appreciated!
import java.util.Scanner;
import java.io.*;
public class HW3
{
public static void main(String[] args) throws IOException
{
File f = new File("integers.txt");
Scanner fr = new Scanner(f);
int sum = 0;
int count = 0;
int[] max = new int[5];
int[] min = new int[5];
int temp;
while(fr.hasNextInt())
{
count++;
fr.nextInt();
}
Scanner fr2 = new Scanner(new File("integers.txt"));
int numbers[] = new int[count];
for(int i=0;i<count;i++)
{
numbers[i]=fr2.nextInt(); //fills array with the integers
}
for(int j:numbers)//get sum
{
sum+=j;
}
for (int j=0; j < 5; j++) //finds five highest
{
for (int i=0; i < numbers.length; i++)
{
if (numbers[i] > max[j])
{
temp = numbers[i];
numbers[i] = max[j];
max[j] = temp;
}
}
}
for (int j=0; j < 5; j++) //finds five lowest...array not assigned values
{
for (int i=0; i < numbers.length; i++)
{
if (numbers[i] < min[j])
{
temp = numbers[i];
numbers[i] = min[j];
min[j] = temp;
}
}
}
System.out.println("Total amount of numbers in text file is " + count);
System.out.println("Sum is: " + sum);
System.out.println(max[0] + " " + max[1] + " " + max[2] + " " + max[3] + " " + max[4]);
System.out.println(min[0] + " " + min[1] + " " + min[2] + " " + min[3] + " " + min[4]);
}
}
Your min array will be initialized with zero values. So the values in numbers will always be higher (assuming there are no negatives).
I'd suggest that you initialize min[j] with numbers[0] before the inner loop.
for (int j=0; j < 5; j++) //finds five highest
{
min[j] = numbers[0]; // Add this line
for (int i=0; i < numbers.length; i++)
{
Try debugging your code by entering inside your nested min loop the following line:
System.out.println("the value of numbers[i] is: " + numbers[i]);
so it looks like this:
for (int j=0; j < 5; j++) //finds five lowest...array not assigned values
{
for (int i=0; i < numbers.length; i++)
{
if (numbers[i] < min[j])
{
System.out.println("the value of numbers[i] is: " + numbers[i]);
temp = numbers[i];
numbers[i] = min[j];
min[j] = temp;
}
}
}
You'll notice something interesting. The innermost nested part doesn't even start.
Try putting that line into the nested max loop in its respective location instead... and it will run fine and show the max array values. You are getting zero values for the min array because (other than initial assigning) the innermost part of the nested min loop isn't being started somehow, so it fails to run and searched values do not get assigned to the min array.
The outer nested parts of the min loop run fine if you try debugging them with a similar line. It's this part that won't start and something's wrong with:
if (numbers[i] < min[j])
{
System.out.println("the value of numbers[i] is: " + numbers[i]);
temp = numbers[i];
numbers[i] = min[j];
min[j] = temp;
}
(Update)
In the min loop, numbers[i] from i=0 to i=4 have a value of 0 after completing the max loop.
You only need to add one line and use int i=5 instead of int i=0 inside your min loop:
for (int j=0; j < 5; j++) //finds five lowest...array not assigned values
{
min[j] = max[4]; // added line
for (int i=5; i < numbers.length; i++) // change to int i=5
{
if (numbers[i] < min[j])
{...
As the other answer states, your problem is that you did not take into account the arrays beginning at 0. In Java, it sets default values for that data structure. For primitives, this will normally be 0 or false. However, when you move into data structures, you will have problems with null pointer exceptions if you fail to initialize your objects. For this reason, I would urge you to get into the habit of setting the values in your data structures before you ever use them. This will save you A LOT of debugging time in the future.
If you know the values in advance, you can set them manually with {0,0,0,0,0} notation, or your can initialize using a for loop:
for(int i = 0; i < array.length; i++)
array[i] = init_value;
I would recommend that you also look into trying to consolidate as much as possible. For example, in your code you go through the same data 4 times:
1) read the integers from the file into an integer array
2) sum all of the numbers in the integer array
3) look for max
4) look for min
I'm not sure if you've covered functions yet, but one example of consolidating this might look like:
while(fr2.hasNextInt()){
int i = fr2.nextInt();
sum += i;
checkHighest(i);
checkLowest(i);
}
You then define these functions and put the meat elsewhere. This lets you only worry about the loops in one place.
You have 2 problems.
First was explained by Tom Elliott.
The second problem is that also the max[] array is initialized with 0, and when you search for max values you change the value from max array (which is 0) with the value from the numbers array, so the numbers array becomes filled with 0s.
A quick solve (though not the best) would be to copy the numbers array in a temp array and use that temp when searching for min values.
In case you didn't exactly understood what I said, try to make a print of the numbers array after you found the 5 max values.
Just curious , Cant you just sort it(using quick sort) select top five and bottom five ?
- if you can use sorting I think this should work then
int sum = 0;
int count = 0;
int[] max = {Integer.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE};
int[] min = {Integer.MAX_VALUE,Integer.MAX_VALUE,Integer.MAX_VALUE,Integer.MAX_VALUE,Integer.MAX_VALUE};
int temp;
int visited[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
for (int j : numbers)// get sum
{
sum += j;
}
int tempindex;
for (int j = 0; j < 5; j++) // finds five highest
{
for (int i = 0; i < numbers.length; i++) {
if (visited[i] != 1) {
if (numbers[i] > max[j]) {
max[j] = numbers[i];
tempindex = i;
}
}
}
visited[tempindex] = 1;
}
for (int j = 0; j < 5; j++) // finds five lowest...array not assigned
// values
{
for (int i = 0; i < numbers.length; i++) {
if (visited[i] != 1) {
if (numbers[i] < min[j]) {
min[j] = numbers[i];
tempindex = i;
}
}
}
visited[tempindex] = 1;
}

How to add a certain number in an array of numbers?

I'm currently using this code to add all the numbers in an int array:
int sum = 0;
for (int i = 0; i < array.length; i++)
{
sum += array[i];
}
int total = sum;
For example if I had an array of numbers such as [1, 1, 2, 2, 3, 3, 1] and I only wanted to add all the 1's in the array, how would I go about doing so?
Just check if each array member is equal to 1 :
int sum = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i]==1)
sum += array[i];
}
you need to compare that number with array index i;
int sum = 0;
int num = 0;// this number will compare with array index
for (int i = 0; i < array.length; i++)
{
if (array[i]==num)
sum += array[i];
}
int total = sum;
It really depends on how you choose those numbers. For example, if the number you chose has certain property(such as adding all 1,2,3 or adding all even number), you can use if statement to get the number. If the choice is depends on the certain property of index of the array, (add the No.1, No.2, No.3, No.5, No.8, No.13 ...) you can add another loop inside the "for" loop.
Inside loop filter it as
if (yourNumberToCompare==array[i]) {
sum += array[i];
}
Where yourNumberToCompare is the number that you want to compare.
Final code will be
int sum = 0;
int yourNumberToCompare = 1; // this will be as per your choice
for (int i = 0; i < array.length; i++) {
if (yourNumberToCompare==array[i]) {// this is the filter I was talking about
sum += array[i];
}
}
int total = sum;
Java 8 version:
int[] integers = new int[]{1,2,3,4,5,6,7,8,9,1};
int sum = Arrays.stream(integers).filter(x -> x == 1).sum();

Categories