java two dimensional array sorting - java

Write a program that prompts the user to enter a nxn matrix of double values and displays a new matrix which has the columns of the initial matrix sorted. You may use any sorting algorithm to solve the problem; please specify the name of the used sorting algorithm into your code header. Your program must implement a sorting algorithm; you cannot use the sorting methods provided in the Array class. The sorting should be implemented into a method, in which a new array is returned and the original array is intact:
public static double[][] sortCol(double[][] a)
The program should also implement a method that prints the initial and the result matrices to user. The print out should be nicely formatted. Here is a sample run:
What is the dimension of matrix? 3
Enter a 3x3 matrix row by row:
0.15 0.875 0.375
0.55 0.005 0.225
0.30 0.12 0.4
The column sorted array is:
0.15 0.005 0.225
0.3 0.12 0.375
0.55 0.875 0.4
This is what I have. I believe it is almost perfect. The sorting method I used I think will sort the column but it may also be sorting the rows. However when I run the program I get this...
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at Hmwk3_jrgluck.main(Hmwk3_jrgluck.java:16)
Any ideas/ help..
import java.util.Scanner;
public class sdfjasdf {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("What is the dimension of your matrix?");
int matrixdim = input.nextInt();
double[][] matrix = new double[matrixdim][matrixdim];
System.out.println("Enter " + matrixdim + " rows, and " + matrixdim
+ " columns.");
Scanner input1 = new Scanner(System.in);
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix.length; column++)
matrix[row][column] = input1.nextDouble();
}
System.out.println(sortCol(matrix));
}
public static double sortCol(double[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
double currentMin = matrix[i][0];
int currentMinIndex = i;
for (int j = i; j < matrix.length; j++) {
if (currentMin > matrix[j][0]
|| (currentMin == matrix[j][0] && matrix[currentMinIndex][1] > matrix[j][1])) {
currentMin = matrix[j][0];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
double temp0 = matrix[currentMinIndex][0];
double temp1 = matrix[currentMinIndex][1];
matrix[currentMinIndex][0] = matrix[i][0];
matrix[currentMinIndex][1] = matrix[i][1];
matrix[i][0] = temp0;
matrix[i][1] = temp1;
}
}
return sortCol(matrix);
}
}

I suspect that your locale can require commas instead dots in float number format. Try changing your data to
0,15 0,875 0,375
0,55 0,005 0,225
0,30 0,12 0,4
If that is true but you prefer to (or must) use dots instead of comma you can change locale used in Scanner by invoking
input.useLocale(new Locale("en", "US"));
or change global Locale before creating Scanner object with
Locale.setDefault(new Locale("en", "US"));
Also return type of sortCol should be aether
double[][] in case you want to return sorted copy of array (without changing original one). In that case you will need to first create copy of original array
void in case you want to sort original array (you don't have to return reference to object that you already have since you used it as methods argument)
Right now you are trying to return double by invoking again sortCol(matrix), so it again will try to return sortCol(matrix) (and so on) which will lead to stack overflow.

Related

Sorting 2d String array using java

I am trying to sort a string 2d array taken as user input. But this code is working for some cases and not working for some.
The code is:
public class Source {
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner(System.in);
String[][] customerDetails= new String[5][3];
customerDetails[0][0]="10";
customerDetails[0][1]="Raj";
customerDetails[0][2]="Chennai";
customerDetails[1][0]="100";
customerDetails[1][1]="Akshay";
customerDetails[1][0]="Pune";
customerDetails[2][0]="20";
customerDetails[2][1]="Simrath";
customerDetails[2][2]="Amristar";
customerDetails[3][0]="30";
customerDetails[3][1]="Gaurav";
customerDetails[3][2]="Delhi";
customerDetails[4][0]="101";
customerDetails[4][1]="Ganesh";
customerDetails[4][2]="Chennai";
/*for (int i = 0; i < 5; i++) {
for (int j = 0; j < 3; j++) {
//customerArray[i][j] = sc.nextLine();
}
}*/
Arrays.sort(customerArray, (a, b)->a[0].compareTo(b[0]));
for (int y = 0; y < 5; y++) {
for (int z = 0; z < 3; z++) {
System.out.println(customerArray[y][z]);
}
}
}
}
I have given direct inputs in this code. I want to sort the numbers as String
You are getting wrong answer because you were comparing 0th index of each row of 2D array which are String. So, according to string comparison logic the outputs are correct. To get the sorting order as integer, you have to convert 0th index of each row to Integer in your comparator.
Modify your sort method call like below which should work according to your expectation because a[0] and b[0] are converted to Integer before comparison:
Arrays.sort(customerArray, (a, b)->Integer.valueOf(a[0]).compareTo(Integer.valueOf(b[0])));
Output:
10
Akhil
Pune
20
Rajni
Hyderabad
30
Praveen
Delhi
100
Rohith
Chennai
101
Sam
Bangalore

Why does nested for loops used to generate a 2D array from another 2D array returns 0 for last index of each inner array?

I would like to build an array of columns from this array the goal is to have this method accept a jagged array I.E. not square or rectangular, like the on in my code example is rectangular for instance. As you can see from my output every 4th index of one the inner arrays equals zero, though it would seem that the value at the time it is a assigned is actually equal to the correct value from the sales array. Notice in the main method that when I output salesByColumn[2][4] that the value is 0.0 (it is the last entry to the console). If you look in the Sales class where the method used to generate this 2D array that when it assigns salesByColumn it does so like salesByColumn[ i ][ j ], therefore you can determine that when that index is assigned that i = 2 and j = 4. The method assigns salesByColumn[2][4] to sales[4][2], which if you observe the sales array sales[4][2] = 2391.0. Inside the method I also print the value of sales[4][2] when the method is called and as you can see at the top of the output it evaluates to 2391.0. So why is it assigning it to 0.0 when the method is called and iterated upon? Thank you for your time and consideration.
MAIN CLASS
public class Main {
public static void main(String[] args) {
double[][] salesByColumn = Sales.salesByColumn();
for(double[] column : salesByColumn) {
for(double sale : column) {
System.out.println(sale);
}
System.out.println();
}
System.out.println(salesByColumn[2][4]);
}
}
SALES CLASS
public class Sales {
static double[][] sales = {
{1540.0, 2010.0, 2450.0, 1845.0},
{1130.0, 1168.0, 1847.0, 1491.0},
{1580.0, 2305.0, 2710.0, 1284.0},
{1105.0, 4102.0, 2391.0, 1576.0},
{1105.0, 4102.0, 2391.0, 1576.0}
}
public static double[][] salesByColumn() {
int maxColumns = 0;
for(double[] row : sales) {
if(row.length > maxColumns) {
maxColumns = row.length;
}
}
System.out.println("Look here " + sales[4][2]);
double[][] salesByColumn = new double[maxColumns][];
for(int i = 0; i < maxColumns; i++) {
salesByColumn[i] = new double[(sales.length)];
for(int j = 0; j < sales[i].length; j++) {
salesByColumn[i][j] = sales[j][i];
}
}
return salesByColumn;
}
}
OUTPUT
run:
Look here 2391.0
1540.0
1130.0
1580.0
1105.0
0.0
2010.0
1168.0
2305.0
4102.0
0.0
2450.0
1847.0
2710.0
2391.0
0.0
1845.0
1491.0
1284.0
1576.0
0.0
0.0
BUILD SUCCESSFUL (total time: 0 seconds)
The index in your inner loop is incorrect. You don't want to iterate over the length of sales[i], you need the total number of rows so that you can turn each row into a column.
Here is a working loop
System.out.println("Look here " + sales[4][2]);
double[][] salesByColumn = new double[maxColumns][];
for(int i = 0; i < maxColumns; i++) {
salesByColumn[i] = new double[(sales.length)];
for(int j = 0; j < sales.length; j++) {
System.out.println("Assigning "+i+", "+j+" to" +sales[j][i]);
salesByColumn[i][j] = sales[j][i];
}
}
If your real input data is truly jagged as you mention then you'll need an index check in the inner loop.

Cannot convert double into double[][] error in java?

Okay so I'm still working on a matrix project for my APCS class, and I am currently trying to figure out how to get the user to input all the numbers for the matrix. Right now I have a setNums class that uses the Rows and Columns already inputted to throw up a bunch of inputboxes and then inputs those numbers into a 2 dimensional array like so:
public void setNums(String Matrixnum){
for (int i = 1; i <= myRows; i++){
for(int j = 1; j <= myColumns; j++){
String StrNum = JOptionPane.showInputDialog(null, Matrixnum + " Row " + i + " Column " + j + " enter number:");
myNums[i][j] = Double.parseDouble(StrNum);
}
}
}
I then have a getNums class that should go through the array and return them one by one, when I need the numbers later on for adding, subtracting, and multiplying the matrices:
public double[][] getNums(){
for(int i = 1; i <= myRows; i++) {
for(int j = 1; j <= myColumns; j++) {
return myNums[i][j];
}
}
}
The issue is that when I try to return myNums, it says "cannot convert from double to double[][]" I don't understand why the code thinks it's a double and not a double[][]. I initialized it correctly:
private double[][] myNums;
...and I made sure my parsedouble was outputting to the array, which was the issue in a similar thread I found. This is my first time working with 2 dimensional arrays, so I bet there's something simple here that I don't understand. Any help is greatly appreciated. Thanks!
The compiler returns this error Cannot convert double into double[][]
because your are actually returning single double number instead of your double array double[][] that you defined as return type of your method getNums()
Instead you can fix the problem by returning only myNums array:
public double[][] getNums(){
return myNums;
}
Also you can declare another method if you want to get any specific number from your array by using array indexes i and j:
public double getNumber(int i, int j){
return myNums[i][j];
}

Moving Average Using User-Input Array

I need to write a program that calculates a moving average by a user inputted array. The first element of the array is the window size, and the input is terminated by a 0. The output values are printed with two digits after the decimal point.
Example input: 3 2 4 7 7 8 11 12 0
Corresponding Output: 4.33 6.00 7.33 8.67 10.33
(4.33 is average of 2,4,7 and 6 is average of 4,7,7 etc.)
Here's my code so far:
package movingaverage;
import java.util.Scanner;
public class MovingAverage {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
avg[0] = sum / 5;
int j = 1;
for (int i = 5; i < arr.length; i++) {
sum = sum + arr[i] - arr[i - 5];
avg[j++] = sum / 5;
}
}
}
I think I have the loop right, but I'm not sure how to get the array to end at 0.
This is a possible solution.
public class Test
{
private static final Scanner SCANNER;
static {
SCANNER = new Scanner(System.in);
}
public static final void main(final String... args) {
final String[] numbers = SCANNER.nextLine().trim().split(" ");
final int consideredElements = Integer.parseInt(numbers[0]);
float sum = 0;
int value = 0;
for (int i = 1; i < numbers.length; i++) {
sum = 0;
for (int k = 0; k < consideredElements; k++) {
value = Integer.parseInt(numbers[i + k]);
if (value == 0) {
return;
}
sum += value;
}
System.out.println(new BigDecimal(sum / consideredElements).setScale(2, RoundingMode.HALF_EVEN));
}
}
}
First, you are using 5 in a couple of places in your program, I see no justification for that. Could it be that your expectation of user input lead you to put 5 where the number you really should use, depends on user input? Maybe you should use the window size instead? I’m guessing a bit here.
Next, as #lppEdd pointed out, you are not reading the numbers from your input — only the window size.
Next, you are declaring your array of size n, which I believe was your window size, not your array size. I believe the real solution to this problem is using better and more explanatory variable names.
Your code does not compile since you have not declared the array avg that you try to store your moving average into.
Fifth, when you want your average as a double, you need to convert to double before dividing (this is a classic pitfall that has already generated many questions on Stack Overflow).
I hope this gets you a couple of steps further.

Need assistance Fixing Some coding in this Java Class File

So im new to Stack Overflow and hope I am saying this question correctly.
I was given this assignment from class and was done with it until my professor tweak the assignment a little bit. In summary i made 2 classes the would work with each other and call off the variable from the other class into the class it was being called to. Now my professor want 1 java file which mean one class file. I do not know how to rewrite the program with both code into one class.
Assignment:
"(The Location class) Design a class named Location for locating a maximal value and its location in a two-dimensional array. The class contains public data fields row, column, and maxValue that store the maximal value and its indices in a two-dimensional array with row and column as int types and maxValue as double type.
Write the following method that returns the location of the largest element in a two-dimensional array:
public static Location locateLargest(double[][] a)
The return value is an instance of Location. Write a test program that prompts the user to enter two-dimensional array and displays the location of the largest element in the array. Here is sample run:
Enter the number of rows and columns of the array: 3 4
Enter the array:
23.5 35 2 10
4.5 3 45 3.5
35 44 5.5 9.6
The location of the largest element is 45 at (1, 2)
SO i did all that with the 1st class coding:
public class Location {
int row; //blue variable = class variable
int column;
double maxValue;
}
Then here the code that call in the program in the second class
import java.util .*;
public class TestLocation {
public static void main(String[] args)
{
Location mylocation;
int row;
int column;
double [][] numArray; //we can leave this blank
Scanner Reading = new Scanner(System.in);
System.out.println(" How many rows will you be entering?");
row = Reading.nextInt(); //nextInt -what it reads will convert into a integer
System.out.println(" How many columns will you be entering?");
column = Reading.nextInt();
numArray = new double [row][column];
System.out.println("Enter the array please");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
numArray[i][j] = Reading.nextDouble();
//i is the row and j is the column
}
}
mylocation = locateLargest(numArray);
int temp = (int)mylocation.maxValue; //this is to print out the difference between int and double(decimal)
if (temp == mylocation.maxValue)
System.out.println("Highest Number: " +(int)mylocation.maxValue); //(int forces to be an integer then the double it was, eliminate decimal places)
else
System.out.println("Highest Number: " +mylocation.maxValue); //print out with decimal
System.out.println("Position: (" + mylocation.row+", " + mylocation.column +")");
Reading.close();
}
public static Location locateLargest(double[][] a)
{
Location mylocation = new Location(); //this is where we are going to store my information in
mylocation.maxValue = a[0][0]; //this is the max value to the first number
mylocation.row = 0;
mylocation.column = 0;
for (int i = 0; i < a.length; i++) //Length of the row; how many row there are
{
for (int j = 0; j < a[0].length; j++) //Length of a row; how many column in that row
//we added array here in the second because we want of get the length of the second dimension
//.length get the length of the current dimension , so a.length get the length of the first dimension
{
if (mylocation.maxValue < a[i][j] )
{
mylocation.maxValue = a[i][j];
mylocation.row = i;
mylocation.column = j;
}
}
}
return mylocation;
}
}
how can i reprogram this with the new instruction that was in the assignment box above that require me to but all the coding into one class = 1 java file? I tried almost everything And could not get the results i want.
One java file only allows one public class file. Remove public keyword from the first java file, and put them into the same file as the second one will work.
class Location {
int row; //blue variable = class variable
int column;
double maxValue;
}

Categories

Resources