NoName
NoName

Reputation: 9

Java: Using percentages to fill 2D array?

I have a 2D array and I need to fill it with something with specific percentages, for example fill it with the letter A 15% of the time, B 35% of the time and C 50% of the time. How would I do this?

    int array[][] = new array[10][10]

    for(int row=0; x<array.length;row++)
    {
      for(int col=0; col<array[0].length; col++)
         {
              array[row][col]=      //Fill 15% A, 35% B, 50% C,  

         }

    } 

Upvotes: 0

Views: 422

Answers (1)

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51553

Your int[][] array isn't going to hold Strings.

Here's one way to get a String[][] array with the A, B, and C frequencies you want.

[C, B, A, C, C, C, B, B, B, C]
[C, C, A, A, C, B, C, B, B, B]
[B, A, C, C, C, C, C, B, B, C]
[B, B, A, C, C, C, C, C, B, C]
[A, C, B, C, A, A, C, C, B, B]
[A, A, C, C, B, C, C, B, C, C]
[C, B, C, C, B, C, B, C, B, A]
[C, C, C, B, B, B, B, C, B, A]
[B, A, C, B, C, C, C, B, B, B]
[C, C, A, B, B, C, A, C, C, C]

And here's the code.

package com.ggl.testing;

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

public class ArrayShuffle {

    public static void main(String[] args) {
        ArrayShuffle arrayShuffle = new ArrayShuffle();

        String[][] array = arrayShuffle.createArray();
        for (int i = 0; i < array.length; i++) {
            System.out.println(Arrays.toString(array[i]));
        }
    }

    public String[][] createArray() {
        int a = 15;
        int b = 35;
        int c = 50;

        int length = a + b + c;

        List<String> list = new ArrayList<>(length);
        addString(list, a, "A");
        addString(list, b, "B");
        addString(list, c, "C");

        Collections.shuffle(list);

        return copyListToArray(list);
    }

    private void addString(List<String> list, int a, String s) {
        for (int i = 0; i < a; i++) {
            list.add(s);
        }
    }

    private String[][] copyListToArray(List<String> list) {
        String[][] array = new String[10][10];

        int k = 0;
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                array[i][j] = list.get(k++);
            }
        }
        return array;
    }

}

Upvotes: 1

Related Questions