Forum: Ruby Bracket Packing (#78) (2 solutions)

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Eric I. (Guest)
on 2006-05-07 22:38
(Received via mailing list)
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
James G. (Guest)
on 2006-05-08 01:28
(Received via mailing list)
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
Robert R. (Guest)
on 2006-05-11 21:16
(Received via mailing list)
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:
James G. (Guest)
on 2006-05-11 21:25
(Received via mailing list)
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
This topic is locked and can not be replied to.