DEV Community

Damien Sedgwick
Damien Sedgwick

Posted on

ChatGPT - Complex Coding Challenges: 6 KYU

Hello and welcome back to this series where we put ChatGPT through its paces!

We have a slight change in direction this time around because we have swapped out SQL with Haskell.

So before we start, here is the challenge Array.diff

The instructions and description is as follows:

Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.

It should remove all values from list a, which are present in list b keeping their order.

arrayDiff([1,2],[1]) == [2]

If a value is present in b, all of its occurrences must be removed from the other:

arrayDiff([1,2,2,2,3],[2]) == [1,3]
Enter fullscreen mode Exit fullscreen mode

Lets get started.

Solving it in JavaScript

function arrayDiff(a, b) {
  return a.filter((value) => !b.includes(value));
}
Enter fullscreen mode Exit fullscreen mode

A very concise and simple solution, that passes all tests.

Solving it in C

#include <stdlib.h>

int* array_diff(const int* arr1, size_t n1, const int* arr2, size_t n2, size_t* z) {
    int* result = malloc(n1 * sizeof(int));
    size_t count = 0;
    for (size_t i = 0; i < n1; i++) {
        int found = 0;
        for (size_t j = 0; j < n2; j++) {
            if (arr1[i] == arr2[j]) {
                found = 1;
                break;
            }
        }
        if (!found) {
            result[count++] = arr1[i];
        }
    }
    *z = count;
    return realloc(result, count * sizeof(int));
}

Enter fullscreen mode Exit fullscreen mode

The solution for C is very verbose in comparison, however, it too passes all of the tests.

Solving it in Haskell

module Difference where

difference :: Eq a => [a] -> [a] -> [a]
difference a b = filter (`notElem` b) a

Enter fullscreen mode Exit fullscreen mode

Another more concise solution and more passed tests!

It feels like it has been a bit easier this time around even though the level of difficulty has been increased.

I wonder if it is due to my questioning getting better and more refined or if something else is at play here.

Top comments (0)