-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTradeMaximizer.java
More file actions
659 lines (579 loc) · 25.3 KB
/
TradeMaximizer.java
File metadata and controls
659 lines (579 loc) · 25.3 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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
// TradeMaximizer.java
// Created by Chris Okasaki (cokasaki)
// Version 1.3a
// $LastChangedDate: 2008-03-07 09:08:08 -0500 (Fri, 07 Mar 2008) $
// $LastChangedRevision: 28 $
import java.io.*;
import java.util.*;
import java.text.*;
public class TradeMaximizer {
public static void main(String[] args) { new TradeMaximizer().run(); }
final String version = "Version 1.3a";
// This function is executed by main() at startup
void run() {
System.out.println("TradeMaximizer " + version);
// Read in the want options, usernames, and want lists
List< String[] > wantLists = readWantLists();
if (wantLists == null) return;
// Display custom options, if they exist
if (options.size() > 0) {
System.out.print("Options:");
for (String option : options) System.out.print(" "+option);
System.out.println();
}
System.out.println();
// Create the graph by parsing the want lists and other input
buildGraph(wantLists);
// Display more info if requested by options
if (showMissing && officialNames != null && officialNames.size() > 0) {
for (String name : usedNames) officialNames.remove(name);
List<String> missing = new ArrayList<String>(officialNames);
Collections.sort(missing);
for (String name : missing) {
System.out.println("**** Missing want list for official name " +name);
}
System.out.println();
}
if (showErrors && errors.size() > 0) {
Collections.sort(errors);
System.out.println("ERRORS:");
for (String error : errors) System.out.println(error);
System.out.println();
}
// Input parsing is completed. Before we start processing, we'll take a
// timestamp so we can later report the total processing time
long startTime = System.currentTimeMillis();
// Remove unusable entries and edges from the graph
graph.removeImpossibleEdges();
// Perform the actual search
List<List<Graph.Vertex>> bestCycles = graph.findCycles();
int bestSumSquares = sumOfSquares(bestCycles);
// Repeat the search for each iteration
if (iterations > 1) {
graph.saveMatches();
for (int i = 0; i < iterations-1; i++) {
// Shuffle the receiver order around
graph.shuffle();
// Perform the actual search again
List<List<Graph.Vertex>> cycles = graph.findCycles();
// Determine if we have a better solution this time
int sumSquares = sumOfSquares(cycles);
if (sumSquares < bestSumSquares) {
// Save off info on the new find
bestSumSquares = sumSquares;
bestCycles = cycles;
graph.saveMatches();
// Prepare some display information for the user
int[] groups = new int[cycles.size()];
for (int j = 0; j < cycles.size(); j++)
groups[j] = cycles.get(j).size();
Arrays.sort(groups);
// Display stats on the new find
System.out.print("[ "+sumSquares + " :");
for (int j = groups.length-1; j >= 0; j--)
System.out.print(" " + groups[j]);
System.out.println(" ]");
}
}
System.out.println();
// Restore info regarding our best matching solution
graph.restoreMatches();
}
long stopTime = System.currentTimeMillis();
displayMatches(bestCycles);
if (showElapsedTime)
System.out.println("Elapsed time = " + (stopTime-startTime) + "ms");
}
// Find the sum of the squared cycle (loop) sizes. Used in determining
// which solution has the largest loops.
int sumOfSquares(List<List<Graph.Vertex>> cycles) {
int sum = 0;
for (List<Graph.Vertex> cycle : cycles) sum += cycle.size()*cycle.size();
return sum;
}
boolean caseSensitive = false;
boolean requireColons = false;
boolean requireUsernames = false;
boolean showErrors = true;
boolean showRepeats = true;
boolean showLoops = true;
boolean showSummary = true;
boolean showNonTrades = true;
boolean showStats = true;
boolean showMissing = false;
boolean sortByItem = false;
boolean allowDummies = false;
boolean showElapsedTime = false;
static final int NO_PRIORITIES = 0;
static final int LINEAR_PRIORITIES = 1;
static final int TRIANGLE_PRIORITIES = 2;
static final int SQUARE_PRIORITIES = 3;
static final int SCALED_PRIORITIES = 4;
static final int EXPLICIT_PRIORITIES = 5;
int priorityScheme = NO_PRIORITIES;
int smallStep = 1;
int bigStep = 9;
long nonTradeCost = 1000000000L; // 1 billion
int iterations = 1;
//////////////////////////////////////////////////////////////////////
List<String> options = new ArrayList<String>();
HashSet<String> officialNames = null;
List<String> usedNames = new ArrayList<String>();
List<String[]> readWantLists() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
List<String[]> wantLists = new ArrayList<String[]>();
boolean readingOfficialNames = false;
for (int lineNumber = 1;;lineNumber++) {
String line = in.readLine();
if (line == null) return wantLists;
line = line.trim();
if (line.length() == 0) continue; // skip blank link
// Handle options
if (line.matches("#!.*")) {
if (wantLists.size() > 0)
fatalError("Options (#!...) cannot be declared after first real want list", lineNumber);
if (officialNames != null)
fatalError("Options (#!...) cannot be declared after official names", lineNumber);
for (String option : line.toUpperCase().substring(2).trim().split("\\s+")) {
if (option.equals("CASE-SENSITIVE"))
caseSensitive = true;
else if (option.equals("REQUIRE-COLONS"))
requireColons = true;
else if (option.equals("REQUIRE-USERNAMES"))
requireUsernames = true;
else if (option.equals("HIDE-ERRORS"))
showErrors = false;
else if (option.equals("HIDE-REPEATS"))
showRepeats = false;
else if (option.equals("HIDE-LOOPS"))
showLoops = false;
else if (option.equals("HIDE-SUMMARY"))
showSummary = false;
else if (option.equals("HIDE-NONTRADES"))
showNonTrades = false;
else if (option.equals("HIDE-STATS"))
showStats = false;
else if (option.equals("SHOW-MISSING"))
showMissing = true;
else if (option.equals("SORT-BY-ITEM"))
sortByItem = true;
else if (option.equals("ALLOW-DUMMIES"))
allowDummies = true;
else if (option.equals("SHOW-ELAPSED-TIME"))
showElapsedTime = true;
else if (option.equals("LINEAR-PRIORITIES"))
priorityScheme = LINEAR_PRIORITIES;
else if (option.equals("TRIANGLE-PRIORITIES"))
priorityScheme = TRIANGLE_PRIORITIES;
else if (option.equals("SQUARE-PRIORITIES"))
priorityScheme = SQUARE_PRIORITIES;
else if (option.equals("SCALED-PRIORITIES"))
priorityScheme = SCALED_PRIORITIES;
else if (option.equals("EXPLICIT-PRIORITIES"))
priorityScheme = EXPLICIT_PRIORITIES;
else if (option.startsWith("SMALL-STEP=")) {
String num = option.substring(11);
if (!num.matches("\\d+"))
fatalError("SMALL-STEP argument must be a non-negative integer",lineNumber);
smallStep = Integer.parseInt(num);
}
else if (option.startsWith("BIG-STEP=")) {
String num = option.substring(9);
if (!num.matches("\\d+"))
fatalError("BIG-STEP argument must be a non-negative integer",lineNumber);
bigStep = Integer.parseInt(num);
}
else if (option.startsWith("NONTRADE-COST=")) {
String num = option.substring(14);
if (!num.matches("[1-9]\\d*"))
fatalError("NONTRADE-COST argument must be a positive integer",lineNumber);
nonTradeCost = Long.parseLong(num);
}
else if (option.startsWith("ITERATIONS=")) {
String num = option.substring(11);
if (!num.matches("[1-9]\\d*"))
fatalError("ITERATIONS argument must be a positive integer",lineNumber);
iterations = Integer.parseInt(num);
}
else if (option.startsWith("SEED=")) {
String num = option.substring(5);
if (!num.matches("[1-9]\\d*"))
fatalError("SEED argument must be a positive integer",lineNumber);
graph.setSeed(Long.parseLong(num));
}
else
fatalError("Unknown option \""+option+"\"",lineNumber);
options.add(option);
}
continue;
}
if (line.matches("#.*")) continue; // skip comment line
if (line.indexOf("#") != -1) {
if (readingOfficialNames) {
if (line.split("[:\\s]")[0].indexOf("#") != -1) {
fatalError("# symbol cannot be used in an item name",lineNumber);
}
}
else
fatalError("Comments (#...) cannot be used after beginning of line",lineNumber);
}
// Handle official name
if (line.equalsIgnoreCase("!BEGIN-OFFICIAL-NAMES")) {
if (officialNames != null)
fatalError("Cannot begin official names more than once", lineNumber);
if (wantLists.size() > 0)
fatalError("Official names cannot be declared after first real want list", lineNumber);
officialNames = new HashSet<String>();
readingOfficialNames = true;
continue;
}
if (line.equalsIgnoreCase("!END-OFFICIAL-NAMES")) {
if (!readingOfficialNames)
fatalError("!END-OFFICIAL-NAMES without matching !BEGIN-OFFICIAL-NAMES", lineNumber);
readingOfficialNames = false;
continue;
}
if (readingOfficialNames) {
if (line.charAt(0) == ':')
fatalError("Line cannot begin with colon",lineNumber);
if (line.charAt(0) == '%')
fatalError("Cannot give official names for dummy items",lineNumber);
String[] toks = line.split("[:\\s]");
String name = toks[0];
if (!caseSensitive) name = name.toUpperCase();
if (officialNames.contains(name))
fatalError("Official name "+name+"+ already defined",lineNumber);
officialNames.add(name);
continue;
}
// Handle wants
// check parens for user name preceding wants
if (line.indexOf("(") == -1 && requireUsernames)
fatalError("Missing username with REQUIRE-USERNAMES selected",lineNumber);
if (line.charAt(0) == '(') {
if (line.lastIndexOf("(") > 0)
fatalError("Cannot have more than one '(' per line",lineNumber);
int close = line.indexOf(")");
if (close == -1)
fatalError("Missing ')' in username",lineNumber);
if (close == line.length()-1)
fatalError("Username cannot appear on a line by itself",lineNumber);
if (line.lastIndexOf(")") > close)
fatalError("Cannot have more than one ')' per line",lineNumber);
if (close == 1)
fatalError("Cannot have empty parentheses",lineNumber);
// temporarily replace spaces in username with #'s
if (line.indexOf(" ") < close) {
line = line.substring(0,close+1).replaceAll(" ","#")+" "
+ line.substring(close+1);
}
}
else if (line.indexOf("(") > 0)
fatalError("Username can only be used at the front of a want list",lineNumber);
else if (line.indexOf(")") > 0)
fatalError("Bad ')' on a line that does not have a '('",lineNumber);
// Check wants for semicolons, which indicate a large step in rank
// value between two wants
line = line.replaceAll(";"," ; "); // place extra space around semicolons
int semiPos = line.indexOf(";");
if (semiPos != -1) {
if (semiPos < line.indexOf(":")) // Semicolons can only appear between wants
fatalError("Semicolon cannot appear before colon",lineNumber);
String before = line.substring(0,semiPos).trim();
if (before.length() == 0 || before.charAt(before.length()-1) == ')')
fatalError("Semicolon cannot appear before first item on line", lineNumber);
}
// Check and remove colon, which should occur just after the item whose
// wants are being specified
int colonPos = line.indexOf(":");
if (colonPos != -1) {
if (line.lastIndexOf(":") != colonPos)
fatalError("Cannot have more that one colon on a line",lineNumber);
String header = line.substring(0,colonPos).trim();
if (!header.matches("(.*\\)\\s+)?[^(\\s)]\\S*"))
fatalError("Must have exactly one item before a colon (:)",lineNumber);
line = line.replaceFirst(":"," "); // remove colon
}
else if (requireColons) {
fatalError("Missing colon with REQUIRE-COLONS selected",lineNumber);
}
if (!caseSensitive) line = line.toUpperCase();
// Add an array of each item on the list to wantLists. The first item is
// the username, if present. The next item (or the first, if no username)
// is the item whose wants are specified in the remaining items.
wantLists.add(line.trim().split("\\s+"));
}
}
catch(Exception e) {
fatalError(e.getMessage());
return null;
}
}
void fatalError(String msg) {
System.out.println();
System.out.println("FATAL ERROR: " + msg);
System.exit(1);
}
void fatalError(String msg,int lineNumber) {
fatalError(msg + " (line " + lineNumber + ")");
}
//////////////////////////////////////////////////////////////////////
Graph graph = new Graph();
List< String > errors = new ArrayList< String >();
final long INFINITY = 100000000000000L; // 10^14
// final long NOTRADE = 1000000000L; // replaced by nonTradeCost
final long UNIT = 1L;
int ITEMS; // the number of items being traded (including dummy items)
int DUMMY_ITEMS; // the number of dummy items
String[] deleteFirst(String[] a) {
assert a.length > 0;
String[] b = new String[a.length-1];
for (int i = 0; i < b.length; i++) b[i] = a[i+1];
return b;
}
void buildGraph(List< String[] > wantLists) {
HashMap< String,Integer > unknowns = new HashMap< String,Integer >();
// create the nodes
for (int i = 0; i < wantLists.size(); i++) {
String[] list = wantLists.get(i);
assert list.length > 0; // Every array of strings should be a formatted want list
String name = list[0]; // The item to be traded (whose wants are specified here)
String user = null;
int offset = 0; // Note: this is unused
// Check whether a name is present as the first string
if (name.charAt(0) == '(') {
user = name.replaceAll("#"," "); // restore spaces in username
list = deleteFirst(list); // remove the username from the list
// was Arrays.copyOfRange(list,1,list.length);
// but that caused problems on Macs
wantLists.set(i,list);
name = list[0]; // set the current item to be traded to the next string
}
// Check whether this item is a dummy item
boolean isDummy = (name.charAt(0) == '%');
if (isDummy) {
if (user == null)
errors.add("**** Dummy item " + name + " declared without a username.");
else if (!allowDummies)
errors.add("**** Dummy items not allowed. ("+name+")");
else {
name += " for user " + user;
list[0] = name;
}
}
// Check whether the item exists in the list of official item names, if present
if (officialNames != null && !officialNames.contains(name) && name.charAt(0) != '%') {
errors.add("**** Cannot define want list for "+name+" because it is not an official name. (Usually indicates a typo by the item owner.)");
wantLists.set(i,null);
}
else if (graph.getVertex(name) != null) {
errors.add("**** Item " + name + " has multiple want lists--ignoring all but first. (Sometimes the result of an accidental line break in the middle of a want list.)");
wantLists.set(i, null);
}
else {
ITEMS++; // increment the number of items being offered
if (isDummy) DUMMY_ITEMS++; // keep track of how many offered items are dummy items
// Add sender and receiver vertices (nodes) to the graph
Graph.Vertex vertex = graph.addVertex(name,user,isDummy);
// Mark this item's name as added to the graph
if (officialNames != null && officialNames.contains(name))
usedNames.add(name);
// Keep track of the longest name+entry length for output formatting purposes
if (!isDummy) width = Math.max(width, show(vertex).length());
}
}
// Create the edges
for (String[] list : wantLists) {
if (list == null) continue; // skip the duplicate lists
String fromName = list[0];
Graph.Vertex fromVertex = graph.getVertex(fromName);
// Add the "no-trade" edge to itself (from receiver to sender node)
graph.addEdge(fromVertex,fromVertex.twin,nonTradeCost);
// Evaluate each want for this item
long rank = 1;
for (int i = 1; i < list.length; i++) {
String toName = list[i]; // focus on this want
// A single semicolon represents a large step in rank value between
// two items
if (toName.equals(";")) {
rank += bigStep;
continue;
}
// Perform entry error checking on the current want
if (toName.indexOf('=') >= 0) {
// Handle explicit priorities (e.g., ThisWant=100)
if (priorityScheme != EXPLICIT_PRIORITIES) {
errors.add("**** Cannot use '=' annotation in item "+toName+" in want list for item "+fromName+" unless using EXPLICIT_PRIORITIES.");
continue;
}
if (!toName.matches("[^=]+=[0-9]+")) {
errors.add("**** Item "+toName+" in want list for item "+fromName+" must have the format 'name=number'.");
continue;
}
String[] parts = toName.split("=");
assert(parts.length == 2);
long explicitCost = Long.parseLong(parts[1]);
if (explicitCost < 1) {
errors.add("**** Explicit priority must be positive in item "+toName+" in want list for item "+fromName+".");
continue;
}
rank = explicitCost;
toName = parts[0];
}
// Handle dummy items
if (toName.charAt(0) == '%') {
// Make sure this item has an associated username if it wants a dummy item
if (fromVertex.user == null) {
errors.add("**** Dummy item " + toName + " used in want list for item " + fromName + ", which does not have a username.");
continue;
}
// Append the username to the dummy item to prevent confusion in cases
// where multiple users have dummy items with the same name.
toName += " for user " + fromVertex.user;
}
Graph.Vertex toVertex = graph.getVertex(toName); // grab the vertex (node) for this want
if (toVertex == null) {
if (officialNames != null && officialNames.contains(toName)) {
// this is an official item whose owner did not submit a want list
rank += smallStep;
}
else {
// there is no offical item list; track number of uknown items
int occurrences = unknowns.containsKey(toName) ? unknowns.get(toName) : 0;
unknowns.put(toName,occurrences + 1);
}
continue;
}
toVertex = toVertex.twin; // adjust to the sending vertex
if (toVertex == fromVertex.twin) {
errors.add("**** Item " + toName + " appears in its own want list.");
}
else if (graph.getEdge(fromVertex,toVertex) != null) {
if (showRepeats)
errors.add("**** Item " + toName + " is repeated in want list for " + fromName + ".");
}
else if (!toVertex.isDummy &&
fromVertex.user != null &&
fromVertex.user.equals(toVertex.user)) {
errors.add("**** Item "+fromVertex.name +" contains item "+toVertex.name+" from the same user ("+fromVertex.user+")");
}
else {
long cost = UNIT;
switch (priorityScheme) {
case LINEAR_PRIORITIES: cost = rank; break;
case TRIANGLE_PRIORITIES: cost = rank*(rank+1)/2; break;
case SQUARE_PRIORITIES: cost = rank*rank; break;
case SCALED_PRIORITIES: cost = rank; break; // assign later
case EXPLICIT_PRIORITIES: cost = rank; break;
}
// All edges out of a dummy node have the same cost because
// they are usually considered to be the same item for
// duplicate protection.
if (fromVertex.isDummy) cost = nonTradeCost;
// Add a connection from the listed item's receiver node to
// the wanted item's sender node.
graph.addEdge(fromVertex,toVertex,cost);
// Increase the rank for calculating the priority of the next want
rank += smallStep;
}
}
// Update costs for those priority schemes that need information such as
// number of wants
if (!fromVertex.isDummy) {
switch (priorityScheme) {
case SCALED_PRIORITIES:
int n = fromVertex.edges.size()-1;
for (Graph.Edge edge : fromVertex.edges) {
if (edge.sender != fromVertex.twin)
edge.cost = 1 + (edge.cost-1)*2520/n;
}
break;
}
}
}
// "Freeze" the graph, declaring that we have finished adding things to it
// and readying it for cleanup and analysis
graph.freeze();
// If any unknown items were added as wants, display those to the user now
for (Map.Entry< String,Integer > entry : unknowns.entrySet()) {
String item = entry.getKey();
int occurrences = entry.getValue();
String plural = occurrences == 1 ? "" : "s";
errors.add("**** Unknown item " + item + " (" + occurrences + " occurrence" + plural + ")");
}
} // end buildGraph
String show(Graph.Vertex vertex) {
if (vertex.user == null || vertex.isDummy) return vertex.name;
else if (sortByItem) return vertex.name + " " + vertex.user;
else return vertex.user + " " + vertex.name;
}
//////////////////////////////////////////////////////////////////////
void displayMatches(List<List<Graph.Vertex>> cycles) {
int numTrades = 0;
int numGroups = cycles.size();
int totalCost = 0;
int sumOfSquares = 0;
List< Integer > groupSizes = new ArrayList< Integer >();
List< String > summary = new ArrayList< String >();
List< String > loops = new ArrayList< String >();
for (List<Graph.Vertex> cycle : cycles) {
int size = cycle.size();
numTrades += size;
sumOfSquares += size*size;
groupSizes.add(size);
for (Graph.Vertex v : cycle) {
assert v.match != v.twin;
loops.add(pad(show(v)) + " receives " + show(v.match.twin));
summary.add(pad(show(v)) + " receives " + pad(show(v.match.twin)) + " and sends to " + show(v.twin.match));
totalCost += v.matchCost;
}
loops.add("");
}
if (showNonTrades) {
for (Graph.Vertex v : graph.RECEIVERS) {
if (v.match == v.twin && !v.isDummy)
summary.add(pad(show(v)) + " does not trade");
}
for (Graph.Vertex v : graph.orphans) {
if (!v.isDummy)
summary.add(pad(show(v)) + " does not trade");
}
}
if (showLoops) {
System.out.println("TRADE LOOPS (" + numTrades + " total trades):");
System.out.println();
for (String item : loops) System.out.println(item);
}
if (showSummary) {
Collections.sort(summary);
System.out.println("ITEM SUMMARY (" + numTrades + " total trades):");
System.out.println();
for (String item : summary) System.out.println(item);
System.out.println();
}
System.out.print("Num trades = " + numTrades + " of " + (ITEMS-DUMMY_ITEMS) + " items");
if (ITEMS-DUMMY_ITEMS == 0) System.out.println();
else System.out.println(new DecimalFormat(" (0.0%)").format(numTrades/(double)(ITEMS-DUMMY_ITEMS)));
if (showStats) {
System.out.print("Total cost = " + totalCost);
if (numTrades == 0) System.out.println();
else System.out.println(new DecimalFormat(" (avg 0.00)").format(totalCost/(double)numTrades));
System.out.println("Num groups = " + numGroups);
System.out.print("Group sizes =");
Collections.sort(groupSizes);
Collections.reverse(groupSizes);
for (int groupSize : groupSizes) System.out.print(" " + groupSize);
System.out.println();
System.out.println("Sum squares = " + sumOfSquares);
// System.out.println("Orphans = " + graph.orphans.size());
}
}
// Keep track of name widths for formatting purposes
int width = 1;
// Pad a name with trailing spaces so they align nicely
String pad(String name) {
while (name.length() < width) name += " ";
return name;
}
} // end TradeMaximizer