<commit_before><commit_msg>Add CPT lesson on array mapping<commit_after>---
title: Array Mapping
description: Array mapping is a technique used to associate a key with a value.
layout: default
---

Primitive arrays map the key type (`int`) to a value (the type of the array). In this lesson, we will explore mapping with letters as keys.
{% highlight java %}
array[0] = 1;
{% endhighlight %}
Notice the `0` as the accessing index. This is the key. With arrays, the key is always an `int`.

However, we can take advantage of the fact that a `char` can be easily cast to an `int`.

---

Let's try a problem:
> Find the number of occurrences of each letter in a word.

We need to *map* each letter to an index in the array. Let's use `a` to `0`, `b` to `1`, `c` to `2`, ... , `z` to `25`. Conveniently, ASCII values of letters are in the same order, just with a different starting number.
{% highlight java%}
String word = "hello";
int[] occ = new int[26]; // Occurrences
for(char c : word.toCharArray()) {
	occ[c - 'a']++; // 'a' for lowercase and 'A' for uppercase
}
{% endhighlight %}

Mapping isn't limited to only letters though. Just use a bigger array to support more characters.
{% highlight java%}
String word = "mcpt.ca";
int[] occ = new int[256]; // Many more ASCII values
for(char c : word.toCharArray()) {
	occ[c]++;
}

// Print the occurences of only lowercase letters
for(char i = 'a'; i <= 'z'; i++) {
	System.out.println("The letter " + i + " occurs " + occ[i] + " times");
}
{% endhighlight %}
{'fraction_non_alphanumeric': 0.13395225464190982, 'fraction_numerical': 0.008620689655172414, 'mean_word_length': 3.7452830188679247, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6678785', 'n_tokens_mistral': 492, 'n_tokens_neox': 461, 'n_words': 226}