Most efficient/elegant way to clip a number?

What about boring, old, readable, and shortest yet: float clip(float n, float lower, float upper) { return std::max(lower, std::min(n, upper)); } ? This expression could also be ‘genericized’ like so: template <typename T> T clip(const T& n, const T& lower, const T& upper) { return std::max(lower, std::min(n, upper)); } Update Billy ONeal added: Note that … Read more

Incrementor logic

Quoting Java Language Specification, 15.7 Evaluation Order: The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right. The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated. If the operator … Read more

Solving “Who owns the Zebra” programmatically?

Here’s a solution in Python based on constraint-programming: from constraint import AllDifferentConstraint, InSetConstraint, Problem # variables colors = “blue red green white yellow”.split() nationalities = “Norwegian German Dane Swede English”.split() pets = “birds dog cats horse zebra”.split() drinks = “tea coffee milk beer water”.split() cigarettes = “Blend, Prince, Blue Master, Dunhill, Pall Mall”.split(“, “) # … Read more