I am trying to print an output that would find the max number and also print the index number of the array as well. I am able to print the max number but I am unable to print the index number.
public static int findMax(int[] allNumbers) {
int maxValue = allNumbers[0];
for (int i = 1; i < allNumbers.length; i++) {
if (allNumbers[i] > maxValue) {
maxValue = allNumbers[i];
}
}
return (int) maxValue;
}
my array:
int[] allNumbers = new int[inpNum];
I can call the max number with the following
findMax(number)
You can return an array of the max value and index:
public static int[] findMax(int[] allNumbers) {
int maxValue = allNumbers[0];
int index = 0;
for (int i = 1; i < allNumbers.length; i++) {
if (allNumbers[i] > maxValue) {
maxValue = allNumbers[i];
index = i;
}
}
return new int[] {maxValue , index};
}
Related
Hello I want find the highest index n array. For example I have two arrays :
[1,2,3,0,-1] - should return 2 - index with max values
[] - should return -1 because array is empty
I have method:
public int findMax(int[] array){
int values =0;
for(int i=0; i<array.length; i++){
if(array == null)
{return -1;}
else(array{i}>values){
return i;
}
}
What i'm doing wrong?
Your program has logical as well as compilation errors. I guess you want to write a code like this,
public static void main(String[] args) throws IOException {
System.out.println(findMax(new int[] { 1, 2, 3, 0, -1 }));
System.out.println(findMax(new int[] {}));
}
public static int findMax(int[] array) {
if (array == null || array.length == 0) {
return -1;
}
int maxIndex = 0;
int maxNum = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > maxNum) {
maxNum = array[i];
maxIndex = i;
}
}
return maxIndex;
}
Like you expected, this gives following output,
2
-1
Suppose you want to find both maximum element and first index of maximum value.
Code for this:
public void findMax(int[] array){
int values =-99999999; //values is any large negative number
int index=-1;
if(array.length == 0)
{System.out.println("-1");}
for(int i=0; i<array.length; i++){
if(array[i]>values){
values=array[i];
index=i;
}
System.out.println("Max element is"+values +"and index is"+index);
}
}
Try this one:
public int findMax(int[] array) {
if (array == null || array.length == 0)
return -1;
int index = 0;
int max = -Integer.MAX_VALUE;
for (int i=0; i< array.length; i++) {
if (array[i] > max) {
index = i;
max = array[i];
}
}
return index;
}
public int findMax(int[] array){
return IntStream.range(0, array.length).boxed().max(Comparator.comparing(i -> array[i])).orElse(-1));
}
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;
}
}
I have written the following code and am now trying to figure out the best way to achieve what is explained in the four comments:
Integer[] expectedValues = new Integer[4];
for (int i = 0; i <= 3; i++) {
expectedValues[i] = getExpectedValue(i);
}
int choice = randomNumGenerator.nextInt(100) + 1;
if (choice <= intelligence) {
// return index of highest value in expectedValues
} else if (choice <= intelligence * 2) {
// return index of 2nd highest value in expectedValues
} else if (choice <= intelligence * 3) {
// return index of 3rd highest value in expectedValues
} else {
// return index of lowest value in expectedValues
}
What would be an elegant way o doing so? I do not need to keep expected values as an array - I am happy to use any data structure.
You could create a new array containing the indices and sort on the values - in semi-pseudo code it could look like this (to be adapted):
int[][] valueAndIndex = new int[n][2];
//fill array:
valueAndIndex[i][0] = i;
valueAndIndex[i][1] = expectedValues[i];
//sort on values in descending order
Arrays.sort(valueAndIndex, (a, b) -> Integer.compare(b[1], a[1]));
//find n-th index
int n = 3; //3rd largest number
int index = valueAndIndex[n - 1][0];
If you want to work with simple arrays, maybe this might be a solution:
public static void main(String[] args) {
int[] arr = new int[] { 1, 4, 2, 3 };
int[] sorted = sortedCopy(arr);
int choice = randomNumGenerator.nextInt(100) + 1;
if (choice <= intelligence) {
System.out.println(findIndex(arr, sorted[3])); // 1
} else if (choice <= intelligence * 2) {
System.out.println(findIndex(arr, sorted[2])); // 3
} else if (choice <= intelligence * 3) {
System.out.println(findIndex(arr, sorted[1])); // 2
} else {
System.out.println(findIndex(arr, sorted[0])); // 0
}
}
static int[] sortedCopy(int[] arr) {
int[] copy = new int[arr.length];
System.arraycopy(arr, 0, copy, 0, arr.length);
Arrays.sort(copy);
return copy;
}
static int findIndex(int[] arr, int val) {
int index = -1;
for (int i = 0; i < arr.length; ++i) {
if (arr[i] == val) {
index = i;
break;
}
}
return index;
}
You can "wipe out" the highest value n-1 times. After this the highest value is the n-th highest value of the original array:
public static void main(String[] args) {
int[] numbers = new int[]{5, 9, 1, 4};
int n = 2; // n-th index
for (int i = 0; i < n - 1; ++i) {
int maxIndex = findMaxIndex(numbers);
numbers[maxIndex] = Integer.MIN_VALUE;
}
int maxIndex = findMaxIndex(numbers);
System.out.println(maxIndex + " -> " + numbers[maxIndex]);
}
public static int findMaxIndex(int[] numbers) {
int maxIndex = 0;
for (int j = 1; j < numbers.length; ++j) {
if (numbers[j] > numbers[maxIndex]) {
maxIndex = j;
}
}
return maxIndex;
}
The complexity is O(n * numbers.length).
So I'm writing a method to calculate mode of a sorted array. But when i print out the mode value, it always comes out as 0.00, and i tried to fix it but could't.
Here's my code for this method:
(numRead is the passed array, num is the array length that actually have values)
public static void modeCalc(double[] numRead, int num)
{
double maxValue = numRead[0];
int maxCount = 0;
for (int i = 0; i < numRead.length; i++)
{
int count = 0;
for (int j = 0; j < numRead.length; j++)
{
if (numRead[j] == numRead[i])
count++;
}
if (count > maxCount)
{
maxCount = count;
maxValue = numRead[i];
}
}
return maxValue;
}
Any help is much appreciated!
This should work. You need to return a double, and you need to use num.
class ModeArray
{
public static void main(String[] args) {
double[] numRead = { 1, 2, 3, 3, 4, 4, 4, 5, 0, 0, 0, 0, 0 };
System.out.println(modeCalc(numRead, 8));
}
public static double modeCalc(double[] numRead, int num) {
double maxValue = numRead[0];
int maxCount = 0;
for (int i = 0; i < num; i++) {
int count = 0;
for (int j = 0; j < num; j++) {
if (numRead[j] == numRead[i]){
count++;
}
}
if (count > maxCount) {
maxCount = count;
maxValue = numRead[i];
}
}
return maxValue;
}
}
If you know the array is sorted, you should use this information.
public static double modeCalc(double[] numRead, int num) {
double maxValue = numRead[0];
double lastValue = maxValue;
int count = 1;
int maxCount = 1;
for (int i = 1; i < num; i++) {
if (numRead[i] == lastValue) {
count++;
} else {
count = 1;
lastValue = numRead[i];
}
if (count > maxCount) {
maxCount = count;
maxValue = lastValue;
}
}
return maxValue;
}
PS: Please don't use if-statement without braces. It makes it easier to add bugs, and harder to find them.
a cursory glance suggests that your array has more 0 values at the end of the sorted data and these become the mode. here is what appears to be the problem, it is stated that numRead is the sorted array, but it has only num values of significance. the loops search the array to the end, not for the number of elements that have good values. change numRead.length to num and see if that helps. also, try passing a full array (no empty elements) and see if it works any better. it is likely that the empty elements are initialized to zero and that there are more of these than any other value.
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.