Question

I have 5 menus with children. In first menu I have 16 children, in second 22 children, in third 10 children, in fort and fifth 19 children.

Every sub menu has 5 rows and this children must be in this rows beautifully arranged. The same number in each row if possible or one more.

example for first and second menu with 16 and 22 children:

  • MENU1 4 children in first row, 3 in second, 3 in third, 3 in forth and 3 in fifth

  • MENU2 5 children in first row, 5 in second, 4 in third, 4 in forth and 4 in fifth

and my problem is how to create algorithm which will add children in sub menu. Children must be beautifully arranged. The same number in each row if possible or one more.

Was it helpful?

Solution

Because I'm not 100% clear on what "beautiful" means in your question, I've made a few assumptions about what is acceptable.

The following code works for up to 100 menu configurations.

  • It first tries to distribute items into rows of 3,4,5 or 6 (60% of cases)
  • Then it tries to leave only 1 on the last row (30% of cases)
  • Then it tries to leave only 2 on the last row (10% of cases)

The Code:

<?php

$column_range = range(3,6);

#$menu = array(16,22,10,19);
$menu = range(1,100); # showing a range of menu configurations

print_r($menu); print '<hr />';

foreach ($menu as $item){

    $beautiful = False;

    foreach($column_range as $column_width){
        if($item%$column_width==0 && $beautiful==False){
            print "$item will be beautiful if you use $column_width per row";
            print '<br />';
            $beautiful = True;
        }
    }

    if($beautiful==False){

        foreach($column_range as $column_width){
            if($item%$column_width==1 && $beautiful==False){
                print "$item is hard to make beautiful, most rows will have $column_width, however the last row will have 1 one it";
                print '<br />';
                $beautiful = True;
            }
        }
    }

    if($beautiful==False){

        foreach($column_range as $column_width){
            if($item%$column_width==2 && $beautiful==False){
                print "$item is hard to make beautiful, most rows will have $column_width, however the last row will have 2 one it";
                print '<br />';
                $beautiful = True;
            }
        }
    }

    if($beautiful==False){
        print "$item what shall i do with you";
        print '<br />';
    }

}

?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top