• 生成给定范围的n随机整数


    python:

    1 import random
    2 
    3 def randomMore(min,max,n):
    4     res = []
    5     while len(res) != n:
    6         num = random.randrange(min,max)
    7         if num not in res:
    8             res.append(num)
    9     print(res)
    View Code

    java:

     1 import java.util.ArrayList;
     2 import java.util.List;
     3 import java.util.Random;
     4 /**
     5         *  1. 实现一个函数,生成给定范围[min, max]内的n个随机正整数,入参为(min,max,n),且要求输出的n个正整数不重复;
     6         *  2. 为这个函数编写一下测试用例,比如(1,100,10),(1,100,100)
     7         */
     8 public class randomDef {
     9     //TODO
    10     public List getRandom(int min, int max, int n){
    11         List list = new ArrayList();
    12         Random random = new Random();
    13         while (list.size() != n){
    14             int s = random.nextInt(max)%(max-min+1) + min;
    15             if(!list.contains(s)){
    16                 list.add(s);
    17             }
    18         }
    19         return list;
    20     }
    21 
    22     public static void main(String [] args){
    23         randomDef list = new randomDef();
    24         List l = list.getRandom(2,200,10);
    25         System.out.print(l);
    26     }
    27 }
    View Code
  • 相关阅读:
    诸暨集训游记
    P2678 跳石头
    P1577 切绳子
    P1328 生活大爆炸版石头剪刀布
    P1067 多项式输出
    分解因数
    【管理篇】团队组织与架构演进方法论
    【状态机】行为状体机和协议状态机
    【数据库】分库分表
    【OLAP】从数仓到Kappa架构
  • 原文地址:https://www.cnblogs.com/whycai/p/14678924.html
Copyright © 2020-2023  润新知