Wednesday, September 18, 2013

Problem 43 - Coffeescript

Another language that falls in the "fairly boring" category. I can tell that there are nicer ways to do this problem, but most nice ways are a lot harder than the easy way, but the easy way is only easy in a language with nice features like arrays. So, as it is the middle of the week and I should probably spend most of my time on classwork, I decided to go the easy way on this problem - maybe I will go the hard way some time later. I used Coffeescript for this problem, a language that compiles to javascript but which is in some ways nicer for some things according to its proponents - it wasn't too hard a language to use, even if it does have some strange features.

Anyway, here is the coffeescript code (oh what a creative name that was...)

concatDigits = (digits) ->
    sum = 0
    for i in digits
        do(i) ->
            sum = sum*10 + i
    return sum


hasProperty = (digits) ->
    if (concatDigits(digits[1..3]) % 2 is 0 and 
       concatDigits(digits[2..4]) % 3 is 0 and
       concatDigits(digits[3..5]) % 5 is 0 and
       concatDigits(digits[4..6]) % 7 is 0 and
       concatDigits(digits[5..7]) % 11 is 0 and
       concatDigits(digits[6..8]) % 13 is 0 and
       concatDigits(digits[7..])  % 17 is 0)
        concatDigits(digits)
    else
        0
    
fac = (x) => if x < 2 then 1 else x * fac(x - 1)
NthLP = (N, p, rem) ->
    if rem.length == 1 then return p.concat(rem)
    k = fac(rem.length - 1)
    index = Math.floor(N / k)
    p.push(rem[index])
    rem = if index is 0
            rem[1..]
          else if index is rem.length - 1
            rem[..-2]
          else 
            rem[..index-1].concat(rem[index+1..])
    return NthLP(N % k, p, rem)

sum = 0
i = 0
while i < fac(10)
    digits = NthLP(i, [], j for j in [0..9])
    sum += hasProperty(digits)
    i += 1
console.log(sum)

No comments:

Post a Comment