Menu
Coddy logo textTech

size

Lekcja 9 z 14 w kursie Tablice haszujące – Struktury danych, część 4 w Coddy.

challenge icon

Wyzwanie

Łatwy

Dodaj metodę size do klasy HashMap.

Nie przyjmuje ona żadnych danych wejściowych i zwraca aktualną liczbę par przechowywanych w tablicy (wartość count).

Spróbuj swoich sił

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hashmap.h"

int main() {
    HashMap h;
    HashMap_init(&h);
    char line[256];
    while (fgets(line, sizeof(line), stdin)) {
        line[strcspn(line, "\r\n")] = '\0';
        char* cmd = strtok(line, " \t");
        if (!cmd) continue;
        if (strcmp(cmd, "state") == 0) { printf("%d %d %d\n", h.capacity, h.capacity, h.count); }
        if (strcmp(cmd, "hash") == 0) { char* arg = strtok(NULL, " \t"); if (arg) printf("%d\n", HashMap_hash(&h, atoi(arg))); }
        if (strcmp(cmd, "put") == 0) { char* a = strtok(NULL, " \t"); char* b = strtok(NULL, " \t"); if (a && b) HashMap_put(&h, atoi(a), atoi(b)); }
        if (strcmp(cmd, "bucketSize") == 0) { char* arg = strtok(NULL, " \t"); if (arg) printf("%d\n", h.buckets[atoi(arg)].size); }
        if (strcmp(cmd, "count") == 0) { printf("%d\n", h.count); }
        if (strcmp(cmd, "get") == 0) { char* arg = strtok(NULL, " \t"); if (arg) printf("%d\n", HashMap_get(&h, atoi(arg))); }
        if (strcmp(cmd, "containsKey") == 0) { char* arg = strtok(NULL, " \t"); if (arg) printf("%s\n", HashMap_containsKey(&h, atoi(arg)) ? "true" : "false"); }
        if (strcmp(cmd, "remove") == 0) { char* arg = strtok(NULL, " \t"); if (arg) HashMap_remove(&h, atoi(arg)); }
        if (strcmp(cmd, "size") == 0) { printf("%d\n", HashMap_size(&h)); }
    }
    return 0;
}

Wszystkie lekcje w sekcji Tablice haszujące – Struktury danych, część 4

Poćwicz samodzielnie: Kompilator C online