-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontact4.js
100 lines (79 loc) · 2.17 KB
/
contact4.js
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
'use strict';
// https://www.hackerrank.com/challenges/contacts/problem
const fs = require('fs');
const { finished } = require('stream');
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
const value = ''
/*
* Complete the contacts function below.
*/
class Node {
constructor() {
this.children = {}
this.words_in_subtree = 0
}
}
function insert(new_name, contacts) {
let current_position = contacts
for (let index in new_name) {
let letter = new_name[index]
if (!current_position.children[letter]) {
current_position.children[letter] = new Node()
}
current_position.children[letter].words_in_subtree += 1
current_position = current_position.children[letter]
}
}
function search(search_term, contacts) {
let current_position = contacts
for (let index in search_term) {
let letter = search_term[index]
if (!current_position.children[letter]) {
return 0
}
current_position = current_position.children[letter]
}
return current_position.words_in_subtree
}
function contacts(queries, ops) {
let number_of_operations = ops
let root = new Node()
let results = []
for (let x = 0; x < number_of_operations; x++) {
const command = queries[x][0]
const value = queries[x][1]
if (command === 'add') {
insert(value, root)
} else if (command === 'find') {
//console.log('find', value)
//console.log(root)
let sum = search(value, root)
results.push(sum)
console.log(sum)
}
}
// console.log(trie)
// console.log('cache', cache)
return results
}
//////
/**
* nui1
* nui2
* nui
// se chave do map comecar com value procurado
// se o valor procurado.lenght < que chave do Map atual.length
// entao soma é igual a soma de todos os values de todas as chaves que comecam com o valor procurado
*/
let reader = fs.createReadStream('input01.txt');
reader.on('data', function (chunk) {
inputString += chunk.toString()
});
reader.on("end", () => {
inputString = inputString.trim().split('\n').map(str => str.trim().split(" "))
let ops = inputString.shift()
const result = contacts(inputString, ops)
process.exit(0)
});