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] + " ");
}
}
Related
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]
I was asked to write, to remove the element (lets say k=30) from the array and shift the other elements to its left without using inbuilt methods.
I have tried the below approach.
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = new int[] { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int count = 0;
System.out.println("---Original Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k)
count++;
}
for (int j = 0; j < count; j++) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k) {
for (int l = i; l < arr.length - 1; l++) {
arr[l] = arr[l + 1];
}
}
}
}
System.out.println("---Modified Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
I need output like this: [1 2 4 5 6 0 0]
But the output from the above logic is: [1 2 4 5 6 6 6]
Also, I'm worried about using nested for loops here. Is there any way that we can reduce the time complexity with out using any inbuilt methods?
Here is another variant:
int[] arr = new int[] { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int j = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != k) {
arr[j++] = arr[i];
}
}
while (j < arr.length) {
arr[j++] = 0;
}
In order to not change your approach drastically, I would suggest adding another iteration of the array at the end, to insert 0s to count-many indices from the end of your array.
This would be as simple as adding the following snippet:
// nested for loop
// ...
// set trailing elements to 0s
for (int i = 0; i < count ; i++)
arr[arr.length-1-i] = 0;
System.out.println("\n---Modified Array------");
// ...
There are some cleaner/more-efficient ways of solving this problem.
Based exactly on your approach, I went ahead and made a modification to your nested loop to not require another iteration.
for (int j = 0; j < count; j++) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k) {
for (int l = i; l < arr.length - 1; l++)
arr[l] = arr[l + 1];
// since we have performed the shifting, we can safely set the last element to 0
arr[arr.length-1] = 0; // <----- this was missing!!
}
}
}
The following code gives the desired result:
int [] arr = { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int elementCount = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k) {
++elementCount;
}
}
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k) {
count++;
for (int j = i; j < arr.length-1; j++) {
arr[j] = arr[j+1];
}
arr[arr.length-1] = 0;
}
if (count == elementCount) {
break;
}
}
I don't know if it helps. This is a simplified aproach, that is easier to read and understand(at least for people that learned C), that does removal as required....
public static void main(String[] args) {
int[] arr = new int[] { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int i=0;
int j=0;
for(;j<arr.length;i++,j++){
if((arr[i]=arr[j])==k) i--;
}
while(i<j)arr[i++]=0;
System.err.println(Arrays.toString(arr));
}
output:[1, 2, 4, 5, 6, 0, 0]
First version with a small fix on your code. You issue is that the shifted elements need to be replaced by zero. Which require basically an if statement with the arr.length - count
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = new int[] { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int count = 0;
System.out.println("---Original Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k)
count++;
}
for (int j = 0; j < count; j++) {
for (int i = 0; i < arr.length; i++) {
if(i >= arr.length - count){
arr[i] = 0;
}else {
if (arr[i] == k) {
for (int l = i; l < arr.length - 1; l++) {
arr[l] = arr[l + 1];
}
}
}
}
}
System.out.println("---Modified Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
}
Which gives output
---Original Array------
1 2 30 4 5 30 6
---Modified Array------
1 2 4 5 6 0 0
Now, we can simplify the code also
public static void main(String[] args) {
int[] arr = new int[] { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int count = 0;
System.out.println("---Original Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
for(int i = 0; i < arr.length; i++){
if(arr[i]==k){
count++;
}else{
arr[i-count] = arr[i];
}
}
for(int i = 1; i <= count; i++){
arr[arr.length - i] = 0;
}
System.out.println("---Modified Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
}
which give the same output
How to calculate amount of COLUMNS containing zero, in a multidimensional array.
The number of rows containing zeros I was able to calculate, but I can not understand how to calculate amount of columns. Please, help.
public class Main {
public static void main (String[] args) {
int i;
int j;
int count = 0;
int [][] arr = {{3, 0, 0, 6}, {4, 0, 1, 1}};
for (i = 0; i < arr.length; i++) {
System.out.println();
for (j = 0; j < arr[i].length; j++){
System.out.print(arr[i][j] + ", ");
}
}
System.out.println();
//-----------------------------------------------------------
for (i = 0; i<arr.length; i++) {
for (j = 0; j<arr[i].length; j++) {
if (arr[i][j] == 0) {
count++;
break;
}
}
}
System.out.println("the amount of rows containing zeros = " + count);
}
}
Another straightforward way to get the same result for a sqaure matrix:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int i;
int j;
int count = 0;
int [][] arr = {{3, 0, 0, 6}, {4, 0, 1, 0}};
for (i = 0; i < arr.length; i++)
{
System.out.println();
for (j = 0; j < arr[i].length; j++)
{
System.out.print(arr[i][j] + ", ");} }
System.out.println();
//--------------------------------------------------------------------
for (i = 0; i<arr.length; i++)
for (j = 0; j<arr[i].length; j++)
if (arr[i][j] == 0)
{
count++;
break;
}
System.out.println("the amount of rows containing zeros = " + count);
//--------------------------------------------------------------------
count=0;
for (i = 0; i<arr[0].length; i++)
for (j = 0; j<arr.length; j++)
if (arr[j][i] == 0)
{
count++;
break;
}
System.out.println("the amount of cols containing zeros = " + count);
}
}
Output:
3, 0, 0, 6,
4, 0, 1, 0,
the amount of rows containing zeros = 2
the amount of cols containing zeros = 3
http://ideone.com/VE0qAw
I have an error in my code, since it is not printing all of the elements of the array after it's been sorted. Can someone spot it and help me out? (I am only in my 5th week of Java, so definitely a newbie!)
public class Test01 {
public static void main(String[] args) {
int[] arr = {1, 3, 5, 4, 2};
for (int i = 0; i < arr.length - 1; i++) {
int currentMin = arr[i];
int currentMinIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (currentMin > arr[j]){
currentMin = arr[j];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
arr[currentMinIndex] = arr[i];
arr[i] = currentMin;
}
System.out.print(arr[i] + " ");
}
}
}
The current output for this is:
1 2 3 4
So I am just missing printing the '5'
thanks for the help!
You are running the loop an index short. Change
for (int i = 0; i < arr.length - 1; i++) { // The -1 is the issue
to
for (int i = 0; i < arr.length ; i++) {
public class Test01 {
public static void main(String[] args) {
int[] arr = {1, 3, 5, 4, 2};
for (int i = 0; i < arr.length; i++) {
int currentMin = arr[i];
int currentMinIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (currentMin > arr[j]){
currentMin = arr[j];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
arr[currentMinIndex] = arr[i];
arr[i] = currentMin;
}
System.out.print(arr[i] + " ");
}
}
}
im looking for a way to print the array as is after each pass. this is the sort code i have so far. its a basic implementation of the bubble sort algorithm that prints out the original state of the array and the sorted state
public class bubbleSortTest
{
public static void main(String a[])
{
int i;
int array[] = {90, 8, 7, 56, 123, 235, 9, 1, 653};
System.out.println("Values Before the sort:\n");
for(i = 0; i < array.length; i++)
System.out.print( array[i]+" ");
System.out.println();
bubble_srt(array, array.length);
System.out.print("Values after the sort:\n");
for(i = 0; i <array.length; i++)
System.out.print(array[i]+" ");
System.out.println();
System.out.println("PAUSE");
}
public static void bubble_srt( int a[], int n )
{
int i, j,t=0;
for(i = 0; i < n; i++)
{
for(j = 1; j < (n-i); j++)
{
if(a[j-1] > a[j])
{
t = a[j-1];
a[j-1]=a[j];
a[j]=t;
}
}
}
}
}
Add a new for loop inside the outer loop of sorting to print the values after each pass.
for(i = 0; i < n; i++)
{
System.out.print(" After "+(i+1)+"st pass: ");
for(k=0;k<n;k++)
System.out.print(" "+a[k]);
...............
...............