Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding IF in a simple mapping function

Tags:

c++

function

r

ruby

I'm trying to avoid an IF in the following mapping function:

 X  Y
 1  11
 2  10
 3  9
 4  8
 5  7
 6  6
 7  5
 8  4
 9  3
10  2
11  1
12  12

It's basically Y = (12 - X), except when X = 12. In this case, Y = 12.

The Y vector is the reverse of the X vector shifted by one position. Is there a way to write this function using min and max or something like this in order to avoid a conditional?

  • I'm not attached to any programming language here
like image 568
João Daniel Avatar asked Jan 18 '26 14:01

João Daniel


1 Answers

y = 12 - x%12;

works for all x from 1 to 12 inclusive. % is the C-style modulus operator, giving the remainder from dividing x by 12. That's zero if x is 12, and x for 1 to 11.

like image 57
Mike Seymour Avatar answered Jan 21 '26 05:01

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!