-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBigram.js
104 lines (89 loc) · 2.73 KB
/
Bigram.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
101
102
103
104
BigramNetwork = function(){
this.nodeList = [];
this.cursor = null;
}
BigramNetwork.prototype.getNodeByValue = function(value){
var result = null;
for(var i = 0; i < this.nodeList.length; i++){
var aNode = this.nodeList[i];
if(aNode.value === value){
result = aNode;
break;
}
}
if(result == null){
result = new BigramNode(value, this);
this.nodeList.push(result);
}
return result;
}
BigramNetwork.prototype.buildNetworkUsingDataStringAndSeparator = function(dataString, separator){
var valueArray = dataString.split(separator);
this.buildNetworkUsingValueArray(valueArray);
}
BigramNetwork.prototype.buildNetworkUsingValueArray = function(valueArray){
for(var i = 0; i < valueArray.length; i++){
var aValue = valueArray[i];
if(this.cursor == null){
this.cursor = this.getNodeByValue(aValue);
}else{
this.cursor = this.cursor.addValueConnection(aValue);
}
}
//Returning cursor to the first node
this.cursor = this.nodeList[0];
}
BigramNode = function(value, network){
this.value = value;
this.connectionList = [];
this.totalConnectionWeight = 0;
this.network = network;
}
BigramNode.prototype.addValueConnection = function(value){
this.totalConnectionWeight++;
//Getting node value
var nodeToAdd = this.network.getNodeByValue(value);
var isNodeFound = false;
for(var i = 0; i < this.connectionList.length; i++){
var aConnection = this.connectionList[i];
if(nodeToAdd == aConnection.node){
//connection found
aConnection.addWeight();
isNodeFound = true;
break;
}
}
if(isNodeFound == false){
var newConnection = new BigramConnection(nodeToAdd);
this.connectionList.push(newConnection);
}
return nodeToAdd;
}
BigramNode.prototype.getNextNode = function(){
var result = null;
if(this.totalConnectionWeight > 0){
var randomWeightValue = Math.floor(Math.random() * this.totalConnectionWeight + 1);
var currentWeightCounter = 0;
for(var i = 0; i < this.connectionList.length; i++){
var aConnection = this.connectionList[i];
currentWeightCounter += aConnection.weight;
if(randomWeightValue <= currentWeightCounter){
result = aConnection.node;
break;
}
}
}
return result;
}
BigramConnection = function(node){
this.node = node;
this.weight = 1;
}
BigramConnection.prototype.addWeight = function(){
this.weight++;
}
module.exports = {
BigramNetwork: BigramNetwork,
BigramNode: BigramNode,
BigramConnection: BigramConnection
}