zoukankan      html  css  js  c++  java
  • 生成指定范围不重复的随机数

    题目:生成1-10范围中任意5个随机数。

    方法一:不使用容器

     1 package com.study.pratice03;
    2
    3 import java.util.Random;
    4
    5 public class MyRandom
    6 {
    7
    8 public static void main(String[] args)
    9 {
    10 // TODO Auto-generated method stub
    11 int[] randArray = new int[5];
    12 int randInt = 0;// 产生的随机数
    13 int count = 0;// 产生合格随机数的个数
    14 boolean flag = false;// 标记产生的随机数是否重复
    15 Random rand = new Random();
    16 while (count < 5)
    17 {
    18 randInt = rand.nextInt(11);
    19 for (int i = 0; i < count; i++)
    20 {
    21 if (randArray[i] == randInt)
    22 {
    23 flag = true;
    24 break;
    25 }
    26 else
    27 {
    28 flag = false;
    29 }
    30 }
    31 if (!flag && randInt != 0)
    32 {
    33 randArray[count++] = randInt;
    34 }
    35 }
    36 for (int x : randArray)
    37 System.out.println(x);
    38
    39 }
    40
    41 }

    方法二:使用容器

    View Code
     1 package com.study.pratice03;
    2
    3 import java.util.ArrayList;
    4 import java.util.List;
    5 import java.util.Random;
    6
    7 public class SetRandom
    8 {
    9
    10 public static void main(String[] args)
    11 {
    12 // TODO Auto-generated method stub
    13 List<Integer> list = new ArrayList<Integer>();
    14 Random rd = new Random();
    15 int count = 0;
    16 while (count < 5)
    17 {
    18 int randInt = rd.nextInt(11);
    19 if (randInt != 0 && !list.contains(randInt))
    20 {
    21 list.add(randInt);
    22 count++;
    23 }
    24 }
    25 for (Integer inte : list)
    26 System.out.println(inte);
    27 }
    28 }




  • 相关阅读:
    洛谷 P1233 木棍加工
    洛谷 P3378 【模板】堆(小根堆)
    leetcode难度及面试频率
    设计模式大全
    多线程经典面试题
    查找子字符串----KMP算法深入剖析
    线程与进程的区别
    海量数据面试题----分而治之/hash映射 + hash统计 + 堆/快速/归并排序
    解析STL中典型的内存分配
    C++ 常量类型 const 详解
  • 原文地址:https://www.cnblogs.com/xiongyu/p/2266500.html
Copyright © 2011-2022 走看看