Separate one array with a hyphen - java

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.

Related

print and count the maximun values in 2d array java

I have 2d array java, I need to look at it and check on the max value, then print it with the count of how many it is in the array
I was trying to do like this but it doesn't work
int[][] rand = new int[][]{
{1, 80, 3, 4, 5},
{13, 199, 80, 8},
{12, 22, 80, 190}
};
int max = rand[0][0];
int count = 0;
for (int i = 0; i < rand.length; i++){
for (int ii = 0; ii < rand[i].length; ii++) {
if (rand[i][ii] > max) {
max = rand[i][ii];
count++;
}
}
}
System.out.println(max + " " + count);
You are not handling count correctly:
int max = rand[0][0];
int count = 0
for (int i = 0; i < rand.length; i++){
for (int ii = 0; ii < rand[i].length; ii++) {
if (rand[i][ii] > max) {
max = rand[i][ii];
count = 1; // a new maximum's first occurrence
} else if (rand[i][ii] == max) {
count++; // another occurrence of the current maximum
}
}
}
System.out.println(max + " " + count);
When you find a new maximum, you should reset count to 1.
You should check if the current element is equal to the current maximum, and increment count if that's the case.
Output:
199 1
EDIT:
Fixed the case where the first element is the maximum. It turns out count should be initialized to 0 after all, since the loops re-visit the first element, so we don't want to count it twice if it's the maximum.
You can use streams:
int max = Arrays.stream(rand)
.mapToInt(row -> Arrays.stream(row).max().getAsInt())
.max().getAsInt();
int count = Arrays.stream(rand)
.mapToInt(row -> (int) Arrays.stream(row).filter(i-> i==max).count())
.reduce(Integer::sum).getAsInt();

Given 2 numbers, build an array that holds all numbers within them

Refreshing my Java, With 2 numbers as user input , I'm trying to display all numbers in between. My code works using different types, likse strings, String builder and using Java8. But somehow, the Array part does not work..
Here is my code..
System.out.println("Enter the first number :");
Scanner key = new Scanner(System.in);
int num1 = key.nextInt();
int num2 =0;
System.out.println("Enter the Second number :");
try{
num2 = key.nextInt();
do {
if (num2 < num1) {
System.out.println("Second number " + num2 + " is less than " + num1);
System.out.println("Enter the Second number :");
num2 = key.nextInt();
}
} while(num2 <num1);
}
catch (ArithmeticException e) {
if (num2 <num1)
{
System.out.println("Second number " +num2 + "cannot be less than " + num1);
}
}
int length = (num2 - num1) +1;
int [] numOfIntegers = new int [length];
System.out.println("Now the length of numOfInteger is : " + numOfIntegers.length);
// TimeUnit.SECONDS.sleep(2);
//int counter = num1;
for(int i=num1;i<length; i++)
{
numOfIntegers[i] = i ;
}
RESULT is like this :
Numbers within 2 and 8 Using an Array is [0, 0, 2, 3, 4, 5, 6]
What am I doing wrong..
Java 8 allows to do that in one line with IntStream
DOCUMENTATION
public static void main(String[] args) {
int[] a = IntStream.range(num1, num2+1).toArray();
for(int aa:a)
{
System.out.println(aa);
}
}
EXAMPLE: If you Substitute Num1= 2 and Num2=8 , Output Will be 2 3 4 5 6 7 8
When you fill your array, you start at index num1. You should start at index 0. That is
for(int i=num1;i<length; i++)
{
numOfIntegers[i] = i ;
}
should be
for(int i=0; i < length; i++)
{
numOfIntegers[i] = num1 + i;
}
You need to add an variable to loop the array index from 0 th position to array length. Since your for loop first point to an index in the middle. i.e. here it is 2 and it goes forward up to array length. You could change it as below.
for ( int i = num1, k = 0; k < length; i++ )
{
numOfInteger[k++] = i;
}
Here in this loop:
for(int i=num1;i<length; i++)
{
numOfIntegers[i] = i ;
}
You start adding at index num1, which is why the first couple slots in your Array are still your default value. You want to start the index at zero:
for(int i = num1, j = 0; j < length; i++) {
numOfInteger[j++] = i;
}
Which will produce:
[2, 3, 4, 5, 6, 7, 8]
In the final loop:
for(int i = num1 ; i < length; i++)
{
numOfIntegers[i] = i ;
}
You are basically counting from num1 to length i.e the loop counter is being assigned values (2,3,4,5,6) and 0,1 positions of the array are being left out with 0 as default values.
Adjust the loop to iterate from 0 to length like below:
for(int i = 0 ; i < length ; i++)
{
numOfIntegers[i] = num1 + i;
}

Java array loop method returns last value in array

I'm making a program to determine who has the fastest time in a marathon out of an array of times and one of corresponding names. In order to make them match up I return the index of the lowest time instead of the value of the index. When I return the value of the index instead of the index it returns the correct name and time, however, when returning the index it returns the last value in both arrays.
package Lec3;
public class Marathon
{
public static void main (String[] arguments)
{
String[] names =
{
"Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt", "Alex",
"Emma", "John", "James", "Jane", "Emily", "Daniel", "Neda",
"Aaron", "Kate"
};
int[] times =
{
341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299,
343, 317, 265
};
for (int i = 0; i < names.length; i++)
{
System.out.println(names[i] + ": " + times[i]);
}
int key = firstPlace(times, names);
System.out.println("In first place is " + names[key] + " with a time of " + times[key] + " minutes!");
}
public static int firstPlace(int[] time, String[] names)
{
int i;
int bestTime = 1000;
int firstValue = 0;
for(i = 0; i < time.length; i++)
{
if(time[i] < bestTime)
{
firstValue = i;
}
}
return firstValue;
}
}
for(i = 0; i < time.length; i++)
{
if(time[i] < bestTime)
{
firstValue = i;
}
}
In this loop you don't update bestTime so the times are all compared against the initial value of 1000. They're all smaller leading to a victory for the last one.
You have a loop in main where you iterate names to display all of the names and times. You can find the lowest key in that loop. Like,
int key = 0;
for (int i = 0; i < names.length; i++) {
System.out.println(names[i] + ": " + times[i]);
if (times[i] < times[key]) {
key = i;
}
}
System.out.println("In first place is " + names[key] + " with a time of " + times[key] + " minutes!");
Or, in your current method, change
if(time[i] < bestTime)
to
if (time[i] < time[firstValue])
and eliminate bestTime.

Selection sort not working properly with zero or negative inputs

Im not really sure why the selection sort isn't working with negative numbers and zeros in the array. It works perfectly fine with all positive integers. Feedback would be greatly appreciated.
private static void selectionSort(int[] digits) {
for (int i = 0; i < digits.length - 1; i++) {
int index = i;
for (int j = i + 1; j < digits.length; j++) {
if (digits[j] < digits[index]) {
index = j;
}
int min = digits[index];
digits[index] = digits[i];
digits[i] = min;
}
}
System.out.println("Array after sorrting:");
System.out.println("Number of digits in array: " + digits.length);
System.out.print("Digits in array: ");
for (int i: digits) {
System.out.print(i + " ");
}
System.out.println("\n");
}
Selection sort method along with the class for the project:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = 0;
do {
n = getNumDigits(in);
if (n != 0) {
int[] digits = new int[n];
getDigits(digits, in);
displayDigits(digits);
selectionSort(digits);
}
} while (n != 0);
in.close();
System.out.println("No digits to sort? Goodbye! ");
}
// Given a Scanner as input, prompts the user for the number of digits they will
// be
// entering into an array. If the number given by the user is less than 0,
// display
// an error message and ask for a number that is 0 or greater. When a valid
// number is
// received, return it to the calling program.
private static int getNumDigits(Scanner inScanner) {
int digits = 0;
do {
System.out.print("Please enter the number of digits to be stored: ");
digits = inScanner.nextInt();
if (digits < 0) {
System.out.println("ERROR! You must enter a non-negative number of digits!\n");
}
} while (digits < 0);
return digits;
}
// Given an array and a Scanner as input, prompt the user to input integers to
// fill the
// array. The procedure should display a prompt for the user to enter an
// integer, and
// should loop until the entire array is filled with integer.
private static void getDigits(int[] digits, Scanner inScanner) {
int i = 0;
while (i < digits.length) {
System.out.print("Enter integer " + i + ": ");
digits[i] = inScanner.nextInt();
i++;
}
}
// Given an array as input, displays the total number of digits contained in the
// array
// and displays the contents of the array in order, starting at index 0 and
// ending
// with the final index of the array.
private static void displayDigits(int[] digits) {
System.out.println("\nArray before sorrting:");
System.out.println("Number of digits in array: " + digits.length);
System.out.print("Digits in array: ");
for (int i = 0; i < digits.length; i++) {
System.out.print(digits[i] + " ");
}
System.out.println("\n");
}
// FOR LAB10B
// Given an array of integers as input, sorts the array using the Selection Sort
// algorithm
// provided in the Closed Lab 10 write-up.
private static void selectionSort(int[] digits) {
for (int i = 0; i < digits.length - 1; i++) {
int index = i;
for (int j = i + 1; j < digits.length; j++) {
if (digits[j] < digits[index]) {
index = j;
}
int min = digits[index];
digits[index] = digits[i];
digits[i] = min;
}
}
System.out.println("Array after sorrting:");
System.out.println("Number of digits in array: " + digits.length);
System.out.print("Digits in array: ");
for (int i: digits) {
System.out.print(i + " ");
}
System.out.println("\n");
}
Thanks & I apologize for all the edits. I never use online forums.
Try doing swapping outside inner for loop :-
private static void selectionSort(int[] digits) {
for (int i = 0; i < digits.length - 1; i++) {
int index = i;
for (int j = i + 1; j < digits.length; j++) {
if (digits[j] < digits[index]) {
index = j;
}
//previously u were doing swapping here
//System.out.println("inner : " + convert(digits));
}
//i shifted the swapping block to this place
int min = digits[index];
digits[index] = digits[i];
digits[i] = min;
//System.out.println("outer : " + convert(digits));
}
System.out.println("Array after sorrting:");
System.out.println("Number of digits in array: " + digits.length);
System.out.print("Digits in array: ");
for (int i: digits) {
System.out.print(i + " ");
}
System.out.println("\n");
}
============
input : 4,0,-4,5,2,1,
Array after sorrting:
Number of digits in array: 6
Digits in array: -4 0 1 2 4 5
============
input : 3,4,2,5,3,21,-7,3,26,-43,-12,22,
Array after sorrting:
Number of digits in array: 12
Digits in array: -43 -12 -7 2 3 3 3 4 5 21 22 26

working with array and summing the elements

I have to solve the following problem: Given an array of integers and given an integer value, list all possible numbers form the array that sums up to the given value.
Example:
Input: array = {1, 2, 2, 3, 4, 5}, int N = 5
Output: {1, 2, 2}, {1, 4}, {5} {2, 3}.
here is my code till now, can anybody help me?
import java.util.Scanner;
public class sumarray {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int[] array = new int[3];
for (int i = 0; i < array.length; i++) {
array[i] = scan.nextInt();
}
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (array[i] + array[j] == 5) {
System.out.println("{" + array[i] + "," + array[j] + "}");
}
}
}
}
}
This is a common Dynamic Programming problem called Subset Sum.
You can do this like so if you only want to print (note that you have {2, 3} twice because there are two 2s):
public class Main {
public static void main(String[] args){
int[] arr = {1, 2, 2, 3, 4, 5};
subsetSum(arr, 5);
}
private static void subsetSum(int[] arr, int sum) {
subsetSum(arr, 0, sum, "");
}
private static String lineSep = System.getProperty("line.separator");
private static void subsetSum(int[] arr, int i, int sum, String aggregated) {
if (sum == 0){
System.out.println("Success with:" + aggregated);
System.out.println("And done.");
System.out.println();
return;
}
if (arr.length <= i){
// failed (uncomment following lines to see why)
// System.out.println("Failed with:" + aggregated);
// System.out.println();
return;
}
int current = arr[i];
subsetSum(arr, i+1, sum, aggregated + lineSep + "not " + current);
subsetSum(arr, i+1, sum - current, aggregated + lineSep + current);
return;
}
}
This uses the fact that String is immutable (so a new string is created for every frame), and does forward aggregation of selected numbers. I've added some text to make it descriptive so you see what's going on.
Output:
not 1
not 2
not 2
not 3
not 4
5
And done.
not 1
not 2
2
3
And done.
not 1
2
not 2
3
And done.
1
not 2
not 2
not 3
4
And done.
1
2
2
And done.
This is problem called Subset Sum.
and this my code and i know not professional but it is solution for this specific problem
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] array = new int[6];
for (int i = 0; i < array.length; i++) {
array[i] = scan.nextInt();
}
int N=5; //N= the given value
int a1=0; // for use to sure not duplicate answer in this case is {2,3}
int a2=0; // for use to sure not duplicate answer
// and we put in a1 and a2 numbers if we add together dose not equal N which is here equal(5)
for (int i = 0; i < array.length; i++) {
if (array[i]==N)
System.out.println("{" + array[i] +"}");
for (int j = i+1; j < array.length; j++) {
for (int f = j+1; f < array.length; f++){
if(array[j]+array[i] == 5 ){
if(a1!=array[i] && a2!=array[j]){ // make sure dose not same number that is done.
System.out.println("{" + array[i] + ","+ array[j] + "}");
a1=array[i];
a2=array[j];}}
else if(array[i] + array[j]+array[f] == 5){
System.out.println("{" + array[i] + "," + array[j] + ","+ array[f] + "}");}
}}}}
the output is :
{1,2,2} {1,4} {2,3} {5}
i hope this help you :)

Categories