You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求实现指定数值映射的Java优雅函数(无需if判断)

Elegant Solutions for Your Number Mapping Problem

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=1 to 5: Integer division i/6 equals 0, so the formula simplifies to 6 - i—perfectly matching your first five mappings (1→5, 2→4, etc.).
  • For i=6 and 7: i/6 equals 1 (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:05:15