Skip to content

Instantly share code, notes, and snippets.

@yurivish
Created October 19, 2014 16:08
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save yurivish/e20a803e5c3fa101a8aa to your computer and use it in GitHub Desktop.
window._d = window.d = console?.log.bind(console) ? ->
randUpTo = (num) -> ~~(num * Math.random())
randIndex = (arr) -> randUpTo(arr.length)
randEntry = (arr) -> arr[randIndex(arr)]
d3.text 'data/aphorisms.txt', (err, text) ->
throw err if err
lines = text.split('\n')
wordsByLine = lines.map (line) -> line.split(' ')
tokensByLine = wordsByLine.map (words) -> words.map (word) -> word.toLowerCase()
db = { }
for tokens, lineIndex in tokensByLine
for token in tokens
db[token] ?= [ ]
db[token].push lineIndex
generate = ->
startIndex = endIndex = randIndex tokensByLine
attempts = 0
while startIndex == endIndex && attempts < 10
joinToken = randEntry tokensByLine[startIndex]
endIndex = randEntry db[joinToken]
attempts++
if attempts == 10 then return
startTokens = tokensByLine[startIndex]
startWords = wordsByLine[startIndex]
endTokens = tokensByLine[endIndex]
endWords = wordsByLine[endIndex]
# d startTokens, endTokens, joinToken
result =
startTokens[...startTokens.lastIndexOf(joinToken)].join(' ') +
' ' +
endTokens[endTokens.indexOf(joinToken)..].join(' ')
result
d generate() for i in [1..1000]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment