char * reverse(const char * in, char * out, size_t out_len){
out[out_len - 1] = 0;
int i = 0;
while(!(ou_str[out_len - 1 - i] = in_str[i]))
++i;
return &(ou_str[out_len - 1 - i]);
} out must point to a big enough buffer
ascending :: (Ord a) => (b -> a) -> Comparator b
ascending f x y = compare (f x) (f y)
descending :: (Ord a) => (b -> a) -> Comparator b
descending = flip . ascending
secondary :: Comparator a -> Comparator a -> Comparator a
secondary f g x y = case f x y of {
EQ -> g x y;
z -> z; }
-- Returns a list of unique elements together with their frequency. Listed in decreasing order of frequency, followed by
increasing order of the elements.
count :: (Ord a) => [a] -> [(a, Int)]
count = map (head &&& length) . sortBy (descending length `secondary` ascending head) . group . sort
main :: IO ()
main = interact $ unlines . map (\(x, y) -> (take 20 $ x ++ repeat ' ') ++ " : " ++ show y) . count . words
Name:
Anonymous2012-10-29 16:56
>>8
How come? Not evaluating in[0] ?
Or **out++ = *in; instead of **out = *in;
++out;
>>21
The size is the one as reported by strlen(in), so it shouldn't segfault. Mayhaps a better idea would be
void reverse(char* in, char* out) {
int sz = strlen(in);
out[size] = 0;
rev(in, out+size-1);
}
But this wouldn't exactly be ideal, in my opinion.
You're right about the stack thing, though, it's completely unnecessary. I forgot, is TCO a thing in C compilers or is gcc the only one that supports it?
void rev(char* in, char* out) {
for (;;) {
*out = *in;
if (*in) { in++; out--; }
else { return; }
}
}
The length of a C string is determined by the terminating null-character: A C string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself).
This should not be confused with the size of the array that holds the string. For example:
char mystr[100]="test string";
defines an array of characters with a size of 100 chars, but the C string with which mystr has been initialized has a length of only 11 characters. Therefore, while sizeof(mystr) evaluates to 100, strlen(mystr) returns 11.
>>30
I know I had a brain fart, thinking about typeof, I was so embarrassed with the aberration I just said that I closed the computer and went outside