0

I have to implement a dictionary in c language without using pointers and with just help of the array. It has 2 functionalities of adding words and deleting words. It also has two arrays, one having the string of the elements of the dictionary and one(next[]) for saving the index of the next element. After adding words, the words need to be ordered according to their english name which works fine. My problem is in the second case which an element needs to be deleted. The functionality that we are looking for is to delete the element by swapping its position with the last element, deleting the last element and find the right position of the element which has been swapped with the deleted one. My codes works fine when the element is in the middle of the dictionary but when the element needs to be deleted is the first element, it deletes all the other elements except the first one(we expect it to do the same steps and also change the renew the starting index accordingly) and for the last element, it goes on a loop instead of just deleting that element. Can you help me fix this problem?

This is the code:

#include <stdio.h> 
#include <string.h> 
 
#define MAX_SIZE 10 
#define WORD_SIZE 20 
 
struct dictionary { 
    char english[WORD_SIZE]; 
    char turkish[WORD_SIZE]; 
}; 
 
int main() { 
    struct dictionary dict[MAX_SIZE]; 
    int next[MAX_SIZE]; 
    int size = 0; 
    int start = -1; 
 
    char input[WORD_SIZE]; 
    int choice = 0; 
 
    // Initialize next array 
    for (int i = 0; i < MAX_SIZE; i++) { 
        next[i] = i + 1; 
    } 
    next[MAX_SIZE - 1] = -1; 
 
    // Menu loop 
    while (choice != 4) { 
        printf("\n\nDictionary Menu:\n"); 
        printf("1. Add a word\n"); 
        printf("2. Delete a word\n"); 
        printf("3. View the dictionary\n"); 
        printf("4. Quit\n"); 
 
        printf("\nEnter your choice: "); 
        scanf("%d", &choice); 
 
        switch (choice) { 
            case 1: 
                if (size >= MAX_SIZE) { 
                    printf("The dictionary is full.\n"); 
                } else { 
                    // Add a new word 
                    printf("Enter the English word: "); 
                    scanf("%s", input); 
                    // Convert to lowercase 
                    for (int i = 0; i < strlen(input); i++) { 
                        input[i] = tolower(input[i]); 
                    } 
                    strcpy(dict[size].english, input); 
 
                    printf("Enter the Turkish word: "); 
                    scanf("%s", input); 
                    strcpy(dict[size].turkish, input); 
 
                    // Find the correct position for the new word 
                    int curr = start; 
                    int prev = -1; 
                    while (curr != -1 && strcmp(dict[curr].english, dict[size].english) < 0) { 
                        prev = curr; 
                        curr = next[curr]; 
                    } 
 
                    // Insert the new word at the correct position 
                    if (prev == -1) { 
                        next[size] = start; 
                        start = size; 
                    } else { 
                        next[prev] = size; 
                        next[size] = curr; 
                    } 
                    size++; 
                    printf("Word added successfully.\n"); 
                } 
                break; 
                 
            case 2: 
                if (size == 0) { 
                    printf("The dictionary is empty.\n"); 
                } else { 
                    // Delete a word 
                    printf("Enter the English word to delete: "); 
                    scanf("%s", input); 
                    // Convert to lowercase 
                    for (int i = 0; i < strlen(input); i++) { 
                        input[i] = tolower(input[i]); 
                    } 
 
                    int curr = start; 
                    int prev = -1; 
                    int delete_index = -1; 
 
                    // Find the index of the word to delete 
                    while (curr != -1) { 
                        if (strcmp(dict[curr].english, input) == 0) { 
                            delete_index = curr; 
                            break; 
                        } 
                        prev = curr; 
                        curr = next[curr]; 
                    } 
 
                    if (delete_index == -1) { 
                        printf("The word '%s' is not in the dictionary.\n", input); 
                    } else { 
                        // Replace the deleted word with the last word in the dictionary 
                        size--; 
                        if (delete_index == size) { 
                            if (prev == -1) { 
                                start = -1; 
                            } else { 
                                next[prev] = -1; 
                            } 
                        } else { 
                            strcpy(dict[delete_index].english, dict[size].english); 
                            strcpy(dict[delete_index].turkish, dict[size].turkish);
next[delete_index] = next[size]; 
                            if (prev == -1) { 
                                start = delete_index; 
                            } else { 
                                next[prev] = delete_index; 
                            } 
                        } 
                        printf("The word '%s' has been deleted from the dictionary.\n", input); 
                    } 
                } 
                break; 
            case 3: 
                if (size == 0) { 
                    printf("The dictionary is empty.\n"); 
                } else { 
                    // Print all the words in the dictionary 
                    printf("English\tTurkish\n"); 
                    printf("-----------------\n"); 
                    int curr = start; 
                    while (curr != -1) { 
                        printf("%s\t%s\n", dict[curr].english, dict[curr].turkish); 
                        curr = next[curr]; 
                    } 
                } 
                break; 
            case 4: 
                printf("Goodbye!\n"); 
                break; 
            default: 
                printf("Invalid choice.\n"); 
        } 
    } 
 
    return 0; 
}
yasakrami
  • 25
  • 4
  • You have probably written too much code to be able to [*debug*](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) efficiently. Scale back your code, preferably to a plain and simple "hello world" program. Then add one ***small*** piece of code to the program. Build with extra warnings enabled and treat them as errors. Once it builds cleanly, *test* that little piece of code. When all is working, then continue to next small piece of code. And so on. Also use *functions* to divide the code into smaller and more manageable pieces. – Some programmer dude Mar 26 '23 at 09:49
  • If there's a problem, then using the above method will make it much easier to isolate the problem and debug it. I also recommend you learn how to use a [*debugger*](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) to step through your code line by line while monitoring variables and their values. In combination with pen and paper it's the best way to solve problems in code. – Some programmer dude Mar 26 '23 at 09:50
  • I have already tried this but I could not find the problem that is why I am asking. I would be grateful if you can help me figure out this problem and how to fix it. – yasakrami Mar 26 '23 at 09:54
  • You have problems "deleting" elements. Then make a small [mre] that only does that. Use hard-coded "input" (i.e. data in the actual source code). And as I advised, only implement it piece by piece. As long as every piece works, then it's fine. When the last piece you added makes it stop working, then you know where to look and probably also what to look for. And some debugging over only that little piece of code could help you create an even smaller and simpler example to debug. Do this in iterations until it's solved. – Some programmer dude Mar 26 '23 at 12:18
  • Copying the element from index `size` to the deleted spot has problems: you need to know which element has its `next` referring to `size`, because **that** one has to be set to -1, but you don't have that index unless you iterate the whole list to the end. This would not be very efficient. In fact, the whole idea of implementing a dictionary as a linked list is a bad one. A binary tree or trie (both can be implemented as arrays) would be much better. – trincot Mar 26 '23 at 20:26
  • Your insert algorithm tries to keep the list sorted, but even if you fix the delete operation, that algorithm to copy an element will not guarantee that the list remains sorted. You haven't told us whether the list has to be sorted at all times. It will be easier to work with the concept of a free list. That way you don't have to copy entries and you can keep the list sorted. – trincot Mar 26 '23 at 20:40

1 Answers1

0

C programming language does not provide any direct implementation of Map or Dictionary Data structure. However, it doesn't mean we cannot implement one. In C, a simple way to implement a map is to use arrays and store the key-value pairs as elements of the array.

How to implement Map in C?

One approach is to use two arrays, one for the keys and one for the values, where the key at index i in the key array corresponds to the value at index i in the value array.

  • Variables used to implement Map in C
    • This implementation uses two arrays, keys and values, to store the key-value pairs.
    • The maximum number of elements in the map is defined as MAX_SIZE.
    • The size variable keeps track of the current number of elements in the map.
  • Functions used to implement Map in C
    • The getIndex function searches for a key in the keys array and returns its index if found, or -1 if not found.
    • The insert function inserts a key-value pair into the map. If the key already exists, it updates the value.
    • The get function returns the value of a key in the map, or -1 if the key is not found.
    • The printMap function prints all the key-value pairs in the map. In the main function, we insert some key-value pairs into the map, get the value of some keys, and print the map.

Here's an example implementation of a map using arrays:

#include <stdio.h>
#include <string.h>

#define MAX_SIZE                                           \
    100 // Maximum number of elements in the map

int size = 0; // Current number of elements in the map
char keys[MAX_SIZE][100]; // Array to store the keys
int values[MAX_SIZE]; // Array to store the values

// Function to get the index of a key in the keys array
int getIndex(char key[])
{
    for (int i = 0; i < size; i++) {
        if (strcmp(keys[i], key) == 0) {
            return i;
        }
    }
    return -1; // Key not found
}

// Function to insert a key-value pair into the map
void insert(char key[], int value)
{
    int index = getIndex(key);
    if (index == -1) { // Key not found
        strcpy(keys[size], key);
        values[size] = value;
        size++;
    }
    else { // Key found
        values[index] = value;
    }
}

// Function to get the value of a key in the map
int get(char key[])
{
    int index = getIndex(key);
    if (index == -1) { // Key not found
        return -1;
    }
    else { // Key found
        return values[index];
    }
}

// Function to print the map
void printMap()
{
    for (int i = 0; i < size; i++) {
        printf("%s: %d\n", keys[i], values[i]);
    }
}

int main()
{
    insert("Geeks", 5);
    insert("GFG", 3);
    insert("GeeksforGeeks", 7);

    printf("Value of complete Map: \n");
    printMap();

    printf("\nValue of apple: %d\n", get("GFG"));
    printf("Index of GeeksforGeeks: %d\n",
           getIndex("GeeksforGeeks"));

    return 0;
}

Output

Value of complete Map: 
Geeks: 5
GFG: 3
GeeksforGeeks: 7

Value of apple: 3
Index of GeeksforGeeks: 2

This implementation is simple and easy to understand, but it has some limitations. One limitation is that the keys must be unique, otherwise the insert function will overwrite the value of an existing key. Another limitation is that the maximum size of the map is fixed, and if we exceed the maximum size, we cannot insert any more elements into the map.