【问题标题】:Android: How to generate unique random numbers in an array and perform bubble sort?Android:如何在数组中生成唯一的随机数并执行冒泡排序?
【发布时间】:2016-05-31 16:18:39
【问题描述】:

以下是我的代码,但它不会生成唯一的随机数

Random rand = new Random();

int[] array = new int[n];

for (int i = 0; i < n; i++){
    array[i] = rand.nextInt(n)+1;
}


for (int i = 0; i < ( n - 1 ); i++)
{
    for (int j = 0; j < n - i - 1; j++) {
        if (array[j] > array[j+1]){
            int temp = array[j];
            array[j]   = array[j+1];
            array[j+1] = temp;
        }
    }
}

【问题讨论】:

  • 它会产生什么?
  • 你为什么要做冒泡排序?
  • n 永远不会被初始化

标签: android sorting random unique


【解决方案1】:
public TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv=(TextView)findViewById(R.id.textView);

    Random r = new Random();

    StringBuffer temp =new StringBuffer("Random numbers:");
    for(int i=0;i<10;i++) {
        int i1 = r.nextInt(100 - 0) + 0;

        temp.append(String.valueOf(i1));
        temp.append(String.valueOf(" "));
    }
    tv.setText(temp.toString());
}
//here ,,I generate 10 random numbers and save it in to stringBuffer and dispaly it in to textView..here range is up to 0 to 100...you can take your own Range ...I hope ,,It will help you...

【讨论】:

  • 我把这行代码换成了array[i] = rand.nextInt(n)+1;与
  • 我把这行代码换成了array[i] = rand.nextInt(n)+1;数组[i]=rand.nextInt(100 - 0) + 0;但它仍然会产生重复的数字
  • @Madhav Gor 你对如何洗牌数组元素有任何想法吗?示例数组依次包含数字 1 到 100,我打乱然后执行排序操作。
  • 你想随机填充这些数字吗??@Sonika
  • 制作一个 100 的数组并执行 while 循环 .in while 循环检查生成的数字在数组中是否可用..如果不可用,则添加该数字,否则生成另一个随机数..@Sonika
【解决方案2】:

看看这个!...它对我有用

Random rand = new Random();

int n = 10;
int[] array = new int[n];

for (int i = 0; i < n; i++){
    array[i] = (int) (rand.nextDouble() * n + 1);
}


for (int i = 0; i < ( n - 1 ); i++)
{
    for (int j = 0; j < n - i - 1; j++) {
        if (array[j] > array[j+1]){
            int temp = array[j];
            array[j]   = array[j+1];
            array[j+1] = temp;
        }
    }
}

for (int piece: array) {
  System.out.println(piece);
}

【讨论】:

  • 当我显示已排序的数组其生成的重复数字时,它没有解决。以下代码用于在文本视图中显示数组。
  • for(int i=0;i
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-06
相关资源
最近更新 更多