hi everyone,

i am trying to write a java program that assigns a specified number of true values to random elements in an array. for example if i have a boolean array of 10 elements i would like 5 of these elements to be randomly assigned true values.

im new to java so this question will seem pretty silly to most of you but i would appreciate any help
thanks

Recommended Answers

All 2 Replies

Here's a simple pseudocode solution.

boolean[10] array  /* Array of all false values */
int count = 5      /* Number of true values we want */
while count > 0:
    int k = Math.random()*10  /* Random integer from 0 to 9, inclusive */
    if array[k] == false:
        array[k] = true
        count --

This code decrements the counter when true values are assigned and tries again when it sees that the element it picks has already been set.

This is certainly not an optimal solution, but it's pretty easy to put together.

Thanks for that, im not really fussed about elegant solutions. since im only a begginner anything that works is good :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.