从百分比生成Java中的数组 [英] Generating an array in java from percentage

查看:94
本文介绍了从百分比生成Java中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这里有一个关于编码逻辑的问题.我必须根据百分比生成一个布尔数组.

I have an issue about coding logic here. I have to generate an array of Boolean, based on percentage.

为澄清起见,我得到了一个百分比"X"(int值),并且我想生成一个布尔数组,该数组由X的1个百分数组成,它们是随机分布的.而且,数组的长度是恒定的.

To clarify, I got a percentage 'X' (int value) and I want to generate a array of Boolean which is composed ox X percents of 1, randomly distributed. Moreover, the length of the array is constant.

例如,我想基于X = 40生成布尔数组,我将拥有:

For example, I I want to generate my array of Boolean, based on X=40, I would have:

[0,1,0,1,0,0,0,0,1,1,0,0,1,0,0,1,1,0,1,0]

我没有找到任何简单的解决方案或现有函数来生成此数组.有人可以帮我这个忙吗?

I did not managed to find any easy solution or an existing function to generate this array. Mays someone can help me about this?

谢谢:)

推荐答案

以下是为您提供的一种方法:

Here is an approach for you:

import java.util.Arrays;
import java.util.Collections;
import java.util.List;    

public class RandomizeArray {    

    public static void main(String args[]) {
        Boolean[] myArray = new Boolean[40];
        int xPercentage = 40;
        int ratio = myArray.length * xPercentage / 100;

        Arrays.fill(myArray, Boolean.FALSE);

        for(int i = 0; i<ratio; i++) {
            myArray[i] = true;
        }

        List<Boolean> l = Arrays.asList(myArray);
        Collections.shuffle(l);

        System.out.println(l);

    }    

}

输出:

[false, false, false, false, true, true, true, false, false, false, true, false, false, true, false, true, true, true, false, false, true, false, false, true, false, false, true, true, false, true, false, false, false, false, true, false, true, false, false, true]

[false, false, true, false, false, false, true, false, true, true, false, false, false, false, false, true, true, true, false, false, false, true, false, false, true, true, true, false, false, false, false, true, true, false, false, true, false, true, false, true]

这篇关于从百分比生成Java中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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