FusionDirectory
 All Data Structures Files Functions Variables
class_Combinations.inc
1 <?php
2 /*
3  This code is part of FusionDirectory (http://www.fusiondirectory.org/)
4  Copyright (C) 2018 FusionDirectory
5 
6  This program is free software; you can redistribute it and/or modify
7  it under the terms of the GNU General Public License as published by
8  the Free Software Foundation; either version 2 of the License, or
9  (at your option) any later version.
10 
11  This program is distributed in the hope that it will be useful,
12  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  GNU General Public License for more details.
15 
16  You should have received a copy of the GNU General Public License
17  along with this program; if not, write to the Free Software
18  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
19 */
20 
23 class Combinations implements Iterator
24 {
25  protected $current = NULL;
26  protected $input = NULL;
27  protected $n = 0;
28  protected $size = 0;
29  protected $pos = 0;
30 
31  function __construct($input, $size)
32  {
33  $this->input = array_values($input);
34  $this->n = count($this->input);
35  $this->size = $size;
36  $this->rewind();
37  }
38 
39  function key()
40  {
41  return $this->pos;
42  }
43 
44  function current()
45  {
46  $r = array();
47  for ($i = 0; $i < $this->size; $i++) {
48  $r[] = $this->input[$this->current[$i]];
49  }
50  return $r;
51  }
52 
53  function next()
54  {
55  if ($this->_next()) {
56  $this->pos++;
57  } else {
58  $this->pos = -1;
59  }
60  }
61 
62  function rewind()
63  {
64  $this->current = range(0, $this->size);
65  $this->pos = 0;
66  }
67 
68  function valid()
69  {
70  return ($this->pos >= 0);
71  }
72 
73  protected function _next()
74  {
75  $i = $this->size - 1;
76  while (($i >= 0) && ($this->current[$i] == $this->n - $this->size + $i)) {
77  $i--;
78  }
79  if ($i < 0) {
80  return FALSE;
81  }
82  $this->current[$i]++;
83  while ($i++ < $this->size - 1) {
84  $this->current[$i] = $this->current[$i - 1] + 1;
85  }
86  return TRUE;
87  }
88 }