Biparticiones de un número
Definir la función
1 |
biparticiones :: Integer -> [(Integer,Integer)] |
tal que (biparticiones n) es la lista de pares de números formados por las primeras cifras de n y las restantes. Por ejemplo,
1 2 |
biparticiones 2025 == [(202,5),(20,25),(2,25)] biparticiones 10000 == [(1000,0),(100,0),(10,0),(1,0)] |
Soluciones
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
import Test.QuickCheck -- 1ª solución -- =========== biparticiones1 :: Integer -> [(Integer,Integer)] biparticiones1 x = [(read y, read z) | (y,z) <- biparticionesL1 xs] where xs = show x -- (biparticionesL1 xs) es la lista de los pares formados por los -- prefijos no vacío de xs y su resto. Por ejemplo, -- biparticionesL1 "2025" == [("2","025"),("20","25"),("202","5")] biparticionesL1 :: [a] -> [([a],[a])] biparticionesL1 xs = [splitAt k xs | k <- [1..length xs - 1]] -- 2ª solución -- =========== biparticiones2 :: Integer -> [(Integer,Integer)] biparticiones2 x = [(read y, read z) | (y,z) <- biparticionesL2 xs] where xs = show x -- (biparticionesL2 xs) es la lista de los pares formados por los -- prefijos no vacío de xs y su resto. Por ejemplo, -- biparticionesL2 "2025" == [("2","025"),("20","25"),("202","5")] biparticionesL2 :: [a] -> [([a],[a])] biparticionesL2 xs = takeWhile (not . null . snd) [splitAt n xs | n <- [1..]] -- 3ª solución -- =========== biparticiones3 :: Integer -> [(Integer,Integer)] biparticiones3 a = takeWhile ((>0) . fst) [divMod a (10^n) | n <- [1..]] -- 4ª solución -- =========== biparticiones4 :: Integer -> [(Integer,Integer)] biparticiones4 n = [quotRem n (10^x) | x <- [1..length (show n) -1]] -- 5ª solución -- =========== biparticiones5 :: Integer -> [(Integer,Integer)] biparticiones5 n = takeWhile (/= (0,n)) [divMod n (10^x) | x <- [1..]] -- Comparación de eficiencia -- ========================= -- λ> numero n = (read (replicate n '2')) :: Integer -- (0.00 secs, 0 bytes) -- λ> length (biparticiones1 (numero 10000)) -- 9999 -- (0.03 secs, 10,753,192 bytes) -- λ> length (biparticiones2 (numero 10000)) -- 9999 -- (1.89 secs, 6,410,513,136 bytes) -- λ> length (biparticiones3 (numero 10000)) -- 9999 -- (0.54 secs, 152,777,680 bytes) -- λ> length (biparticiones4 (numero 10000)) -- 9999 -- (0.01 secs, 7,382,816 bytes) -- λ> length (biparticiones5 (numero 10000)) -- 9999 -- (2.11 secs, 152,131,136 bytes) -- -- λ> length (biparticiones1 (numero (10^7))) -- 9999999 -- (14.23 secs, 10,401,100,848 bytes) -- λ> length (biparticiones4 (numero (10^7))) -- 9999999 -- (11.43 secs, 7,361,097,856 bytes) |