Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathGenerateCodeTable.java
More file actions
Latest commit
510 lines (465 loc) · 20.3 KB
/
Copy pathGenerateCodeTable.java
File metadata and controls
510 lines (465 loc) · 20.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
importjava.io.*;
importjava.util.*;
importjava.util.stream.*;
importjava.text.SimpleDateFormat;
/*
Used to generate table of contents.
- No args: generate GitHub table
- args == 'wordpress', generate WordPress table.
- args == 'review', generate Review Page
- args == 'all', genereate both table
*/
publicclassGenerateCodeTable {
privatestaticStringGIT_HUB_LINK = "https://github.com/awangdev/LintCode/blob/master/Java/";
privatestaticStringNOT_AVAILABLE = "N/A";
privatestaticStringLINTCODE_TOKEN = "[lint]";
privatestaticStringTOOL_TOKEN = "[tool]";
privatestaticSimpleDateFormatDATE_FORMAT = newSimpleDateFormat("yyyy-MM-dd");
/*
TableRow, used to hold table object and sort by date.
*/
privatestaticclassTableRow {
privatelongdate = 0;
privateStringfileName;
privateStringlevel;
privateStringtutorialLink;
privateStringtimeComplexity;
privateStringspaceComplexity;
privateStringnote;
privateList<String> tags;
publicTableRow(
longdate,
StringfileName,
Stringlevel,
StringtutorialLink,
StringtimeComplexity,
StringspaceComplexity,
Stringnote,
List<String> tags) {
this.date = date;
this.fileName = fileName;
this.level = level;
this.timeComplexity = timeComplexity;
this.spaceComplexity = spaceComplexity;
this.tutorialLink = tutorialLink;
this.note = note;
this.tags = tags;
}
publicStringgetLeetcodeNum() {
String[] fileNameArr = fileName.split("\\.");
if (LINTCODE_TOKEN.equals(fileNameArr[0].toLowerCase())) {
returnLINTCODE_TOKEN;
}
if (TOOL_TOKEN.equals(fileNameArr[0].toLowerCase())) {
returnTOOL_TOKEN;
}
try {
Integer.parseInt(fileNameArr[0]);
returnfileNameArr[0];
} catch(Exceptione) {
returnNOT_AVAILABLE;
}
}
publiclonggetDate() {
returnthis.date;
}
publicStringgetFileName() {
returnthis.fileName;
}
publicStringgetLevel() {
returnthis.level;
}
publicStringgetTutorialLink() {
returnthis.tutorialLink;
}
publicStringgetNote() {
returnthis.note;
}
publicList<String> getTags() {
returnthis.tags;
}
publicStringgetTableComposedLine(inti) {
Datedate = newDate(this.date);
return"|" + this.getLeetcodeNum() + "|[" + this.fileName + "](" + GIT_HUB_LINK + fileName.replace(" ", "%20")
+ ")|" + this.level + "|" + this.tags + "|" + this.timeComplexity + "|" + this.spaceComplexity + "|Java|" + i + "|\n";
}
}
publicstaticStringTUTORIAL_KEY_WORD = "tutorial:";
publicstaticStringTAGS_KEY_WORD = "tags:";
publicstaticStringTIME_KEY_WORD = "time:";
publicstaticStringSPACE_KEY_WORD = "space:";
publicstaticvoidmain(String[] args) {
GenerateCodeTablegct = newGenerateCodeTable();
//Read Java Solution Folder
Filefolder = newFile("./Java");//"." = current path
if (!folder.exists() || !folder.isDirectory()) {
System.out.println("Check Directory:1");
return;
}
File[] listOfFiles = folder.listFiles();
if (listOfFiles == null) {
System.out.println("Check Directory:2");
return;
}
StringoutputContent = "";
FileoutFile;
if (args.length == 0){
outputContent = gct.generateREADME(listOfFiles);
gct.printTable("README.md", outputContent);
} elseif (args != null && args[0].contains("wordpress")) {//Wordpress
outputContent = gct.generateWordPressPage(listOfFiles);
gct.printTable("WordPress.txt", outputContent);
} elseif (args != null && args[0].contains("review")) {//Review Page
outputContent = gct.generateReviewPage(listOfFiles);
gct.printTable("ReviewPage.md", outputContent);
} elseif (args != null && args[0].contains("tags")) {//Wordpress
outputContent = gct.generateTagREADME(listOfFiles);
gct.printTable("TagREADME.md", outputContent);
} elseif (args != null && args[0].contains("all")) {
outputContent = gct.generateREADME(listOfFiles);
gct.printTable("README.md", outputContent);
//outputContent = generateWordPressPage(listOfFiles);
//printTable("WordPress.txt", outputContent);
outputContent = gct.generateReviewPage(listOfFiles);
gct.printTable("ReviewPage.md", outputContent);
outputContent = gct.generateTagREADME(listOfFiles);
gct.printTable("TagREADME.md", outputContent);
outputContent = gct.generateTagReviewPage(listOfFiles);
gct.printTable("TagReviewPage.md", outputContent);
outputContent = gct.generateLevelReviewPage(listOfFiles);
gct.printTable("LevelReviewPage.md", outputContent);
}
System.out.println("Mission Accomplished. Now go ahead and commit");
}
/*
Output the content into file
*/
publicvoidprintTable(StringfileName, StringoutputContent) {
//System.out.println(outputContent);
//Write to README.md
try {
FileoutFile = newFile(fileName);
FileOutputStreamfop = newFileOutputStream(outFile);
byte[] contentInBytes = outputContent.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
} catch (IOExceptione) {
e.printStackTrace();
}
}
/*
Generate Wordpress contents
*/
publicStringgenerateWordPressPage(File[] listOfFiles) {
//Assemble output
StringoutputContent = "Java Solutions to algorithm problems from LintCode, LeetCode...etc.\n" +
"<table>" +
"<thead>" +
"<tr>" +
"<th align='center'>#</th>" +
"<th align='left'>Problem</th>" +
"<th align='center'> Language</th>" +
"</tr>" +
"</thead>" +
"<tbody>";
intcount = 0;
for (Filefile : listOfFiles) {
if (file.getName().contains(".java")) {
outputContent+=
"<tr>" +
"<td align='center'>" + count + "</td>" +
"<td align='left'><a href='" + GIT_HUB_LINK + file.getName() + "'>" + file.getName() + "</a></td>" +
"<td align='center'>Java</td>" +
"</tr>";
count++;
}
}
outputContent += "</tbody></table>";
returnoutputContent;
}
/*
Generate GitHub README contents
*/
publicStringgenerateREADME(File[] listOfFiles) {
//Assemble output
StringoutputContent = "# Java Algorithm Problems\n\n" +
"| Leetcode# | Problem | Level | Tags | Time | Space | Language | Sequence |\n" +
"|:---------:|:------------|:------:|:----:|-----:|------:|:--------:|---------:|\n";
List<TableRow> tableRows = getTableRows(listOfFiles);
for (inti = 0; i < tableRows.size(); i++) {
outputContent += tableRows.get(i).getTableComposedLine(i);
}
returnoutputContent;
}
/* Generate the tags Table*/
publicStringgenerateTagREADME(File[] listOfFiles) {
StringoutputContent = generateTableOfContent("TagREADME.md") + "\n\n";
Stringheader = "| Leetcode# | Problem | Level | Tags | Time | Space | Language | Sequence |\n" +
"|:---------:|:------------|:------:|:----:|-----:|------:|:--------:|---------:|\n";
List<TableRow> tableRows = getTableRows(listOfFiles);
Map<String, List<TableRow>> tagToRows = newHashMap<>();
tableRows.forEach(tableRow -> {
for (Stringtag: tableRow.getTags()) {
if (tag == null || tag.length() == 0) {
continue;
}
if (!tagToRows.containsKey(tag)) {
tagToRows.put(tag, newArrayList<TableRow>());
}
tagToRows.get(tag).add(tableRow);
}
});
// Build View
List<Map.Entry<String, List<TableRow>>> entries = newArrayList<>(tagToRows.entrySet());
entries.sort(Comparator.comparing(entry -> -entry.getValue().size()));
for (Map.Entry<String, List<TableRow>> entry : entries) {
StringBuffersb = newStringBuffer(" \n\n\n## " + entry.getKey() + " (" + entry.getValue().size() + ")\n");
sb.append(header);
List<TableRow> entryTableRows = entry.getValue();
entryTableRows.sort(Comparator.comparing(row -> String.join(",", row.getTags())));
for (inti = 0; i < entryTableRows.size(); i++) {
sb.append(entryTableRows.get(i).getTableComposedLine(i));
}
outputContent += sb.toString() + "\n\n\n";
}
returnoutputContent;
}
// Generate review files by tags
publicStringgenerateTagReviewPage(File[] listOfFiles) {
List<TableRow> tableRows = getTableRows(listOfFiles);
Map<String, List<TableRow>> tagToRows = newHashMap<>();
// Group by tags:
tableRows.forEach(tableRow -> {
for (Stringtag: tableRow.getTags()) {
if (tag == null || tag.length() == 0) {
continue;
}
if (!tagToRows.containsKey(tag)) {
tagToRows.put(tag, newArrayList<TableRow>());
}
tagToRows.get(tag).add(tableRow);
}
});
// Build View
StringoutputContent = "";
for (Map.Entry<String, List<TableRow>> entry : tagToRows.entrySet()) {
StringBuffersb = newStringBuffer(" \n\n\n## " + entry.getKey() + " (" + entry.getValue().size() + ")\n");
sb.append(buildReviewSection(entry.getValue()));
outputContent += sb.toString() + "\n\n\n";
printTable("review/" + entry.getKey() + ".md", sb.toString());
}
returnoutputContent;
}
// Generate review files by levels
publicStringgenerateLevelReviewPage(File[] listOfFiles) {
List<TableRow> tableRows = getTableRows(listOfFiles);
Map<String, List<TableRow>> levelToRows = newHashMap<>();
// Group by levels:
tableRows.forEach(tableRow -> {
Stringlevel = tableRow.getLevel();
if (NOT_AVAILABLE.equals(tableRow.getLevel())) {
level = "NA";
}
if (!levelToRows.containsKey(level)) {
levelToRows.put(level, newArrayList<TableRow>());
}
levelToRows.get(level).add(tableRow);
});
// Build View
StringoutputContent = "";
for (Map.Entry<String, List<TableRow>> entry : levelToRows.entrySet()) {
StringBuffersb = newStringBuffer(" \n\n\n## " + entry.getKey() + " (" + entry.getValue().size() + ")\n");
sb.append(buildReviewSection(entry.getValue()));
outputContent += sb.toString() + "\n\n\n";
printTable("review/level/" + entry.getKey() + ".md", sb.toString());
}
returnoutputContent;
}
/*
Generate Review Page contents
Review Page content:
1. Sequence
2. Name
3. Difficulty
4. Summary of solution, key points.
*/
publicStringgenerateReviewPage(File[] listOfFiles) {
//Assemble output
StringoutputContent = "# Review Page\n\n" +
"This page summarize the solutions of all problems. For thoughts,ideas written in English, refer to deach individual solution. \n" +
"New problems will be automatically updated once added.\n\n";
List<TableRow> tableRows = getTableRows(listOfFiles);
intcount = 0;
intcountMiss = 0;
outputContent += buildReviewSection(tableRows);
returnoutputContent;
}
privateStringbuildReviewSection(List<TableRow> tableRows) {
intcount = 0;
intcountMiss = 0;
StringBuffersb = newStringBuffer();
for (TableRowtableRow: tableRows) {
// Skip non-ready items
if (NOT_AVAILABLE.equals(tableRow.getLevel())) {
System.out.println(countMiss + ". [File not yet formatted]: " + tableRow.getFileName() + " [Skipping. Please revisit]");
countMiss++;
continue;
}
//System.out.println(count + ". " + tableRow.getLevel() + " [File not yet formatted]: " + tableRow.getFileName());
sb.append("**" + count + ". [" + tableRow.getFileName());
sb.append("](" + GIT_HUB_LINK);
sb.append(tableRow.getFileName().replace(" ", "%20") +")**");
sb.append(" Level: " + tableRow.getLevel() + " Tags: " + tableRow.getTags() + "\n");
sb.append(" " + tableRow.getTutorialLink() + "\n");
sb.append(tableRow.getNote() + "\n");
sb.append("\n---\n\n");
count++;
}
returnsb.toString();
}
privateList<TableRow> getTableRows(File[] listOfFiles) {
List<TableRow> tableRows = newArrayList<>();
for (Filefile : listOfFiles) {
if (file.getName().contains(".java")) {
tableRows.add(getTableRow(file.getName()));
}
}
List<TableRow> nonProcessedRows = tableRows.stream()
.filter(tableRow -> tableRow.getLeetcodeNum().equals(NOT_AVAILABLE))
.collect(Collectors.toList());
List<TableRow> processedLeetCodeRows = tableRows.stream()
.filter(tableRow -> !tableRow.getLeetcodeNum().equals(NOT_AVAILABLE)
&& !tableRow.getLeetcodeNum().equals(LINTCODE_TOKEN) && !tableRow.getLeetcodeNum().equals(TOOL_TOKEN)
)
.collect(Collectors.toList());
List<TableRow> processedLintCodeRows = tableRows.stream()
.filter(tableRow -> tableRow.getLeetcodeNum().equals(LINTCODE_TOKEN))
.collect(Collectors.toList());
List<TableRow> processedToolCodeRows = tableRows.stream()
.filter(tableRow -> tableRow.getLeetcodeNum().equals(TOOL_TOKEN))
.collect(Collectors.toList());
Collections.sort(processedLeetCodeRows, Comparator.comparing(TableRow::getDate));
Collections.sort(processedLintCodeRows, Comparator.comparing(TableRow::getDate));
System.out.println("Non Reviewed Problems: " + nonProcessedRows.size()
+ ", Reviewed LeetCode Problems: " + processedLeetCodeRows.size()
+ ", Reviewed LintCode Problems: " + processedLintCodeRows.size());
List<TableRow> output = newArrayList<>();
output.addAll(nonProcessedRows);
output.addAll(processedLintCodeRows);
output.addAll(processedToolCodeRows);
output.addAll(processedLeetCodeRows);
returnoutput;
}
privateTableRowgetTableRow(StringfileName) {
TableRowtableRow = null;
StringtutorialLink = "";
StringcalculatedLevel = NOT_AVAILABLE;
StringtimeComplexity = "";
StringspaceComplexity = "";
longtimestamp = 0;
List<String> tags = newArrayList<>();
// get timestamp of file
Filefile = newFile("Java/" + fileName);
timestamp = file.lastModified();
try {
BufferedReaderreader = newBufferedReader(newInputStreamReader(
newFileInputStream("Java/" + fileName), "UTF-8"));
// Get level
Stringline = reader.readLine().trim();
if (line.length() == 1 && !calculateLevel(line).isEmpty()){
calculatedLevel = calculateLevel(line.toUpperCase());
line = reader.readLine().trim();
}
// TODO: remove the legacy timestamp.
// Below are existing logic to parse timestamp. Remove when all timestamp is cleaned up.
if (line.length() != 0) {
try{
Long.parseLong(line);
line = reader.readLine().trim();
} catch(Exceptione){ }
}
// Get tutorial
if (line.contains(TUTORIAL_KEY_WORD)) {
tutorialLink = "[Link](" + line.substring(TUTORIAL_KEY_WORD.length()) + ")";
line = reader.readLine().trim();
}
// Get Tags
if (line.contains(TAGS_KEY_WORD)) {
// Do something
StringtagLine = line.substring(TAGS_KEY_WORD.length());
for (Stringtag : tagLine.split(",")) {
tags.add(tag.trim());
}
Collections.sort(tags);
line = reader.readLine().trim();
}
// Get Time
if (line.contains(TIME_KEY_WORD)) {
timeComplexity = line.substring(6).trim(); // "time:"
line = reader.readLine().trim();
}
// Get Space
if (line.contains(SPACE_KEY_WORD)) {
spaceComplexity = line.substring(7).trim(); // "space:"
}
// Get Note
Stringnote = "";
while ((line = reader.readLine()) != null && !line.equals("```") && !line.equals("/*")) {
note += line + "\n";
}
// Get result
tableRow = newTableRow(timestamp, fileName, calculatedLevel, tutorialLink, timeComplexity, spaceComplexity, note, tags);
} catch (Exceptione) {
System.err.format("IOException: %s%n. Filename: %s", e, fileName);
}
returntableRow;
}
privateStringcalculateLevel(Stringlevel) {
switch(level) {
case"N" :
return"Naive";
case"E" :
return"Easy";
case"M" :
return"Medium";
case"H" :
return"Hard";
case"S" :
return"Super";
case"R" :
return"Review";
}
returnNOT_AVAILABLE;
}
// Build the table of contents of the page. Need to have 'gh-md-toc' installed
privateStringgenerateTableOfContent(StringfileName) {
StringBuffersb = newStringBuffer();
try {
Runtimert = Runtime.getRuntime();
String[] commands = {"./gh-md-toc", fileName};
Processproc = rt.exec(commands);
BufferedReaderstdInput = newBufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReaderstdError = newBufferedReader(new
InputStreamReader(proc.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
Strings = null;
while ((s = stdInput.readLine()) != null) {
if (!s.contains("[gh-md-toc]") && !s.contains("table-of-contents")) {
sb.append(s.trim() + "\n");
}
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (Exceptione) {
System.err.format("IOException: %s%n", e);
}
System.out.println(sb.toString());
returnsb.toString();
}
}