0

I am new to Ruby and I am using ruby monk to improve my knowledge. There is one solution of a problem that I dont understand. the task is: Given a 3 or 4 digit number with distinct digits, return a sorted array of all the unique numbers that can be formed with those digits. I dont understand how number of combinations was calculated. Here is the code:

no_of_combinations = number.to_s.size == 3 ? 6 : 24

Please explain to me what is 3 ? 6 : 24 and how it works. Thank you

3
  • It’s read as (number.to_s.size == 3) ? 6 : 24 and is an expression using the conditional operator.
    – Ry-
    Sep 11, 2014 at 23:40
  • I really don't understand why people use the conditional operator in Ruby. What's wrong with no_of_combinations = if number.to_s.size == 3 then 6 else 24 end? Sep 12, 2014 at 0:29
  • Those are permutations, not combinations. Given three distinct digits (i.e., from a particular 3-digit number), there are three ways to select the hundreds digit, and for each of those, two ways to choose the tens digit, and for each pair of the the first two digits, just one way to select the ones digit. Hence, there are 3x2x1 = 3! = 6 permutations of the three digits. Similarly, there are 4x3x2x1 = 4! = 24 4-digit numbers that can be constructed from four distinct digits. Sep 12, 2014 at 0:49

2 Answers 2

0

The operation with the ternary operator ?: (takes 3 argument: condition ? if_cond_true : if_cond_not_true) is equivalent to:

no_of_combinations = if(number.to_s.size == 3)
                       6
                     else
                      24
                     end

6==3! #number of permutations of 3 distinct elements/digits

24==4! #number of permutations of 4 distinct elements/digits

Where ! denotes factorial (4!==4×3×2×1).

4
  • thank you, it is much clearer to me now. I just wonder why the solution covers only options of input with 3 and 4 digit numbers Sep 12, 2014 at 0:08
  • lol..never mind. It is in the description of a problem. Thanks again Sep 12, 2014 at 0:14
  • You're welcome. Also, feel free to check out this really cool SO feature of thanking by clicking the accept button right next to the answer. ;) Sep 12, 2014 at 0:39
  • 1
    LOL @PSkocik, you should have also mentioned the extra thanks provided by clicking the up arrow. Sep 12, 2014 at 0:44
0

This is a ternary operation in ruby. Its read as:

if(number.size isEqaul to 3)
    no_of_combinations equals 6

else
    no_of_combinations equals 24 

Think of it like this:

if_this_is_true  ?  then_do_this  :  else_do_this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.