Created
September 19, 2013 22:59
-
-
Save christiangenco/6631011 to your computer and use it in GitHub Desktop.
Find the ideal move for The Factor Game (http://illuminations.nctm.org/ActivityDetail.aspx?ID=12)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'pry' | |
| class Integer | |
| def factors() (1...self).select { |n| (self % n).zero? } end | |
| end | |
| class Array | |
| def score(n) | |
| total = n | |
| minus = n.factors.inject(0) {|sum, f| | |
| if self.index f | |
| f + sum | |
| else | |
| sum | |
| end | |
| } | |
| return 0 if minus == 0 | |
| total - minus | |
| end | |
| def moves | |
| self.map{|n| | |
| [n, self.score(n)] | |
| } | |
| end | |
| def best | |
| moves = self.moves.sort_by{|a| a[1]} | |
| move = moves.last | |
| moves.reverse.each{|m| | |
| if m[1] == move[1] && m[0] != move[0] | |
| puts "\t#{m}" | |
| # move = m | |
| # move = m if rand > 0.5 | |
| end | |
| break if m[1] < move[1] || m[1] == 0 | |
| } | |
| move | |
| end | |
| end | |
| numbers = (1..49).to_a | |
| # numbers = (1..100).to_a | |
| scores = [0, 0] | |
| turn = 0 | |
| while numbers.length > 0 | |
| player = turn % 2 | |
| other = (turn+1) % 2 | |
| # if player == 0 | |
| move, score = numbers.best | |
| # else | |
| # move, score = numbers.moves.sample | |
| # end | |
| puts "Player #{player} chooses #{move}, player #{other} forced to choose #{(move.factors & numbers).join(', ')} (#{score})" | |
| numbers.delete(move) | |
| numbers -= move.factors | |
| scores[player] += score | |
| # binding.pry | |
| turn += 1 | |
| end | |
| puts "final: #{scores}" |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: