Home > Software design >  how to check if two lists are equal, up to a permutation in caml
how to check if two lists are equal, up to a permutation in caml

Time:11-10

Hello everyone i'am beginner in caml and i was trying to answer the question below but i don't know from where to start: can someone help me please to solve this?

Write a function :a list -> a list -> bool that check if two lists are equivalent up to permutation. For example [2; 3; 4; 3] is equivalent to [3; 3; 4; 2] but not equivalent to [2; 4; 3]. So how can we check if two lists are equal, up to a permutation in caml?

CodePudding user response:

I'm sorry, I do not know javascript or caml very well. Here is my version. Java is high-level enough, and I'm sure you will figure it.
Here is how I'd do it:

boolean equals(Type A1[], Type A2[])
{
    int len1 = A1.length; // length of the first array
    int len2 = A2.length; // length of the second array

    // if the length are not equal
    if(len1 != len2){
        return false;
    }
    /*sort algorithm of your choice */
    sort(A1); // sort first array  
    sort(A2);

    for(int i = 0; i < len1; i  ){
        if(A1[i] != A2[i]) // if there is at least one non equal element
            return false;
    }

    // everything is ok
    return true;
}

CodePudding user response:

You have multiple option to compare array. One easy way would be make a string.

let arr1 = [2, 3, 4, 3].sort()
let arr2 = [3, 3, 4, 2].sort()
let arr3 = [2, 4, 3].sort()

if(JSON.stringify(arr1) === JSON.stringify(arr2)) {
  console.log('arr1 = arr2');
}

if(JSON.stringify(arr1) !== JSON.stringify(arr3)) {
  console.log('arr1 != arr3');
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related