如何生成对相似数字和10的幂次有限制的随机数 [英] How to generate random numbers with restrictions on like numbers and powers of ten

查看:49
本文介绍了如何生成对相似数字和10的幂次有限制的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

We need to generate random numbers within a certain digit range with few restrictions 
e.g. For double digit range 11 - 99, the resultant output should not include all like numbers [11,22,33,44,...99] and multiples of 10 [20,30,40....90]

The resultant output should be [12,13,14,15,16,17,18,19,21,23,...98]

注意:此功能也应无缝适用于其他数字范围(例如3个数字范围(跨度101-999)和4个数字范围(跨度1001-9999))

Note: This function should work seamlessly for other digit ranges also (e.g. 3 digit ranges spanning 101 - 999 and four digit ranges spanning 1001 - 9999)

我们很难识别类似的数字(例如11、22、33、44、55、66、77、88、99、111、222、333,....,3333 ...)

We are having difficulties in identifying like numbers (e.g 11, 22, 33, 44, 55, 66, 77, 88, 99, 111, 222, 333, ...., 3333 ...)

protected static List<Integer> fetchRandIntegers(int min, int max, int howMany, boolean randomize) {

    // We need to reverse minimum, maximum values for negative ranges
    if (min > max) {
        int tmp = min;
        min = max;
        max = tmp;
    }

    List<Integer> allNumbers = new ArrayList<Integer>();
    for (int i = min; i <= max; i++) {
        allNumbers.add(i);
    }

    if (randomize) {
    ...
    }

    return allNumbers;

}

推荐答案

确定整数 i 是否所有数字都相同:

To identify if integer i has all digits the same:

  • i 转换为 string 并比较字符,或者
  • 反复取模并除以10,然后检查所有模数是否相同
  • Convert i to string and compare the characters, or
  • Repeatedly modulo and divide by 10 and check if all modulos are the same

类似:

public boolean hasAllDigitsSame (int i)
{
    int a = i ;
    int m = a % 10 ;
    int mm = m ;
    while(a > 0)
    {
        m = a % 10;
        if (m != mm)
          return False ;
        a /= 10 ;
    }
    return True ;
 }

确定整数 i 是否为 10 (100,1000)的倍数:

To identify if integer i is a multiple of 10 (100, 1000):

  • 检查 i模10 是否为 0 .

这篇关于如何生成对相似数字和10的幂次有限制的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆