Шарлатан

Краен срок
23.12.2013 23:30

Срокът за предаване на решения е отминал

Шарлатанство

Изберете си число между 1 и 10. Умножете това число по 2. Умножете полученото по 5. Разделете новия резултат на числото, което бяхте избрали първоначално. Извадете 7 от новия резултат.

Абракадабра!

Получихте 3, нали?

Всички сме чували/представяли такива трикове, дори сме бивали дълбоко впечатлявани от тях, когато сме били невръстни. Разбира се, тестването на достоверността на тези трикове би било по-лесно, ако се напише малко код. Един изключително полезен съвет от книгата "The Pragmatic Programmer: From Journeyman to Master" e:

Program close to the problem domain

Да опитаме.

Искаме да създадем мини-език, a.k.a. DSL в който „операторите“ са манипулациите с числа, близки до естествения език, с който бихме описали трика. Например, трикът, който представихме в началото, може да бъде записан и проверен по следния начин:

Charlatan.trick do
  pick_from 1..10
  multiply_by 2
  multiply_by 5
  divide_by :your_number
  subtract 7
  you_should_get 3
end

За целите на това предизвикателство, ще приемем, че горният код е по-четим заради близостта си до "проблемната област" (domain), от този:

(1..10).all? do |number|
  ((number * 2 * 5) / number) - 7 == 3
end

Затова, създайте модул Charlatan, в който има метод Charlatan.trick, приемащ блок, който дефинира „проверяваща програма“ от следния вид:

  1. pick_from <range> – задава интервал от цели числа, за които ще тестваме дали трикът работи. Приема само области от числа.
  2. Числови манипулации, които могат да бъдат извършвани върху предходния резултат:
    • add <number> – добавя число към текущия резултат.
    • subtract <number> – изважда число от текущия резултат.
    • multiply_by <number> – умножава текущия резултат по число.
    • divide_by <number> – Разделя (целочислено) текущия резултат на число.
  3. you_should_get <number> – последният ред на програмата указва числото, което трябва да бъде „разпознато“ от шарлатана в края на трика.

Вместо число, на всички операции без pick_from, може да се подаде символът :your_number, който трябва да представлява стойността на първоначално избраното число.

Изпълнението на Charlatan.trick трябва да връща true, или false, в зависимост от това дали манипулациите върху всяко число от областта са довели до числото, подадено като аргумент на you_should_get.

Примери:

Charlatan.trick do
  pick_from 1..1
  add 1
  you_should_get 2
end                    # => true

Charlatan.trick do
  pick_from 1..2
  add 2
  subtract 2
  you_should_get :your_number
end                    # => true

Charlatan.trick do
  pick_from 10..100
  multiply_by 3
  you_should_get 1000
end                    # => false

Забележка: Подадените на Charlatan.trick програми ще бъдат коректни, всички ще започват с pick_from и ще завършват с you_should_get. Също така, няма да се подават некоректни данни, както сме казвали много пъти досега.

Ако изпитвате затруднения да измислите как да реализирате този DSL, питайте във форума или ни пишете.

Решения

Димитър Димитров
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Димитър Димитров
module Charlatan
class Evaluator
operations = {
add: :'+',
subtract: :'-',
multiply_by: :'*',
divide_by: :'/',
}
operations.each do |operation_name, operation|
define_method operation_name do |argument|
@operations_queue << [operation, argument]
end
end
def initialize
@operations_queue = []
end
def pick_from(range)
@numbers = range
end
def you_should_get(argument)
@numbers.all? do |number|
expected = argument == :your_number ? number : argument
expected == perform_operations_on(number)
end
end
private
def perform_operations_on(number)
@operations_queue.reduce(number) do |current_result, (operation, argument)|
argument = number if argument == :your_number
current_result.public_send operation, argument
end
end
end
def self.trick(&block)
Evaluator.new.instance_eval &block
end
end
........

Finished in 0.0099 seconds
8 examples, 0 failures
Георги Ангелов
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Георги Ангелов
class Charlatan
def initialize
@operations = []
end
def pick_from(range)
@range = range
end
def add(number)
@operations << [:+, number]
end
def subtract(number)
@operations << [:-, number]
end
def multiply_by(number)
@operations << [:*, number]
end
def divide_by(number)
@operations << [:/, number]
end
def you_should_get(expected_number)
@expected_number = expected_number
end
def verify_trick
@range.all? do |picked_number|
result = @operations.reduce(picked_number.to_r) do |current_number, (operation, number)|
number = picked_number if number == :your_number
operation.to_proc.call(current_number, number)
end
expected = @expected_number == :your_number ? picked_number : @expected_number
result == expected
end
end
def self.trick(&block)
charlatan = new
charlatan.instance_eval &block
charlatan.verify_trick
end
end
........

Finished in 0.00994 seconds
8 examples, 0 failures
Георги Гърдев
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Георги Гърдев
module Charlatan
class << self
def trick(&block)
instance_eval(&block)
end
def pick_from(range)
@@picked = range.to_a
@@transformed = @@picked
end
def multiply_by(number)
@@transformed = operation(:*, number)
end
def divide_by(number)
@@transformed = operation(:/, number)
end
def subtract(number)
@@transformed = operation(:-, number)
end
def add(number)
@@transformed = operation(:+, number)
end
def you_should_get(number)
if number == :your_number
@@transformed == @@picked
else
@@transformed.all? { |element| element == number }
end
end
private
def operation(operator, number)
if number == :your_number
@@transformed.zip(@@picked).map { |tuple| tuple.reduce(operator) }
else
@@transformed.map { |element| operator.to_proc.call(element, number) }
end
end
end
end
........

Finished in 0.01418 seconds
8 examples, 0 failures
Георги Пурнаров
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Георги Пурнаров
module Charlatan
class Charlatan_functions
def self.pick_from array
@array=array.to_a
@instance_array=array.to_a
end
def self.add number
if number==:your_number
@array = @array.each_with_index.map { |element,i| element + @instance_array[i] }
else
@array = @array.map { |element| element + number}
end
end
def self.subtract number
if number==:your_number
@array = @array.each_with_index.map { |element,i| element - @instance_array[i] }
else
@array = @array.map { |element| element - number}
end
end
def self.multiply_by number
if number==:your_number
@array = @array.each_with_index.map { |element,i| element * @instance_array[i] }
else
@array = @array.map { |element| element * number}
end
end
def self.divide_by number
if number==:your_number
@array = @array.each_with_index.map { |element,i| element / @instance_array[i] }
else
@array = @array.map { |element| element/number}
end
end
def self.you_should_get number
if number==:your_number
@array.each_with_index.map { |element,i| element == @instance_array[i] }.all?
else
@array.map { |element| element == number}.all?
end
end
end
def Charlatan.trick &block
Charlatan_functions.instance_eval &block
end
end
........

Finished in 0.01136 seconds
8 examples, 0 failures
Стефан Василев
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Стефан Василев
module Charlatan
extend self
def trick(&block)
p instance_eval &block
end
def pick_from(range)
@values_between_range = []
range.each { |number| @values_between_range << number }
@range = []
range.each { |number| @range << number }
end
def add(value)
@values_between_range.each_index { |index| @values_between_range[index] += (value == :your_number ? @range[index] : value) }
end
def subtract(value)
@values_between_range.each_index { |index| @values_between_range[index] -= (value == :your_number ? @range[index] : value) }
end
def multiply_by(value)
@values_between_range.each_index { |index| @values_between_range[index] *= (value == :your_number ? @range[index] : value) }
end
def divide_by(value)
@values_between_range.each_index { |index| @values_between_range[index] /= (value == :your_number ? @range[index] : value) }
end
def you_should_get(value)
@values_between_range.each_index do |index|
return false if @values_between_range[index] != (value == :your_number ? @range[index] : value)
end
true
end
end
true
.true
.true
.true
.true
.true
.true
.true
false
.

Finished in 0.01011 seconds
8 examples, 0 failures
Георги Шопов
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Георги Шопов
module Charlatan
class << self
def trick(&block)
CheckTrick.new.instance_eval(&block)
end
private
class CheckTrick
def pick_from(range)
@initial_range = range.to_a
@modified_range = @initial_range.dup
end
def add(addend)
transform_range(:+, addend)
end
def subtract(addend)
transform_range(:-, addend)
end
def multiply_by(multiplier)
transform_range(:*, multiplier)
end
def divide_by(divisor)
transform_range(:/, divisor)
end
def you_should_get(expectation)
@modified_range.each_with_index.all? do |number, index|
if expectation == :your_number
number == @initial_range[index]
else
number == expectation
end
end
end
def transform_range(method, argument)
@modified_range.map!.each_with_index do |number, index|
if argument == :your_number
number.public_send(method, @initial_range[index])
else
number.public_send(method, argument)
end
end
end
end
end
end
........

Finished in 0.01128 seconds
8 examples, 0 failures
Антонио Николов
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Антонио Николов
module Charlatan
@@args
@@should_get
@@range
def charlatan_magic
@@range.all? do |number|
current_number = number
@@args.each do |function|
case function[0]
when :add
function[1] == :your_number ? current_number += number : current_number += function[1]
when :subtract
function[1] == :your_number ? current_number -= number : current_number -= function[1]
when :multiply_by
function[1] == :your_number ? current_number *= number : current_number *= function[1]
when :divide_by
function[1] == :your_number ? current_number /= number : current_number /= function[1]
end
end
@@should_get == :your_number ? current_number == number : @@should_get == current_number
end
end
def pick_from(range)
@@range = range
end
def add(number)
@@args << [:add, number]
end
def subtract(number)
@@args << [:subtract, number]
end
def multiply_by(number)
@@args << [:multiply_by, number]
end
def divide_by(number)
@@args << [:divide_by, number]
end
def you_should_get(number)
@@should_get = number
end
def Charlatan.trick(&block)
@@args = []
block.call
charlatan_magic
end
end
include Charlatan
........

Finished in 0.0101 seconds
8 examples, 0 failures
Николай Хубанов
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Николай Хубанов
class Charlatan
def self.trick(&block)
Charlatan.new(&block).correct_trick?
end
def initialize(&block)
@operations = []
instance_eval(&block)
end
def pick_from range
@range = range
end
def you_should_get result
@result = result
end
def add(number)
@operations << [:+, number]
end
def subtract(number)
@operations << [:-, number]
end
def multiply_by(number)
@operations << [:*, number]
end
def divide_by(number)
@operations << [:/, number]
end
def correct_trick?
@range.all? do |number|
@operations.inject(number) do |result, operation|
result.send operation[0], operation[1] == :your_number ? number : operation[1]
end.eql?(@result == :your_number ? number : @result)
end
end
end
........

Finished in 0.0097 seconds
8 examples, 0 failures
Ясен Трифонов
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Ясен Трифонов
class Charlatan
class << self
def trick(&block)
class_eval &block
end
private
def pick_from(range)
@numbers = []
range.each { |number| @numbers << number }
@original = @numbers
end
def you_should_get(result)
result_array = @original.dup
result_array.map! { result } if result != :your_number
result_array == @numbers
end
def add(other)
check other, :+
end
def subtract(other)
check other, :-
end
def multiply_by(other)
check other, :*
end
def divide_by(other)
check other, :/
end
def check(other, operation)
other_array = @original.dup
other_array.map! { other } if other != :your_number
@numbers = [@numbers, other_array].transpose.map { |number| number.reduce(operation) }
end
end
end
........

Finished in 0.00983 seconds
8 examples, 0 failures
Георги Кръстев
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Георги Кръстев
class Charlatan
def self.trick(&block)
new.instance_eval &block
end
def pick_from(range)
@range = range
@numbers = range.lazy
end
def add(addend)
operation(addend, &:+)
end
def subtract(subtrahend)
operation(subtrahend, &:-)
end
def multiply_by(multiplier)
operation(multiplier, &:*)
end
def divide_by(divisor)
operation(divisor, &:/)
end
def you_should_get(expected)
operation(expected, &:==).all?
end
private
def operation(argument)
@numbers = if argument == :your_number
@numbers.zip(@range).map { |pair| yield *pair }
else
@numbers.map { |number| yield number, argument }
end
end
end
........

Finished in 0.01819 seconds
8 examples, 0 failures
Виктор Кетипов
  • Некоректно
  • 6 успешни тест(а)
  • 2 неуспешни тест(а)
Виктор Кетипов
module Charlatan
def Charlatan.trick(&block)
trick_set = TrickSet.new
trick_set.instance_eval(&block)
puts trick_set.result
return trick_set.result
end
Action = Struct.new(:type, :number)
class TrickSet
def initialize()
@actions = Array.new
@add = 0
@multiply = 1
end
def pick_from(range)
@range = range
end
def add(number)
action = Action.new
action.type = "add"
action.number = number
@actions.push(action)
end
def subtract(number)
action = Action.new
action.type = "subtract"
action.number = number
@actions.push(action)
end
def multiply_by(number)
action = Action.new
action.type = "multiply_by"
action.number = number
@actions.push(action)
end
def divide_by(number)
action = Action.new
action.type = "divide_by"
action.number = number
@actions.push(action)
end
def execute_action(action, x)
if action.type == "add"
x + action.number
elsif action.type == "subtract"
x - action.number
elsif action.type == "multiply_by"
x * action.number
elsif action.type == "divide_by"
x / action.number
end
end
def you_should_get(number)
@range.each do |x|
x_after_actions = x
@actions.each { |action| x_after_actions = execute_action(action, x_after_actions) }
expected_result = number == :your_number ? x : number
if x_after_actions != expected_result then
#return false
@result = false
return
end
end
#return true
@result = true
end
def result()
@result
end
end
end
true
.true
.true
.true
.true
.Ftrue
.F

Failures:

  1) Charlatan allows :your_number as an argument to arithmetic methods
     Failure/Error: you_should_get 0
     TypeError:
       :your_number can't be coerced into Fixnum
     # /tmp/d20140105-32545-2su3w4/solution.rb:46:in `-'
     # /tmp/d20140105-32545-2su3w4/solution.rb:46:in `execute_action'
     # /tmp/d20140105-32545-2su3w4/solution.rb:56:in `block (2 levels) in you_should_get'
     # /tmp/d20140105-32545-2su3w4/solution.rb:56:in `each'
     # /tmp/d20140105-32545-2su3w4/solution.rb:56:in `block in you_should_get'
     # /tmp/d20140105-32545-2su3w4/solution.rb:54:in `each'
     # /tmp/d20140105-32545-2su3w4/solution.rb:54:in `you_should_get'
     # /tmp/d20140105-32545-2su3w4/spec.rb:45:in `block (3 levels) in <top (required)>'
     # /tmp/d20140105-32545-2su3w4/solution.rb:4:in `instance_eval'
     # /tmp/d20140105-32545-2su3w4/solution.rb:4:in `trick'
     # /tmp/d20140105-32545-2su3w4/spec.rb:42:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

  2) Charlatan actually performs calculations
     Failure/Error: you_should_get 3
     TypeError:
       :your_number can't be coerced into Fixnum
     # /tmp/d20140105-32545-2su3w4/solution.rb:50:in `/'
     # /tmp/d20140105-32545-2su3w4/solution.rb:50:in `execute_action'
     # /tmp/d20140105-32545-2su3w4/solution.rb:56:in `block (2 levels) in you_should_get'
     # /tmp/d20140105-32545-2su3w4/solution.rb:56:in `each'
     # /tmp/d20140105-32545-2su3w4/solution.rb:56:in `block in you_should_get'
     # /tmp/d20140105-32545-2su3w4/solution.rb:54:in `each'
     # /tmp/d20140105-32545-2su3w4/solution.rb:54:in `you_should_get'
     # /tmp/d20140105-32545-2su3w4/spec.rb:63:in `block (3 levels) in <top (required)>'
     # /tmp/d20140105-32545-2su3w4/solution.rb:4:in `instance_eval'
     # /tmp/d20140105-32545-2su3w4/solution.rb:4:in `trick'
     # /tmp/d20140105-32545-2su3w4/spec.rb:57:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

Finished in 0.01031 seconds
8 examples, 2 failures

Failed examples:

rspec /tmp/d20140105-32545-2su3w4/spec.rb:41 # Charlatan allows :your_number as an argument to arithmetic methods
rspec /tmp/d20140105-32545-2su3w4/spec.rb:56 # Charlatan actually performs calculations
Диан Николов
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Диан Николов
module Charlatan
def self.trick
yield
end
end
def pick_from(range)
@range = range.to_a.zip range.to_a
end
def add(number)
@range.each { |n| n[1] += (number != :your_number ? number : n[0]) }
end
def subtract(number)
@range.each { |n| n[1] -= (number != :your_number ? number : n[0]) }
end
def divide_by(number)
@range.each { |n| n[1] /= (number != :your_number ? number : n[0]) }
end
def multiply_by(number)
@range.each { |n| n[1] *= (number != :your_number ? number : n[0]) }
end
def you_should_get(number)
@range.all? { |n| n[1] == (number != :your_number ? number : n[0]) }
end
........

Finished in 0.0096 seconds
8 examples, 0 failures
Наталия Пацовска
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Наталия Пацовска
module Charlatan
def self.trick(&block_to_validate)
block_source = extract_source block_to_validate
trick_from_source_code(block_source).valid?
end
def self.available_operations
{add: :+, subtract: :-, multiply_by: :*, divide_by: :/}
end
private
def self.extract_source(block)
file_path, start_line = block.source_location
source = File.open(file_path, "rb") { |file| file.read }
source.lines.slice(start_line, source.lines.size).take_while { |line| line.match(/end/) == nil }
end
def self.trick_from_source_code(block_source)
operations = []
range, expected_result = nil
block_source.map do |line|
_, instruction_name, argument = line.match(/\s*(\S*)\s*(\S*)/).to_a
case instruction_name
when "pick_from"
range = Range.new(*argument.split("..").map(&:to_i))
when "you_should_get"
argument = argument.start_with?(":") ? nil : argument.to_i
expected_result = argument
else
argument = argument.start_with?(":") ? nil : argument.to_i
operations << {available_operations[instruction_name.to_sym] => argument}
end
end
Trick.new range, operations, expected_result
end
class Trick
def initialize(range, operations, expected_result)
@range = range
@operations = operations
@expected_result = expected_result
end
def valid?
@range.all? do |your_number|
result = @operations.reduce(your_number) do |result, operation|
result.send operation.keys.first, (operation.values.first or your_number)
end
result == (@expected_result or your_number)
end
end
end
end
........

Finished in 0.01239 seconds
8 examples, 0 failures
Георги Урумов
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Георги Урумов
module Charlatan
def self.trick(&block)
instance_eval(&block)
end
private
def self.pick_from(range)
@result = range.to_a.sample
@your_number = @result
end
def self.add(number)
return @result += @your_number if number.is_a? Symbol
@result += number
end
def self.subtract(number)
return @result -= @your_number if number.is_a? Symbol
@result -= number
end
def self.multiply_by(number)
return @result *= @your_number if number.is_a? Symbol
@result *= number
end
def self.divide_by(number)
return @result /= @your_number if number.is_a? Symbol
@result /= number
end
def self.you_should_get(number)
return @result == @your_number if number.is_a? Symbol
@result.eql? number
end
end
........

Finished in 0.01115 seconds
8 examples, 0 failures
Николай Каращранов
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Николай Каращранов
module Charlatan
def your_number()
@constant_array
end
def pick_from(range)
@constant_array = range.to_a
@variable_array = range.to_a
end
def operation_with_array(operation, array)
@variable_array = @variable_array.each_with_index.map do |m, index|
m.send(operation, array[index])
end
end
def add(number)
if number == :your_number
operation_with_array(:+, send(number))
else
@variable_array.map! { |m| m + number }
end
end
def subtract(number)
if number == :your_number
operation_with_array(:-, send(number))
else
@variable_array.map! { |m| m - number }
end
end
def multiply_by(number)
if number == :your_number
operation_with_array(:*, send(number))
else
@variable_array.map! { |m| m * number }
end
end
def divide_by(number)
if number == :your_number
operation_with_array(:/, send(number))
else
@variable_array.map! { |m| m / number }
end
end
def you_should_get(number)
if (number == :your_number)
@variable_array == send(number)
else
@variable_array.uniq == [number]
end
end
def self.trick()
yield
end
end
class Object
include Charlatan
end
........

Finished in 0.00961 seconds
8 examples, 0 failures
Деян Хаджиев
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Деян Хаджиев
module Charlatan
class DSLObject
def initialize
@numbers = []
end
def pick_from(enum)
@original_enum = enum
@numbers = enum.to_a
end
def add(number)
generic_action(:+, number)
end
def subtract(number)
generic_action(:-, number)
end
def multiply_by(number)
generic_action(:*, number)
end
def divide_by(number)
generic_action(:/, number)
end
def you_should_get(number)
generic_action(:==, number)
@numbers.all?
end
private
def generic_action(action, number)
if number == :your_number
zipped = @numbers.zip @original_enum.to_a
@numbers = zipped.map { |element| element[0].send(action, element[1]) }
else
@numbers.map! { |element| element.send(action, number) }
end
end
end
class << self
def trick(&block)
context = DSLObject.new
context.instance_eval(&block)
end
end
end
........

Finished in 0.00983 seconds
8 examples, 0 failures
Мария Митева
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Мария Митева
module Charlatan
def self.trick(&block)
queries = Query.new(&block)
queries.return_result
end
class Query
def initialize(&block)
instance_eval(&block)
end
def pick_from(range)
@range = range.zip(range)
end
def add(number)
if number == :your_number
@range = @range.map { |x, y| [x, y + x] }
else
@range = @range.map { |x, y| [x, y + number] }
end
end
def subtract(number)
if number == :your_number
@range = @range.map { |x, y| [x, y - x] }
else
@range = @range.map { |x, y| [x, y - number] }
end
end
def multiply_by(number)
if number == :your_number
@range = @range.map { |x, y| [x, y * x] }
else
@range = @range.map { |x, y| [x, y * number] }
end
end
def divide_by(number)
if number == :your_number
@range = @range.map { |x, y| [x, y / x] }
else
@range = @range.map { |x, y| [x, y / number] }
end
end
def you_should_get(number)
if number == :your_number
set = @range.select { |x, y| x != y }
@result = set.empty?
else
set = @range.map { |x, y| y }.uniq
@result = set.size == 1 && (set.include? number)
end
end
def return_result
@result
end
end
end
........

Finished in 0.01043 seconds
8 examples, 0 failures
Росен Рачев
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Росен Рачев
module Charlatan
def self.trick(&block)
instance_eval &block
end
def self.pick_from(range)
@result = range.to_a.dup
@your_number = range.to_a.dup
end
def self.add(number)
if number == :your_number
@result = @result.zip(@your_number).map { |element| element.reduce(:+) }
else
@result = @result.map { |element| element + number }
end
end
def self.subtract(number)
if number == :your_number
@result = @result.zip(@your_number).map { |element| element.reduce(:-) }
else
@result = @result.map { |element| element - number }
end
end
def self.multiply_by(number)
if number == :your_number
@result = @result.zip(@your_number).map { |element| element.reduce(:*) }
else
@result = @result.map { |element| element * number }
end
end
def self.divide_by(number)
if number == :your_number
@result = @result.zip(@your_number).map { |element| element.reduce(:/) }
else
@result = @result.map { |element| element / number }
end
end
def self.you_should_get(number)
if number == :your_number
@result == @your_number
else
@result.all? { |element| element == number } or @result == number
end
end
end
........

Finished in 0.01014 seconds
8 examples, 0 failures
Мария Терзиева
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Мария Терзиева
module Charlatan
def Charlatan.trick(&block)
Actions.new.execute_actions(&block)
end
class Actions
def pick_from(range)
@current_result = @your_number = range.to_a.sample
end
def action(operation, number)
if number == :your_number
@current_result = @current_result.public_send operation, @your_number
else
@current_result = @current_result.public_send operation, number
end
end
def multiply_by(number)
action :*, number
end
def add(number)
action :+, number
end
def subtract(number)
action :-, number
end
def divide_by(number)
action :/, number
end
def you_should_get(number)
action :==, number
end
def execute_actions(&block)
instance_eval &block
end
private :action
end
end
........

Finished in 0.00972 seconds
8 examples, 0 failures
Илиян Танев
  • Некоректно
  • 6 успешни тест(а)
  • 2 неуспешни тест(а)
Илиян Танев
module Charlatan
def self.trick(&block)
@numbers = []
@original_numbers = []
instance_eval(&block)
end
def self.pick_from(range, &block)
@numbers = range.to_a
@original_numbers = range.to_a
@numbers.each(&block)
end
def self.multiply_by(num)
if(num.is_a? Symbol)
@numbers.map! { |n| n * n }
else
@numbers.map! { |n| n * num }
end
end
def self.add(num)
if(num.is_a? Symbol)
@numbers.map! { |n| n + n }
else
@numbers.map! { |n| n + num }
end
end
def self.subtract(num)
if(num.is_a? Symbol)
@numbers.map! { |n| n - n }
else
@numbers.map! { |n| n - num }
end
end
def divide_by(num)
if(num.is_a? Symbol)
@numbers.map! { |n| n / n }
else
@numbers.map! { |n| n / num }
end
end
def self.you_should_get(num)
if(num.is_a? Symbol)
(@numbers - @original_numbers).empty?
else
@numbers.all? { |n| n == num }
end
end
end
....F..F

Failures:

  1) Charlatan performs division
     Failure/Error: divide_by 2
     NoMethodError:
       undefined method `divide_by' for Charlatan:Module
     # /tmp/d20140105-32545-qao338/spec.rb:36:in `block (3 levels) in <top (required)>'
     # /tmp/d20140105-32545-qao338/solution.rb:5:in `instance_eval'
     # /tmp/d20140105-32545-qao338/solution.rb:5:in `trick'
     # /tmp/d20140105-32545-qao338/spec.rb:34:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

  2) Charlatan actually performs calculations
     Failure/Error: divide_by :your_number
     NoMethodError:
       undefined method `divide_by' for Charlatan:Module
     # /tmp/d20140105-32545-qao338/spec.rb:61:in `block (3 levels) in <top (required)>'
     # /tmp/d20140105-32545-qao338/solution.rb:5:in `instance_eval'
     # /tmp/d20140105-32545-qao338/solution.rb:5:in `trick'
     # /tmp/d20140105-32545-qao338/spec.rb:57:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

Finished in 0.00986 seconds
8 examples, 2 failures

Failed examples:

rspec /tmp/d20140105-32545-qao338/spec.rb:33 # Charlatan performs division
rspec /tmp/d20140105-32545-qao338/spec.rb:56 # Charlatan actually performs calculations
Калоян Калудов
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Калоян Калудов
module Charlatan
class << self
alias_method :trick, :instance_eval
def pick_from(range)
@test_cases = []
range.each { |number| @test_cases << TestCase.new(number) }
end
def multiply_by(number)
@test_cases.each { |test_case| test_case.do_operation :*, number }
end
def divide_by(number)
@test_cases.each { |test_case| test_case.do_operation :/, number }
end
def add(number)
@test_cases.each { |test_case| test_case.do_operation :+, number }
end
def subtract(number)
@test_cases.each { |test_case| test_case.do_operation :-, number }
end
def you_should_get(number)
@test_cases.all? { |test_case| test_case.do_operation :==, number }
end
end
private
class TestCase
attr_reader :result_so_far
def initialize(your_number)
@your_number = your_number
@result_so_far = your_number
end
def do_operation(operator, number)
if number == :your_number
@result_so_far = @result_so_far.public_send operator, @your_number
else
@result_so_far = @result_so_far.public_send operator, number
end
end
end
end
........

Finished in 0.00973 seconds
8 examples, 0 failures
Кристиан Ташков
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Кристиан Ташков
module Charlatan
class << self
def trick(&block)
trick_object = Trick.new
trick_object.instance_eval(&block)
end
end
end
class Trick
def initialize
@numbers = {}
end
def pick_from(range)
range.each { |number| @numbers[number] = number}
end
def add(number)
new_numbers = @numbers.map do |key, value|
[key, value + get_actual_number(number, key)]
end
@numbers = Hash[new_numbers]
end
def subtract(number)
new_numbers = @numbers.map do |key, value|
[key, value - get_actual_number(number, key)]
end
@numbers = Hash[new_numbers]
end
def multiply_by(number)
new_numbers = @numbers.map do |key, value|
[key, value * get_actual_number(number, key)]
end
@numbers = Hash[new_numbers]
end
def divide_by(number)
new_numbers = @numbers.map do |key, value|
[key, value / get_actual_number(number, key)]
end
@numbers = Hash[new_numbers]
end
def you_should_get(number)
@numbers.all? { |key, num| get_actual_number(number, key) == num }
end
def get_actual_number(number, key)
number == :your_number ? key : number
end
end
........

Finished in 0.00969 seconds
8 examples, 0 failures
Михаил Господинов
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Михаил Господинов
class CharlatanDSL
def initialize
@operations = []
end
def pick_from(range)
@domain = Hash[range.map {|number| [number,number]}]
end
def my_number_or_value(number,value)
value == :your_number ? number : value
end
def dsl_operation(value,operation_symbol)
@domain = @domain.merge(@domain) do |original_number, current_number|
input_number = my_number_or_value original_number, value
current_number.send operation_symbol, input_number
end
end
def add(value)
dsl_operation value, :+
end
def subtract(value)
dsl_operation value, :-
end
def multiply_by(value)
dsl_operation value, :*
end
def divide_by(value)
dsl_operation value, :/
end
def you_should_get(value)
@domain.all? do |original_number,current_number|
input_number = my_number_or_value original_number, value
current_number == input_number
end
end
def to_s
@domain.to_s
end
end
class Charlatan
def self.get_DSL
CharlatanDSL.new
end
def self.trick(&block)
get_DSL.instance_exec &block
end
end
........

Finished in 0.01017 seconds
8 examples, 0 failures
Красимира Божанова
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Красимира Божанова
class Charlatan
class << self
def trick(&block)
methods = { "multiply_by" => :*, "divide_by" => :/, "subtract" => :-, "add" => :+ }
methods.keys.each do |validate_method|
define_singleton_method("#{validate_method}") do |argument|
perform_operation(argument, methods["#{validate_method}"])
end
end
class_eval &block
end
def pick_from(range)
@@initial_choices = *range
@@modified_numbers = *range
end
def you_should_get(result)
@@modified_numbers.each_with_index.all? do |choice, index|
choice == initialize_number(result, index)
end
end
private
def initialize_number(argument, index)
argument == :your_number ? @@initial_choices[index] : argument
end
def perform_operation(argument, operation)
@@modified_numbers.map!.with_index do |choice, index|
choice.public_send operation, initialize_number(argument, index)
end
end
end
end
........

Finished in 0.0105 seconds
8 examples, 0 failures
Емануела Моллова
  • Некоректно
  • 6 успешни тест(а)
  • 2 неуспешни тест(а)
Емануела Моллова
module Charlatan
class Operators
def initialize()
@values = {}
@your_number
end
def execute(&block)
instance_eval(&block)
end
def pick_from(range)
@values[:pick_from] = range
end
def add(number)
set_operator(:+, number)
end
def multiply_by(number)
set_operator(:*, number)
end
def divide_by(number)
set_operator(:/, number)
end
def subtract(number)
set_operator(:-, number)
end
def you_should_get(number)
number = set_number(number)
if @your_number
@values[:current_value].first == number
else
@values[:current_value].all? { |x| x == number }
end
end
private
def set_number(number)
number == :your_number ? @your_number = @values[:pick_from].first : number
end
def set_operator(operator, number)
number = set_number(number)
@values[:current_value] ? key = :current_value : key = :pick_from
@values[:current_value] = @values[key].map { |x| x.send(operator, number) }
end
end
def self.trick(&block)
Operators.new.execute(&block)
end
end
F.....F.

Failures:

  1) Charlatan works without operations
     Failure/Error: you_should_get 1
     NoMethodError:
       undefined method `all?' for nil:NilClass
     # /tmp/d20140105-32545-1j4yxtb/solution.rb:37:in `you_should_get'
     # /tmp/d20140105-32545-1j4yxtb/spec.rb:5:in `block (3 levels) in <top (required)>'
     # /tmp/d20140105-32545-1j4yxtb/solution.rb:9:in `instance_eval'
     # /tmp/d20140105-32545-1j4yxtb/solution.rb:9:in `execute'
     # /tmp/d20140105-32545-1j4yxtb/solution.rb:55:in `trick'
     # /tmp/d20140105-32545-1j4yxtb/spec.rb:3:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

  2) Charlatan accepts :your_number as an argument to you_should_get
     Failure/Error: you_should_get :your_number
     NoMethodError:
       undefined method `first' for nil:NilClass
     # /tmp/d20140105-32545-1j4yxtb/solution.rb:35:in `you_should_get'
     # /tmp/d20140105-32545-1j4yxtb/spec.rb:52:in `block (3 levels) in <top (required)>'
     # /tmp/d20140105-32545-1j4yxtb/solution.rb:9:in `instance_eval'
     # /tmp/d20140105-32545-1j4yxtb/solution.rb:9:in `execute'
     # /tmp/d20140105-32545-1j4yxtb/solution.rb:55:in `trick'
     # /tmp/d20140105-32545-1j4yxtb/spec.rb:50:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

Finished in 0.00997 seconds
8 examples, 2 failures

Failed examples:

rspec /tmp/d20140105-32545-1j4yxtb/spec.rb:2 # Charlatan works without operations
rspec /tmp/d20140105-32545-1j4yxtb/spec.rb:49 # Charlatan accepts :your_number as an argument to you_should_get
Моника Димитрова
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Моника Димитрова
module Charlatan
def Charlatan.trick(&block)
block.call
end
end
class Object
def pick_from(range)
@@random_number = Random.rand(range)
@@current_number = @@random_number
end
def add(number)
if number == :your_number
@@current_number += @@random_number
else
@@current_number += number
end
end
def subtract(number)
if number == :your_number
@@current_number -= @@random_number
else
@@current_number -= number
end
end
def multiply_by(number)
if number == :your_number
@current_number *= @@random_number
else
@@current_number *= number
end
end
def divide_by(number)
if number == :your_number
@@current_number /= @@random_number
else
@@current_number /= number
end
end
def you_should_get(number)
if number == :your_number
@@current_number == @@random_number
else
@@current_number == number
end
end
end
........

Finished in 0.00962 seconds
8 examples, 0 failures
Валентин Ейткен
  • Некоректно
  • 3 успешни тест(а)
  • 5 неуспешни тест(а)
Валентин Ейткен
module Charlatan
def self.trick
yield
end
def pick_from(range)
@picked_value = range.first + rand(range.last - range.first)
@charlatan_value = @picked_value
end
def multiply_by(n)
@charlatan_value *= number_value(n)
end
def divide_by(n)
@charlatan_value /= number_value(n)
end
def subtract(n)
@charlatan_value -= number_value(n)
end
def add(n)
@charlatan_value += number_value(n)
end
def you_should_get(n)
@charlatan_value == number_value(n)
end
private
def number_value(n)
n == :your_number ? @picked_value : n
end
end
include Charlatan
FFFFF...

Failures:

  1) Charlatan works without operations
     Failure/Error: Charlatan.trick do
       expected: true value
            got: false
     # /tmp/d20140105-32545-158er48/spec.rb:3:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

  2) Charlatan performs addition
     Failure/Error: Charlatan.trick do
       expected: true value
            got: false
     # /tmp/d20140105-32545-158er48/spec.rb:10:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

  3) Charlatan performs substraction
     Failure/Error: Charlatan.trick do
       expected: true value
            got: false
     # /tmp/d20140105-32545-158er48/spec.rb:18:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

  4) Charlatan performs multiplication
     Failure/Error: Charlatan.trick do
       expected: true value
            got: false
     # /tmp/d20140105-32545-158er48/spec.rb:26:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

  5) Charlatan performs division
     Failure/Error: Charlatan.trick do
       expected: true value
            got: false
     # /tmp/d20140105-32545-158er48/spec.rb:34:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

Finished in 0.01026 seconds
8 examples, 5 failures

Failed examples:

rspec /tmp/d20140105-32545-158er48/spec.rb:2 # Charlatan works without operations
rspec /tmp/d20140105-32545-158er48/spec.rb:9 # Charlatan performs addition
rspec /tmp/d20140105-32545-158er48/spec.rb:17 # Charlatan performs substraction
rspec /tmp/d20140105-32545-158er48/spec.rb:25 # Charlatan performs multiplication
rspec /tmp/d20140105-32545-158er48/spec.rb:33 # Charlatan performs division
Давид Петров
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Давид Петров
class Charlatan
def self.trick(&block)
queries = Query.new(&block)
operations = queries.operations[1..-2]
hash = {:add => :+, :subtract => :-, :multiply_by => :* , :divide_by => :/ }
queries.operations[0][1].all? do |x|
expected = queries.operations[-1][1]
expected = x if expected == :your_number
result = x
operations.each do |a|
a[1]==:your_number ? result = result.send(hash[a[0]], x) : result = result.send(hash[a[0]], a[1])
end
expected == result
end
end
end
class Query
attr_accessor :operations
def self.setter(*method_names)
method_names.each do |name|
send :define_method, name do |data|
instance_variable_set "@#{name}".to_sym, data
@operations<<[name, data]
end
end
end
setter :pick_from, :add, :subtract, :multiply_by, :divide_by, :you_should_get
def initialize(&block)
@operations=[]
@pick_from = 1..1
@add = 0
@subtract = 0
@multiply_by = 1
@divide_by = 1
@you_should_get = 1
instance_eval(&block)
end
end
........

Finished in 0.01245 seconds
8 examples, 0 failures
Димитър Бонев
  • Коректно
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)
Димитър Бонев
module Charlatan
def self.trick(&steps)
Trick.new.instance_exec &steps
end
class Trick
def initialize
@operations = []
end
def pick_from(range)
@pick_range = range
end
def add(amount)
@operations.push ->() { @current_result += to_number amount }
end
def subtract(amount)
@operations.push ->() { @current_result -= to_number amount }
end
def multiply_by(multiplier)
@operations.push ->() { @current_result *= to_number multiplier }
end
def divide_by(divisor)
@operations.push ->() { @current_result /= to_number divisor }
end
def you_should_get(expected)
@pick_range.all? do |picked|
@picked_number = picked
@current_result = picked
@operations.each { |op| op.call }
@current_result == to_number(expected)
end
end
def to_number(arg)
if arg == :your_number
@picked_number
else
arg
end
end
end
end
........

Finished in 0.00964 seconds
8 examples, 0 failures
Никола Ненков
  • Некоректно
  • 7 успешни тест(а)
  • 1 неуспешни тест(а)
Никола Ненков
class Charlatan
class << self
def trick(&block)
instance_eval(&block)
end
def pick_from(range)
@@current_result = range.to_a
end
def add(number)
@@current_result.map! { |current_value| current_value + number_value(number, current_value) }
end
def subtract(number)
@@current_result.map! { |current_value| current_value - number_value(number, current_value) }
end
def multiply_by(number)
@@current_result.map! { |current_value| current_value * number_value(number, current_value) }
end
def divide_by(number)
@@current_result.map! { |current_value| current_value / number_value(number, current_value) }
end
def you_should_get(number)
@@current_result.all? { |value| value == number_value(number, value) }
end
private
def number_value(given_number, current_value)
given_number == :your_number ? current_value : given_number
end
end
end
.......F

Failures:

  1) Charlatan actually performs calculations
     Failure/Error: Charlatan.trick do
       expected: true value
            got: false
     # /tmp/d20140105-32545-1y39hg6/spec.rb:57:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

Finished in 0.00985 seconds
8 examples, 1 failure

Failed examples:

rspec /tmp/d20140105-32545-1y39hg6/spec.rb:56 # Charlatan actually performs calculations