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.
Related
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 .
I was wondering how to get the mode of a 2d array in java. What are some different ways I could approach the problem? So far here is my code for the method. EDIT: Also, i forgot to mention that the array has to be positive and single digit numbers so numbers from 0-9 inclusive.
public static int getMostRepeatedNumber(int[][] array) {
int theMode = 0;
if(array.length < 0){
return -1;
}
for(int row = 0; row <array.length;row++){
for(int col = 0; col <array[0].length; col++){
int temp = array[row][col];
}
}
return theMode;
}
Because elements in array are all single digit (from 0 to 9), so we can count and store the frequency of each value easily using an array int[]freq with length 10.
int[]freq = new int[10];
for(int[] row : array){
for(int val : row)
freq[val]++;
}
int mode = 0;
for(int i = 1; i < 10; i++)
if(freq[i] > freq[mode])
mode = i;
return mode;
Since you are only dealing with integers from 0 through 9, the easiest approach is to build a frequency table and then scan for the largest value:
public static int getMostRepeatedNumber(int[][] array) {
if(array == null){
return -1;
}
// build frequency table
int[] frequencies = new int[10]; // all zero
for(int [] row : array){
for(int val : row){
frequencies[val]++;
}
}
// scan for the largest value
int largest = 0;
int mode = -1;
for (int i = 0; i < 10; ++i) {
if (frequencies[i] > largest) {
largest = frequencies[i];
mode = i;
}
}
return mode;
}
How can I find the smallest value in a int array without changing the array order?
code snippet:
int[] tenIntArray = new int [10];
int i, userIn;
Scanner KyBdIn = new Scanner(System.in);
System.out.println("Please enter 10 integer numbers ");
for(i = 0; i < tenIntArray.length; i++){
System.out.println("Please enter integer " + i);
userIn = KyBdIn.nextInt();
tenIntArray[i] = userIn;
}
I am not sure how I can find the smallest array value in the tenIntArray and display the position
For example the array holds - [50, 8, 2, 3, 1, 9, 8, 7 ,54, 10]
The output should say "The smallest value is 1 at position 5 in array"
This figure should be helpful :
Then to answer your question, what would you do on paper ?
Create and initialize the min value at tenIntArray[0]
Create a variable to hold the index of the min value in the array and initialize it to 0 (because we said in 1. to initialize the min at tenIntArray[0])
Loop through the elements of your array
If you find an element inferior than the current min, update the minimum value with this element and update the index with the corresponding index of this element
You're done
Writing the algorithm should be straightforward now.
Try this:
//Let arr be your array of integers
if (arr.length == 0)
return;
int small = arr[0];
int index = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] < small) {
small = arr[i];
index = i;
}
}
Using Java 8 Streams you can create a Binary operator which compares two integers and returns smallest among them.
Let arr is your array
int[] arr = new int[]{54,234,1,45,14,54};
int small = Arrays.stream(arr).reduce((x, y) -> x < y ? x : y).getAsInt();
The method I am proposing will find both min and max.
public static void main(String[] args) {
findMinMax(new int[] {10,40,50,20,69,37});
}
public static void findMinMax(int[] array) {
if (array == null || array.length < 1)
return;
int min = array[0];
int max = array[0];
for (int i = 1; i <= array.length - 1; i++) {
if (max < array[i]) {
max = array[i];
}
if (min > array[i]) {
min = array[i];
}
}
System.out.println("min: " + min + "\nmax: " + max);
}
Obviously this is not going to one of the most optimized solution but it will work for you. It uses simple comparison to track min and max values. Output is:
min: 10
max: 69
int[] input = {12,9,33,14,5,4};
int max = 0;
int index = 0;
int indexOne = 0;
int min = input[0];
for(int i = 0;i<input.length;i++)
{
if(max<input[i])
{
max = input[i];
indexOne = i;
}
if(min>input[i])
{
min = input[i];
index = i;
}
}
System.out.println(max);
System.out.println(indexOne);
System.out.println(min);
System.out.println(index);
Here is the function
public int getIndexOfMin(ArrayList<Integer> arr){
int minVal = arr.get(0); // take first as minVal
int indexOfMin = -1; //returns -1 if all elements are equal
for (int i = 0; i < arr.size(); i++) {
//if current is less then minVal
if(arr.get(i) < minVal ){
minVal = arr.get(i); // put it in minVal
indexOfMin = i; // put index of current min
}
}
return indexOfMin;
}
the first index of a array is zero. not one.
for(i = 0; i < tenIntArray.length; i++)
so correct this.
the code that you asked is :
int small = Integer.MAX_VALUE;
int i = 0;
int index = 0;
for(int j : tenIntArray){
if(j < small){
small = j;
i++;
index = i;
}
}
System.out.print("The smallest value is"+small+"at position"+ index +"in array");
I'm just practicing some MIT java assignments. But, I'm not sure how to find the second largest number. http://ocw.csail.mit.edu/f/13
public class Marathon {
public static void main(String[] arguments) {
String[] names = { "Elena", "Thomas", "Hamilton", "Suzie", "Phil",
"Matt", "Alex", "Emma", "John", "James", "Jane", "Emily",
"Daniel", "Neda", "Aaron", "Kate" };
int[] times = { 341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412,
393, 299, 343, 317, 265 };
for (int i = 0; i < names.length; i++) {
System.out.println(names[i] + ": " + times[i]);
}
System.out.println();
System.out.println("Largest Timing " + Largest(times));
System.out.println();
}
public static int Largest(int[] times) {
int maxValue = times[0];
for (int i = 1; i < times.length; i++) {
if (times[i] > maxValue) {
maxValue = times[i];
}
}
return maxValue;
}
}
Instead of resorting to sorting the array, you can simply do the following:
Keep a largestValue and a secondLargestValue
Loop through the entire array once, for each element:
Check to see if the current element is greater than largestValue:
If so, assign largestValue to secondLargestValue, then assign the current element to largestValue (think of it as shifting everything down by 1)
If not, check to see if the current element is greater than secondLargestValue
If so, assign the current element to secondLargestValue
If not, do nothing.
O(n) run time
O(1) space requirement
Sorting the array simply to find an order statistics is too wasteful. You can find the second largest element by following an algorithm that resembles the one that you already have, with an additional variable representing the second largest number.
Currently, the next element could be larger than the max or equal to/smaller than the max, hence a single if is sufficient:
if (times[i] > maxValue) {
maxValue = times[i];
}
With two variables to consider, the next element could be
Greater than the max - the max becomes second largest, and the next element becomes the max
Smaller than the max but greater than the second largest - the next element becomes second largest.
A special care must be taken about the initial state. Look at the first two items, and assign the larger one to the max and the smaller to the second largest; start looping at the element number three, if there is one.
Here is how you can code it:
if (times[i] > maxValue) {
secondLargest = maxValue;
maxValue = times[i];
} else if (times[i] > secondLargest) {
secondLargest = times[i];
}
Generally speaking:
Have two values -- "largest" and "notQuite".
Initialize both to -9999 or whatever.
Scan through your list. If the number is larger than "largest", set "largest" to that number. But before you do that, copy the old "largest" value to "notQuite".
If, on the other hand, the number is smaller than "largest" but is larger than "notQuite", set "notQuite" to that number.
When you're done examining all the numbers, "notQuite" contains the second-largest.
And note that, as you fill in the above numbers, you can also keep a "largestIndex" and "notQuiteIndex" and fill those in with the corresponding array index values, so you can identify the "winning" value. Unfortunately, though, if there are multiple identical "largest" or "secondLargest" values the simple index scheme doesn't work and you need to keep a list of some sort.
private static int secLargest(int[] numbers) {
int maxVal = 0;
int nextMaxVal = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] > maxVal) {
nextMaxVal = maxVal;
maxVal = numbers[i];
}
if (numbers[i] < maxVal) {
nextMaxVal = maxVal;
maxVal = numbers[i];
}
}
return nextMaxVal;
}
private void secondLargest(int arr[]){
int maxOne=arr[0];
int maxTwo=arr[1];
for(int i=0;i<arr.length;i++){
if(arr[i]>maxOne){
maxTwo=maxOne;
maxOne=arr[i];
}else if (arr[i]>maxTwo) {
maxTwo=arr[i];
}
}
System.out.println(maxOne);
System.out.println(maxTwo);
}
int largest=time[0];
int secondLargest=largest;
for(int i=0;i<time.length;i++){
if(time[i]>largest){
secondLargest=largest;
largest=time[i];
}
else if(secondLargest<time[i] && time[i]<largest || secondLargest>=largest)
secondLargest=time[i];
}
return secondLargest;
public void findMax(int a[]) {
int large = Integer.MIN_VALUE;
int secondLarge = Integer.MIN_VALUE;
for (int i = 0; i < a.length; i++) {
if (large < a[i]) {
secondLarge = large;
large = a[i];
} else if (a[i] > secondLarge) {
if (a[i] != large) {
secondLarge = a[i];
}
}
}
System.out.println("Large number " + large + " Second Large number " + secondLarge);
}
The above code has been tested with integer arrays having duplicate entries, negative values. Largest number and second largest number are retrieved in one pass. This code only fails if array only contains multiple copy of same number like {8,8,8,8} or having only one number.
It will also extract second largest number if largest number occours two times as well as in a single for loop.
import java.util.*;
public class SecondLargestInArray
{
public static void main(String[] args)
{
int arr[] = {99,14,46,47,86,92,52,48,36,66,85,92};
int largest = arr[0];
int secondLargest = arr[0];
System.out.println("The given array is:" );
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i]+"\t");
}
for (int i = 0; i < arr.length; i++)
{
if (arr[i] > largest)
{
secondLargest = largest;
largest = arr[i];
}
else if((arr[i]<largest && arr[i]>secondLargest) || largest==secondLargest)
{
secondLargest=arr[i];
}
}
System.out.println("\nLargest number is:" + largest);
System.out.println("\nSecond largest number is:" + secondLargest);
}
}
Find the second largest element in the given array:
public static void findSecondMax(){
int[] arr = {3, 2, 20, 4, 1, 9, 6, 3, 8};
int max = 0;
int secondMax = 0;
for(int i =0; i< arr.length; i++) {
if(max < arr[i]) max = arr[i];
if((max > arr[i]) && (secondMax < arr[i])) secondMax = arr[i];
}
System.out.println(secondMax);
}
public static void main (String args[]) {
int [] arr = {1,4,3,10,4,8,20,5,33};
int largest = 0;
int secondLargest = 0;
for (int x : arr) {
if (x > largest) {
secondLargest = largest;
largest = x;
}
else if (x > secondLargest) {
secondLargest = x;
}
}
System.out.println("secondLargest:"+secondLargest);
}
Updated : Changed to Java.
class Main {
public static void main(String[] args) {
int a = Integer.MIN_VALUE;
int b = Integer.MIN_VALUE;
int[] arr = {44,6,43,8,9,-10,4,15,3,-30,23};
for(int i=0; i < arr.length; i++){
if( arr[i] > a || arr[i] > b ){
if( a < b ) {
a = arr[i];
} else {
b = arr[i];
}
}
}
int secondLargest = a < b ? a : b;
System.out.println(secondLargest);
}
}
I can find numbers<10 with if loop and store them with count++; But that is all.
I would like to see the algorithm in any lang (I can do some C++,java), so I can use it.
Go through each row and record a count of numbers less than 10.
Store that aside, go to next row, do same thing, compare, throw out lower one.
public int findMostLowNumbersRow(double[][] arr, double threshold) {
int maxLowNumbers = 0;
int rowNum = -1;
for (int i = 0; i < arr.length; ++i) {
int count = countLowNumbers(arr[i], threshold);
if (count > maxLowNumbers) {
rowNum = i;
maxLowNumbers = count;
}
}
return rowNum;
}
public int countLowNumbers(double[] row, double threshold) {
int count = 0;
for (double number : row) {
if (number < threshold) {
++count;
}
}
return count;
}
call with
findMostLowNumbersRow(yourMatrix, 10.0);
the function returns the number of the row that contains the most numbers less than 10.
int max_count = 0;
for (int i=0; i<MATRIX_SIZE; i++) {
int tmp_count = 0;
for (int j=0; j<MATRIX_SIZE; j++) {
if (matrix[i][j] > 10) tmp_count++;
}
if (tmp_count > max_count) max_count = tmp_count;
}
// use max_count
It's something like the following:
import static java.lang.System.out;
public class Zeug {
public static void main(String[] args) {
final int SIZE = 10;
int[][] matrix = new int[SIZE][SIZE];
for(int i=0;i<matrix.length;i++) {
for(int j=0;j<matrix.length;j++) {
matrix[i][j] = (int) Math.round(Math.random() * 23);
}
}
int max=0;
for(int i=0;i<matrix.length;i++) {
int count=0;
for(int j=0;j<matrix.length;j++) {
if(matrix[i][j]<10) {
count++;
}
}
max = Math.max(count, max);
}
out.println(max);
}
}
Write some pseudo-code and it'll be clearer:
Set the index of the lowest row equal to the first one.
Set the max count of values below the threshold to zero.
Loop over all rows.
Set the count of values below the threshold to zero.
Loop over all the columns in the current row and count the number of values below the threshold.
If the count of values below the current threshold is greater than the max count, set the index of the lowest row equal to the current one.
You'll need two nested loops and some counters.
Since you said any language, here we go in Ruby
matrix.max { |a,b| a.select{|e|e<10}.size <=> b.select{|e|e<10}.size }
assuming that matrix is an array of arrays.