-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnumberpartition.java
More file actions
446 lines (363 loc) · 12.2 KB
/
numberpartition.java
File metadata and controls
446 lines (363 loc) · 12.2 KB
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Collections;
import java.lang.Math;
public class numberpartition {
//number of iterations for approximation algorithms
public static final int max_iter = 25000;
public static final long bound = 1000000000000L;
public static final int setsize = 100;
public static void main(String [] args) throws FileNotFoundException{
PrintStream ps = new PrintStream(System.out);
//ensure proper arguments
if(args.length > 1){
ps.printf("Input should be of the form: ./kk inputfile, 100 integers in file \n");
return;
}
//create file reader
Scanner s;
s = new Scanner(new BufferedReader(new FileReader(args[0])));
//load numbers from file into array
long[] nums = new long[100];
for(int i = 0; i < 100; i++){
nums[i] = s.nextLong();
}
//long[] test = {10,8,7,6,5,10,4,3,13,5};
/*
//partition generation/move tests
int [] P = randomPartGen(10);
setPrint(P);
randomPartMove(P);
setPrint(P);
randomPartMove(P);
setPrint(P);
randomPartMove(P);
setPrint(P);
*/
//print output
long file_residue = kk(nums);
ps.printf("%d\n",file_residue);
/*
// log data into CSV file
try {
FileWriter writer = new FileWriter("results.csv");
// 50 random instances
for (int i = 1; i <= 50; i++) {
long[] A = standardRandomSetGen(setsize);
int[] S = standardRandomSolGen(setsize);
// original residue
writer.append(String.valueOf(standardResidue(S, A)));
writer.append(',');
// KK residue
writer.append(String.valueOf(kk(A)));
writer.append(',');
// Standard Repeated Random residue
int[] S_a = standardRepeatedRandom(S, A);
writer.append(String.valueOf(standardResidue(S_a, A)));
writer.append(',');
// Standard Hill Climbing residue
int[] S_b = standardHillClimbing(S, A);
writer.append(String.valueOf(standardResidue(S_b, A)));
writer.append(',');
// Standard Simulated Annealing residue
int[] S_c = standardSimulatedAnnealing(S, A);
writer.append(String.valueOf(standardResidue(S_c, A)));
writer.append(',');
// Prepartitioning Repeated Random residue
long res_a = repeatedPartRandom(A);
writer.append(String.valueOf(res_a));
writer.append(',');
// Prepartitioning Hill Climbing residue
long res_b = hillPartClimb(A);
writer.append(String.valueOf(res_b));
writer.append(',');
// Prepartitioning Simulated Annealing residue
long res_c = simularedPartAnnealing(A);
writer.append(String.valueOf(res_c));
writer.append('\n');
}
writer.flush();
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
*/
}
/**
* Karmarkar-Karp Algorithm implementation
*/
public static long kk(long [] input){
int length = input.length;
PriorityQueue<Long> heap = new PriorityQueue<>(100,Collections.reverseOrder());
//add all items to heap
for(int i = 0; i < length; i++){
heap.offer(input[i]);
}
//perform repeated differencing
while(heap.size() > 1){
long num1 = heap.poll();
long num2 = heap.poll();
heap.add(num1-num2);
}
//return last element in the heap
return heap.poll();
}
/**
* Repeated random algorithm with standard representation
*/
public static int[] standardRepeatedRandom(int[] S, long[] A) {
int[] S_1;
for (int i = 0; i < max_iter; i++) {
S_1 = standardRandomSolGen(S.length);
if (standardResidue(S_1, A) < standardResidue(S, A)) {
S = S_1;
}
}
return S;
}
/**
* Hill climbing algorithm with standard representation
*/
public static int[] standardHillClimbing(int[] S, long[] A) {
int[] S_1;
for (int i = 0; i < max_iter; i++) {
S_1 = standardRandomMove(S);
if (standardResidue(S_1, A) < standardResidue(S, A)) {
S = S_1;
}
}
return S;
}
/**
* Simulated annealing algorithm with standard representation
*/
public static int[] standardSimulatedAnnealing(int[] S, long[] A) {
int[] S_1;
int[] S_2 = new int[S.length];
System.arraycopy(S, 0, S_2, 0, S.length);
for (int i = 0; i < max_iter; i++) {
S_1 = standardRandomMove(S);
if (standardResidue(S_1, A) < standardResidue(S, A)) {
S = S_1;
} else if (Math.random() < Math.exp(0 - (standardResidue(S_1, A) - standardResidue(S, A)) / T(i))) {
S = S_1;
}
if (standardResidue(S, A) < standardResidue(S_2, A)) {
S_2 = S;
}
}
return S_2;
}
/**
* Cooling schedule function
*/
public static double T(int iter) {
return Math.pow(10, 10) * Math.pow(0.8, iter / 300.0);
}
/**
* Calculates the residue
*/
public static long standardResidue(int[] S, long[] A) {
long residue = 0;
for (int i = 0; i < S.length; i++) {
residue += S[i] * A[i];
}
if (residue < 0) {
residue = 0 - residue;
}
return residue;
}
/**
* Perform a random move on set s
*/
public static int[] standardRandomMove(int[] S) {
int[] rmove = new int[S.length];
System.arraycopy(S, 0, rmove, 0, S.length);
// random indices
int i = 0;
int j = 0;
while (i == j) {
i = (int) (Math.random() * rmove.length);
j = (int) (Math.random() * rmove.length);
}
// switch first index always
rmove[i] = 0 - rmove[i];
// switch second index with prob 0.5
if (Math.random() < 0.5) {
rmove[j] = 0 - rmove[j];
}
return rmove;
}
/**
* Generate random set of n elements
*/
public static long[] standardRandomSetGen(int n) {
long[] set = new long[n];
for (int i = 0; i < n; i++) {
set[i] = randomLong();
}
return set;
}
/**
* Generate a random long between 1 and 10^12
*/
public static long randomLong() {
return (long)Math.ceil((Math.random() * bound));
}
/**
* Generate a random solution of n elements
*/
public static int[] standardRandomSolGen(int n) {
int sol[] = new int[n];
for (int i = 0; i < n; i++) {
if (Math.random() < 0.5) {
sol[i] = 1;
} else {
sol[i] = -1;
}
}
return sol;
}
/**
* Perform repeated random algorithm with prepartitioning for num_iters trials
*/
public static long repeatedPartRandom(long[] A){
int length = A.length;
int[] P = randomPartGen(length);
int[] P2 = P.clone();
long prev_res = partitionResidue(P,A);
long new_res = -1;
//iterate over possible solutions max_iter times
//*note* wasting a lot of memory allocation here, can
//change randomPartGen if necessary
for(int i = 0; i < max_iter;i++){
P2 = randomPartGen(length);
new_res = partitionResidue(P2,A);
if(new_res < prev_res){
P = P2.clone();
prev_res = new_res;
}
}
//return residue of final partition
return prev_res;
}
/**
* Return residue from hill-climbing on random prepartition
*/
public static long hillPartClimb(long[] A){
int length = A.length;
int[] P = randomPartGen(length);
//will hold changes in original partition
int[] P2 = P.clone();
long prev_res = partitionResidue(P,A);
long new_res = -1;
//iterate over possible solutions max_iter times
//*note* wasting a lot of memory allocation here, can
//change randomPartGen if necessary
for(int i = 0; i < max_iter;i++){
randomPartMove(P2);
new_res = partitionResidue(P2,A);
if(new_res < prev_res){
P = P2.clone();
prev_res = new_res;
}
}
//return residue of final partition
return prev_res;
}
/**
* Returns residue from simulated annealing on prepartitioned set
*/
public static long simularedPartAnnealing(long[] A){
int length = A.length;
int[] P = randomPartGen(length);
int[] P2 = P.clone();
int[] P3 = P.clone();
long min_res = partitionResidue(P,A);
long prev_res = min_res;
long new_res = -1;
for(int i = 0; i < max_iter; i++){
randomPartMove(P2);
new_res = partitionResidue(P2,A);
if(new_res < prev_res){
P = P2.clone();
prev_res = new_res;
}else if(Math.random() < Math.exp((-(new_res-prev_res)/(((10000000000L)*Math.pow(0.8, i/300.0)))))){
P = P2.clone();
prev_res = new_res;
}
if(prev_res < min_res){
P3 = P.clone();
min_res = prev_res;
}
}
return min_res;
}
/**
* Return a residue from Karmarkar-Karp given a partition and a set
*/
public static long partitionResidue(int[] P, long[] A){
int length = P.length;
//this is an error, return -1
if(length!=A.length){
return -1;
}
long[] newInput = new long[length];
for(int i = 0; i < length; i++){
newInput[P[i]]+=A[i];
}
return kk(newInput);
}
/**
* Generate a random partition of size n
*/
public static int[] randomPartGen(int n){
int[] partition = new int[n];
for(int i = 0; i < n; i++){
int part = (int)(Math.random()*n);
partition[i] = part;
}
return partition;
}
/**
* Perform a random move on partition P, given existing partition
*/
public static void randomPartMove(int[] P){
//index i whose partition number p_i will change
int from_index;
//index j the partition p_i will change to
int to_index;
int length = P.length;
from_index = (int)(Math.random()*length);
to_index = (int)(Math.random()*(length-1));
//if equal, increment in order to align range of to_index w/ from_index
if(to_index==P[from_index]){
++to_index;
}
P[from_index] = to_index;
}
/**
* Print a solution array
*/
public static void solPrint(int[] sol) {
System.out.printf("[%2d", sol[0]);
for (int i = 1; i < sol.length; i++) {
System.out.printf("|%2d", sol[i]);
}
System.out.printf("]\n");
}
/**
* Print an array of non-negative integers (long)
*/
public static void setPrint(long[] sol) {
System.out.printf("[%2d", sol[0]);
for (int i = 1; i < sol.length; i++) {
System.out.printf("|%2d", sol[i]);
}
System.out.printf("]\n");
}
}