forked from kyordhel/GPSRCmdGen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWildcardReplacer.cs
630 lines (552 loc) · 18.6 KB
/
WildcardReplacer.cs
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace GPSRCmdGen
{
/// <summary>
/// Replaces wildcards in a task prototype string
/// with random values from data stored in a generator.
/// </summary>
public class WildcardReplacer
{
#region Variables
/// <summary>
/// The random generator that contains all required data
/// </summary>
private readonly Generator generator;
/// <summary>
/// The maximum difficulty degree to be used during the replacement
/// </summary>
private DifficultyDegree tier;
/// <summary>
/// Dicctionary of used categories
/// </summary>
private Dictionary<string, Category> categories;
/// <summary>
/// Dicctionary of used gestures
/// </summary>
private Dictionary<string, Gesture> gestures;
/// <summary>
/// Dicctionary of used locations
/// </summary>
private Dictionary<string, Location> locations;
/// <summary>
/// Dicctionary of used names
/// </summary>
private Dictionary<string, PersonName> names;
/// <summary>
/// Dicctionary of used objects
/// </summary>
private Dictionary<string, GPSRObject> objects;
/// <summary>
/// Dicctionary of used questions
/// </summary>
private Dictionary<string, PredefindedQuestion> questions;
/// <summary>
/// List of available categories
/// </summary>
private List<Category> avCategories;
/// <summary>
/// List of available gestures
/// </summary>
private List<Gesture> avGestures;
/// <summary>
/// List of available locations
/// </summary>
private List<Location> avLocations;
/// <summary>
/// List of available names
/// </summary>
private List<PersonName> avNames;
/// <summary>
/// List of available objects
/// </summary>
private List<GPSRObject> avObjects;
/// <summary>
/// List of available objects
/// </summary>
private List<PredefindedQuestion> avQuestions;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="GPSRCmdGen.WildcardReplacer"/> class.
/// </summary>
/// <param name="g">A Generator which contains the databases and the random generator.</param>
/// <param name="tier">The maximum difficulty degree for wildcard replacements</param>
public WildcardReplacer(Generator g, DifficultyDegree tier){
this.generator = g;
this.tier = tier;
this.categories = new Dictionary<string, Category> ();
this.gestures = new Dictionary<string, Gesture> ();
this.locations = new Dictionary<string, Location> ();
this.names = new Dictionary<string, PersonName> ();
this.objects = new Dictionary<string, GPSRObject> ();
this.questions = new Dictionary<string, PredefindedQuestion>();
FillAvailabilityLists ();
}
#endregion
#region Evaluate Methods
/// <summary>
/// Evaluates a <c>category</c> wildcard, creating a new replacement if the wildcard
/// has not been defined before, or retrieving the replacement otherwise.
/// </summary>
/// <param name="w">The wilcard to find a replacement for</param>
/// <returns>An appropiate replacement for the wildcard.</returns>
private INameable EvaluateCategory (Wildcard w)
{
string keycode = w.Name.ToLower ();
string key = keycode + w.Id;
if(this.categories.ContainsKey(key))
return this.categories[key];
Category cat = GetCategory ();
categories.Add (key, cat);
return cat;
}
/// <summary>
/// Evaluates a <c>gesture</c> wildcard, creating a new replacement if the wildcard
/// has not been defined before, or retrieving the replacement otherwise.
/// </summary>
/// <param name="w">The wilcard to find a replacement for</param>
/// <returns>An appropiate replacement for the wildcard.</returns>
private INameable EvaluateGesture(Wildcard w)
{
string keycode = w.Name.ToLower ();
string key = keycode + w.Id;
if(this.gestures.ContainsKey(key))
return this.gestures[key];
Gesture ges = GetGesture ();
gestures.Add (key, ges);
return ges;
}
/// <summary>
/// Evaluates a <c>location</c> wildcard, creating a new replacement if the wildcard
/// has not been defined before, or retrieving the replacement otherwise.
/// </summary>
/// <param name="w">The wilcard to find a replacement for</param>
/// <returns>An appropiate replacement for the wildcard.</returns>
private INameable EvaluateLocation(Wildcard w)
{
string keycode = w.Name.ToLower ();
if (keycode == "location")
{
switch (w.Type.ToLower())
{
case "beacon":
keycode = "beacon"; break;
case "room":
keycode = "room"; break;
case "placement":
keycode = "placement"; break;
}
}
string key = keycode + w.Id;
if(this.locations.ContainsKey(key))
return this.locations[key];
Location loc = GetLocation (keycode);
locations.Add (key, loc);
return loc;
}
/// <summary>
/// Evaluates a <c>name</c> wildcard, creating a new replacement if the wildcard
/// has not been defined before, or retrieving the replacement otherwise.
/// </summary>
/// <param name="w">The wilcard to find a replacement for</param>
/// <returns>An appropiate replacement for the wildcard.</returns>
private INameable EvaluateName(Wildcard w)
{
string keycode = w.Name.ToLower ();
if (keycode == "name") {
string type = w.Type.ToLower ();
if (type == "male")
keycode = "male";
else if (type == "female")
keycode = "female";
}
string key = keycode + w.Id;
if(this.names.ContainsKey(key))
return this.names[key];
PersonName nam = GetName (keycode);
names.Add (key, nam);
return nam;
}
/// <summary>
/// Evaluates an <c>object</c> wildcard, creating a new replacement if the wildcard
/// has not been defined before, or retrieving the replacement otherwise.
/// </summary>
/// <param name="w">The wilcard to find a replacement for</param>
/// <returns>An appropiate replacement for the wildcard.</returns>
private INameable EvaluateObject(Wildcard w)
{
string keycode = w.Name.ToLower ();
if (keycode == "object") {
string type = w.Type.ToLower ();
if (type == "alike")
keycode = "aobject";
else if (type == "known")
keycode = "kobject";
}
string key = keycode + w.Id;
if(this.objects.ContainsKey(key))
return this.objects[key];
GPSRObject obj = GetObject (keycode);
objects.Add (key, obj);
return obj;
}
/// <summary>
/// Evaluates a <c>question</c> wildcard, creating a new replacement if the wildcard
/// has not been defined before, or retrieving the replacement otherwise.
/// </summary>
/// <param name="w">The wilcard to find a replacement for</param>
/// <returns>An appropiate replacement for the wildcard.</returns>
private INameable EvaluateQuestion(Wildcard w)
{
string keycode = w.Name;
string key = keycode + w.Id;
if (this.questions.ContainsKey(key))
return this.questions[key];
PredefindedQuestion qst = GetQuestion();
questions.Add(key, qst);
return qst;
}
/// <summary>
/// Evaluates a void wildcard
/// </summary>
/// <param name="w">The wilcard to find a replacement for</param>
/// <returns>An appropiate replacement for the wildcard.</returns>
private INameable EvaluateVoid(Wildcard w)
{
return new HiddenTaskElement();
}
#endregion
#region Random Generation Methos
/// <summary>
/// Retrieves a <c>Category</c> object from the corresponding availability
/// list, also removing the element to avoid duplicates.
/// </summary>
/// <returns>A category</returns>
private Category GetCategory ()
{
Category item = this.avCategories [this.avCategories.Count - 1];
this.avCategories.RemoveAt (this.avCategories.Count - 1);
return item;
}
/// <summary>
/// Retrieves a <c>Category</c> object from the corresponding availability
/// list, also removing the element to avoid duplicates.
/// </summary>
/// <returns>A category</returns>
private Gesture GetGesture ()
{
Gesture item = this.avGestures [this.avCategories.Count - 1];
this.avGestures.RemoveAt (this.avCategories.Count - 1);
return item;
}
/// <summary>
/// Retrieves a <c>Location</c> object from the corresponding availability
/// list, also removing the element to avoid duplicates.
/// </summary>
/// <param name="keycode">The specific type of location to fetch<param>
/// <returns>A location</returns>
private Location GetLocation(string keycode)
{
Location item;
switch (keycode)
{
case "beacon":
item = this.avLocations.First(l => l.IsBeacon);
break;
case "room":
item = this.avLocations.First(l => l is Room);
break;
case "placement":
item = this.avLocations.First(l => l.IsPlacement);
break;
default:
item = this.avLocations[this.avLocations.Count - 1];
break;
}
this.avLocations.Remove(item);
return item;
}
/// <summary>
/// Retrieves a <c>Name</c> object from the corresponding availability
/// list, also removing the element to avoid duplicates.
/// </summary>
/// <param name="keycode">The specific type of name to fetch<param>
/// <returns>A name</returns>
private PersonName GetName (string keycode)
{
PersonName item;
switch(keycode){
case "male":
item = this.avNames.First(n => n.Gender == Gender.Male);
break;
case "female":
item = this.avNames.First(n => n.Gender == Gender.Female);
break;
default:
item = this.avNames [this.avNames.Count - 1];
break;
}
this.avNames.Remove (item);
return item;
}
/// <summary>
/// Retrieves a <c>GPSRObject</c> object from the corresponding availability
/// list, also removing the element to avoid duplicates.
/// </summary>
/// <param name="keycode">The specific type of object to fetch<param>
/// <returns>An object</returns>
private GPSRObject GetObject (string keycode)
{
GPSRObject item;
switch(keycode){
case "aobject":
item = this.avObjects.First(o => o.Type == GPSRObjectType.Alike);
break;
case "kobject":
item = this.avObjects.First(o => o.Type == GPSRObjectType.Known);
break;
// case "uobject":
// return GPSRObject.Unknown;
default:
item = this.avObjects [this.avObjects.Count - 1];
break;
}
this.avObjects.Remove (item);
return item;
}
/// <summary>
/// Retrieves a <c>Question</c> object from the corresponding availability
/// list, also removing the element to avoid duplicates.
/// </summary>
/// <returns>A question</returns>
private PredefindedQuestion GetQuestion()
{
PredefindedQuestion item = this.avQuestions[this.avQuestions.Count - 1];
this.avQuestions.RemoveAt(this.avQuestions.Count - 1);
return item;
}
/// <summary>
/// Gets a subset of the provided list on which every element has at most the specified difficulty degree.
/// </summary>
/// <param name="baseList">Base list which contains all objects.</param>
/// <typeparam name="T">The type of objects to fetch. Must be ITiered.</typeparam>
/// <returns>The tiered subset.</returns>
private List<T> GetTieredList<T>(List<T> baseList) where T : ITiered
{
if ((baseList == null) || (baseList.Count < 1))
throw new Exception("Requested too many elements (count is greater than objects in baseList)");
IEnumerable<T> ie = baseList.Where(item => (int)item.Tier <= (int)this.tier);
List<T> tieredList = new List<T>(ie);
return tieredList;
}
#endregion
#region Tokenize Methods
/// <summary>
/// Converts the wildcard contained within the provided regular expression
/// match object into a Token object, considering obfuscation
/// </summary>
/// <param name="w">The regular expression match object that contains the wildcard.</param>
private Token TokenizeObfuscatedWildcard(Wildcard w)
{
INameable obfuscated = null;
INameable inam = FindReplacement(w);
switch (w.Name)
{
case "beacon":
case "placement":
obfuscated = ((SpecificLocation)inam).Room;
break;
case "object":
case "aobject":
case "kobject":
obfuscated = ((GPSRObject)inam).Category;
break;
}
if(obfuscated == null)
return new Token(w.Value, inam, FetchMetadata(w));
Token token = new Token(w.Value, obfuscated, FetchMetadata(w));
token.Metadata.Add(inam.Name);
return token;
}
/// <summary>
/// Converts the literal substring string, starting at the given position,
/// into a Token object.
/// </summary>
/// <param name="taskPrototype">The task prototype string.</param>
/// <param name="index">Start position within the task prototype.</param>
private Token TokenizeSubstring(string taskPrototype, int index)
{
string ss = taskPrototype.Substring (index);
return String.IsNullOrEmpty (ss) ? null : new Token (ss);
}
/// <summary>
/// Converts the literal string to the left of the provided wildcard match
/// into a Token object.
/// </summary>
/// <param name="taskPrototype">The task prototype string.</param>
/// <param name="cc">Read header for the task prototupe string pointing to
/// the start of the literal string</param>
/// <param name="m">The regular expression match object that contains the next
/// wildcard.</param>
private Token TokenizeLeftLiteralString(string taskPrototype, ref int cc, Wildcard w)
{
string ss = taskPrototype.Substring (cc, w.Index - cc);
cc = w.Index + w.Value.Length;
return String.IsNullOrEmpty (ss) ? null : new Token (ss);
}
/// <summary>
/// Converts the wildcard contained within the provided regular expression
/// match object into a Token object.
/// </summary>
/// <param name="m">The regular expression match object that contains the wildcard.</param>
private Token TokenizeWildcard(Wildcard w)
{
// Handle obfuscated wildcards
if (w.Obfuscated)
return TokenizeObfuscatedWildcard(w);
// Get a replacement for the wildcard
INameable inam = FindReplacement(w);
// Create the token
return new Token(w.Value, inam, FetchMetadata(w));
}
#endregion
#region Methods
/// <summary>
/// Evaluates the provided regular expression match object producing
/// an INameable replacement object
/// </summary>
/// <param name="m">The regular expression match object to evaluate.</param>
/// <returns>An INameable replacement object if an adequate replacement
/// could be found or produced, null otherwise.</returns>
private INameable FindReplacement(Wildcard w)
{
if (!w.Success)
return null;
switch (w.Name)
{
case "category":
return EvaluateCategory(w);
case "gesture":
return EvaluateGesture(w);
case "name": case "female": case "male":
return EvaluateName(w);
case "location": case "beacon": case "placement": case "room":
return EvaluateLocation(w);
case "object": case "aobject": case "kobject":
return EvaluateObject(w);
case "question":
return EvaluateQuestion(w);
case "void":
return EvaluateVoid(w);
default:
return null;
}
}
/// <summary>
/// Evaluates the provided regular expression match object producing
/// an replacement string
private string Evaluator(Wildcard w)
{
INameable inam = FindReplacement(w);
if (inam != null)
return inam.Name;
return w.Value;
}
/// <summary>
/// Fills the availability lists with information from the Generator databases
/// </summary>
private void FillAvailabilityLists()
{
// Copy objects from generator's lists
this.avCategories = new List<Category>(generator.AllObjects.Categories);
this.avGestures = GetTieredList(generator.AllGestures);
this.avLocations = new List<Location>(generator.AllLocations);
this.avNames = new List<PersonName>(generator.AllNames);
this.avObjects = GetTieredList(generator.AllObjects.Objects);
this.avQuestions = GetTieredList(generator.AllQuestions);
// Shuffle the availability list once in O(1) so just retrieve last
// item every time as random
this.avCategories.Shuffle(generator.Rnd);
this.avGestures.Shuffle(generator.Rnd);
this.avLocations.Shuffle(generator.Rnd);
this.avNames.Shuffle(generator.Rnd);
this.avObjects.Shuffle(generator.Rnd);
this.avQuestions.Shuffle(generator.Rnd);
}
/// <summary>
/// Extracts the metadata strings from a regular expression match object that
/// contains the wildcard
/// </summary>
/// <param name="m">The regular expression match object that contains the wildcard.</param>
private string[] FetchMetadata(Wildcard w){
string sMeta = w.Metadata;
if(String.IsNullOrEmpty(sMeta)) return null;
sMeta = ReplaceWildcards(sMeta);
return sMeta.Split (new string[]{"\r", "\n", @"\\", @"\\r", @"\\n"}, StringSplitOptions.None);
}
/// <summary>
/// Produces a Task from a task prototype string by replacing all the wildcards
/// within it
/// </summary>
/// <param name="taskPrototype">The task prototype string</param>
/// <returns>A Task based on the provided task prototype.</returns>
public Task GetTask(string taskPrototype)
{
int bcc = 0;
Token token;
// Find all wildcards in the task prototype
List<Wildcard> wildcards = FindWildcards(taskPrototype);
// Having n wildcards interlaced with literal strings and starting with a
// literal string there will be n+1 literal strings. Therefore, the worst
// number of tokens will never be greater than 2n+1
// Since the list may be reallocated, 2n+2 is used for performance
List<Token> tokens = new List<Token>(2 * wildcards.Count + 2);
// For each wildcard found
foreach (Wildcard w in wildcards) {
// Add the string on the left (if any) as a token
token = TokenizeLeftLiteralString (taskPrototype, ref bcc, w);
if(token != null) tokens.Add (token);
token = TokenizeWildcard(w);
tokens.Add (token);
}
// If there is more text to the right, add it as last token
token = TokenizeSubstring (taskPrototype, bcc);
if(token != null) tokens.Add (token);
// Build the task, add the tokens, and return it.
Task task = new Task () { Tokens = tokens };
return task;
}
/// <summary>
/// Replaces all wildcards in the input string with random values.
/// </summary>
/// <returns>The input string with all wildcards replaced.</returns>
/// <param name="taskPrototype">The input string</param>
public string ReplaceWildcards(string taskPrototype)
{
return GetTask(taskPrototype).ToString();
}
#endregion
#region Static Methods
public static List<Wildcard> FindWildcards(string s)
{
int cc = 0;
List<Wildcard> wildcards = new List<Wildcard>(100);
Wildcard w;
while (cc < s.Length)
{
if (s[cc] == '{')
{
w = Wildcard.XtractWildcard(s, ref cc);
if (w == null) continue;
wildcards.Add(w);
}
++cc;
}
return wildcards;
}
#endregion
}
}