Project Euler

Project Euler Problem 22

steloflute 2012. 6. 3. 22:59

Problem 22

19 July 2002

Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 53 = 49714.

What is the total of all the name scores in the file?


Answer:
871198282

 

 

C#

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;
using System.IO;

namespace Euler {
    class Program {
        static void Main(string[] args) {
            Console.WriteLine(File.ReadAllText("names.txt").Replace("\"", "").Split(',').OrderBy(x=>x).Select((str, index) => str.Sum(c => c - 'A' + 1) * (index + 1)).Sum());
            Console.ReadKey();
        }
    }
}


Racket


(define sorted

  (sort (string-split (string-replace (file->string "names.txt") "\"" "") ",") string<?))

(define (string-sum s)

  (apply + 

         (map (lambda (x) (- (char->integer x)

                             (char->integer #\A)

                             -1))

              (string->list s))))

(displayln (for/sum ([rank (in-range 1 (add1 (length sorted)))])

             (* rank (string-sum (list-ref sorted (sub1 rank))))))



Javascript

To run, save and run

오빤 Continuation-Passing Style

 

<script>
function readURL(url,continuation) { // CPS(continuation-passing style) !!
 var r=new XMLHttpRequest();
 var result;
 r.open("GET", url, true);
 r.onreadystatechange=function() {
  if (r.readyState==4) {
   continuation(r.responseText);
  }
 }
 r.send();
}

function stringSum(s) {
  var sum=0;
  var base="A".charCodeAt(0);
  for(var i=0;i<s.length;i++) sum+=s.charCodeAt(i)-base+1;
  return sum;
}

function k(text) {
  var sorted=text.replace(/"/g,"").split(","); 
  sorted.sort();
 
  var sum=0;
  for(var i=0;i<sorted.length;i++) {
    sum+=(i+1)*stringSum(sorted[i]);
  }
  alert(sum); 
}

var url="http://projecteuler.net/project/names.txt";
readURL(url,k);
</script>

 

'Project Euler' 카테고리의 다른 글

Project Euler Solutions in Clojure: clojure-euler  (0) 2012.06.05
Project Euler Problem 23  (0) 2012.06.03
Project Euler Problem 21  (0) 2012.06.03
Project Euler Problem 20  (0) 2012.06.03
Project Euler Problem 19  (0) 2012.06.03