Name: Anonymous 2010-11-11 5:21
I'm currently working my way through the problems at projecteuler.net .
I never went to a college programming course ( but will next year), so I'm sorry for the probably trivial question.
I solved Problem 22 ( http://projecteuler.net/index.php?section=problems&id=22 ) with this code:
Any suggestions what could have done better?
I never went to a college programming course ( but will next year), so I'm sorry for the probably trivial question.
I solved Problem 22 ( http://projecteuler.net/index.php?section=problems&id=22 ) with this code:
#include <stdio.h>
#include <stdlib.h>
struct list_el {
char name[20];
struct list_el * next;
};
typedef struct list_el item;
int name_value(char *name) {
int sum = 0;
while(*name != '\0')
sum += *name++ - 'A' +1;
return sum;
}
//returns 1 if name1 is lower that name2
//0 else
int lower(char *name1, char* name2) {
int i;
for(i=0;name1[i] != '\0';i++) {
//if name1 is longer than name2 name1 should be lower on the list
if(name2[i] == '\0')
return 1;
//if the value of name1 is greater than name2 (Z > A) name1 should be lower on the list
if(name1[i] > name2[i])
return 1;
//if the value of name1 is less than name2 (A < Z) name1 should be higher on the list
if(name1[i] < name2[i])
return 0;
}
//if name1 is shorter than name2 name1 should be higher on the list
return 0;
}
int main(int argc, char *argv[])
{
FILE *fin = fopen("names.txt","r");
item *curr, *cursor;
char name[20]; //buffer for the name
int i, sum = 0;
//Initialize list
item first,last;
first.name[0] = '\0';
first.next = &last;
last.name[0] = '\0';
last.next = NULL;
//Fill List
while(fscanf(fin,"\"%[^\",]\",",name) != EOF){
//create new item
curr = (item *) malloc(sizeof(item));
strcpy(curr->name,name);
//Now where should we put our new item?
for(cursor=&first;cursor->next!=&last;cursor=cursor->next) {
//Write if next name should be below this one
if(lower(cursor->next->name,name)){
curr->next = cursor->next;
cursor->next = curr;
break;
}
}
//Last item reached, append to list.
if(cursor->next == &last) {
curr->next = &last;
cursor->next = curr;
}
}
for(i=1,cursor=first.next;cursor!=&last;cursor=cursor->next,i++)
sum += name_value(cursor->name) * i;
for(cursor=&first;cursor!=&last;cursor=cursor->next)
free(cursor);
free(&last);
printf("%ld\n",sum);
return 0;
}Any suggestions what could have done better?