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

import (
	"math"
	"sort"
	"strings"
	"unicode"
	"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]
}

func noSpaceCompare(a, b string) bool {
	dropSpaces := func(r rune) rune {
		if unicode.IsSpace(r) {
			return -1
		}
		return r
	}
	return strings.Map(dropSpaces, a) == strings.Map(dropSpaces, b)
}