Combinatratics

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: Combinatratics

Post by superdezign »

I prefer to write the code than visualize. lol

Code: Select all

class SetStuff {
  protected $length; // length of a valid record
  protected $set = array(); // set of records

  public function __construct($length = 0, array $set) {
    $this->length = (int)$length;

    foreach ($set as $item) {
      $this->add($item);
    }
  }

  public function add($item) {
    if (strlen($item) == $this->length) {
      $this->set[] = $item;
    }
  }

  public function find($rule) {
    $results = array();

    if (strlen($rule) != $this->length) {
      return $results;
    }

    foreach ($this->set as $item) {
      $isValid = true;

      for ($i = 0; $isValid && $i < $this->length; $i++) {
        if ($rule[$i] != '_') {
          $isValid = $isValid && ($rule[$i] == $item[$i]);
        }
      }

      if ($isValid) {
        $results[] = $item;
      }
    }

    return $results;
  }
} 
You would run SetStuff::find() on all of the rules, and then use array_unique() on the resulting arrays to remove duplicates. Though, that is assuming that there are no duplicates in the set and that you do not want duplicates in the results. If there are duplicates in the set, then instead of adding the actual items to the resulting array in SetStuff::find(), just add their index, run array_unique() on that array, and then use SetStuff to replace the indices with the literal items.

This could all be implemented in the class, of course. I would have done it, but the code was starting to feel lengthy. :P
Post Reply