Showing posts with label Amanda. Show all posts
Showing posts with label Amanda. Show all posts

Sunday, May 23, 2010

Project Euler | Problem 6 (&7!)

Problem 6 is one of those where functional programming just makes things WAY too easy. Look at this:
squares x = [y^2| y<-[1..x]]
answer = (sum ([1..100]))^2 - sum(squares 100)

If you know how list comprehension (the [result | var<-generator;condition] part) works, and you know that [x..y] is all the natural numbers between x and y, including x and y, you can understand the above.
List comprehension works like this:
The generator generates one value. Each occurrence of var is replaced by the value, the conditions, of any, are evaluated, and if all of them apply, result is evaluated and "returned". Since functional languages like these are lazy, evaluation of a list comprehension only occurs when a value from the list is actually needed. Thus, one can define all prime numbers as follows:
allPrimes = [y |y<-[1..];isPrime( y )]
And use it as a list containing all possible primes (assuming the isPrime function exists). Just be sure not to call reverse or something on an infinite list like this. If you try to find the xth prime, all you have to do is allPrimes!x and the list will be evaluated up to the xth result.

[edit]
Holy crap, I almost answered problem 7 without even reading the question. Given allPrimes from above and isPrime from problem 3, we can do:
allPrimes ! 10001

And we're given the prime we want.
[/edit]


By the way, this album is fucking badass:
Ultramagnetic MC's - Critical Beatdown
The Cosmic Hearse, a blog I've followed for nearly a year now, posted this and I've been hooked ever since. Its sound is fairly repetitive, but Kool Keith is just really fucking solid and there are some great samples and beats here. One of the strongest rap albums out there, possibly.

Project Euler | Problem 4

This problem asks you to find the biggest 6-digit palindrome that is the product of two 3-digit numbers. I found this one quite boring, so I'll just put the code (in the functional language Amanda) I used to solve it here and not think about it too much.
condition x = (~.empty) [y | y <- [100..999] ; divides y x ; (x/y)<1000 ]
isPalindrome len val = (take len (itoa val))=((reverse.drop len) (itoa val))
pali6 = reverse [x| x <- [100000..999999]; isPalindrome 3 x]
answer = hd [x | x <- pali6 ; condition x]
divides y x = (x%y = 0)

Those familiar with haskell should probably be able to understand this. It takes about half a minute to evaluate, which is probably because I first calculate all the palindromes and then check them. Also, it should be possible to do the whole thing in one line, but it gets kinda hard to read that way.