Generating objects with a certain value within a defined distribution

Asked

Viewed 57 times

0

I’m having a hard time creating percentage-related goals.

What I want to do is a method that generates objects, all objects have only one attribute.

I need that 20% of the objects are generated with this attribute having as value 1 and the others having as value 2, however, I need it in a way that in my ArrayQueue those with a value of 1 and 2 are not necessarily positioned on one side of the other.

  • 1

    20% deterministic or random?

  • deterministic!

  • 1

    "don’t necessarily be positioned next to each other" by chance means adding objects to an array and shuffling them (Collections.shuffle())?

1 answer

2


If your difficulty is creating the objects, try this:

import java.util.ArrayList;

public class Porcentagem {
    private final int valor;

    public Porcentagem(int valor) {
        this.valor = valor;
    }

    public int getValor() {
        return valor;
    }

    public static void main(String[] args) {
        ArrayList<Porcentagem> q = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            q.add(new Porcentagem(i % 5 == 0 ? 1 : 2));
        }
    }
}

Basically, this algorithm repeatedly inserts an element with value 1 followed by four elements with value 2. Thus, it ensures a deterministic order where 1s will not be on each other’s side. If that’s not what you want, please explain it better.

Note: There is no class ArrayQueue in java. I just found ArrayList and ArrayDeque. I used ArrayList in the code above, but you can use the one you think best.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.