Sort Java array while adding numbers - java

I apologize for my english. So far I got this code that sort an array. The user input 10 numbers and after that, the program makes the sorting. But what I want is that every time the user inputs a number, the program immediately makes the sort. How can I do that?
For example, if I input 5 and then 3, immediately takes the 3 to the first position. And then if I put 2, immediately take it to the first position and sort the others (2,3,5). Then if I put 1, takes it to the first position, sorting the others(1,2,3,5) and so on.
import java.util.Scanner;
public class Nine{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int temp = 0;
int[] num = new int[10];
for(int i = 0; i < 10; i++){
System.out.print("Número: ");
num[i] = input.nextInt();
}
System.out.println();
for(int i = 0; i < 10; i++){
System.out.print(num[i] + " ");
}
System.out.println();
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10 - i - 1; j++){
if(num[j+1] < num[j]){
temp = num[j+1];
num[j+1] = num[j];
num[j] = temp;
}
}
}
System.out.println();
for(int i = 0; i < 10; i++){
System.out.print(num[i] + " ");
}
}
}
Now I have this code and it works. It does what I wanted to do. But to me it's a little bit complicated. I'm still a beginner. I understand what it does but is there a better way to do it. An easier way? Thanks
import java.util.Scanner;
public class practice {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] num = new int[10];
int n = 0, l = 0, t = 0;
for(int i = 0; i < num.length; i++){
System.out.print("Número: ");
n = input.nextInt();
l = 0;
while(num[l] < n && l < i){
l = l + 1;
}
t = i;
while(t > l){
num[t] = num[t - 1];
t = t - 1;
}
num[l] = n;
for(int temp : num){
System.out.print(temp + " ");
}
System.out.println();
}
}
}

here you go
public class TestProgram {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int temp = 0;
int[] num = new int[10];
for (int b = 0; b < 10; b++) {
System.out.println("Número: ");
num[b] = input.nextInt();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10 - i - 1; j++) {
if (num[j + 1] < num[j]) {
temp = num[j + 1];
num[j + 1] = num[j];
num[j] = temp;
}
}
}
System.out.println();
for (int k = 0; k < 10; k++) {
System.out.println(num[k] + " ");
}
}
}
}

To do this create a sort method which you can call to sort an array then return a new sorted array. Next every time a user inputs run a for loop which will create an array with the current amount entered. While entering just use i+1. Finally, with the new array call the sort method and the sorted array will be returned and you can do as you wish with the new array.

You make things more difficult for yourself using an array but assuming you want to start with an array of size 10 filled with 0s (so 0 is not a valid input) the basic algorithm is to go through the currently sorted array and if the current value is less than the indexed value move all the values in the sorted array to the right and insert the current value at the current index. As others have already mentioned for larger datasets this is very inefficient but for an array of size 10 it's not a big deal.
int current = input.nextInt();
for (int j = 0; j < sorted.length; j++) {
if (sorted[j] == 0) {
sorted[j] = current;
break;
}
if (current < sorted[j]) {
for (int k = sorted.length - 1; k > j; k--) {
sorted[k] = sorted[k - 1];
}
sorted[j] = current;
break;
}
}
Here's what the output at each iteration would look like for the input 5, 3, 2, 1, 4, 10, 20, 15, 13, 5:
5 0 0 0 0 0 0 0 0 0
3 5 0 0 0 0 0 0 0 0
2 3 5 0 0 0 0 0 0 0
1 2 3 5 0 0 0 0 0 0
1 2 3 4 5 0 0 0 0 0
1 2 3 4 5 10 0 0 0 0
1 2 3 4 5 10 20 0 0 0
1 2 3 4 5 10 15 20 0 0
1 2 3 4 5 10 13 15 20 0
1 2 3 4 5 5 10 13 15 20

Related

Why does my code output an extra "0" after finding the most frequent integer in an array?

An example of integers entered would be: 5 9 2 2 1 4 5 5 -1 and my code's output is "5 0". In this example array, I only need it to display "5 ". Try it yourself with any combination of integer input, ending your input with a -1 and you'll get the most frequent integer with a zero. Any ideas why my code does this?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int[] b = new int[21];
for (int i = 0; i < b.length; ++i) { //integer input from user
b[i] = scnr.nextInt();
if (b[i] == -1) { //array input stops when input is -1
break;
}
}
int maxcount = 0;
int element_having_max_freq;
for (int i = 0; i < b.length; ++i) {
int count = 0;
for (int j = 0; j < b.length; ++j) {
if (b[i] == b[j]) {
count = count + 1;
}
}
if (count > maxcount) {
maxcount = count;
element_having_max_freq = b[i];
System.out.println(element_having_max_freq+ " ");
}
}
}
}
Your array is of size 21 and initialized as all zeros. All numbers you don't overwrite with the user input will remain zeros, which means that in the case of your test input 5 9 2 2 1 4 5 5 -1, you get another 12 zeros.
Try placing a breakpoint after the part of the code that parses the user input and have a look at b.

I need to get all even numbers from random length 2D Array and make another 2D array with even numbers I've got

My Java code get all numbers I need, but every row in new array have length like in old array. How to make array with different row length only for numbers I've got?
Please check for my code:
import java.util.Arrays;
import java.util.Random;
public class Help {
public static void main(String[] args) {
Random random = new Random();
int n = random.nextInt(10);
int m = random.nextInt(10);
if (n > 0 && m > 0) {
int[][] arr = new int[n][m];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = random.nextInt(20);
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println("***** EvenMatrix *****");
int[][] evenMatrix = new int[n][m];
int evenElement = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] % 2 != 0) {
continue;
} else
evenElement = arr[i][j];
for (int k = 0; k < arr[i].length; k++) {
evenMatrix[i][j] = evenElement;
}
System.out.print(evenMatrix[i][j] + " ");
}
System.out.println();
}
System.out.println(Arrays.deepToString(evenMatrix));
} else {
System.out.println("Incorrect array length! Try again!");
System.exit(0);
}
}
}
I wanted to help but didn't understand the question well
Let's say your random numbers are 3x3 for n and m
And let's say your array "arr" is
[1,2,3]
[4,5,6]
[7,8,9}
And you want to be your array "evenMatrix" to be
[2,4,6,8] n = 1 and m = 4
or
[2,4] n = 2 and m = 2
[6,8]
Not n = 3 m = 3 just like in the array "arr"
[2,4,6]
[8,0,0]
is that right? If so you can check n and m before creating the "evenArray" like
int[][] evenMatrix;
if(n<m)
evenMatrix = new int[m][m];
else
evenMatrix = new int[n][n];
creating a square matrix but this still has problems let's say your random numbers are n = 5 and m = 2 so this code will create a 5x5 matrix and fill with even numbers and let's say your randomize arr array doesn't have that many even numbers are so it will become something ugly
The easy solution here is to use an ArrayList, however, we can also create variable length rows using the following, note the comments below explaining the process, but the key is this int[][] evenMatrix = new int[n][];, note how we only specify the column size, not the row size.
Complete code:
System.out.println("***** EvenMatrix *****");
//Create 3D array
int[][] evenMatrix = new int[n][];
for (int i = 0; i < arr.length; i++) {
//Create inner row that we will trim later
int[] evenElements = new int[m];
//Create a counter to track variable locations
int counter = 0;
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] % 2 != 0) {
continue;
} else{
evenElements[counter] = arr[i][j];
//Incriment counter
counter++;
}
System.out.print(arr[i][j] + " ");
}
System.out.println();
//Trim the inner array to the correct length that we know from the `counter`
evenElements = Arrays.copyOf(evenElements, counter);
//Assign the inner row of variable length to the 3D matrix
evenMatrix[i] = evenElements;
}
//Print the result
System.out.println(Arrays.deepToString(evenMatrix));
Example output of the above code:
1 11 15 0 15 18 10
6 12 0 13 15 15 3
10 13 6 1 12 4 12
10 7 12 8 19 4 6
5 10 4 12 4 5 5
***** EvenMatrix *****
0 18 10
6 12 0
10 6 12 4 12
10 12 8 4 6
10 4 12 4
[[0, 18, 10], [6, 12, 0], [10, 6, 12, 4, 12], [10, 12, 8, 4, 6], [10, 4, 12, 4]]

How to search for intervals in Java

Just before I begin to annoy you, I am a Java beginner and my main issue up to date is two- ord more-dimensional arrays.
Let me represent my problem:
The task in the study was: you have an sorted array, then you type the number of how many searching operations(let them named by N) the Programm should do.
Due to this you type N x 2 different values a and b, a should be smaller than b.
The Programm should search in the sorted array for intervalls containing your a and b and print these intervalls out.
For example:
The array to search for looks like this:
[1, 3, 5, 7, 9]
then the user types in the number of operations, for example 3. Following to this the a and b couples:
3 6
2 9
1 5
The output of the programm should be according to these a and b couples:
3 7
1 9
1 5
I tried to master this exercise but as mentioned above I have problems with multidimensional arrays. At the following you can see my code and I just want tipps or specific informations about arrays to understand how they're working.
And i improved it:
import java.util.*;
public class Blatt9{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
boolean check1 = false;
int N = s.nextInt();
int[] array = new int[N];
for(int i = 0; i < array.length; i++){
array[i] = s.nextInt();
}
for(int j = 0; j < array.length; j++){
for(int k = j+1; j < array.length -1; j++){
if(array[j] < array[k]){
check1 = true;
}
else{
check1 = false;
}
}
}
if(check1){
System.out.println("nicht aufsteigend sortiert");
}
else{
System.out.println("korrekt");
}
//Beginn der eigentlichen Aufgabe
int abfragen = s.nextInt(); // Anzahl der Abfragen
int[][] arr = new int[abfragen][2]; //um die abfragen zu speichern
int a = 0;
int b = 0;
for(int i = 0; i < abfragen; i++){
a = s.nextInt();
b = s.nextInt();
if(a>b){
System.out.println("Zahl 1 muss kleiner Zahl 2 sein");
break;
}
arr[i][0] = a;
arr[i][1] = b;
}
int intervall1 = 0;
int intervall2 = 0;
for(int i = 0; i < array.length; i++){
for(int j = 0; j < arr.length; j++){
if(array[i] <= a){
intervall1 = a;
}
if(array[i]>= b){
intervall2 = b;
}
}
System.out.print(intervall1 + " " + intervall2);
System.out.println();
}
}
}
The output now is:
input:
5
1 3 5 7 9
korrekt
3
3 6
2 9
1 5
begin of output:
1 0
1 0
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5

The Sum of large Integers using Arrays

I am trying to write a program that sums up the total of two large numbers. I used two arrays for the numbers to sum up and the third array to store the result of the summation, But I am getting the wrong output, would you check?
Here is my method:
public static int [] sumBigInt(int [] A, int [] B, int n)
{
int sumPerCol = 0;
int carriedValue = 0;
int[] totalArray = new int[A.length + 1];
for(int i = A.length - 1; i >= 0; i--)
{
sumPerCol = A[i] + B[i] + carriedValue;
if( i == 0)
totalArray[i] = carriedValue;
else if(sumPerCol >= 10)
{
carriedValue = sumPerCol / 10;
totalArray[i] = sumPerCol % 10;
}
else
{
totalArray[i] = sumPerCol;
carriedValue = 0;
}
}// end of for-Loop
return totalArray;
}
**** In main, I am not getting the correct output:
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(TwoTo_n(8));
int[] arrayA = {6,9,4,6,9,1,8,9,3,5,6};
int[] arrayB = {5,9,6,4,3,1,6,7,6,9,5};
int[] arrayTest = new int[arrayA.length + 1];
for (int i = 0; i < arrayTest.length; i++)
arrayTest[i] = sumBigInt(arrayA, arrayB, 14)[i];
for (int i = 0; i < arrayTest.length; i++)
System.out.print(arrayTest[i] + " ");
}
Here is the output I get :
1 9 1 1 2 3 5 7 0 5 1 0
The output should be:
1 2 9 1 1 2 3 5 7 0 5 1 => now the digit in position 1 disappears :(
There is ONE digit missing; that digit should be added at position zero in my final array, but its not showing up.
Thank you
Your code is almost correct. In order to fix it, think what happens to carriedValue after you finish the loop:
When the loop ends, and carriedValue is zero, your program returns the correct value
When the loop ends, and carriedValue is one, the most significant digit of the result gets dropped.
All you need to do to fix this is to "shift" digit positions in your totalArray by one, and assign carriedValue to the top digit after the end of the loop:
for(int i = A.length - 1; i >= 0; i--) {
sumPerCol = A[i] + B[i] + carriedValue;
if(sumPerCol >= 10) {
carriedValue = sumPerCol / 10;
totalArray[i+1] = sumPerCol % 10;
} else {
totalArray[i+1] = sumPerCol;
carriedValue = 0;
}
}// end of for-Loop
totalArray[0] = carriedValue;
Note the use of totalArray[i+1] in place of totalArray[i]. This is because your method automatically extends the number of significant digits by one. You could change this behavior by re-allocating the array and copying data into it only when carriedValue is non-zero.
Demo.

How do I get the right output for this array?

I'm trying to obtain specific outputs for an array. The array's been put in a while loop to continue to set up new arrays until it reaches its counter. The counter and the amount of elements in each array line up, but once I try to get my output, it doesn't work out. What should I fix to work it out?
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i; int j; int n; int u;
int count = 0;
n = input.nextInt();
System.out.println("Times repeated: " + n);
while(count < n) //counter represents amount of times loop will occur
{
i = input.nextInt();
int[] numbers = new int[i];
System.out.println("Length of Array: " + i);//represents how many numbers within a line
count++;
for(j = 0; j < numbers.length; j++) //numbers within line
{
numbers[j] = input.nextInt();}
for(int p = 0; p < numbers.length - 1; p++) //prints specific values in line
{
numbers[p] = numbers[numbers.length - 1 ];
p = numbers[p];
System.out.println(p);
System.out.println(Arrays.toString(numbers)); }
input.close();}
} }
First User Input:
3
2
10
1
Expected Output:
10
Instead, I get 1. What I wanted to do was subtract the last element of the array from the rest of the array to get the desired output. This includes the last element as well.
code works fine, just need to close scanner outside while. Fix the brackets.
input.close(); outside while loop
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i;
int j;
int n;
int u;
int count = 0;
n = input.nextInt();
System.out.println("Times repeated: " + n);
while (count < n) // counter represents amount of times loop will occur
{
i = input.nextInt();
int[] numbers = new int[i];
System.out.println("Length of Array: " + i);// represents how many numbers within a line
count++;
for (j = 0 ; j < numbers.length ; j++) // numbers within line
{
numbers[j] = input.nextInt();
}
for (int p = 0 ; p < numbers.length - 1 ; p++) // prints specific values in line
{
numbers[p] = numbers[numbers.length - 1];
p = numbers[p];
System.out.println(p);
System.out.println(Arrays.toString(numbers));
}
}
input.close();
}
output
2
Times repeated: 2
2
Length of Array: 2
1
2
2
[2, 2]
2
Length of Array: 2
1
2
2
[2, 2]

Categories