Jonathan Herrej&#243;n - 24 days ago 16
Java Question

How to do an action while there's still values in the array?

I'm solving this hackerrank challenge called Cut the Sticks, but I cant find a way to do this action while there are still values in the array.

The problem says that given an array, find the minimum element, subtract it from all the elements in the array while they're different from 0 and print the number of subtractions made.

Then with the new array with the subtractions made, repeat the same, find the minimum and subtract it until you can't make any subtraction.

This is my code. I've tried making the sum of all the elements in the array and then doing the next steps while the sum is not 0, but I can't get it to work. It displays wildly large numbers infinitely.

``````import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(); // Numero de sticks
int arr[] = new int[n]; // Arreglo Contenedor de longitud de sticks
for (int arr_i = 0; arr_i < n; arr_i++) {
arr[arr_i] = in.nextInt(); // Longitud de los sticks
}
int cut_counter = 0;

int min = arr[0];
for (int i = 0; i < n; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
//System.out.println(min);
for (int j = 0; j < n; j++) {
if (arr[j] != 0) {
arr[j] = arr[j] - min;
cut_counter += 1;
}
}

System.out.println(cut_counter);
/*System.out.println(" ");
for (int i = 0; i < n; i++) {
System.out.print(arr[i]);
}*/

}
}
``````

Some small modifications to your code that might be what you need:

``````public static void main(String[] args) {
System.out.print("Enter number of numbers: ");
Scanner in = new Scanner(System.in);
int n = in.nextInt(); // Numero de sticks
int arr[] = new int[n]; // Arreglo Contenedor de longitud de sticks
System.out.println("Enter " + n + " numbers: ");
for (int arr_i = 0; arr_i < n; arr_i++) {
arr[arr_i] = in.nextInt(); // Longitud de los sticks
}

int cut_counter;
do {

cut_counter = 0;

boolean min_set = false;
int min=Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
if (arr[i]!=0) {
min=arr[i];
min_set=true;
}
}
if (!min_set)
break;
for (int i = 0; i < n; i++) {
if (arr[i] < min && arr[i] != 0) {
min = arr[i];
}
}
System.out.println("Min=" + min);
//System.out.println(min);
for (int j = 0; j < n; j++) {
if (arr[j] != 0 && min > 0 ) {
arr[j] = arr[j] - min;
cut_counter += 1;
}
}

System.out.println("cut_counter=" + cut_counter);

for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
} while (cut_counter > 0);

}
``````