Caddy
A 2005 Roborodentia entry with vision and path planning capability
 All Data Structures Files Functions Variables Typedefs Macros Pages
permutation.c
1 /*
2  * This file is part of Caddy.
3  *
4  * Caddy is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * Caddy is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with Caddy. If not, see <http://www.gnu.org/licenses/>.
16  */
17 #include "permutation.h"
18 
19 static void swap(uint8_t *a, uint8_t *b);
20 static void reverseArray(uint8_t *first, uint8_t *last);
21 
22 bool generateNextPermutation(uint8_t *first, uint8_t *last)
23 {
24  uint8_t *i = last - 1;
25  if (first == last || first == i) // check for n=0 or n=1
26  return false;
27 
28  for (;;)
29  {
30  uint8_t *ii = i--;
31  if (*i < *ii)
32  {
33  uint8_t *j = last;
34  while (!(*i < *--j)) ;
35 
36  swap(i, j);
37  reverseArray(ii, last);
38 
39  return true;
40  }
41  if (i == first)
42  {
43  reverseArray(first, last);
44  return false;
45  }
46  }
47 
48  // Should not reach this line
49  return false;
50 }
51 
60 static void swap(uint8_t *a, uint8_t *b)
61 {
62  uint8_t tmp = *a;
63  *a = *b;
64  *b = tmp;
65 }
66 
76 static void reverseArray(uint8_t *first, uint8_t *last)
77 {
78  last--; // point last to element to begin reversing
79 
80  if (first < last)
81  {
82  while (first < last)
83  swap(first++, last--);
84  }
85  else
86  {
87  while (last < first)
88  swap(last++, first--);
89  }
90 }