I really would appreciate somebody help.
Here is the Function:
Code: Select all
<?php
require_once( 'Person.php');
require_once( 'Asiinit.php');
function printSociety($curSociety){ //we can do not print the person ,which means the person is dead
for ( $i = 0; $i<count($curSociety); $i++) {
if($curSociety[$i]->age<100) //check the age
echo "Person ID:".$curSociety[$i]->id." age:".$curSociety[$i]->age."<br />\n";
$theNumOfChildren = count($curSociety[$i]->children);
for($j=0; $j < $theNumOfChildren; $j++){ //print the children
if($curSociety[$i]->children[$j]->age<100) //check the age
echo "Person ID:".$curSociety[$i]->children[$j]->id." age:".$curSociety[$i]->children[$j]->age."<br />\n";
}
}
}
function updateSociety($curSociety) //there is something wrong with the function,can not change the age,need to be improved
{
for ( $i = 0; $i<count($curSociety); $i++){
$curSociety[$i]->age+=1;
$theNumOfChildren = count($curSociety[$i]->children);
for($j=0; $j < $theNumOfChildren; $j++){
$curSociety[$i]->children[$j]->age+=1;
}
}
}
$curYear=0;
while($curYear<=100) //just print every ten years for test ,need to be improved
{
echo "This is YEAR:".$curYear."<br />\n";
printSociety($society);
updateSociety($curSociety);
$curYear=$curYear+1;
}
Code: Select all
<?php
//this class will represent both a Person and a Child in the society
class Person {
var $id;
var $age;
var $children;
function Person( $id, $age) {
$this->id = $id;
$this->age = $age;
// all children if any are added will be places into this array
$this->children = array();
}
function addChild( $child) {
array_push( $this->children, $child);
}
}
?>
Code: Select all
<?php
require_once( 'Person.php');
/**
* Rules of society:
* 1. Whenever a person reaches the age of 100, he dies
* 2. At initiation, a person may be given a number of children,
* each of age from 0 to 10
* 3. A Child is a full-fledged person and should be treated as such
* 4. Society is becoming extinct, since no new children are born into it
*/
// this array contains the entire society
$society = array();
$id = 0; // this will be used to give unique id to everyone in society
// create 100 people of age
for ( $i = 0; $i < 100; $i++) {
// create a new person with a random age between 20 and 50
// mt_rand is a PHP random number generator function
$person = new Person( $i, mt_rand( 20, 50));
$id++; // next person will have another id
if ( mt_rand( 0, 1) === 0) { // 50/50 change of adding children to this person
$count = mt_rand( 1, 5); // add between 1 and 5 chidren to this person
for ( $y = 0; $y < $count; $y++) {
$person->addChild( new Person( $id, mt_rand( 0, 20)));
$id++; // next child or person will have another id
}
}
array_push( $society, $person);
}
?>