【问题标题】:Generating an array in java from percentage在java中从百分比生成一个数组
【发布时间】:2019-07-02 23:50:33
【问题描述】:

我在这里遇到了关于编码逻辑的问题。我必须根据百分比生成一个布尔数组。

为了澄清,我得到了一个百分比“X”(整数值),我想生成一个布尔数组,它由 ox X 的百分比组成,随机分布。而且数组的长度是不变的。

例如,我想生成我的布尔数组,基于 X=40,我会:

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

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

谢谢你:)

【问题讨论】:

  • 您可以先创建空槽,然后生成真实物品的数量,然后将物品一个一个随机放置到当前可用的空槽中。这种方式可能更容易实现。
  • 用连续的零和一填充一个数组,然后执行random shuffling
  • @PM77-1,我认为您的评论先于我的回答。如果你想做你的回答,请告诉我,我会删除我的。
  • @MikeSamuel - 我不想提供代码。这就是我发表评论的原因。请保留你的答案。

标签: java arrays methods percentage


【解决方案1】:

Random shuffling of an array 解释如何洗牌。

// Create an array.  Initially elements are zero
int[] arr = new int[n];
// Put the right number of 1's in it
double limit = n * (X / 100.0);
for (int i = 0; i < limit; ++i) {  // Assumes X <= 100
  arr[i] = 1;
}
// Randomize the order of elements.
shuffleArr(arr);

【讨论】:

    【解决方案2】:

    您可以使用(Math.random() &lt; percentage)获取 falsetrue 具有所需的概率。

    double percentage = 0.4; // use 0.0 <= percentage <= 1.0
    boolean[] array = new boolean[100];
    for (int i = 0; i < array.length; i++) {
        array[i] = (Math.random() < percentage);
    }
    

    【讨论】:

    • 通过这种方法(+1)(不仅是位置,还有)count resp。 百分比设置位是随机的(因此不准确/受波动影响)。
    【解决方案3】:

    这里有一个适合你的方法:

    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]
    

    【讨论】:

      【解决方案4】:

      考虑一个实用函数,我认为它在许多用例中很方便,例如:

      // Bases on {@link java.util.Random#ints(int, int)}, but "with uniqueness and limit".
      static IntStream uniqueInts(int min, int max, int count, java.util.Random rnd) {
          // check parameters ... (max > min), (max - min > count), (rnd != null...)
          // call Random.ints(min, max) with distinct and limit
          return rnd.ints(min, max).distinct().limit(count);
      }
      

      ,然后应用到您的案例...再次使用 BitSet,因为我讨厌“每个 boolean 浪费 7 位”的事实:

      static BitSet randomBits(int total, int goodPercent, Random rand) {
          final BitSet bitSet = new BitSet(total);
          uniqueInts(0, total,  total * goodPercent / 100, rand)
              .forEach(i -> {
                  bitSet.set(i);
              });
          // bitsSet.cardinality() == total * goodPercent / 100 (!)
          return bitSet;
      }
      

      ..最后(打印和主要方法):

      static void printBits(int length, BitSet bs, PrintStream out) {
          int i = 0;
          out.append('[');
          for (; i < bs.length(); i++) {
              out.append(bs.get(i) ? '1' : '0');
          }
          // fill with zeros (according to BitSet.length() definition...
          // and provide parameter, since BitSet lacks this information).
          for (; i < length; i++) {
              out.append('0');
          }
          out.append(']');
          out.println();
      }
      
      public static void main(String[] args) {
          int total = 20;
          int goodPercent = 40;
          Random rand = new Random();
          // repeat it total times, to make a nice square
          for (int i = 0; i < total; i++) {
              BitSet test = randomBits(total, goodPercent, rand);
              printBits(total, test, System.out);
          }
      }
      

      输出:

      [01100011011001010000]
      [01100000000101011110]
      [00000101101110001001]
      [01001001000110100110]
      [01001110100001110000]
      [00100110011100000011]
      [01011100001011001000]
      [00000011101101100010]
      [11101000110000010010]
      [01010100100011011000]
      [10000101100010001101]
      [00100001110010110001]
      [01100000010111100001]
      [10000001110101000110]
      [00001010011010100011]
      [01101000001110100001]
      [01000100110000101101]
      [00110000001010011110]
      [10011011100000000011]
      [01011000010111000100]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-02-09
        • 2016-09-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多