find row of matrix with most numbers < 10 method
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, g开发者_运维百科o 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.
精彩评论