Page 2 of 2

Re: Combinatratics

Posted: Sun Aug 01, 2010 3:10 pm
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