Skip to content

Instantly share code, notes, and snippets.

@Tosainu
Created September 4, 2017 09:47
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Tosainu/b9e72a87ee5a1e4b1cb89ce256019470 to your computer and use it in GitHub Desktop.
#!/usr/bin/env stack
-- stack --stack-yaml ./stack.yaml runghc --package pwn
-- Tokyo Westerns CTF 3rd 2017: Palindromes Pairs - Coding Phase -
{-# LANGUAGE OverloadedStrings #-}
import Control.Monad
import qualified Data.ByteString.Char8 as BS
import Data.Monoid ((<>))
-- https://github.com/Tosainu/pwn.hs
import Pwn
isPalindrome :: BS.ByteString -> Bool
isPalindrome str = str == BS.reverse str
comb2 :: [BS.ByteString] -> [BS.ByteString]
comb2 xs = join $ map (\x -> map (x<>) xs) xs
countPalindrome :: [BS.ByteString] -> Int
countPalindrome = length . (filter isPalindrome) . comb2
main :: IO ()
main = do
r <- remote "ppc1.chal.ctf.westerns.tokyo" 8765
recvuntil r "----- START -----\n" >>= BS.putStr
forM_ [1..50] $ \n -> do
recvuntil r (BS.pack $ "Input " <> show n <> "/50\n") >>= BS.putStr
recvline r >>= BS.putStr
l <- BS.init <$> recvline r
BS.putStrLn l
let n = countPalindrome $ BS.words l
ns = BS.pack $ show n
BS.putStrLn ns >> sendline r ns
interactive r
-- $ ./solve.hs
-- [x] Opening connection to ppc1.chal.ctf.westerns.tokyo on port 8765
-- [+] Opening connection to ppc1.chal.ctf.westerns.tokyo on port 8765: Done
-- ####################################
-- # Palindromes Pairs #
-- ####################################
--
-- A word is called "palindrome" if it reads the same backward as forward.
-- For instance, "cbabc", "cbc", "a", "caac" and "deaed" are palindromes.
--
-- Given the list of words s_1, s_2, s_3, ..., s_n,
-- your task is the count pair (i, j) that the concatenation of s_i and s_j is palindrome.
--
--
-- Input Format:
-- The first line contains n.
-- The second line contains s_1, s_2, s_3, ..., s_n separated by space.
-- n
-- s_1 s_2 s_3 ... s_n
--
-- Output Format:
-- Your program must output the number of pairs in one line.
--
-- Conditions:
-- * n <= 50
-- * |TestCase| = 50
-- * Each word only contains lower alphabets.
--
-- Example Input 1:
-- 3
-- a ba cab
--
-- Example Output 1:
-- 3
--
-- Explanation of Example1:
-- 'aa' (1,1), 'aba' (1,2), 'bacab' (2,3)
--
-- Example Input 2:
-- 5
-- a aa aaa aaaa aaaaa
--
-- Example Output 2:
-- 25
--
--
-- ----- START -----
-- Input 1/50
-- 6
-- kw ju hb h p px
-- 4
-- Correct!
--
-- Input 2/50
-- 19
-- g aj vt w kes me kg zkf ftp fhh nrf ztw wi f pl c se ioe bnn
-- 8
-- Correct!
--
-- Input 50/50
-- 4
-- sbg o fq ow
-- 2
-- [*] Entering interactive mode
-- Correct!
--
-- Congratulations! The Flag is 'TWCTF{find_favorite_smell}'.
-- [*] Connection closed
-- [*] Leaving interactive mode
--
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment