improve and fix some test apps
[libfirm] / ir / be / test / queens-handoptimized.c
1 /*
2  * Project:     GCC-firm
3  * File name:   test/Queens.c
4  * Purpose:     solve the queens problem
5  * Author:      Markus Armbruster (in sather-k)
6  * Modified by: Michael Beck (for GCC-firm)
7  * Created:     XX.11.2001
8  * CVS-ID:      $Id$
9  * Copyright:   (c) 2001 Universitaet Karlsruhe
10  * Licence:
11  */
12 /*
13   -- The notorious n-queens problem (C.F. Gauss, 1850)
14   -- Copyright (C) 1996 Markus Armbruster
15 */
16
17 #include <stdlib.h>
18 #include <stdio.h>
19
20
21 typedef int boolean;
22
23 #define true    1
24 #define false   0
25
26 //static int *row;
27 // queen in column c is at row[c]
28
29 static inline int myabs(int i) {
30     if(0 > i)
31         i = -i;
32     return(i);
33 }
34
35 static inline boolean place_ok (int i, const int *r, int ri) {
36     // return whether queen in column i is
37     // not in check from queens left of it
38     int j = 0;
39     boolean res;
40
41     while (j < i) {
42                 int rj = r[j];
43         if ((rj == ri) || ((myabs(ri-rj)) == (i-j))) {
44             res = false;
45             return(res);
46         }
47         j = j+1;
48     }
49
50     res = true;
51     return(res);
52 }
53
54 int solve (int n) {
55     // return the number of solutions to the n-queens problem
56     int c = 0;
57     int res = 0;
58     int *row;
59
60     row = malloc(sizeof(*row) * n);
61     row[0] = -1;
62     while (c >= 0) {
63         int rc = row[c];
64
65         do {
66             rc++;
67         } while ((rc < n) && (!place_ok(c, row, rc)));
68
69         if (rc < n) { // successfully placed at (c,row[c])
70             row[c] = rc;
71
72             if (c == n-1)
73                 res = res+1;
74             else {
75                 c = c+1;
76                 row[c] = -1;
77             }
78             continue;
79         }
80
81         row[c] = rc;
82         c = c-1;
83     }
84     free(row);
85
86     return(res);
87 }
88
89 static void usage (const char *progname) {
90     printf("usage: %s\n", progname);
91 }
92
93
94 int main (int argc, char *argv[]) {
95     int n;
96
97     switch (argc) {
98     case 1:
99         n = 8;
100         break;
101     case 2:
102         n = atoi(argv[1]);
103         break;
104     default:
105         usage("queens");
106         return 0;
107     }
108     printf("The %d-queens problem has %d solutions.\n", n, solve(n));
109
110     return 0;
111 }