Problem 57735. Easy Sequences 98: One-line Code Challenge - Ternary Operator Function
Ternary operation is a standard construct in most computer languages. The ternary operator assigns value to a variable depending on the result of the condition. For example, we find the following syntax in C and many C-like languages:
which means that y is assigned the value of either m or n, depending on whether the statement (p > q) is true or false, respectively.
Unfortunately, Matlab does not have a ternary operator and if we need to get the same effect, we may write the statement this way:
But that is 5 lines of Matlab code versus just a single line in C!
In this problem we are required create the function ternaryFunc, which takes on the following parameters: data values a and b; a conditional function C, that outputs true or false, and functions T and F which are applied to a and b, depending on the value of C(a,b). We can write the function as follows:
NOTE: The following restrictions apply:
- The function should only have one (1) line of code, excluding the function start line.
- Semicolons (;) are considered end-of-line characters.
- Use of if, while and switch statements is not allowed.
- Regular expressions and string manipulation are not allowed.
- Use of variable length arguments is not allowed.
HINT: As an exercise you may want to first solve Problem #44243.
Solution CommentsShow comments
Problem Recent Solvers5