繁体   English   中英

计算列表中整数的出现次数

[英]Counting number of occurences of ints in a list

我正在尝试执行以下操作:
我正在编写的函数采用int [(x,y),(i,j)...]的元组列表,范围为0-6
我想返回一个[Int] ,其中每个元素都是在列表中看到的相应数量的计数。
例如[(0,1), (1,2), (2,3)]将返回[1, 2, 2, 1, 0, 0, 0]

换句话说,一个0,两个1's,两个2's 1三个并且没有4s,5s或6s

countNumbers :: [(Int, Int)] -> [Int]  
countNumbers [] = [0, 0, 0, 0, 0, 0, 0]

但由于我是Haskell的新手,因此不确定如何进行此操作。
编辑-我已经找到了解决方案-请让我知道是否有更简洁的编码方式!

type ProbabilityMatrix = (Int,Int,Int,Int,Int,Int,Int)
-- converts list of tuples into list of ints as suggested
tupleToList :: [(Int, Int)] -> [Int]  
tupleToList ((a,b):xs) = a : b : tupleToList xs  
tupleToList _          = []    

tupleToList2 :: [Int] -> ProbabilityMatrix -> ProbabilityMatrix  
tupleToList2 [] list = list  
tupleToList2 (x : xs) (zero, one, two, three, four, five, six)  
  | x == 0 =  tupleToList2 xs (zero + 1, one, two, three, four, five, six)  
  | x == 1 = tupleToList2 xs (zero, one + 1, two, three, four, five, six)  
  | x == 2 = tupleToList2 xs (zero, one, two + 1, three, four, five, six)  
  | x == 3 = tupleToList2 xs (zero, one, two, three + 1, four, five, six)  
  | x == 4 = tupleToList2 xs (zero, one, two, three, four + 1, five, six)  
  | x == 5 = tupleToList2 xs (zero, one, two, three, four, five + 1, six)  
  | x == 6 = tupleToList2 xs (zero, one, two, three, four, five, six + 1)  
  | otherwise = tupleToList2 xs (zero + 1, one, two, three, four, five, six)   

如何为每个元组创建Ints的结果列表,然后将它们与Sum函数合并在一起。 您至少需要两个带有签名的功能:

tupleToList :: (Int, Int) -> [Int]

sumLists :: [Int] -> [Int] -> [Int]

第一个将检测元组中的两个项目,并为其生成相应的列表,例如tupleToList (4, 2) -> [0,0,1,0,1,0,0]

第二个函数将通过在同一索引处对2个计数器求和来合并两个整数列表,例如sumLists [0,1,1,0,1] [1,1,0,0,0] -> [1,2,1,0,1] 您可以递归执行此操作,直到得到1个将解决问题的列表。

tupleToList元组列表中的每个元素执行tupleToList (可能使用map ),然后通过迭代执行2个列表的sumLists来合并结果列表(也许使用foldl

这种方法很幼稚,可能会在输入较大数据时运行缓慢。

您可以尝试以下解决方案:

-- flattens a list of tuples into a list
flatten :: (Num a) => [(a, a)] -> [a]
flatten xs = concat [[a,b] | (a, b) <- xs]

-- updates list element at a position
update_list :: (Num a) => Int -> [a] -> [a]
update_list n xs = take n xs ++ [(xs !! n) + 1] ++ drop (n + 1) xs

-- performs count of numbers
count_numbers :: [(Int, Int)] -> [Int]
count_numbers xs = go (flatten xs) acc
    where go [] acc = acc
          go (x:xs) acc = go xs (update_list x acc)
          acc = replicate 7 0

它首先展平列表的位置:

*Main> flatten [(0,1), (1,2), (2,3)]
[0,1,1,2,2,3]

然后在特定位置更新列表:

*Main> update_list 1 (replicate 7 0)
[0,1,0,0,0,0,0]

并执行对列表元素的计数,类似于您的函数tupleToList2 ,其中存储并更新了数量的累加器:

*Main> count_numbers [(0,1), (1,2), (2,3)]
[1,2,2,1,0,0,0]
*Main> count_numbers [(0,1), (1,2), (2,4)]
[1,2,2,0,1,0,0]
*Main> count_numbers [(0,0), (1,0), (3,6)]
[3,1,0,1,0,0,1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM