Definir la función
mayorProducto :: Int -> Integer -> Integer |
tal que (mayorProducto n x) es el mayor producto de n dígitos consecutivos del número x (suponiendo que x tiene al menos n dígitos). Por ejemplo,
mayorProducto 2 325 == 10 mayorProducto 5 11111 == 1 mayorProducto 5 113111 == 3 mayorProducto 5 110111 == 0 mayorProducto 5 10151112 == 10 mayorProducto 5 101511124 == 10 mayorProducto 5 (product [1..1000]) == 41472 |
Soluciones
import Test.QuickCheck import Data.List (inits, tails) import Data.Char (digitToInt) -- 1ª solución -- =========== mayorProducto1 :: Int -> Integer -> Integer mayorProducto1 n x = maximum [product xs | xs <- segmentos n (cifras x)] -- (cifras x) es la lista de las cifras del número x. Por ejemplo, -- cifras 325 == [3,2,5] cifras :: Integer -> [Integer] cifras x = map (toInteger . digitToInt) (show x) -- (segmentos n xs) es la lista de los segmentos de longitud n de la -- lista xs. Por ejemplo, -- segmentos 2 [3,5,4,6] == [[3,5],[5,4],[4,6]] segmentos :: Int -> [Integer] -> [[Integer]] segmentos n xs = take (length xs - n + 1) (map (take n) (tails xs)) -- 2ª solución -- =========== mayorProducto2 :: Int -> Integer -> Integer mayorProducto2 n x = maximum (aux ns) where ns = [read [d] | d <- show x] aux xs | length xs < n = [] | otherwise = product (take n xs) : aux (tail xs) -- 3ª solución -- =========== mayorProducto3 :: Int -> Integer -> Integer mayorProducto3 n = maximum . map (product . take n) . filter ((>=n) . length) . tails . cifras -- 4ª solución -- =========== mayorProducto4 :: Int -> Integer -> Integer mayorProducto4 n = maximum . map (product . map (fromIntegral . digitToInt)) . filter ((==n) . length) . concatMap inits . tails . show -- --------------------------------------------------------------------- -- Comparación de soluciones -- -- --------------------------------------------------------------------- -- Tiempo (en segundos) del cálculo de (mayorProducto 5 (product [1..n])) -- -- | Def | 500 | 1000 | 5000 | 10000 -- | 1 | 0.01 | 0.02 | 0.06 | 0.11 -- | 2 | 0.01 | 0.03 | 0.80 | 3.98 -- | 3 | 0.01 | 0.03 | 0.82 | 4.13 -- | 4 | 2.77 | | | |
Pensamiento
A las palabras de amor
les sienta bien su poquito
de exageración.Antonio Machado