-
Notifications
You must be signed in to change notification settings - Fork 2
/
random-surfer.ts
98 lines (76 loc) · 2.01 KB
/
random-surfer.ts
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
// Randomly surfs web pages to discover the probability of finding certain pages
// in a network.
import { randomItem } from "./random-item.js"
export class Page {
readonly name: string
readonly links: Page[] = []
constructor(name: string) {
this.name = name
}
linkTo(...others: Page[]) {
for (const other of others) {
if (!this.links.includes(other)) {
this.links.push(other)
}
}
}
randomLink(): Page | undefined {
return randomItem(this.links)
}
}
const a = new Page("A")
const b = new Page("B")
const c = new Page("C")
const d = new Page("D")
const e = new Page("E")
a.linkTo(b, c)
b.linkTo(d, e)
c.linkTo(a, d, c)
e.linkTo(a, c, b)
d.linkTo(b)
export function surf(pages: readonly [Page, ...Page[]], iterations: number) {
let current = randomItem(pages)
for (; iterations > 0; iterations--) {
const next = current.randomLink()
if (next) {
current = next
} else {
current = randomItem(pages)
}
}
return current
}
export function repeatedlySurf(
pages: readonly [Page, ...Page[]],
iterations: number,
count: number,
) {
const output: Record<string, number> = Object.create(null)
for (; count > 0; count--) {
const final = surf(pages, iterations)
output[final.name] = (output[final.name] ?? 0) + 1
}
return output
}
export function alternateSurf(start: Page, iterations: number) {
const scores: Record<string, number> = Object.create(null)
let current = start
for (; iterations > 0; iterations--) {
const next = current.randomLink()
if (next) {
current = next
} else {
throw new Error("All pages must have at least one outgoing link.")
}
scores[current.name] = (scores[current.name] ?? 0) + 1
}
return Object.fromEntries(
Object.entries(scores).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),
)
}
export function normalize(scores: Record<string, number>, size: number) {
for (const key in scores) {
scores[key] = Math.round(scores[key]! / size)
}
return scores
}