Skip to content

Commit 7d731a1

Browse files
authored
Merge pull request #3210 from ntrel/char-pair
[index.dd] Tweak character pair frequency example Signed-off-by: Dennis <dkorpel@users.noreply.github.com> Merged-on-behalf-of: Dennis <dkorpel@users.noreply.github.com>
2 parents 500a6eb + 7a52db7 commit 7d731a1

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

index.dd

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -204,20 +204,24 @@ void main()
204204
}
205205
----
206206
)
207-
$(EXTRA_EXAMPLE_RUNNABLE Count frequencies of all 2-tuples,
207+
$(EXTRA_EXAMPLE_RUNNABLE Count frequencies of character pairs,
208208
----
209209
void main()
210210
{
211211
import std.stdio : writefln;
212+
// An associative array mapping pairs of characters to integers
212213
int[char[2]] aa;
213214
auto arr = "ABBBA";
214215

215-
// Iterate over all pairs in the string and observe each pair
216-
// ('A', 'B'), ('B', 'B'), ('B', 'A'), ...
217-
// String slicing doesn't allocate a copy
216+
// Iterate over all pairs in the string
217+
// ['A', 'B'], ['B', 'B'], ..., ['B', 'A']
218218
foreach (i; 0 .. arr.length - 1)
219-
aa[arr[i .. $][0 .. 2]]++;
220-
219+
{
220+
// String slicing doesn't allocate a copy
221+
char[2] pair = arr[i .. i + 2];
222+
// count occurrences
223+
aa[pair]++;
224+
}
221225
foreach (key, value; aa)
222226
writefln("key: %s, value: %d", key, value);
223227
}

0 commit comments

Comments
 (0)