scrabble_score 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,29 @@
1
+ require 'set'
2
+
3
+ module ScrabbleScore
4
+ class Dictionary
5
+ attr_reader :words
6
+
7
+ def initialize(words = nil)
8
+ @words = words.to_set and return unless words.nil?
9
+
10
+ load_words_from_dictionary
11
+ end
12
+
13
+ def contains(word)
14
+ @words.include?(word.downcase)
15
+ end
16
+
17
+ private
18
+
19
+ def load_words_from_dictionary
20
+ @words = Set.new
21
+ path = File.join(ScrabbleScore::ROOT, 'assets', 'dictionary.txt')
22
+ file = File.open(path, 'r')
23
+ file.each_line do |line|
24
+ @words.add(line.chomp)
25
+ end
26
+ file.close
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,39 @@
1
+ module ScrabbleScore
2
+ class Letters
3
+ TILE_VALUES = {
4
+ 'a' => 1, 'b' => 3, 'c' => 3, 'd' => 2, 'e' => 1, 'f' => 4,
5
+ 'g' => 2, 'h' => 4, 'i' => 1, 'j' => 8, 'k' => 5, 'l' => 1,
6
+ 'm' => 3, 'n' => 1, 'o' => 1, 'p' => 3, 'q' => 10, 'r' => 1,
7
+ 's' => 1, 't' => 1, 'u' => 1, 'v' => 4, 'w' => 4, 'x' => 8,
8
+ 'y' => 4, 'z' => 10
9
+ }
10
+
11
+ attr_reader :word
12
+
13
+ def initialize(word)
14
+ @word = Letters.cleanse(word)
15
+ end
16
+
17
+ def permutations
18
+ permutation_array = []
19
+ letter_array = @word.split(//)
20
+
21
+ (2..letter_array.size).each do |length|
22
+ letter_array.permutation(length).each do |perm|
23
+ permutation_array << perm.join
24
+ end
25
+ end
26
+ permutation_array.uniq
27
+ end
28
+
29
+ def score
30
+ score = 0
31
+ @word.downcase.each_char { |ch| score += TILE_VALUES[ch] }
32
+ score
33
+ end
34
+
35
+ def self.cleanse(word)
36
+ word.downcase.gsub(/[^a-z]/, '')
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,3 @@
1
+ module ScrabbleScore
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,23 @@
1
+ module ScrabbleScore
2
+ class WordFinder
3
+ def initialize(dictionary = ScrabbleScore::Dictionary.new)
4
+ @dictionary = dictionary
5
+ end
6
+
7
+ def search(letters)
8
+ permutations = ScrabbleScore::Letters.new(letters).permutations
9
+ permutations.select! { |perm| @dictionary.contains(perm) }
10
+ end
11
+
12
+ def search_with_score(letters)
13
+ found_words = search(letters)
14
+
15
+ hash = {}
16
+ found_words.each do |word|
17
+ hash[word] = ScrabbleScore::Letters.new(word).score
18
+ end
19
+
20
+ hash
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,8 @@
1
+ require 'scrabble_score/version'
2
+ require 'scrabble_score/letters'
3
+ require 'scrabble_score/dictionary'
4
+ require 'scrabble_score/word_finder'
5
+
6
+ module ScrabbleScore
7
+ ROOT = File.dirname(__dir__)
8
+ end
@@ -0,0 +1,24 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'scrabble_score/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'scrabble_score'
8
+ spec.version = ScrabbleScore::VERSION
9
+ spec.authors = ['Nick Aschenbach']
10
+ spec.email = ['nick.aschenbach@gmail.com']
11
+ spec.summary = %q{A scrabble cheater scoring library}
12
+ spec.description = %q{An engine that finds words from a set of letters and calculates the scrabble score}
13
+ spec.homepage = 'https://github.com/nick-aschenbach/scrabble-score'
14
+ spec.license = 'MIT'
15
+
16
+ spec.files = `git ls-files -z`.split("\x0")
17
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
18
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
19
+ spec.require_paths = ['lib']
20
+
21
+ spec.add_development_dependency 'bundler', '~> 1.6'
22
+ spec.add_development_dependency 'rspec', '3.0.0'
23
+ spec.add_development_dependency 'simplecov', '0.9.1'
24
+ end
@@ -0,0 +1,8 @@
1
+ aardvark
2
+ beetle
3
+ cringe
4
+ dirge
5
+ effort
6
+ dirth
7
+ fade
8
+ ghast
@@ -0,0 +1,130 @@
1
+ require 'spec_helper'
2
+
3
+ describe ScrabbleScore::Dictionary do
4
+ describe '#initialize' do
5
+ context 'when not specifying the dictionary' do
6
+ it 'loads the default dictionary' do
7
+ stub_const('ScrabbleScore::ROOT', File.join(File.dirname(__FILE__), '..', '..'))
8
+
9
+ dictionary = ScrabbleScore::Dictionary.new
10
+
11
+ expected_words = %w[aardvark beetle cringe dirge effort dirth fade ghast]
12
+ expect(dictionary.words).to match_array(expected_words)
13
+ end
14
+ end
15
+
16
+ context 'when specifying the dictionary' do
17
+ it 'uses the specified dictionary' do
18
+ seed_words = %w[apple pear banana]
19
+ dictionary = ScrabbleScore::Dictionary.new(seed_words)
20
+
21
+ expect(dictionary.words).to match_array(seed_words)
22
+ end
23
+ end
24
+ end
25
+
26
+ describe '#contains' do
27
+ let(:seed_words) { %w[gas coal uranium wind solar] }
28
+ let(:dictionary) { ScrabbleScore::Dictionary.new(seed_words) }
29
+
30
+ it 'finds words in the dictionary' do
31
+ seed_words.each do |word|
32
+ expect(dictionary.contains(word)).to be_truthy
33
+ end
34
+ end
35
+
36
+ it 'does not find words not in the dictionary' do
37
+ expect(dictionary.contains('foobar')).to be_falsey
38
+ end
39
+
40
+ it 'has the important two letter words' do
41
+ words = %w[
42
+ aa ab ad ae ag ah ai al am an ar as at aw ax ay ba be bi bo
43
+ by de do ed ef eh el em en er es et ex fa fe go ha he hi hm
44
+ ho id if in is it jo ka ki la li lo ma me mi mm mo mu my na
45
+ ne no nu od oe of oh oi om on op or os ow ox oy pa pe pi qi
46
+ re sh si so ta ti to uh um un up us ut we wo xi xu ya ye yo
47
+ za
48
+ ]
49
+ dictionary = ScrabbleScore::Dictionary.new
50
+
51
+ words.each { |word| expect(dictionary.contains(word)).to be_truthy }
52
+ end
53
+
54
+ it 'has the important three letter words' do
55
+ words = %w[
56
+ aah aal aas aba abo abs aby ace act add ado ads adz aff aft
57
+ aga age ago ags aha ahi ahs aid ail aim ain air ais ait ala
58
+ alb ale all alp als alt ama ami amp amu ana and ane ani ant
59
+ any ape apo app apt arb arc are arf ark arm ars art ash ask
60
+ asp ass ate att auk ava ave avo awa awe awl awn axe aye ays
61
+ azo baa bad bag bah bal bam ban bap bar bas bat bay bed bee
62
+ beg bel ben bes bet bey bib bid big bin bio bis bit biz boa
63
+ bob bod bog boo bop bos bot bow box boy bra bro brr bub bud
64
+ bug bum bun bur bus but buy bye bys cab cad cam can cap car
65
+ cat caw cay cee cel cep chi cig cis cob cod cog col con coo
66
+ cop cor cos cot cow cox coy coz cru cry cub cud cue cum cup
67
+ cur cut cwm dab dad dag dah dak dal dam dan dap daw day deb
68
+ dee def del den dev dew dex dey dib did die dif dig dim din
69
+ dip dis dit doc doe dog dol dom don dor dos dot dow dry dub
70
+ dud due dug duh dui dun duo dup dye ear eat eau ebb ecu edh
71
+ eds eek eel eff efs eft egg ego eke eld elf elk ell elm els
72
+ eme ems emu end eng ens eon era ere erg ern err ers ess eta
73
+ eth eve ewe eye fab fad fag fan far fas fat fax fay fed fee
74
+ feh fem fen fer fes fet feu few fey fez fib fid fie fig fil
75
+ fin fir fit fix fiz flu fly fob foe fog foh fon fop for fou
76
+ fox foy fro fry fub fud fug fun fur gab gad gae gag gal gam
77
+ gan gap gar gas gat gay ged gee gel gem gen get gey ghi gib
78
+ gid gie gig gin gip git gnu goa gob god goo gor gos got gox
79
+ goy gul gum gun gut guv guy gym gyp had hae hag hah haj ham
80
+ hao hap has hat haw hay heh hem hen hep her hes het hew hex
81
+ hey hic hid hie him hin hip his hit hmm hob hod hoe hog hon
82
+ hop hos hot how hoy hub hue hug huh hum hun hup hut hyp ice
83
+ ich ick icy ids iff ifs igg ilk ill imp ink inn ins ion ire
84
+ irk ism its ivy jab jag jam jar jaw jay jee jet jeu jew jib
85
+ jig jin job joe jog jot jow joy jug jun jus jut kab kae kaf
86
+ kas kat kay kea kef keg ken kep kex key khi kid kif kin kip
87
+ kir kis kit koa kob koi kop kor kos kue kye lab lac lad lag
88
+ lam lap lar las lat lav law lax lay lea led lee leg lei lek
89
+ les let leu lev lex ley lez lib lid lie lin lip lis lit lob
90
+ log loo lop lot low lox lug lum luv lux lye mac mad mae mag
91
+ man map mar mas mat maw max may med meg mel mem men met mew
92
+ mho mib mic mid mig mil mim mir mis mix moa mob moc mod mog
93
+ mol mom mon moo mop mor mos mot mow mud mug mum mun mus mut
94
+ myc nab nae nag nah nam nan nap naw nay neb nee neg net new
95
+ nib nil nim nip nit nix nob nod nog noh nom noo nor nos not
96
+ now nth nub nun nus nut oaf oak oar oat oba obe obi oca oda
97
+ odd ode ods oes off oft ohm oho ohs oil oka oke old ole oms
98
+ one ono ons ooh oot ope ops opt ora orb orc ore ors ort ose
99
+ oud our out ova owe owl own oxo oxy pac pad pah pal pam pan
100
+ pap par pas pat paw pax pay pea pec ped pee peg peh pen pep
101
+ per pes pet pew phi pht pia pic pie pig pin pip pis pit piu
102
+ pix ply pod poh poi pol pom poo pop pot pow pox pro pry psi
103
+ pst pub pud pug pul pun pup pur pus put pya pye pyx qat qis
104
+ qua rad rag rah rai raj ram ran rap ras rat raw rax ray reb
105
+ rec red ree ref reg rei rem rep res ret rev rex rho ria rib
106
+ rid rif rig rim rin rip rob roc rod roe rom rot row rub rue
107
+ rug rum run rut rya rye sab sac sad sae sag sal sap sat sau
108
+ saw sax say sea sec see seg sei sel sen ser set sew sex sha
109
+ she shh shy sib sic sim sin sip sir sis sit six ska ski sky
110
+ sly sob sod sol som son sop sos sot sou sow sox soy spa spy
111
+ sri sty sub sue suk sum sun sup suq syn tab tad tae tag taj
112
+ tam tan tao tap tar tas tat tau tav taw tax tea ted tee teg
113
+ tel ten tet tew the tho thy tic tie til tin tip tis tit tod
114
+ toe tog tom ton too top tor tot tow toy try tsk tub tug tui
115
+ tun tup tut tux twa two tye udo ugh uke ulu umm ump uns upo
116
+ ups urb urd urn urp use uta ute uts vac van var vas vat vau
117
+ vav vaw vee veg vet vex via vid vie vig vim vis voe vow vox
118
+ vug vum wab wad wae wag wan wap war was wat waw wax way web
119
+ wed wee wen wet wha who why wig win wis wit wiz woe wog wok
120
+ won woo wop wos wot wow wry wud wye wyn xis yag yah yak yam
121
+ yap yar yaw yay yea yeh yen yep yes yet yew yid yin yip yob
122
+ yod yok yom yon you yow yuk yum yup zag zap zas zax zed zee
123
+ zek zep zig zin zip zit zoa zoo zuz zzz
124
+ ]
125
+ dictionary = ScrabbleScore::Dictionary.new
126
+
127
+ words.each { |word| expect(dictionary.contains(word)).to be_truthy }
128
+ end
129
+ end
130
+ end
@@ -0,0 +1,56 @@
1
+ require 'spec_helper'
2
+
3
+ describe ScrabbleScore::Letters do
4
+ describe '.TILE_VALUES' do
5
+ def check_tile_values(array, expected_value)
6
+ array.each { |letter| expect(ScrabbleScore::Letters::TILE_VALUES[letter]).to be(expected_value) }
7
+ end
8
+
9
+ it 'has expected values' do
10
+ check_tile_values(%w[a e i l n o r s t u], 1)
11
+ check_tile_values(%w[d g], 2)
12
+ check_tile_values(%w[b c m p], 3)
13
+ check_tile_values(%w[f h v w y], 4)
14
+ check_tile_values(%w[k], 5)
15
+ check_tile_values(%w[j x], 8)
16
+ check_tile_values(%w[q z], 10)
17
+ end
18
+ end
19
+
20
+ describe '#word' do
21
+ it 'returns the initialized word' do
22
+ word = ScrabbleScore::Letters.new('apple')
23
+ expect(word.word).to eq('apple')
24
+ end
25
+ end
26
+
27
+ describe '#score' do
28
+ it 'calculates the scrabble value for a word' do
29
+ expect(ScrabbleScore::Letters.new('test').score).to be(4)
30
+ expect(ScrabbleScore::Letters.new('quiz').score).to be(22)
31
+ expect(ScrabbleScore::Letters.new('jester').score).to be(13)
32
+ end
33
+ end
34
+
35
+ describe '#permutations' do
36
+ it 'calculates all possible permutations of the letters' do
37
+ letters = ScrabbleScore::Letters.new('abc')
38
+ expect(letters.permutations).to match_array(['ab', 'ba', 'ac', 'ca', 'bc', 'cb', 'abc', 'acb', 'bac', 'bca', 'cab', 'cba'])
39
+ end
40
+
41
+ it 'generates only unique permutations' do
42
+ letters = ScrabbleScore::Letters.new('foo')
43
+ expect(letters.permutations).to match_array(['fo', 'of', 'oo', 'foo', 'ofo', 'oof'])
44
+ end
45
+ end
46
+
47
+ describe '.cleanse' do
48
+ it 'only saves lower case characters' do
49
+ expect(ScrabbleScore::Letters.cleanse('AbIGwOrD')).to eq('abigword')
50
+ end
51
+
52
+ it 'only saves a-z characters' do
53
+ expect(ScrabbleScore::Letters.cleanse('a!@#$%^&*()_+z')).to eq('az')
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,36 @@
1
+ require 'spec_helper'
2
+
3
+ describe ScrabbleScore::WordFinder do
4
+ describe '#search' do
5
+ let(:empty_dictionary) { ScrabbleScore::Dictionary.new([]) }
6
+ it 'permutates the input' do
7
+ expect_any_instance_of(ScrabbleScore::Letters).to receive(:permutations).and_call_original
8
+
9
+ ScrabbleScore::WordFinder.new(empty_dictionary).search('foo')
10
+ end
11
+
12
+ it 'searches its dictionary for permutations' do
13
+ expect_any_instance_of(ScrabbleScore::Letters).to receive(:permutations).and_return(['bar'])
14
+ expect_any_instance_of(ScrabbleScore::Dictionary).to receive(:contains).with('bar')
15
+
16
+ ScrabbleScore::WordFinder.new(empty_dictionary).search('anything')
17
+ end
18
+
19
+ it 'returns permutations that are words in the dictionary' do
20
+ dictionary = %w[stop pot top sop to]
21
+ word_finder = ScrabbleScore::WordFinder.new(ScrabbleScore::Dictionary.new(dictionary))
22
+
23
+ expect(word_finder.search('opt')).to match_array(%w[pot top to])
24
+ end
25
+ end
26
+
27
+ describe '#search_with_score' do
28
+ it 'returns a hash of (word, score) pairs' do
29
+ dictionary = %w[flavor or fav rat trap]
30
+ word_finder = ScrabbleScore::WordFinder.new(ScrabbleScore::Dictionary.new(dictionary))
31
+
32
+ expected_hash = {'flavor' => 12, 'or' => 2, 'fav' => 9}
33
+ expect(word_finder.search_with_score('lovrfa')).to eq(expected_hash)
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,5 @@
1
+ require 'simplecov'
2
+ SimpleCov.start if ENV["COVERAGE"]
3
+
4
+ require 'scrabble_score'
5
+
metadata ADDED
@@ -0,0 +1,109 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: scrabble_score
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Nick Aschenbach
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2014-09-28 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.6'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.6'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rspec
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - '='
32
+ - !ruby/object:Gem::Version
33
+ version: 3.0.0
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - '='
39
+ - !ruby/object:Gem::Version
40
+ version: 3.0.0
41
+ - !ruby/object:Gem::Dependency
42
+ name: simplecov
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - '='
46
+ - !ruby/object:Gem::Version
47
+ version: 0.9.1
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - '='
53
+ - !ruby/object:Gem::Version
54
+ version: 0.9.1
55
+ description: An engine that finds words from a set of letters and calculates the scrabble
56
+ score
57
+ email:
58
+ - nick.aschenbach@gmail.com
59
+ executables: []
60
+ extensions: []
61
+ extra_rdoc_files: []
62
+ files:
63
+ - ".gitignore"
64
+ - Gemfile
65
+ - LICENSE.txt
66
+ - README.md
67
+ - assets/dictionary.txt
68
+ - lib/scrabble_score.rb
69
+ - lib/scrabble_score/dictionary.rb
70
+ - lib/scrabble_score/letters.rb
71
+ - lib/scrabble_score/version.rb
72
+ - lib/scrabble_score/word_finder.rb
73
+ - scrabble_score.gemspec
74
+ - spec/assets/dictionary.txt
75
+ - spec/lib/scrabble_score/dictionary_spec.rb
76
+ - spec/lib/scrabble_score/letters_spec.rb
77
+ - spec/lib/scrabble_score/word_finder_spec.rb
78
+ - spec/spec_helper.rb
79
+ homepage: https://github.com/nick-aschenbach/scrabble-score
80
+ licenses:
81
+ - MIT
82
+ metadata: {}
83
+ post_install_message:
84
+ rdoc_options: []
85
+ require_paths:
86
+ - lib
87
+ required_ruby_version: !ruby/object:Gem::Requirement
88
+ requirements:
89
+ - - ">="
90
+ - !ruby/object:Gem::Version
91
+ version: '0'
92
+ required_rubygems_version: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ requirements: []
98
+ rubyforge_project:
99
+ rubygems_version: 2.4.1
100
+ signing_key:
101
+ specification_version: 4
102
+ summary: A scrabble cheater scoring library
103
+ test_files:
104
+ - spec/assets/dictionary.txt
105
+ - spec/lib/scrabble_score/dictionary_spec.rb
106
+ - spec/lib/scrabble_score/letters_spec.rb
107
+ - spec/lib/scrabble_score/word_finder_spec.rb
108
+ - spec/spec_helper.rb
109
+ has_rdoc: