---
# System prepended metadata

title: Week 7 - Maps

---

# Week 7 - Maps

## Team

Team name: Totally Useless
Date: 2022/05/12

Members

| Role                                                                                                                                                                          | Name |
|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------|
| **Facilitator** keeps track of time, assigns tasks and makes sure all the group members are heard and that decisions are agreed upon.                                             |   Stefan   |
| **Spokesperson** communicates group’s questions and problems to the teacher and talks to other teams; presents the group’s findings.                                              |   Tautvydas   |
| **Reflector** observes and assesses the interactions and performance among team members. Provides positive feedback and intervenes with suggestions to improve groups’ processes. | Ines     |
| **Recorder** guides consensus building in the group by recording answers to questions. Collects important information and data.                                                   |   Adelina   |

## Activities

### Activity 1: The ctype header file

* The ctype.h header file of the C Standard Library declares several functions that are useful for testing and mapping characters.
* All the functions accepts int as a parameter, whose value must be EOF or representable as an unsigned char.
* Some of tyhe most useful functions in this header file are:
```c
int isalnum(int num) //This function identifies the alphanumeric characters
int isalpha(int num) //This function identifies the alphabets from other characters
int islower(int num) //This function identifies the lowercase alphabets.
int isupper(int num) //This function identifies the uppercase alphabets.
int isspace(int num) //This function identifies white-space characters.
int tolower(int num) //This function converts uppercase alphabet to lowercase alphabet.
int toupper(int num) //This function convert lowercase alphabet to uppercase alphabet. 
```
### Activity 2: Count letters in a string

```c
unsigned long countLetters(unsigned long counts[static 26], const char* str) {
    int count = 0;
    for(int i = 0; str[i] != '\0'; ++i){
        if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) {
            counts[tolower(str[i]) -'a']++;
            count++;
        }
    }
    return count;
}

int main(void){
	unsigned long counts[26] = {0};
	const char* text = "The Quick Brown Fox Jumps Over The Lazy Dog.";
	unsigned long total = countLetters(&counts[0], text);
	assert(35 == total);
	printCounts(&counts[0], false, true);
}
```

### Activity 3: Recognizing languages

```c
const char* makeSignature(unsigned long counts[static 26]) {
    static char signature[7];
    unsigned long temp[sizeof(signature)] = {0};
    signature[6] = '\0';

    for(unsigned long i = 0; i < sizeof(signature)-1; i++) {
        for(unsigned long j = 0; j < ('Z' - 'A' + 1); j++) {
            if(temp[i] < counts[j]) {
                unsigned long check = 0;
                for(unsigned long a = 0; a < i+1; a++) {
                    if (check == i) {
                        temp[i] = counts[j];
                        signature[i] = j + 'a';
                    }
                    if(temp[a] != counts[j]) {
                        check++;
                    }
                }
            }
        }
    }
    return &signature[0];
}

int main(void) {
    unsigned long counts1[26] = {15,3,4,5,16,6,7,8,9,7,6,3,2,11,14,1,2,12,13};
	unsigned long counts2[26] = {16,4,7,5,20,7,4,3,14,5,9,1,2,18,6,12,9,13,9,15};
	assert(strcmp("eaosrn", makeSignature(counts1)) == 0);
	assert(strcmp("enatir", makeSignature(counts2)) == 0);
}
```

| File       | Signature | Language |
| ---------- | --------- | -------- |
| alice0.txt |  etaoin   |   en     |
| alice1.txt |  iantes   |   fi     |
| alice2.txt |  eaionr   |   it     |
| alice3.txt |  enisra   |   de     |



### Activity 4: Find out: dictionaries around us

* The BSN number database which associates a person to a BSN number;
* University databases: a database of student numbers associated with a student;
* A database of OV Chipkaart numbers associated with a public transport user;
* A collection of unique numbers associated with different shoe brands;
* ID number databeses : a database of passport numbers associated to different travelers.

### Activity 5: Find out: dictionaries in other languages

* Python:
```python
mydict = {"name":"Max","age":28}
print(mydict)
```

* C#:
```csharp
In C#
private static Dictionary<string,object> dict;
dict = new Dictionary<string,object>();
```

* Java:
```java
Map<String, String> dictionary = new HashMap<String, String>();
dictionary.put("key", "value");
String value = dictionary.get("key");
```

* C++
```cpp
map<string,string> dictho;
cout << dictho.size(); //for example.
```

* Javascript:
```javascript
var dict = new Object();
//or
var dict = {
  FirstName: "Chris",
  "one": 1,
  1: "some value"
};
// using indexer
var name = dict["FirstName"];

// as property
var name = dict.FirstName;

```

* C++ functions:
```cpp
//inserting
    map<string,string> dictho;
    dictho.insert(pair<string,string>("Strawberry"," Aardbei"));
    dictho.insert(pair<string,string>("Orange"," Oranje"));
    dictho.insert(pair<string,string>("Apple"," Appel"));
    dictho.insert(pair<string,string>("Banana"," banaan"));
//Deleting
    dictho.erase("Orange");
//Checking if the key exists
  for(auto pair : dictho){
       if(dictho.find("Orange") != dictho.end()){
           cout << "key  found";
       }else{
           cout << "They key is not Found";
       }
    }
//Retriving
    string key;
    cin >> key;
    for(const auto& pair : dictho){
       if(pair.first == key){
           cout << "key  found and the value is " << pair.second;
       }else{
           cout << "They key is not Found";
       }
    }
```

* C# functions:
```csharp
//Inserting
Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>();  
AuthorList.Add("Mahesh Chand", 35);  

//Deleting
AuthorList.Remove("Mahesh Chand");  

//Checking if key exists
myDict.ContainsKey("India")
if (AuthorList.ContainsKey("Mahesh Chand"))
            Console.WriteLine("Key : Mahesh Chand is present");
  
        else
            Console.WriteLine("Key : Mahesh Chand is absent");

//Reteriving key
            int value;
            bool hasValue =  AuthorList.TryGetValue("Mahesh Chand", out value);
 if (hasValue)
            {
                Console.WriteLine(value);
            }
            else
            {
                Console.WriteLine("Key is not present");
            }

```
### Activity 6: The ensureCapacity function

```c
bool _ensureCapacity(counter_t* counter, const size_t minimumCapacity){
    size_t new_capacity = counter->capacity;
    while (minimumCapacity > new_capacity){
        new_capacity = new_capacity * GROWTH_FACTOR + 1;
    }

    if (new_capacity > counter->capacity){
       pair_t * new_data = realloc(counter->data, new_capacity * sizeof(pair_t));
       if(new_data != NULL){
           counter->data = new_data;
           counter->capacity = new_capacity;
           return true;
       }
    }
    return false;
}
```

### Activity 7: insertAt function
```c
static bool _insertAt(counter_t* counter, const size_t index, const char* key, unsigned long value){
    if (_ensureCapacity(counter, counter->size + 1)) {
        memmove(counter->data+index+1,counter->data+index,(counter->size-index) * sizeof(pair_t));
        counter->data[index] = makePair(key,value);
        counter->size++;
        return true;
    }
    return false;
}

int main() {
	counter_t counter;
	initCounter(&counter, 0);
	insert(&counter, "Bob", 3);
	insert(&counter, "Dave", 4);
	insert(&counter, "Alice", 5);
	insert(&counter, "Eva", 3);
	insert(&counter, "Charlie", 7);
	assert(strcmp(counter.data[0].key, "Alice") == 0);
	assert(counter.data[0].value == 5);
	assert(strcmp(counter.data[1].key, "Bob") == 0);
	assert(counter.data[1].value == 3);
	assert(strcmp(counter.data[2].key, "Charlie") == 0);
	assert(counter.data[2].value == 7);
	assert(strcmp(counter.data[3].key, "Dave") == 0);
	assert(counter.data[3].value == 4);
	assert(strcmp(counter.data[4].key, "Eva") == 0);
	assert(counter.data[4].value == 3);
	assert(counter.size == 5);
	assert(counter.capacity >= counter.size);
	destroyCounter(&counter);
}
```

### Activity 8: Increment function
```c
unsigned long increment(counter_t* counter, const char* key){
    if(key!=NULL && counter != NULL)
    {
        long temp = getOrDefault(counter,key,0);
        insert(counter,key,temp+1);
        return temp+1;
    }
    return 0;
}

int main(void) {
	counter_t counter;
	initCounter(&counter, 0);
	increment(&counter, "Alice");
	increment(&counter, "Alice");
	increment(&counter, "Alice");
	increment(&counter, "Bob");
	increment(&counter, "Bob");
	assert(counter.size == 2);
	assert(counter.data[0].value == 3);
	assert(counter.data[1].value == 2);
	destroyCounter(&counter);
}
```

### Activity 9: Find out: function `strtok`

Strtok is a function that takes a character array and a list of a char of separator characters as an argument and it is used to separate a string by checking the separator character and "breaking" the string into different "tokens". If a token is found, a pointer to the beginning of the token is returned.
Otherwise, a null pointer. A null pointer is always returned when the end of the string is reached in the string being scanned.
```c
 void processLine(counter_t* counter, char* line) {

 // a const char variable of separator characters created
 const char* sep = "\t (),.;:?!\"\n'";
     
// calling strtok to split the line given as a parameter 
// and splitting it when catching a one of the "sep" characters
 char* token = strtok(line, sep);

// a loop that goes through the line and 
// splits it into tokens until the end of the string is reached
 while (token) {
 if (strlen(token))
// increment the token count
 increment(counter, token);
//  overwriting token with NULL to terminate the current token
 token = strtok(NULL, sep);
 }
}
```

### Activity 10: How many words?

Unique words: 4385
Times Alice appears: 393
Times the appears: 1549
Times rabbit appears: 3
```c
    counter_t counter;
    counter = processFile("alice0.txt");
    unsigned long temp1 = increment(&counter,"Alice");
    unsigned long temp2 = increment(&counter,"the");
    unsigned long temp3 = increment(&counter,"rabbit");
    printf("%zu\n",counter.size);
    printf("%lu\n",temp1);
    printf("%lu\n",temp2);
    printf("%lu\n",temp3);
    destroyCounter(&counter);
    return 0;
```

## Looking back

### What we've learnt

We have learned more during this week to use dictionaries and mapping.

### What were the surprises

We haven't had any big surprises.

### What problems we've encountered

We haven't encountered any problems in the activities but we found problems in meeting up during exams and holidays.

### What was or still is unclear

Nothing for this week.

### How did the group perform?
The exam period and the holidays made it hard for us to meet and work on the activities since each one of us was in a different country. 


How was the collaboration? What were the reasons for hick-ups? What worked well? What can be improved next time?





> Written with [StackEdit](https://stackedit.io/).
