Challenge
You must write a program which takes a string and a flag as input and performs one of the following functions.
Input
If your language does not support command line arguments, you may take the arguments as input via STDIN.
The flag will be two characters: a dash and an ASCII character such as -d
or -c
.
Functions
The following is the list of functions which you must implement in your program. The title of each is the flag which corresponds to the function.
Counting: -c
This counts the number of duplicate lines in the input file. For example, if the input is:
aa
aa
bb
bb
bb
xx
The output will be:
2 aa
3 bb
1 xx
Because there are two lines of aa, three lines of bb, and one line of xx. The output should be separated by newlines.
Duplication: -d
This shows which lines are duplicates. For example, using the above example string (aa\naa\nbb\nbb\nbb\nxx
), the output would be:
aa
bb
Because these are lines which have been duplicated. You should only output each line once.
Duplication: -D
This is almost the same as -d
except it outputs each line the number of times that it occurs in the input file. For example, using the example string the output will be:
aa
aa
bb
bb
bb
Because aa occurs twice and bb occurs three times.
Unique: -u
Similar to above except it only prints unique lines. For example, using the example file, the output will be:
xx
Because xx is the only unique line. Also, due to xx being unique, you will only ever have to output this once.
Example
Note that although the input string will not always be sorted, the output must be sorted alphabetically. For example, for the following input:
hello world
apple pie
zebra
dog
hello world
apple pie
apple pie
apple pie
The output for each of the flags would be:
-c
4 apple pie
1 dog
2 hello world
1 zebra
-d
apple pie
hello world
-D
apple pie
apple pie
apple pie
apple pie
hello world
hello world
-u
dog
zebra
Rules
Your programs must not use the UNIX program uniq as, frankly, that is plain cheating.
All output should be to STDOUT.
The file will only ever contain lowercase, alphabetical characters, newlines and spaces:
abcdefghijklmnopqrstuvwxyz
The output should be sorted alphabetically.
In case there is any confusion, programs written on any operating system can enter. The challenge is not limited to UNIX.
As per PPCG standard, functions and anonymous functions are allowed, taking input via their arguments and outputting via a returned string.
Winning
As this is code-golf, the shortest code in bytes wins.
["foo", "bar"], "-c"
be considered a valid input? (array of strings + flag as separated string) \$\endgroup\$