Comparing value of multiple ints and returning the largest.

I’m going to have a series many integers, and after a while, I want to get all their values, and return the largest int in the series, then perform an action based on the actual variable returned (not its value).

Ex. Suppose we took a bunch of ints that represented foods, and after comparing the amount of each food present,apple has the most and is returned as ‘apple’ (or maybe its index if using an array), not the amount of apples.

I was thinking of using an array and an enum, but I’m not sure of the easiest and least redundant approach to doing this.

Today is your lucky day, I was in the mood to provide a script :wink:

using UnityEngine;
using System.Collections;

public class FruitClass : MonoBehaviour {
	
	public enum Fruits {
		Apple,
		Orange,
		Banana,
		numEntries // we use this as marker for the number of entries
	}
	
	public int[] myFruits;
	
	void Awake(){
        // provide necessary space
		myFruits=new int[(int)Fruits.numEntries];

        // fill array
		myFruits[(int)Fruits.Apple]=3;
		myFruits[(int)Fruits.Orange]=1;
		myFruits[(int)Fruits.Banana]=4;

        // find index of maximum value
		int maxIndex=-1;
		int maxValue=0;
		for(int i=0;i<(int)Fruits.numEntries;i++){
			if(myFruits*>maxValue){*

_ maxValue=myFruits*;_
_
maxIndex=i;_
_
}_
_
}_
_
// output result*_
* if(maxIndex>=0)*
* Debug.Log("The fruit I have most of are "+(Fruits)maxIndex+“s, of which there are “+maxValue+”.”);*
* }*
}
The int<->Fruits casts cannot be prevented with this approach in C#, it forces a compiler error when missing.
EDIT: Look! I even documented it! :smiley:

Or you can use System.Collections.Generic.Dictionary, where your keys are from the Fruit enum, the values are integers.

For getting the min/max items, you can use LINQ, like described here:

This is a simple and elegant solution.

The easiest way of doing it using a standard array(square brackets).

// c#

int[] nums = { 1, 2, 3, 4, 5, 6, 7 };

nums.Max(); // Will result in 7
nums.Min(); // Will result in 1

// US/JS

var nums: int[] = { 1, 2, 3, 4, 5, 6, 7 };

nums.Max(); // Will result in 7
nums.Min(); // Will result in 1