Reputation: 13
Given two random arrays that are five integers long (and have a max value of 6 for each integer), I need a function that compares which array has the lowest integer. If the two arrays have the same lowest integer, The function compares the next two lowest, and so on. the only methods I can think of for smallestOfTwo() would take hundreds of lines of data, and too much memory. Here's what little I have so far:
public static void main(String[] args) {
int[] n= new int [5];
int[] m= new int [5];
for(int i=0; i<n.length; i++) {
n[i]=(int) (Math.random() * 6) + 1;
}
for(int x=0;x<n.length;x++) {
m[x]=(int) (Math.random() * 6) + 1;
}
System.out.println(smallestOfTwo(n,m)+" has the smallest value of the two arrays");
}
public static String smallestOfTwo(int[] x,int[] y) {
String smallest = "unassigned";
//help??
if() {
smallest = "Array n"
}
else
smallest = "Array m"
return smallest;
}
Upvotes: 1
Views: 62
Reputation: 56423
you could sort the arrays first which will make the task at hand easier to solve than simply loop through the arrays and compare their values.
public static String smallestOfTwo(int[] n,int[] m)
{
Arrays.sort(n);
Arrays.sort(m);
for (int i = 0; i < n.length; i++) {
if(n[i] < m[i]){
return "Array n";
}else if(n[i] > m[i]){
return "Array m";
}
}
return "both Array n & Array m are the same";
}
Upvotes: 1
Reputation: 618
You can use Arrays Class it has a static method sort
Ex: int arr[]={5,3,2,1};
Arrays.sort(arr);
the new array will be sorted and just take the first or the last as you want (the largest or the smallest)
You can see Arrays methods in this site
https://www.tutorialspoint.com/java/util/java_util_arrays.htm
Upvotes: 0
Reputation: 2119
Sort the arrays using Bubble sort in a descending order, go for the last index in both. Now you have to compare these two.
Upvotes: 0