Online Judge Solutions

Sunday, January 4, 2015

CanIWin

This was discussed at http://www.mitbbs.com/article_t/JobHunting/32861097.html

In "the 100 game," two players take turns adding, to a running total, any integer from 1..10. The player who first causes the running total to reach or exceed 100 wins. 

What if we change the game so that players cannot re-use integers? 

For example, if two players might take turns drawing from a common pool of numbers of 1..15 without replacement until they reach a total >= 100. This problem is to write a program that determines which player would win with ideal play. 

Write a procedure, "Boolean canIWin(int maxChoosableInteger, int desiredTotal)", 
which returns true if the first player to move can force a win with optimal play. 

发信人: sirzen (会飞的鸭子), 信区: JobHunting
标  题: Re: 问一道L家的题
发信站: BBS 未名空间站 (Sun Jan  4 21:59:55 2015, 美东)

如果可以重复选数字,那么如果 target % (maxChoosable + 1) == 0 那么玩家2必胜
,如果不是0那么玩家1第一步先拿到target % (maxChoosable + 1),然后对应玩家2拿
的数字来拿 maxChoosable + 1 - player2Num,最后就刚好抢到target。



如果不可以重复选数字, there is a solution from http://blog.csdn.net/lsdtc1225/article/details/40342473:  
public boolean canIWin(int max, int target) { List<Integer> candidates = new ArrayList<Integer>(); for (int i = 1; i <= max; i++){ candidates.add(i); } return helper(candidates, target); } public boolean helper(List<Integer> candidates, int target){ if (candidates.get(candidates.size()-1) >= target){ return true; } for (int i = 0; i < candidates.size(); i++){ int removed = candidates.remove(i); if (!helper(candidates, target-removed)){ candidates.add(i, removed); return true; } candidates.add(i, removed); } return false; }

No comments:

Post a Comment