aboutsummaryrefslogtreecommitdiff
path: root/challenge-005/zapwai/javascript/ch-2.js
blob: 07ba52c4c28e96f6e488a8f9de20a7cd82ce7c11 (plain)
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
let dict;

const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', handleFileUpload);

const ourParagraph = document.getElementById('ourParagraph');

function handleFileUpload(event) {
    const file = event.target.files[0];
    if (!file) {
	console.error('No file selected');
	return;
    }
    const reader = new FileReader();
    reader.onload = function(e) {
	const content = e.target.result;
	const words = content.split(/\s+/);
	dict = words;
	mostAnagrams();
    };	
    reader.readAsText(file);    
}

function mostAnagrams() {
    let sorted = dict.slice();
    sorted.forEach( (w, i) => {
	sorted[i] = w.split('').sort().join("");
    });
    sorted.sort();

    let maxnum = 0;
    let maxword = "";

    let flag = 0;
    let cnt = 0;
    for (let i = 0; i < sorted.length; i++) {
	if (flag == 1) {
	    if (sorted[i+1] != sorted[i]) {
		flag = 0;
		cnt += 1;
		if (maxnum < cnt) {
		    maxnum = cnt;
		    maxword = sorted[i];
		}
		cnt = 0;
	    }
	    cnt += 1;
	} else {
	    if (sorted[i + 1] == sorted[i]) {
		cnt += 1;
		flag = 1;
	    }
	}
    }
    
    ourParagraph.innerHTML =
	`Max number of anagrams: ${maxnum}<br>
Characters: ${maxword}<br>`;
}