Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Improvements?

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:

#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?

Name: Anonymous 2010-11-11 5:38


#include <stdio.h>
int main() {
  int n=1,v,c,a=0;
  for(;!feof(stdin);n++) {
    for(v=0;;) {
      c = fgetc(stdin);
      if(c=='\n'||c==EOF)
        break;
      v += c - 64;
    }
    a += v * n;
  }
  printf("%d\n",a);
  return 0;
}



ran with unix command line:

cat names.txt | tr -d \" | tr , \\n | sort | ./22

Name: Anonymous 2010-11-11 5:44

Well the point was to sort it myself.
Adding chars up and multiplying them with an index is not that much fun.

Name: Anonymous 2010-11-11 6:23

>>3
ihbt man strcmp man qsort hax my anus my other car is a cdr etc

Name: Anonymous 2010-11-11 6:33

>>4
/polecat kebabs/

Name: Anonymous 2010-11-11 6:42

>>4
oh yeah youre right... -.-'

Name: Anonymous 2010-11-11 7:03

cat names.txt | tr -d \" | tr , \\n | sort | ./22

Not unix enough.  Free Sage to anyone who will solve this problem using unix tools only.

Name: Fuck off, !Ep8pui8Vw2 2010-11-11 7:11

>>5
Fuck off, ``faggot''.

Name: Anonymous 2010-11-11 9:22

>>7

cat names.txt | tr -d \" | tr , \\n | sort \
    | xargs -i echo "echo {} | sed \"s/./&\n/g\" | xargs -iinput printf '%d - 64 + ' \"'input\"; echo 0" \
    | bash | xargs -i bash -c 'echo $(({}))' \
    | awk '{ if (NR % 10 == 0) print NR; SUM += NR * $0}; END {printf "%d", SUM}'

Name: Anonymous 2010-11-11 9:30

>>9
cat | tr

Great. Almost as good as cat | grep

Name: Anonymous 2010-11-11 9:36

>>10 *blush* I just copied >>2-kun without really thinking. The rest of the stuff was crazy enough to leave no time for considering if tr can accept file names, and if so, then what's the syntax.

Name: Anonymous 2010-11-11 10:20

#include "names.txt" into an array initializer, qsort it, and loop.

Name: Anonymous 2010-11-11 11:16


tr(1) - Linux man page
Name
tr - translate or delete characters
Synopsis
tr [OPTION]... SET1 [SET2]


MANPAGES
MOTHERFUCKERS
DO
YOU
READ
THEM

Name: >>9,11 2010-11-11 11:35

>>13 Lol I have bitch tits, apparently.

Name: Anonymous 2010-11-11 11:44

>>10
I fucking hate you, idiotic troll. I bet you're the same person who also keeps spamming ``char isn't always 8 bits'' every time a snippet of C is posted. I ALWAYS use cat | grep because it allows me to visualize the informational flow better. Fuck off of /prog/ already, or at least stop repeating the same stupid trolls all the time.

Name: Anonymous 2010-11-11 11:52

btw, optimized version:

cat names.txt | tr -d \" | tr , \\n | sort \
    | xargs -i echo "echo \$((\`echo {} | sed \"s/./&\n/g\" | xargs -iinput printf '%d - 64 + ' \"'input\"; echo 0\`))" \
    | bash | awk '{ if (NR % 10 == 0) print NR; sum += NR * $0}; END {printf "%d", sum}'

Name: Anonymous 2010-11-11 12:09

>>15
i agree.  < is so against the flow.

Name: Anonymous 2010-11-11 12:30

>>17 Redirection is unnecessary, you can just say grep -i "have" bitch.tits.

Name: Anonymous 2010-11-11 13:17

Your "Lower" function is already implemented in the c standard library as strcmp.  You should use that because it is less likely to have bugs.

In addition, I approve of your list implementation and custom insertion sort.  Not bad.  The fact that you're willing to reimplement the wheel is actually a good thing in this case because it means you actually understand how a data structure works.  Good on you.  That said, the standard way to sort something using standard c is using Quicksort, which is implemented as qsort in the standard C library.

Lastly, every call to malloc and free is expensive...using arrays if possible is faster.


Here's my solution

#include<string.h>
#include<stdio.h>
#include<stdlib.h>

int commacount(FILE* fp)
{
    int cc=0;
    int c;
    while((c=fgetc(fp))!=EOF)
        cc+=(c==',');

    return cc;
}
int name_value(char *name) {
    int sum = 0;
    while(*name != '\0')
        sum += *name++ - 'A' +1;
    return sum;
}
int main(int argc,char** argv)
{
    int cc;
    int i;
    int total=0;

    char *name;//list of names read in 64 characters long each
    FILE* f=fopen("names.txt","r");
    cc=commacount(f)+1;
    freopen("names.txt","r",f);
    name=(char *)malloc(64*cc);
   
    for(i=0;i<cc;i++)
    {
        fscanf(f,"\"%[^\",]\",",name+i*64);
    }
    qsort(name,cc,64,strcmp);
    for(i=0;i<cc;i++)
    {
        total+=(i+1)*name_value(name+i*64);
    }
    printf("%d\n",total);
    free(name);
    return 0;
}

Name: Anonymous 2010-11-11 17:49

useless use of cat

Name: Anonymous 2010-11-11 18:13

strcpy(curr->name,name);
fscanf(f,"\"%[^\",]\",",name+i*64);

Cool heap overflow bros.


import Data.Char (ord)
import Data.List (sort)
import Text.ParserCombinators.Parsec

main = do
    result <- parseFromFile names "22.txt"
    case result of
        Left  error -> print "derp"
        Right names -> print $ nameScoreSum names

nameScoreSum names = sum . zipWith nameScore [1..] . sort $ names
  where
    nameScore position name = position * sum (map charValue name)
    charValue c = ord c - (ord 'A' - 1)

names = name `sepBy` char ','
name  = between quote quote (many1 letter)
quote = char '"'

Name: Anonymous 2010-11-11 20:58

ENTERPRISE FIOC SOLUTIONS

#!/usr/bin/python

names = sorted( [name.strip('\n\"') for name in \
            open("names.txt").readline().split(',')] )
print sum( map( lambda (x,y): x*y, \
    zip( range(1,len(names)+1) , \
    [sum( map(ord,name) ) for name in names] ) ) )

Name: Anonymous 2010-11-11 21:04

>>22
That's not ENTERPRISE, you functional faggot.

Name: Anonymous 2010-11-11 21:05

>>23
You apparently missed the thread on F#

Name: Anonymous 2010-11-11 21:36

>>22
That should be map(lambda x: ord(x)-ord('A')-1 ,name)

Name: Anonymous 2010-11-11 21:37

>>25
Dammit, map(lambda x: ord(x)-ord('A')+1 ,name)

Name: Anonymous 2010-11-11 21:54

>>22
You know that you don't need to escape your newlines when you have unclosed parentheses?

Name: Anonymous 2010-11-11 23:23

>>27
Meh.  Force of habit that comes from that FORCED INDENTION.

Name: Anonymous 2010-11-12 4:27

>>19
Yeh I rewrote it and used qsort and strcmp after >>3-san made me hang my head in shame.

Name: Anonymous 2010-11-12 4:45

>>29
You were >>3-san

Name: Anonymous 2010-11-12 5:05

>>30
oh yeah i meant >>4-san

Name: Anonymous 2010-11-12 7:54


d = "*ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def x(name):return(sum(map(lambda a:d.index(a),[c for c in name])))
with open('names.txt') as f:l=sorted(f.readline().replace('"','').split(','))
print(sum(map(lambda n:(l.index(n)+1)*x(n),[n for n in l])))

Name: Anonymous 2010-11-12 18:55

$ time cat names.txt | tr -d \" | tr , \\n | sort \
| xargs -i echo "echo \$((\`echo {} | sed \"s/./&\n/g\" | xargs -iinput printf '%d - 64 + ' \"'input\"; echo 0\`))" \
 | bash | awk '{ sum += NR * $0}; END {printf "%d\n", sum}' &
$ 871198282
cat names.txt  0.00s user 0.00s system 0% cpu 0.062 total
tr -d \"  0.00s user 0.00s system 0% cpu 0.058 total
tr , \\n  0.00s user 0.00s system 0% cpu 0.056 total
sort  0.02s user 0.00s system 36% cpu 0.054 total
xargs -i echo   1.95s user 4.67s system 6% cpu 1:39.39 total
bash  20.46s user 47.72s system 61% cpu 1:50.36 total
awk '{ sum += NR * $0}; END {printf "%d", sum}'  0.09s user 0.02s system 0% cpu 1:50.36 total

[1]  + done       time cat names.txt | tr -d \" | tr , \\n | sort | xargs -i echo  | bash | awk


ANONIX QUALITY

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List