# Números como suma de N sumandos

Definir la función

 sumas :: Int -> [Int] -> [Int]

tal que (sumas n xs) es la lista de los números que se pueden obtener como suma de n, o menos, elementos de xs. Por ejemplo,

 sumas 0 [2,5] == [0] sumas 1 [2,5] == [0,2,5] sumas 2 [2,5] == [0,2,4,5,7,10] sumas 3 [2,5] == [0,2,4,5,6,7,9,10,12,15] sumas 2 [2,3,5] == [0,2,3,4,5,6,7,8,10] sumas 3 [2,3,5] == [0,2,3,4,5,6,7,8,9,10,11,12,13,15] length (sumas 8 [1..200]) == 1601

#### Soluciones

 import Data.List (nub, sort)   sumas :: Int -> [Int] -> [Int] sumas 0 _ = [0] sumas n xs = nub (sort (ys ++ [x+y | x <- xs, y <- ys])) where ys = sumas (n-1) xs

#### Solución con Maxima

 sumas (n,xs) := block ([ys], if n > 0 then ( ys : sumas (n-1, xs), unique (append (ys, create_list (x+y,x,xs,y,ys))) ) else [0])\$

## 8 soluciones de “Números como suma de N sumandos”

1. carruirui3
 import Data.List (nub, sort)   sumas :: Int -> [Int] -> [Int] sumas 0 _ = [0] sumas n xs = sort . nub \$ sumas (n-1) xs ++ map sum (sequence [xs | i <- [1..n]])
2. alvalvdom1
 import Data.List   sumas :: Int -> [Int] -> [Int] sumas 0 _ = [0] sumas n xs = nub (sort (c ++ [x+y | x <- c, y <- xs])) where c = sumas (n-1) xs
3. javoliher
 sumas :: Int -> [Int] -> [Int] sumas 0 xs = [0] sumas 1 xs = 0:xs sumas n xs = (sort.nub)\$ [x+y | x <- xs, y <- ys]++ ys where ys = sumas (n-1) xs
4. erisan
 import Data.List   sumas :: Int -> [Int] -> [Int] sumas 0 _ = [0] sumas 1 xs = 0 : xs sumas n xs = sort \$ nub [sum y | y <- nub ((subsequences (concatMap (replicate n) xs))), length y <= n]
5. abrdelrod
 import Data.List   sumas 0 _ = [0] sumas n xs = (map head.group.sort) (ys ++ [x+y | x <- ys, y <- xs]) where ys = sumas (n-1) xs
6. fracruzam
 import Data.List   sumas :: Int -> [Int] -> [Int] sumas n = nub . sort . map sum . aux n   aux :: Int -> [a] -> [[a]] aux 0 _ = [[]] aux 1 xs = []: map (x -> [x]) xs aux n xs = []:[x:ys | x <- xs , ys <- aux (n-1) xs]
7. juamorrom1

import Data.List

sumas :: Int -> [Int] -> [Int]
sumas 0 _ = [0]
sumas 1 xs = 0:xs
sumas n xs = 0: (iterate (xs `sumaListaTodos`) xs) !! (n-1)

sumaNumeroTodos :: Int -> [Int] -> [Int]
sumaNumeroTodos x ys = [ x + y | y <- 0:ys ]

sumaListaTodos :: [Int] -> [Int] -> [Int]
sumaListaTodos xs ys = sort \$ nub \$ concat [sumaNumeroTodos x ys | x <- xs ]

8. antmacrui

En Maxima

 sumas (n,xs) := block ([ys], if n > 0 then ( ys : sumas (n-1, xs), unique (append (ys, create_list (x+y,x,xs,y,ys))) ) else [0])\$

Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.