I'm trying to make a method than returns the second bigger number of an array.
When I return the value, in console appears 2 or more values. I can't understand why is this happening. Can somebody help me to understand this, please?
I did a method to search the bigger value so I can use it on the one which returns the second bigger.
public class ThirdMax {
public static int maxNum (int[] array) { //Returns the bigger value of the array.
int aux = 0; //Variable to store the bigger value found and compare it with the rest.
for (int i = 0; i < array.length; i++) {
if(array[i] > aux) { //If the actual value is bigger than the aux
aux = array[i]; //override the aux value with actual value.
}
}
System.out.println(aux);
return aux;
}
public static int secondMax(int[] array) { //Returns the second bigger value on the array.
int valorMax = maxNum(array); //Store the bigger value on a variable so we can use it later.
int valorMax2 = 0; //Variable to store the result.
int[] auxArray = new int [array.length];
for (int i = 0; i < array.length; i++) {
if(array[i] == valorMax) { //When we get to the valorMax, we replace it in the array with a 0.
array[i] = 0;
} else {
auxArray[i] = array[i];
}
valorMax2 = maxNum(auxArray); //Search again the bigger value after the previous one is replaced by 0.
}
return valorMax2;
}
}
Thanks in advance for your time!
You call maxNum(auxArray); multiple times. Each of them prints a max value.
Hence you received multiple result.
To immediately resolve it, remove the print System.out.println(aux);
in your function.
And make only one print function right before you return
System.out.println(valorMax2);
return valorMax2;
But your code looks not good. It need multiple improvement.
To find the second biggest number, you only need to loop once like this:
public static int secondMax(int[] array) {
int max = Integer.MIN_VALUE; // Max value
int secondMax = Integer.MIN_VALUE; // Second max value, its our result
for (int i = 0; i < array.length; i++) {
if (array[i] > max) {
secondMax = max;
max = array[i];
} else if (array[i] > secondMax) {
secondMax = array[i];
}
}
return secondMax;
}
This looks OK, but can't extends to find n-th max number, because our if conditions will be very complex. Then you try to find max number once at a time:
// Return max number in array which is lower than ceilValue
// Return Integer.MIN_VALUE if no such value found
public static int maxValueBelow(int[] array, int ceilValue) {
int max = Integer.MIN_VALUE;
for (int i = 0; i<array.length; i++) {
if (array[i] < ceilValue && array[i] > max) {
max = array[i];
}
}
return max;
}
public static int findNthValue(int[] array) {
int maxValue = maxValueBelow(array, Integer.MAX_VALUE);
int secondMaxValue = maxValueBelow(array, maxValue);
int thirdMaxValue = maxValueBelow(array, secondMaxValue);
// You can improve this function by give it's a second parameter `n`, and use for loop to find the `n-th` max value.
}
Since you're setting the largest number to 0 you really don't need auxArray.
You also don't need a second valorMax.
You might want to refactor your code to the following.
public static int secondMax(int[] array) {
int valorMax = maxNum(array);
for (int i = 0; i < array.length; i++) {
if(array[i] == valorMax) {
array[i] = 0;
}
}
return maxNum(array); // just return the result of maxNum(array)
}
be sure to remove the print statement from maxNum if you don't want your program to print 2 numbers to console.
Because you put get second max function in the wrong place.
public static int secondMax(int[] array) {
int valorMax = maxNum(array);
int valorMax2 = 0;
int[] auxArray = new int [array.length];
for (int i = 0; i < array.length; i++) {
if(array[i] == valorMax) {
array[i] = 0;
} else {
auxArray[i] = array[i];
}
}
valorMax2 = maxNum(auxArray); // this should be out of loop
return valorMax2;
}
}
Related
So far, I have this method, which is supposed to find the max age of a ArrayList. However, in my data, I have two values that are tied at 58 for joint max. How do I get the second 58 from this loop? the index of the first 58 is 1, but the index I need is 4. I cannot hard code.
public static int maxAge (ArrayList<Integer> ages) {
int hold = 0;
int max = 0;
for (int i = 0; i < ages.size(); i++) {
if (max < ages.get(i)) {
max = ages.get(i);
hold = i;
}
else i++;
}
return hold;
}
You can simply change your condition to:
if (max <= ages.get(i))
It depends on why you want the other 58. If you want to return the latest match, you can just loop backwards.
I know, is ugly. But I would try to write a functional version.
Optional<Integer> max = ages.stream()
.max(Integer::compare);
if (max.isPresent()) {
return IntStream.range(0, ages.size())
.mapToObj(pos -> {
return new int[] {pos, ages.get(pos)};
})
.filter(pair -> pair[1] == max.get())
.collect(Collectors.toCollection(LinkedList::new))
.getLast()[0];
} else
return 0;
There are multiple ways to change the condition to fit your description. Try this:
public static int maxAge (ArrayList<Integer> ages) {
int hold = 0;
int max = 0;
for (int i = 0; i < ages.size(); i++) {
if (max < ages.get(i) || max == ages.get(i) {
max = ages.get(i);
hold = i;
}
else i++;
}
return hold;
}
The code below, will enable you return all the indexes associated with the maximum value of your list. But you must run it on Java 8 since it use Lambda Expressions.
public static ArrayList<Integer> maxAge (ArrayList<Integer> ages ) {
int max = 0;
ArrayList<Integer> maxIndexes = new ArrayList<Integer>() ;
for (int i = 0; i < ages.size(); i++) {
if (max <= ages.get(i)) {
final int finalMax = max ;
final int finalIndex = i ;
maxIndexes.removeIf((elt)-> finalMax < ages.get(finalIndex)) ;
maxIndexes.add(i) ;
max = ages.get(i) ;
}
}
return maxIndexes ;
}
I'm having trouble figuring out how exactly to make it find the max number and minimum number in the array.
Write a method range that accepts an ArrayList of integers as a parameter and that returns the range of values contained in the list, which is defined as 1 more than the difference between the largest and smallest elements. For example if a variable called list stores the following values:
[18, 14, 29, 12, 7, 25]
The call of range(list) should return 23, because this is one more than the largest difference between any pair of values (29 - 7 + 1 = 23). An empty list is defined to have a range of 0.
So far I have this:
public static int range(ArrayList<Integer> list)
{
int min = 0;
int max = 0;
int range = 0;
for (int i: list)
{
if (list.size() > 0)
{
range = max - min + 1;
}
}
return range;
}
Thank you VERY MUCH!
You have more than method to achive this goal.
Using Collections (more compact but expensive because it iterates two times on the list, one to find the max and one to find the min):
public static int range(final ArrayList<Integer> list) {
if (list.isEmpty()) {
return 0;
} else {
return (Collections.max(list) - Collections.min(list)) + 1;
}
}
Or using your own algorithm like this (more code but finds min and max with just one loop):
public static int range(final ArrayList<Integer> list) {
if (list.isEmpty()) {
return 0;
} else {
int max = list.get(0);
int min = list.get(0);
for (final int i : list) {
if (i > max) {
max = i;
} else if (i < min) {
min = i;
}
}
return (max - min) + 1;
}
}
Why not use Collections.min and Collections.max
int difference = Collections.max(list) - Collections.min(list);
You never calculate the max and the min value in your loop.
Hint : In this loop, find the max and the min value. Then calculate the range and return it.
int min = 0;
int max = 0;
for (int i: list){
//find max and min here
}
return max - min + 1;
This task only needs two lines:
Collections.sort(list);
return list.isEmpty() ? 0 : list.get(list.size() - 1) - list.get(0);
Use the java JDK's API to do the heavy lifting for you
It's how you look at a problem that's important
Less code is good (as long as it's legible
You could sort it and then peek fist and last item.
public static int range(List<Integer> input)
{
if(input == null || input.size() == 0) throw new IllegalArgumentException("");
if(input.size() == 1) return 0;
List<Integer> copy = new ArrayList(input);
Collections.sort(copy);
int min = copy.get(0);
int max = copy.get(copy.lenght-1);
return max - min;
}
This is not a perfect solution as list may contain nulls.
You can start with simple comparison.
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(Integer integer : input) {
if(i == null) continue;
int i = integer.intValue();
if(i < min) {
min = i;
}
if(i > max) {
max = i;
}
}
return max - min;
public static int range(ArrayList<Integer> list){
int min = list.get(0);
int max = list.get(0);
for (int i = 0; i < list.size(); i++){
if (list.get(i) > max)
max = list.get(i);
if ((list.get(i) < min))
min = list.get(i);
}
return max-min+1;
}
I have another solution that works. Let me explain how it works.
The first if statement checks for the empty list case.
Afterwards, I declared an integer variable int diff to return at the end. Two numbers are selected by the two for loops where the first one starts at index 0 while the nested loop starts at index 1 so that no same numbers are considered when looping through. The difference between two numbers are obtained using the formula declared as int calc. Since we're looking for the biggest difference between two numbers, we set diff = calc and keep it updating.
Lastly, we return diff + 1 as the problem stated.
public int range(ArrayList<Integer> list) {
if (list.size() == 0) {
return 0;
}
int diff = 0;
for (int i = 0; i < list.size(); i++) {
for (int j = 1; j < list.size(); j++) {
int calc = Math.abs(list.get(i) - list.get(j));
if (diff < calc) {
diff = calc;
}
}
}
return diff + 1;
}
class CalorieExpenditures {
String activity
int lbs90
int lbs100
int lbs110
int lbs120
int lbs130
int lbs140
int lbs150
int lbs160
int lbs170
int lbs180
int lbs190
int lbs200
int lbs220
int lbs240
int lbs260
int lbs280
int lbs300
}
From the above POGO (b'se i am using grails).
How to find the nearest lbs property from POGO
e.g
if i pass 282 it will return lbs280 and if i pass 295 it will return lbs300.
logic is the difference between two values if the difference is same will return the grater value.
You can suggest java method or grails method to work with.
I need a simple program that finds nearest value.
Thanks in advance.
Below is example to find given number from int array, with nearest lower & upper
public class FindNearestInt
{
public static void main(String[] args)
{
Random random = new Random();
int array[] = new int[30];
//Initialise array with rendom values
for (int i = 0; i < array.length; i++)
{
array[i] = random.nextInt(200);
}
System.out.println(Arrays.toString(array));
Arrays.sort(array);
System.out.println(Arrays.toString(array));
// Number you want to find in array
int searchFor = 57;
//Nearest lower you searching for
int nearestLower = 0;
//Nearest upper you searching for
int nearestUpper = Integer.MAX_VALUE;
int searchForExist = -1;
for (int i = 0; i < array.length; i++)
{
int j = array[i];
if (j < searchFor)
{
if(j > nearestLower){
nearestLower = j;
}
} else if (j > searchFor){
if(j < nearestUpper){
nearestUpper = j;
}
} else {
nearestLower = -1;
nearestUpper = -1;
searchForExist = j;
break;
}
}
System.out.println("Nearest Lower : " + nearestLower);
// This will print -1 if number exist in array
System.out.println("Provided Number Already Exist : " + searchForExist);
System.out.println("Nearest Upper : " + nearestUpper);
}
}
A simpler and faster solution is to use a formula
public static int nearest(int num) {
return num < 90 ? 90 :
num < 200 ? Math.round(num/10.0) * 10 :
num < 300 ? Math.round(num/20.0) * 20 : 300;
def calorieExpendituresWeightCategory(float weight){
int nearest = 0;
int min = Integer.MAX_VALUE
CalorieExpenditures.properties.each {
if(it.toString().startsWith("lbs")){
int j = it.toString().substring(it.toString().indexOf("lbs"))
int k = (weight - j) * (weight - j)
if(k < min){
min = k
nearest = j
}
}
}
return nearest
}
This works for me i think simple and works for me.
Thanks for the answers.
I wrote a method to get the maximum number in the queue , but I need to return the location of the maximum number in the queue .
this is the max method I wrote :
public int maxValue(int[] array) {
int maximum = array[0];
for (int i = 0; i < array.length; i++) {
if (array[i] > maximum) {
maximum = array[i];
}
}
return maximum;
}
Use a int maximumIndex besides:
int maximumIndex = 0;
...
maximumIndex = i;
...
return maximumIndex;
How do I create a method that takes a two-dimensional array as a parameter and displays the index of the row with the most zeros? The program I have does compile. It just displays an incorrect result. The method countZeros() counts the number of zeros in each row. I need to compare each count with the next, so I created count and count2. The location of the greater count will be stored in rowNum. I'm not sure what I am doing wrong. I think it may be indexing incorrectly.
Here is my code:
public class P118
{
public static void main(String[]args)
{
int[][]num = {{0,3,6,0,0}, {1,3,8,9,8}, {9,9,9,0,8}, {3,7,9,9,9}};
System.out.print(rowWithMostZeros(num));
}
public static int rowWithMostZeros(int[][]arr)
{
int count = 0, count2 = 0, rowNum = -1;
for(int row = 0; row<arr.length;row++)
{
count = countZeros(arr[row]);
if(count>count2)
{
rowNum = row;
}
}
for(int i=0; i<arr.length;i++)
{
count2 = countZeros(arr[i]);
}
return rowNum;
}
public static int countZeros(int[]x)
{
int count = 0;
for(int i = 0; i<x.length;i++)
{
if(x[i]==0)
{
count++;
}
}
return count;
}
}
Try this:
public static int rowWithMostZeros(int[][] arr) {
if (arr == null || arr.length < 1) {
return -1;
}
int rowWithMostZeros = 0;
int count = countZeros(arr[0]);
for (int i = 1; i < arr.length; i++) {
int count2 = countZeros(arr[i]);
if (count2 > count) {
rowWithMostZeros = i;
}
}
return rowWithMostZeros;
}
public static int countZeros(int[] arr) {
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
count += 1;
}
}
return count;
}
Any code that counts occurrences could work with the following method:
Start with with either using the first row, or invalid data as the 'max'
Check if the other values are greater. If they are, replace
the 'max' count ( the amount) and the 'row number' with that one.
Here is the code that first sets the values to the first row being the max, and then checks if any of the other rows have more zeros.:
public static int rowWithMostZeros(int[][]arr)
{
int mostZeroCount = countZeros(arr[0];
int rowNum = 0;
for(int row = 1; row<arr.length;row++)
{
int count = countZeros(arr[row]);
if(count>mostZeroCount)
{
rowNum = row;
mostZeroCount = count;
}
}
return rowNum;
}
The problem with the original method was that it always set count to be the next value which had more then one 0, without comparing to the actual maximum amount of 0's previously seen. Therefore, at the end, it would simply return the last row that had at least one 0 (Which in this case was Row 2, the third row)
You should use the variable count2 to store the maximum number of zeros in all rows so far, in order to compare it with the next row. In order to do this, you need to assign it the current count inside the if block, in case the "count" is bigger than count2. I have redesigned your code below using maxCount and currentCount, for extra clarity. The second loop in your code is unnecessary, I didn't really understood why you did it.
public static int rowWithMostZeros(int[][]arr){
int currentCount = 0, maxCount = 0, rowNum = -1;
for(int row = 0; row maxCount){
maxCount = currentCount;
rowNum = row;
}
return rowNum;
}
public static int countZeros(int[]x){
int count = 0;
for(int i = 0; i<x.length;i++){
if(x[i]==0){
count++;
}
}
return count;
}