Sort 2D array by average value of each line - java

I have complex task to differently sort two dimensional array manually.
So far I get done those tasks:
User needs to input row size from 10 - 20,
Generate 2D array where row size is user input and column size is randomly generated from 10-50,
Each array is filled with randomly generated numbers from 100 - 999,
Output each array row by its descending value,
Output average value of each array line,
Output on screen array with biggest average value,
So far I can't solve task Nr. 7. Output sorted two dimensional array by each lines average value.
Tried to implement new arrayAverage in loop to sort lines it didn't work.
Array just need to be sorted without creating new array.
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class SortArray2D {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Sorting two dimensional arrays!!!");
System.out.print("Enter arrays 1st dimension size 10 - 20: ");
int array1stDsize = sc.nextInt();
int array2ndDsize = new Random().nextInt(40) + 10;
System.out.println();
sc.close();
if (array1stDsize > 20 || array1stDsize < 10) {
System.out.println("The number you entered is too big or too small!!!");
} else {
//initializing array
int[][] array = new int[array1stDsize][array2ndDsize];
for (int i = 0; i < array.length; i = i + 1) {
for (int j = 0; j < array[i].length; j = j + 1) {
int input = new Random().nextInt(900) + 100;
array[i][j] = input;
}
}
System.out.println("Array element output: ");
arrayOutput(array);
// array element sorting from biggest to smallest
for (int k = 0; k < array.length; k++) {
for (int i = 1; i < array[k].length; i++) {
for (int j = i; j > 0; j--) {
if (array[k][j] > array[k][j - 1]) {
int element = array[k][j];
array[k][j] = array[k][j - 1];
array[k][j - 1] = element;
}
}
}
}
System.out.println();
System.out.println("Descending Array element output: ");
arrayOutput(array);
System.out.println();
System.out.println("Average value output by array: ");
float[] arrayAverage = new float[array1stDsize];
float average = 0;
for (int i = 0; i < array.length; i = i + 1) {
for (int j = 0; j < array[i].length; j = j + 1) {
average = average + array[i][j];
}
average = (float) (Math.round((average / array[i].length) * 100.0) / 100.0);
System.out.println(i + ". array average value: " + average);
arrayAverage[i] = average;
}
System.out.println();
System.out.println("New array from average values: ");
System.out.println(Arrays.toString(arrayAverage));
System.out.println();
System.out.println("Most valuest array is: ");
double max = 100;
int row = 0;
for (int i = 0; i < arrayAverage.length; i++) {
if (max < arrayAverage[i]) {
max = arrayAverage[i];
row = i;
}
}
System.out.print("Its founded " + row + ". row and it's value is: ");
for (int j = 0; j < array[row].length; j = j + 1) {
System.out.print(" " + array[row][j]);
}
System.out.println();
System.out.println();
//2D array sorting by average values
}
}
public static int[][] arrayOutput(int[][] array) {
for (int i = 0; i < array.length; i = i + 1) {
for (int j = 0; j < array[i].length; j = j + 1) {
if (j == 0) {
System.out.print("{ " + array[i][j]);
} else {
System.out.print(", " + array[i][j]);
}
}
System.out.print(" }");
System.out.println();
}
return array;
}
}

The part of your code that calculates the average:
float[] arrayAverage = new float[array1stDsize];
float average = 0;
for (int i = 0; i < array.length; i = i + 1) {
for (int j = 0; j < array[i].length; j = j + 1) {
average = average + array[i][j];
}
average = (float) (Math.round((average / array[i].length) * 100.0) / 100.0);
System.out.println(i + ". array average value: " + average);
arrayAverage[i] = average;
}
is slightly wrong, you need to set the average variable to zero before calculating the average of the next rows:
...
arrayAverage[i] = average;
average = 0;
With the Java Streams one can get the matrix sorted by average of rows pretty elegantly, namely:
Arrays.sort(array, comparingDouble(row -> IntStream.of(row)
.average()
.getAsDouble()));
To sort the array one uses the method Arrays.sort, and then for each row one gets its average as a double value IntStream.of(row).average().getAsDouble(), and used as the sorting parameter comparingDouble(....).
A running example:
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.IntStream;
import static java.util.Comparator.comparingDouble;
public class Test {
public static void main(String[] args) {
int array[][] = {{10, 20, 30},{40, 50, 60}, {1,2,3} };
Arrays.sort(array, comparingDouble(row -> IntStream.of(row).average().getAsDouble()));
Arrays.stream(array).map(Arrays::toString).forEach(System.out::println);
}
}
The output:
[1, 2, 3]
[10, 20, 30]
[40, 50, 60]
For the reverse order use instead:
Arrays.sort(array, comparing(row -> IntStream.of(row).average().getAsDouble(), reverseOrder()));
The output:
[40, 50, 60]
[10, 20, 30]
[1, 2, 3]
EDIT: WITH NO STREAMS
Without using streams what you can do is the following:
1 - Get the array with the averages of the matrix rows:
float[] arrayAverage = average(matrix);
You already know how to calculate the average, therefore you just need to extract a method out of the code that you have created, namely:
private static float[]average(int[][] array) {
float[] arrayAverage = new float[array.length];
float sum = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
sum += array[i][j];
}
arrayAverage[i] = (float) (Math.round((sum / array[i].length) * 100.0) / 100.0);
sum = 0;
}
return arrayAverage;
}
2 - Create an array that will represent the rows and initialized as the following:
int [] row_position = new int [arrayAverage.length];
for(int i = 0; i < row_position.length; i++)
row_position[i] = i;
3 - Sort the arrayAverage using the easiest sort, the bubble sort. While sorting that array update accordingly the positions stored on the row_position:
for(int i=0; i < arrayAverage.length; i++){
for(int j=1; j < (arrayAverage.length-i); j++){
if(arrayAverage[j-1] > arrayAverage[j]){
float temp = arrayAverage[j-1];
arrayAverage[j-1] = arrayAverage[j];
arrayAverage[j] = temp;
int temp_pos = row_position[j-1];
row_position[j-1] = row_position[j];
row_position[j] = temp_pos;
}
}
}
4 - Now that you have the row_positions array that tells you how the sorted rows should be rearranged, you just need to swap the rows accordingly:
int[][] tmp_matrix = new int [matrix.lenght][];
for (int i = 0; i < tmp_matrix.length; i++) {
tmp_matrix[i] = matrix[row_position[i]];
}
matrix = new_matrix;
Bear in mind, however, that for simplicity-sake I have assumed a quadratic matrix of NxN, and the above solution can be improved performance-wise.

At last, made it to work, looks like this.
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class SortArray2D {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Sorting two dimensional arrays!!!");
System.out.print("Enter arrays 1st dimension size 10 - 20: ");
int array1stDsize = sc.nextInt();
System.out.println();
sc.close();
if (array1stDsize > 20 || array1stDsize < 10) {
System.out.println("The number you enteraed is too big or too small!!!");
} else {
int[][] array = new int[array1stDsize][];
Random random = new Random();
for (int i = 0; i < array.length; i++) {
array[i] = new int[random.nextInt(31) + 10];
for (int j = 0; j < array[i].length; j++) {
int input = new Random().nextInt(900) + 100;
array[i][j] = input;
}
}
System.out.println("Array element output: ");
arrayOutput(array);
// array element sorting from biggest to smallest
for (int k = 0; k < array.length; k++) {
for (int i = 1; i < array[k].length; i++) {
for (int j = i; j > 0; j--) {
if (array[k][j] > array[k][j - 1]) {
int element = array[k][j];
array[k][j] = array[k][j - 1];
array[k][j - 1] = element;
}
}
}
}
System.out.println();
System.out.println("Descending Array element output: ");
arrayOutput(array);
System.out.println();
System.out.println("Average value output by array: ");
float[] arrayAverage = new float[array1stDsize];
for (int i = 0; i < array.length; i = i + 1) {
float sum = 0;
for (int j = 0; j < array[i].length; j = j + 1) {
sum = sum + array[i][j];
}
float average = (float) (Math.round((sum / array[i].length) * 100.0) / 100.0);
System.out.println(i + ". array average value: " + average);
arrayAverage[i] = average;
}
// array lines sorting from by average value increasing
for (int i = 0; i < arrayAverage.length; i = i + 1) {
for (int j = i; j > 0; j--) {
if (arrayAverage[j] < arrayAverage[j - 1]) {
float tmpor = arrayAverage[j];
arrayAverage[j] = arrayAverage[j - 1];
arrayAverage[j - 1] = tmpor;
int[] tmp = array[j];
array[j] = array[j - 1];
array[j - 1] = tmp;
}
}
}
System.out.println();
System.out.print("Array from average values sorted: ");
System.out.println(Arrays.toString(arrayAverage));
System.out.println();
System.out.println("Incerasing Array line output: ");
arrayOutput(array);
System.out.println();
System.out.print("Most valuest array is array: ");
double max = 100;
int row = 0;
for (int i = 0; i < arrayAverage.length; i++) {
if (max < arrayAverage[i]) {
max = arrayAverage[i];
row = i;
}
}
for (int j = 0; j < array[row].length; j = j + 1) {
System.out.print(" " + array[row][j]);
}
}
}
public static int[][] arrayOutput(int[][] array) {
for (int i = 0; i < array.length; i = i + 1) {
for (int j = 0; j < array[i].length; j = j + 1) {
if (j == 0) {
System.out.print("{ " + array[i][j]);
} else {
System.out.print(", " + array[i][j]);
}
}
System.out.print(" }");
System.out.println();
}
return array;
}
}

Output sorted 2d array in ascending order:
int[][] arr = {
{12, 54, 87}, // avg 51
{98, 56, 32}, // avg 62
{19, 73, 46}}; // avg 46
Arrays.stream(arr)
// sort an array by the
// average value of the row
.sorted(Comparator.comparingDouble(row ->
// get the average value or 0 if the row is empty {}
Arrays.stream(row).average().orElse(0)))
// string representation
// of the row content
.map(Arrays::toString)
// output line by line
.forEach(System.out::println);
Output:
[19, 73, 46]
[12, 54, 87]
[98, 56, 32]

Related

Java How do i repeat sort until no swaps are done in bubblesort?

I am taking 10 elements and performing a bubble sort on them. I want to add an algorithm that repeats the sort until no swaps are needed to make this more efficient.
Essentially I want to:
repeat until no swaps done in a pass
For elements 1 to (n-1)
compare contents of element value 1 with the contents of the next value
if value 1 is greater than value 2
then swap the values
This is what I have done so far :
{
//create array
int[] iList = new int[10];
Scanner sc = new Scanner(System.in);
//takes in array input for 10 numbers
System.out.println("Enter a array of numbers ");
for(int i = 0; i< 10; i++ )
{
int num = i + 1;
System.out.println("Enter number " + num);
iList[i] = sc.nextInt();
}
//Bubble sorts the array
System.out.println("The array =");
for(int a = 0; a < iList.length; a++ )
{
for(int b = a+1; b < iList.length; b++)
{
if(iList[a] > iList[b])
{
int iTemp = iList[a];
iList[a] = iList[b];
iList[b] = iTemp;
}
System.out.println("Progress = " + Arrays.toString(iList) );
}
}
} ```
Here is my implementation :
public static void sort(int[] nums) {
boolean isSwapped;
int size = nums.length - 1;
for (int i = 0; i < size; i++) {
isSwapped = false;
for (int j = 0; j < size - i; j++) {
if (nums[j] > nums[j+1]) {
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
isSwapped = true;
}
}
if (!isSwapped) break;
}
System.out.println("Sorted Array: " + Arrays.toString(nums));
}

How would I calculate the average in a 2D Array?

To start, I'm not completely new to Java and I have taken a course on it. Recently, I picked it up a again after a year and I'm a bit confused as to how to calculate an average in a 2D array of integers. For example, here's an excerpt of code not including the average calculation:
//Program fills array with x students and their corresponding test grades for n amount of tests
System.out.println("Amount of students?");
int numstudents = sc.nextInt();
System.out.println("Amount of tests?");
int numtests = sc.nextInt();
int[][] marks = new int [numstudents][numtests];
int[] average = new int [numstudents];
for (int i = 0; i < numstudents; i++) {
for (int j = 0; j < numtests; j++) {
System.out.println("Enter the mark for student " + (i+1) + " on test " + (j+1));
marks[i][j] = sc.nextInt();
//Array is filled with grades.
}
}
Now let's say I wanted to calculate the average for each student and store the values in the average[] array. My main problem is figuring out how to loop it so that it includes every test for marks[0][j] and then moves on to marks[1][j] and so on. If I do something like the code below, it takes each test value and divides it by numtests.
for (int i = 0; i < numstudents; i++) {
for (int j = 0; j < numtests; j++) {
average[i] = marks[i][j]/numtests;
System.out.println("The average is " + average[i]);
}
}
I think average[i] should be calculated
for (int i = 0; i < numstudents; i++) {
//here
for (int j = 0; j < numtests; j++) {
}
How about writing codes like as follows?
int eachsum = 0;
for (int i = 0; i < numstudents; i++) {
for (int j = 0; j < numtests; j++) {
eachsum += marks[i][j];
}
average[i] = eachsum/numtests;
System.out.println("The average for student " + (i+1) + " is " + average[i]);
eachsum = 0;
}
You can do the following:
int[] average = Arrays.stream(marks)
.map(ints -> Arrays.stream(ints).summaryStatistics().getAverage())
.mapToLong(Math::round)
.mapToInt(Math::toIntExact)
.toArray();
Input:
int[][] marks = {
{80, 70 ,90},
{90, 65 ,90},
{50, 70 ,70},
{80, 75 ,85}
};
Output:
[80,
82,
63,
80]

How to get the sum for each row?

I want to find and display the row number that has the maximum sum and display the row values and this is sample input/output:
The problem is every time the maximum sum is the third row how to solve these issues.
int [][] scores = new int[4][3];
for (int i=0; i<scores.length; i++)
{
System.out.print("Enter values for row "+i+": ");
for (int j=0; j<scores[i].length;j++)
scores[i][j] = kbd.nextInt();
}
int sum, sumMax, ii=0;
for (int i=0; i<scores.length; i++)
{
sum =0; sumMax = 0; ii=0;
for (int j=0; j<scores[i].length;j++)
{
sum += scores[i][j];
if (sum>sumMax)
{
sumMax = sum;
ii = i;
}
}
}
System.out.println("Row "+ii+" has the maximum sum");
System.out.print("Row "+ii+" has the following values: ");
for (int j = 0; j < 3; j++)
System.out.print(scores[ii][j] + " ");
To print a specific row, you need one loop only
System.out.print("Row " + ii + " has the following values: ");
for (int j = 0; j < 3; j++)
System.out.print(scores[ii][j] + " ");
Or with Arrays.toString
System.out.println("Row " + ii + " has the following values: " + Arrays.toString(scores[ii]));
Also your finding max code is wrong, as you reset ii and sumMax to 0 for each row, the max can only be the last line, you need to keep track of these 2 along the rows. Also use the if only after computing the row's sum, no need to test at every bow of every row
int sum, sumMax = Integer.MIN_VALUE, ii = 0;
for (int i = 0; i < scores.length; i++) {
sum = 0;
for (int j = 0; j < scores[i].length; j++) {
sum += scores[i][j];
}
if (sum > sumMax) {
sumMax = sum;
ii = i;
}
}
You can add the rows while getting the input from scanner and store them in an array. Then you can search for the max value in the sums array:
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
int[][] scores = new int[4][3];
int[] rowSums = new int[4];
for (int i = 0; i < scores.length; i++) {
System.out.print("Enter values for row " + i + ": ");
for (int j = 0; j < scores[i].length; j++){
scores[i][j] = kbd.nextInt();
rowSums[i] += scores[i][j];
}
}
int index = 0;
int maxSum = rowSums[index];
for(int i = 1; i < rowSums.length; i++){
if(rowSums[i] > maxSum){
maxSum = rowSums[i];
index = i;
}
}
System.out.println("Row "+index+" has the maximum sum");
System.out.print("Row "+index+" has the following values: ");
for(int i = 0; i < scores[index].length; i++){
System.out.print(scores[index][i] + " ");
}
}
}

How to do selection sorting in Java?

Here is the my code for a project I am working on for class:
import java.lang.reflect.Array;
public class Project10_MaryEvans {
public static void main(String[] args) {
int[] numbers = {2, 7, 5, 3, 4, 9, 8, 10, 1, 6};
int i = 0;
final int NUMBERS_SIZE = 10;
System.out.print("Unsorted: ");
for (i = 0; i < NUMBERS_SIZE; ++i){
System.out.print(numbers[i] + " ");{
System.out.println();
}
sorting(numbers, NUMBERS_SIZE);
System.out.print("Sorted: ");
for(i = 0; i < NUMBERS_SIZE; ++i){
System.out.print(numbers[i] + " ");
}
System.out.println();
return;
}
}
public static int[] shuffle(int[] numbers){
for(int i = 0; i < numbers.length; ++i) {
numbers[i] = (int)Math.random() * numbers[i];
}
return numbers;
}
public static void sorting(int[] numbers, int numberSize) {
int i = 0;
int j = 0;
int indexSmallest = 0;
int temp = 0;
for (i = 0; i < numberSize; ++i) {
indexSmallest = i;
for(j = i + 1; j < numberSize; ++j) {
if(numbers[j] < numbers[indexSmallest]) {
indexSmallest = j;
}
}
}
}
}
I am not getting the correct output. My output is:
Unsorted: 2
Sorted: 2 7 5 3 4 9 8 10 1 6
I'm juste gonna give you tips here:
Use Arrays.toString(numbers) to print your array easily.
Use numbers.length to get the size of the numbers array.
(the most important one) Your sorting doesn't actually do any sorting, you just set indexes values, but you don't modify the array numbers (numbers[i] = numbers[j] for example).
Your first loop (in main) is useless.
And read the comments.
maybe you have make two for loop nested in your main function, it should be like
System.out.print("Unsorted: ");
for (i = 0; i < NUMBERS_SIZE; ++i){
System.out.print(numbers[i] + " ");
}
System.out.println();
sorting(numbers, NUMBERS_SIZE);
System.out.print("Sorted: ");
for(i = 0; i < NUMBERS_SIZE; ++i){
System.out.print(numbers[i] + " ");
}
System.out.println();
return;
In your sorting function you're forgetting to exchange current element with the minimal found. You're just computing indexes.
Use this method for sorting. Not need int numberSize parameter. It can get through array length. If you need int numberSize parameter replace numbers.length with numberSize.
public static void sorting(int[] numbers) {
int temp;
for (int i = 0; i < numbers.length; i++) {
for (int j = i + 1; j < numbers.length; j++) {
if (numbers[i] > numbers[j]) {
temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
}
Main Method:
public static void main(String[] args) {
int[] numbers = {2, 7, 5, 3, 4, 9, 8, 10, 1, 6};
int i = 0;
final int NUMBERS_SIZE = 10;
System.out.print("Unsorted: ");
for (i = 0; i < NUMBERS_SIZE; ++i){
System.out.print(numbers[i] + " ");
}
System.out.println();
sorting(numbers);
System.out.print("Sorted: ");
for(i = 0; i < NUMBERS_SIZE; ++i){
System.out.print(numbers[i] + " ");
}
}

Problems Sorting a two column array and outputting value frequency in Java

Here is the problem I have, I spent a long time toying with for loops and arrays and temp variables, and now my output is just a couple numbers.
/*
Write a program that reads numbers from the keyboard into an array of type int[].
You may assume that there will be 50 or fewer entries in the array. Your program
allows any number of numbers to be entered, up to 50. The output is to be a
two-column list. The first column is a list of the distinct array elements;
the second is the count of the number of occurrences of each element.
The list should be sorted on entries in the first column, largest to smallest.
For the array:
-12, 3, -12, 4, 1, 1, -12, 1, -1, 1, 2, 3, 4, 2, 3, -12
the output should be:
N Count
4 2
3 3
2 2
1 4
-1 1
-12 4
*/
import java.util.Scanner;
public class Project2C {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[][] twoColumn = new int[2][50];
int[] inputValues = new int[50];
int temp = 0;
int valueFrequency = 0;
int lastUsedSpace = 0;
//gather user input to fill an array (up to 50 values);
System.out.println("Input up to 50 values.");
for (int i = 0; i < 50; i++) {
System.out.println("value #" + (i + 1) + ":");
inputValues[i] = keyboard.nextInt();
/*System.out.println("Press 0 to stop, or 1 to continue.");
if (keyboard.nextInt() == 0) {
break;
}
else if (keyboard.nextInt() == 1){
continue;
}
else if (keyboard.nextInt() != 0 && keyboard.nextInt() != 1) {
System.out.println("You must enter 0 or 1. Now you must re-enter the value.");
i--;
}*/
}
// checking if each value occurs more than once, and assigning it a place
// in the two column array if it is unique.
for (int i = 0; i < inputValues.length; i++) {
for (int j = 0; j < inputValues.length; j++) {
if (i == 0 && inputValues[i] != inputValues[j]) {
twoColumn[0][lastUsedSpace] = inputValues[i];
} else if (i > 0 && inputValues[i] != inputValues[j]) {
twoColumn[0][lastUsedSpace + 1] = inputValues[i];
}
}
}
lastUsedSpace = -1;
//Sorting the first column of the two column array
for (int i = 0; i < twoColumn.length; i++) {
for (int j = 0; j < twoColumn.length; j++) {
if (twoColumn[0][i] < twoColumn[0][j + 1]) {
temp = twoColumn[0][j + 1];
twoColumn[0][j + 1] = twoColumn[0][i];
twoColumn[0][i] = temp;
}
}
}
// filling in the frequency column of the array
for (int i = 0; i < inputValues.length; i++) {
for (int j = 0; j < inputValues.length; j++) {
if (inputValues[i] == inputValues[j]) {
valueFrequency = valueFrequency + 1;
}
if (j <= inputValues.length - 1 && lastUsedSpace == -1) {
lastUsedSpace = 0;
twoColumn[1][0] = valueFrequency;
valueFrequency = 0;
} else if (j <= inputValues.length - 1 && lastUsedSpace > -1) {
twoColumn[1][lastUsedSpace + 1] = valueFrequency;
valueFrequency = 0;
}
}
}
//printing output
for (int i = 0; i < twoColumn.length; i++) {
System.out.println("Input Frequency");
System.out.println(twoColumn[0][i]+" "+twoColumn[1][i]);
}
}
}
}
there I tested and fixed it you should take out the -999 jazz if you want the user to have to go through the whole 50
import java.util.Arrays;
import java.util.Scanner;
public class swinging {
static Scanner keyboard = new Scanner(System.in);
static int[] inputValues = new int[50];
int temp = 0;
int valueFrequency = 0;
int lastUsedSpace = 0;
public static void main(String[] args){
int j = 0;
for (; j < 50; j++) {
System.out.println("value #" + (j + 1) + ":");
inputValues[j] = keyboard.nextInt();
if(inputValues[j]==-999)break;
}
theValues= bubbleSort(Arrays.copyOf(inputValues, j));
for (int i = 0; i < theValues.length; i++) {
System.out.println("Input Frequency");
System.out.println(theValues[i]+" "+howMany[i]);
}
}
static int[] theValues;
static int[] howMany;
public static int[] bubbleSort(int[] Is ){
boolean switchedOne=true;
int temp;
howMany=new int[Is.length];
Arrays.fill(howMany,1);
int length=Is.length-1;
while(switchedOne){switchedOne=false;
for(int i=0;i<length;i++){
if(Is[i]>Is[i+1]){temp=Is[i];Is[i]=Is[i+1];Is[i+1]=temp;switchedOne=true;
temp=howMany[i];howMany[i]=howMany[i+1];howMany[i+1]=temp;}
if(Is[i]==Is[i+1]){Is=removeElement(Is,i+1);howMany=removeElement(howMany,i+1);howMany[i]++;length--;}
}
}
return Is;
}
public static int[] removeElement(int[] Is,int index){
for(int i=index;i<Is.length-1;i++){Is[i]=Is[i+1];}
return Arrays.copyOf(Is,Is.length-1);
}}
In case you are not playing with loops and wish to solve the problem on a higher-level, you could use a TreeMap and NavigableMap. See example below.
// ArrayGroupByCount.java
package com.geoloo.array;
import java.util.HashMap;
import java.util.NavigableMap;
import java.util.Scanner;
import java.util.TreeMap;
/*
* Description: Display occurence of entered numbers in descending order
* Sample input/output:
Input up to 50 values. 0 to exit
value #1:-12
value #2:3
value #3:-12
value #4:4
value #5:1
value #6:1
value #7:-12
value #8:1
value #9:-1
value #10:1
value #11:2
value #12:3
value #13:4
value #14:2
value #15:3
value #16:-12
value #17:0
map: {1=4, 2=2, 3=3, 4=2, -12=4, -1=1}
nmap: {4=2, 3=3, 2=2, 1=4, -1=1, -12=4}
*/
public class ArrayGroupByCount {
public static void main(String[] args) {
Integer input = 0;
Scanner keyboard = new Scanner(System.in);
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
TreeMap<Integer, Integer> treemap = new TreeMap<Integer, Integer>();
System.out.println("Input up to 50 values. 0 to exit");
for (int i = 0; i < 50; i++) {
System.out.print("value #" + (i + 1) + ":");
input = (int)keyboard.nextInt();
if(input==0){
break;
}
int content = 0;
if(map.containsKey(input))
content = map.get(input);
map.put(input, content+1);
}
keyboard.close();
treemap.putAll(map);
NavigableMap<Integer, Integer> nmap=treemap.descendingMap();
System.out.println("map: "+map);
System.out.println("nmap: "+nmap);
}
}
package project2c;
import java.util.Scanner;
public class Project2C {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int valueAmount = 0;
int temp = 0;
int valueFrequency = 1;
//gather user input to fill an array (up to 50 values);
System.out.println("how many values would you like to process?");
valueAmount = keyboard.nextInt();
int[] inputValues = new int[valueAmount];
for (int i = 0; i < valueAmount; i++) {
System.out.println("value #" + (i + 1) + ":");
inputValues[i] = keyboard.nextInt();
}
//sort values in descending order
for (int i = 0; i < inputValues.length - 1; i++) {
for (int j = 0; j < inputValues.length - 1; j++) {
if (inputValues[j + 1] > inputValues[j]) {
temp = inputValues[j + 1];
inputValues[j + 1] = inputValues[j];
inputValues[j] = temp;
}
}
}
//print out put
System.out.println();
System.out.println("Value Frequency");
for (int i = 0; i < inputValues.length - 1; i++) {
if (inputValues[i] == inputValues[i + 1]) {
valueFrequency = valueFrequency + 1;
} else if (inputValues[i] > inputValues[i + 1]) {
System.out.println(inputValues[i] + " " + valueFrequency);
valueFrequency = 1;
}
}
}
}

Categories

Resources