Filter Elements:haskell基本操作
从序列中输出那些出现至少k次的元素
函数式解法就是构造一系列的函数,然后进行函数间的组合来解决问题。此题还是多组读入,在读入时就是做一个递归,每次递归将当读取序列和K值,然后将序列和K值传入一个过滤函数,在传之前先构造两个序列,一个是按原顺序去重的序列,一个是将元素和出现次数构成元组的序列。传入过滤函数时,对于每个出现在去重序列的元素,判断它的出现次数是否不小于k,若是则输出,并递归地读到下一个去重序列元素,直至去重序列为空,一次计算则结束
import Data.List
main=do
line<-getLine
mainLoop (read line::Int)
mainLoop ::Int -> IO()
mainLoop 0 =return()
mainLoop n=do
line<-getLine
let k=last [read x::Int | x<-words line]
line<-getLine
let r=[read x::Int | x<-words line]
let singleElemArray=nub r
let groupedArray=[(head x,length x)|x<-group $ sort r]
output [fst x|x<-groupedArray,(snd x)>=k] singleElemArray
mainLoop (n-1)
output :: [Int]->[Int]->IO()
output [] _ =putStrLn "-1"
output x [] =putStrLn ""
output x (y:ys)=if (y `elem` x)
then do
putStr ((show y)++" ")
output x ys
else
output x ys