[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: help with C algorythm (find unique value in an array) could you please make changes



On Mon, Jan 22, 2007 at 10:30:29AM +0000, Jon Dowland wrote:
> I think it's our duty to provide the most cunning/evil
> solution possible then :)

Probably not all that evil or cunning by most people's
standards, but here's my solution. I tried to do a
continuation-passing-style tail recursive thing, but my C
skills aren't up to it.


-- 
Jon Dowland
#include <stdio.h>
#include <stdlib.h>
/*
 * find the number of unique values in an array
 */

typedef enum { false, true, } boolean;

struct node {
    struct node * next;
    int val;
};
boolean in_list(const int val, const struct node *list) {
    if(NULL == list) return false;
    return val == list->val || in_list(val, list->next);
}
struct node * add_to_list(const int val, struct node *list) {
    if(NULL == list) {
        list = malloc(sizeof(struct node));
        if(!list) {
            fprintf(stderr,"error allocating list node\n");
            exit(1);
        }
        list->val = val;
        list->next = NULL;
    } else list->next = add_to_list(val, list->next);
    return list;
}
int list_size(const struct node *list) {
    if(NULL == list) return 0;
    return 1 + list_size(list->next);
}

int main(int argc, char **argv) {
    int i;
    struct node *p, *list = NULL;

    if(argc < 2) {
        fprintf(stderr, "usage: %s number [ number ... ]\n", argv[0]);
        exit(1);
    }
    /* populate the unique list */
    for(i = 1; i < argc; ++i) {
        int val = atoi(argv[i]);
        if(!in_list(val, list)) {
            list = add_to_list(val, list);
        }
    }

    /* loop and print out the list */
    for(p = list; NULL != p; p = p->next) {
        printf("%d ", p->val);
    }
    printf("\n");

    /* now for the new array */
    printf("number of unique numbers: %d\n", list_size(list));

    return 0;
}

Reply to: