locked
Shorter way to compare variables RRS feed

  • Question

  • if(a >=b && a >=c && a >= d && a >= e)
     {
        
     }
    Any way to short this condition i have around 20 variables
    Sunday, September 18, 2016 6:48 PM

Answers

  • I suggest to declare the function's signature as :

    bool IsMoreOrEqualToAll(int a, params int[] list){

    so the asker can use it as:

    if (IsMoreOrEqualToAll(a, b, c, d, e, ...))

    Of course he didn't tell us the .NET version he's on so the keyword may not be supported. :P

    • Marked as answer by cheong00Editor Monday, September 26, 2016 1:20 AM
    Monday, September 19, 2016 2:05 AM
    Answerer
  • if(a >=b && a >=c && a >= d && a >= e)
     {
        
     }
    Any way to short this condition i have around 20 variables

    Right now you check A against all variables B through U and only continue if it is bigger then all of them. I am goint to asume all of them are teh same type (propably any numerical one). If those goes across types, stuff is a lot harder.

    First put B through U into a arrray. Once you have done that, it becaomes a simple itteration/array operation.

    Simplest way would be to find out the biggest number in the array, then look if a is >= to it.  Ideally you might be able to do that once for the list, then just keep the result around. It would shorten the CPU load by a factor of 20.
    I think the linq Expansion Method Top() or whatever it is called could help you finding the "higest number from that array"
    Alterantively ordering them and taking the first or last element (depending how you ordered it) would work too. That is what all Collections have a Sort() function for.

    If you can not simply get the highest Element or reorder the array, another approach would be code like this:

    bool IsMoreOrEqualToAll(int a, int[] list){
      foreach(int current in list){
        if(!(a >= current))
          return false;
      }
      return true;
    }
    You just feed it a value and a list, and it will only return true if a is more or equal to every element in the list.

    Remember to mark helpfull answers as helpfull and close threads by marking answers.

    Sunday, September 18, 2016 7:31 PM

All replies

  • What are the data types for a through e? You might use some transitive or other similar logic since you don't indicate distinct logic for each case, you just ensure all conditions are valid the execute something.
    Sunday, September 18, 2016 7:16 PM
  • Can you change your code so that the variables are elements of an array or list?

    Then you can do something like:

    if (a >= mylist.Max()) ...


    • Edited by Brian Muth Sunday, September 18, 2016 7:19 PM
    • Proposed as answer by Kevin Linq Monday, September 19, 2016 5:08 AM
    Sunday, September 18, 2016 7:19 PM
  • Hello,

     You can place all your values in an array. Then iterate over them. But, the real

    question is Why and Where do these variables come from?

     Thanks :)

    Sunday, September 18, 2016 7:24 PM
  • if(a >=b && a >=c && a >= d && a >= e)
     {
        
     }
    Any way to short this condition i have around 20 variables

    Right now you check A against all variables B through U and only continue if it is bigger then all of them. I am goint to asume all of them are teh same type (propably any numerical one). If those goes across types, stuff is a lot harder.

    First put B through U into a arrray. Once you have done that, it becaomes a simple itteration/array operation.

    Simplest way would be to find out the biggest number in the array, then look if a is >= to it.  Ideally you might be able to do that once for the list, then just keep the result around. It would shorten the CPU load by a factor of 20.
    I think the linq Expansion Method Top() or whatever it is called could help you finding the "higest number from that array"
    Alterantively ordering them and taking the first or last element (depending how you ordered it) would work too. That is what all Collections have a Sort() function for.

    If you can not simply get the highest Element or reorder the array, another approach would be code like this:

    bool IsMoreOrEqualToAll(int a, int[] list){
      foreach(int current in list){
        if(!(a >= current))
          return false;
      }
      return true;
    }
    You just feed it a value and a list, and it will only return true if a is more or equal to every element in the list.

    Remember to mark helpfull answers as helpfull and close threads by marking answers.

    Sunday, September 18, 2016 7:31 PM
  • By follow the Max method that instructed by the others, you can create an array inline in the condition expression:

    if (a >= new int[] { b, c, d, e }.Max())
    {
       // something
    }

    Sunday, September 18, 2016 11:27 PM
  • I suggest to declare the function's signature as :

    bool IsMoreOrEqualToAll(int a, params int[] list){

    so the asker can use it as:

    if (IsMoreOrEqualToAll(a, b, c, d, e, ...))

    Of course he didn't tell us the .NET version he's on so the keyword may not be supported. :P

    • Marked as answer by cheong00Editor Monday, September 26, 2016 1:20 AM
    Monday, September 19, 2016 2:05 AM
    Answerer
  • I'm curious, have you even checked what will the "params" keyword do here before you reply?
    Monday, September 19, 2016 4:01 AM
    Answerer
  • I vote yours as an alternatife method with variable number of parameters called params array parameter, without need to explicitly create instance of array argument :)
    Monday, September 19, 2016 5:34 AM
  • I think that major credit should go to Christopher84 here because he provided the main method body. And his method is better than the others which use .Max() because there is no need to find out what is the largest number among the other numbers. The method can return as soon as "a" is smaller than any numbers in the sequence.

    Both methods can do, but in most case this will return faster.

    Monday, September 19, 2016 6:50 AM
    Answerer
  • Yes, the linq extention method is actually do the lazy iteration that compares each number to get the maximum value before we use to compare with "a" value, so the Max method is simple code but more slower, otherwise traditional iteration more faster because directly compare with "a" value, or we can use lambda expression to custom the query as traditional approach do.
    Monday, September 19, 2016 7:02 AM
  • Yes I have read, an array parameter will ask the user to explicitly create instance of "new int[] { b, c, d, e }", againts the "params" that provide a shortcut to creating a temporary array, regardless the number of values as argument if actually he has to create the array instance with the same constructor method in this case.
    Monday, September 19, 2016 7:36 AM
  • 1) The main goal the asker want is to type things shorter, only when the required code is similarly short that the performance matters.

    IMO you can never find a way more efficient than the code original asker typed, so arguing we introduce new intermediate variables as "inefficient" is pointless.

    2) Note that the original asker is not even saying that there will be an array. It's normal for any of the 20 variables to change between each compare. How can you not compare every of the variables against the next time is beyond me.

    3) As for comment that "Finding the maximum value of an array is *fast* and should never be replaced by a bloated method that compares value by value ( it may be necessary to check all or almost all values).", why won't you take a look on how exactly it is implemented in current version of .NET framework before you reply?

    P.S.: I'm going to ignore you if you continue to keep accusing my opinion is wrong without a valid reason... or even basic fact checking.

    Monday, September 19, 2016 7:53 AM
    Answerer

  • The user will use an array already created by some function that RETURNS such array; this is real life programming.

    Moreover try using the params keyword to enter 50 values or more... :P

    params keyword is very useful for forums, where the examples have 2,3 or 5 values to enter... :-)

    Ok no problem, it's depend on the what actually he has the values :)

    And about what actually do with the linq method, it's same process with the lazy iteration as 'bloated' or as 'low level' code... the decision up to him :)


    • Edited by Fariztech Monday, September 19, 2016 7:57 AM
    Monday, September 19, 2016 7:56 AM
  • Don't continue to spread misinformation here.

    The "params" keywork is just a syntactic sugar here for you to input infinate amount of parameter at the point onward, with the input prepacked in an array in the order the parameter is passed. There's no difference in performance in the following code fragments:

            public void Test()
            {
                int a = 1, b = 3, c = 18;
                if (IsMoreOrEqualToAll(a, new int[]{b,c}))
                {
                    Console.WriteLine("A is the largest");
                }
                else
                {
                    Console.WriteLine("A is NOT the largest");
                }
            }
    
            bool IsMoreOrEqualToAll(int a, int[] list)
            {
                foreach (int current in list)
                {
                    if (!(a >= current))
                        return false;
                }
                return true;
            }

            public void Test()
            {
                int a = 1, b = 3, c = 18;
                if (IsMoreOrEqualToAll(a, b, c ))
                {
                    Console.WriteLine("A is the largest");
                }
                else
                {
                    Console.WriteLine("A is NOT the largest");
                }
            }
    
            bool IsMoreOrEqualToAll(int a, params int[] list)
            {
                foreach (int current in list)
                {
                    if (!(a >= current))
                        return false;
                }
                return true;
            }
    As for "But would you use it for as many as 50 values?", try tell "But would you use COALESCE() for as many as 50 values?" to any maintainers of SQL queries.


    Monday, September 19, 2016 8:07 AM
    Answerer
  • Don't continue to spread misinformation here.

    The "params" keywork is just a syntactic sugar here for you to input infinate amount of parameter at the point onward, with the input prepacked in an array in the order the parameter is passed. There's no difference in performance in the following code fragments:

            public void Test()
            {
                int a = 1, b = 3, c = 18;
                if (IsMoreOrEqualToAll(a, new int[]{b,c}))
                {
                    Console.WriteLine("A is the largest");
                }
                else
                {
                    Console.WriteLine("A is NOT the largest");
                }
            }
    
            bool IsMoreOrEqualToAll(int a, int[] list)
            {
                foreach (int current in list)
                {
                    if (!(a >= current))
                        return false;
                }
                return true;
            }

            public void Test()
            {
                int a = 1, b = 3, c = 18;
                if (IsMoreOrEqualToAll(a, b, c ))
                {
                    Console.WriteLine("A is the largest");
                }
                else
                {
                    Console.WriteLine("A is NOT the largest");
                }
            }
    
            bool IsMoreOrEqualToAll(int a, params int[] list)
            {
                foreach (int current in list)
                {
                    if (!(a >= current))
                        return false;
                }
                return true;
            }

    Don't pretend you did not understand me!

    ENTER 50 values in that code, and see what I mean!

    Now, change the 'a' value and tell me if those comparisons will have to be performed again or not?  :P

    We do not know if the list is static. If it is not, all Performance Optimisations are dangerous:

    Which is faster? | Fabulous Adventures In Coding

    I mentioend the option that he could do find te max once then re-use it if possible.

    And you know what is really funny about params? You do not need to write any extra code to support both params AND covnentional arrays:

    bool IsMoreOrEqualToAll(int a, int[] list){
      //insert whatever comparision code works
    }
    
    bool IsMoreOrEqualToAll(int a, params int list){
      //just call that other one
      return IsMoreOrEqualtToAll(a, list);
    }
    I could solve the problem within 5 seconds and I asume everyone here would be able to do the same. Stop trying to make an argument out of not trying the obvious please.

    Remember to mark helpfull answers as helpfull and close threads by marking answers.

    Monday, September 19, 2016 8:28 AM
  • Now please just answer me a simple question: if b is changed, how can the comparison not be rerun? Say, try change b from 3 to 2000 in the code below.

    As for entering 50 values, as your wish:

            public void Test()
            {
                int a = 1001, b = 3, c = 18, d = 24, e = 12,
                    f = 50, g = 30, h = 2, i = 21, j = 36,
                    k = 103, l = 400, m = 201, n = 75, o = 302,
                    p = 88, q = 28, r = 32, s = 6, t = 35,
                    u = 11, v = 51, w = 84, x = 71, y = 16,
                    z = 501,
                    aa = 1, ab = 3, ac = 18, ad = 24, ae = 12,
                    af = 50, ag = 30, ah = 2, ai = 21, aj = 36,
                    ak = 103, al = 400, am = 201, an = 75, ao = 302,
                    ap = 88, aq = 28, ar = 32, @as = 6, at = 35,
                    au = 11, av = 51, aw = 84, ax = 71;
    
                if (IsMoreOrEqualToAll(a, b, c, d, e, f, g, h, i, j,
                    k, l, m, n, o, p, q, w, s, t,
                    u, v, w, x, y, z, aa, ab, ac, ad,
                    ae, af, ag, ah, ai, aj, ak, al, am, an,
                    ao, ap, aq, aw, @as, at, u, av, aw, ax))
                {
                    Console.WriteLine("A is the largest");
                }
                else
                {
                    Console.WriteLine("A is NOT the largest");
                }
            }
    
            bool IsMoreOrEqualToAll(int a, params int[] list)
            {
                foreach (int current in list)
                {
                    if (!(a >= current))
                        return false;
                }
                return true;
            }

    Intentionally used the non-intutive Excel column naming scheme to show you the effect.


    • Edited by cheong00Editor Monday, September 19, 2016 9:08 AM changed value of a to make it fit the subject of dicussion
    Monday, September 19, 2016 9:01 AM
    Answerer