Print int array with "and" before last element - java

The following is for one of my assignments in my java programming class. I have all the code written already I just can't figure how to make the output display what i need it to display.
For my assignment I have to write a program with a single-dimension array that holds 10 integer numbers between 1 and 100 and sort the array using a bubble sort.
An example of what the output needs to look like is this:
The unsorted list is: 54, 27, 13, 97, 5, 63, 78, 34, 47, and 81
The sorted list is: 5, 13, 27, 34, 47, 54, 63, 78, 81, and 97
My output is displaying this:
The unsorted list is: 54, 27, 13, 97, 5, 63, 78, 34, 47, 81,
The sorted list is: 5, 13, 27, 34, 47, 54, 63, 78, 81, 97,
I can't figure out how to write the "and" into the output.
public class Chpt7_Project {
/** The method for sorting the numbers */
public static void bubbleSort(int[] numbers)
{
int temp;
for (int i = numbers.length - 1; i > 0; i--)
{
for (int j = 0; j < i; j++)
{
if (numbers[j] > numbers[j + 1])
{
temp = numbers[j]; // swap number[i] with number[j]
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
}
public static void main(String[] args) { // Test Method
System.out.print("The unsorted list is: ");
// Generate 10 random numbers between 1 and 100
int[] numbers = new int[10];
for (int i=0;i<numbers.length;i++) {
numbers[i] = (int) (Math.random() * 100);
System.out.print(numbers[i] + ", ");
}
System.out.println();
bubbleSort (numbers); // numbers are sorted from smallest to largest
System.out.print("The sorted list is: ");
for (int i=0;i<numbers.length;i++) {
System.out.print(numbers[i] + ", ");
}
}
}

Change this loop
for (int i=0;i<numbers.length;i++) {
System.out.print(numbers[i] + ", ");
}
to
for (int i=0;i<numbers.length;i++) {
if(i== numbers.length-1) {
System.out.println("and "+numbers[i]);
} else {
System.out.print(numbers[i] + ", ");
}
}

Output:
The unsorted list is: 67, 86, 78, 80, 56, 45, 24, 2, 67, and 98
The sorted list is: 2, 24, 45, 56, 67, 67, 78, 80, 86, and 98
Modified Code(Integrated what #abhinav mentioned):
public class Chpt7_Project {
/** The method for sorting the numbers */
public static void bubbleSort(int[] numbers) {
int temp;
for (int i = numbers.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (numbers[j] > numbers[j + 1]) {
temp = numbers[j]; // swap number[i] with number[j]
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
}
public static void main(String[] args) { // Test Method
System.out.print("The unsorted list is: ");
// Generate 10 random numbers between 1 and 100
int[] numbers = new int[10];
for (int i=0;i<numbers.length;i++) {
numbers[i] = (int) (Math.random() * 100);
if(i== numbers.length-1) {
System.out.println("and "+numbers[i]);
} else {
System.out.print(numbers[i] + ", ");
}
}
System.out.println();
bubbleSort (numbers); // numbers are sorted from smallest to largest
System.out.print("The sorted list is: ");
for (int i=0;i<numbers.length;i++) {
if(i== numbers.length-1) {
System.out.println("and "+numbers[i]);
} else {
System.out.print(numbers[i] + ", ");
}
}
}
}

Related

Java find missing numbers in array

I am trying to learn Java on my own for only 3 weeks (from YouTube videos and blogs) and this is my first language. I want to write a program to find missing number (s) in an ascending integer array. I found a way, but it only works if the last number in the incrementing array is less than 10. Like 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
I also found other programs on the internet, but they all have the same problem.
I tried to write on my own with my limited 3 week knowledge and succeeded. But I think I took the long way. The code is almost 27 lines long.
Let me show you the code
I have an integer array with 9 elements:
[12, 13, 17, 18, 20, 21, 24, 25, 26]
and 14, 15, 16, 19, 22, 23 are missing
public class Exercises {
public static void main(String[] args) {
int[] arr = {12, 13, 17, 18, 20, 21, 24, 25, 26};
int len = arr.length;
System.out.println("\nArray source: \n" + Arrays.toString(arr));
//for avoiding ArrayIndexOutOfBoundsException
//error I am creating temp. array with 10 elemets
//and adding main array elements to temp. array
int[] tempArr = new int[len + 1];
for (int i = 0; i < len; i++) {
tempArr[i] = arr[i];
}
//adding last element to temp. array
int max = 0;
for (int i = 0; i < tempArr.length; i++) {
if (tempArr[i] > max) {
max = tempArr[i];
}
}
tempArr[tempArr.length - 1] = max + 1;
System.out.println("\nMissing number(S): ");
for (int i = 0; i < len - 1; i++) {
// If it comes to the last loppf main array
// this will be use temp. arrays' last element to
// compare main array
if (i == (len - 1) && (tempArr[i + 1] - arr[i]) > 1) {
System.out.println(tempArr[i]);
} else if ((arr[i + 1] - arr[i]) > 1) {
for (int a = 1; a <= (arr[i + 1] - arr[i]) - 1; a++) {
System.out.println(arr[i] + a);
}
}
}
}
}
Output:
Array source:
[12, 13, 17, 18, 20, 21, 24, 25, 26]
Missing number(S):
14
15
16
19
22
23
I got what I wanted, but is there a more optimal way to do that?
Btw if I want to make code more esthetic it becomes huge :D
public class Exercises {
public static void main(String[] args) {
int[] arr = {12, 13, 17, 18, 20, 21, 24, 25, 26};
int len = arr.length;
int[] tempArr = new int[len + 1];
int[] correctArr = new int[MathUtils.max(arr) - MathUtils.min(arr) + 1];
int countArr = (MathUtils.max(arr) - (MathUtils.max(arr) - MathUtils.min(arr)) - 1);
for (int i = 0; i < correctArr.length; i++) {
countArr++;
correctArr[i] = countArr;
}
System.out.println("\nArray source: \n" + Arrays.toString(arr));
System.out.println("Source should be: \n" + Arrays.toString(correctArr));
for (int i = 0; i < len; i++) {
tempArr[i] = arr[i];
}
int max = 0;
for (int i = 0; i < tempArr.length; i++) {
if (tempArr[i] > max) {
max = tempArr[i];
}
}
tempArr[tempArr.length - 1] = max + 1;
int count = 0;
for (int i = 0; i < len - 1; i++) {
if (i == (len - 1) && (tempArr[i + 1] - arr[i]) > 1) {
count++;
} else if ((arr[i + 1] - arr[i]) > 1) {
for (int a = 1; a <= (arr[i + 1] - arr[i]) - 1; a++) {
count++;
}
}
}
if (count == 1) {
System.out.println("\nThere is only one missing number:");
} else if (count > 1) {
System.out.println("\nThere are " + count + " missing numbers:");
}
for (int i = 0; i < len - 1; i++) {
if (i == (len - 1) && (tempArr[i + 1] - arr[i]) > 1) {
System.out.println(tempArr[i]);
} else if ((arr[i + 1] - arr[i]) > 1) {
for (int a = 1; a <= (arr[i + 1] - arr[i]) - 1; a++) {
System.out.println(arr[i] + a);
}
}
}
}
}
Output:
Array source:
[12, 13, 17, 18, 20, 21, 24, 25, 26]
Source should be:
[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
There are 6 missing numbers:
14
15
16
19
22
23
You look to be over complicating things since a simple nested for loop is probably all that you need. The outer loop loops through the array, up to but not including the last number, and the inner loop loops between one item in the array going to the next item, from arr[i] + up to arr[i + 1]. Note that the inner loop won't "loop" if the two array items are contiguous, and so no if blocks are needed:
public class MissingNumber {
public static void main(String[] args) {
int[] arr = {12, 13, 17, 18, 20, 21, 24, 25, 26};
System.out.println("missing numbers");
for (int i = 0; i < arr.length - 1; i++) {
for (int j = arr[i] + 1; j < arr[i + 1]; j++) {
System.out.println("" + j);
}
}
}
}
Output:
missing numbers
14
15
16
19
22
23
That's it
You can use List<Integer> to avoid repeating the same calculation.
static List<Integer> missingNumbers(int[] a) {
List<Integer> missingNumbers = new ArrayList<>();
for (int i = 1, length = a.length; i < length; ++i)
if (a[i - 1] + 1 < a[i])
for (int j = a[i - 1] + 1; j < a[i]; ++j)
missingNumbers.add(j);
return missingNumbers;
}
public static void main(String[] args) {
int[] a = {12, 13, 17, 18, 20, 21, 24, 25, 26};
List<Integer> missingNumbers = missingNumbers(a);
if (missingNumbers.size() == 1)
System.out.println("There is only one missing number:");
else
System.out.println("There are " + missingNumbers.size() + " missing numbers:");
for (int n : missingNumbers)
System.out.println(n);
}
output:
There are 6 missing numbers:
14
15
16
19
22
23
int[] arr = { 12, 13, 17, 18, 20, 21, 24, 25, 26 };
System.out.println("Array Source:");
System.out.println(Arrays.toString(arr) + "\n");
System.out.println("Missing number(s):");
int nextNumber = arr[0] + 1;
for (int i = 1; i < arr.length; i++) {
while (arr[i] > nextNumber) {
System.out.println(nextNumber);
nextNumber++;
}
nextNumber++;
}
To fill the array with all numbers from min to max you can write
int[] shouldBe = IntStream.range(min, max + 1).toArray();
and in this special case
int[] shouldBe = IntStream.range(arr[0], arr[arr.length - 1] + 1).toArray();
public class missingnumber{
public static void main(String args[]){
int arr[]={1,2,3,4,6,7,8,9};
for(int i=arr.length-1;i>0;i--){
if(arr[i]-1!=arr[i-1]){
System.out.println(arr[i]-1);
}
}
}
}

Separate one array with a hyphen

I'm stuck on a school project. I'm supposed to print an array with [input] amount of randomized digits between 1-999 that have been sorted. First by odd and even but also ascending / descending. I'll give you guys a quick demonstration of how the program is supposed to work:
Enter the amount of digits you want to randomize: 10;
Your numbers are: 5, 818, 916, 935, 464, 89, 275, 470, 209, 388
Your numbers sorted: 388, 464, 470, 818, 916, 935, 275, 209, 89, 5
Out of the above 10 numbers, 5 were even and 5 were odd.
I got the sorting right, with the ascending even numbers to the left and the descending odd numbers to the right. But here's the problem I got. I want to separate these 2 categories with a hyphen (and I can't use arrayList). Like following:
Your numbers sorted: 388, 464, 470, 818, 916 - 935, 275, 209, 89, 5
I can print my full code here for anyone willing to help me think!
class Main {
public static void main(String[] args) {
System.out.println("How many random numbers in the range 0 - 999 are desired?");
int randNum = 0;
Scanner scan = new Scanner(System.in);
randNum = scan.nextInt();
int min = 1;
int max = 1000;
int evenAmount = 0;
int oddAmount = 0;
int[] arr = new int[randNum];
for (int i = 0; i < arr.length; i++) {
arr[i] = ThreadLocalRandom.current().nextInt(min, max);
}
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0)
{
evenAmount++;
}
else
{
oddAmount++;
}
}
Integer[] even = new Integer[evenAmount];
Integer[] odd = new Integer[oddAmount];
int a = 0;
int b = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0)
{
even[a++] = arr[i];
}
else
{
odd[b++] = arr[i];
}
}
Arrays.sort(even);
Arrays.sort(odd, Collections.reverseOrder());
System.out.println("\n" + "Here are the random numbers: " + "\n");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + ", ");
System.out.print("");
}
Integer[] result = new Integer[evenAmount + oddAmount];
String[] strEven = new String[evenAmount];
String[] strOdd = new String[oddAmount];
String[] strSeparate = {"-"};
for (int i = 0; i < evenAmount; i++)
{
strEven[i] = String.valueOf(even[i]);
}
for (int i = 0; i < oddAmount; i++)
{
strOdd[i] = String.valueOf(odd[i]);
}
System.arraycopy(even, 0, result, 0, evenAmount);
System.arraycopy(odd, 0, result, evenAmount, oddAmount);
System.out.println("\n" + "\n" + "Here are the random numbers arranged: " + "\n");
for (int i = 0; i < result.length; i++) {
System.out.print(result[i] + ", ");
}
System.out.println("\n" + "Out of the above " + arr.length + " numbers, " + evenAmount + " were even and " + oddAmount + " were odd.");
scan.close();
}
}```
But here's the problem I got. I want to separate these 2 categories
with a hyphen (and I can't use arrayList). Like following:
Your numbers sorted: 388, 464, 470, 818, 916 - 935, 275, 209, 89, 5
You already know how many even numbers there are with your evenAmount variable. You can use that to determine when to print a "-" instead of a ",". You can also not print a "," after the last item with a little more checking:
System.out.print("Your numbers sorted: ");
for (int i = 0; i < result.length; i++) {
System.out.print(result[i]);
if (i < (result.length - 1)) {
System.out.print(((i + 1) == evenAmount) ? " - " : ", ");
}
}
System.out.println();
Here's an alternative solution in pseudocode. I will leave turning this into actual code as an exercise:
Use a for loop to print the even numbers from index 0 to index evenAmount
Print a hyphen
Use a for loop to print the odd numbers from index evenAmount to the end
I would use arrays.toString() to convert the array to a string so you can insert the hyphen.

Sorting an array using Bucket Sort [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I want to sort this array = {20, 46, 22, 19, 6, 42, 14, 5, 48, 47, 17, 39, 51, 7, 2} using bucket sort. I get a arrayindexoutofboundsexception error in my code. Can someone please help me to correct my code...
package com.bucketsort;
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] arr = {20, 46, 22, 19, 6, 42, 14, 5, 48, 47, 17, 39, 51, 7, 2};
System.out.println("Unsorted: " + Arrays.toString(arr));
bucketSort(arr);
System.out.println("Sorted : " + Arrays.toString(arr));
}
public static int[] bucketSort(int[] arr) {
int max = getMax(arr);
int[] sortedArray = new int[max + 1];
//loop and place n at nth position
for (int cur : arr) {
for (int i = 0; i <= max; i++) {
int currentVal = arr[i];
sortedArray[currentVal] = currentVal;
}
}
return sortedArray;
}
//method to get the maximum value
public static int getMax(int[] arr) {
int maxValue = arr[0];
for(int i=1;i<arr.length;i++) {
if(arr[i] > maxValue) {
maxValue = arr[i];
}
}
return maxValue;
}
}
This is a screenshot of what I get when i run this code.
The problem starts here:
for (int i = 0; i <= max; i++) {
int currentVal = arr[i];
sortedArray[currentVal] = currentVal;
}
Since you are returning the value from the getMax function instead of index.
The problem here is this part of your code, you loop from the 0 to max for the arr which its length fixed 15 and before the max
for (int cur : arr) {
for (int i = 0; i <= max; i++) { <---
int currentVal = arr[i]; <---
sortedArray[currentVal] = currentVal;
}
}
, Just remove that and use the following:
for (int cur : arr) {
sortedArray[curr] = curr;
}

How do I get the sum of a row in an array? [duplicate]

This question already has answers here:
How to sum a row in a matrix
(6 answers)
Closed 2 years ago.
I have an array as listen in the code below and I must use the method sumRow but im not sure how to do it, most tutorials online are of no help to me. I know it seems easy but if someone could help or explain it to me that would be awesome
code:
public class Sum
{
public static void main(String[] args)
{
int[][] array = {{32, 4, 14, 65, 23, 6},
{4, 2, 53, 31, 765, 34},
{64235, 23, 522, 124, 42, 64}};
}
public static int sumRow(int[][] array, int row)
{
//This is where the sumRow method is supposed to be made.
}
}
Use Arrays.stream(arr).sum():
public static int sumRow(int[][] array, int row) {
if (row < 0 || row >= array.length) return -1; // row is not valid
return Arrays.stream(array[row]).sum();
}
public class Sum {
public static void main(String[] args) {
int[][] array = {{32, 4, 14, 65, 23, 6},
{4, 2, 53, 31, 765, 34},
{64235, 23, 522, 124, 42, 64}};
}
public static int sumRow(int[][] array, int row) {
int sum = 0;
for (int col = 0; col < array[row].length; col++) {
sum += array[row][col];
}
return sum;
}
}
Iterate the row of the array and add each element to sum where int sum has been initialized with 0.
Demo:
public class Main {
public static void main(String[] args) throws IllegalArgumentException {
int[][] array = { { 32, 4, 14, 65, 23, 6 },
{ 4, 2, 53, 31, 765, 34 },
{ 64235, 23, 522, 124, 42, 64 } };
// Test
System.out.println(sumRow(array, 0));
System.out.println(sumRow(array, 1));
System.out.println(sumRow(array, 2));
System.out.println(sumRow(array, 5));
System.out.println(sumRow(array, -1));
}
public static int sumRow(int[][] array, int row) throws IllegalArgumentException {
int sum = 0;
if (row >= 0 && row < array.length) {
for (int i = 0; i < array[row].length; i++) {
sum += array[row][i];
}
} else {
throw new IllegalArgumentException("The row number should be >=0 and <" + array.length);
}
return sum;
}
}
Output:
144
889
65010
Exception in thread "main" java.lang.IllegalArgumentException: The row number should be >=0 and <3
at Main.sumRow(Main.java:22)
at Main.main(Main.java:11)
Another demo (with exception handled):
public class Main {
public static void main(String[] args) throws IllegalArgumentException {
int[][] array = { { 32, 4, 14, 65, 23, 6 },
{ 4, 2, 53, 31, 765, 34 },
{ 64235, 23, 522, 124, 42, 64 } };
// Test
for (int i = -1; i < 4; i++) {
try {
System.out.println("Sum of row, " + i + ": " + sumRow(array, i));
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
public static int sumRow(int[][] array, int row) throws IllegalArgumentException {
int sum = 0;
if (row >= 0 && row < array.length) {
for (int i = 0; i < array[row].length; i++) {
sum += array[row][i];
}
} else {
throw new IllegalArgumentException("The row number should be >=0 and <" + array.length);
}
return sum;
}
}
Output:
The row number should be >=0 and <3
Sum of row, 0: 144
Sum of row, 1: 889
Sum of row, 2: 65010
The row number should be >=0 and <3

largest and second largest number getting same value from integer array in java?

here i have written code to print largest and second largest number from array.But when i have largest number two times in my array then its printing both largest and second largest as same.Can anybody tell me where I'm doing mistakes.This is my code.
int arr[] = {96, 1, 23, 47, 81, 92, 52, 48, 56, 66, 65, 96, 81, 6};
int largest = arr[0];
int secondLargest = arr[0];
// check the condition
for (int i = 0; i < arr.length; i++) {
// this condition check for largest number
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest) {
secondLargest = arr[i];
}
}
// print the result
System.out.println("second largest number is:" + secondLargest);
System.out.println("largest number is:" + largest);
and output coming as:
second largest number is:96
largest number is:96
There are 2 issues:
1) the initialization of the largest and second largest (use Integer.MIN_VALUE); You are setting the second largest at your first iteration and it is the largest number in array
2) the condition for setting secondLargest; you should also check: arr[i] < largest
int arr[] = {96, 1, 23, 47, 81, 92, 52, 48, 56, 66, 65, 96, 81, 6};
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
// check the condition
for (int i = 0; i < arr.length; i++) {
// this condition check for largest number
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest && arr[i] < largest) {
secondLargest = arr[i];
}
}
output:
second largest number is:92
largest number is:96
You are initializing largest and secondLargest to the first element of the array, so if the first element is already the largest, both would hold the largest in the end.
A better initialization is to set them to a real small value :
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
int arr[] = {96, 1, 23, 47, 81, 92, 52, 48, 56, 66, 65, 96, 81, 6};
There are two numbers with the value 96. So after 96 > 96 fails, it goes to the condition of arr[i] > secondLargest and it passes that test. That's why you'll have the largest and secondLargest as the same number, 96.
Here is a solution using the binarySearch
int arr[] = {96, 1, 23, 47, 81, 92, 52, 48, 56, 66, 65, 96, 81, 6};
Arrays.sort(arr);
int largest = arr[arr.length - 1];
int binarySearch = Arrays.binarySearch(arr, largest);
System.out.println("largest = " + largest);
// need to handle the case for arrays which are...
// - empty
// - contain only one int
// - the largest int is on index zero
System.out.println("second largest = " + arr[binarySearch - 1]);

Categories