php 盖尔-沙普利算法
c# 下的代码:https://www.cnblogs.com/aitong/p/10973774.html
<?php class People { public $id; public $partnerid; public $satisfaction; public $reqArray; function __construct($myID) { $this->id = $myID; $this->partnerid = -1; } function isMarried() { if ($this->partnerid >= 0) { return true; } else { return false; } } function getSatisfaction() { $num = count($this->reqArray); $index = array_search($this->partnerid, $this->reqArray); $sa = ($num - $index)/$num; return $sa; } function initRequestList($num) { $this->reqArray = range(0, $num - 1); shuffle($this->reqArray); } } class Male extends People { private $reqIndex; function __construct($myID) { parent::__construct($myID); $this->reqIndex = 0; } function request($femaleArray) { if ($this->isMarried()) { return true; } $femaleID = $this->reqArray[$this->reqIndex]; $feMale = $femaleArray[$femaleID]; if ($feMale->BeRequest($this->id)) { $this->partnerid = $femaleID; return true; } else { $this->reqIndex = $this->reqIndex + 1; return false; } } } class FeMale extends People { function __construct($myID) { parent::__construct($myID); } function BeRequest($maleID) { if ($this->isMarried()) { return false; } $this->partnerid = $maleID; return true; } } class Marry { public $maleArr; public $femaleArr; function __construct($num) { $this->maleArr = array(); $this->femaleArr = array(); for ($i = 0; $i < $num; $i++) { $this->maleArr[$i] = new Male($i); $this->maleArr[$i]->initRequestList($num); $this->femaleArr[$i] = new FeMale($i); $this->femaleArr[$i]->initRequestList($num); } } function needMatch() { foreach ($this->maleArr as $key => $value) { if (!($value->isMarried())) { return true; } } return false; } function start() { while ($this->needMatch()) { foreach ($this->maleArr as $key => $value) { $value->request($this->femaleArr); } } } function getMaleSatisfaction() { $sa = 0; foreach ($this->maleArr as $key => $value) { $saItem = $value->getSatisfaction(); //var_dump($saItem); $sa = $sa + $saItem; } $sa = $sa / count($this->maleArr); return $sa; } function getFemaleSatisfaction() { $sa = 0; foreach ($this->femaleArr as $key => $value) { $saItem = $value->getSatisfaction(); $sa = $sa + $saItem; } $sa = $sa / count($this->maleArr); return $sa; } } $marry = new Marry(500); $marry->start(); echo 'male satisfaction : '; echo $marry->getMaleSatisfaction(); echo '<br />'; echo 'female satisfaction : '; echo $marry->getFemaleSatisfaction();