File: magicsquares.java

package info (click to toggle)
groovy2 2.2.2%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 23,916 kB
  • sloc: java: 136,570; xml: 948; sh: 486; makefile: 67; ansic: 64
file content (234 lines) | stat: -rw-r--r-- 7,591 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
/* The Computer Language Shootout
   http://shootout.alioth.debian.org/

   benchmark implementation (not optimized)
   JRE 1.5 only
   contributed by Josh Goldfoot */

import java.io.*;
import java.lang.*;
import java.util.*;

public class magicsquares {
    
    static int n;
    static int mn;
    
    public static class FfmResult {
        public int x;
        public int y;
        public int[] moves;
        public FfmResult(int ix, int iy, int[] imoves) {
            x = ix;
            y = iy;
            moves = (int[]) imoves.clone();
        }
    }
    
    public static class PQNode implements Comparable {
        public int [] grid;
        boolean priorityCalculated;
        private int priority;
        private FfmResult ffm;
        
        public PQNode() {
            grid = new int [n * n];
            int i;
            for (i = 0; i < n * n; i++)
                grid[i] = 0;
            priorityCalculated = false;
            ffm = null;
        }
        public PQNode(PQNode other) {
            grid = (int[]) other.grid.clone();
            priorityCalculated = false;
        }

        public int[] gridRow(int y) {
            int[] r = new int[n];
            int x;
            for (x = 0; x < n; x++)
                r[x] = grid[x + y * n];
            return r;
        }

        public int[] gridCol(int x) {
            int[] r = new int[n];
            int y;
            for (y = 0; y < n; y++)
                r[y] = grid[x + y * n];
            return r;
        }

        public int[] diagonal(int q) {
            int[] r = new int[n];
            int i;
            for (i = 0; i < n; i++) {
                if (q == 1)
                    r[i] = grid[i + i * n];
                else if (q == 2) {
                    r[i] = grid[i + (n - 1 - i) * n];
                }
            }
            return r;
        }

        public int[] possibleMoves(int x, int y) {
            int zerocount, sum, highest, j, i;
            
            if (grid[x + y * n] != 0)
                return ( new int [] { });
            ArrayList<int[]> cellGroups = new ArrayList<int[]>();
            cellGroups.add(gridCol(x));
            cellGroups.add(gridRow(y));
            if (x == y)
                cellGroups.add(diagonal(1));
            if (x + y == n - 1)
                cellGroups.add(diagonal(2));
            HashSet<Integer> usedNumbers = new HashSet<Integer>();
            for (i = 0; i < grid.length; i++)
                usedNumbers.add(new Integer(grid[i]));
            HashSet<Integer> onePossible = new HashSet<Integer>();
            highest = n * n;
            for (int[] group: cellGroups) {
                zerocount = 0;
                sum = 0;
                for (int num: group) {
                    if (num == 0)
                        zerocount++;
                    sum += num;
                }
                if (zerocount == 1)
                    onePossible.add(new Integer(mn - sum));
                if (mn - sum < highest)
                    highest = mn - sum;
            }
            if (onePossible.size() == 1) {
                Integer onlyPossibleMove = (Integer) onePossible.iterator().next();
                int opmint = onlyPossibleMove.intValue();
                if (opmint >= 1 && 
                        opmint <= n * n && 
                        ! usedNumbers.contains(onlyPossibleMove))
                    return (new int[] { opmint });
                else
                    return ( new int [] { });
            } else if (onePossible.size() > 1)
                return ( new int [] { });
            ArrayList<Integer> moves = new ArrayList<Integer>();
            for (i = 1; i <= highest; i++) {
                Integer ii = new Integer(i);
                if (! usedNumbers.contains(ii))
                    moves.add(ii);
            }
            int[] r = new int[moves.size()];
            i = 0;
            for (Integer move: moves) {
                r[i++] = move.intValue();
            }
            return r;
        }

        public FfmResult findFewestMoves() {
            if (ffm != null)
                return ffm;
            int x, y, mx, my, ind;
            int[] minmoves = (new int[] { });
            int[] moves;
            mx = my = -1;
            for (y = 0; y < n; y++)
                for (x = 0; x < n; x++) {
                    ind = x + y * n;
                    if (grid[ind] == 0) {
                        moves = possibleMoves(x,y);
                        if (mx == -1 || moves.length < minmoves.length) {
                            mx = x;
                            my = y;
                            minmoves = (int[]) moves.clone();
                        }
                    }
                }
            ffm = new FfmResult(mx, my, minmoves);
            return ffm;
        }
        
        public void calculatePriority()
        {
            int i, zerocount;
            zerocount = 0;
            for (int cell: grid)
                if (cell == 0)
                    zerocount++;
            priority = zerocount + findFewestMoves().moves.length;
            priorityCalculated = true;
        }
        
        public int getPriority()
        {
            if (priorityCalculated)
                return priority;
            else {
                calculatePriority();
                return priority;
            }
        }
        
        public int compareTo(Object anotherMSquare) throws ClassCastException {
            if (!(anotherMSquare instanceof PQNode))
                throw new ClassCastException();
            PQNode other = (PQNode) anotherMSquare;
            int c = getPriority() - other.getPriority();
            if (c == 0) {
                int i = 0;
                while (c == 0 && i < n * n) {
                    c = grid[i] - other.grid[i];
                    i++;
                }
            }
            return c;
        }

        public String toString() {
            StringBuilder sb = new StringBuilder();
            int y, x;
            for (y = 0; y < n; y++) {
                for (x = 0; x < n; x++) {
                    sb.append(grid[x + y * n]);
                    if (x < n-1)
                        sb.append(' ');
                }
                if (y < n-1)
                    sb.append('\n');
            }
            return sb.toString();
        }

        
    }
    
    public magicsquares() { }
    
    public static void main(String[] args) {
        n = 3;
        if (args.length > 0) 
            n = Integer.parseInt(args[0]);
        mn = n * (1 + n * n) / 2;
        PriorityQueue<magicsquares.PQNode> pq = new PriorityQueue<magicsquares.PQNode>(); 
        pq.offer(new magicsquares.PQNode() );
        while (! pq.isEmpty()) {
            PQNode topSquare = pq.poll();
            if (topSquare.getPriority() == 0) {
                System.out.println(topSquare);
                break;
            }
            magicsquares.FfmResult result = topSquare.findFewestMoves();

            int ind = result.x + result.y * n;
            for (int move: result.moves) {
                magicsquares.PQNode newSquare = new magicsquares.PQNode(topSquare);
                newSquare.grid[ind] = move;
                pq.offer(newSquare);
            }
        }
                
    }
}