0

I am trying to insert 3 objects of different classes into an array, such that, the array looks like this [objA,.., objA, objB,.., objB, objC,..., objC]. The way I have my function set up is to get a rand for number of times each of objA, objB and objC will be inserted into the array, then have 3 for loops to insert each of the objects.

    $no_of_objA = rand(5, 10);
    $no_of_objB = rand(1, 5);
    $no_of_objC = rand(3, 8);

    for($i = 0; $i < $no_of_objA; $i++)
        $this->users[$i] = new A();

    for($i = $no_of_objA; $i < ($no_of_objA + $no_of_objB); $i++)
        $this->users[$i] = new B();

    for($i = ($no_of_objA + $no_of_objB); $i < ($no_of_objA + $no_of_objB + $no_of_objC); $i++)
        $this->users[$i] = new C();

The worst case for this obviously will be Big-O of largest number generated form the rand function. This works fine, but, I'm kind of thinking there may be a more elegant and optimized solution to achieving this.

I'm not really concerned by the order the objects are inserted...

4
  • 2
    free cookie if any one knows what the OP is doing Commented Jul 6, 2016 at 3:21
  • I won't get a free cookie.... Commented Jul 6, 2016 at 3:21
  • @Rasclatt can i sell ya one? :) Commented Jul 6, 2016 at 3:23
  • @Dagon As long as I don't have to try and wrap my head around a similar algorithm scheme, then maybe...I'm a cheap-skate though. Commented Jul 6, 2016 at 3:27

1 Answer 1

2

If you don't care about tracking with IDs

$a_count = mt_rand(5, 10); //Faster than rand
$b_count = mt_rand(1, 5);
$c_count = mt_rand(3, 8);

for($i = 0;$i < $a_count; $i++){
    $this->users[] = new A();
}
for($i = 0;$i < $b_count; $i++){
    $this->users[] = new B();
}
for($i = 0;$i < $c_count; $i++){
    $this->users[] = new C();
}
Sign up to request clarification or add additional context in comments.

1 Comment

This actually produces exactly the same result as the code in the question, since PHP will automatically index the array starting at 0. It is more elegant in that the loops are simpler but it produces the same result. It is not any faster, and I don't think a faster solution exists. Creating and inserting n objects is obviously O(n).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.