Im new to java and I am trying to print elements I got from a selection sort algorithm both by columns and by rows.
The expected output for an unsorted matrix can be by rows
486 123 147
927 to 456 (rows) or 258 (columns)
135 (unsorted) 789 369
Thanks in advance! Please no professional solutions since I am a student.
public void sort(boolean byColumn)
{
double[] temp = null;
double placeHolder = 0.0;
int total = 0;
int index = 0;
/* Incrementing the total to use for the length of the temporary array. */
for (int rows = 0; rows < mdArray.length; rows++)
{
for (int columns = 0; columns < mdArray[rows].length; columns++)
{
total++;
}
}
temp = new double[total];
/* This nested for loop converts the indices of mdArray to one long temp array. */
for (int rows = 0; rows < mdArray.length; rows++)
{
for (int columns = 0; columns < mdArray[rows].length; columns++)
{
temp[index] = mdArray[rows][columns];
index++;
}
}
for (int i = 0; i < temp.length; i++) // Sorting the temporary array using selection sort.
{
for (int j = i + 1; j < temp.length; j++)
{
if (temp[j] < temp[i])
{
placeHolder = temp[i];
temp[i] = temp[j];
temp[j] = placeHolder;
}
}
}
index = 0;
if (byColumn) // Sorting the invoking array by column.
{
for (int rows = 0; rows < mdArray.length; rows++) // Puts sorted elements back into mdArray.
{
for (int columns = 0; columns < mdArray[rows].length; columns++)
{
mdArray[rows][columns] = temp[index];
index++;
}
}
for (int rows = 0; rows < mdArray.length; rows++)
{
System.out.println();
for (int columns = 0; columns < mdArray[rows].length; columns++)
{
System.out.print(mdArray[rows][columns] + " ");
}
}
}
else if (!byColumn) // Sorting the invoking by row.
{
for (int columns = 0; columns < mdArray[columns].length; columns++)
{
for (int rows = 0; rows < mdArray.length; rows++)
{
mdArray[columns][rows] = temp[index];
index++;
}
}
for (int rows = 0; rows < mdArray.length; rows++)
{
System.out.println();
for (int columns = 0; columns < mdArray[rows].length; columns++)
{
System.out.print(mdArray[rows][columns] + " ");
}
}
}
else if (byColumn && isRagged()) //
System.out.println("Cannot sort ragged arrays by column.");
}
Hint: if you add comment line to your code, this is definetly means, that it is better to extract code part to the separate method.
In your case, I reccomend to implement two more methods: sortByColumn(int[][] arr) and sortByRow(int[][] arr), because using sort(arr, true) is not so clear at the first sight (what exactly true means).
Public methods for the clients (clear to use):
public static void sortByColumn(int[][] arr) {
sort(arr, true);
}
public static void sortByRow(int[][] arr) {
sort(arr, false);
}
Sort implementation (proctected and not available to the client directly):
prvate static void sort(int[][] arr, boolean byColumn) {
int[] temp = convertToSimpleArray(arr);
selectionSort(temp);
if (byColumn) {
for (int row = 0, i = 0; row < arr.length; row++)
for (int col = 0; col < arr[row].length; col++)
arr[row][col] = temp[i++];
} else {
for (int col = 0, i = 0; i < temp.length; col++)
for (int row = 0; row < arr.length; row++)
if (col < arr[row].length)
arr[row][col] = temp[i++];
}
}
Method for create 1D array from given 2D array:
private static int[] convertToSimpleArray(int[][] arr) {
int total = 0;
for (int row = 0; row < arr.length; row++)
for (int col = 0; col < arr[row].length; col++)
total++;
int[] res = new int[total];
for (int row = 0, i = 0; row < arr.length; row++)
for (int col = 0; col < arr[row].length; col++)
res[i++] = arr[row][col];
return res;
}
Method for sort array with required sort algorithm:
private static void selectionSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] >= arr[i])
continue;
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
Input:
int[][] arr = {
{ 19, 44, 16, 39, 26 },
{ 42, 6, 30 },
{ 44, 37, 0, 46 },
{ 37, 42, 48, 19, 40 } };
Output:
sortByColumn(arr) provides:
0 6 16 19 19
26 30 37
37 39 40 42
42 44 44 46 48
sortByRow(arr) provides:
0 19 37 42 46
6 26 39
16 30 40 44
19 37 42 44 48
Related
I have to write a program that reads a file containing set of 16 numbers and creates a magic square. A magic square is one where the sum of each row, column, and diagonal is the same. I have to use the sentinel method to control your loop. The sentinel value is -999. When I run the code it shows that all are not magic square. When I run it it looks like the following.
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
NOT a magic square
1 15 14 4
12 6 7 9
8 10 11 5
13 3 2 16
NOT a magic square
30 8 20 11
3 10 21 35
24 25 13 7
12 26 15 16
NOT a magic square
14 8 19 92
37 53 16 27
67 10 54 2
15 62 44 12
NOT a magic square
2 5 6 1
8 5 2 9
4 5 6 7
3 2 7 5
NOT a magic square
The following is the code.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
class square {
public static void main(String[] args) throws IOException {
File data = new File("Lab8Data.txt");
Scanner input = new Scanner(data);
int[][] array = new int[4][4];
int[] rowTotal = new int[4];
int[] columnTotal = new int[4];
for (int row = 0; row < array.length; row++)
array[0][row] = input.nextInt();
while (array[0][0] != -999) {
for (int column = 1; column < array.length; column++)
for (int row = 0; row < 4; row++)
array[column][row] = input.nextInt();
for (int column = 0; column < array.length; column++) {
for (int row = 0; row < array.length; row++)
System.out.print(array[column][row] + " ");
System.out.println();
}
for (int column = 0; column < array.length; column++)
for (int row = 0; row < array.length; row++)
rowTotal[column] += array[column][row];
for (int row = 0; row < array.length; row++)
for (int column = 0; column < array.length; column++)
columnTotal[row] += array[column][row];
int diagonalOne = 0;
for(int row = 0; row < array.length; row++)
diagonalOne = diagonalOne + array[row][row];
int otherDiagonal = 0;
for (int row = 0; row < array.length; row++) {
otherDiagonal = otherDiagonal + array[row][Math.abs(3 - row)];
int rows = rowTotal[0];
boolean rowEqual = true;
for (int r = 0; r < array.length; r++)
if (rowTotal[r] != r)
rowEqual = false;
int col = columnTotal[0];
boolean columnEqual = true;
for (int column = 0; column < array.length; column++)
if (rowTotal[column] != col)
columnEqual = false;
int diagonal = diagonalOne;
boolean diagonalEqual = true;
if (otherDiagonal != diagonal)
diagonalEqual = false;
boolean isMagic = false;
if (rowEqual && columnEqual && diagonalEqual)
if (rows == col && col == diagonal)
isMagic = true;
if (isMagic)
System.out.println("Is a magic square");
else
System.out.println("NOT a magic square");
for (int r = 0; r < 4; r++)
array[0][r] = input.nextInt();
}
}
}
}
This should be a magic square.
1 15 14 4
12 6 7 9
8 10 11 5
13 3 2 16
What should I do to make it print if the square is magic correctly.
I initialize the variables inside the loop, otherwise the totals will not be correct:
while (true) {
int[][] array = new int[4][4];
int[] rowTotal = new int[4];
int[] columnTotal = new int[4];
the first number you read is either the sentinel, or array[0][0]:
int number = input.nextInt();
if (number == -999) {
break;
}
array[0][0] = number;
Now you need to read the remainder of row 0:
for (int column = 1; column < array[0].length; column++) {
array[0][column] = input.nextInt();
}
and then the other rows:
for (int row = 1; row < array.length; row++) {
for (int column = 0; column < array[row].length; column++) {
array[row][column] = input.nextInt();
}
}
Now, the calculations; column totals:
for (int column = 0; column < array.length; column++) {
for (int row = 0; row < array.length; row++) {
columnTotal[column] += array[row][column];
}
}
row totals:
for (int row = 0; row < array.length; row++) {
for (int column = 0; column < array.length; column++) {
rowTotal[row] += array[row][column];
}
}
diagonals:
int diagonalOne = 0;
for (int row = 0; row < array.length; row++) {
diagonalOne += array[row][row];
}
int otherDiagonal = 0;
for (int row = 0; row < array.length; row++) {
otherDiagonal += array[row][array.length - row - 1];
}
then the comparisons:
int row = rowTotal[0];
boolean rowEqual = true;
for (int r = 0; r < array.length; r++) {
if (rowTotal[r] != row) {
rowEqual = false;
}
}
int col = columnTotal[0];
boolean columnEqual = true;
for (int column = 0; column < array.length; column++) {
if (columnTotal[column] != col) {
columnEqual = false;
}
}
int diagonal = diagonalOne;
boolean diagonalEqual = true;
if (otherDiagonal != diagonal) {
diagonalEqual = false;
}
boolean isMagic = false;
if (rowEqual && columnEqual && diagonalEqual) {
if (row == col && col == diagonal) {
isMagic = true;
}
}
if (isMagic) {
System.out.println("Is a magic square");
} else {
System.out.println("NOT a magic square");
}
Of course you wouldn't need to store the totals in arrays: you could just compare them as you compute them.
int sum = 0;
for (int row = 0; row < array.length; row++) {
sum += array[row][row];
}
boolean isMagic = true;
int magicNumber = sum;
sum = 0;
for (int row = 0; row < array.length; row++) {
sum += array[row][array.length - row - 1];
}
if (sum != magicNumber) {
isMagic = false;
}
for (int column = 0; column < array.length; column++) {
sum = 0;
for (int row = 0; row < array.length; row++) {
sum += array[row][column];
}
if (sum != magicNumber) {
isMagic = false;
}
}
for (int row = 0; row < array.length; row++) {
sum = 0;
for (int column = 0; column < array.length; column++) {
sum += array[row][column];
}
if (sum != magicNumber) {
isMagic = false;
}
}
public class Foo {
public static void main(String... args) throws IOException {
File file = new File("Lab8Data.txt");
int[][] square = readSquareFromFile(file);
boolean magicSquare = isMagicSquare(square);
System.out.println(magicSquare);
}
private static int[][] readSquareFromFile(File file) {
// TODO read from file
return new int[][] {
{ 1, 15, 14, 4 },
{ 12, 6, 7, 9 },
{ 8, 10, 11, 5 },
{ 13, 3, 2, 16 } };
}
private static boolean isMagicSquare(int[][] square) {
int magicNumber = Arrays.stream(square[0]).sum();
return isRowsMagic(square, magicNumber)
&& isColumnsMagic(square, magicNumber)
&& isDiagonalsMagic(square, magicNumber);
}
private static boolean isRowsMagic(int[][] square, int magicNumber) {
for (int row = 0; row < square.length; row++) {
int sum = 0;
for (int col = 0; col < square[row].length; col++)
sum += square[row][col];
if (sum != magicNumber)
return false;
}
return true;
}
private static boolean isColumnsMagic(int[][] square, int magicNumber) {
for (int col = 0; col < square[0].length; col++) {
int sum = 0;
for (int row = 0; row < square.length; row++)
sum += square[row][col];
if (sum != magicNumber)
return false;
}
return true;
}
private static boolean isDiagonalsMagic(int[][] square, int magicNumber) {
return getLeftDiagonalSum(square) == magicNumber && getRightDiagonalSum(square) == magicNumber;
}
private static int getLeftDiagonalSum(int[][] square) {
int sum = 0;
for (int i = 0; i < square.length; i++)
sum += square[i][i];
return sum;
}
private static int getRightDiagonalSum(int[][] square) {
int sum = 0;
for (int row = 0, col = square.length - 1; row < square.length; row++, col--)
sum += square[row][col];
return sum;
}
}
I'm trying to add specific elements from one 2d array to another , the process of adding is that I'm choosing the smallest element in the first row of the array and add that element to the other 2d array at the same position so for example :
2 22 3
5 1 54
7 3 10
20 22 21
here the smallest element in the first row is 2 so 2 should be added to the other 2d array at the same position , and for the second row 1 is the smallest element so we add 1 to the other 2d array as well , the smallest element in the third row is 3 , and the final row the fourth row the smallest element is 20 but we cannot pick 20 as the smallest because we check the sum of columns in the second 2d array which was initialized with 0's , so here if we pick 20 then the sum of its column is 21 because 20 + 1 + 0 + 0 = 21 , if we pick 22 then 22 + 3 + 1 + 0 = 26 and if we pick 21 then 21 + 0 + 0 + 0 = 21 ,so here 21 is the smallest because the sum of its column is the smallest :
1 0 0
0 1 0
0 3 0
0 0 21
and the process goes on for the other rows and columns if there are any.
This is what I've made so far :
import java.util.Arrays;
public class Main
{
//Method which finds the sum of columns
public static int[] sumOfCol(int[][] tempArr){
int size = tempArr[0].length; // Replace it with the size of maximum length inner
array
int temp[] = new int[size];
for (int i = 0; i < tempArr.length; i++){
for (int j = 0; j < tempArr[i].length; j++){
temp[j] += tempArr[i][j];
}
}
System.out.println(Arrays.toString(temp));
return temp;
}
//The algorithm
public static void algorithm(int[][] tempArr,int[][] tempArr2){
for (int i = 0; i < tempArr.length; i++) {
int minimum = tempArr[i][0];
for (int j = 0; j < tempArr[0].length; j++) {
if (tempArr[i][j] < minimum) {
minimum = tempArr[i][j];
tempArr2[i][j] = minimum;
}
}
}
}
//To generate teh Array
public static void generateArray(int[][] arr){
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 3; j++) {
arr[i][j] = (int) ((Math.random() * (25 - 1)) + 1);
}
}
}
//To print an array
public static void printArray(int[][] arr){
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int [][] tempArr = new int [5][3];
int[][] tempArr2 = new int[tempArr.length][tempArr[0].length];
//Initilise second array with 0's
for (int i = 0; i < tempArr2.length; i++) {
for (int j = 0; j < tempArr2[0].length; j++) {
tempArr2[i][j] = 0;
}
}
generateArray(tempArr);
System.out.println("Array before executing the algorithm : ");
printArray(tempArr);
algorithm(tempArr,tempArr2);
System.out.println("Array after executing the algorithm : ");
printArray(tempArr2);
}
}
I wasn't able to find the error in your code but found another way to do what you are looking for:
//The algorithm
public static int[][] algorithm(int[][] tempArr){
// create the empty array.
int[][] modifiedArr = new int[tempArr.length][tempArr[0].length];
for (int i = 0; i < modifiedArr.length; i++) {
for (int j = 0; j < modifiedArr[0].length; j++) {
modifiedArr[i][j] = 0;
}
}
// loop through all rows and change one value in each row on modifiedArr in a way that leads to the column sum being miniumum.
for (int i = 0; i < tempArr.length; i++) {
setMinimumColumn(tempArr,modifiedArr,i);
}
return modifiedArr;
}
static void setMinimumColumn(int[][] originalArr, int[][] modifiedArr, int row){
int minColumn = 0;
int minColumnSum = Integer.MAX_VALUE;
for (int i=0; i <originalArr[row].length ;i++){
modifiedArr[row][i] = originalArr[row][i];
int columnSum = getColumnSum(modifiedArr,i);
if (columnSum < minColumnSum) {
minColumn = i;
minColumnSum = columnSum;
}
modifiedArr[row][i] = 0;
}
modifiedArr[row][minColumn] = originalArr[row][minColumn];
}
static int getColumnSum(int[][] arr, int column){
int sum = 0;
for (int i = 0; i<arr.length; i++){
for (int j = 0; j<arr[0].length; j++) {
if (j == column){
sum+=arr[i][j];
}
}
}
return sum;
}
public static void main(String[] args) {
int [][] tempArr = new int [5][3];
generateArray(tempArr);
System.out.println("Array before executing the algorithm : ");
printArray(tempArr);
System.out.println("Array after executing the algorithm : ");
printArray(algorithm(tempArr));
}
Basically, you start by looping through the rows. Every row is given to the setMinimumColumn method, which loops through all element in that row and tries putting them in modifiedArr in a way that minimizes the column sum. Doing this for all columns gives you the answer.
I have 4x4 2D array that already has values in each index. I want to have a function that calculates the sum of a row/column of the array and store it at the first/final column and have the other indexes revert to 0.
This is what I have to render my array:
public static void print2Darray(int[][] numbers) {
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers.length; j++) {
System.out.print(numbers[i][j]);
System.out.print("\t");
}
System.out.println();
}
}
Which displays something like this:
10 15 30 40
15 5 8 2
20 2 4 2
1 4 5 0
Currently this is the function that I have:
public static void sumLeft(int[][] numbers) {
for (int i = 0; i < numbers.length; i++) {
numbers[i][0] = (numbers[i][0] + numbers[i][1] + numbers[i][2] + numbers[i][3]);
if (i == 3) {
numbers[0][1] = 0;
numbers[0][2] = 0;
numbers[0][3] = 0;
numbers[1][1] = 0;
numbers[1][2] = 0;
numbers[1][3] = 0;
numbers[2][1] = 0;
numbers[2][2] = 0;
numbers[2][3] = 0;
numbers[3][1] = 0;
numbers[3][2] = 0;
numbers[3][3] = 0;
}
}
}
Which does this:
95 0 0 0
30 0 0 0
28 0 0 0
10 0 0 0
I just want to find an algorithm that would do this without "cheating" or just hacking my way through it.
All you need to do is loop over the elements of the "row" array:
public static void sumLeft(int[][] numbers) {
for (int i = 0; i < numbers.length; i++) {
for (int j = 1; j < numbers[i].length; j++) {
numbers[i][0] += numbers[i][j];
numbers[i][j] = 0;
}
}
}
Why did not you do simple this:
for (int i = 0; i < numbers.length; i++) {
for (int j = 1; j < numbers[i].length; j++) {
numbers[i][0] += numbers[i][j];
numbers[i][j] = 0;
}
}
Use the inner loop in the reverse order as:
for (int i = 0; i < numbers.length; i++) { // for all rows
int sum = 0; // about to be sum, reset every row
for (int j = numbers[i].length -1 ; j >=0; j--) { // iterate reverse in columns
if (j == 0) {
numbers[i][j] += sum; // final sum
} else {
sum += numbers[i][j]; // keep evaluating
numbers[i][j] = 0; //reset
}
}
}
I am studying and have a little trouble.
I have to build matrix like this on the picture
Matrix
But i can't put a stars in that places.
public static void main(String[] args) {
int[][] twoD = new int[5][5];
int i, j, k = 1;
for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++) {
twoD[i][j] = k;
k++;
}
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++)
System.out.print(twoD[i][j] + " ");
System.out.print("\n");
}
}
Here is my code, please help to find
You can take the answer from a previous question and slightly modify it like so
public static void printCross(int size, char display)
{
int count = 0; //add a counter
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
count++; //increment each index we come across
if (row == col || row + col == size - 1) {
//print out the X using teh given display character
System.out.print(String.format("%-3s", display));
} else {
//print out the current count
System.out.print(String.format("%-3s", count));
}
}
System.out.println();
}
}
Output
X 2 3 4 X
6 X 8 X 10
11 12 X 14 15
16 X 18 X 20
X 22 23 24 X
I have found the easiest way i think.
public static void main(String args[]){
String[][] Matrix = { {" *"," 2"," 3"," 4"," *"} , {" 6"," *"," 8"," *","10"} , {"11","12"," *","14","15"} , {"16"," *","18"," *","20"} , {" *","22","23","24"," *"}};
for(int i=0; i< Matrix.length; i++){
for(int j=0;j < Matrix.length; j++){
System.out.print(Matrix[i][j]+" ");
}
System.out.println("");
}
}
I need to write a short program on how to add two matrices.. The first matrix should look like this:
1 2 3 4 5 6 7 8 9 10
11 12 13.......19 20
21................30
31................40
41................50
etc..
91...............100
But I don't really come to a solution how to increment the first array.. :S
Here is what I got so far:
package uebung05;
public class MatrixAddition
{
public static void main(String[] argv)
{
int firstArray[][] = new int[10][10];
int secondArray[][] = new int[10][10];
int ergArray[][] = new int[10][10];
System.out.println("Matrix 1\n----------------------------");
// Inkrementieren der ersten Matrix
for(int row = 0; row < firstArray.length; row++)
{
for(int column = 0; column < firstArray[row].length; column++)
{
// Increment Array here???
System.out.print(firstArray[row][column] + " ");
}
System.out.println();
}
System.out.println("\nMatrix 2\n----------------------------");
// Dekrementieren der zweiten Matrix
for(int row = 0; row < secondArray.length; row++)
{
for(int column = 0; column < secondArray[row].length; column++)
{
// Array mit Werten befüllen
secondArray[row][column] = column + 1;
System.out.print(secondArray[row][column] + " ");
}
System.out.println();
}
System.out.println("\nAddition beider Matrizen\n----------------------------");
// Addition firstArray & secondArray
for(int row = 0; row < ergArray.length; row++)
{
for(int column = 0; column < ergArray[row].length; column++)
{
// Addition
ergArray[row][column] = firstArray[row][column] +
secondArray[row][column];
System.out.print(ergArray[row][column] + " ");
}
System.out.println();
}
}
}
Method to add the first and second matrices together:
public static int[][] matrixAdd(int[][] A, int[][] B)
{
// Check if matrices have contents
if ((A.length < 0) || (A[0].length < 0)) return B;
if ((B.length < 0) || (B[0].length < 0)) return A;
// create new matrix to store added values in
int[][] C = new int[A.length][A[0].length];
for (int i = 0; i < A.length; i++)
{
for (int j = 0; j < A[i].length; j++)
{
C[i][j] = A[i][j] + B[i][j];
}
}
return C;
}
But I don't really come to a solution how to increment the first array.
// Inkrementieren der ersten Matrix
for(int row = 0; row < firstArray.length; row++)
{
for(int column = 0; column < firstArray[row].length; column++)
{
firstArray[row][column] = 1+ row*10 + column;
System.out.print(firstArray[row][column] + " ");
}
System.out.println();
}
Sum two matrices in the new one and return:
public int[][] addMatrixes(int[][] src1, int[][] src2){
int[][] dst = new int[src1.length][src1[0].length];
for(int i=0;i<src1.length;i++){
for(int j=0;j<src1[0].length;j++){
dst[i][j] = src1[i][j] + src2[i][j];
}
}
return dst;
}
Not very generic, but you can define your first matrix with only one easy loop :
int dim = 10;
int size = dim*dim;
int firstArray[][] = new int[dim][dim];
int row, column;
for (int index = 0; index < size; index++ ){
row = index/dim;
column = index%dim;
firstArray[row][column]=row*10+column+1;
System.out.print(String.valueOf(firstArray[row][column])+"\t");
if (column == 9){ System.out.println("");}
}