21

Something like this should work: public static string ToString(this Dictionary<string,string> source, string keyValueSeparator, string sequenceSeparator) { if (source == null) throw new ArgumentException("Parameter source can not be null."); var pairs = source.Select(x => string.Format("{0}{1}{2}", x.Key, keyValueSeparator, x.Value)); ...


16

Implementing a hash table This hash table implementation is a bit limited: it supports only String keys and int values. It would be good to generalize it. When getting a value of a key not in the table, the common expected behavior is null. Since you're using int as the type of values, this is not possible, but -1 just doesn't seem special enough to be ...


14

First and foremost there is std::unordered_map. If you just need a hash map, use it. What's wrong Your hash is an int, if your string consists of negative chars or overflows, you will get a negative value at the end. In C/C++ the modulo operator (%) returns a negative value for a negative input. How does that compile? What's Item? mBuckets = new Bucket&...


14

A few small points: public class HashTable<T, TU> Use more mnemonic names, like TKey, TValue here. public class HashTable<T, TU> The name indicates how the class is implemented; name it after what it does logically. This is a map, or a dictionary, or a key-value store, or whatever you want to call it. That it is a hash table is a mechanism; ...


13

General Many of the variable names lack meaning and are inconsistent. I cover some of them specifically below, but for example print is not a good choice for a list of suggestions--even though you intend to print them. Instead, suggestions clearly identifies what the list holds. Learn to use JavaDoc for documenting public classes and methods. Not only is ...


13

Note: I didn't have the willpower to go through and make all the edits and test your code with them like I normally do. Apologies. It should still work the same, but you'll want to double-check and call me out on any mistakes. IntKIntVEntry In your class Javadoc comment, you need to explain better what it does. Just Simple container class containing a ...


13

Each of these: string account = string.Empty; if (queryWhere.ContainsKey("account") && queryWhere["account"] != null && !string.IsNullOrEmpty(queryWhere["account"].ToString())) { account = queryWhere["account"].ToString(); } Should be reduced to: string account; if(!queryWhere.TryGetValue("account", out account)) { account =...


13

I think you are missing the point. Different objects can produce same hashcode. This can happen: obj.Equals(otherObj) // false obj.GetHashCode() == otherObj.GetHashCode() //true If for some reason you want your Equals methods to return true when hashcodes are equal, then by all means. Make sure to document this behavior though. However if you want to ...


13

I spotted some bugs: The functions malloc and realloc might fail if there is not enough memory, and in this case they would return NULL, and since the code does not check the result, this would lead to undefined behaviour. It's necessary to check the results of these functions. Update: a comment was skeptical about this recommendation, noting that on some ...


12

You're misusing the term strategy pattern. Instead of doing this kind of thing: template <class K, class V> void Map<K,V>::SetDataStructureStrategy(int ds_type) { if(ds_ != NULL) { delete ds_; } if(ds_type == DSType::DYNAMIC_MAP) { ds_ = new DynamicMap<K,V>; } else if(ds_type == DSType::ARRAY_MAP) { ds_ = new ...


12

Nit-picky stuff. private boolean same(final IntKeyIndex them, final int index) { final int k = keys.get(index); int t = them.getIndex(k); if (t != index) { return false; } return true; } I would think that you would just want to drop the if statement and return the boolean return t == index; EDIT: @Rolfl pointed out that ...


12

This entire answer refers to my rewrite of the asker's code on the Go Playground and is mostly a summary of our discussion on the chat.so Go/Golang room. For reference, I'm reproducing the code below: package main import ( "bufio" "io" "os" "strconv" ) // charSet is a limited bitset to contain all lowercase latin characters (a-z). type ...


11

I highly recommend Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin. It's an excellent source of great advice precisely aimed at your questions. The earlier you start, the fewer bad habits you'll need to unlearn later on. Formatting Your line length and whitespace seem okay, though you a little off from Sun's (now Oracle's) Java ...


11

In addition to @janos's comments and suggestions, I have some other issues to point out. Infinite loops Your code will enter an infinite loop when the table is full. Putting in the 33rd value will enter this loop: while (table[hash] != null && table[hash].getKey() != key) hash = (hash + 1) % TABLE_SIZE; Even in @janos's ...


11

While using methods with side effects in list- or dict-comprehensions is generally frowned upon, in this case you could make use of dict.pop to get the id and at the same time remove it from the dictionary. >>> a = [{'bar': 'baz', 'id': 'foo'}, {'bar': 'baz', 'id': 'qux'}] >>> {d.pop("id"): d for d in a} {'qux': {'bar': 'baz'}, 'foo': {'...


10

There are a couple of issues with this design. The first is that a default constructed Map object is in a state such that any operations on it will fail. The user instead has to call a bunch of set functions directly after construction. All of this should be moved directly into the constructor itself. The next issues are to do with language improvements. ...


10

Consider following the conventions of the standard library for member-names, so you can use generic algorithms with your class: size for getCount, empty for isEmpty, contains for containsKey, at/[] for getData. As Node is in Bucket, there's no sense in templating that too unless you need additional template-parameter (you don't). Consider killing the ...


10

typedef _t POSIX reserves identifiers ending in _t. You should maybe use _s also for the typedef: struct Foobar { void *foo; int32_t bar; }; typedef struct Foobar foobar_s; Or not use typedef at all. #define _MAX POSIX reserves identifiers ending in _MAX or _MIN. For your macros (or consts, but don't use enum for that) that design maximums ...


9

You can actually inline all this with the Aggregate method from LINQ. return d.Aggregate(new StringBuilder(), (sb, x) => sb.Append(x.Key + keySep + x.Value + pairSep), sb => sb.ToString(0, sb.Length - 1)); Assuming you can read LINQ, it is probably the cleanest. But it isn't the fastest. I tried all the proposed solutions, and the answer by Mattias ...


9

It looks like your implementation relies on Width.CompareTo(second.Width) to return either 1, 0, or -1. This assumption is wrong. If first.Length is greater than second.Length, CompareTo is allowed to return 9999, or 1, or 500. These could very well screw up your additions. Sure, the current .NET implementation returns either 1, 0, or -1, but that's an ...


8

Dict.h Do not do this. using namespace std; Especially in a header file. You are polluting the namespace for everybody that uses your header file (and you will break peoples code). Some people say its OK to use this in a source file. I disagree with even that as it causes problems in anything more than a toy program. But to make sure you don't get into ...


8

No Type Safety Currently your classes provide no type safety: Cache cache = new Cache(); cache.put("my key", Integer.class, 5); // ... String cached = cache.get("my key", String.class); This compiles but fails at runtime with a ClassCastException thrown by CachedValue.getValue. What's The Key? The reason why this can happen is that your class is not ...


8

I want to build a dictionary that allows multiple keys for one value: This is a very basic relational database. So the first piece of feedback is that new programmers often start coding with poorly defined test-cases or non-normalised test-cases whereby they get lost developing their test portfolio. If you would have started with clarifying your case, I'm ...


8

Normally operations on a hashmap should be pretty much constant (O(n)=1), so it's something like O(n) = n + 2*m (number of characters in the String plus twice the amount of different characters in the string, since you iterate twice over the map to find the max and the corresponding character). Memory should also be pretty much linear, since you are storing ...


8

You don't need to use Set since indexes can never repeat. Use a List isntead. You don't need to keep track of the count. You can just get indices.size(). That makes ShowIndexDuplicateData class unnecessary. You probably should be dealing with int[] rather than Integer[]. There aren't many reasons to have a Integer[] With that, you can really simplify ...


8

Bug Your algorithm is not quite correct. For example: areAnagrams("abc", "abc") -> true (correct) areAnagrams("abc", "abcd") -> true (wrong) areAnagrams("abcd", "abc") -> false (correct) The problem is that you are checking that the characters in s1 exist with the same frequency in s2. But there can be characters in s2 that do not exist ...


8

Separate responsibilities Key concepts are not separated well. The functionality of the hash table and user interaction are all mixed up and spread out across the various functions of the program. I propose a different program organization where the responsibilities are separated better: Create a class for the hash table, with functions put(key, value) ...


8

General Good work for a C newcomer! Welcome to the club! Thank you for providing a good test program, and for the macro to exercise the list code - that really helps give confidence in the implementation. The tests do have some limitations, since they only test inserting elements and freeing the entire table; there's no tests of lookup, updating values ...


7

You have a bug This doesn't compile for me: hm->[index] = k; hm->[index] = v; I think you meant this: hm->k[index] = k; hm->v[index] = v; Understanding the warnings and responding to them Recently, I wrote a C header file that defines a new type called HashMap that allows for the storage of key/value pairs. As comments pointed out, this ...


7

You have a lot of unnecessary vertical spacing which should be removed to improve readability. Based on the naming guidelines input parameter should be named using camelCase casing. Because WriteToRange() can be called also as a normal static method you need to check both input parameters for null. The storeDictionaryData is basically a object[...


Only top voted, non community-wiki answers of a minimum length are eligible