求实现指定数值映射的Java优雅函数(无需if判断)
Nice catch on that tricky edge case with i=6! Your initial modulo approach was close, but it missed the swap between 6 and 7. Let's fix this without any messy if blocks—here are two clean, efficient ways to implement the mapping:
1. Pure Mathematical Expression (No Conditionals)
This uses integer division to handle the two mapping patterns in one line:
int result = 6 - i + 7 * (i / 6);
How it works:
- For
i=1to5: Integer divisioni/6equals0, so the formula simplifies to6 - i—perfectly matching your first five mappings (1→5, 2→4, etc.). - For
i=6and7:i/6equals1(since integer division truncates towards zero), so we add 7 to the base formula. This gives us:6 - 6 + 7 = 7(correct for i=6)6 - 7 + 7 = 6(correct for i=7)
2. Concise Ternary Operator (High Readability)
If you prefer something more intuitive at a glance, this ternary version makes the two mapping rules explicit:
int result = i <= 5 ? 6 - i : 13 - i;
How it works:
- For values 1-5, we use
6 - i(since each pairs with a number that adds up to 6). - For 6 and 7, we use
13 - i(since 6+7=13, swapping the two values).
Full Test Code Implementation
Drop either of these into your test loop, and it'll pass seamlessly:
StringBuilder stb = new StringBuilder(); String expected = "1=5; 2=4; 3=3; 4=2; 5=1; 6=7; 7=6; "; for (int i=1; i<8; i++) { // Pick either line below int result = 6 - i + 7 * (i / 6); // int result = i <=5 ? 6 -i : 13 -i; stb.append(i+"="+result+"; "); } assertEquals(expected, stb.toString());
The issue with your original 6 - i%7 was that it only accounted for the first five mappings—this approach didn't account for the 6↔7 swap, which follows a different pattern. Both solutions above neatly merge both patterns without any clunky conditional blocks.
内容的提问来源于stack exchange,提问作者Mister Vanderbilt

