Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
require 'peg_game'

RSpec.describe PegGame do
game = PegGame.new(5,9)
game = PegGame.new(5,5)

it "should create a new board of 5x9" do
expect(game.board.size).to eq(5)
Expand Down
File renamed without changes.
2 changes: 2 additions & 0 deletions peg_game/egjimenezg/.rspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
--color
--require spec_helper
21 changes: 21 additions & 0 deletions peg_game/egjimenezg/lib/input_peg.txt

Large diffs are not rendered by default.

119 changes: 119 additions & 0 deletions peg_game/egjimenezg/lib/peg_game.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
require 'bigdecimal'

class PegGame
attr_accessor :board,:probabilityMatrix,:cols

def initialize(rows,cols)
@board = []
@probabilityMatrix = []
@cols = cols

rows.times do | row |
@board << []

colsForRow = cols-1
displacement = 0

if(isOdd(row)) then
@board[row][0] = " "
@board[row][(cols*2)-2] = " "
colsForRow -= 1
displacement = 1
end

colsForRow.times do | col |
@board[row][(col*2)+displacement] = "X"
@board[row][(col*2)+1+displacement] = "."
end

@board[row][(colsForRow*2)+displacement] = "X"
end

rows.times do | row |
@probabilityMatrix << []

(((cols-1)*2)-1).times do | col |
@probabilityMatrix[row][col] = 0
end
end

end

def quitSpikeIn(row,col)
@board[row][isOdd(row) ? ((col*2)+1) : (col*2)] = "."
end

def getProbabilityForPositions(row,columns,targetColumn)
columnProbabilities = []

columns.each do | column |
if(@board[row+1][column+1] == 'X') then
if(column == 0) then
columnProbabilities << {:column => column+1,:parent => column,:probability => BigDecimal.new("1.0")}
elsif(column == ((@cols-2)*2)) then
columnProbabilities << {:column => column-1,:parent => column,:probability => BigDecimal.new("1.0")}
else
if(((targetColumn-(column-1)).abs)+(row+1) < @board.size) then
columnProbabilities << {:column => column-1,:parent => column,:probability=> BigDecimal.new("0.5")}
end

if((((column+1)-targetColumn).abs)+(row+1) < @board.size) then
columnProbabilities << {:column => column+1,:parent => column,:probability=> BigDecimal.new("0.5")}
end
end
elsif(@board[row+1][column+1] == '.') then
columnWithProbability = {:column => column,:parent => column}

if(row+1 == @board.size-1 && column != targetColumn) then
columnWithProbability[:probability] = BigDecimal.new("0.0")
else
columnWithProbability[:probability] = BigDecimal.new("1.0")
end

columnProbabilities << columnWithProbability
end

end

columnProbabilities
end

def getProbabilityFromColumnToTargetColumn(originColumn,targetColumn)
targetColumn *= 2
@probabilityMatrix[0][originColumn*2] = BigDecimal.new("1.0")
columns = [originColumn*2]
probabilityRows = []

(@board.size-1).times do | row |
probabilityRows = getProbabilityForPositions(row,columns.uniq,targetColumn)

probabilityRows.each do | probabilityRow |
@probabilityMatrix[row+1][probabilityRow[:column]] += (@probabilityMatrix[row][probabilityRow[:parent]]*probabilityRow[:probability])
end

columns.each do | column |
@probabilityMatrix[row][column] = 0
end

columns.clear
columns = probabilityRows.collect{ | probabilityRow | probabilityRow[:column] }
end

probability = @probabilityMatrix[@board.size-1][targetColumn]
@probabilityMatrix[@board.size-1][targetColumn] = 0
probability
end

def getColumnWithHighestProbabilityToFallInTargetColumn(targetColumn)
probabilities = []
(cols-1).times do | column |
probabilities << getProbabilityFromColumnToTargetColumn(column,targetColumn)
end
highestProbability = probabilities.max
{:column => probabilities.index(highestProbability),:probability => highestProbability.truncate(6)}
end

def isOdd(row)
row % 2 != 0
end
end
30 changes: 30 additions & 0 deletions peg_game/egjimenezg/lib/peg_game_script.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
require './peg_game'

inputFile = File.open("input_peg.txt","r")
outputFile = File.open("output_peg.txt","w")

cases = inputFile.gets.tr("\n","").to_i

cases.times do | i |
line = inputFile.gets.split
rows = line[0].to_i
cols = line[1].to_i
targetColumn = line[2].to_i
spikesRemoved = line[3].to_i

points = []

spikesRemoved.times do | j |
point = [line[4+(j*2)],line[4+((j*2)+1)]]
points << point
end

game = PegGame.new(rows,cols)

points.each do | x, y |
game.quitSpikeIn(x.to_i,y.to_i)
end

result = game.getColumnWithHighestProbabilityToFallInTargetColumn(targetColumn)
outputFile.write("#{result[:column]} #{result[:probability]}\n")
end
56 changes: 56 additions & 0 deletions peg_game/egjimenezg/spec/peg_game_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
require 'peg_game'

RSpec.describe PegGame do

game = PegGame.new(5,5)

it "should create a new board of RxC" do
expect(game.board.size).to eq(5)
expect(game.board[0]).to match_array(['X','.','X','.','X','.','X','.','X'])
expect(game.board[1]).to match_array([' ','X','.','X','.','X','.','X',' '])
end

[
[1, 1, 4],
[2, 1, 5],
[3, 2, 4]
].each do |row, col, size|
it "should quit spike in (#{row}, #{col}) from board" do
game_row = game.board[row]
spikes = game_row.count('X')
expect(spikes).to eq size
game.quitSpikeIn(row, col)

game_row = game.board[row]
spikes = game_row.count('X')
expect(spikes).to eq(size - 1)
end
end

[
[0,[0],0,[{:column => 1,:parent => 0,:probability => BigDecimal.new("1.0")}]],
[0,[6],0,[{:column => 5,:parent => 6,:probability => BigDecimal.new("1.0")}]],
[0,[4],0,[{:column => 3,:parent => 4,:probability => BigDecimal.new("0.5")}]],
[1,[1],0,[{:column => 1,:parent => 1,:probability => BigDecimal.new("1.0")}]],
[3,[4],6,[{:column => 4,:parent => 4,:probability => BigDecimal.new("0.0")}]],
[1,[3,5],6,[{:column => 4,:parent => 3,:probability => BigDecimal.new("0.5")},
{:column => 4,:parent => 5,:probability => BigDecimal.new("0.5")},
{:column => 6,:parent => 5,:probability => BigDecimal.new("0.5")}]]
].each do | row, columns, targetColumn, columnsWithProbability |
it "should calculate the probabilities of the ways when the ball drop from columns #{columns}" do
probabilities = game.getProbabilityForPositions(row,columns,targetColumn)
expect(probabilities).to match_array(columnsWithProbability)
end
end

it "should calculate the probability of fall from the first column to the target column" do
probability = game.getProbabilityFromColumnToTargetColumn(0,0)
expect(probability).to eq(0.5)
end

it "should find the column with highest probability to fall in the target column" do
columnWithProbability = game.getColumnWithHighestProbabilityToFallInTargetColumn(0)
expect(columnWithProbability).to include({:column => 0,:probability => BigDecimal.new("0.5") })
end

end
96 changes: 96 additions & 0 deletions peg_game/egjimenezg/spec/spec_helper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# The `.rspec` file also contains a few flags that are not defaults but that
# users commonly want.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end

# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end

# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# These two settings work together to allow you to limit a spec run
# to individual examples or groups you care about by tagging them with
# `:focus` metadata. When nothing is tagged with `:focus`, all examples
# get run.
config.filter_run :focus
config.run_all_when_everything_filtered = true

# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"

# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!

# This setting enables warnings. It's recommended, but in some cases may
# be too noisy due to issues in dependencies.
config.warnings = true

# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = 'doc'
end

# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10

# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random

# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end