Ranking array Java - java

I am trying to rank my array in my assignment but I don't understand how to do it. Can someone help me? Thank you in advance
I added an image of the full assignment instructions.
Here is an image of my assignment:
And here is my code:
public class Assignment_3_Question_1 {
// Here, I predefined my data set.
static int referenceScore[][]={{39,40,17,35,42,6},{40,41,27,41,42,36},{42,40,26,42,42,35}};
static int finalScore[][]={{39,40,17,35,42,6},{40,41,27,41,42,36},{42,40,26,42,42,35}};
static int scoreAmongOthers[][]=new int[3][6];
static int max;
static int rank = 1;
static int count = 0;
static int total = 0;
public static void main(String[] args) {
for (int k = 0; k < 10; k++){
max = referenceScore[0][0];
for (int team = 0; team < 3; team++){
for (int position = 0; position < 6; position++){
if (max < referenceScore[team][position]){
max = referenceScore[team][position];
}
}
}
for (int x = 0; x < 3; x++){
for(int y = 0; y < 6; y++){
if(referenceScore[x][y]==max){
scoreAmongOthers[x][y]=rank;
referenceScore[x][y]=0;
count++;
}
}
}
rank = count + 1;
}
// Print out the
System.out.println("\tP1\tP2\tP3\tP4\tP5\tP6\tTotal\tRank");
// Prints out the results and the rank for each team
for(int teamNb = 0; teamNb<3; teamNb++){
System.out.print("Team"+(teamNb+1));
for(int p=0; p<6; p++){
total = total + finalScore[teamNb][p];
System.out.print("\t" + finalScore[teamNb][p]+"("+ scoreAmongOthers[teamNb][p]+") ");
}
System.out.print("\t"+ total);
total = 0;
System.out.println();
}
}
}

So I understand that the point of the exercise is to practice working with arrays. You have outlined the required algorithm in your comment. Here is my implementation.
public class RankScores {
private static int getRank(int[][] scores, int rowIndex, int columnIndex) {
int count = 0;
int score = scores[rowIndex][columnIndex];
for (int row = 0; row < scores.length; row++) {
for (int col = 0; col < scores[row].length; col++) {
if (scores[row][col] > score) {
count++;
}
}
}
return count + 1;
}
private static int getTeamRank(int[] scores, int index) {
int count = 0;
int score = scores[index];
for (int i = 0; i < scores.length; i++) {
if (scores[i] > score) {
count++;
}
}
return count + 1;
}
public static void main(String[] args) {
int referenceScore[][]={{39,40,17,35,42,6},{40,41,27,41,42,36},{42,40,26,42,42,35}};
int ranks[][] = new int[referenceScore.length][];
int totals[] = new int[referenceScore.length]; // total score for each team
int teamRanks[] = new int[referenceScore.length];
for (int row = 0; row < ranks.length; row++) {
ranks[row] = new int[referenceScore[row].length];
totals[row] = 0;
for (int col = 0; col < ranks[row].length; col++) {
ranks[row][col] = getRank(referenceScore, row, col);
totals[row] += referenceScore[row][col];
}
}
for (int team = 0; team < teamRanks.length; team++) {
teamRanks[team] = getTeamRank(totals, team);
}
System.out.println(" P1 P2 P3 P4 P5 P6 Total Rank");
for (int row = 0; row < ranks.length; row++) {
System.out.print("Team " + (row + 1) + " ");
for (int col = 0; col < ranks[row].length; col++) {
System.out.printf("%2d(%2d) ", referenceScore[row][col], ranks[row][col]);
}
System.out.println(" " + totals[row] + " " + teamRanks[row]);
}
}
}
Running the above code produces the following output.
P1 P2 P3 P4 P5 P6 Total Rank
Team 1 39(11) 40( 8) 17(17) 35(13) 42( 1) 6(18) 179 3
Team 2 40( 8) 41( 6) 27(15) 41( 6) 42( 1) 36(12) 227 1
Team 3 42( 1) 40( 8) 26(16) 42( 1) 42( 1) 35(13) 227 1

Related

Comparing elements in row and columns, in this case 1 and 0

I've created a 2 dimensional array with the same length and it is randomly filled with 1 and 0 for example.
0100
0010
1110
1111
How do I code the program to find the rows,columns and diagonals with all 1s and 0s
This is my code so far:
public class Test2dArray {
public static void main(String[] args) {
int row,column;
System.out.print("Enter the lenghth of matrix:");
Scanner input = new Scanner(System.in);
Random rand = new Random ();
int mSize = input.nextInt();
int [][] mArray = new int [mSize][mSize];
for (row=0; row < mSize; row++){
for(column=0; column < mSize; column++){
mArray[row][column]=rand.nextInt(2);
System.out.print(mArray[row][column]+ " ");
}
System.out.println();
}
}
}
Code isn't perfect (I'm sure it can be optimized) but it works
public static void main (String[] args) throws java.lang.Exception {
int row = 5;
int column = 5;
int [][] mArray = fillArray(row, column);
System.out.println("Rows: " + findRows(mArray));
System.out.println("Columns: " + findColumns(mArray));
System.out.println("Diags: " + findDiags(mArray));
}
private static ArrayList<Integer> findRows(int [][] mArray) {
ArrayList<Integer> result = new ArrayList<Integer>();
for (int i = 0; i < mArray.length; i++){
boolean isRow = true;
for(int j = 0; j < mArray[0].length; j++){
if (j > 0 && mArray[i][j] != mArray[i][j - 1]) {
isRow = false;
break;
}
}
if (isRow) result.add(i);
}
return result;
}
private static ArrayList<Integer> findColumns(int [][] mArray) {
ArrayList<Integer> result = new ArrayList<Integer>();
for (int j = 0; j < mArray[0].length; j++){
boolean isColumn = true;
for(int i = 0; i < mArray.length; i++){
if (i > 0 && mArray[i][j] != mArray[i - 1][j]) {
isColumn = false;
break;
}
}
if (isColumn) result.add(j);
}
return result;
}
private static ArrayList<Integer> findDiags(int [][] mArray) {
ArrayList<Integer> result = new ArrayList<Integer>();
for (int i = 1; i < mArray.length; i++) {
boolean isDiag = true;
for (int j = 0; j < i; j++) {
if (mArray[i - j][j] != mArray[i - j - 1][j + 1]) {
isDiag = false;
break;
}
}
if (isDiag) result.add(i);
}
for (int i = 0; i < mArray.length - 2; i++) {
boolean isDiag = true;
for (int j = i + 1; j < mArray.length - 1; j++) {
if (mArray[mArray.length - j + i][j] != mArray[mArray.length - j + i - 1][j + 1]) {
isDiag = false;
break;
}
}
if (isDiag) result.add(mArray.length + i);
}
return result;
}
private static int[][] fillArray(int row, int column) {
int [][] mArray = new int [row][column];
Random rand = new Random();
for (int i = 0; i < row; i++){
for(int j = 0; j < column; j++){
mArray[i][j] = rand.nextInt(2);
System.out.print(mArray[i][j] + " ");
}
System.out.println();
}
return mArray;
}
Iterate and for each row and columns and sum the values into rowSum and columSum.
So:
if (rowSum == mSize)
System.out.print("The row "+i+"is full of ones");
if (rowSum == 0)
System.out.print("The row "+i+"is full of zeros");
And the same, obviously, for the columns and diagonals.

10x10 Two dimensional array and search minimum, maximum value and its index location

int[][] numList = new int[10][10];
int column;
for (int row = 0; row < 10; row++) {
for (column = 0; column < 10; column++) {
numList[row][column] = (int) (Math.random() * 100);
System.out.print(numList[row][column] + "\t");
}
System.out.println("");
}
public class Test1 {
public static void main(String[] args) {
int numList[][]=new int[10][10];
int max=0;
int min=999;
int minX=0;
int maxX=0;
int minY=0;
int maxY=0;
for (int row = 0; row < 10; row++) {
for (int column = 0; column < 10; column++) {
int num=(int)(Math.random()*100);
numList[row][column] = num;
if(num>max){
max=num;
maxX=row;
maxY=column;
}
if(num<min){
min=num;
minX=row;
minY=column;
}
System.out.print(numList[row][column] + "\t");
}
System.out.println("");
}
System.out.println("Max value=>"+max+"["+maxX+","+maxY+"]");
System.out.println("Min value=>"+min+"["+minX+","+minY+"]");
}
}
Your code is only inserting data into 2 dimensional array. To find min and max inside array and its corresponding index you need to write a function search as shown follow:
public class prog{
public void search( int[][] numList )
{
int max=0;
int maxX=0;
int maxY=0;
int min=0;
int minX=0;
int minY=0;
for (int row = 0; row < 10; row++) {
for (int column = 0; column < 10; column++) {
if( min > numList[row][column])
{
min = numList[row][column];
minX=row;
minY= column;
}
if( max < numList[row][column])
{
max= numList[row][column];
maxX=row;
maxY=column;
}
}
}
System.out.print("MinX:"+ minX+ " MinY: "+ minY+ " MaxX:"+ maxX+ " MaxY:"+ maxY);
}
public static void main(String[] args){
int[][] numList = new int[10][10];
int column;
for (int row = 0; row < 10; row++) {
for (column = 0; column < 10; column++) {
numList[row][column] = (int) (Math.random() * 100);
System.out.print(numList[row][column] + "\t");
}
System.out.println("");
}
prog obj = new prog();
obj.search( numList);
}

Exception array out of bounds

My code needs to multiply each row of an array by each column of the next. The user inputs the height and width and the program will randomly generate the array values. It doesn't give any errors if the arrays are equal for example (3x3)(3x3) or even if you do (3x2)(2x3). if however you enter something like (3x3)(3x2) it gives an out of bounds exception.
public class Multiply {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int width = -1;
int height = 0;
int width2 = 0;
int height2 = 0;
while (width != height2) {
while (height <= 0) {
System.out.print("Enter a height for array1: ");
height = checkInt(scan);
}
while (width <= 0) {
System.out.print("Enter a width for array1: ");
width = checkInt(scan);
}
while (height2 <= 0) {
System.out.print("Enter a height for array2: ");
height2 = checkInt(scan);
}
while (width2 <= 0) {
System.out.print("Enter a width for array2: ");
width2 = checkInt(scan);
}
if (width != height2) {
System.out
.println("Error! Dimensions of matrices not compatible. Try again.");
width = -1;
height = 0;
width2 = 0;
height2 = 0;
}
}
int array1[][] = randomMatrix(height, width);
int array2[][] = randomMatrix(height2, width2);
int product[][] = matrixMultiply(array1, array2, height, width2);
printArray(product);
}// end of main method
public static int[][] randomMatrix(int height, int width) {
int array1[][] = new int[height][width];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
array1[i][j] = (int) (-10 + Math.random() * 20);
}
}
return array1;
}// end of randomMatrix method
public static int[][] matrixMultiply(int[][] array1, int[][] array2, int height, int width) {
int[][] product = new int[height][width];
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array1[i].length; j++) {
int prod = 0;
for (int k = 0; k < array2.length; k++) {
prod = prod + array1[i][k] * array2[k][j];
}
product[i][j] = prod;
}
}
return product;
}// end of matrixMultiply method
public static void printArray(int[][] array) {
System.out.println(" ");
System.out.println("Row Major Representation:");
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
System.out.println(" ");
System.out.println("Column Major Representation:");
for (int i = 0; i < array[1].length; i++) {
for (int j = 0; j < array.length; j++) {
System.out.print(array[j][i] + " ");
}
System.out.println();
}
}
public static int checkInt(Scanner scan) {
int width = 0;
if (scan.hasNextInt()) {
width = scan.nextInt();
return width;
} else {
scan.next();
return 0;
}
}
}// end of public class Multiply
The value of the variable "j" (Line 82) in its final iteration is causing the Out of Bounds Exception. The error occurs for (3x3)(3x2) because in the final "j" iteration, j equals 2, making the value higher than 1 (the highest index value for j's location). Adding some logic to check for when j > the highest index will prevent the issue.

Finding the largest row and column, solution is inconsistent

Where is the logic error?.. Sometimes the solution is correct and sometimes it is not. The program is suppose to calculate the row with the greatest sum and column with the greatest sum. For example:
1 1 1 1
0 0 1 0
0 0 1 0
0 0 1 0
Then the output would be:
largest row = 0
largest column = 2 //since count starts at 0
This is what I have:
import java.util.Random;
public class LargestRowAndColumn {
public static void main(String[] args) {
Random f = new Random();
int[][] m = new int[4][4];
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
m[i][j] = f.nextInt(2);
}
}
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
System.out.print(m[i][j] + " ");
}
System.out.println();
}
System.out.println("The largest row is index: " + computeRow(m));
System.out.println("The largest column is index: " + computeColumn(m));
}
public static int computeRow(int[][] m) {
int[] count = new int[m.length];
int sum;
for (int i = 0; i < 4; i++) {
sum = 0;
for (int j = 0; j < 4; j++) {
sum = sum + m[i][j];
}
count[i] = sum;
}
int maxIndex = 0;
for (int i = 0; i < i + 1; i++) {
for (int j = count.length - 1; j >= i; j--) {
if (count[i] < count[j]) {
maxIndex = j;
break;
}
}
}
return maxIndex;
}
public static int computeColumn(int[][] m) {
int[] count = new int[m.length];
int sum = 0;
for (int i = 0; i < 4; i++) {
sum = 0;
for (int j = 0; j < 4; j++) {
sum = sum + m[j][i];
}
count[i] = sum;
}
int maxIndex = 0;
for (int i = 0; i < i + 1; i++) {
for (int j = count.length - 1; j >= i; j--) {
if (count[i] < count[j]) {
maxIndex = j;
break;
}
}
}
return maxIndex;
}
}
Your maxIndex nested loop is too complex. It should be a single loop, checking the current max value seen so far with the current item in the loop. Something like this:
int maxIndex = 0;
for (int i = 1; i < count.length; i++) {
if (count[i] > count[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
Your code is correct , but
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
m[i][j] = f.nextInt(2);
}
}
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
System.out.print(m[i][j] + " ");
}
Because of the two loops:
You are creating two random 2-dimensional array instead of one.
There is one which is being printed and the other one which is not being printed but being used for index values you require so do :
System.out.print("Index" + "\t0"+"\t1"+"\t2"+"\t3" +"\n");
System.out.print("--------------------------------------------\n");
for (int i = 0; i < m.length; i++) {
System.out.print(i+ "|\t");
for (int j = 0;j < m[0].length; j++) {
m[i][j] = f.nextInt(101);
System.out.print(m[i][j] + " \t");
}
System.out.println();
}
This will also print the index, which may assist you
Why you made your job difficult. Make 2 loops, 1 for calculating the row with biggest sum, 1 for calculating the line with the bigger sum.
You don't need an int array count[i]. In your example you calculate the row with the greatest sum, you don't need to know the sum of every row after the for loop finished, so you can use a simple int bigRow.
int bigRow = 1, sumRow = 0;
// We assume that 1st row is the biggest
// Calculate the sumRow
for (int j=0;j<n;j++)
sumRow = sumRow + m[i][j] ;
// At this moment our maximum is row 1 with its sum.
// Now we compare it with the rest of the rows
// If another row is bigger, we set him as the biggest row
for ( int i=1;i<n;i++) // We start with row 2 as we calculated the 1st row
{ int auxRow = 0;
for (int j=0;j<m;j++)
{ auxRow = auxRow + m[i][j] ; }
if (auxRow > sumRow ) { auxRow=sumRow ; bigRow = i;}
}
Do the same with lines.
int bigLine = 1, sumLine = 0 ;
Let me know if you have another problem.

Calculate sum of rows above and below a point, and also sum of columns left and right a point

Hey guys I am doing a question where I have to find a point in a Matrix A of N x M rows such that
the sum of rows above the point is equal to the sum of row
Consider this example
/**
* A[0][0] = 2 A[0][1] = 7 A[0][2] = 5
* A[1][0] = 3 A[1][1] = 1 A[1][2] = 1
* A[2][0] = 2 A[2][1] = 1 A[2][2] = -7
* A[3][0] = 0 A[3][1] = 2 A[3][2] = 1
* A[4][0] = 1 A[4][1] = 6 A[4][2] = 8
* #param matrix
* #return
*/
In this example the if we look at the point A[1][1], it can be said that the row above (sum = 14) is equal to the sum of rows below the point.
Can anyone help me on this?
I have so far gotten this far. But I know this is a sucky approach.
public int solution(int[][] matrix) {
int rows = matrix[0].length;
int columns = matrix.length;
int sumabove = 0;
int sumbelow = 0;
for( int i = 1; i < rows; i++ ) {
for (int j = 0; j < columns; j++) {
sumabove += matrix[i - 1][j];
sumbelow += matrix[i + 1][j];
}
}
return 0;
}
The idea is to calculate sum for every row (int[] rowsSum) and sum for all rows (totalRowsSum). And then to iterate through rows, comparing sum of previous rows (currentSum) with sum of next rows (totalRowsSum - currentSum - rowsSum[i]).
Code example.
public static int solution(int[][] matrix)
{
int foundRowNumber = -1;
int rows = matrix.length;
int columns = matrix[0].length;
int[] rowsSum = new int[rows];
int totalRowsSum = 0;
for (int i = 0; i < rows; i++)
{
int rowSum = 0;
for (int j = 0; j < columns; j++)
{
rowSum += matrix[i][j];
}
rowsSum[i] = rowSum;
totalRowsSum += rowSum;
}
int currentSum = 0;
for (int i = 0; i < rows; i ++)
{
if (currentSum == totalRowsSum - currentSum - rowsSum[i])
{
foundRowNumber = i;
break;
}
currentSum += rowsSum[i];
}
return foundRowNumber;
}
i'd say:
1st: get the sum of the whole matrix
2nd: divide by 2 and store in a var (mid)
3rd: loop it to go down a row each time and it will get the sum of that row and subtract it from the total sum, if it is smaller than the remaining then keeps going, if the remaining number is smaller then (mid) then you went over the middle and you start checking the columns for the row you are in and before in another loop using the same concept
something like this (pseudo code):
int sum = matrix.sum();
int mid = sum/2;
int topsum = 0;
int botsum = sum;
int counter=0;
bool fail = false;
while(topsum!=botsum && !fail) //either break when both top and bottom are same or if there is no middle gorund
{
int rowsum; //use loop to get the sum of the row
for(int i=0; i>colLength(); i++) rowsum=+ matrix[counter][i];
topsum =+ rowsum;
botsum=-rowsum;
counter++;
if(botsum>mid) //if you go over the middle
{
botsum=-rowsum; //take it back before last addition acction
counter --; //go back to the last row;
//loop
//here you will start checking columns to get to the middle.
}
}
this was made so that it would get you the cell and not row, but you can change it to your liking.
Ok I was able to do make a solution. But I think I made a mess of the complexity. I was supposed to do in a linear complexity. Anyways my solution is
public class MainClass {
static int matrix[][] = {{2, 7, 5}, {3, 1, 1}, {2, 1, -7}, {0, 2, 1}, {1, 6, 8}};
public static void main(String[] args) {
System.out.print(solution(matrix));
}
/**
* A[0][0] = 2 A[0][1] = 7 A[0][2] = 5
* A[1][0] = 3 A[1][1] = 1 A[1][2] = 1
* A[2][0] = 2 A[2][1] = 1 A[2][2] = -7
* A[3][0] = 0 A[3][1] = 2 A[3][2] = 1
* A[4][0] = 1 A[4][1] = 6 A[4][2] = 8
* #param matrix
* #return
*/
public static int solution(int[][] matrix) {
int columns = matrix[0].length;
int rows = matrix.length;
int sumRowsAbove = 0;
int sumRowsBelow = 0;
int sumColLeft = 0;
int sumColRight = 0;
int equilibrium = 0;
for( int i = 0; i < rows; i++ ) {
for (int j = 0; j < columns; j++) {
sumRowsBelow = getSumRowsBelow(i);
sumRowsAbove = getSumAbove(i);
sumColLeft = getSumColumnLeft(j);
sumColRight = getSumColumnRight(j);
if(sumRowsAbove == sumRowsBelow && sumColLeft == sumColRight) {
equilibrium++;
}
int x = 2;
x+=2;
}
}
return equilibrium;
}
public static int getSumRowsBelow(int rowNum) {
int columns = matrix[0].length;
int rows = matrix.length;
int sumBelow = 0;
for( int i = rowNum; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if((i+1) < rows){
sumBelow += matrix[i + 1][j];
}
}
}
return sumBelow;
}
public static int getSumColumnRight(int column) {
int columns = matrix[0].length;
int rows = matrix.length;
int sumBelow = 0;
for (int j = column; j <= columns; j++) {
for( int i = 0; i < rows; i++) {
if((j+1) < columns){
sumBelow += matrix[i][j + 1];
}
}
}
return sumBelow;
}
public static int getSumColumnLeft(int column) {
int columns = matrix[0].length;
int rows = matrix.length;
int sumBelow = 0;
for (int j = column; j >= 0; j--) {
for( int i = 0; i < rows; i++) {
if((j-1) >= 0){
sumBelow += matrix[i][j - 1];
}
}
}
return sumBelow;
}
public static int getSumAbove(int rowNum) {
int columns = matrix[0].length;
int rows = matrix.length;
int sumBelow = 0;
for( int i = rowNum; i >= 0; i--) {
for (int j = 0; j < columns; j++) {
if((i-1) >= 0){
sumBelow += matrix[i - 1][j];
}
}
}
return sumBelow;
}
}
This is a codility question regarding find the number of points (equilibriums) such the sum of elements in rows above the selected point is equal to the sum of rows below the point. And also sum of columns from the left of the selected point is equal to the sum of columns to the right of the point.

Categories

Resources