Archive for the 'RPCFN: Challenge #4' Category


Ruby**Fun, part 1

This fourth challenge looks like a fun one. It’s the kind that is pretty simple, but you know a super elegant solution exists. I wouldn’t be surprised if there was a pretty simple one-liner for this. I’m excited to give this a try:

You just started working for CoolNewCompany which is developing mathematics related software. Since you are new to the team, your boss gives you an easy task to test your abilities. Write a class that pretty-prints polynomials, following some simple rules:

  • if a coefficient is 1, it doesn’t get printed
  • if a coefficient is negative, you have to display something like “- 2x^3″, not “+ -2x^3″
  • if a coefficient is 0, nothing gets added to the output
  • for x^1 the ^1 part gets omitted
  • x^0 == 1, so we don’t need to display it

Here’s a couple of usage examples:

puts[-3,-4,1,0,6]) # => -3x^4-4x^3+x^2+6
puts[1,0,2]) # => x^2+2

Don’t concern yourself too much with error handling, but if somebody tries to create a polynomial with less than 2 elements, your program has to raise an ArgumentError with the message “Need at least 2 coefficients.”

Please check the provided unit tests for more examples and make sure to use them for verifying your solution!

Requirements: This has to be a pure Ruby script, using only the Ruby Standard Libraries (meaning, no external Gems). You do not need to build a gem for this. Pure Ruby code is all that is needed.

This seems like a fun time to use RSpec so I’ll go ahead and make the first test:

it “should create a polynomial object”

This is simple, you just make a new class, run spec and it passes! Let’s make the next test do something that requires code:

it “should throw an ArgumentError if there are less than 2 elements in creation”

Again, this is straightforward, expect an argument with len > 2. This is where I really like Ruby’s syntax of

do this if this. It makes everything look super clean. Great, it passes two tests! On to the third:

it “should ‘puts’ the correct term for each value”

This is where it gets tricky, it’s so easy to just brute force it, but I’m trying to learn the proper “Rubyist” format.

It’s late though and I’m off to bed. Until next time!


How often I post

July 2017
« Dec    

This is everything