Created
July 21, 2013 22:38
-
-
Save homelinen/6050285 to your computer and use it in GitHub Desktop.
Simple Implementation of Chinese Whispers. Supports varying iterations and percent change.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Chinese Whispers | |
# | |
# author: Calum Gilchrist | |
# | |
# Experiment to distort a string based on the number of nodes between the | |
# sender and recipient | |
# | |
require 'raspell' | |
require 'optparse' | |
# Take a string and return a malformed string | |
# | |
# Each word in the string has a percentage chance of being replaced with a | |
# similar word. | |
# | |
# str - Input string | |
# percent - (float) How often the word is altered | |
# | |
# Example: | |
# pass_and_receive('There's a sniper over the top of the hill.', 0.05) | |
# => 'There a sander over the top's of the hill.' | |
# Returns a string that might not be quite the same as the original | |
def pass_and_receive(str, percent) | |
speller = Aspell.new("en_GB") | |
speller.suggestion_mode = Aspell::NORMAL | |
words = str.split | |
trans_words = [] | |
rand = Random.new | |
words.each do |word| | |
if rand.rand > percent | |
trans_words.push word | |
else | |
# Use a suggested word as a replacement | |
suggested = speller.suggest(word) | |
trans_words.push suggested.sample | |
end | |
end | |
new_str = trans_words.join ' ' | |
end | |
options = {} | |
OptionParser.new do |opts| | |
opts.banner = 'Usage: chinese-whsipers.rb string [-p PERCENT]' | |
options[:percent] = 0.05 | |
opts.on('-p', '--percent PERCENT', 'Percent word transformation') do |percent| | |
options[:percent] = percent.to_f / 100 | |
end | |
options[:count] = 9 | |
opts.on('-c', '--count COUNT', 'Number of Iterations') do |count| | |
# Subtract 1 for counting from 0 | |
options[:count] = count.to_i - 1 | |
end | |
end.parse! | |
if ARGV.empty? | |
puts "Not enough arguments" | |
exit(2) | |
end | |
message = ARGV.join ' ' | |
(0..options[:count]).each do |i| | |
puts message | |
message = pass_and_receive(message, options[:percent]) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment