summaryrefslogtreecommitdiff
path: root/flood.go
blob: c741bd618b97e440d110633bdb4279d629b86cb0 (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
package main

import (
	"math"
	"sort"
	"strings"
	"unicode/utf8"
)

const (
	runes = 6
	words = 6
)

func entropy(s string) (e float64) {
	n := make(map[rune]float64)
	for _, r := range s {
		n[r] += 1 / float64(len(s))
	}
	for _, v := range n {
		e -= v * math.Log2(v)
	}
	return e
}

func isFlood(s string) bool {
	if utf8.RuneCountInString(s) <= runes {
		return false
	}
	if v := strings.Fields(s); len(v) >= words {
		return commonWord(v) >= len(v)/2
	}
	return entropy(s) <= 1
}

func commonWord(v []string) int {
	m := make(map[string]int)
	for _, w := range v {
		m[w]++
	}
	l := make([]int, len(m))
	for _, n := range m {
		l = append(l, n)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(l)))
	return l[0]
}