21
\$\begingroup\$

My dad is a retired teacher, and he used to give combined spelling and math quizzes, where the student would spell a word, and then 'score' the word by adding up the letters, where a=1, b=2, etc. (e.g. cat = 3+1+20=24). This made grading the quizzes easier, as he would just have to check for incorrect 'scores' rather than incorrectly spelled words, and had the added benefit of testing 2 skills at once.

He hired a friend of mine to write a program that would score words for him, so he could generate lengthy answer keys without error. This problem is inspired by that program.

Requirements:

  1. Accept any word with uppercase and lowercase letters
  2. Return an error for any special characters, i.e. spaces, hyphens, @^%# etc.
  3. a=1, b=2,... and A=1, B=2,...
  4. Print the score of the word
  5. (Optional) check that the word is in a dictionary after scoring, and print a warning if it is not.
  6. No importing an external letter->number dictionary. You must generate it yourself.

Any language is acceptable. This is similar to the 'digital root battle,' but much simpler.

\$\endgroup\$
12
  • 2
    \$\begingroup\$ Is this supposed to be a code golf? \$\endgroup\$ Apr 23, 2011 at 18:08
  • 2
    \$\begingroup\$ @Zach Using the code-golf tag. \$\endgroup\$
    – Lowjacker
    Apr 23, 2011 at 18:24
  • 3
    \$\begingroup\$ Yeah, only checking scores? I'd spell cat as aaaaaaaaaaaaaaaaaaaaaaaa. Dad: Score is 24? That's right! \$\endgroup\$
    – ericw31415
    May 8, 2016 at 14:13
  • 4
    \$\begingroup\$ @ericw31415 Every hashing function has collisions ;-). So far none of his students have tried that attack vector \$\endgroup\$
    – Zach
    May 9, 2016 at 15:39
  • 3
    \$\begingroup\$ @Zach Also, it would be too complex if his dad made his students do SHA-512 of their words. \$\endgroup\$
    – ericw31415
    May 10, 2016 at 20:42

39 Answers 39

9
\$\begingroup\$

Ruby, 43 characters

$_=gets.upcase;p~/[^A-Z]/?_: $_.sum-64*~/$/

The error message this generates isn't exactly helpful, though. Both solutions posted here assume the input has no trailing linebreak, so to test them, use echo -n.

Ruby, 76 characters with dictionary check

l=STDIN.gets;$_=l.upcase;p~/[^A-Z]/?_: $_.sum-64*~/$/;[*$<].index(l)||$><<?W

The warning message consists of the single character "W". The path to the dictionary has to be supplied via ARGV. Example usage:

$ echo -n asd | ruby addletters.rb /usr/share/dict/words
24
W
$ echo -n cat | ruby addletters.rb /usr/share/dict/words
24
\$\endgroup\$
3
  • 2
    \$\begingroup\$ You could chop of 9 characters in the dictionary check version by making the error message an exclamation mark. \$\endgroup\$ Apr 24, 2011 at 16:55
  • \$\begingroup\$ You get a consolation prize for the shortest entry with a dictionary check. Way to go! \$\endgroup\$
    – Zach
    Apr 26, 2011 at 12:49
  • \$\begingroup\$ Why was the dictionary check proposed if it doesn't give you any real edge (on the contrary, it just bloated the code)? \$\endgroup\$ Apr 27, 2011 at 17:23
8
\$\begingroup\$

Golfscript - 23 chars

0\{.31&.(.26%=@64///+}/

Ensure there are no trailing newlines in input (e.g. use echo -n).

\$\endgroup\$
3
  • \$\begingroup\$ We have a new winner! \$\endgroup\$
    – Zach
    Apr 26, 2011 at 15:48
  • \$\begingroup\$ Generally, external filtering is supposed to be included in character count somehow (Ctrl-f external filtering.), though I assume it's only 2 extra characters to do without. \$\endgroup\$ Apr 26, 2011 at 16:29
  • 2
    \$\begingroup\$ @Jesse: echo -n really doesn't count as external filtering -- in fact the answer you linked suggests it as a valid form for input. \$\endgroup\$
    – Nabb
    Apr 27, 2011 at 5:25
8
\$\begingroup\$

Python (65 64)

print sum(['',ord(i)-64]['@'<i<'[']for i in raw_input().upper())

This raises an error if the word contains non-letter characters, but not a helpful or informative one. (Edit: tip of the hat to st0le for the indexing trick.)

\$\endgroup\$
5
  • 1
    \$\begingroup\$ print sum(['',ord(i)-64]['@'<i<'[']for i in raw_input().upper()) shaved a couple of chars. \$\endgroup\$
    – st0le
    Apr 24, 2011 at 5:03
  • \$\begingroup\$ Just one char actually. :-\ \$\endgroup\$
    – st0le
    Apr 24, 2011 at 5:09
  • \$\begingroup\$ Save 4 characters by using input; forces user to put quotes around input strings, but "user-friendly" and "not dangerous" aren't in the spec! \$\endgroup\$
    – jscs
    Apr 24, 2011 at 7:15
  • \$\begingroup\$ Well, just change it to Python 3! raw_inputinput \$\endgroup\$ May 3, 2011 at 12:26
  • \$\begingroup\$ print sum([i,ord(i)-64]['@'<i<'[']for i in raw_input().upper()) another byte shaved \$\endgroup\$ May 8, 2016 at 20:01
5
\$\begingroup\$

Python 2.6 (72 Chars) Without dictionary check

print sum(map(" abcdefghijklmnopqrstuvwxyz".index, raw_input().lower()))

Python 2.6 (178 Chars*) With dictionary check

w=raw_input().lower()
print sum(map(" abcdefghijklmnopqrstuvwxyz".index, w))
if w not in open('/usr/share/dict/american-english').read().split():
 print('Word not in dictionary')

*Can be lowered to 156 with a less helpful error message. :-)

Thanks to all commenters for helping improve this.

\$\endgroup\$
8
  • \$\begingroup\$ You might want to consider using the sum builtin with a generator expression, rather than a for loop. It would let you trim off a few chars (~17). \$\endgroup\$
    – user1011
    Apr 24, 2011 at 0:53
  • \$\begingroup\$ @jloy: Thanks for pointing that out. \$\endgroup\$
    – John
    Apr 24, 2011 at 2:13
  • \$\begingroup\$ the parentheses on print can be eliminated \$\endgroup\$
    – st0le
    Apr 24, 2011 at 5:11
  • \$\begingroup\$ its seems you're using a just once, so use the literal itself..."0abc....z".index(i) will work equivalently. \$\endgroup\$
    – st0le
    Apr 24, 2011 at 5:13
  • \$\begingroup\$ The 0 in your scoring array is clever, but it also means that cat0 is accepted without error, which isn't right, I think. Which is too bad, since it would allow you to pass map(a.index,w) to sum instead (substituting the literal for a as st0le suggests). \$\endgroup\$
    – user1011
    Apr 24, 2011 at 6:06
4
\$\begingroup\$

Python (80)

w=raw_input().lower()
s=0
for l in w:s+=range(97,123).index(ord(l))+1
print s

Python v2 (65 but char ` will get accepted)

print sum(map(range(96,123).index,map(ord,raw_input().lower())))

v3 (60 chars, @ will be accepted but not counted, thanks jloy)

print sum(map(range(64,91).index,map(ord,input().upper())))
\$\endgroup\$
2
  • \$\begingroup\$ HINT: THERE IS A WAY TO REMOVE ONE MORE CHAR FROM YOUR SOLUTIONS. :) \$\endgroup\$
    – user1011
    Apr 25, 2011 at 6:49
  • 3
    \$\begingroup\$ @jloy What a helpful 'hint'. ;) \$\endgroup\$ May 1, 2011 at 21:14
4
\$\begingroup\$

Scala: 59 chars, 7 of them payload, no dict:

(0/:"Payload".map(c=>if(c.isLetter)(c-'A')%32 else-999))(_+_)
67

No dictionary so far. Negative result means: Negative!

(0/:"Pay!wall?".map(c=>if(c.isLetter)(c-'A')%32 else-999))(_+_)   
-1915

Handles German Umlaute gracefully, by the way:

(0/:"Müllrößchen".map(c=>if(c.isLetter)(c-'A')%32 else-999))(_+_)
155
\$\endgroup\$
4
  • \$\begingroup\$ Wow, less chars than the Perl version (and still more readable). \$\endgroup\$ Apr 24, 2011 at 9:41
  • \$\begingroup\$ I tried SHiNKiROUs and chinesis-Perl-solution, but they didn't work for me. Saved them as alpha.pl and started them by perl alpha.pl. Do they just handle Ascii? Well - at Perl is such an old beast ... :) \$\endgroup\$ Apr 24, 2011 at 11:32
  • \$\begingroup\$ Perl and Unicode is a big mess. You probably have to run them as perl -M5.010 alpha.pl or something like that. \$\endgroup\$ Apr 24, 2011 at 19:38
  • \$\begingroup\$ I heard that I need single quotes instead of double quotes on Linux, and this worked, thanks. \$\endgroup\$ Apr 24, 2011 at 21:48
4
\$\begingroup\$

Java + Google Guava libraries, 347 characters, with dictionary check

Unreadable 1 long string version :-)

import java.io.*;import com.google.common.base.*;import com.google.common.io.*;class C{public static void main(String[]a)throws Exception{int s=0;for(int c:a[0].toUpperCase().toCharArray()){assert(c>64&&c<91);s+=c-64;}String d=Files.toString(new File(a[1]),Charsets.UTF_8);if(StringUtils.containsIgnoreCase(d,a[0]))System.out.println("w");System.out.println(s);}}

Human-readable version (sort of :-))

import java.io.*;

import com.google.common.base.*;
import com.google.common.io.*;

class C {
    public static void main(String[] a) throws Exception {
        int s=0;

        for(int c : a[0].toUpperCase().toCharArray()) {
            System.out.println(c);
            assert(c > 64 && c < 91);
            s += c - 64;
        }

        String d = Files.toString(new File(a[1]), Charsets.UTF_8);

        if (d.contains(a[0])) System.out.println("w");

        System.out.println(s);
    }
}

The dictionary path is now passed in via a[1], for assertions to work you have to use the -eaflag (+3 more chars). As for the dictionary, the dict /usr/share/dict/words (should be available on most *nix systems) has been used.

\$\endgroup\$
5
  • \$\begingroup\$ So far you're the only one with a dictionary check, so +1 \$\endgroup\$
    – Zach
    Apr 24, 2011 at 0:18
  • \$\begingroup\$ one line? this isn't particularily readable this way, though i guess it saves chars \$\endgroup\$ Apr 24, 2011 at 0:22
  • \$\begingroup\$ I will add a more readable solution (and also a shorter one using Google Guava to reduce boilerplate code). \$\endgroup\$ Apr 24, 2011 at 9:27
  • \$\begingroup\$ You just allow ascii, but use Charset.UTF-8? \$\endgroup\$ Apr 24, 2011 at 11:12
  • 1
    \$\begingroup\$ Because the String UTF-8 is shorter than the other charsets :-). \$\endgroup\$ Apr 24, 2011 at 11:18
4
\$\begingroup\$

Python 3, 95 chars with dictionary

d=input().lower()
print(d in open("d").read()and sum(['',ord(c)-96]['`'<c<'{']for c in d)or'f')

The dictionary has to be in a file called d.

Python 3, 61 without dictionary, but stolen idea

print(sum(['',ord(c)-96]['`'<c<'{']for c in input().lower()))
\$\endgroup\$
3
\$\begingroup\$

VB.NET, 84 82 73 71

Console.Write(Console.ReadLine.Sum(Function(c)Asc(Char.ToUpper(c))-64))


Edit: With validation is:

Dim r=Console.ReadLine
Console.Write(If(r.All(AddressOf Char.IsLetter),r.Sum(Function(c)Asc(Char.ToUpper(c))-64),"Invalid input."))

129 characters. In which case:

C#, 118

var r=Console.ReadLine();Console.Write(r.All(char.IsLetter)?r.Sum(c=>char.ToUpper(c)-64).ToString():"Invalid input.");
\$\endgroup\$
4
  • 1
    \$\begingroup\$ This doesn't validate the input. \$\endgroup\$
    – Lowjacker
    Apr 23, 2011 at 21:09
  • \$\begingroup\$ Oops! Hold on a second... \$\endgroup\$
    – Ry-
    Apr 23, 2011 at 21:22
  • 3
    \$\begingroup\$ I think you should provide complete programs. Your C# solution doesn’t compile; you need to place it in a Main method inside a class declaration, and count all the characters. \$\endgroup\$
    – Timwi
    Apr 24, 2011 at 13:07
  • 1
    \$\begingroup\$ No, because that code doesn't do anything, and it's not fair to disadvantage users of object-oriented languages. This is valid C#/VB.NET anyways. \$\endgroup\$
    – Ry-
    Apr 24, 2011 at 18:50
3
\$\begingroup\$

Improving slightly on John's answer: Python (90)

s=0
for i in raw_input().lower():
 s+=("abcdefghijklmnopqrstuvwxyz".index(i)+1)
print(s)
\$\endgroup\$
1
  • 2
    \$\begingroup\$ adding the dummy char in the string beginning is shorter...parentheses can be removed \$\endgroup\$
    – st0le
    Apr 24, 2011 at 5:14
3
\$\begingroup\$

Erlang, 104

a()->
a(string:to_lower(io:get_line([])),0).
a([_|[]],S)->
S;
a([C|R],S) when C<${, C>=$`->
a(R,S+C-$`).
\$\endgroup\$
3
\$\begingroup\$

Perl (52) (48)

golfed even more thanks to Timwi

perl -lpe "($w=uc)=~/[^A-Z]/&&die;$w=~s/./$_-=64-ord$&/ge"

\$\endgroup\$
6
  • \$\begingroup\$ You're missing the -e flag there. \$\endgroup\$
    – Lowjacker
    Apr 23, 2011 at 21:11
  • 1
    \$\begingroup\$ You should at least include the p and l interpreter flags in your character count. See this discussion on meta. \$\endgroup\$
    – Ventero
    Apr 23, 2011 at 23:12
  • \$\begingroup\$ syntax error at -e line 1, near "(=" Execution of -e aborted due to compilation errors. What am I doing wrong? \$\endgroup\$ Apr 24, 2011 at 11:22
  • \$\begingroup\$ if you're running on unix, change double quotes to single ones \$\endgroup\$ Apr 24, 2011 at 11:22
  • \$\begingroup\$ @Timwi: 'Accept any word with uppercase and lowercase letters' went to the wrong thread, sorry. I deleted it now. @chinese: Yes, thanks, with single quotes it's ok. As long as I restrict myself to ascii input. :) \$\endgroup\$ Apr 24, 2011 at 16:32
3
\$\begingroup\$

Golfscript - 39 chars

n%~{.96>{96}{64}if-..26>\0<|{0/}*}%{+}*

The error it throws is not exactly the best, but hey, it aborts execution.

\$\endgroup\$
2
  • \$\begingroup\$ I don't know anything about golfscript, so I'm going to assume this meets the requirements and declare you the winner! \$\endgroup\$
    – Zach
    Apr 26, 2011 at 12:45
  • \$\begingroup\$ Whoops, you've been beat! I guess 2 days isn't long enough to wait on a code golf question? \$\endgroup\$
    – Zach
    Apr 26, 2011 at 15:48
3
\$\begingroup\$

PYTHON 62 68* Characters

print sum(map(chr,range(65,91)).index(c)+1 for c in input().upper())

Requires user to input strings using quotes, and is not safe (input executes code), but, as I said in a comment to another post, "user-friendly" and "not a security risk" ain't in the spec!


* I forgot about print, dammit.

\$\endgroup\$
1
  • \$\begingroup\$ jloy's answer is still shorter, actually, because of the input/raw_input difference. \$\endgroup\$
    – jscs
    Apr 24, 2011 at 21:54
3
\$\begingroup\$

Husk, 17 bytes

?osṁo%32c¹¨eŻ→¨Λ√

Try it online!

Returns 'error' for invalid input, score of word otherwise.

?              Λ√       # if every element is a letter
 os                     # return the string of
   ṁ    c¹              # the sum of all their ASCII values
    o%32                # MOD 32
          ¨eŻ→¨         # otherwise, return the compressed string
                        # "error"

If it's acceptable to return '0' as the 'error' for invalid input, we can have a 11 byte 10 byte 9 byte solution:

§&ṁ%32Πm√
\$\endgroup\$
3
\$\begingroup\$

05AB1E, 15 bytes

lvAyk>})D0åi0ëO

Try it online! Returns 0 on error.

lvAyk>})D0åi0ëO  # full program
 v               # for y in...
                 # implicit input...
l                # lowercased...
    k            # push 0-based index of...
   y             # y...
    k            # in...
  A              # the lowercase alphabet...
    k            # or -1 if not found...
     >           # plus 1
      }          # end loop
           i     # if...
         0       # 0...
          å      # is in...
       )         # stack...
            0    # push 0
             ë   # else...
              O  # push sum...
        D        # of stack
                 # implicit output
\$\endgroup\$
2
\$\begingroup\$

Ruby 1.9, 69

w=gets.chop.upcase
w[/[^A-Z]/]&&fail
p w.bytes.inject(0){|s,b|s+b-64}
\$\endgroup\$
2
  • \$\begingroup\$ Does only handle ascii characters. I thought Ruby is from our century? :) \$\endgroup\$ Apr 24, 2011 at 11:31
  • \$\begingroup\$ @user unknown: The spec doesn't say it has to. Doing it would be rather complicated... \$\endgroup\$
    – Lowjacker
    Apr 24, 2011 at 11:41
2
\$\begingroup\$

Perl (71)

($a)=lc<>;$a=~/[^a-z]/i&&die;$x+=ord$_ for split//,$a;die$x-96*length$a;
\$\endgroup\$
2
\$\begingroup\$

GolfScript, 50(53)

Gives an error on bad characters, but not a very good one (50 characters):

);[{""123,97>+91,65>+?}/].-1?0<{{26%1+}%{+}*}{@}if

Gives "E" on error instead (53 characters):

);[{""123,97>+91,65>+?}/].-1?0<{{26%1+}%{+}*}{;"E"}if

The alphabet-generating snippet 123,97>+ is stolen from Ventero .

\$\endgroup\$
0
2
\$\begingroup\$

J (55)

+/64-~-&32`]@.(<&97)`_:@.(<&65)`_:@.(>&122)"0,I.a.&e."0

This satisfies all the conditions except the dictionary one. As an error condition, it returns "infinity" (the underscore symbol in J) for words that contain anything but letters.

\$\endgroup\$
2
\$\begingroup\$

Haskell (127)

(raises an error on weird characters)
(also: the space between toUpper. and \x is needed otherwise it parses it as(toUpper) .\ (x))

import Char
main=getLine>>=putStrLn.show.sum.(map$(-65+).ord.toUpper. \x->if x`elem`['A'..'Z']++['a'..'z']then x else error"")

Haskell (70)

(does not raise an error, but 45% shorter)

import Char
main=getLine>>=putStrLn.show.sum.(map$(-65+).ord.toUpper)
\$\endgroup\$
2
\$\begingroup\$

C++ (111 107)

void main(){int a=0;s8*b=new s8[99];for(cin>>b;*b;)if(isalpha(*b))a+=tolower(*b++)-96;else return;cout<<a;}

The "set up"/etc:

#include <iostream>
#include <cstdio>
#include <cctype>

#ifdef _MSC_VER
    typedef __int8 s8;
#else
    typedef signed char s8;
#endif

"Undefined" behavior (It's more 'bad practice' than 'undefined', but oh well):

  • void main() That says it all.
  • I'm using new without delete.
\$\endgroup\$
2
\$\begingroup\$

Jelly, 10 9 bytes

ŒuØAiⱮoµS

Try it online!

Seemingly, it turns out a byte shorter to actually error than to return 0.

Œu           Uppercase the input,
    i        find the index (or 0 if not found)
     Ɱ       of each letter from the input
  ØA         in "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
      o      replace any 0 with the corresponding character of the input,
       µS    then take the sum.

Jelly errors if it attempts to add integers and strings together, and although two strings can be added together by +, this still errors in the case of a fully symbolic input because S is defined specifically as a reduce starting from zero.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Nice. It'll be tough to better (or even match) 9-bytes... \$\endgroup\$ Nov 19, 2020 at 22:21
1
\$\begingroup\$

JavaScript 1.8, 80 chars

Surprisingly readable!

alert(Array.reduce(prompt().toLowerCase(),function(a,b)a+b.charCodeAt(0)-96,0))
\$\endgroup\$
2
  • \$\begingroup\$ For use in Chrome I had to convert it a little: alert(prompt().toLowerCase().split("").reduce(function(a,b){return a+b.charCodeAt(0)-96},0)). I still like JavaScript solutions most :) \$\endgroup\$
    – pimvdb
    Jun 2, 2011 at 9:32
  • \$\begingroup\$ It doesn't return an error when you do invalid character??? \$\endgroup\$
    – ericw31415
    May 8, 2016 at 14:07
1
\$\begingroup\$

APL (34)

+/{⍵∊⍳26:⍵}¨{64-⍨A-32×96<A←⎕UCS⍵}⍞

Gives either the score, or a VALUE ERROR if there are non-alphabetic characters in the input.

Explanation:

  • : read a line of input
  • {...}: function applied to every character of input
  • A←⎕UCS⍵: store the ASCII value of the current character in A
  • A-32×96<A: make character uppercase: from A is subtracted 32 if 96<A (so, if it's uppercase), otherwise 0
  • 64-⍨: subtract 64 from this, giving A=1, B=2 ...
  • ¨: apply this function to every character:
  • ⍵∊⍳26: if the character is between 1 and 26...
  • :⍵: then return ⍵ (and since there's no else clause there will be a VALUE ERROR if it's not between 1 and 26)
  • +/: sum all the values together (and this value is automatically outputted because it's the final result).
\$\endgroup\$
1
\$\begingroup\$

JavaScript, 60 bytes

s=>[...s.toUpperCase()].reduce((a,b)=>a+b.charCodeAt()-64,0)

If the program must return an error on invalid inputs, then 80 bytes:

s=>/[^a-z]/i.test(s)?_:[...s.toUpperCase()].reduce((a,b)=>a+b.charCodeAt()-64,0)

If an input is invalid, then the console will say that _ is not defined (there must not already be a variable defined called _).

\$\endgroup\$
1
\$\begingroup\$

Python 3, 58 55

print(sum(ord(x)%32for x in input()if x.isalpha()or z))

without dictionary or stolen idea but still unhelpful error ;)

thx @Eᴀsᴛᴇʀʟʏ

Test here.

\$\endgroup\$
5
  • \$\begingroup\$ I think you can save a byte by switching to python 2 and doing print<SPACE>sum(ord(......., removing the 2 parentheses around the expression. \$\endgroup\$
    – Riker
    May 8, 2016 at 20:48
  • \$\begingroup\$ @EᴀsᴛᴇʀʟʏIʀᴋ that is right but than the input has to be in parenthesis and I don't want to promote python 2 ;) \$\endgroup\$ May 8, 2016 at 20:52
  • \$\begingroup\$ PYTHON 2 IS LIFE!! and also, I don't think that would require the input to be parenthesized? \$\endgroup\$
    – Riker
    May 8, 2016 at 21:52
  • \$\begingroup\$ @EᴀsᴛᴇʀʟʏIʀᴋ sry i meant quoted. input() in python3 is raw_input() in python2 \$\endgroup\$ May 8, 2016 at 23:34
  • \$\begingroup\$ oh, I forgot. Hm. \$\endgroup\$
    – Riker
    May 9, 2016 at 1:11
1
\$\begingroup\$

C, 98 bytes

 int a(char *s){int b=0;while(*s){if(!isalpha(*s))throw 1;b+=(toupper(*(s++))-64);}printf("%d",b);}
\$\endgroup\$
1
\$\begingroup\$

F# (no validation) 79 57 chars

let a w=w|>Seq.fold(fun a b->a+(int b)-65)0|>printfn"%i"
\$\endgroup\$
1
\$\begingroup\$

C# with validation: 108 chars (with 12 for error message):

var s=Console.ReadLine();Console.Write(s.All(Char.IsLetter)?s.Sum(x=>x&'_'-'@').ToString():"Invalid input");

C# without validation: 60 53 chars:

Console.Write(Console.ReadLine().Sum(x=>x&'_'-'@'));
\$\endgroup\$
1
  • 1
    \$\begingroup\$ In the second one without validation, you can reduce the characters even more by removing the s variable declaration and using Console.ReadLine() inline. \$\endgroup\$
    – hermiod
    Jun 3, 2012 at 9:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.