# Integer comparisons

Say we have a dozen integers, or half a dozen, either way…

We were to be checking whether or not an integer (say, intA) were higher than intB, intC, intD and so forth - however, again checking if intA is actually not higher but intB is…would look something like this:

``````if (intA > intB  intA > intC  intA > intD){
//doSomething
}

if (intB > intA  intB > intC  intB > intD){
//doSomethingOther
}
``````

That’s a lot of code to have to keep checking, and confusing to keep track of.

Is there an easier method to check whether intA is of a higher value than all the other ints - or is lower, to do something?

Unleash the power of a List.

My arch nemesis must be wrestled with again? Oh the joy!

But lists in C# are your friend, they want to be your friend anyways.

For example:

``````List<int> toCompare = new List<int>() { intB, intC, intD, intZ };

bool isHighest = true;

foreach (int compare in toCompare)
{
if (intA < compare)
{
isHighest = false;
break;
}
}
``````

Theres lots of fancy ways to do it in C# but use the way that reads best, to you.

Next wrap up your code in a nice method:

``````public bool IsHighest(int compare, List<int> toCompare)
{
bool isHighest = true;

foreach (int n in toCompare)
{
if (compare < n)
{
isHighest = false;
break;
}
}

return isHighest;
}
``````

And now its really tidy to use in your code:

``````if (IsHighest(5, new List<int>() { 1, 2, 3, 4 }))
{
}
``````

Its like making a nest or home for yourself. Make code how you feel comfortable, you shape it to your convienience, it supports your goal, not the other way round.

Oh young one, it is time to unleash the power of LINQ!

``````using System.Linq;
...
var nums = new[] { 1, 2, 3, 4, 5, 6, 7, 9, 10 };
if (nums.All(n => n < 15)) Console.WriteLine("All numbers are smaller than 15");
if (nums.Any(n => n < 5)) Console.WriteLine("At least one number is smaller than 5");
/*So on and so forth*/
``````

Now, there’s nothing wrong with manually writing out functions - for example CrazySI’s IsHighest function - but this is more versatile and quicker to implement - and can always be refactored later

You call that a nice method?

``````/*Nice Class*/
public static class MathHelper
{
/*Helper Method - See Easier Syntax Examples*/
public static bool IsHighest(this IEnumerable<int> toCompare, int compare)
{
foreach (int n in toCompare)  /*Shorter, Cleaner Code*/
if (compare <= n)  /*Correct Comparison [based on OP]*/
return false;
return true;
}
}

...

/*Many datatypes*/
var numArray = new[] { 1, 2, 3, 4, 5, 6, 7, 9, 10 };
var numList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 9, 10 };

/*Easy Syntax*/
if (numArray.IsHighest(11)) Console.WriteLine("Array");
if (numList.IsHighest(11)) Console.WriteLine("List");

/*Alternate Syntax*/
if (MathHelper.IsHighest(numArray,11)) Console.WriteLine("Array");
if (MathHelper.IsHighest(numList, 11)) Console.WriteLine("List");
``````

I hate to quote myself but…

I personally can’t stand Lin(q?), for anything more than very simple methods, it can quickly become very unwieldy and unreadable. People will appreciate it when they can read your code and understand it. (The amount of times I have cursed the Linq primadonna when trying to debug their code sigh)

And not meaning to piss on Mr C# Extraordinaires bonfire, but my philosophy would be in this case to keep it simple, especially when you’re starting out.

I expect you’re just not structuring it right - I mean sure you can write LINQ like this - but that’s just the dev being silly

And yes, while I did show off a bit of my 1337 skillz I would note that you:

• Used a redudant isHighest variable.
• Failed to use the correct comparison!

So, there’s something to be said for using the inbuilt functions rather than trying to roll your own

@CrazySim - if I can’t get Linq working, then I might just go that route

@npsf3000
How should I declare “n” in JS?

From my understanding of the syntax differences:

``````var nums = new Array (intA, intB, intC);

if (nums.All(n => n < 15) { Console.WriteLine("All numbers are smaller than 15"); }
``````

I’ll go through MSDN for linq commands afterwards.

Uh-oh.

Some things fly over me lol, surely I’m not a plain idiot for not understanding how LINQ/C# is handling the “n” to JS.

I’ve tried to declare it as a var both outside the if, within the if and within the function it’s self: no-go.

``````import System.Collections.Generic;

function Start ()
{
var intz : List.<int> = new List.<int>();

for (var i : int in intz)
{
Debug.Log(i.ToString());
}

intz.Sort();

for (var i : int in intz)
{
Debug.Log(i.ToString());
}

Debug.Log("The biggest int in intz is " + intz[intz.Count-1].ToString());
}
``````

Option A) By using C# [You’ll love me later, honest].

Option B) By using somewhat messy syntax:

``````#pragma strict
import System.Linq;

function Start () {
var nums = [1,2,3,4,5];
print(nums.All(function(x) {x < 6;}));
}
``````

Nope. Lambda’s are a semi-advanced topic… and US has such poor documentation there’s no expecation that you’d magically figure it out.

Yes if your even semi-serious about programming you’ll switch to a standard language, like C#. I don’t quite understand what was going through the designers mind when they devised US, yet another non standard scripting language, which like others will sooner or later fade away. I think for me that was the biggest pull Unity had, in terms of scripting C# was a very attractive option to me.

(BTW I was going to say I’d sooner expect to find a Polar Bear in Cairns than a C# programmer)

@npsf30000
Huh…interesting, thanks! =)

@Crazysi
Perhaps once I’m comfortable enough with unity and know enough US, I’ll switch to C#. It’ll be a little while til then.

Hi,
It seems that you have at least 3 options :

• Use List.Sort() method with unityscript as shown above to solve the problem
• Learn LINQ and learn how to use LINQ with unityscript to solve the problem
• Learn C# and LINQ to solve the problem.

In this particular case sorting doesn’t make much sense though it can in other scenarios… the better alternative in this situation would be Max.

``````var numArray = new[] { 1, 2, 3, 4, 5, 6, 7, 9, 10 };
var numList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 9, 10 };
...
if (11 > numArray.Max()) print("Array");
if (11 > numList.Max()) print("List");
``````

Similar to what you where doing, less LOC, doesn’t need lambda’s[as opposed to my All() example] and doesn’t bother wasting time sorting numbers. Unlike All() it will not early exit - so not good for larger collections were returning false occurs on a notable basis.

Ok, so this is probably going to make some of you want to smack me across the internet. But I was trying to think of a good…functional way to accomplish this. It may be of use to you, or may not But I’d like feedback if this is something people would think is useful, confusing, etc etc.

`````` private static void TestHighAction()
{

// Initialize the dictionary
// This will be done at the start of your game, whatever
Dictionary<int, WinnerData> participants = new Dictionary<int, WinnerData>();

// Initialize with player names and the method to call for each player, if they winn.
// These will be assigned when different players change
participants[0] = new WinnerData("Joe Schmoe", 0, PlayerOneWins);
participants[1] = new WinnerData("Bala KaBalla", 0, PlayerTwoWins);
participants[2] = new WinnerData("Uncle Smiley", 0, PlayerThreeWins);

// When you have the final scores, assign them to the players.
participants[0].Value = 3;
participants[1].Value = 8;
participants[2].Value = 5;

// Find out who won
// Do this when we want to perform an action based on their scores.
int winningValue = 0;
WinnerData winner = null;
foreach (WinnerData highestItem in participants.Values)
{
if (highestItem.Value > winningValue)
{
winningValue = highestItem.Value;
winner = highestItem;
}
}

// Call the winning action
winner.ActionToPerform();

// When a new game starts, don't forget to do this:
participants.Clear();
}

private static void PlayerOneWins()
{
// Play unique animation and stuff when player one wins
}

private static void PlayerTwoWins()
{
// Play unique animation and stuff when player two wins
}

private static void PlayerThreeWins()
{
// Play unique animation and stuff when player three wins
}

public class WinnerData
{
private int _value;

public WinnerData(string description, int value, Action actionToPerform)
{
_description = description;
_value = value;
_actionToPerform = actionToPerform;
}

public int Value
{
get
{
return _value;
}
set
{
_value = value;
}
}

public Action ActionToPerform
{
get
{
return _actionToPerform;
}
}

public string Description
{
get
{
return _description;
}
}
}
``````

The idea is, after you initialize the dictionary somewhere in your program, you just have to change the values and it ‘automatically’ calls the method of whoever is largest. I’d probably prefer to do something like this instead of coding multiple lines of

If A > B and A> C and A> D call method one ()
if (B > A and B > C and B > D) call method two()

But I guess it depends on how many variables there are to compare. If you only have a few, this might be overkill.

Its a good idea if it suits what you are doing…kind of like buying a discounted item whilst shopping.

I think you could improve your idea by:
Eliminating or hiding lines 22-31, etc. and create a new Class that hides all this. At the moment you have to call your mechansim in a obtuse way.
Bind to Action rather than WinnerData. Then you can use this class in a more generic way. At the moment it serves very specific purpose only.

The short of it is you ought to wrap up how things are done behind the scenes in a generic way, so thats its trivial for whoever/whatever is using your code to utilise it AND make it useable for multiple purposes without having to understand HOW it works.

npsf3000 : Thanks for the info, much appreciated.