Skip to content

Instantly share code, notes, and snippets.

@vaibhavsagar
Last active September 14, 2016 15:45
Show Gist options
  • Save vaibhavsagar/f521f2b7d30aa3eca7b419e0e22e1ad2 to your computer and use it in GitHub Desktop.
Save vaibhavsagar/f521f2b7d30aa3eca7b419e0e22e1ad2 to your computer and use it in GitHub Desktop.
Week 5 code dojo solution with @phasedchirp
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 76,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"4"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": [
"4"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": [
"4"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"\n",
"import Data.List\n",
"input = \"abba\"\n",
"choose2 n = n*(n-1) `div` 2\n",
"reduced input = let\n",
" substrings = filter (/=\"\") $ concatMap tails $ inits input\n",
" sortedSubstrings = sort $ map sort substrings\n",
" counts = map length $ group sortedSubstrings\n",
" in foldr (\\x y -> if x > 1 then y + choose2 x else y) 0 counts\n",
"reduced \"abba\"\n",
"\n",
"\n",
"reduced' = foldReduced . (length <$>) <$> group <$> sort . (sort <$>) . filter (/= \"\") . (>>= tails) . inits\n",
"foldReduced = foldr (\\x y -> if x > 1 then y + choose2 x else y) 0\n",
"\n",
"\n",
"reduced'' = let\n",
" notNull = filter (/=\"\")\n",
" sorted = (sort <$>)\n",
" mapGroup = (group <$>)\n",
" in sum. (( (foldReduced . (length <$>)). group <$>)) . group <$>\n",
" (sort . sorted . notNull . (>>= tails) . inits)\n",
"\n",
"reduced' \"abba\"\n",
"reduced'' \"abba\""
]
},
{
"cell_type": "code",
"execution_count": 71,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[3,2,2,6,3]"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"map reduced'' [\n",
" \"ifailuhkqq\",\n",
" \"hucpoltgty\",\n",
" \"ovarjsnrbf\",\n",
" \"pvmupwjjjf\",\n",
" \"iwwhrlkpek\"]"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"readN :: Int -> IO [String]\n",
"readN 0 = return []\n",
"readN n = do\n",
" s <- getLine\n",
" rest <- readN $ n-1\n",
" return $ s:rest\n",
" \n",
"main :: IO ()\n",
"main = do\n",
" num <- read <$> getLine :: IO Int\n",
" inputs <- readN num\n",
" let counts = map reduced inputs\n",
" mapM_ print counts"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Haskell",
"language": "haskell",
"name": "haskell"
},
"language_info": {
"codemirror_mode": "ihaskell",
"file_extension": ".hs",
"name": "haskell",
"version": "7.10.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment