Qiita Teams that are logged in
You are not logged in to any team

Community
Service
Qiita JobsQiita ZineQiita Blog
5
Help us understand the problem. What is going on with this article?
@golden_lucky

# 単価が異なるお菓子をどういう組み合わせで買えば目標の合計値になるか問題

More than 1 year has passed since last update.

``````module Main where

import System.Environment

main :: IO ()
main = do
-- 第一引数：目標の合計金額
-- 残り：お菓子たちの単価
x:xs <- fmap (map \$ read) getArgs
putStrLn \$ show \$ seek x (length xs) \$ comb \$ matrix xs

matrix :: [Int] -> [[(Int,Int)]]
matrix xs = map (\i -> map (\j -> (j,i)) [1..10]) xs

comb :: [[(Int, Int)]] -> [[(Int, Int)]]
comb [] = []
comb ([]:rest) = comb rest
comb ((x:xs):[]) = [[x]] ++ comb [xs]
comb ((x:xs):rest) = [(x:ys) | ys <- comb rest] ++ comb (xs:rest)

seek :: Int -> Int -> [[(Int, Int)]] -> [[(Int, Int)]]
seek target n = filter (totalIs target)
where d (i,j) = i*j
totalIs t xs = length xs == n && t == (sum \$ map d xs)
``````

``````λ> :main "3000" "146" "172" "400" "500"
[[(4,146),(3,172),(1,400),(3,500)]]
λ>
``````

146円のお菓子が4個、172円のが3個、400円のが1個、500円のが3個で3000円になるらしいです。

1. 厳密には、それぞれの上限を10個とするとか、お菓子はなるべく高いものを多く買うとか、もうちょっと制限があった。

5
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
1. We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
2. you can read useful information later efficiently
By "stocking" the articles you like, you can search right away