How to print all possible balanced parentheses for an expression?

Here is actual code in Python, using generators to avoid using too much memory. #! /usr/bin/python def parenthesized (exprs): if len(exprs) == 1: yield exprs[0] else: first_exprs = [] last_exprs = list(exprs) while 1 < len(last_exprs): first_exprs.append(last_exprs.pop(0)) for x in parenthesized(first_exprs): if 1 < len(first_exprs): x = ‘(%s)’ % x for y in parenthesized(last_exprs): if … Read more

Eric Lippert’s challenge “comma-quibbling”, best answer?

Inefficient, but I think clear. public static string CommaQuibbling(IEnumerable<string> items) { List<String> list = new List<String>(items); if (list.Count == 0) { return “{}”; } if (list.Count == 1) { return “{” + list[0] + “}”; } String[] initial = list.GetRange(0, list.Count – 1).ToArray(); return “{” + String.Join(“, “, initial) + ” and ” + list[list.Count … Read more

Compile time sizeof_array without using a macro

Try the following from here: template <typename T, size_t N> char ( &_ArraySizeHelper( T (&array)[N] ))[N]; #define mycountof( array ) (sizeof( _ArraySizeHelper( array ) )) int testarray[10]; enum { testsize = mycountof(testarray) }; void test() { printf(“The array count is: %d\n”, testsize); } It should print out: “The array count is: 10”

Efficiently reverse the order of the words (not characters) in an array of characters

A solution in C/C++: void swap(char* str, int i, int j){ char t = str[i]; str[i] = str[j]; str[j] = t; } void reverse_string(char* str, int length){ for(int i=0; i<length/2; i++){ swap(str, i, length-i-1); } } void reverse_words(char* str){ int l = strlen(str); //Reverse string reverse_string(str,strlen(str)); int p=0; //Find word boundaries and reverse word by … Read more

How to test randomness (case in point – Shuffling)

Statistics. The de facto standard for testing RNGs is the Diehard suite (originally available at http://stat.fsu.edu/pub/diehard). Alternatively, the Ent program provides tests that are simpler to interpret but less comprehensive. As for shuffling algorithms, use a well-known algorithm such as Fisher-Yates (a.k.a “Knuth Shuffle”). The shuffle will be uniformly random so long as the underlying … Read more