简体   繁体   中英

Is there a way to get the Math.min() for random integers? Java

I am currently making a game and I'm trying to compare the shortest path that is displayed on screen (which is a random generated path of integers) and the path that the user takes. This part of the code is the one in which I try to get the Math.min() of the total paths on screen:

int path1 = randomNum3 + randomNum8;
int path2 = randomNum2 + randomNum7;
int path3 = randomNum + randomNum6;
int path4 = randomNum3 + randomNum5 + randomNum7;
int path5 = randomNum2 + randomNum5 + randomNum8;
int path6 = randomNum + randomNum4 + randomNum7;
int path7 = randomNum2 + randomNum4 + randomNum6;


int caminoMasCorto = Math.min(path1, path2, path3, path4, path5,
        path6, path7);

The error that is showing me is this one:

no suitable method found for min(int,int,int,int,int,int,int)

method Math.min(int,int) is not applicable

(actual and formal argument lists differ in length)

Yes. As the error says, Math.min(int, int) takes two arguments. Change

int caminoMasCorto = Math.min(path1, path2, path3, path4, path5,
        path6, path7);

to

int caminoMasCorto = Math.min(path1, Math.min(path2, 
        Math.min(path3, Math.min(path4, Math.min(path5, Math.min(path6, path7))))));

or (as Andreas noted)

int caminoMasCorto = Math.min(Math.min(Math.min(Math.min(Math.min(Math.min(
        path1, path2), path3), path4), path5), path6), path7);

Alternatively, you would write your own min function that takes an arbitrary number of int (s) and returns the smallest. Like,

private static int myMin(int... vals) {
    if (vals == null || vals.length < 1) {
        throw new RuntimeException("No values");
    }
    int t = vals[0];
    for (int i = 1; i < vals.length; i++) {
        t = Math.min(t, vals[i]);
    }
    return t;
}

And then use

int caminoMasCorto = myMin(path1, path2, path3, path4, path5,
        path6, path7);

Use whichever you find most readable.

To find the minimum of a lot of int variables, use:

int caminoMasCorto = IntStream.of(path1, path2, path3, path4, path5,
        path6, path7).min().getAsInt();

If you're not using Java 8+, you can do this:

int caminoMasCorto = path1;
for (int value : new int[] { path2, path3, path4, path5, path6, path7 })
    caminoMasCorto = Math.min(caminoMasCorto, value);

Java's Math.min accepts two arguments. To extend this to multiple numbers, try this method:

public int minExtension (int... numbers) {
    int minimum = numbers[0];

    for (int number : numbers) {
        minimum = Math.min(number, minimum)
    }

    return minimum
}

Call it like this

int caminoMasCorto = minExtension (path1, path2, path3, path4, path5, path6, path7);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM