I am using a list of integer arrays, which is a class variable, to hold the answers. The integer arrays are added to the list in a method, and the results are fine (has 1s). But when I fetch it in main method, the value in it is all 0s! I do not understand, where is the list changed?
public class test {
private static int sum=0;
static ArrayList<Integer[]> res = new ArrayList<Integer[]>();
private static double max=0;
public static void main(String[] args) {
int n = 6;
double B = 23.6;
double[] menu = { 1.2, 2, 2.5, 3.5, 3.2, 6.2, 7.8, 4.0, 5.6, 10, 6.5 };
Integer[] solution = new Integer[menu.length];
combinate(menu, 0, n,0, res, solution);
for(int i=0;i<res.size();i++) {
//not getting the element!!!!!!!!!!!!
//Integer[] sol = res.get(i);
System.out.println(i+" "+res.get(i));
System.out.println("Arraylist contains:"+Arrays.toString( res.get( i ) ) );
double sums = 0.0;
for (int j = 0; j < res.get(i).length; j++) {
if(res.get(i)[j]!=null)
sums += menu[j] * res.get(i)[j];
}
if (max < sums && sums < B) {
max = sums;
}
}
System.out.println(max + " max");
}
public static void combinate(double[] left, int n, int k,int sum,
ArrayList<Integer[]> res, Integer[] holder) {
if (n == left.length) {
if (sum == k) {
res.add(holder);
System.out.println(res.size()+" "+Arrays.toString(res.get(res.size()-1)));
}
sum = 0;
return;
}
{
holder[n] = 1;
sum++;
combinate(left, n + 1, k, sum,res, holder);
holder[n] = 0;
sum--;
combinate(left, n + 1, k, sum,res, holder);
}
}
}
}
The answers looks like this:
when print in method combinate, the list elements looks like [1111100000]
while in main method, there are all [000000000000]
what goes wrong here?
if (sum == k)
{
res.add(holder.clone()); // take copy of holder at that moment
System.out.println(res.size()+" "+Arrays.toString(res.get(res.size()-1)));
}
Will Help.
[See Experiment : http://rextester.com/DNNZ68674 ]
Have your method "combinate" return new res like public static ArrayList<Integer[]> combinate(double[] left, int n, int k,int sum,
ArrayList<Integer[]> res, Integer[] holder)
then in your main : res = combinate(...);
You have only a single Integer[] instance that you add to your result (res.add(holder)) and overwrite while unwinding the recursion.
You should add a clone of your array to the result:
res.add(holder.clone());
In the original code you're passing the "holder"-variable as a parameter. In Java parameters are passed by value.
This means, you can change the value inside of the combinate-function, but this will never be reflected back to the calling main-function - that's the nature of call by value.
Related
I'm trying to write this algorithm in Java following the steps below:(I know other solutions, just trying to figure out this one)
int min_diff = LARGE_NUMBER;
int diff;
for (each subset S of size n/2 of A) {
diff = abs(sum(S) – sum(A-S));
if (diff < min_diff) {
min_diff = diff;
TempSet = S;
}
}
print min_diff, TempSet;
I tried to find all subset permutations of size n/2 using the code from this link: https://www.geeksforgeeks.org/print-subsets-given-size-set/
The code in this link print all permutations. I thought first I need to store the arrays in an ArrayList so I can use them in the for loop, but I couldn't get it to work. The code below gives wrong output (every array is 60 60 60 instead of permutations:
static List<int[]> intArrays = new ArrayList<>();
static void combinationUtil(int[]arr, int n, int r, int index, int[] data, int i)
{
if (index == r) {
intArrays.add(data);
return;
}
if (i >= n)
return;
data[index] = arr[i];
combinationUtil(arr, n, r, index + 1, data, i + 1);
combinationUtil(arr, n, r, index, data, i + 1);
}
static void printCombination(int arr[], int n, int r)
{
int data[] = new int[r];
combinationUtil(arr, n, r, 0, data, 0);
for(int[] arr1:intArrays){
System.out.println(Arrays.toString(arr1));
}
}
public static void main(String[] args)
{
int arr[] = { 10, 20, 30, 40,50,60};
int n=arr.length;
int r=n/2;
printCombination(arr, n, r);
}
Can anyone tell me what's wrong with my code? Or how can I solve this problem following the above steps?
Your problem is when you do intArrays.add(data);
intArrays always contains the reference to data array. The array is passed by reference. You gets {60, 60, 60} because is the last state of data array (the last subset).
To fix the problem you must to do intArrays.add(data.Clone()); if exists Clone function or similar in you language or just implement it yourself.
Code in C#. Sorry I don't have any java compiler installed.
static int[] CloneArray(int[] arr)
{
int[] ret = new int[arr.Length];
for (int i = 0; i < arr.Length; ++i) ret[i] = arr[i];
return ret;
}
I am struggling in my code with an error.
This is the error I got:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method recur(Integer[]) in the type D_and_con is not applicable for the arguments (int[])
at edu.uqu.algorithms.inversions.D_and_con.recur(D_and_con.java:27)
at edu.uqu.algorithms.inversions.MainTest.main(MainTest.java:27)
The code computes the number of inversions.
It is:
package edu.uqu.algorithms.inversions;
import java.io.FileNotFoundException;
import java.util.Arrays;
import edu.uqu.algorithms.inversions.util.IOUtil;
public class MainTest {
public static void main(String[] args) {
try {
/*//Inversions using BRUTE FORCE
Integer[] tokens1 = IOUtil.loadFileIntoArray("IntegerArray.txt");
long startTime1 = System.currentTimeMillis();
System.out.println("Started Computing Total nb of invertions BRUTE FORCE..........................");
System.out.println("Total nb of invertions BRUTE FORCE: " + Inversions.countInvertionsBruteForce(tokens1));
long runningTime1 = (System.currentTimeMillis() - startTime1);
System.out.println("BRUTE FORCE Running time: " + runningTime1);
System.out.println("\n");*/
//Inversions using DIVIDE & CONQUER
Integer[] tokens2 = IOUtil.loadFileIntoArray("IntegerArray.txt");
long startTime2 = System.currentTimeMillis();
System.out.println("Started Computing Total nb of invertions DIVIDE & CONQUER..........................");
System.out.println("MMMMM" + D_and_con.recur(tokens2) );
long runningTime2 = (System.currentTimeMillis() - startTime2);
System.out.println("DIVIDE & CONQUER Running time: " + runningTime2);
System.out.println("----------------------- FINISHED -------------------------");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
----------------------------------------
/************************************
*
* The aim of this code is to count the number of inversions in
* an array of integers. Two ways of counting are used, a Brute Force algorithm and
* a recursive Divide and Conquer algorithm.
*
***********************************/
package edu.uqu.algorithms.inversions;
/**
public class Inversions{
/**
* Brute force inversions counting method.
*/
public static long countInvertionsBruteForce(Integer[] entries_p)
{
long result = 0;
for(int i = 0; i < entries_p.length; i++){
for(int j = i+1; j < entries_p.length; j++){
if(entries_p[i] > entries_p[j]) result++;
}
//System.out.println("BRUTE FORCE intermediate result for i = " + i + " IS: " + result);
}
return result;
}
}
--------------------------
Divide and conquer
/************************************
*
* The aim of this code is to count the number of inversions in
* an array of integers. Two ways of counting are used, a Brute Force algorithm and
* a recursive Divide and Conquer algorithm.
*
***********************************/
package edu.uqu.algorithms.inversions;
import java.math.BigDecimal;
public class D_and_con{
private static BigDecimal totalcount = new BigDecimal(0);
public static Integer[] recur(Integer[] entries_p)
{
int n = entries_p.length;
if(n == 1)
{
return entries_p;
}
int middel = n/2;
int[] Larray = new int[middel];
int[] Rarray = new int[n - middel];
System.arraycopy(entries_p , 0 , Larray, 0 , Larray.length );
System.arraycopy(entries_p , Larray.length , Rarray , 0 , Rarray.length);
recur(Larray);\\ERROR APPEAR HERE
recur(Rarray);\\ERROR APPEAR HERE
comb(Larray , Rarray , entries_p );
return entries_p;
}
private static void comb(int[] Larray, int[] Rarray, Integer[] newarray)
{
int LarrayL = Larray.length;
int RarrayL = Rarray.length;
int i=0 , j=0 , k=0 ;
while(i< LarrayL && i<RarrayL)
{
if(Larray[i] < Rarray[i] )
{
newarray[k] = Larray[i];
i++;
}
else
{
newarray[k] = Rarray[j];
i++;
totalcount = totalcount.add (new BigDecimal(Larray.length - 1));
}
k++;
}
while(i < LarrayL) {
newarray[k] = Larray[i];
i++;
k++;
}
while(j < RarrayL) {
newarray[k] = Rarray[j];
j++;
k++;
}
}
}
Explanation
The compiler complaints that you feed your recur method with something of type int[] but you declared that it accepts Integer[]. Therefore take a look at the method signature
// entries_p is Integer[], not int[]
public static Integer[] recur(Integer[] entries_p)
but you feed the method with int[] as seen here
int[] Larray = new int[middel];
int[] Rarray = new int[n - middel];
...
recur(Larray);
recur(Rarray);
Integer is different to int. Though Java can automatically convert both into each other (boxing) it won't do that for advanced types liked arrays Integer[] and int[].
Converting
You will need to convert the types by yourself. Note that Integer[] in contrast to int[] is capable of storing null.
Here are some easy conversions, first without using Streams:
// from int[] to Integer[]
int[] source = ...
Integer[] target = new Integer[source.length];
for (int i = 0; i < source.length; i++) {
// Convert int to Integer
target[i] = Integer.valueOf(source[i]);
}
// from Integer[] to int[]
Integer[] source = ...
int[] target = new int[source.length];
for (int i = 0; i < source.length; i++) {
if (source[i] == null) {
// Don't support null values
throw IllegalArgumentException();
}
// Convert Integer to int
target[i] = source[i].intValue();
}
And now the same using Streams (Java 8):
// from int[] to Integer[]
int[] source = ...
Integer[] target = Arrays.stream() // IntStream
.boxed() // Stream<Integer>
.toArray(Integer[]::new)
// from Integer[] to int[]
Integer[] source = ...
int[] target = Arrays.stream() // Stream<Integer>
.mapToInt(Integer::intValue) // Stream<Integer>
.toArray(int[]::new)
Changing method or argument
Instead of converting the array from one into the other type you may also adjust your method or the argument. For example you could change the method signature from
public static Integer[] recur(Integer[] entries_p)
to
public static Integer[] recur(int[] entries_p)
then it will accept int[] as argument. You may also change the return type to int[]. The other alternative would, as said, be to change the argument from int[] to Integer[]. This applies to that code section:
// You may change both to Integer[]
int[] Larray = new int[middel];
int[] Rarray = new int[n - middel];
Change your Integer[] arrays to int[] arrays!
"int" is a primitive data-type and "Integer" is a Class.
To solve your problem:-
1 - Integer[] tokens2 = IOUtil.loadFileIntoArray("IntegerArray.txt"); //Read data from file in int[].
2 - Integer[] recur(Integer[] entries_p){} //change it as int[] recur(int[] entries_p)
I have a 2D array
int[][] lists=new int[][]{{22, 23},{34, 35},{47, 15}};
I have to get all combinations of each elements in every rows, like this:
int [][] result= {{22,34,47},{22,34,15},{22,35,47},{22,35,15},{23,34,47},{23,34,15},{23,35,47},{23,35,15}}
Then for each rows from the newest array I have to calculate average. For this I create a method average(int[]a).
All I need is to get only those combinations with highest average.
Because my initial array can have a large number of rows/columns, I'm trying to generate each combination and check if it's average is higher then memorate it.
Here is my code, but obviously it doesn't work. Can someone help me?
public static int average(int[]a)
{
int sum=0;
for(int i=0;i<a.length;i++)sum+=a[i];
return sum/a.length;
}
public static void cartesian(int[][] lists, int[] values, int n)
{
int sum=0;
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (n == lists.length) {
if(average(values)>sum) {
result.clear();
result.add(Arrays.stream(values).boxed().collect(java.util.stream.Collectors.toList()));
sum=average(values);}
}
else
{
for(int i: lists[n]) {
values[n] = i;
cartesian(lists, values, n+1);
}
}
return result;
}
public static void main(String[] args)
{
List<List<Integer>> result = cartesian(lists, new int[lists.length], 0);
for(List<Integer> i: result) System.out.println(i);
}
I think there are a couple errors of logic in your cartesian code. From what I can tell, that is the function that determines what array has the highest average. First of all, in the statement
int sum=0;
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (n == lists.length) {
if(average(values)>sum) {
The last line is irrelevant - you've defined sum so that if your values aren't negative the if statement will always be true. Also, later in the code,
else
{
for(int i: lists[n]) {
values[n] = i;
cartesian(lists, values, n+1);
}
I think you meant to put cartesian(lists, values, n+1) outside of the for loop. Here is how I would rewrite this code:
public static void cartesian(int[][] lists, int[] values, int n)
{
int sum=0;
List<List<Integer>> result = new ArrayList<List<Integer>>();
int[] totest = lists[n];
if(average(totest) > average(values) || r.equals(null)) {
result.clear();
result.add(Arrays.stream(totest).boxed().collect(java.util.stream.Collectors.toList()));
if(n != lists.length - 1){cartesian(lists, totest, n + 1)};
}
else
{
if(n != lists.length - 1){cartesian(lists, totest, n + 1)};
}
return result;
}
It's trivial to write a function to determine the min/max value in an array, such as:
/**
*
* #param chars
* #return the max value in the array of chars
*/
private static int maxValue(char[] chars) {
int max = chars[0];
for (int ktr = 0; ktr < chars.length; ktr++) {
if (chars[ktr] > max) {
max = chars[ktr];
}
}
return max;
}
but isn't this already done somewhere?
Using Commons Lang (to convert) + Collections (to min/max)
import java.util.Arrays;
import java.util.Collections;
import org.apache.commons.lang.ArrayUtils;
public class MinMaxValue {
public static void main(String[] args) {
char[] a = {'3', '5', '1', '4', '2'};
List b = Arrays.asList(ArrayUtils.toObject(a));
System.out.println(Collections.min(b));
System.out.println(Collections.max(b));
}
}
Note that Arrays.asList() wraps the underlying array, so it should not be too memory intensive and it should not perform a copy on the elements of the array.
You can simply use the new Java 8 Streams but you have to work with int.
The stream method of the utility class Arrays gives you an IntStream on which you can use the min method. You can also do max, sum, average,...
The getAsInt method is used to get the value from the OptionalInt
import java.util.Arrays;
public class Test {
public static void main(String[] args){
int[] tab = {12, 1, 21, 8};
int min = Arrays.stream(tab).min().getAsInt();
int max = Arrays.stream(tab).max().getAsInt();
System.out.println("Min = " + min);
System.out.println("Max = " + max)
}
}
==UPDATE==
If execution time is important and you want to go through the data only once you can use the summaryStatistics() method like this
import java.util.Arrays;
import java.util.IntSummaryStatistics;
public class SOTest {
public static void main(String[] args){
int[] tab = {12, 1, 21, 8};
IntSummaryStatistics stat = Arrays.stream(tab).summaryStatistics();
int min = stat.getMin();
int max = stat.getMax();
System.out.println("Min = " + min);
System.out.println("Max = " + max);
}
}
This approach can give better performance than classical loop because the summaryStatistics method is a reduction operation and it allows parallelization.
The Google Guava library has min and max methods in its Chars, Ints, Longs, etc. classes.
So you can simply use:
Chars.min(myarray)
No conversions are required and presumably it's efficiently implemented.
By sorting the array, you get the first and last values for min / max.
import java.util.Arrays;
public class apples {
public static void main(String[] args) {
int a[] = {2,5,3,7,8};
Arrays.sort(a);
int min =a[0];
System.out.println(min);
int max= a[a.length-1];
System.out.println(max);
}
}
Although the sorting operation is more expensive than simply finding min/max values with a simple loop. But when performance is not a concern (e.g. small arrays, or your the cost is irrelevant for your application), it is a quite simple solution.
Note: the array also gets modified after this.
Yes, it's done in the Collections class. Note that you will need to convert your primitive char array to a Character[] manually.
A short demo:
import java.util.*;
public class Main {
public static Character[] convert(char[] chars) {
Character[] copy = new Character[chars.length];
for(int i = 0; i < copy.length; i++) {
copy[i] = Character.valueOf(chars[i]);
}
return copy;
}
public static void main(String[] args) {
char[] a = {'3', '5', '1', '4', '2'};
Character[] b = convert(a);
System.out.println(Collections.max(Arrays.asList(b)));
}
}
I have a little helper class in all of my applications with methods like:
public static double arrayMax(double[] arr) {
double max = Double.NEGATIVE_INFINITY;
for(double cur: arr)
max = Math.max(max, cur);
return max;
}
You could easily do it with an IntStream and the max() method.
Example
public static int maxValue(final int[] intArray) {
return IntStream.range(0, intArray.length).map(i -> intArray[i]).max().getAsInt();
}
Explanation
range(0, intArray.length) - To get a stream with as many elements as present in the intArray.
map(i -> intArray[i]) - Map every element of the stream to an actual element of the intArray.
max() - Get the maximum element of this stream as OptionalInt.
getAsInt() - Unwrap the OptionalInt. (You could also use here: orElse(0), just in case the OptionalInt is empty.)
public int getMin(int[] values){
int ret = values[0];
for(int i = 1; i < values.length; i++)
ret = Math.min(ret,values[i]);
return ret;
}
import java.util.Random;
public class Main {
public static void main(String[] args) {
int a[] = new int [100];
Random rnd = new Random ();
for (int i = 0; i< a.length; i++) {
a[i] = rnd.nextInt(99-0)+0;
System.out.println(a[i]);
}
int max = 0;
for (int i = 0; i < a.length; i++) {
a[i] = max;
for (int j = i+1; j<a.length; j++) {
if (a[j] > max) {
max = a[j];
}
}
}
System.out.println("Max element: " + max);
}
}
A solution with reduce():
int[] array = {23, 3, 56, 97, 42};
// directly print out
Arrays.stream(array).reduce((x, y) -> x > y ? x : y).ifPresent(System.out::println);
// get the result as an int
int res = Arrays.stream(array).reduce((x, y) -> x > y ? x : y).getAsInt();
System.out.println(res);
>>
97
97
In the code above, reduce() returns data in Optional format, which you can convert to int by getAsInt().
If we want to compare the max value with a certain number, we can set a start value in reduce():
int[] array = {23, 3, 56, 97, 42};
// e.g., compare with 100
int max = Arrays.stream(array).reduce(100, (x, y) -> x > y ? x : y);
System.out.println(max);
>>
100
In the code above, when reduce() with an identity (start value) as the first parameter, it returns data in the same format with the identity. With this property, we can apply this solution to other arrays:
double[] array = {23.1, 3, 56.6, 97, 42};
double max = Arrays.stream(array).reduce(array[0], (x, y) -> x > y ? x : y);
System.out.println(max);
>>
97.0
Here's a utility class providing min/max methods for primitive types: Primitives.java
int [] numbers= {10,1,8,7,6,5,2};
int a=Integer.MAX_VALUE;
for(int c:numbers) {
a=c<a?c:a;
}
System.out.println("Lowest value is"+a);
Example with float:
public static float getMaxFloat(float[] data) {
float[] copy = Arrays.copyOf(data, data.length);
Arrays.sort(copy);
return copy[data.length - 1];
}
public static float getMinFloat(float[] data) {
float[] copy = Arrays.copyOf(data, data.length);
Arrays.sort(copy);
return copy[0];
}
Pass the array to a method that sorts it with Arrays.sort() so it only sorts the array the method is using then sets min to array[0] and max to array[array.length-1].
The basic way to get the min/max value of an Array. If you need the unsorted array, you may create a copy or pass it to a method that returns the min or max. If not, sorted array is better since it performs faster in some cases.
public class MinMaxValueOfArray {
public static void main(String[] args) {
int[] A = {2, 4, 3, 5, 5};
Arrays.sort(A);
int min = A[0];
int max = A[A.length -1];
System.out.println("Min Value = " + min);
System.out.println("Max Value = " + max);
}
}
Here is a solution to get the max value in about 99% of runs (change the 0.01 to get a better result):
public static double getMax(double[] vals){
final double[] max = {Double.NEGATIVE_INFINITY};
IntStream.of(new Random().ints((int) Math.ceil(Math.log(0.01) / Math.log(1.0 - (1.0/vals.length))),0,vals.length).toArray())
.forEach(r -> max[0] = (max[0] < vals[r])? vals[r]: max[0]);
return max[0];
}
(Not completely serious)
int[] arr = {1, 2, 3};
List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
int max_ = Collections.max(list);
int i;
if (max_ > 0) {
for (i = 1; i < Collections.max(list); i++) {
if (!list.contains(i)) {
System.out.println(i);
break;
}
}
if(i==max_){
System.out.println(i+1);
}
} else {
System.out.println("1");
}
}
It's trivial to write a function to determine the min/max value in an array, such as:
/**
*
* #param chars
* #return the max value in the array of chars
*/
private static int maxValue(char[] chars) {
int max = chars[0];
for (int ktr = 0; ktr < chars.length; ktr++) {
if (chars[ktr] > max) {
max = chars[ktr];
}
}
return max;
}
but isn't this already done somewhere?
Using Commons Lang (to convert) + Collections (to min/max)
import java.util.Arrays;
import java.util.Collections;
import org.apache.commons.lang.ArrayUtils;
public class MinMaxValue {
public static void main(String[] args) {
char[] a = {'3', '5', '1', '4', '2'};
List b = Arrays.asList(ArrayUtils.toObject(a));
System.out.println(Collections.min(b));
System.out.println(Collections.max(b));
}
}
Note that Arrays.asList() wraps the underlying array, so it should not be too memory intensive and it should not perform a copy on the elements of the array.
You can simply use the new Java 8 Streams but you have to work with int.
The stream method of the utility class Arrays gives you an IntStream on which you can use the min method. You can also do max, sum, average,...
The getAsInt method is used to get the value from the OptionalInt
import java.util.Arrays;
public class Test {
public static void main(String[] args){
int[] tab = {12, 1, 21, 8};
int min = Arrays.stream(tab).min().getAsInt();
int max = Arrays.stream(tab).max().getAsInt();
System.out.println("Min = " + min);
System.out.println("Max = " + max)
}
}
==UPDATE==
If execution time is important and you want to go through the data only once you can use the summaryStatistics() method like this
import java.util.Arrays;
import java.util.IntSummaryStatistics;
public class SOTest {
public static void main(String[] args){
int[] tab = {12, 1, 21, 8};
IntSummaryStatistics stat = Arrays.stream(tab).summaryStatistics();
int min = stat.getMin();
int max = stat.getMax();
System.out.println("Min = " + min);
System.out.println("Max = " + max);
}
}
This approach can give better performance than classical loop because the summaryStatistics method is a reduction operation and it allows parallelization.
The Google Guava library has min and max methods in its Chars, Ints, Longs, etc. classes.
So you can simply use:
Chars.min(myarray)
No conversions are required and presumably it's efficiently implemented.
By sorting the array, you get the first and last values for min / max.
import java.util.Arrays;
public class apples {
public static void main(String[] args) {
int a[] = {2,5,3,7,8};
Arrays.sort(a);
int min =a[0];
System.out.println(min);
int max= a[a.length-1];
System.out.println(max);
}
}
Although the sorting operation is more expensive than simply finding min/max values with a simple loop. But when performance is not a concern (e.g. small arrays, or your the cost is irrelevant for your application), it is a quite simple solution.
Note: the array also gets modified after this.
Yes, it's done in the Collections class. Note that you will need to convert your primitive char array to a Character[] manually.
A short demo:
import java.util.*;
public class Main {
public static Character[] convert(char[] chars) {
Character[] copy = new Character[chars.length];
for(int i = 0; i < copy.length; i++) {
copy[i] = Character.valueOf(chars[i]);
}
return copy;
}
public static void main(String[] args) {
char[] a = {'3', '5', '1', '4', '2'};
Character[] b = convert(a);
System.out.println(Collections.max(Arrays.asList(b)));
}
}
I have a little helper class in all of my applications with methods like:
public static double arrayMax(double[] arr) {
double max = Double.NEGATIVE_INFINITY;
for(double cur: arr)
max = Math.max(max, cur);
return max;
}
You could easily do it with an IntStream and the max() method.
Example
public static int maxValue(final int[] intArray) {
return IntStream.range(0, intArray.length).map(i -> intArray[i]).max().getAsInt();
}
Explanation
range(0, intArray.length) - To get a stream with as many elements as present in the intArray.
map(i -> intArray[i]) - Map every element of the stream to an actual element of the intArray.
max() - Get the maximum element of this stream as OptionalInt.
getAsInt() - Unwrap the OptionalInt. (You could also use here: orElse(0), just in case the OptionalInt is empty.)
public int getMin(int[] values){
int ret = values[0];
for(int i = 1; i < values.length; i++)
ret = Math.min(ret,values[i]);
return ret;
}
import java.util.Random;
public class Main {
public static void main(String[] args) {
int a[] = new int [100];
Random rnd = new Random ();
for (int i = 0; i< a.length; i++) {
a[i] = rnd.nextInt(99-0)+0;
System.out.println(a[i]);
}
int max = 0;
for (int i = 0; i < a.length; i++) {
a[i] = max;
for (int j = i+1; j<a.length; j++) {
if (a[j] > max) {
max = a[j];
}
}
}
System.out.println("Max element: " + max);
}
}
A solution with reduce():
int[] array = {23, 3, 56, 97, 42};
// directly print out
Arrays.stream(array).reduce((x, y) -> x > y ? x : y).ifPresent(System.out::println);
// get the result as an int
int res = Arrays.stream(array).reduce((x, y) -> x > y ? x : y).getAsInt();
System.out.println(res);
>>
97
97
In the code above, reduce() returns data in Optional format, which you can convert to int by getAsInt().
If we want to compare the max value with a certain number, we can set a start value in reduce():
int[] array = {23, 3, 56, 97, 42};
// e.g., compare with 100
int max = Arrays.stream(array).reduce(100, (x, y) -> x > y ? x : y);
System.out.println(max);
>>
100
In the code above, when reduce() with an identity (start value) as the first parameter, it returns data in the same format with the identity. With this property, we can apply this solution to other arrays:
double[] array = {23.1, 3, 56.6, 97, 42};
double max = Arrays.stream(array).reduce(array[0], (x, y) -> x > y ? x : y);
System.out.println(max);
>>
97.0
Here's a utility class providing min/max methods for primitive types: Primitives.java
int [] numbers= {10,1,8,7,6,5,2};
int a=Integer.MAX_VALUE;
for(int c:numbers) {
a=c<a?c:a;
}
System.out.println("Lowest value is"+a);
Example with float:
public static float getMaxFloat(float[] data) {
float[] copy = Arrays.copyOf(data, data.length);
Arrays.sort(copy);
return copy[data.length - 1];
}
public static float getMinFloat(float[] data) {
float[] copy = Arrays.copyOf(data, data.length);
Arrays.sort(copy);
return copy[0];
}
Pass the array to a method that sorts it with Arrays.sort() so it only sorts the array the method is using then sets min to array[0] and max to array[array.length-1].
The basic way to get the min/max value of an Array. If you need the unsorted array, you may create a copy or pass it to a method that returns the min or max. If not, sorted array is better since it performs faster in some cases.
public class MinMaxValueOfArray {
public static void main(String[] args) {
int[] A = {2, 4, 3, 5, 5};
Arrays.sort(A);
int min = A[0];
int max = A[A.length -1];
System.out.println("Min Value = " + min);
System.out.println("Max Value = " + max);
}
}
Here is a solution to get the max value in about 99% of runs (change the 0.01 to get a better result):
public static double getMax(double[] vals){
final double[] max = {Double.NEGATIVE_INFINITY};
IntStream.of(new Random().ints((int) Math.ceil(Math.log(0.01) / Math.log(1.0 - (1.0/vals.length))),0,vals.length).toArray())
.forEach(r -> max[0] = (max[0] < vals[r])? vals[r]: max[0]);
return max[0];
}
(Not completely serious)
int[] arr = {1, 2, 3};
List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
int max_ = Collections.max(list);
int i;
if (max_ > 0) {
for (i = 1; i < Collections.max(list); i++) {
if (!list.contains(i)) {
System.out.println(i);
break;
}
}
if(i==max_){
System.out.println(i+1);
}
} else {
System.out.println("1");
}
}