Finding the lowest double in a Java array - java

I am trying to catch the lowest double from user input. I am only catching the value of the initialized min variable - what am I missing? Thanks!
public static void main(String[] args) {
double[] lowNum = new double[10];
Scanner input = new Scanner(System.in);
for (int i=0; i<=9; i++) {
System.out.println("Enter a double: ");
lowNum[i] = input.nextDouble();
}
input.close();
double min = calcLowNum(lowNum);
System.out.println(min);
}
public static double calcLowNum(double[] a) {
double min=0;
for (int i=0; i>=9; i++){
for (int j=0; j>=9; j++){
if (a[i]<=a[j] && j==9){
min=a[i];
}
else {
continue;
}
}
}
return min;

You could just use Collections#min to find the minimum value. You will need Apache Commons-Lang for this though.
// This would be the array 'a'
double[] array = {15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Convert the primitive array into a Class array
Double[] dArray = ArrayUtils.toObject(array);
List<Double> dList = Arrays.asList(dArray);
// Find the minimum value
Double returnvalue = Collections.min(dList);
return returnvalue; // or you can do returnvalue.doubleValue() if you really want

First of all, change the i>=9 and j>=9 to i<=9 and j<=9 in:
for (int i=0; i>=9; i++){
for (int j=0; j>=9; j++){
Otherwise, your loops are effectively no-ops.
A far more robust approach is to write the loops like so:
for (int i = 0; i < a.length; i++) {
or like so:
for (double val : a) {
Finally, finding the minimum can be done by iterating over the array just once, comparing each element with the current minimum (but make sure to initialize min appropriately!)

If You really need to store all inputs and than find minimal, easiest way to do it to use library function for sorting array:
...
//sorting array, so first element will be the lowest
Arrays.sort(lownum);
double min = lownum[0];
I agree with Peter Lawree You don't actually need all the array; You need to save first input and all the followings compare with it and store if lower:
double lastInput=0, min=0;
for (int i=0; i<=9; i++) {
System.out.println("Enter a double: ");
lastInput = input.nextDouble();
if (0==i) {
//if this is first iteration, save first input as min
min=lastInput;
} else {
if (lastInput<min) min=lastInput;
}
}
return min;
P.S. Actually, You should use Double.compare to compare doubles. So example with Arrays.sort() better if number of inputs not huge, in this case first example will take much more memory and time to execute.
Update: Java8 solution
double findMin(double[] input) {
return Arrays.stream(input).min().getAsDouble();
}

OMG, iterate over array - this is the worst workaround (but my bad english is more worse than it). Look at http://code.google.com/p/guava-libraries/ This lib contains robust code for your need (de-facto must have library in your project). You can see and analyze sources - it's free , but you experience in best practice will be grown as my english skills.
Below is excample of guava code:
public static double min(double... array) {
checkArgument(array.length > 0);
double min = array[0];
for (int i = 1; i < array.length; i++) {
min = Math.min(min, array[i]);
}
return min;
}
P.S: learn libraries with standart code and do not reinvent the wheel. Be happy!

Related

How to find the largest difference in change in an array? - java

Suppose I declare an array:
int[] arr = {10,2,7,11,3};
The largest (positive) change in this array would be 9 as 11 - 2 = 9.
How would I write a method that find the largest change in code with the smaller integer occurring earlier?
Thank you,
I rewrote the answer since I misunderstood the question.
The simplest but almost certainly not the most efficient way to do this is to check every change and comparing it to the previous one. If it is bigger, discard the previous one and remember this one instead.
int change = arr[1] - arr[0]; //give it an initial value, if we find a bigger change we will replace it
for(int i = 0; i < arr.length - 1; i++) {
for(int j = i + 1; i < arr.length; j++) {
if(arr[j]-arr[i] > change) {
change = arr[j]-arr[i];
}
}
}
This will still give an answer even if there are no positive changes. If you do not want that, you can modify it. It is trivial.
Keep in mind that arr.length - 1 is important in the outer loop.
Looks like you want to find the smallest number and the largest number in the list and comparing it with the largest number on the list.
List first item as minimum.
Compare to next item and if greater, assign that number as lesser.
List first item as largest.
Compare to next item and if smaller, assign that number as greater.
At the end of the list, you will have the least and the greatest number. The difference will be the difference between the smallest and the largest.
Hope that helps.
Interesting question! You could brute-force this pretty easily, as I'm still thinking for a more creative solution.
int [] arr = {5, 4, 3, 2, 1};
int biggestDifference = arr[1]-arr[0];
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
if ((arr[j] - arr[i]) > biggestDifference) {
biggestDifference = arr[j] - arr[i];
}
}
}
Sorting the array would ensure that the smallest number will always be at the front and largest at the back.
public static void main(String []args){
int[] arr = {10,2,7,11,3};
int diff = findBiggestDiff(arr);
System.out.println(diff);
}
public static int findBiggestDiff(int[] arr){
Arrays.sort(arr);
int diff = arr[arr.length-1] - arr[0];
return diff;
}

Is this way standard to calculate the smallest number in Java

I wrote a program that calculate the smallest number. But I don't know how programers would do it.
I did it by "IF statement", which is working, but not sure if it is the standard or common way of coding it.
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.print("Enter three values: ");
int num1 = in.nextInt();
int num2 = in.nextInt();
int num3 = in.nextInt();
System.out.print(smallest(num1, num2, num3));
}
public static int smallest(int num1, int num2, int num3)
{
if (num1 < num2 && num1 < num3){return num1;}
else if (num2 < num1 && num2 < num3){return num2;}
else return num3;
}
There is Math#min method. You can use that one:
minimum = min(n1, min(n2, n3))
Another idea would be to not even store all of the numbers but instead just keep track of the smallest, if that's all you're looking for:
int smallest = in.nextInt();
for (int i = 0; i < 2; i++) { // take 2 more inputs
int next = in.nextInt();
if (next < smallest)
smallest = next;
}
If you indeed do not need to access inputs other than the smallest later on, this approach would likely be optimal.
You can solve the more general problem of finding the smallest value of an array (or a list). It is a bad idea to sort() the structure, as you only need to find the smallest element. A really basic technique for doing so would be something like that:
public int smallest(int[] array) {
if(array.length == 0) throw new IllegalArgumentException();
int min = array[0];
for(int i=1 ; i<array.length ; i++)
if(array[i] < min)
min = array[i];
return min;
}
This has a O(n) complexity which is minimal for a non-sorted array because you have to go through the entire array anyway.
This is of course only optimal in the general case of an array that's already full of number. If you only need to get the minimum from user's inputs then you should definitely go for arshajii's algorithm to save a bit of memory because it allows you not to store the entire array.
I would do this:
public static int smallest(int... nums) {
Arrays.sort(nums);
return nums[0];
}
Not only is it minimal elegant code, by using a varargs parameter, it can handle any quantity of ints.
And the code that calls it need not be altered.
A way of doing this is by creating an array of integers, and then sorting it and grabbing the first element.
Something like:
int[] input = new int[]{in.nextInt(), in.nextInt(), in.nextInt()};
Arrays.sort(input);
int min = input[0];
Also seeing as you have made a function for it, you could turn that one into the following, instead of my above approach:
public static int smallest(int... numbers) {
if (numbers.length == 0) {
throw new IllegalArgumentException("numbers: numbers.length == 0");
}
Arrays.sort(numbers);
return numbers[0];
}
In this example you are using varargs, meaning that you can put in as many ints as you want. The varargs argument is essentially an array once it gets into your function, so then you can just work with it like any array. Be sure to do a check on the number of items in the array though, as varargs can also be 0.
You can call the code the same way as the old one:
int smallest = smallest(5, 10, 15); will return 5.

Numbers I can get by adding an array in java

I need to get a minimum number that I cant get by adding different numbers of an array. Basically if I have these numbers:1,1,1,5; I can get 1,2,3,5,6... but I cant get 4 so that is the number I am looking for. Now this is my code:
import java.util.Scanner;
public class Broj_6 {
public static void main(String[] args) {
Scanner unos = new Scanner(System.in);
int k;
int n = unos.nextInt();
int niz []= new int [n];
for(int i = 0;i<n;i++){
niz[i]=unos.nextInt();
}
BubbleSort(niz);
for(int i = 0;i<n;i++){
System.out.print(niz[i] + " ");
}
for(int br = 1;br<=10000;br++){
for(k = 1;k<n;k++){
if(niz[k]>br){
break;
}
}
int podniz [] = new int [k];
for(int i=0;i<podniz.length;i++){
niz[i] = podniz[i];
}
//This is where I will need my logic to go
}
}
static void BubbleSort (int [] niz){
int pom;
for(int i = 0;i<niz.length-1;i++){
for(int j = 0;j<niz.length-1-i;j++){
if(niz[j]>niz[j+1]){
pom = niz[j];
niz[j] = niz[j+1];
niz[j+1] = pom;
}
}
}
}
}
So the code goes by testing each number individually from 1 to 100000 and makes a subarray of all numbers given that are less than the number itself. Now here is the problem,I dont know how to mix and match the numbers in the subarray so it can get(or not get) the desired number. When every combination is tested and there is no desired number,I will break; the loop and print i. Just to clarify,I can only use addition,and each number can only go in once
You can achieve this as below:
Use two nested loops, like below to calculate the sum of different numbers:
List<Integer> additionList = new ArrayList<Integer>();
int []inputNumbers = .... // Logic to read inputs
for(int _firstIndex = 0; _firstIndex < totalInputs; _firstIndex++){
for(int _secondIndex = _firstIndex + 1; _secondIndex < totalInputs; _secondIndex++){
additionList.add(inputNumbers[_firstIndex]); // only because you have 1 in the sample output
additionList.add(inputNumbers[_firstIndex] + inputNumbers[_secondIndex ]);
}
}
Then sort additionList and look for any missing entry. The first missing entry will be your answer,
Sorting the whole array and then finding sum of all subarrays does solve the problem, but is costly: O(2n^2) ~ O(n^2).
More efficient way to solve this will be Kadane's Algorithm: http://en.wikipedia.org/wiki/Maximum_subarray_problem
What the algo does:
Start from first element and increase the array size (sub array) till you reach the sum you're desiring.
my_num = 1;
while(true){
if(sum_subarray) > my_num){
current position = new subarray;
}
and this subarray concept is calculated through Kadane's approach:
def sum_subarray(A):
sum_ending_here = sum_so_far = 0
for x in A:
sum_ending_here = max(0, max_ending_here + x)
sum_so_far = max(sum_so_far, sum_ending_here)
return sum_so_far
I couldn't solve the problem completely. 'my_num' mentioned here needs to be incremented from 1, and break when my_num > max_sum. I hope someone can add to it and make it compilable.
Note:
This will also take care if negative elements are present in array.

Calculate average in java

EDIT: I've written code for the average but I don't know how to make it so that it also uses ints from my args.length rather than the array.
I need to write a java program that can calculate:
the number of integers read in
the average value – which need not be an integer!
NOTE: I don't want to calculate the average from the array but the integers in the args.
Currently I have written this:
int count = 0;
for (int i = 0; i<args.length -1; ++i)
count++;
System.out.println(count);
}
int nums[] = new int[] { 23, 1, 5, 78, 22, 4};
double result = 0; //average will have decimal point
for(int i=0; i < nums.length; i++){
result += nums[i];
}
System.out.println(result/count)
Can anyone guide me in the right direction? Or give an example that guides me in the right way to shape this code?
Thanks in advance.
Just some minor modification to your code will do (with some var renaming for clarity) :
double sum = 0; //average will have decimal point
for(int i=0; i < args.length; i++){
//parse string to double, note that this might fail if you encounter a non-numeric string
//Note that we could also do Integer.valueOf( args[i] ) but this is more flexible
sum += Double.valueOf( args[i] );
}
double average = sum/args.length;
System.out.println(average );
Note that the loop can also be simplified:
for(String arg : args){
sum += Double.valueOf( arg );
}
Edit: the OP seems to want to use the args array. This seems to be a String array, thus updated the answer accordingly.
Update:
As zoxqoj correctly pointed out, integer/double overflow is not taken care of in the code above. Although I assume the input values will be small enough to not have that problem, here's a snippet to use for really large input values:
BigDecimal sum = BigDecimal.ZERO;
for(String arg : args){
sum = sum.add( new BigDecimal( arg ) );
}
This approach has several advantages (despite being somewhat slower, so don't use it for time critical operations):
Precision is kept, with double you will gradually loose precision with the number of math operations (or not get exact precision at all, depending on the numbers)
The probability of overflow is practically eliminated. Note however, that a BigDecimal might be bigger than what fits into a double or long.
int values[] = { 23, 1, 5, 78, 22, 4};
int sum = 0;
for (int i = 0; i < values.length; i++)
sum += values[i];
double average = ((double) sum) / values.length;
This
for (int i = 0; i<args.length -1; ++i)
count++;
basically computes args.length again, just incorrectly (loop condition should be i<args.length). Why not just use args.length (or nums.length) directly instead?
Otherwise your code seems OK. Although it looks as though you wanted to read the input from the command line, but don't know how to convert that into an array of numbers - is this your real problem?
It seems old thread, but Java has evolved since then & introduced Streams & Lambdas in Java 8. So might help everyone who want to do it using Java 8 features.
In your case, you want to convert args which is String[] into double
or int. You can do this using Arrays.stream(<arr>). Once you have stream of String array elements, you can use mapToDouble(s -> Double.parseDouble(s)) which will convert stream of Strings into stream of doubles.
Then you can use Stream.collect(supplier, accumulator, combiner) to calculate average if you want to control incremental calculation yourselves. Here is some good example.
If you don't want to incrementally do average, you can directly use Java's Collectors.averagingDouble() which directly calculates and returns average. some examples here.
System.out.println(result/count)
you can't do this because result/count is not a String type, and System.out.println() only takes a String parameter. perhaps try:
double avg = (double)result / (double)args.length
for 1. the number of integers read in, you can just use length property of array like :
int count = args.length
which gives you no of elements in an array.
And 2. to calculate average value :
you are doing in correct way.
Instead of:
int count = 0;
for (int i = 0; i<args.length -1; ++i)
count++;
System.out.println(count);
}
you can just
int count = args.length;
The average is the sum of your args divided by the number of your args.
int res = 0;
int count = args.lenght;
for (int a : args)
{
res += a;
}
res /= count;
you can make this code shorter too, i'll let you try and ask if you need help!
This is my first answerso tell me if something wrong!
If you're trying to get the integers from the command line args, you'll need something like this:
public static void main(String[] args) {
int[] nums = new int[args.length];
for(int i = 0; i < args.length; i++) {
try {
nums[i] = Integer.parseInt(args[i]);
}
catch(NumberFormatException nfe) {
System.err.println("Invalid argument");
}
}
// averaging code here
}
As for the actual averaging code, others have suggested how you can tweak that (so I won't repeat what they've said).
Edit: actually it's probably better to just put it inside the above loop and not use the nums array at all
I'm going to show you 2 ways. If you don't need a lot of stats in your project simply implement following.
public double average(ArrayList<Double> x) {
double sum = 0;
for (double aX : x) sum += aX;
return (sum / x.size());
}
If you plan on doing a lot of stats might as well not reinvent the wheel. So why not check out http://commons.apache.org/proper/commons-math/userguide/stat.html
You'll fall into true luv!
public class MainTwo{
public static void main(String[] arguments) {
double[] Average = new double[5];
Average[0] = 4;
Average[1] = 5;
Average[2] = 2;
Average[3] = 4;
Average[4] = 5;
double sum = 0;
if (Average.length > 0) {
for (int x = 0; x < Average.length; x++) {
sum+=Average[x];
System.out.println(Average[x]);
}
System.out.println("Sum is " + sum);
System.out.println("Average is " + sum/Average.length);
}
}
}
// question: let, Take 10 integers from keyboard using loop and print their average value on the screen.
// here they ask user to input 10 integars using loop and average those numbers.so the correct answer in my perspective with java is below:-
import java.util.Scanner;
public class averageValueLoop {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
int sum = 0;
for (int i = 0; i < 10; i++){
System.out.print("Enter a number: ");
sum = sum + sc.nextInt();
}
double average = sum / 10;
System.out.println("Average is " + average);
}
}
}

Sort integer in Ascending Order - Java

I need help understanding how to sort numbers.
Below is what I have I came up with so far and it didn't work. Can you please point out the mistake and tell me what to do?
I saw some of you guys using java.util.Arrays . Can you describe to me its functions?
import static java.lang.System.*;
import java.util.*;
public class Lab07v2_Task10{
public static void main (String[] args){
Scanner orcho = new Scanner (in);
int quantity = 5;
int[] myArray = new int [quantity];
out.println("Please enter 5 numbers");
for(int count = 0; count<myArray.length; count++){
myArray[count] = orcho.nextInt();
}
int maxSoFar = myArray[0];
for(int count = myArray.length-1; count>=0; count--){
if(myArray[count] > maxSoFar){
maxSoFar = myArray[count];
}
out.println(maxSoFar);
}
}
}
No solution.
The idea is to take several steps, do a for-loop. And assume that you are in the middle. The first part already is sorted, the rest is to-be-done.
Then tackle the current element with respect to what already is sorted.
int maxSoFar = myArray[0];
for (int i = 1; i < myArray.length; i++) {
// The array 0, ..., i-1 is sorted
if (myArray[i] >= maxSoFar) {
// Still sorted
maxSoFar = myArray[i];
} else {
// myArray[i] must be shifted left
...
}
// Now the array 0, ..., i is sorted
}
This is a general trick: assume part is already done, tackle one small step, and let continue.
The java.util.Arrays.sort(int[]) method sorts the specified array of int into ascending numerical order.
try this out..
// sorting array
java.util.Arrays.sort(myArray);
// let us print all the elements available in list
System.out.println("The sorted int array is:");
for (int number : myArray) {
System.out.println("Number = " + number);
}
}
Arrays.sort is a method which is a utility method available in java.util package.
Where Arrays is a system defined Utility class which contains the mehtod sort(int[]) takes int[] (array) as an argument and after sorting this array, It re-assign Array.
For more deep Info Here or Official Java Docs
The way your program runs right now: it will print 5 numbers and the number that it prints is the highest number it finds at that iteration.
The way that you want it to work: sort 5 numbers from lowest to highest. Then print these 5 numbers. This is an implementation of bubble sort in your program:
for(int i = 0; i< myArray.length; i++){
for(int j = 0; j < myArray.length-1; j++){
if(myArray[j] > myArray[j+1]){ //if the current number is less than the one next to it
int temp = myArray[j]; //save the current number
myArray[j] = myArray[j+1]; //put the one next to it in its spot
myArray[j+1] = temp; //put the current number in the next spot
}
}
}
it is probably the easiest sort to understand. Basically, for as many times as the length of your array, comb over the numbers and bring the next highest number as far up as it can go.
When it's done sorting you can then print the numbers.

Categories