-
Notifications
You must be signed in to change notification settings - Fork 0
/
script_5000.js
219 lines (166 loc) · 45.5 KB
/
script_5000.js
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// ---------------------- arrangement of words ----------------------
//
// words are divided based on their length
// and are arranded in decreaseing order of their frequency of occurrance
//
// wordList = [
// [], // left empty intetionally
// ["a","I"], // 1 letter words
// ["an","as","at","if","so"], // 2 letter words
// ["the","act","cat","fog"], // 3 letter words
// ["have","what","them"], // 4 letter words
// ["their","again"] // 5 letter words
// // till 14 letter words
// ]
// ------------------------------------------------------------------
wordList = [[],["a","i"],["be","of","in","to","it","he","on","do","at","we","by","or","as","go","if","my","up","so","me","no","us","mr","oh","tv","pm","ok","am","ms","ad","hi","vs","ie","pc","ah","re","uh","ha"],["the","and","for","you","say","but","his","not","she","can","who","get","her","all","one","out","see","him","now","how","its","our","two","way","new","day","use","man","any","may","try","ask","too","own","put","old","why","let","big","few","run","off","lot","eye","job","far","yes","sit","yet","end","bad","pay","law","car","set","kid","ago","add","art","war","low","win","guy","air","boy","age","buy","die","cut","six","son","arm","tax","hit","eat","oil","red","per","top","bed","hot","lie","dog","cup","box","lay","sex","act","ten","gun","leg","fly","bit","sea","bar","bag","gas","mrs","nor","key","sky","fan","ice","sun","ear","fit","cry","egg","hey","bus","tie","map","nod","dry","fat","lip","mom","aid","mix","cat","due","dad","fee","row","fix","era","fun","tip","aim","jew","hat","gay","lab","sir","gap","sad","tea","cop","pot","cap","toy","dig","wet","pan","ceo","pop","mad","via","hip","bet","odd","raw","joy","dna","tap","rub","net","ill","owe","ski","rid","cow","etc","sue","jet","god","nut","ban","pet","sin","pie","lap","toe","log","beg","pig","van","bay","hay","rat","rip","pen","mud","pad","bat","wow","sum","pit","hug","gym","huh","kit","pro","bid","jaw","bow","bug","ass","cab","web","bee","jar","gut","pin","dam","shy","oak","tag","dot","dip","pat","rib","rod","ash","rim","lid","fur","opt","ego","spy","cue","fog"],["have","that","with","this","they","from","what","make","know","will","time","year","when","them","some","take","into","just","your","come","than","like","then","more","want","look","also","find","here","give","many","well","only","tell","very","even","back","good","life","work","down","call","over","last","need","feel","high","most","much","mean","keep","same","seem","help","talk","turn","hand","show","part","such","case","week","each","hear","play","move","live","hold","next","must","home","room","area","fact","book","word","side","kind","four","head","long","both","away","hour","game","line","ever","lose","meet","city","name","five","once","real","team","best","idea","body","lead","stop","face","read","door","sure","grow","open","walk","girl","food","foot","able","love","wait","send","stay","fall","plan","kill","yeah","care","late","hard","else","pass","sell","role","rate","drug","wife","mind","pull","free","less","hope","view","town","road","true","full","join","pick","wear","form","site","base","star","half","easy","cost","data","land","wall","news","test","step","baby","type","draw","film","tree","hair","soon","term","rule","risk","fire","bank","west","seek","rest","deal","past","goal","fill","drop","upon","push","note","fine","near","page","poor","race","dead","rise","east","save","thus","size","fund","sign","list","left","loss","bill","fail","miss","sort","blue","song","dark","hang","rock","cold","main","card","seat","cell","nice","firm","huge","ball","onto","pain","wide","fish","trip","unit","deep","edge","fear","heat","sing","whom","skin","item","yard","beat","tend","task","shot","wish","safe","rich","vote","none","born","wind","fast","bird","hurt","nine","camp","date","hole","ship","park","spot","lack","boat","wood","roll","gain","hide","gold","club","farm","band","ride","text","tool","wild","earn","tiny","feed","path","shop","folk","lift","jump","warm","soft","gift","wave","deny","suit","blow","cook","burn","shoe","bone","wine","cool","hell","tour","grab","fair","pair","knee","tape","hire","lady","neck","lean","tall","hate","male","army","shut","lots","rain","fuel","leaf","pool","salt","soul","bear","thin","poll","okay","code","jury","desk","ring","mark","loan","crew","meal","cash","link","root","nose","file","sick","duty","slow","zone","wake","warn","snow","slip","meat","soil","golf","user","kick","used","bowl","host","hall","rely","debt","rare","tank","bond","wing","pour","stir","beer","tear","hero","seed","busy","copy","cite","gray","dish","core","rush","vast","flow","mass","bomb","tone","aids","gate","hill","milk","cast","plus","weak","wrap","drag","roof","diet","wash","post","chip","self","bike","lake","bend","arab","sand","lock","pose","sale","mine","tale","joke","coat","urge","dust","glad","pack","iron","gene","kiss","boss","king","mood","boot","bean","peak","vary","wire","holy","twin","luck","toss","bury","pray","ally","pure","peer","belt","flag","corn","moon","crop","pink","buck","poem","bind","mail","tube","quit","jail","pace","cake","flat","wage","snap","gear","gang","teen","yell","spin","bell","rank","lost","pant","wipe","port","dirt","rice","deck","pole","mode","bake","sink","swim","tire","fade","mask","load","deer","fate","oven","poet","mere","pale","flee","lawn","plot","pipe","math","tail","palm","soup","pile","aide","mall","heel","tent","myth","menu","loud","auto","bite","pine","chef","boom","shit","cope","ease","wise","acid","odds","lung","ugly","rope","sake","gaze","clue","dear","coal","sigh","dare","rose","rail","mess","norm","stem","rape","hunt","echo","pill","bare","rent","pump","evil","slam","melt","fold","beef","duck","dose","trap","lens","lend","nail","cave","herb","suck","leap","pond","dump","limb","tune","harm","horn","grip","beam","fork","disk","hook","exit","mild","doll","noon","amid","hers","jazz","oral","fist","bath","bold","hint","peel","flip","bias","lamp","chin","chop","silk","rage","dawn","tide","seal","scan","fool","rear","cart","mate","slap","ours","barn","tuck","drum","sail","nest","lane","cage","rack","wolf","grin","aunt","calm","haul","ruin","bush","clip","bull","exam","loop","edit","whip","boil","pork","sock","sexy","lion","cord","soap","cute","shed","icon","heal","coin","damn","mill","hike","sack","tray","coup","skip","sole","weed","deem","cure","fame","atop","toll","chew","butt","dumb","bulk","goat","neat","poke","soar","clay","fare","disc","sofa","soak","slot","riot","tile","till","plea","bulb","bolt","dock","trim","spit","does"],["their","would","about","there","think","which","could","other","these","first","thing","those","woman","child","after","world","still","three","state","never","leave","while","great","group","begin","where","every","start","might","place","again","right","small","night","point","today","bring","large","under","water","write","money","story","young","month","study","issue","black","house","since","until","power","often","among","stand","later","white","least","learn","watch","speak","level","allow","spend","party","early","force","offer","maybe","music","human","serve","sense","build","death","reach","local","class","raise","field","major","along","heart","light","voice","whole","price","carry","drive","break","thank","value","model","agree","paper","space","event","whose","table","court","teach","image","phone","cover","quite","clear","piece","movie","north","third","catch","cause","plant","short","south","floor","close","wrong","sport","board","fight","throw","order","focus","blood","color","store","sound","enter","share","shoot","seven","scene","stock","eight","happy","occur","media","ready","argue","staff","trade","glass","skill","crime","stage","truth","check","laugh","guess","prove","claim","enjoy","legal","final","green","above","trial","radio","visit","avoid","peace","apply","shake","chair","treat","style","adult","worry","range","dream","stuff","hotel","heavy","tough","exist","agent","owner","ahead","coach","total","civil","mouth","smile","score","front","admit","alone","fresh","video","judge","stare","troop","track","basic","plane","labor","refer","touch","sleep","press","brain","dozen","sorry","stick","stone","scale","drink","truck","sales","shape","crowd","horse","guard","terms","quick","pound","basis","guest","block","title","faith","river","count","marry","limit","worth","speed","cross","youth","broad","twice","grade","quiet","dress","aware","chief","below","voter","moral","photo","daily","fully","actor","birth","clean","train","plate","alive","abuse","extra","paint","climb","sweet","metal","urban","lunch","sugar","enemy","panel","sight","adopt","works","empty","trail","novel","iraqi","theme","storm","union","fruit","prime","dance","being","shift","trend","angry","truly","earth","chest","thick","sheet","ought","brown","shirt","pilot","guide","steal","funny","blame","crazy","chain","solve","equal","forth","frame","trust","ocean","tooth","smart","topic","nurse","aside","email","doubt","grant","cloud","cheap","beach","route","upper","tired","fewer","apart","match","proud","waste","wheel","cable","rural","cream","solid","noise","grass","taste","sharp","lower","honor","knock","asset","bread","lucky","brief","steel","shout","layer","slide","shall","error","print","album","joint","reply","cycle","grand","hello","knife","phase","quote","elect","sauce","shock","habit","juice","entry","maker","asian","usual","anger","round","smell","tower","smoke","coast","inner","swing","mayor","fifth","favor","weigh","false","latin","essay","giant","depth","shell","onion","brand","award","arise","armed","stake","fiber","minor","label","index","draft","rough","drama","clock","sweep","super","yield","fence","bunch","found","react","cheek","apple","virus","blind","slave","elite","tight","bible","chart","solar","strip","salad","pause","bench","lover","newly","imply","pride","ideal","crash","craft","fault","loose","prior","relax","stair","proof","dirty","alter","split","vital","adapt","irish","honey","tribe","shelf","buyer","shade","mount","angle","crack","given","trace","meter","rapid","fifty","porch","rifle","trick","nerve","ratio","humor","glove","delay","scope","badly","eager","motor","float","blade","cabin","yours","pitch","lemon","naked","shrug","flame","wound","flesh","grain","brush","seize","shore","ghost","awful","piano","mouse","chase","brick","patch","swear","slice","exact","uncle","grave","couch","shine","upset","organ","magic","jeans","flour","slope","candy","medal","curve","logic","harsh","greet","march","snake","flash","islam","roman","elbow","plead","sixth","trunk","rumor","cloth","plain","fraud","array","burst","flood","arena","drift","drain","hurry","wrist","guilt","skirt","hence","await","spill","grace","towel","prize","boost","alarm","weird","sweat","outer","drunk","chaos","forty","lobby","trait","thumb","unity","twist","shame","rebel","fluid","click","carve","belly","scare","ankle","rider","crawl","donor","opera","clerk","laser","realm","blend","pizza","civic","steep","alien","scary","angel","silly","ranch","elder","dutch","greek","quest","juror","stiff","toxic","grief","buddy","sword","glory","faint","queen","input","steam","unite","equip","bless","bonus","mixed","orbit","grasp","spite","cuban","wagon","sheer","thigh","sheep","whale","skull","spell","booth","waist","royal","panic","crush","cliff","tumor","pulse","fixed","diary","irony","spoon","midst","alley","rival","punch","known","purse","cheat","fever","dried","shove","stove","alike","dough","trash","gross","spray","beast","shark","fleet","debut","scent","stack","cease","nasty","wheat","aisle","vocal","risky","pasta","genre","merit","chunk","robot","boast","added","sneak","blank","dying","spare","cling","blink","squad","chill","steer","rally","cheer","steak","awake","liver","widow","beard","brake","valid","forum","enact","suite","straw","globe","blast","screw","drill","cruel","grape","charm","loyal","radar","frown","spark","blond","arrow","ridge","brave","dense","sunny","swell","bride","weave","devil","cargo","spine","fatal","drown","kneel","naval","women"],["people","should","school","become","really","family","system","during","number","always","happen","before","mother","though","little","around","friend","father","member","almost","change","minute","social","follow","parent","create","public","others","office","health","person","within","result","reason","moment","enough","across","second","toward","policy","appear","market","expect","nation","course","behind","remain","effect","former","report","better","effort","decide","strong","leader","police","return","action","season","player","record","ground","matter","center","couple","figure","street","itself","either","recent","doctor","worker","simply","source","nearly","choose","window","listen","chance","energy","period","summer","likely","letter","choice","single","church","future","anyone","myself","author","agency","nature","reduce","common","series","animal","factor","decade","artist","career","beyond","simple","accept","answer","amount","growth","degree","wonder","attack","region","pretty","arrive","lawyer","sister","design","indeed","rather","entire","forget","remove","memory","expert","spring","finish","theory","impact","charge","reveal","weapon","manage","camera","weight","affect","inside","writer","middle","detail","method","sexual","cancer","finger","garden","notice","modern","budget","victim","threat","dinner","relate","travel","debate","senior","assume","suffer","speech","option","forest","global","senate","reform","access","credit","corner","recall","safety","income","strike","nobody","object","client","please","attend","spirit","battle","crisis","define","easily","vision","status","normal","slowly","driver","handle","survey","winter","soviet","refuse","screen","reader","target","prison","demand","flight","emerge","bright","sample","settle","highly","mostly","lesson","living","unless","border","gather","critic","aspect","insist","annual","french","affair","spread","ignore","belief","murder","review","editor","engage","coffee","anyway","commit","female","afraid","native","indian","active","extend","remind","united","depend","direct","famous","flower","supply","search","circle","device","bottom","island","studio","damage","intend","danger","desire","injury","engine","fourth","expand","ticket","mental","farmer","planet","obtain","invite","repeat","pocket","breath","belong","advice","breast","thanks","yellow","shadow","locate","county","bridge","profit","muscle","notion","prefer","museum","beauty","unique","ethnic","stress","select","actual","bottle","hardly","launch","defend","ensure","extent","estate","pursue","jewish","branch","relief","manner","rating","golden","motion","german","gender","except","afford","regime","appeal","mirror","length","secret","master","winner","volume","pepper","divide","oppose","league","employ","barely","sector","beside","merely","invest","expose","narrow","accuse","useful","reject","talent","escape","height","assess","plenty","campus","proper","guilty","column","signal","regard","twenty","prayer","cheese","permit","scream","deeply","agenda","unable","arrest","visual","fairly","silent","widely","inform","bother","enable","saving","desert","double","formal","stream","racial","potato","online","jacket","rarely","priest","adjust","retire","attach","severe","impose","symbol","clinic","tomato","butter","surely","glance","fellow","smooth","nearby","silver","junior","throat","salary","unlike","resist","assist","viewer","secure","recipe","wooden","honest","origin","advise","wealth","deputy","assure","dealer","phrase","muslim","switch","killer","assign","heaven","button","burden","string","resort","tissue","broken","stupid","occupy","cousin","retain","latter","terror","bullet","square","gently","detect","remote","mutual","mainly","freeze","singer","evolve","partly","thirty","treaty","sudden","tongue","stable","steady","vessel","dining","wisdom","garlic","poetry","scared","slight","differ","custom","carbon","closer","scheme","galaxy","hunter","infant","derive","fabric","asleep","tennis","barrel","modest","stroke","prompt","absorb","cotton","flavor","orange","assert","valley","versus","hungry","wander","submit","legacy","shower","depict","garage","borrow","comedy","twelve","weekly","devote","ethics","summit","gifted","medium","basket","powder","cookie","admire","exceed","rhythm","lovely","script","tactic","margin","horror","defeat","sacred","soccer","tunnel","virtue","abroad","makeup","legend","remark","resign","reward","gentle","invent","ritual","insect","salmon","combat","bitter","subtle","bishop","export","closet","retail","excuse","tshirt","deadly","korean","suburb","render","strict","motive","temple","and/or","random","domain","cattle","fiscal","endure","strain","guitar","behave","dancer","colony","closed","modify","govern","ballot","praise","injure","canvas","format","turkey","convey","frozen","spouse","resume","sodium","bounce","pickup","needle","timing","rescue","firmly","poster","oxygen","pastor","punish","equity","statue","repair","decent","purple","eating","parade","cancel","candle","entity","vanish","racism","casual","enroll","intent","toilet","hidden","tender","lonely","shared","pillow","ruling","lately","softly","verbal","tribal","import","divine","genius","broker","output","rocket","donate","inmate","tackle","carpet","bubble","bloody","accent","shrimp","voting","patrol","immune","exotic","drawer","runner","empire","puzzle","tragic","safely","eleven","bureau","breeze","costly","insert","helmet","casino","hockey","liquid","foster","filter","rabbit","outfit","patent","pencil","banker","eighth","behalf","stance","compel","shrink","fierce","weaken","openly","unfair","deploy","ladder","jungle","invade","sphere","unfold","collar","streak","monkey","mentor","sleeve","debris","parish","hunger","faster","regret","carrot","plunge","refuge","outlet","intact","vendor","thrive","peanut","comply","patron","solely","banana","palace","cruise","mobile","forbid","brutal","thread","coming","denial","rental","warmth","regain","rubber","freely","update","marker","preach","bucket","marble","mutter","depart","trauma","ribbon","shorts","soften","hazard","seldom","timber","flying","seller","marine","boring","bronze","vacuum","sensor","manual","pistol"],["because","through","between","another","student","country","problem","against","company","program","believe","without","million","provide","service","however","include","several","nothing","whether","already","history","morning","himself","teacher","process","college","someone","suggest","control","perhaps","require","finally","explain","develop","federal","receive","society","special","support","project","produce","picture","product","patient","certain","century","culture","billion","brother","realize","hundred","husband","economy","medical","current","involve","defense","subject","officer","private","quickly","foreign","natural","concern","similar","usually","article","despite","central","exactly","protect","serious","thought","quality","meeting","prepare","disease","success","ability","herself","general","feeling","message","outside","benefit","forward","present","section","compare","station","clearly","discuss","example","various","manager","network","science","imagine","tonight","respond","popular","contain","measure","perform","evening","mention","trouble","instead","improve","soldier","reflect","surface","purpose","pattern","machine","address","reality","partner","kitchen","capital","account","western","prevent","citizen","mission","publish","release","opinion","version","species","freedom","achieve","concept","perfect","conduct","examine","variety","nuclear","replace","british","feature","weekend","african","element","chinese","attempt","village","express","willing","deliver","vehicle","observe","average","operate","collect","promote","survive","failure","comment","regular","anybody","quarter","growing","destroy","context","mistake","clothes","promise","combine","victory","healthy","finding","contact","justice","eastern","primary","plastic","writing","chicken","theater","session","welcome","respect","russian","strange","reading","explore","complex","athlete","meaning","married","predict","weather","supreme","balance","connect","somehow","analyst","largely","revenue","package","obvious","anymore","propose","visitor","hearing","traffic","capture","content","declare","setting","outcome","airport","english","neither","surgery","correct","ancient","silence","typical","confirm","attract","bedroom","totally","stretch","fashion","welfare","opening","overall","initial","careful","holiday","witness","beneath","limited","faculty","liberal","massive","decline","towards","succeed","fishing","unusual","closely","approve","acquire","compete","illegal","forever","israeli","display","musical","suspect","scholar","warning","climate","payment","request","emotion","airline","library","recover","factory","expense","funding","therapy","housing","violent","suppose","wedding","portion","abandon","tension","leading","consist","alcohol","spanish","passage","arrange","deserve","resolve","mexican","symptom","breathe","suicide","passion","amazing","intense","advance","inspire","visible","illness","analyze","parking","enhance","mystery","poverty","monitor","digital","heavily","missile","equally","command","veteran","capable","nervous","tourist","crucial","deficit","journey","mixture","whisper","anxiety","embrace","testing","stomach","install","concert","channel","extreme","drawing","protein","absence","rapidly","speaker","restore","quietly","utility","highway","routine","islamic","refugee","barrier","classic","distant","italian","ceiling","roughly","lawsuit","chamber","profile","penalty","cabinet","proceed","dispute","fortune","genetic","adviser","whereas","olympic","fiction","senator","hunting","journal","testify","founder","dismiss","finance","diverse","working","unknown","offense","counter","justify","protest","insight","possess","episode","shortly","assault","license","shelter","tragedy","funeral","squeeze","convert","pretend","elderly","violate","segment","nowhere","comfort","radical","storage","leather","council","fantasy","gesture","ongoing","chapter","divorce","sustain","fifteen","satisfy","briefly","consume","tobacco","besides","wealthy","fighter","educate","painful","uniform","qualify","scandal","helpful","impress","privacy","contest","organic","bombing","explode","handful","horizon","curious","undergo","edition","appoint","battery","arrival","cluster","habitat","actress","running","worried","portray","carrier","cooking","miracle","killing","charity","venture","grocery","exhibit","blanket","recruit","painter","courage","formula","captain","gallery","fitness","inquiry","compose","related","lightly","trading","surgeon","physics","counsel","excited","serving","greatly","pleased","sponsor","ethical","entitle","evident","essence","exclude","pitcher","reverse","missing","confuse","monthly","lecture","enforce","contend","frankly","hallway","monster","crystal","written","consult","forgive","maximum","warrior","outdoor","curtain","walking","playoff","minimum","execute","chronic","retired","trigger","virtual","convict","landing","driving","vitamin","endless","mandate","reserve","genuine","scatter","relieve","suspend","pension","rebuild","shuttle","precise","anxious","liberty","doorway","teenage","pursuit","endorse","thereby","sharply","garbage","servant","elegant","confess","starter","banking","gravity","isolate","hostage","dynamic","stumble","descend","readily","romance","circuit","coastal","burning","diamond","oversee","trailer","loyalty","nominee","alleged","dignity","seventh","tightly","dilemma","shallow","stadium","condemn","costume","statute","cartoon","hostile","vaccine","opposed","jewelry","concede","secular","neutral","biology","whoever","verdict","subsidy","dessert","utilize","rolling","minimal","cocaine","sibling","passing","persist","bicycle","exploit","charter","consent","workout","hormone","texture","custody","outline","uncover","catalog","someday","instant","trainer","eyebrow","inherit","pioneer","kingdom","terrain","planner","closest","density","persian","feather","tighten","partial","builder","glimpse","premise","legally","disturb","logical","slavery","mineral","halfway","fucking","auction","triumph","scratch","harmony","peasant","deposit","impulse","dancing","happily","removal","unhappy","tourism","exhaust","fragile","crowded","prevail","mansion","cottage","balloon","sweater","retreat","premium","fatigue","provoke","harvest","specify","transit","seminar","delight","skilled","summary","dictate","laundry","apology"],["american","question","national","business","continue","together","anything","research","although","remember","consider","actually","probably","interest","economic","possible","military","decision","building","director","position","official","everyone","activity","industry","practice","describe","personal","computer","evidence","daughter","congress","campaign","material","hospital","thousand","increase","security","behavior","recently","movement","language","response","approach","pressure","resource","identify","whatever","indicate","training","election","physical","standard","analysis","strategy","democrat","yourself","maintain","employee","cultural","politics","suddenly","discover","specific","shoulder","property","somebody","magazine","marriage","violence","positive","consumer","painting","attorney","audience","majority","customer","southern","relation","critical","original","directly","attitude","powerful","announce","involved","conflict","argument","complete","solution","distance","mountain","supposed","resident","european","presence","district","contract","strength","previous","reporter","facility","identity","tomorrow","chairman","baseball","religion","document","threaten","slightly","reaction","location","neighbor","function","learning","category","academic","internet","negative","medicine","exercise","familiar","progress","exchange","football","domestic","northern","software","favorite","greatest","surround","surprise","proposal","minority","straight","teaching","regional","organize","struggle","conclude","generate","thinking","possibly","investor","accident","japanese","internal","catholic","contrast","capacity","estimate","governor","producer","division","entirely","complain","variable","coverage","anywhere","pleasure","separate","somewhat","judgment","minister","terrible","multiple","criminal","abortion","incident","enormous","engineer","sentence","convince","addition","creative","priority","creation","graduate","dramatic","universe","schedule","purchase","existing","perceive","planning","opponent","preserve","opposite","exposure","occasion","ordinary","numerous","moreover","employer","dominate","whenever","transfer","disaster","prospect","spending","evaluate","emphasis","creature","disorder","strongly","constant","bathroom","confront","prisoner","designer","educator","relative","teaspoon","birthday","teenager","recovery","observer","historic","apparent","approval","criteria","clinical","normally","activist","ultimate","valuable","chemical","vacation","advocate","pregnant","canadian","darkness","clothing","portrait","survival","ceremony","disagree","unlikely","stranger","electric","literary","overcome","shopping","accurate","champion","scenario","friendly","lifetime","innocent","boundary","withdraw","dialogue","advanced","aircraft","delivery","platform","relevant","shooting","external","entrance","properly","emission","earnings","exciting","musician","instance","athletic","survivor","publicly","tendency","resemble","proposed","standing","provider","downtown","taxpayer","detailed","workshop","romantic","overlook","sequence","absolute","register","heritage","dominant","operator","collapse","mortgage","sanction","civilian","province","distinct","artistic","fighting","persuade","moderate","frequent","everyday","headline","invasion","adequate","concrete","changing","colonial","homeless","decrease","alliance","regulate","laughter","receiver","superior","compound","drinking","midnight","suburban","interior","corridor","weakness","humanity","reliable","hispanic","airplane","initiate","sandwich","motivate","longtime","restrict","assemble","obstacle","basement","bacteria","database","ideology","railroad","peaceful","grateful","adoption","particle","festival","freshman","wherever","rhetoric","profound","currency","doctrine","horrible","commonly","sidewalk","olympics","pleasant","delicate","forehead","traveler","dedicate","diagnose","theology","handsome","provided","wildlife","elevator","guidance","envelope","generous","sunlight","feedback","spectrum","starting","hesitate","metaphor","judicial","diminish","minimize","assembly","equation","offering","precious","prohibit","abstract","hardware","shortage","annually","deadline","sexually","quantity","monument","accuracy","treasure","talented","gasoline","extended","diabetes","dynamics","parental","merchant","improved","ancestor","homeland","symbolic","conceive","combined","patience","tropical","intimate","flexible","casualty","republic","terrific","instinct","teammate","aluminum","ministry","instruct","mushroom","mechanic","sympathy","syndrome","ambition","dissolve","expected","actively","illusion","tolerate","scramble","decorate","donation","interact","supplier","momentum","elephant","mentally","organism","upstairs","backyard","comprise","reminder","disabled","frontier","disclose","notebook","vertical","swimming","outsider","proclaim","required","colorful","textbook","emerging","envision","rational","protocol","distract","discount","retailer","classify","stimulus","likewise","informal","validity","strictly","artifact","listener","socially","equality","cemetery","striking","isolated","eligible","interval","feminist","sprinkle","blessing","formerly","lawmaker","calendar","predator","autonomy","landmark","offender","fraction","fragment","headache","suitable","driveway","homework","molecule","steadily","defender","explicit","magnetic","meantime","transmit","nutrient","severely","hightech","lighting","terribly","honestly","troubled","balanced","managing","diplomat","sometime","epidemic","inherent","selected"],["something","different","important","political","community","president","education","including","sometimes","according","situation","attention","difficult","available","condition","certainly","represent","treatment","determine","recognize","character","everybody","professor","operation","financial","authority","knowledge","executive","religious","establish","statement","direction","interview","structure","candidate","necessary","challenge","beautiful","scientist","agreement","newspaper","concerned","effective","therefore","encourage","afternoon","insurance","beginning","generally","introduce","tradition","potential","christian","apartment","obviously","advantage","technique","principle","equipment","associate","christmas","procedure","influence","wonderful","committee","dangerous","following","classroom","democracy","yesterday","colleague","otherwise","disappear","corporate","somewhere","carefully","emotional","expensive","recommend","basically","currently","emergency","extremely","component","ourselves","landscape","eliminate","meanwhile","telephone","reference","seriously","surprised","vegetable","essential","household","increased","emphasize","secretary","typically","celebrate","physician","virtually","technical","immigrant","passenger","criticism","spiritual","childhood","cigarette","excellent","selection","primarily","regarding","remaining","territory","immediate","transform","existence","discovery","coalition","reduction","substance","elsewhere","practical","volunteer","implement","marketing","complaint","commander","breakfast","exception","objective","dimension","personnel","perfectly","supporter","accompany","gentleman","permanent","literally","construct","sensitive","intention","diversity","historian","negotiate","criticize","precisely","terrorism","provision","satellite","chocolate","universal","testimony","furniture","mechanism","infection","strategic","assistant","encounter","initially","spokesman","incentive","translate","expansion","telescope","interpret","guarantee","awareness","similarly","naturally","regularly","terrorist","extensive","adventure","confident","violation","defensive","prominent","pollution","variation","evolution","celebrity","gradually","stability","framework","depending","counselor","economist","efficient","frequency","explosion","admission","calculate","formation","guideline","publisher","desperate","lifestyle","narrative","principal","temporary","brilliant","offensive","economics","extension","inflation","dependent","operating","discourse","continued","intensity","consensus","recording","pregnancy","reinforce","confusion","cognitive","attribute","defendant","container","architect","highlight","boyfriend","northwest","interrupt","sculpture","integrate","secondary","integrity","classical","estimated","developer","seemingly","inspector","companion","southwest","recession","ownership","nightmare","diagnosis","privilege","broadcast","radiation","amendment","undermine","southeast","convinced","apologize","exclusive","suspicion","residence","signature","promotion","detective","portfolio","invisible","identical","nonprofit","promising","conscious","departure","happiness","reporting","indicator","reluctant","expertise","therapist","recipient","suffering","reception","necessity","performer","inventory","magnitude","collector","realistic","gathering","hopefully","cooperate","continent","undertake","automatic","sentiment","sacrifice","northeast","liability","courtroom","instantly","afterward","alongside","execution","fisherman","isolation","workplace","touchdown","ambitious","uncertain","aesthetic","anonymous","franchise","correctly","sensation","partially","placement","columnist","interfere","stimulate","worldwide","depressed","migration","breathing","hurricane","curiosity","perceived","publicity","ecosystem","specialty","lightning","excessive","commodity","processor","elaborate","transport","allegedly","mortality","municipal","tolerance","screening","voluntary","privately","threshold","routinely","regulator","objection","chemistry","overnight","fantastic","policeman","authorize","sexuality","invention","favorable","youngster","overwhelm","speculate","frustrate","biography","twentieth","foreigner","organized","warehouse","butterfly","plaintiff"],["government","understand","everything","experience","themselves","difference","especially","technology","republican","population","individual","television","democratic","management","particular","production","conference","throughout","generation","commercial","investment","discussion","collection","successful","eventually","restaurant","absolutely","completely","researcher","department","university","interested","leadership","contribute","protection","additional","background","apparently","connection","relatively","historical","expression","literature","assessment","importance","scientific","impossible","instrument","commitment","photograph","conclusion","regulation","appearance","difficulty","appreciate","ultimately","politician","percentage","basketball","frequently","perception","confidence","opposition","industrial","everywhere","resolution","experiment","definitely","curriculum","assistance","depression","journalist","definition","prosecutor","initiative","comparison","settlement","transition","atmosphere","consistent","resistance","philosophy","foundation","discipline","previously","accomplish","illustrate","evaluation","increasing","commission","tablespoon","electronic","reputation","retirement","phenomenon","convention","exhibition","consultant","constantly","enterprise","suggestion","reasonable","elementary","aggressive","employment","impression","respondent","specialist","disability","biological","ingredient","assumption","developing","personally","remarkable","statistics","reflection","revolution","tournament","tremendous","surprising","attractive","originally","profession","constitute","regardless","distribute","vulnerable","capability","psychology","obligation","limitation","preference","incredible","friendship","efficiency","proportion","conviction","strengthen","membership","sufficient","helicopter","punishment","girlfriend","adjustment","motivation","assignment","laboratory","medication","anticipate","legitimate","instructor","nomination","permission","physically","repeatedly","impressive","competitor","subsequent","widespread","occupation","collective","indication","hypothesis","adolescent","concerning","counseling","acceptable","continuous","presidency","acceptance","excitement","occasional","allegation","mainstream","inevitable","unexpected","facilitate","inspection","supervisor","possession","prediction","continuing","innovation","administer","indigenous","separation","enthusiasm","wilderness","mechanical","astronomer","corruption","contractor","compromise","behavioral","complexity","meaningful","electrical","attraction","altogether","engagement","structural","accounting","regulatory","diplomatic","prevention","productive","popularity","automobile","artificial","processing","ridiculous","invitation","officially","mysterious","protective","specialize","associated","withdrawal","thoroughly","optimistic","bankruptcy","revelation","discourage","conspiracy","functional","manipulate","earthquake","creativity","underlying","incredibly","presumably","equivalent","accessible","grandchild","reportedly","ecological","attendance","innovative","ambassador","supportive","aggression","journalism","compliance","supposedly","harassment","likelihood","suspicious","wheelchair","legislator","conception","comparable","conscience","inevitably","constraint","expedition","similarity","conversion","projection","graduation","integrated","ironically","confession","disturbing","technician","coordinate","articulate","accusation","straighten","compelling","accurately","missionary","accelerate","nationwide","stereotype"],["information","development","opportunity","performance","significant","environment","traditional","institution","interesting","participant","immediately","possibility","independent","competition","responsible","demonstrate","perspective","participate","appropriate","application","instruction","educational","temperature","consequence","acknowledge","comfortable","investigate","combination","requirement","expectation","improvement","necessarily","legislation","achievement","explanation","alternative","interaction","personality","association","observation","description","negotiation","essentially","enforcement","competitive","involvement","fundamental","arrangement","concentrate","engineering","immigration","implication","recognition","publication","grandmother","preparation","palestinian","substantial","effectively","incorporate","corporation","advertising","cooperation","communicate","destruction","electricity","complicated","potentially","politically","controversy","imagination","partnership","distinction","grandfather","celebration","composition","appointment","scholarship","reservation","maintenance","examination","cholesterol","restriction","differently","consumption","orientation","furthermore","measurement","frustration","distinguish","nonetheless","quarterback","anniversary","correlation","legislative","integration","prosecution","replacement","intelligent","accommodate","uncertainty","theoretical","transaction","counterpart","residential","businessman","acquisition","destination","exploration","practically","photography","outstanding","credibility","inspiration","agriculture","willingness","spectacular","reliability","fascinating","coordinator","ideological","documentary","progressive","cooperative","mathematics","influential","translation","statistical","fortunately","flexibility","experienced","legislature","encouraging","surrounding","preliminary","speculation","desperately","sensitivity","exclusively","marketplace","embarrassed","demographic","programming","shareholder","calculation","emotionally","grandparent","supermarket","distinctive","theological","contemplate","devastating","neighboring","consecutive","citizenship","sovereignty","contributor","importantly","electronics","convenience","sustainable"],["relationship","organization","particularly","professional","neighborhood","conversation","construction","intelligence","increasingly","presidential","contribution","circumstance","conservative","intervention","contemporary","specifically","manufacturer","investigator","independence","championship","distribution","occasionally","conventional","nevertheless","satisfaction","considerable","intellectual","headquarters","characterize","presentation","introduction","significance","psychologist","photographer","agricultural","successfully","prescription","dramatically","surprisingly","experimental","unemployment","civilization","architecture","overwhelming","consistently","announcement","transmission","respectively","compensation","historically","carbohydrate","disappointed","refrigerator","productivity","practitioner","entrepreneur","christianity","metropolitan","appreciation","commissioner","consequently","conservation","installation","constitution","thanksgiving","deliberately","considerably","jurisdiction","availability","surveillance","economically"],["international","environmental","investigation","communication","understanding","significantly","unfortunately","participation","congressional","entertainment","psychological","approximately","administrator","consideration","extraordinary","concentration","establishment","comprehensive","correspondent","sophisticated","controversial","demonstration","manufacturing","institutional","consciousness","effectiveness","questionnaire","uncomfortable","traditionally","technological","determination","automatically","revolutionary","collaboration","instructional","unprecedented","confrontation","developmental","philosophical","undergraduate","substantially"],["administration","responsibility","representative","characteristic","transportation","interpretation","constitutional","recommendation","representation","discrimination","identification","transformation","administrative","implementation","infrastructure","simultaneously","accomplishment","organizational","disappointment","rehabilitation","accountability"]];
var possibleLetters = [
[" "],
[".",","],
["a","b","c"],
["d","e","f"],
["g","h","i"],
["j","k","l"],
["m","n","o"],
["p","q","r","s"],
["t","u","v"],
["w","x","y","z"]
];
var wordFoundAtIndex = -1;
$(document).ready(function(){
$("#phone").find("button").mouseup(function(event){
var button_pressed = $(event.currentTarget).data("value")
$("#result").val(t9($("#result").val(),button_pressed))
})
blinkCursor();
})
function t9(text,button_pressed){
var input="";
//clear cursor
if(text.slice(-1) == "|"){
text = text.slice(0,-1);
}
//****** main logic ******//
if(button_pressed == "del"){
text = text.slice(0,-1);
wordFoundAtIndex = -1;
input = stripTillSpace("after",text);
input = searchWord(input);
}
else if (button_pressed == "#"){
text = "";
document.getElementById("result").value = "";
}
else if(button_pressed == "*"){
input = stripTillSpace("after",text); // returns text after the last space
input = searchWord(input,((wordFoundAtIndex+1)%wordList[input.length].length));
}
else{
input = stripTillSpace("after",text) + possibleLetters[button_pressed][0];
wordFoundAtIndex = -1; //global variable
input = searchWord(input);
}
// if word not found
if(wordFoundAtIndex == -1){
input = possibleWord(input);
}
//console.log(text +"/"+ input +"--");
text = stripTillSpace("before",text) + input;
return text;
}
function convertToCode(word){
var letterFlag = 0;
var code = "";
for(var i=0; i<word.length; i++){
letterFlag = 0;
for(var j=0; j<=9; j++){
for(var k=0; k<possibleLetters[j].length; k++){
if(word[i]==possibleLetters[j][k]){
code+=j;
letterFlag=1;
break;
}
}
if(letterFlag){
letterFlag=0;
break;
}
}
}
return code;
}
function possibleWord(input){
var text = input;
var inputCode = convertToCode(input);
var possible = 0;
// console.log(input.length);
if(input.length <=14){
for(var i=inputCode.length; i<wordList.length; i++){
for(var j=0; j<wordList[i].length; j++){
if(inputCode == convertToCode(wordList[i][j]).slice(0,inputCode.length)){
text = wordList[i][j].slice(0,inputCode.length);
possible=1;
break;
}
}
if(possible==1){
break;
}
}
}
return text;
}
function searchWord(input,startIndex){
startIndex = startIndex || 0 ; //optional parameter
var inputCode = convertToCode(input);
var text = input;
// try{
//try-catch block coz 'input.length' might be greater than 'wordlist[]' array bound
//'wordlist[input.length].length' - this may produce error
if(input.length <=14){
for(var i=0; i<wordList[input.length].length; i++){
if(inputCode == convertToCode(wordList[input.length][(i+startIndex)%(wordList[input.length].length)])){
text = wordList[input.length][(i+startIndex)%(wordList[input.length].length)];
wordFoundAtIndex = (i+startIndex)%(wordList[input.length].length); // found at index
break;
}
}
}
return text;
}
function stripTillSpace(part,inputText){
var tillIndex=inputText.lastIndexOf(" ");
if (part == "before"){
// console.log("in:"+inputText+" out:"+inputText.slice(0,tillIndex));
if (tillIndex<0){
return "";
}
return inputText.slice(0,tillIndex+1); // returns all the text before the last space (including the last space)
}
else if(part == "after"){
if (tillIndex<0){
return inputText;
}
return inputText.slice(tillIndex+1); // returns all the text after the last space
}
}
function blinkCursor(){
var result = document.getElementById("result");
var value = result.value;
if(value.slice(-1) == "|"){
result.value = value.slice(0,-1);
}
else {
result.value = value+"|";
}
setTimeout(blinkCursor,500);
}
function addWord(){
var value = document.getElementById("newWord").value;
wordList[value.length].unshift(value.toLowerCase());
document.getElementById("notification").innerHTML = "'"+value+"' is added to the dictionary";
setTimeout(function(){
document.getElementById("notification").innerHTML = "";
},2000);
document.getElementById("newWord").value = "";
}