Skip to content

Instantly share code, notes, and snippets.

@ion1 ion1/CodegolfLost.hs
Created Mar 16, 2014

Embed
What would you like to do?
Generate the coefficients for http://codegolf.stackexchange.com/a/24289/1621
name: codegolf-lost
version: 0.0.1
build-type: Simple
cabal-version: >= 1.10
executable codegolf-lost
main-is: CodegolfLost.hs
build-depends: base >= 4.6 && < 4.8
, ad == 3.4.*
, th-printf == 0.2.*
default-language: Haskell2010
ghc-options: -Wall
executable codegolf-lost-entry
main-is: CodegolfLostEntry.hs
build-depends: base >= 4.6 && < 4.8
default-language: Haskell2010
{-# LANGUAGE QuasiQuotes #-}
-- | Generate the coefficients for
-- <http://codegolf.stackexchange.com/a/24289/1621>
module Main (main) where
import Data.List
import Numeric.AD
import Text.Printf.TH
main :: IO ()
main = mapM_ (\xs -> do pr xs; pr (funValues xs); putStrLn "")
(gradientDescent cost initial :: [[Double]])
where
pr = putStrLn . intercalate " " . map [s|%3.3f|]
positions, values, initial :: Floating a => [a]
positions = [ fromInteger n / 6 * pi | n <- [0..5] ]
values = [ 4, 8, 15, 16, 23, 42 ]
initial = replicate 6 0
-- Returns 'values' if the input is perfect.
funValues :: Floating a => [a] -> [a]
funValues xs = map (fun xs) positions
cost :: Floating a => [a] -> a
cost xs = sum (zipWith sqErr (funValues xs) values)
where
sqErr a b = (b - a)**2
fun :: Floating a => [a] -> a -> a
fun coeffs t = sum (zipWith go coeffs [0..])
where
go coeff mul = coeff * cos (fromInteger mul * t)
main = mapM_ (print . round . go) [0..]
where
go n = 22 - 19.2*cos t + 6*cos (2*t) - 5.3*cos (3*t) + 0.5*cos (5*t)
where t = fromInteger (n `mod` 6) / 6 * pi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.