// Solution to Project Euler problem #22
//
// Make sure to download the names file!
// ie: wget http://projecteuler.net/project/names.txt
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct node {
char *name;
struct node *nextnode;
} *Node;
void addthrough(Node newn, Node listn);
unsigned long long scoretotal(Node curnode, int place);
Node liststart;
main() {
int i, j;
FILE *namestxt;
char names[47000], *temp; // Load entire file into memory
namestxt = fopen("names.txt", "r");
if (namestxt == NULL) {
printf("names.txt not found!\n");
exit(EXIT_FAILURE);
}
for (i=0; (j=fgetc(namestxt))!=EOF; i++)
names[i] = j;
names[i] = '\0';
liststart = (Node) malloc(sizeof(struct node));
liststart->name = strtok(names, "\",");
liststart->nextnode = NULL;
while ((temp = strtok(NULL, "\",")) != NULL) {
Node newn = (Node) malloc(sizeof(struct node));
newn->name = temp;
newn->nextnode = NULL;
if (strcmp(liststart->name, newn->name)>0) {
// New node should be start oflist
newn->nextnode = liststart;
liststart = newn;
} else {
addthrough(newn, liststart);
}
}
printf("Solution: %llu\n", scoretotal(liststart, 1));
}
// Add all nodes that shouldn't be at beginning of list
void addthrough(Node newn, Node listn) {
if (listn->nextnode == NULL) {
listn->nextnode = newn;
} else if (strcmp(newn->name, listn->nextnode->name)<0) {
newn->nextnode = listn->nextnode;
listn->nextnode = newn;
} else {
addthrough(newn, listn->nextnode);
}
return;
}
// Runs through list and add scores
unsigned long long scoretotal(Node curnode, int place) {
int i, j = 0;
unsigned long long total;
if (curnode == NULL)
return 0;
// Calculate total for rest of list first
total = scoretotal(curnode->nextnode, place+1);
for (i=0; i<strlen(curnode->name); i++) {
j += curnode->name[i] - 'A' + 1;
}
j *= place;
return total + j;
}
Comments (0)
You don't have permission to comment on this page.