Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import std.stdio;
- struct tableS
- {
- public:
- this(uint s)
- {
- table = new char[][size = s];
- nItems = 0;
- }
- void insert(char[] id)
- {
- if (find(id) > -1 || id.length > 32) {
- return;
- }
- if (nItems < size - 1) {
- writeln("id:", id, " table:", table);
- uint h = hash(id);
- uint h_new;
- uint i = 0;
- do {
- h_new = (h + i) % size;
- writeln("hash", ++i, ": ", h_new);
- } while (null != table[h_new]);
- table[h_new] = id.dup;
- ++nItems;
- } else {
- throw new Exception("table overflow");
- }
- }
- int find(char[] id) {
- uint h = hash(id);
- while (null != table[h]) {
- if (id == table[h]) {
- return h;
- }
- h = (h + 1) % size;
- }
- return -1;
- }
- void print()
- {
- writeln("find(id) index id");
- foreach (i, id; table) {
- writeln(" ", find(id), "\t ", i, " -> ", id);
- }
- }
- private:
- uint hash(char[] id)
- {
- return typeid(id).getHash(&id) % size;
- }
- char[][] table;
- uint size, nItems;
- }
- struct tableM
- {
- public:
- this(uint s)
- {
- table = new char[][size = s];
- nItems = 0;
- }
- void insert(char[] id)
- {
- if (find(id) > -1 || id.length > 32) {
- return;
- }
- if (nItems < size - 1) {
- uint h = hash(id);
- uint h_new;
- uint i = 1;
- writeln("id:", id, h, " table:", table);
- do {
- h_new = (h * i) % size;
- writeln("hash", i++, ": ", h_new);
- } while (null != table[h_new]);
- table[h_new] = id.dup;
- ++nItems;
- } else {
- throw new Exception("table overflow");
- }
- }
- int find(char[] id) {
- uint h = hash(id);
- uint i = 1;
- uint h_new = (h * i++) % size;
- while (null != table[h_new]) {
- if (id == table[h_new]) {
- return h_new;
- }
- h_new = (h * i++) % size;
- }
- return -1;
- }
- void print()
- {
- writeln("find(id) index id");
- foreach (i, id; table) {
- writeln(" ", find(id), "\t ", i, " -> ", id);
- }
- }
- private:
- uint hash(char[] id)
- {
- return 1 + (typeid(id).getHash(&id) % (size - 1));
- }
- char[][] table;
- uint size, nItems;
- }
- void main(char[][] args)
- {
- try {
- auto size = 7;
- auto f = File("file", "r");
- // auto m = tableM(size);
- auto s = tableS(size);
- foreach (id; f.byLine()) {
- // m.insert(id);
- s.insert(id);
- }
- // m.print();
- s.print();
- } catch (Exception e) {
- writeln(e);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement