[There is no Spoon] Solution for There is no Spoon puzzle#7
[There is no Spoon] Solution for There is no Spoon puzzle#7Slavunderkind wants to merge 2 commits intomasterfrom
Conversation
b8e5d88 to
73f6435
Compare
| STDOUT.sync = true # DO NOT REMOVE | ||
| # Solution for https://www.codingame.com/ide/puzzle/there-is-no-spoon-episode-1 | ||
| class Spoon | ||
| attr_accessor :width, :height, :nodes |
There was a problem hiding this comment.
You don't need accessors if you're not setting these either outside of the class, or by the use of self
| attr_accessor :width, :height, :nodes | ||
|
|
||
| def initialize | ||
| @width = gets.to_i # the number of cells on the X axis |
There was a problem hiding this comment.
Extract the gets statements outside of the method and give them as arguments to initialize
| def init_nodes | ||
| n = 0 | ||
| height.times do | ||
| line = gets.chomp # width characters, each either 0 or . |
There was a problem hiding this comment.
Leave the gets outside of the class
| chars.each_char.with_index do |char, i| | ||
| next if char == '.' | ||
|
|
||
| nodes.push([i, n]) |
There was a problem hiding this comment.
A shorter version of push is the << operator
| end | ||
|
|
||
| def find_right_node(node) | ||
| nodes.select { |n| n if n[1] == node[1] && n[0] > node[0] }.min |
There was a problem hiding this comment.
The way to use select is a little different - it expects a true/false statement. Meaning that you don't have to write if inside it.
So instead of
array.select { |n| n if some_condition(n) }
you should just write
array.select { |n| some_condition(n) }
| end | ||
|
|
||
| def find_bottom_node(node) | ||
| nodes.select { |n| n if n[0] == node[0] && n[1] > node[1] }.min |
There was a problem hiding this comment.
Same comment as in find_right_node
|
|
||
| def start | ||
| nodes.each do |node| | ||
| result = "#{node[0]} #{node[1]}" |
There was a problem hiding this comment.
A single node is a pair of [x, y]. In order to obtain a string with a whitespace of the two elements, you can use
result = node.join(' ')
| nodes.select { |n| n if n[0] == node[0] && n[1] > node[1] }.min | ||
| end | ||
|
|
||
| def add_coordinates(result) |
There was a problem hiding this comment.
Do not rely on add_coordinates to add the whitespace. Think of a way to take that logic out of that method, so that the method only returns the pair of coordinates without whitespace
|
|
||
| def add_coordinates(result) | ||
| if result.nil? | ||
| ' -1 -1' |
There was a problem hiding this comment.
Try to use an array to hold coordinates instead of a string
| result = "#{node[0]} #{node[1]}" | ||
| result += add_coordinates(find_right_node(node)) | ||
| result += add_coordinates(find_bottom_node(node)) | ||
| puts result |
There was a problem hiding this comment.
Take the puts outside of the class
e0ecd7c to
df48138
Compare
Refactor init_nodes method and remove find_node method Changes on start method
No description provided.