String Powers
This past semester, I took a course on Computer Science Theory. In particular, CS659 at UNH. The course is intended to give an introduction to the fundamentals of what makes computing work - formal and informal proofs, program verification, finite automata (deterministic and nondeterministic), languages, pushdown automata, and lots of other topics. This course was the toughest I've taken in the CS department to say the least (especially not being a huge math person). What a struggle that was!
There was one topic I found somewhat intriguing though - strings. Strings, in CS theory, are defined inductively. It is essentially a set of values where every member in the set is a value of an alphabet. So, in other words:
S = {wa | w € E* ^ a € E} *NOTE: I MAY HAVE BOTCHED THIS DEFINITION, BUT YOU SHOULD GET THE IDEA*
Similar to strings programmers are used to, you can perform a lot of operations on these strings (obtain substrings, put two strings together, etc). There's one operation that I found really neat but haven't seen around too much - that's the power operation.
The power operation on strings is essentially performing concatenation with a duplicate of itself. For example, lets say I did something like this (assuming Java syntax):
System.out.print( "abcd" + "abcd" );
I would get an output of "abcdabcd". The same output could be achieved from using the string power operation, where the power is 2 (note that this syntax does not exist in the Java String class):
System.out.print( "abcd".power( 2 ) );
Fancy, eh? If I'm not mistaken, operations like this can be performed on strings in other languages like Python (where you can multiply a string by a numeric value to repeat it that many times). While I can't come up with many practical uses for this form of operation, I found it to be a neat operation to have available. I sketched out a recursive function in Java to perform this operation (though it would be significantly more efficient done iteratively I believe).
public String pow( int n ) {
if ( n == 0 ) return "";
else return pow( n, this );
}f
private String pow( int n, String s ) {
if ( n == 1 ) return s;
else return s + pow( --n, s );
}
Another way to improve the performance of this is to force the use of a StringBuffer - This would force Java to not create n different instances of a String to be passed along and concatenated together. In general though, I found this to be a great little feature of formal strings. Maybe you can think of a good practical purpose?
Send lawyers, guns, and money;
The shit has hit the fan!
Warren Zevon, Lawyers, Guns, and Money
Tags: programming, cs, strings, java, warren zevon
