将一系列正整数映射到索引范围

时间:2014-06-10 10:19:49

标签: java math mapping

基本上,我需要的是某种映射函数,它应该将整数(0 - N)映射到索引(0 - M)。对于N = 10,M = 3,函数应映射: 1 - > 0 ,2 - > 1 ,3 - > 2 ,4 - > 3 ,5 - > 0 ,6 - > 1 ,7 - > 2 ,8 - > 3 ,9 - > 0 和10 - >的 1 即可。

我的大脑已经死了,所以我最终得到了一些公牛*& ^%映射:)

public int getIndexForNumber(int number, int maxIndex) {
    int max = maxIndex;
    while (maxIndex > 0) {
        if (number % maxIndex-- == 0) {
            return maxIndex;
        }
    }
    return max;
}

有人可以指导我吗?

2 个答案:

答案 0 :(得分:1)

为什么不只返回余数

public int getIndexForNumber(int number, int maxIndex) {
  return (number - 1) % maxIndex; 
}

如果允许否定号码

public int getIndexForNumber(int number, int maxIndex) {
  int x = (number - 1) % maxIndex; 

  if (x < 0)
    x += maxIndex;

  retrun x; 
}

答案 1 :(得分:0)

映射函数中有一个模式,即数字n映射到(n-1)mod(m + 1)。使用此功能,您可以将函数编写为:

public int getIndexForNumber(int number, int maxIndex) {
    return (number - 1) % (maxIndex + 1);
}