Problem of the Day
A new programming or logic puzzle every Mon-Fri

The Last One

For the last day in MarCh we'll have a special C based problem. The goal is to create a function that takes in an array and returns the x'th element in an array. The trick is that you should also support negative numbers. So looking for -1 should return the last element in the array. Looking for -10 in a 5 element array can return index out of bounds or an error of your choosing.

Permalink: http://problemotd.com/problem/the-last-one/

Comments:

  • David - 9 years, 8 months ago

    Well, this accomplishes the task. Test main included. Note the unsafe ability to specify an incorrect length.

    #include <stdio.h>
    
    #define ALEN(a) sizeof(a)/sizeof(a[0])
    
    //Returns 0 for any invalid inputs.
    
    int xthInt(int* array, int length, int index) {
        if(!length) return 0;
        if(index >= length) return 0;
        if(index < -length) return 0;
        if(index < 0) {
            return array[length + index];
        }
        else {
            return array[index];
        }
    
        return 0;
    }
    
    int main(void) {
    
        int testArray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    
        printf("%i\n", testArray[1]);
        printf("Expect 2: %i\n", xthInt(testArray, ALEN(testArray), 1));
        printf("Expect 0 for too high: %i\n", xthInt(testArray, ALEN(testArray), 10));
        printf("Expect 10: %i\n", xthInt(testArray, ALEN(testArray), -1));
        printf("Expect 1: %i\n", xthInt(testArray, ALEN(testArray), -10));
        printf("Expect 0 for too low: %i\n", xthInt(testArray, ALEN(testArray), -11));
        printf("Expect 1 for fun: %i\n", xthInt(testArray, ALEN(testArray), -0));
    
        return 0;
    }
    

    Didn't feel like refining this to involve proper error handling in some manner, so zero is reserved for incorrect input.

    reply permalink

Content curated by @MaxBurstein