Search Unity

<> operators in <T>(T[] array)

Discussion in 'Scripting' started by AndrAla, May 10, 2017.

  1. AndrAla

    AndrAla

    Joined:
    Mar 11, 2017
    Posts:
    18
    When I try to run this code:
    Code (csharp):
    1.     public static bool IsSolvable<T>(T[] array){
    2.         int inversions = 0;
    3.  
    4.         for (int i = 1; i < array.Length; i++) {
    5.             for (int j = i + 1; j < array.Length; j++) {
    6.                 if (array [j] > array [i]) {
    7.                     inversions++;
    8.                 }
    9.             }
    10.         }
    11.         return inversions % 2 == 0;
    12.     }
    I get an error "Operator > cannot be applied to operands of type 'T' and 'T'".
    The array I'm giving this function is an int array. How can I make this work?
     
  2. CrymX

    CrymX

    Joined:
    Feb 16, 2015
    Posts:
    179
    the type T is totaly Generic, you are doing array [j] > array , you are supossing here the array<T> implement the operator ">" but if you use a list of Object the compiler can't do object > object.

    change the param of your function as public static bool IsSolvable(int[] array)
     
  3. JoshuaMcKenzie

    JoshuaMcKenzie

    Joined:
    Jun 20, 2015
    Posts:
    916
    Constrain the method to IComparable<T> (an interface that int and most value types implement) and use the compareTo method

    Code (CSharp):
    1. public static bool IsSolvable<T>(T[] array)
    2.     where T: IComparable<T>
    3. {
    4.         int inversions = 0;
    5.         for (int i = 1; i < array.Length; i++) {
    6.             for (int j = i + 1; j < array.Length; j++) {
    7.                 if (array [j].CompareTo(array [i]) > 0) {
    8.                     inversions++;
    9.                 }
    10.             }
    11.         }
    12.         return inversions % 2 == 0;
    13.     }
     
    StarManta, KelsoMRK and AndrAla like this.
  4. AndrAla

    AndrAla

    Joined:
    Mar 11, 2017
    Posts:
    18
    That worked, thanks :)
    (had to add "System" to the used libraries 1-st tho)

    EDIT: Is there a way for me to assign the value to an int variable?
    Code (csharp):
    1. int a = array[0];
    this doesn't work. Neither does this:
    Code (csharp):
    1. int a = (int) array[0];
     
    Last edited: May 10, 2017
  5. JoshuaMcKenzie

    JoshuaMcKenzie

    Joined:
    Jun 20, 2015
    Posts:
    916
    its a generic method so you likely want to keep it referenced as a generic type (i.e. T a = array[0]; ). perhaps if you show your code we can give a more specific answer.