代码之家  ›  专栏  ›  技术社区  ›  Jonno_FTW

在haskell中将数字列表连接成一个整数

  •  2
  • Jonno_FTW  · 技术社区  · 17 年前

    我正在做另一个项目- Problem 38 .

    f (a,b) = a*b
    conProInt x n  = map f (zip (replicate n x) ([1..n]))
    
    prob38 = maximum [ (conProInt (x) (n)) | x <- [100..500], n <- [1..9], (sort $ nub $ (decToList $ (conProInt x n) )) == (sort $ (decToList $ (conProInt x n) )), (sort $ nub $ (decToList $ (conProInt x n))) == [1..9] ]
    

    如:

    conProInt 192 3
    

    返回: [192,384,576]

    我需要归还的是: 192384576

    我四处搜索,找不到一个函数,也找不到一个我可以构造的函数来满足我的需求。我该怎么办?

    编辑:

    我已经更新了脚本以合并更快的连接,但它没有返回正确的结果:

    f (a,b) = a*b
    conProInt x n  =( combine (map f (zip (replicate n x) ([1..n]))))
    prob38 = maximum [ (conProInt (x) (n)) | x <- [1..50000], n <- [2..40], (sort $ nub $ (decToList $ (conProInt x n) )) == (sort $ (decToList $ (conProInt x n) )), (sort $ nub $ (decToList $ (conProInt x n))) == [1..9] ]
    

    我很确定泛数字测试

    (sort $ nub $ (decToList $ (conProInt x n) )) == (sort $ (decToList $ (conProInt x n) )), (sort $ nub $ (decToList $ (conProInt x n))) == [1..9]
    

    3 回复  |  直到 11 年前
        1
  •  7
  •   thsutton    17 年前

    通过 String

    read $ concat $ map (show) [192,384,576]
    

    尽管您可能需要添加类型签名:

    Prelude> (read $ concat $ map (show) [192,384,576]) :: Int
    192384576
    
        2
  •  5
  •   Martijn    17 年前

    您可以使用此函数连接数字列表:

    concatNumbers :: [Int] -> String
    concatNumbers = concat . map show
    

    如果希望函数以数字形式返回串联,可以使用 read .

        3
  •  2
  •   Michael Steele    17 年前

    下面是一个如何在不转换字符串的情况下连接数字的示例。

    -- foldl1' is a strict fold.  "foldl1" would also work...
    import Data.List (foldl1')    
    
    -- Combine two numbers such that their digits are concatenated.
    -- op 1 23 = 123, op 0 12 = 12, op 12345 67 = 1234567
    op :: Int -> Int -> Int
    op a b = a * power 10 (numDigits b) + b
    
    -- How many digits does a positive number have?
    numDigits :: Int -> Int
    numDigits x = length . takeWhile (>= 1) . iterate (`div` 10) $ x
    
    -- Take a positive number and raise it to a positive power.
    -- power 5 2 = 25, power 10 3 = 1000
    power :: Int -> Int -> Int
    power x y = foldl1' (*) . take y $ repeat x
    
    -- Take a list of numbers, and concatenate all their digits.
    combine :: [Int] -> Int
    combine xs = foldl1' op xs
    

    运行示例:

    Prelude> :m +Data.List
    Prelude Data.List> let power x y = foldl1' (*) . take y $ repeat x
    Prelude Data.List> let numDigits = length . takeWhile (>=1) . iterate (`div` 10)
    Prelude Data.List> let op a b = a * power 10 (numDigits b) + b
    Prelude Data.List> let combine xs = foldl1' op xs
    Prelude Data.List> combine [192, 384, 576]
    192384576
    Prelude Data.List>
    
    推荐文章