Bracket Packing (#78) (2 solutions)

Here is my solution to the first option of the quiz, which is simply
to detect if there is a problem. It makes use of the allowed
assumption that only one packaging character would be omitted in
incorrect input. So the underlying algorithm is to make sure there
are an even number of combined "("s and ")"s (and the same goes for
the other two types of packaging). The String#count method does much
of the heavy lifting.

["()", “{}”, “[]”].each { |symbol_pair| exit(1) if 0 != ARGV[0].count
(symbol_pair) % 2 }
puts ARGV[0]

Here’s another solution which repeatedly substitutes any of “(B)”,
“[B]”, “{B}”, or “BB” with “B”. In other words it just unwraps and
combines brackets. When all is said an done, one bracket should be
left if the wrapping description was correct.

description = ARGV[0].dup
while description.gsub!(/(B)|[B]|{B}|BB/, “B”)
#empty
end
exit(1) unless description == “B”
puts ARGV[0]

Eric

On May 7, 2006, at 1:36 PM, Eric I. wrote:

[0].count(symbol_pair) % 2 }
puts ARGV[0]

Just thinking out loud here, but how does this fair with inputs like:

“)B(” or “B()”

?

James Edward G. II

Huhu James,
I think “)B(” or “B()” are not valid outputs, because the program only
misses off brackets.

“Now, the problem is that this venerable program has for some reason
begun to output malformed packaging descriptions, occasionally missing
off a bracket”

Please tell me if I misinterpreted the machine.

Kind regards.
Robert

James Edward G. II schrieb:

On May 11, 2006, at 12:13 PM, Robert R. wrote:

Huhu James,
I think “)B(” or “B()” are not valid outputs, because the program only
misses off brackets.

“Now, the problem is that this venerable program has for some reason
begun to output malformed packaging descriptions, occasionally missing
off a bracket”

Please tell me if I misinterpreted the machine.

Right. I think that’s pretty much what everyone agreed on.

James Edward G. II