Solved Problems

Output a string to the console

Write the string "Hello World!" to STDOUT
clojure
(println "Hello World!")
cpp
std::cout << "Hello World" << std::endl;
std::printf("Hello World\n");
Console::WriteLine(L"Hello World");
csharp
System.Console.WriteLine("Hello World!")
erlang
io:format("Hello, World!~n").
fantom
echo("Hello World!")
fsharp
printfn "Hello World!"
groovy
println "Hello World!"
haskell
main = putStrLn "Hello World!"
java
System.out.println("Hello World!");
System.out.printf("Hello World!\n");
ocaml
print_string "Hello world!\n";;
print_endline "Hello world!";;
Printf.printf "Hello world!\n";;
perl
print "Hello World!\n"
python
print "Hello World!"
ruby
puts "Hello World!"
$stdout<<"Hello World!"
scala
println("Hello World!")
printf("Hello World!\n")

Define a string containing special characters

Define the literal string "\#{'}${"}/"
clojure
(def special "\\#{'}${\"}/")
cpp
std::string special = "\\#{'}${\"}/";
String^ special = L"\\#{'}${\"}/";
csharp
string verbatim = @"\#{'}${""""}/";
string cStyle = "\\#{'}${\"\"}/";
erlang
Special = "\\#{'}\${\"}/",
fantom
special := Str<|\#{'}${"}/|>
fsharp
let special = "\#{'}${\"}/"
groovy
special = "\\#{'}\${\"}/"
special = '\\#{\'}${"}/'
special = /\#{'}${'$'}{"}\//
haskell
putStrLn "\"\\#{'}${\"}/\""
let special = "\\#{'}${\"}/"
java
String special = "\\#{'}${\"}/";
ocaml
"\\#{'}${\"}/"
perl
$special = '\#{\'}${"}/';
$special = q(\#{'}${"}/);
python
# yes, Python has way too many forms of string literals :)
print "\\#{'}${\"}/"
print "\\#{'}${"'"'"}/"
print r"""\#{'}${"}/"""
print '\\#{\'}${"}/'
print '\\#{'"'"'}${"}/'
print r'''\#{'}${"}/'''
ruby
special = '\#{\'}${"}/'
scala
val special = "\\#{'}${\"}/"
val special2 = """\#{'}${"}/"""

Define a multiline string

Define the string:
"This
Is
A
Multiline
String"
clojure
(def multiline "This\nIs\nA\nMultiline\nString")
cpp
std::string text =
"This\n"
"Is\n"
"A\n"
"Multiline\n"
"String";
String^ text = L"This\nIs\nA\nMultiline\nString";
std::string text = "This\nIs\nA\nMultiline\nString";
csharp
string output = "This\nIs\nA\nMultiline\nString";
string output = @"This
Is
A
Multiline
String";
erlang
Text = "This\nIs\nA\nMultiline\nString",
fantom
s := "This
Is
A
Multiline
String"
fsharp
let multiline = "This\nIs\nA\nMultiline\nString"
let multiline = "This
Is
A
Multiline
String"
groovy
def text =
"""This
Is
A
Multiline
String"""
def text = "This\nIs\nA\nMultiline\nString"
haskell
s = "This \
\Is \
\A \
\Multiline \
\String"
java
String text = "This\nIs\nA\nMultiline\nString";
String text =
"This\n" +
"Is\n" +
"A\n" +
"Multiline\n" +
"String"
ocaml
"This\nIs\nA\nMultiline\nString"
"This
Is
A
Multiline
String"
perl
$text = 'This
Is
A
Multiline
String';
$text = <<EOF;
This
Is
A
Multiline
String
EOF
python
text = """This
Is
A
Multiline
String"""
# with proper indentation
text = (
"This\n"
"Is\n"
"A\n"
"Multiline\n"
"String"
)
ruby
text = <<"HERE"
This
Is
A
Multiline
String
HERE
text = "This\nIs\nA\nMultiline\nString"
scala
val text = """This
Is
A
Multiline
String"""
val text = "This\nIs\nA\nMultiline\nString"

Define a string containing variables and expressions

Given variables a=3 and b=4 output "3+4=7"
clojure
(format "%d + %d = %d" a b (+ a b))
cpp
Console::WriteLine(L"{0}+{1}={2}", a, b, a+b);
std::printf("%d+%d=%d\n", a, b, a+b);
std::cout << boost::format("%|1|+%|1|=%|1|") % a % b % (a+b) << std::endl;
csharp
int a = 3;
int b = 4;
Console.WriteLine("{0}+{1}={2}", a,b,a+b);
erlang
A = 3, B = 4,
io:format("~B+~B=~B~n", [A, B, (A+B)]).
fantom
echo("$a+$b=${a+b}")
fsharp
let a, b = 3, 4
let mystr = sprintf "%d+%d=%d" a b (a+b)
printfn "%s" mystr
groovy
println "$a+$b=${a+b}"
printf "%d+%d=%d\n", a, b, a + b
haskell
import Text.Printf

main = do
let a = 3
let b = 4
printf "%d+%d=%d" a b (a + b)
a = 3
b = 4
s = show a ++ "+" ++ show b ++ "=" ++ show (a + b)
main = putStrLn s
java
System.out.println(a + "+" + b + "=" + (a+b));
System.out.printf("%d+%d=%d\n", a, b, a + b);
ocaml
Printf.printf "%d+%d=%d" a b (a+b);;
Printf.printf "%d+%d=%d" a b (a+b);;
perl
print "$a+$b=${\($a+$b)}\n";
sprintf("%d+%d=%d", $a, $b, $a + $b);
print $a, '+', $b, '=', $a + $b;
python
class EvalDict(dict):
def __getitem__(s, k):
return eval(k, s)

a=3; b=4
"%(a)d+%(b)d=%(a+b)d" % EvalDict(locals())
a=3; b=4
"%d+%d=%d" % (a, b, a+b)
ruby
puts "#{a}+#{b}=#{a+b}"
puts "#{a}+#{b}=%s" % (a + b)
scala
printf("%d+%d=%d\n", a, b, a + b)
"%d+%d=%d".format(a, b, a + b)
s"$a + $b = ${a+b}"

Reverse the characters in a string

Given the string "reverse me", produce the string "em esrever"
clojure
(require '[clojure.contrib.str-utils2 :as str])
(str/reverse "reverse me")
(apply str (reverse "reverse me"))
cpp
String^ s = "reverse me";
array<Char>^ sa = s->ToCharArray();
Array::Reverse(sa);
String^ sr = gcnew String(sa);
std::string s = "reverse me";
std::reverse(s.begin(), s.end());
std::string s = "reverse me";
std::string sr(s.rbegin(), s.rend());
std::string s = "reverse me";
std::swap_ranges(s.begin(), (s.begin() + s.size() / 2), s.rbegin());
csharp
var str = "reverse me";
Console.WriteLine(new String(str.Reverse().ToArray()));
erlang
Reversed = lists:reverse("reverse me"),
Reversed = revchars("reverse me"),
fantom
"reverse me".reverse
fsharp
let reversed = new String (Array.rev ("reverse me".ToCharArray()))
let word = "reverse me"
//reverse the word
let reversedword =
word.ToCharArray()
|> Array.fold(fun acc x -> x::acc) []
groovy
reversed = "reverse me".reverse()
haskell
reverse "reverse me"
java
String reverse = new StringBuffer("reverse me").reverse().toString();
String reverse = new StringBuilder("reverse me").reverse().toString();
String reverse = StringUtils.reverse("reverse me");
ocaml
let reverse str =
let len = String.length str in
let res = String.create len in
for i = 0 to pred len do
let j = pred len - i in
res.[i] <- str.[j]
done;
(res)
let rev_char str =
let l = Str.split (Str.regexp "") str in
List.fold_left (fun a b -> b ^ a) "" l
;;
perl
$_ = reverse "reverse me"; print
python
"reverse me"[::-1]
ruby
puts "reverse me".reverse
scala
val reversed = "reverse me".reverse

Reverse the words in a string

Given the string "This is a end, my only friend!", produce the string "friend! only my end, the is This"
clojure
(require '[clojure.contrib.str-utils2 :as str])
(str/join " " (reverse (str/split "this is the end, my only friend!" #" ")))
(apply str (interpose " " (reverse (re-seq #"[^\s]+" "This is the end, my only friend!"))))
cpp
array<Char>^ sep = {L' '};
array<String^>^ words =
String(L"This is the end, my only friend!").Split(sep, StringSplitOptions::RemoveEmptyEntries);

Array::Reverse(words); String^ newwords = String::Join(L" ", words);
std::string words = "This is the end, my only friend!"; std::vector<std::string> swv;

boost::split(swv, words, boost::is_any_of(" ")); std::reverse(swv.begin(), swv.end());
std::string newwords = (std::for_each(swv.begin(), swv.end(), StringTAndJ())).value();
csharp
var str = "This is a end, my only friend!";
str = String.Join(" ", str.Split().Reverse().ToArray());
Console.WriteLine(str);
erlang
Reversed = string:join(lists:reverse(string:tokens("This is the end, my only friend!", " ")), " "),
fantom
"This is a end, my only friend!".split.reverse.join(" ")
fsharp
let reversed = String.Join(" ", Array.rev("This is the end, my only friend!".Split [|' '|]))
groovy
reversed = "This is the end, my only friend!".split().reverse().join(' ')
reversed = "This is the end, my only friend!".tokenize(' ').reverse().join(' ')
def revdelim(c, s) { StringUtils.reverseDelimited(s, c) }
revwords = this.&revdelim.curry(" " as char)
reversed = revwords("This is the end, my only friend!")
reversed = StringUtils.reverseDelimited("This is the end, my only friend!", " " as char)
haskell
unwords (reverse (words "This is the end, my only friend!"))
java
List list = new ArrayList();
StringTokenizer st = new StringTokenizer(text, " ");
while(st.hasMoreTokens()) {
list.add(0, st.nextToken());
}
StringBuffer sb = new StringBuffer();
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
String word = (String) iterator.next();
sb.append(word);
if (iterator.hasNext()) {
sb.append(" ");
}
}
String reversed = sb.toString();
List<String> ls = Arrays.asList("This is the end, my only friend!".split("\\s"));
Collections.reverse(ls);
StringBuilder sb = new StringBuilder(32); for (String s : ls) sb.append(" ").append(s);
String reversed = sb.toString().trim();
String reversed = StringUtils.reverseDelimited("This is the end, my only friend!", ' ');
ocaml
let rev_words str =
let l = Str.split (Str.regexp " ") str in
String.concat " " (List.rev l)
;;
perl
$reversed = join ' ', reverse split / /, $text;
python
' '.join(reversed("This is a end, my only friend!".split()))
ruby
reversed = text.split.reverse.join(' ')
scala
"This is the end, my only friend!".split(" ").reverse.reduceLeft( (x,y) => x+' '+y )
val reversed = revwords("This is the end, my only friend!")
(("This is the end, my only friend!" split " ") reverse) mkString " "
val reversedText = text.split(" ").reverse.mkString(" ")

Text wrapping

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> ", yielding this result:

> The quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog.
clojure
(doseq [line (re-seq #".{0,70} "
(apply str
(repeat 10 "The quick brown fox jumps over the lazy dog. ")))]
(println ">" line))
cpp
String^ input = ::copies("The quick brown fox jumps over the lazy dog. ", 10);
String^ sep = " "; String^ prefix = "> ";

String^ wrapped = textwrap(input, 74 - prefix->Length, sep, prefix);
Console::WriteLine("{0}", wrapped);
void rep(ostream &os, const string& str, int times)
{
while (times--)
os << str;
}

void wrap(ostream &os, const string& str, const string &prefix, int width)
{
int line_len = width;
bool first_word = true;

width -= prefix.size();
BOOST_FOREACH(string word, tokenizer<char_separator<char>>(str, char_separator<char>(" ")))
{
line_len += word.size();
if (line_len++ < width)
os << ' ';
else {
if (first_word)
first_word = false;
else
os << endl;
os << prefix;
line_len = word.size();
}
os << word;
}
os << endl;
}

int main()
{
stringstream input;

rep(input, "The quick brown fox jumps over the lazy dog. ", 10);
wrap(cout, input.str(), "> ", 72);
}
csharp
using System;
using System.Text;
using System.Linq; // used for Array.ToList() extension

public class TextWrapper {

/// <summary>
/// Wrap the given text to a given width.
/// </summary>
/// <param name="text">The text to be wrapped</param>
/// <param name="width">The maximum width of each line</param>
/// <param name="prefix">Begin each line with this prefix</param>
/// <returns>The wrapped text</returns>
public string Wrap(string text, int width, string prefix) {

var words = text.Split(' ').ToList();
var result = new StringBuilder(prefix);

width = width - prefix.Length;
prefix = "\n" + prefix;

int lineSize = 0;
foreach (var word in words) {
int wordLen = word.Length;

// Do we need to start a new line?
if ((lineSize + wordLen) > width) {
result.Remove(result.Length - 1, 1); // remove trailing space
lineSize = 0;
result.Append( prefix );
}

result.Append(word).Append(' ');
lineSize += wordLen + 1;
}

return result.ToString();
}

public static void Main() {
var prefix = "> ";
var sentence = "The quick brown fox jumps over the lazy dog. ";

var text = "";
for (int i = 0; i < 10; i++)
text += sentence;

// The description said lines of length 78, but
// the example was 72...
Console.WriteLine(new TextWrapper().Wrap(text, 72, prefix));
}
}
erlang
TextWrap = textwrap(string:copies(Input, 10), 73 - length(Prefix)),
lists:foreach(fun (Line) -> io:format("~s~n", [string:concat(Prefix, Line)]) end, string:tokens(TextWrap, "\n")).
fantom
buf := Buf()
10.times { buf.writeChars("The quick brown fox jumps over the lazy dog. ") }
buf.flip

out := Env.cur.out
sep := ">"; max := 72 - sep.size - 1
acc := 0; Str? s := null
while ((s = buf.readStrToken) != null)
{
if (acc == 0)
out.print(sep)

acc += s.size
if (acc > max)
{
out.print("\n$sep")
acc = s.size
}
out.print(" $s")
buf.readStrToken(4096) { !it.isSpace }
acc++
}
fsharp
let prefix = "> "
let input = "The quick brown fox jumps over the lazy dog. "

(String.split ['\n'] (textwrap (copies input 10) (73 - prefix.Length))) |> List.iter (fun line -> printfn "%s%s" prefix line)
let output maxWidth (s: string) =
let rec wrap = function
| lineSoFar, ([| |]: string array)-> printfn "%s" lineSoFar
| ">" as lineSoFar, (words: string array) ->
// Handle this case separately, thus we can also deal with
// cases where a word is longer then the max width
wrap (lineSoFar + " " + words.[0], Array.sub words 1 (words.Length - 1))
| lineSoFar, words when words.[0].Length + lineSoFar.Length >= maxWidth ->
printfn "%s" lineSoFar
wrap (">", words)
| lineSoFar, words ->
wrap(lineSoFar + " " + words.[0], Array.sub words 1 (words.Length - 1))
wrap (">", s.Split([| ' ' |]))

[| for i in 1 .. 10 do yield "The quick brown fox jumps over the lazy dog." |]
|> String.concat " "
|> output 78
groovy
// no built-in fill, define one using brute force approach
def fill(text, width=80, prefix='') {
width = width - prefix.size()
def out = []
List words = text.replaceAll("\n", " ").split(" ")
while (words) {
def line = ''
while (words) {
if (line.size() + words[0].size() + 1 > width) break
if (line) line += ' '
line += words[0]
words = words.tail()
}
out += prefix + line
}
out.join("\n")
}
println fill('The quick brown fox jumps over the lazy dog. ' * 10, 72, '> ')
// no built-in fill, define one using lastIndexOf
def fill(text, width=80, prefix='') {
def out = ''
def remaining = text.replaceAll("\n", " ")
while (remaining) {
def next = prefix + remaining
def found = next.lastIndexOf(' ', width)
if (found == -1) remaining = ''
else {
remaining = next.substring(found + 1)
next = next[0..found]
}
out += next + '\n'
}
out
}
println fill('The quick brown fox jumps over the lazy dog. ' * 10, 72, '> ')
prefix = '> '
input = 'The quick brown fox jumps over the lazy dog. '
wrap(input * 10, 72 - prefix.size()).eachLine{ println prefix + it }
haskell
import Data.List (intercalate)

-- our list of words ["The", "quick", "brown", ...]
dogs = concat$ replicate 10$ words "The quick brown fox jumps over the lazy dog."

-- ["The", "The quick", "The quick brown", ...]
concats = scanl1 (\s v -> s ++ " " ++ v)

-- takes list of words, returns list of lines
wordwrap :: Int -> [String] -> [String]
wordwrap maxwidth [] = []
wordwrap maxwidth ws = sentence : (wordwrap maxwidth restwords)
where
zipped = zip (concats ws) ws
(sentences, rest) = span (\(s,w) -> (length s) <= maxwidth) zipped
sentence = last (map fst sentences)
restwords = map snd rest

main = putStrLn ("> " ++ intercalate "\n> " (wordwrap 76 dogs))
java
String prefix = "> "; String input = "The quick brown fox jumps over the lazy dog.";

String[] lines = WordUtils.wrap(StringUtils.repeat(input, 10), 72 - prefix.length()).split("\n");

for (String line : lines) System.out.printf("%s%s\n", prefix, line);
ocaml
(* ocamlbuild -no-hygiene textwrap.native && ./textwrap.native *)

let wrap s prefix width =
let width = width - (String.length prefix) in
let len = String.length s in
let rec loop start =
if start >= len then
[]
else
let stop = min (len - start) width in
let sub = String.sub s start stop in
(prefix ^ sub) :: loop (start+stop)
in
loop 0
in

let wrap_and_print s prefix width =
List.iter print_endline (wrap s prefix width)
in
let s = ref "" in
for i = 1 to 10 do
s := !s ^ "The quick brown fox jumps over the lazy dog. "
done;
wrap_and_print !s "> " 78


perl
use Text::Wrap;
$text = "The quick brown fox jumps over the lazy dog. ";
$Text::Wrap::columns = 73;
print wrap('> ', '> ', $text x 10);
$_ = "The quick brown fox jumps over the lazy dog. " x 10;
s/(.{0,70}) /> $1\n/g;
print;
python
import textwrap
print textwrap.fill("The quick brown fox jumps over the lazy dog. " * 10,
72, initial_indent="> ", subsequent_indent="> ")
ruby
prefix = "> "
string = "The quick brown fox jumps over the lazy dog. " * 10
width = 78
realwidth = width - prefix.length
print string.gsub(/(.{1,#{realwidth}})(?: +|$)\n?|(.{#{realwidth}})/, "#{prefix}\\1\\2\n")
scala
val prefix = "> " ; val input = "The quick brown fox jumps over the lazy dog."

WordUtils.wrap(input * 10, 72 - prefix.length).split("\n") foreach {(x) => printf("%s%s\n", prefix, x)}
def wrap(words: List[String]): List[List[String]] = words match {
case Nil => Nil
case _ =>
val output = (words.inits.dropWhile { _.mkString(" ").length > 78 }) next;
output :: wrap(words.drop(output.length))
}

wrap(("The quick brown fox jumps over the lazy dog. " * 10) split(" ") toList) foreach {
words => println("> " + words.mkString(" "))
}

Remove leading and trailing whitespace from a string

Given the string "  hello    " return the string "hello".
clojure
(use 'clojure.contrib.str-utils2)
(trim " hello ")
(clojure.string/trim " hello ")
(.trim " hello ")
cpp
String^ s = " hello "; String^ trimmed = s->Trim();
csharp
string str = " hello ";
str = str.Trim();
Console.WriteLine(str);
erlang
Trimmed = string:strip(S),
fantom
s := " hello ".trim
fsharp
let s = " hello "
let trimmed = s.Trim()
let trimmed = " hello ".Trim()
groovy
assert "hello" == " hello ".trim()
haskell
unwords (words " hello ")
java
String s = " hello "; String trimmed = s.trim();
ocaml
let left_pos s len =
let rec aux i =
if i >= len then None
else match s.[i] with
| ' ' | '\n' | '\t' | '\r' -> aux (succ i)
| _ -> Some i
in
aux 0

let right_pos s len =
let rec aux i =
if i < 0 then None
else match s.[i] with
| ' ' | '\n' | '\t' | '\r' -> aux (pred i)
| _ -> Some i
in
aux (pred len)

let trim s =
let len = String.length s in
match left_pos s len, right_pos s len with
| Some i, Some j -> String.sub s i (j - i + 1)
| None, None -> ""
| _ -> assert false

let () =
let res = trim " hello " in
print_endline res
perl
my $string = " hello ";
$string =~ s{
\A\s* # Any number of spaces at the start of the string
(.+?) # Remember any number of characters until we reach
\s*\z # any number of spaces at the end of the string
}{
$1 # Leave the characters we remembered
}x;
my $string = " hello ";
$string =~ s{\A\s*}{};
$string =~ s{\s*\z}{};

#Modification History:
# 2009-MAR-17: GGARIEPY: [creation] (geoff.gariepy@gmail.com)

$string = " hello ";
$string =~ s/^\s+|\s+$//g; # All the action happens in one regex!

# Regex Notes:
# ^ - anchors to the beginning of the string
# $ - anchors to the end of the string
# g - causes regex to match as many times as possible
# | - logical OR
python
assert 'hello' == ' hello '.strip()
ruby
puts " hello ".strip
" hello ".strip!
scala
val s = " hello ".trim

Make a string uppercase

Transform "Space Monkey" into "SPACE MONKEY"
clojure
(.toUpperCase "Space Monkey")
cpp
String(L"Space Monkey").ToUpper();
std::string s = "Space Monkey";
std::transform(s.begin(), s.end(), s.begin(), std::toupper);
std::string s = "Space Monkey";
boost::to_upper(s);
csharp
string output = "Space Monkey"

System.Console.WriteLine(output.ToUpper())
erlang
io:format("~s~n", [string:to_upper("Space Monkey")]).
fantom
s := "Space Monkey".localeUpper
fsharp
printfn "%s" ("Space Monkey".ToUpper())
printfn "%s" (String.uppercase "Space Monkey")
groovy
println "Space Monkey".toUpperCase()
haskell
toUpperCase oldstring converted = if oldstring == ""
then converted
else toUpperCase (tail(oldstring)) (converted ++ [Char.toUpper(head(oldstring))])

toUpperCase "Space Monkey" ""
toUpperCase = map Char.toUpper

toUpperCase "Space Monkey"
java
String upper = text.toUpperCase();
ocaml
String.uppercase "Space Monkey";;
perl
print uc "Space Monkey"
python
"Space Monkey".upper()
ruby
uppper = text.upcase
scala
println("Space Monkey".toUpperCase)

Make a string lowercase

Transform "Caps ARE overRated" into "caps are overrated"
clojure
(.toLowerCase "Caps ARE overRated")
cpp
std::string s = "Caps ARE overRated";
std::string sl(boost::to_lower_copy(s));
String(L"Caps ARE overRated").ToLower();
csharp
string str = "Caps ARE overRated";
str = str.ToLower() ;
Console.WriteLine(str);
erlang
io:format("~s~n", [string:to_lower("Caps ARE overRated")]).
fantom
s := "Caps ARE overRated".localeLower
fsharp
printfn "%s" ("Caps ARE overRated".ToLower())
printfn "%s" (String.lowercase "Caps ARE overRated")
groovy
println "Caps ARE overRated".toLowerCase()
haskell
import Char
str = map toLower "Caps ARE overRated"
java
"Caps ARE overRated".toLowerCase();
ocaml
String.lowercase "Caps ARE overRated";;
perl
print lc "Caps ARE overRated"
python
"Caps ARE overRated".lower()
ruby
"Caps ARE overRated".downcase
scala
"Caps ARE overRated".toLowerCase

Capitalise the first letter of each word

Transform "man OF stEEL" into "Man Of Steel"
clojure
(use 'clojure.contrib.str-utils2)
(join " " (map capitalize (split "man OF stEEL" #" ")))
cpp
std::string words = "mAn OF stEEL";
std::transform(words.begin(), words.end(), words.begin(), ToCaps<>());
StringBuilder^ sb = gcnew StringBuilder(L"man OF stEEL");

for (int i = 0, isFirst = 1; i < sb->Length; ++i)
{
sb[i] = Char::IsWhiteSpace(sb[i]) ? (isFirst = 1, sb[i]) : isFirst ? (isFirst = 0, Char::ToUpper(sb[i])) : Char::ToLower(sb[i]);
}
std::string words = "mAn OF stEEL";
std::vector<std::string> swv;

boost::split(swv, words, boost::is_any_of(" "));
std::string newwords = (std::for_each(swv.begin(), swv.end(), StringTAndJ(WordToCaps))).value();
csharp
System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase("man OF stEEL".ToLowerInvariant());
erlang
Caps = string:join(lists:map(fun(S) -> to_caps(S) end, string:tokens("man OF stEEL", " ")), " "),
fantom
"man OF stEEL".split.map { it.localeLower.localeCapitalize }.join(" ")
fsharp
let words = String.Join(" ", Array.map (fun (s : String) -> (String.capitalize (s.ToLower()))) ("man OF stEEL".Split [|' '|]))
let wordlst = List.map (fun s -> (String.capitalize (String.lowercase s))) (String.split [' '] "man OF stEEL")
let words = new StringBuilder(List.hd wordlst)
for (s : String) in (List.tl wordlst) do (words.Append(" ").Append(s))
// Previous solutions used old library functions, here's something that works with F# 2.0
let s= "man OF stEEL"
let UpperFirst = function | "" -> "" | s -> s.Substring(0,1).ToUpper() + s.Substring(1).ToLower()
s.Split(' ') |> Array.map UpperFirst |> String.concat " "
let culture = System.Globalization.CultureInfo.GetCultureInfo("en-US")
let titleCase = culture.TextInfo.ToTitleCase "man oF sTeel"
groovy
def capitalize(s) { s[0].toUpperCase() + s[1..-1].toLowerCase() }
caps = "man OF stEEL".replaceAll(/\w+/) { w -> capitalize(w) }
caps = "man OF stEEL".replaceAll(/\w+/) { w -> StringUtils.capitalize(w.toLowerCase()) }
caps = WordUtils.capitalizeFully("man OF stEEL")
haskell
import Data.Char

capitalizeWords = unwords . map capitalizeWord . words
where capitalizeWord [] = []
capitalizeWord (c:cs) = toUpper c : map toLower cs
java
String input = "man OF stEEL";
StringTokenizer tokenizer = new StringTokenizer(input);
StringBuffer sb = new StringBuffer();
while (tokenizer.hasMoreTokens()) {
String word = tokenizer.nextToken();
sb.append(word.substring(0, 1).toUpperCase());
sb.append(word.substring(1).toLowerCase());
sb.append(' ');
}
String text = sb.toString();
StringBuilder sb = new StringBuilder("man OF stEEL"); String s = sb.toString();
int last = s.length() - 1;

for (int i = 0; i <= last; ++i)
if (Character.isSpaceChar(s.charAt(i)) && i < last) { ++i; sb.setCharAt(i, Character.toUpperCase(s.charAt(i))); }
else if (i == 0) sb.setCharAt(i, Character.toUpperCase(s.charAt(i)));
else sb.setCharAt(i, Character.toLowerCase(s.charAt(i)));
Matcher m = Pattern.compile("(\\w+)").matcher("man OF stEEL"); StringBuffer sb = new StringBuffer(32), rsb = new StringBuffer(8);

while (m.find())
{
rsb.replace(0, rsb.length(), m.group().toLowerCase()); rsb.setCharAt(0, Character.toUpperCase(rsb.charAt(0)));
m.appendReplacement(sb, rsb.toString());
}
m.appendTail(sb);
String text = WordUtils.capitalizeFully("man OF stEEL");
ocaml
let capitalize_words str =
let len = String.length str in
let res = String.copy str in
let rec aux i do_up =
if i >= len then res else
match str.[i] with
| ' ' | '\n' | '\t' | '\r' -> aux (succ i) true
| _ ->
res.[i] <-
(if do_up then Char.uppercase else Char.lowercase) str.[i];
aux (succ i) false
in
aux 0 true

let () =
print_endline (capitalize_words "man OF stEEL")
perl
$text =~ s/(\w+)/\u\L$1/g;
python
from string import capwords
capwords("man OF stEEL")
' '.join(s.capitalize() for s in "man OF stEEL".split())
"man OF stEEL".title()
ruby
caps = text.gsub(/\w+/) { $&.capitalize }
caps = text.split.each{|i| i.capitalize!}.join(' ')
text.split.map(&:capitalize) * ' '
scala
def capitalize(s: String) = { s(0).toUpperCase + s.substring(1, s.length).toLowerCase }

"man OF stEEL".split("\\s") foreach {(x) => text.append(capitalize(x)).append(" ")}
val text = WordUtils.capitalizeFully("man OF stEEL")
val text = StringUtils.join("man OF stEEL".split("\\s") map {(x) => StringUtils.capitalize(x.toLowerCase) + " "})
// can be solved without external libraries
(("man OF stEEL" toLowerCase) split " " map (_ capitalize)).mkString(" ")
// This is just a slightly more compact form of the previous solution (my fav).
// It would be nice if split defaulted to whitespace (precompiled reg ex).
"man OF stEEL".toLowerCase.split(" ").map(_.capitalize) mkString " "

Find the distance between two points

clojure
(defstruct point :x :y)

(defn distance
"Euclidean distance between 2 points"
[p1 p2]
(Math/pow (+ (Math/pow (- (:x p1) (:x p2)) 2)
(Math/pow (- (:y p1) (:y p2)) 2))
0.5))

(distance (struct point 0 0) (struct point 1 1)) ; => 1.4142135623730951
(defn distance
"Euclidean distance between 2 points"
[[x1 y1] [x2 y2]]
(Math/sqrt
(+ (Math/pow (- x1 x2) 2)
(Math/pow (- y1 y2) 2))))

(distance [2 2] [3 3])
cpp
Point p1 = {34, 78}, p2 = {67, -45};
double distance = ::distance(p1, p2);
Console::WriteLine("{0,3:F2}", distance);
csharp
System.Drawing.Point p = new System.Drawing.Point(13, 14),
p1 = new System.Drawing.Point(10, 10);
double distance = Math.Sqrt(Math.Pow(p1.X - p.X, 2) + Math.Pow(p1.Y - p.Y, 2)));
erlang
Distance = distance({point, 34, 78}, {point, 67, -45}),
io:format("~.2f~n", [Distance]).
Distance = distance(point:new(34, 78), point:new(67, -45)),
io:format("~.2f~n", [Distance]).
fantom
px1 := 34.0f; py1 := 78.0f; px2 := 67.0f; py2 := -45.0f
distance := |Float x1, Float y1, Float x2, Float y2 -> Float|
{ ((x2-x1).pow(2.0f) + (y2-y1).pow(2.0f)).sqrt }

distance(px1, py1, px2, py2)
fsharp
let distance' = distance (34, 78) (67, -45)
printfn "%3.2f" distance'
groovy
distance = distance(x1, y1, x2, y2)
distance = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1))
haskell
data Floating n => Point2 n = Point2 n n

distance :: Floating n => Point2 n -> Point2 n -> n
distance (Point2 x1 y1) (Point2 x2 y2) = sqrt (x'*x' + y'*y')
where
x' = x1 - x2
y' = y1 - y2


-- > distance (Point2 5 10) (Point2 3 5)
-- 5.385...
-- > distance (Point2 1 1) (Point2 2 2)
-- 1.414...
java
double distance = Point2D.distance(x1, y1, x2, y2);
Point2D point1 = new Point2D.Double(x1, y1);
Point2D point2 = new Point2D.Double(x2, y2);
double distance = point1.distance(point2);
double distance = Math.hypot(x2-x1, y2-y1);
ocaml
type point = { x:float; y:float };;
let distance a b = sqrt((a.x -. b.x)**2. +. (a.y -. b.y)**2.);;
perl
use Math::Complex;
$a = Math::Complex->make(0, 3);
$b = Math::Complex->make(4, 0);
$distance = abs($a - $b);
python
# problem description doesn't say 2D points ;)
from math import sqrt
print sqrt(sum((x-y)**2 for x,y in zip(a, b)))
from math import hypot
print hypot(x2-x1, y2-y1)
ruby
# the hypotenuse sqrt(x**2+y**2)
distance = Math.hypot(x2-x1,y2-y1)
scala
val distance$ = distance((34, 78), (67, -45))
println(distance$)
val distance$ = distance(new Point(34, 78), new Point(67, -45))
println(distance$)
def distance (p1: (Int, Int), p2: (Int, Int)) = {
val (p1x, p1y) = p1
val (p2x, p2y) = p2
val dx = p1x - p2x
val dy = p1y - p2y
Math.sqrt(dx*dx + dy*dy)
}
println(distance((34, 78), (67, -45)))

def euclideanDistance(point1: List[Double], point2: List[Double]): Double = {
sqrt(point1.zip(point2).foldLeft(0.0){case(sum,(v1,v2)) => sum + pow(v1-v2, 2)})
}

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042
clojure
(defn pad
([x] (if (> 8 (.length (str x))) (pad (str 0 x)) (str x)))
)
(defn pad [x]
(format "%08d" x))
(format "%08d" 42)
cpp
String^ formatted = Convert::ToString(42)->PadLeft(8, '0');
String^ formatted = String::Format("{0,8:D8}", 42);
std::printf("%08d", 42);
std::ostringstream os;
os << std::setw(8) << std::setfill('0') << 42 << std::ends;
std::cout << os.str() << std::endl;
std::cout << boost::format("%|08|") % 42 << std::endl;
csharp
string.Format("{0,8:D8}", 42);
erlang
Formatted = io_lib:format("~8..0B", [42]),
io:format("~8..0B~n", [42]).
fantom
formatted := 42.toStr.padl(8, '0')
formatted := 42.toLocale("00000000")
fsharp
printfn "%08d" 42
let formatted = sprintf "%08d" 42
printfn "%s" formatted
let buffer = new StringBuilder()
Printf.bprintf buffer "%08d" 42
printfn "%s" (buffer.ToString())
let formatted = String.Format("{0,8:D8}", 42)
Console.WriteLine(formatted)
let formatted = Convert.ToString(42).PadLeft(8, '0')
Console.WriteLine(formatted)
groovy
formatted = new DecimalFormat('00000000').format(42)
formatted = 42.toString().padLeft(8, '0')
// to stdout
printf "%08d\n", 42
// to a string
formatted = sprintf("%08d", 42)
formatted = String.format("%08d", 42)
haskell
import Text.Printf

printf "%08d" 42
java
String formatted = new DecimalFormat("00000000").format(42);
String formatted = String.format("%08d", 42);
ocaml
Printf.printf "%08d" 42;;
let s = Printf.sprintf "%08d" 42 in
print_string s;;
perl
sprintf("%08d", 42);
python
"%08d" % 42
ruby
42.to_s.rjust(8,"0")
"%08d" % 42
scala
val formatted = String.format("%08d", int2Integer(42))
printf("%08d\n", 42)
println("%08d".format(42))

Right Space pad a number

Given the number 1024 right pad it to 6 characters "1024  "
clojure
(let [s (str 1024)
l (count s)]
(str s (reduce str (repeat (- 6 l) " "))))
cpp
String^ formatted = Convert::ToString(1024)->PadRight(6);
String^ formatted = String::Format("{0,-6:D}", 1024);
std::printf("%-6d\n", 1024);
std::ostringstream os;
os << std::setw(6) << std::setfill(' ') << std::left << 1024 << std::ends;
std::cout << os.str() << std::endl;
std::cout << boost::format("%|-6|") % 1024 << std::endl;
csharp
public class NumberRightPadding {
public static void Main() {
string withStringDotFormat = string.Format("{0,-6}", 1024);
string withToStringDotPadRight = 1024.ToString().PadRight(6);
}
}
erlang
Formatted = io_lib:format("~-6B", [1024]),
io:format("~-6B~n", [1024]).
fantom
formatted := 1024.toStr.padr(6)
fsharp
printfn "%-6d" 1024
let formatted = String.Format("{0,-6:D}", 1024)
Console.WriteLine(formatted)
let formatted = Convert.ToString(1024).PadRight(6)
Console.WriteLine(formatted)
groovy
println 1024.toString().padRight(6)
formatted = sprintf("%-6d", 1024)
haskell
let s = show 1024
p = 6
in s ++ (replicate (p - length s) ' ')
import Text.Printf

main = do
putStrLn $ printf "%-6d" (1024::Int)
java
private static String spaces(int spaces) {
StringBuffer sb = new StringBuffer();
for(int i=0; i<spaces; i++) {
sb.append(' ');
}
return sb.toString();
}

private static String rightPad(int number, int spaces) {
String numberString = String.valueOf(number);
return numberString + spaces(spaces - numberString.length());
}
String text = StringUtils.rightPad(String.valueOf(1024), 6)
String formatted = String.format("%-6d", 1024);
ocaml
Printf.printf "%-6i" 1024;;
perl
sprintf("%-6d", 1024);
python
"%-6s" % 1024
str(1024).rjust(6)
'{0: <6}'.format(1024)
ruby
1024.to_s.ljust(6)
scala
val formatted = String.format("%-6d", int2Integer(1024))
printf("%-6d\n", 1024)
println("%-6d".format(1024))

Format a decimal number

Format the number 7/8 as a decimal with 2 places: 0.88
clojure
(format "%3.2f" (/ 7.0 8))
(* 0.01 (Math/round (* 100 (float (/ 7 8)))))
cpp
String^ formatted = String::Format("{0,3:F2}", result);
Console::WriteLine("{0,3:F2}", (7. / 8.));
std::printf("%3.2f\n", result);
std::ostringstream os;
os.width(3); os.fill('0'); os.setf(std::ios::fixed|std::ios::showpoint); os.precision(2);
os << result << std::ends;
std::cout << os.str() << std::endl;
std::cout << boost::format("%|3.2f|") % result << std::endl;
csharp
public class FormatDecimal {
public static void Main() {
decimal result = decimal.Round( 7 / 8m, 2);
System.Console.WriteLine(result);
}
}
erlang
Formatted = io_lib:format("~.2f", [7/8]),
io:format("~.2f~n", [7/8]).
fantom
formatted := (7.0/8.0).toLocale("0.00")
fsharp
printfn "%3.2f" (0.7 / 0.8)
let formatted = String.Format("{0,3:F2}", (0.7 / 0.8))
Console.WriteLine(formatted)
groovy
def result = 7/8
println result.round(new MathContext(2))
def result = 7/8
printf "%.2g", result
new Double(7/8).round(2)
haskell
import Text.Printf

printf "%3.2f" (7/8)
main = putStrLn $ Numeric.showFFloat (Just 2) (7/8) ""
java
String formatted = String.format("%3.2f", 7./8.);
ocaml
Printf.printf "%4.2f" (7. /. 8.);;
let s = Printf.sprintf "%4.2f" (7. /. 8.) in
print_string s;;
perl
sprintf("%.2f", 7/8);
python
"%.2f" % (7 / 8.0)
round(7./8., 2)
ruby
(7.0/8.0*100).round/100.0
(7.0/8.0).round(2)
scala
val formatted = String.format("%3.2f", double2Double(7./8.))
printf("%3.2f\n", 7./8.)

Left Space pad a number

Given the number 73 left pad it to 10 characters "        73"
clojure
(let [s (str 73)
l (count s)]
(str (reduce str (repeat (- 10 l) " ")) s ))
cpp
String^ formatted = Convert::ToString(73)->PadLeft(10);
String^ formatted = String::Format("{0,10:D}", 73);
std::printf("%10d\n", 73);
std::ostringstream os;
os << std::setw(10) << std::setfill(' ') << 73 << std::ends;
std::cout << os.str() << std::endl;
std::cout << boost::format("%|10|") % 73 << std::endl;
csharp
public class NumberLeftPadding {
public static void Main() {
string withStringDotFormat = string.Format("{0,10}", 73);
string withToStringDotPadLeft = 73.ToString().PadLeft(10);
}
}
erlang
Formatted = io_lib:format("~10B", [73]),
io:format("~10B~n", [73]).
fantom
formatted := 73.toStr.padl(10)
fsharp
let formatted = sprintf "%10d" 73
printfn "%s" formatted
let formatted = String.Format("{0,10:D}", 73)
Console.WriteLine(formatted)
let formatted = Convert.ToString(73).PadLeft(10)
Console.WriteLine(formatted)
groovy
println 73.toString().padLeft(10)
printf "%10d\n", 73
haskell
import Text.Printf

formatted :: String
formatted = printf "%10d" 73
java
private static String spaces(int spaces) {
StringBuffer sb = new StringBuffer();
for(int i=0; i<spaces; i++) {
sb.append(' ');
}
return sb.toString();
}

private static String leftPad(int number, int spaces) {
String numberString = String.valueOf(number);
return spaces(spaces - numberString.length()) + numberString;
}
String formatted = String.format("%10d", 73);
ocaml
Printf.printf "%10d" 73;;
perl
sprintf("%10d", 73);
python
"%10s" % 73
ruby
73.to_s.rjust(10)
scala
val formatted = String.format("%10d", int2Integer(73))
printf("%10d\n", 73)

Generate a random integer in a given range

Produce a random integer between 100 and 200 inclusive
clojure
(+ (rand-int (- 201 100)) 100)
cpp
Random^ rnd = gcnew Random;
int rndInt = rnd->Next(100, 201);
std::srand(std::time(NULL));

unsigned lb = 100, ub = 200;
unsigned rnd = lb + (rand() % ((ub - lb) + 1));
typedef boost::uniform_int<> Distribution;
typedef boost::mt19937 RNG;

Distribution distribution(100, 200);
RNG rng; rng.seed(std::time(NULL));
boost::variate_generator<RNG&, Distribution> generator(rng, distribution);

unsigned rnd = generator();
csharp
System.Random r = new System.Random();
int random = r.Next(100,201);
erlang
RandomInt = gen_rand_integer(100, 200),
fantom
r := Int.random(100..200)
fsharp
let rnd = new Random()
let rndInt = rnd.Next(100, 201)
groovy
random = new Random()
randomInt = random.nextInt(200-100+1)+100
haskell
import System.Random

randInRange :: Int -> Int -> IO Int
randInRange a b = getStdRandom $ randomR (a, b)

main = randInRange 100 200 >>= print
import System.Random

main = randomRIO (1,100) >>= print
java
Random random = new Random();
int randomInt = random.nextInt(200-100+1)+100;
ocaml
Random.self_init ();;
let a = 100 and b = 200 in
Random.int ( b - a + 1 ) + a;;
perl
my $range = 100;
my $minimum = 100;

my $random_number = int(rand($range)) + $minimum;

print "$random_number\n";
python
import random
random.randint(100, 200)
# uses best entropy source available (e.g. /dev/urandom, CryptGenRandom, ...)

import random
print random.SystemRandom().randint(100,200)
ruby
randomInt = rand(200-100+1)+100;
scala
val rnd = new GenRandInt(100, 200)
val randomInt = rnd.next
val rnd = new scala.util.Random
val range = 100 to 200
println(range(rnd.nextInt(range length)))

Generate a repeatable random number sequence

Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values.
clojure
(dotimes [_ 2]
(let [r (java.util.Random. 12345)]
(dotimes [_ 5]
(println (.nextInt r 100))))
(println))
cpp
void printAction(int i) { Console::Write("{0} ", i); }

array<int>^ genFillRand(array<int>^ arr, Random^ rnd, int lb, int ub)
{
for (int i = 0; i < arr->Length; ++i) arr[i] = rnd->Next(lb, ub + 1); return arr;
}

int main()
{
array<int>^ arr1 = genFillRand(gcnew array<int>(5), gcnew Random(12345), 100, 200);
array<int>^ arr2 = genFillRand(gcnew array<int>(5), gcnew Random(12345), 100, 200);

Action<int>^ print = gcnew Action<int>(printAction);
Array::ForEach<int>(arr1, print); Console::WriteLine();
Array::ForEach<int>(arr2, print); Console::WriteLine();
}
typedef boost::uniform_int<> Distribution;
typedef boost::mt19937 RNG;

Distribution distribution(100, 200);
RNG rng;
boost::variate_generator<RNG&, Distribution> generator(rng, distribution);

rng.seed(42L);
std::generate_n(std::ostream_iterator<unsigned>(std::cout, " "), 5, generator);

rng.seed(42L);
std::cout << std::endl;
std::generate_n(std::ostream_iterator<unsigned>(std::cout, " "), 5, generator);
csharp
using System;

public class RepeatableRandom {
public static void Main() {
var r = new Random(12); // seed is 12

for (int i = 0; i < 5; i++)
Console.WriteLine(r.Next());

r = new Random(12);

for (int i = 0; i < 5; i++)
Console.WriteLine(r.Next());
}
}

erlang
setRNG(RNGState),
io:format("~w~n", [lists:map(fun (_) -> gen_rand_integer(100, 200) end, lists:seq(1, 5))]),

setRNG(RNGState),
io:format("~w~n", [lists:map(fun (_) -> gen_rand_integer(100, 200) end, lists:seq(1, 5))]).
fantom
rand := Random.makeSeeded(12345)
first := Int[,].fill(0,5).map { rand.next(100..200) }

rand2 := Random.makeSeeded(12345)
second := Int[,].fill(0,5).map { rand2.next(100..200) }
fsharp
let (seed, lb, ub) = (12345, 100, 200)

let mutable rnd = new Random(seed)
for i = 1 to 5 do printf "%d " (rnd.Next(lb, ub + 1)) done ; printfn ""

rnd <- new Random(seed)
for i = 1 to 5 do printf "%d " (rnd.Next(lb, ub + 1)) done ; printfn ""
groovy
random = new Random(12345)
orig = (1..5).collect { random.nextInt(200-100+1)+100 }
random = new Random(12345)
repeat = (1..5).collect { random.nextInt(200-100+1)+100 }
assert orig == repeat
haskell
import System.Random
import Control.Monad (forM_)

main = do
printRands
printRands

where printRands = forM_ [1..5] (\i -> print (randInt i))
randInt i = fst $ randomR (100, 200) (mkStdGen i) :: Int
import System.Random

gen1 = mkStdGen 12345
gen2 = mkStdGen 12345

main = do
print $ take 5 (randoms gen1 :: [Float])
print $ take 5 (randoms gen2 :: [Float])

java
int[] arr1 = genFillRand(new int[5], new Random(12345), 100, 200);
int[] arr2 = genFillRand(new int[5], new Random(12345), 100, 200);

for (int[] arr : new int[][]{ arr1, arr2 }) { for (int i : arr) System.out.printf("%d ", i); System.out.println(); }
ocaml
let random_stream seed =
Random.init seed;
let state = ref (Random.get_state ()) in
Stream.from
(fun x ->
Random.set_state !state;
let res = Random.float 1. in
state := Random.get_state ();
Some res);;

Stream.npeek 5 (random_stream 1);;
Stream.npeek 5 (random_stream 1);;
perl
srand(12345);
@list1 = map(int(rand(100)+1), (1..5));

srand(12345);
@list2 = map(int(rand(100)+1), (1..5));

print join(', ', @list1) . "\n";
print join(', ', @list2) . "\n";
python
import random

random.seed(12345)
list1 = [random.randint(1,10) for x in range(5)]

random.seed(12345)
list2 = [random.randint(1,10) for x in range(5)]

assert(list1==list2)
ruby
srand(12345)
first = (1..5).collect {rand}
srand(12345)
second = (1..5).collect {rand}
puts first == second
scala
val rnd = new scala.util.Random(12345)
(1 until 6) foreach { (_) => printf("%d ", 100 + rnd.nextInt(200)) } ; println()

rnd.setSeed(12345)
(1 until 6) foreach { (_) => printf("%d ", 100 + rnd.nextInt(200)) } ; println()

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
clojure
(if (re-matches #"[A-Z][a-z]+" "Hello")
(println "ok"))
cpp
if ((gcnew Regex("[A-Z][a-z]+"))->IsMatch("Hello")) Console::WriteLine("ok");
if (Regex::IsMatch("Hello", "[A-Z][a-z]+")) Console::WriteLine("ok");
Regex^ rx = gcnew Regex("[A-Z][a-z]+");
if (rx->IsMatch("Hello")) Console::WriteLine("ok");
cmatch what;
if (regex_match("Hello", what, regex("[A-Z][a-z]+")))
cout << "ok" << endl;
csharp
if (Regex.IsMatch("Hello", "[A-Z][a-z]+"))
{
Console.WriteLine("ok");
}
erlang
String = "Hello", Regexp = "[A-Z][a-z]+",
is_match(String, Regexp) andalso (begin io:format("ok~n"), true end).
case re:run("Hello", "[A-Z][a-z]+") of {match, _} -> ok end.
fantom
if (Regex<|[A-Z][a-z]+|>.matches("Hello"))
echo("ok")
fsharp
if (Regex.IsMatch("Hello", "[A-Z][a-z]+")) then printfn "ok"
groovy
if ("Hello" =~ /[A-Z][a-z]+/) println 'ok'
if ("Hello".find(/[A-Z][a-z]+/)) println 'ok'
// with precompiled regex
def regex = ~/[A-Z][a-z]+/
if ("Hello".find(regex)) println 'ok'
// with precompiled regex
def regex = ~/[A-Z][a-z]+/
if ("Hello".matches(regex)) println 'ok'
if ("Hello".matches("[A-Z][a-z]+")) println 'ok'
haskell
import Text.Regex.Posix
main = if "Hello" =~ "[A-Z][a-z]+" then putStrLn "OK" else return ()
java
if ("Hello".matches("[A-Z][a-z]+")) {
System.out.println("ok");
}
ocaml
if Str.string_match (Str.regexp "[A-Z][a-z]+") "Hello" 0
then print_string "ok";;
perl
print 'ok' if ('Hello' =~ /[A-Z][a-z]+/);
python
found = re.match(r'[A-Z][a-z]+', 'Hello')
if found:
print 'ok'
ruby
puts "ok" if ("Hello"=~/^[A-Z][a-z]+$/)
scala
if ("Hello".matches("[A-Z][a-z]+")) println("ok")

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
clojure
(if-let [groups (re-matches #"one (.*) three" "one two three")]
(println (second groups)))
cpp
Match^ match = Regex::Match("one two three", "one (.*) three");
if (match->Success) Console::WriteLine("{0}", match->Groups[1]->Captures[0]);
cmatch what;
if (regex_match("one two three", what, regex("one (.*) three")))
cout << what[1] << endl;
csharp
using System;
using System.Text.RegularExpressions;

public class RegexBackReference {
public static void Main() {
var oneTwoThree = "one two three";
var pattern = "one (.*) three";

Match match = Regex.Match(oneTwoThree, pattern);

// group 0 is the entire match. 1 is the first backreference
Console.WriteLine(match.Groups[1]);
}
}
erlang
case re:run("one two three", "one (.*) three", [{capture, [1], list}]) of {match, Res} -> hd(Res) end.
fantom
m := Regex<|one (.*) three|>.matcher("one two three")
if (m.matches)
echo("${m.group(1)}")
fsharp
let regmatch = (Regex.Match("one two three", "one (.*) three"))
if regmatch.Success then (printfn "%s" (regmatch.Groups.[1].Captures.[0].ToString()))
groovy
matcher = ("one two three" =~ /one (.*) three/)
if (matcher) println matcher[0][1]
match = "one two three".find("one (.*) three") { it[1] }
if (match) println match
haskell
import Text.Regex
main = case matchRegex (mkRegex "one (.*) three") "one two three" of
Nothing -> return ()
Just (x:_) -> putStrLn x
java
Pattern pattern = Pattern.compile("one (.*) three");
Matcher matcher = pattern.matcher("one two three");
if (matcher.matches()) {
System.out.println(matcher.group(1));
}
ocaml
#load "str.cma" ;;

let s = "one two three" in
if Str.string_match (Str.regexp "one \\(.*\\) three") s 0 then
print_string (Str.matched_group 1 s)
perl
print $1 if "one two three"=~/^one (.*) three$/
python
match = re.match(r'one (.*) three', 'one two three')
if match:
print match.group(1)
ruby
puts $1 if "one two three"=~/^one (.*) three$/
scala
val m = Pattern.compile("one (.*) three").matcher("one two three")
if (m.matches) println(m.group(1))

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/
clojure
(if (re-find #"\d+" "abc 123 @#$")
(println "ok"))
cpp
if (Regex::IsMatch("abc 123 @#$", "\\d+")) Console::WriteLine("ok");
csharp
if(System.Text.RegularExpressions.Regex.IsMatch("abc 123 @#$",@"\d+")){
Console.WriteLine("ok");
}
erlang
% Erlang uses 'egrep'-compatible regular expressions, so shortcuts like '\d' not supported
String = "abc 123 @#$", Regexp = "[0-9]+",
is_match(String, Regexp) andalso (begin io:format("ok~n"), true end).
case re:run("abc 123 @#$", "\\d+") of {match, _} -> ok end.
fantom
m := Regex<|\d+|>.matcher("abc 123 @#\$")
if (m.find)
echo("ok")
fsharp
if (Regex.IsMatch("abc 123 @#$", "\\d+")) then printfn "ok"
groovy
if ('abc 123 @#$' =~ /\d+/) println 'ok'
if ('abc 123 @#$'.find(/\d+/)) println 'ok'
haskell
import Text.Regex
main = case matchRegex (mkRegex "\d+") "abc 123 @#$" of
Nothing -> putStrLn "not ok"
Just _ -> putStrLn "ok"
java
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
System.out.println("ok");
}
ocaml
#load "str.cma" ;;

let re = Str.regexp "[0-9]+" in
try let _ = Str.search_forward re "abc 123 @#$" 0 in
print_string "ok"
with _ -> ()
perl
print "ok" if ("abc 123 @#\$" =~ m/\d+/)
python
found = re.search(r'\d+', 'abc 123 @#$')
if found:
print 'ok'
ruby
puts "ok" if (text=~/\d+/)
scala
if (Pattern.compile("\\d+").matcher("abc 123 @#$").find) println("ok")

Loop through a string matching a regex and performing an action for each match

Create a list [fish1,cow3,boat4] when matching "(fish):1 sausage (cow):3 tree (boat):4" with regex /\((\w+)\):(\d+)/
clojure
(let [matcher (re-matcher #"\((\w+)\):(\d+)" "(fish):1 sausage (cow):3 tree (boat):4")]
(loop [match (re-find matcher)
lst []]
(if match
(recur (re-find matcher) (conj lst (str (second match) (nth match 2))))
lst)))
cpp
Match^ match = Regex::Match("(fish):1 sausage (cow):3 tree (boat):4", "\\((\\w+)\\):(\\d+)");

while (match->Success)
{
list->Add(match->Groups[1]->Captures[0]->ToString() + match->Groups[2]->Captures[0]->ToString());
match = match->NextMatch();
}
csharp
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public static class extensions {
public static IList<string> Map(this string me, string pattern, Func<Match, string> action){
IList<string> matches = new List<string>();
foreach (Match match in Regex.Matches(me,pattern)){
matches.Add(action(match));
}
return matches;
}
}

class Test
{
static void Main()
{
IList<string> list = "(fish):1 sausage (cow):3 tree (boat):4".Map(@"\((\w+)\):(\d+)", (m) => {return m.Groups[1].Value + m.Groups[2].Value;});
}
}
erlang
solve(S) ->
R = "\\((\\w+?)\\):(\\d+)",
{match, M} = re:run(S,R, [global, {capture, all_but_first, list}]),
[ A++N || [A, N] <- M].
fantom
m := Regex<|\((\w+)\):(\d+)|>.matcher(s)
list := Str[,]
while (m.find) { list.add("${m.group(1)}${m.group(2)}") }
fsharp
let list = new ResizeArray<string>()
let mutable regmatch = (Regex.Match("(fish):1 sausage (cow):3 tree (boat):4", "\\((\\w+)\\):(\\d+)"))

while regmatch.Success do
list.Add(regmatch.Groups.[1].Captures.[0].ToString() ^ regmatch.Groups.[2].Captures.[0].ToString())
regmatch <- regmatch.NextMatch()
done

for word in list do printfn "%s" word done
// A solution without mutation:
let results =
Regex.Matches("(fish):1 sausage (cow):3 tree (boat):4", "\\((\\w+)\\):(\\d+)")
|> Seq.cast
|> Seq.map (fun (regmatch: Match) ->
regmatch.Groups.[1].Captures.[0].ToString() + regmatch.Groups.[2].Captures.[0].ToString()
)
|> List.ofSeq
groovy
list = (text =~ /\((\w+)\):(\d+)/).collect{ it[1] + it[2] }
list = []
text.eachMatch(/\((\w+)\):(\d+)/){
list << it[1] + it[2]
}
list = []
text.eachMatch(/\((\w+)\):(\d+)/){ m, name, number ->
list << "$name$number"
}
list = (text =~ /\((\w+)\):(\d+)/).collect{ all, name, num -> "$name$num" }
list = text.findAll(regex){ _, name, num -> "$name$num" }
list = text.findAll(regex){ it[1] + it[2] }
haskell
import Text.Regex

getParenNum s = case matchRegexAll re s of
Nothing -> []
Just (_,_,after,[word,num]) -> (word ++ num):getParenNum after where
re = mkRegex "\\((\\w+)\\):([[:digit:]]+)"

main = putStrLn (show (getParenNum "(fish):1 sausage (cow):3 tree (boat):4"))
java
List list = new ArrayList();
Pattern pattern = Pattern.compile("\\((\\w+)\\):(\\d+)");
Matcher matcher = pattern.matcher(text);
while(matcher.find()) {
list.add(matcher.group(1)+matcher.group(2));
}
ocaml
let result =
let str = "(fish):1 sausage (cow):3 tree (boat):4" in
let ms = Pcre.exec_all ~pat:"\\((\\w+)\\):(\\d+)" str in
Array.to_list (
Array.map (fun m ->
let s = Pcre.get_substrings m in
Printf.sprintf "%s%s" s.(1) s.(2);
) ms
)
perl
while ($text =~ /\((\w+)\):(\d+)/g) {
push @list, "$1$2"
}
python
map(''.join, re.findall(r"\((\w+)\):(\d+)", "(fish):1 sausage (cow):3 tree (boat):4"))
--------------------------------------------------------------------------
(''.join(m.groups()) for m in re.finditer(r"\((\w+)\):(\d+)", "(fish):1 sausage (cow):3 tree (boat):4"))
ruby
list = text.scan(/\((\w+)\):(\d+)/).collect{|x| x.join}
list=[]
text.scan(/\((\w+)\):(\d+)/) {
list << $1+$2
}
scala
val m = Pattern.compile("\\((\\w+)\\):(\\d+)").matcher("(fish):1 sausage (cow):3 tree (boat):4")
var list : List[String] = Nil

while (m.find) list = (m.group(1) + m.group(2)) :: list ; list = list.reverse

Define an empty list

Assign the variable "list" to a list with no elements
clojure
(list)
'()
cpp
Generic::List<String^>^ list = gcnew Generic::List<String^>();
std::list<std::string> list;
csharp
var list = new List<object>();
erlang
List = [],
fantom
list := [,]
fsharp
let list = []
let list = List.empty
let list = new Generic.List<string>()
let list = new Generic.LinkedList<string>()
groovy
list = []
// if a special kind of list is required
list = new LinkedList() // java style
LinkedList list = [] // statically typed
// using 'as' operator
list = [] as java.util.concurrent.CopyOnWriteArrayList

haskell
let list = []
java
List list = Collections.emptyList();
String[] list = {};
ocaml
let list = [];;
perl
@list = ();
python
list = []
ruby
list = []
list = Array.new
scala
val list = Nil
val list = List()
val list : List[String] = List()

Define a static list

Define the list [One, Two, Three, Four, Five]
clojure
(def a '[One Two Three Four Five])
cpp
array<String^>^ input = {"One", "Two", "Three", "Four", "Five"};
Generic::List<String^>^ list = gcnew Generic::List<String^>((Generic::IEnumerable<String^>^) input);
Generic::List<String^>^ list = gcnew Generic::List<String^>();

list->Add("One");
list->Add("Two");
list->Add("Three");
list->Add("Four");
list->Add("Five");
std::string input[] = {"One", "Two", "Three", "Four", "Five"};
std::list<std::string> list(input, input + 5);
std::list<std::string> list;

list.push_back("One");
list.push_back("Two");
list.push_back("Three");
list.push_back("Four");
list.push_back("Five");
list<string> lst = { "One", "Two", "Three", "Four", "Five" };
list<string> lst;
lst += "One", "Two", "Three", "Four", "Five";
csharp
IList<string> list = new string[]{"One","Two","Three","Four","Five"};
erlang
List = [one, two, three, four, five],
List = ['One', 'Two', 'Three', 'Four', 'Five'],
fantom
list := ["One", "Two", "Three", "Four", "Five"]
fsharp
let list = ["One"; "Two"; "Three"; "Four"; "Five"]
let list = (new Generic.LinkedList<string>([|"One"; "Two"; "Three"; "Four"; "Five"|]))
let list = (new Generic.LinkedList<string>())

list.AddFirst("One") ; list.AddLast("Five") ; list.AddBefore(list.Find("Five"), "Four")
list.AddAfter(list.Find("One"), "Two") ; list.AddAfter(list.Find("Two"), "Three")
let list = (new Generic.List<string>())

[|"One"; "Two"; "Three"; "Four"; "Five"|] |> Array.iter (fun x -> list.Add(x))
groovy
list = ['One', 'Two', 'Three', 'Four', 'Five']
// other variations
List<String> numbers1 = ['One', 'Two', 'Three', 'Four', 'Five']
String[] numbers2 = ['One', 'Two', 'Three', 'Four', 'Five']
numbers3 = new LinkedList(['One', 'Two', 'Three', 'Four', 'Five'])
numbers4 = ['One', 'Two', 'Three', 'Four', 'Five'] as Stack // Groovy 1.6+
haskell
let a = ["One", "Two", "Three", "Four", "Five"]
java
List<String> numbers = new ArrayList<String>();
Collections.addAll(numbers, "One", "Two", "Three", "Four", "Five");
List numbers = new ArrayList();
numbers.add("One");
numbers.add("Two");
numbers.add("Three");
numbers.add("Four");
numbers.add("Five");
List numbers = Arrays.asList(new String[]{"One", "Two", "Three", "Four", "Five"});
String[] numbers = {"One", "Two", "Three", "Four", "Five"};
List numbers = new ArrayList(){{put("One"); put("Two"); put("Three"); put("Four"); put("Five"); }};
ocaml
let list = [ "One"; "Two"; "Three"; "Four"; "Five" ];;
perl
@list = qw(One Two Three Four Five);
@list = ('One', 'Two', 'Three', 'Four', 'Five');
python
list = ['One', 'Two', 'Three', 'Four', 'Five']
print list
ruby
list = ['One', 'Two', 'Three', 'Four', 'Five']
list = %w(One Two Three Four Five)
scala
val list = "One" :: "Two" :: "Three" :: "Four" :: "Five" :: Nil
val list = List("One", "Two", "Three", "Four", "Five")
val list: List[String] = List("One", "Two", "Three", "Four", "Five")

Join the elements of a list, separated by commas

Given the list [Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
clojure
(apply str (interpose ", " '("Apple" "Banana" "Carrot")))
cpp
String^ result = String::Join(L", ", fruit->ToArray());
string fruits[] = {"Apple", "Banana", "Carrot"};
string result = boost::algorithm::join(fruits, ", ");
csharp
using System.Collections.Generic;
public class JoinEach {
public static void Main() {
var list = new List<string>() {"Apple", "Banana", "Carrot"};
System.Console.WriteLine( string.Join(", ", list.ToArray()) );
}
}
erlang
Result = string:join(Fruit, ", "),
Result = lists:foldl(fun (E, Acc) -> Acc ++ ", " ++ E end, hd(Fruit), tl(Fruit)),
Result = lists:flatten([ hd(Fruit) | [ ", " ++ X || X <- tl(Fruit)]]).
fantom
["Apple", "Banana", "Carrot"].join(", ")
fsharp
let result = String.Join(", ", [|"Apple"; "Banana"; "Carrot"|])
let result = (List.fold_left (fun acc item -> acc ^ (", " ^ item)) (List.hd fruit) (List.tl fruit))
let result = (List.fold_left (fun (acc : StringBuilder) (item : string) -> acc.Append(", ").Append(item)) (new StringBuilder(List.hd fruit)) (List.tl fruit)).ToString()
groovy
string = fruit.join(', ')
string = fruit.toString()[1..-2]
haskell
import Data.List

let join = intercalate ", " ["Apple", "Banana", "Carrot"]
java
StringBuffer sb = new StringBuffer();
for (Iterator it = fruit.iterator(); it.hasNext();) {
sb.append(it.next());
if (it.hasNext()) {
sb.append(", ");
}
}
String result = sb.toString();
StringBuilder sb = new StringBuilder(fruit.get(0));
for (String item : fruit.subList(1, fruit.size())) sb.append(", ").append(item);
String result = sb.toString();
String result = StringUtils.join(fruit, ", ");
ocaml
let () =
let lst = ["Apple"; "Banana"; "Carrot"] in
let str = String.concat ", " lst in
print_endline str
perl
print join ', ', qw(Apple Banana Carrot);
# Longer and less efficient than join(), but illustrates
# Perl's foreach operator, which can be useful for
# less trivial problems with lists

@list = ('Apple', 'Banana', 'Carrot');
foreach $fruit (@list) {
print "$fruit,";
}
print "\n";
my @a = qw/Apple Banana Carrot/;
{
local $, = ", ";
print @a
}
print "\n";
my @a = qw/Apple Banana Carrot/;
{
local $" = ", ";
print "@a\n";
}
python
print ", ".join(['Apple', 'Banana', 'Carrot'])
ruby
string = fruit.join(', ')
scala
val result =
((fruit.tail foldLeft (new StringBuilder(fruit.head))) {(acc, e) => acc.append(", ").append(e)}).toString
val result = fruit.mkString(",")
val fruit = List[String]("Apple", "Banana", "Carrot")
println(fruit.mkString(", "))

Join the elements of a list, in correct english

Create a function join that takes a List and produces a string containing an english language concatenation of the list. It should work with the following examples:
join([Apple, Banana, Carrot]) = "Apple, Banana, and Carrot"
join([One, Two]) = "One and Two"
join([Lonely]) = "Lonely"
join([]) = ""
clojure
(defn join [lst]
(cond
(= (count lst) 0) ""
(= (count lst) 1) (first lst)
(= (count lst) 2) (str (first lst) " and " (second lst))
(> (count lst) 2) (loop [lst lst sb (StringBuilder.)]
(if (empty? lst)
(.toString sb)
(recur (rest lst) (.append sb (cond
(> (count lst) 2) (str (first lst) ", ")
(> (count lst) 1) (str (first lst) ", and ")
(= (count lst) 1) (str (first lst)))))))))
(defn join
([lst]
(join lst false))
([lst is-long]
(condp = (count lst)
0 ""
1 (first lst)
2 (str (first lst) (if is-long ",") " and " (second lst))
(str (first lst) ", " (join (rest lst) true)))))
cpp
Console::WriteLine(join(fruit));
string join(const vector<string> &s, int b=0)
{
switch (s.size() - b)
{
case 0: return "";
case 1: return s[b];
case 2: return s[b] + (s.size() > 2 ? "," : "") + " and " + s[b+1];
default: return s[b] + ", " + join(s, b+1);
}
}
csharp
using System.Collections.Generic;
using System.Linq;

public class CSharpListToEnglishList {
public string JoinAsEnglishList (List<string> words) {
switch (words.Count) {
case 0: return "";
case 1: return words[0];
case 2: return string.Format("{0} and {1}", words.ToArray());
default:
return JoinAsEnglishList( new List<string>() {
string.Join(", ", words.Take(words.Count - 1).ToArray()) + ",",
words.Last()
});
}
}
// Driver...
public static void Main() {
var joiner = new CSharpListToEnglishList();
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Apple", "Banana", "Carrot", "Orange" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Apple", "Banana", "Carrot" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "One", "Two" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Lonely" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>()) );
}
}
erlang
io:format("~s~n", [join(Fruit)]).

% ------

join([]) -> "";
join([W|Ws]) -> join(Ws, W).

join([], S) -> S;
join([W], S) -> join([], S ++ " and " ++ W);
join([W|Ws], S) -> join(Ws, S ++ ", " ++ W).
%% According to the reference manual, "string is not a data type in Erlang."
%% Instead it has lists of integers. But I/O functions in general accept
%% IO lists, where an IO list is either a list of IO lists or an integer.
%% This gives you O(1) string concatenation.

-module(commalist).
-export([join/1]).

join([]) -> "";
join([W]) -> W;
join([W1, W2]) -> [W1, " and ", W2];
join([W1, W2, W3]) -> [W1, ", ", W2, ", and ", W3];
join([W1|Ws]) -> [W1, ", ", join(Ws)].

fantom
join := |List list -> Str|
{
switch(list.size)
{
case 0: return ""
case 1: return list[0]
case 2: return list.join(" and ")
default: return list[0..-2].join(", ") + ", and " + list[-1]
}
}

echo(join(["Apple", "Banana", "Carrot"]))
echo(join(["One", "Two"]))
echo(join(["Lonely"]))
echo(join([,]))
fsharp
let join list =
let rec join' list' s =
match list' with
| [] -> s
| [w] -> join' [] (s ^ " and " ^ w)
| w :: ws -> join' ws (s ^ ", " ^ w)
match list with
| [] -> ""
| w :: ws -> join' ws w

// ------

printfn "%s" (join fruit)
groovy
def join(list) {
if (!list) return ''
switch(list.size()) {
case 1:
return list[0]
case 2:
return list.join(' and ')
default:
return list[0..-2].join(', ') + ', and ' + list[-1]
}
}
ArrayList.metaClass.joinEng = { ->
def closureMap = [0: { -> delegate.join(' and ')}, 1 : {-> delegate.join(' and ')}].withDefault { k -> { -> delegate[0..-2].join(', ') + ', and ' + delegate[-1] } }
if (delegate.size()) closureMap[delegate.size()-1].call()
else ""
}

assert ["a"].joinEng() == "a"
assert ["a", "b"].joinEng() == "a and b"
assert ["a", "b", "c"].joinEng() == "a, b, and c"
assert [].joinEng() == ""
haskell
join [] = ""
join [x] = x
join [x,y] = x ++ " and " ++ y
join [x,y,z] = x ++ ", " ++ y ++ ", and " ++ z
join (x:xs) = x ++ ", " ++ join xs
java
private String join(List elements) {
if (elements == null || elements.size() == 0) {
return "";
} else if (elements.size() == 1) {
return elements.get(0).toString();
} else if (elements.size() == 2) {
return elements.get(0) + " and " + elements.get(1);
}
StringBuffer sb = new StringBuffer();
for (Iterator it = elements.iterator(); it.hasNext();) {
String next = (String) it.next();
if (sb.length() > 0) {
if (it.hasNext()) {
sb.append(", ");
} else {
sb.append(", and ");
}
}
sb.append(next);
}
return sb.toString();
}
System.out.println(join(fruit));
ocaml
let join list =
let rec join' list acc =
match list with
| [] -> ""
| [single] -> single
| one::[two] ->
if acc = "" then one ^ " and " ^ two
else acc ^ one ^ ", and " ^ two
| first::others -> join' others (acc ^ first ^ ", ")
in
join' list ""
perl
sub myjoin {
$_ = join ', ', @_;
s/, ([^,]+)$/ and $1/;
return $_;
}


# Note: I don't think this meets the spec --Geoff
sub myjoin {
if ($#_ < 2) {
return join ' and ', @_;
} else {
return join(', ', @_[0..$#_-1]) . ' and ' . $_[-1];
}
}

# Note: I don't think this meets the spec --Geoff
# Previous "myjoin()" responses don't meet the spec of including
# the final comma before the "and" if the list has more than
# two elements...this is one way to meet that spec...it may
# not be the most efficient...

sub AnotherMyJoin {
my @list = @_;

if ($#list == -1) {return}
elsif ($#list == 0) {return $list[0]}
elsif ($#list == 1) {return $list[0].' and '.$list[1]}
else {
return join(", ", @list[0..$#list - 1]) . ', and '. $list[$#list];
}
}
# This is the long way, but it's kind of fun
# It illustrates the use of Perl's reverse()
# operator to work our way through the list
# elements backwards...I wrote this one before
# getting smart and looking at some of the other
# algorithms from the other languages. Still,
# it is only 12 lines of code vs 9 for my other
# solution if you disregard the comments.

sub myjoin {
my @list = reverse(@_); # Reverse original order of elements
my $retval;

# Make our exit here if we were passed an empty list
if ($#list == -1) {return}

# Loop through reversed elements in end-to-start order
for (0..$#list) {
# Add the reversed form of each element plus a space char
$retval .= reverse($list[$_]).' ';

# Add 'and' to lists with two or more elements
# placing it in between final and 'next to final'
$retval .= "dna " if ($#list > 0 and $_== 0);

# Add ',' to each element as long as there are more
# than two elements and the current element isn't the
# final element
$retval .= "," if ($#list > 1 and $_ != $#list);
}

# Remove what will end up as an extraneous leading space
chop($retval);

# Done looping, now reverse things back into correct order and return
$retval = reverse($retval);
return($retval);
}
# Yes, this doesn't meet the spec, the spec is flawed
# the serial comma (Oxford comma) is not required in a list
sub english_join {
return join(', ', @_[0..$#_-1])
. ($#_ ? ' and ' : '' )
. $_[-1];
}
python
def join(*x):
if len(x) <= 2:
return ' and '.join(x)
else:
return ', '.join(x[:-1] + ('and ' + x[-1],))

if __name__ == "__main__":
assert join("Apple", "Banana", "Carrot") == "Apple, Banana, and Carrot"
assert join("One", "Two") == "One and Two"
assert join("Lonely") == "Lonely"
assert join(*[]) == ""
ruby
def join(arr)
return '' if not arr
case arr.size
when 0 then ''
when 1 then arr[0]
when 2 then arr.join(' and ')
else arr[0..-2].join(', ') + ', and ' + arr[-1]
end
end
scala
def join(list : List[String]) : String = list match {
case List() => ""
case List(x) => x
case List(x,y) => x + " and " + y
case List(x,y,z) => x + ", " + y + ", and " + z
case _ => list(0) + ", " + join(list.tail)
}
def join(list : List[String]) : String = list match {
case List() => ""
case List(x) => x
case List(x,y) => x + " and " + y
case List(x,y,z) => x + ", " + y + ", and " + z
case x::xs => x + ", " + join(xs)
}
def join[T](list : List[T]) = list match {
case xs if xs.size < 3 => xs.mkString(" and ")
case xs => xs.init.mkString(", ") + ", and " + xs.last
}

Produce the combinations from two lists

Given two lists, produce the list of tuples formed by taking the combinations from the individual lists. E.g. given the letters ["a", "b", "c"] and the numbers [4, 5], produce the list: [["a", 4], ["b", 4], ["c", 4], ["a", 5], ["b", 5], ["c", 5]]
clojure
(defn combine [lst1 lst2]
(mapcat (fn [x] (map #(list % x) lst1)) lst2))
(mapcat (fn [x] (map #(list % x) ["a", "b", "c"])) [4, 5])
cpp
Specialized::StringCollection^ combinations = gcnew Specialized::StringCollection;

for each(int number in numbers)
for each(String^ letter in letters)
combinations->Add(makeCombo(letter, number));
string letters[] = { "a", "b", "c" };
int numbers[] = { 4, 5 };
list<pair<string,int> > combo;

for (int n = 0; n < sizeof numbers / sizeof *numbers; n++)
for (int l = 0; l < sizeof letters / sizeof *letters; l++)
combo.push_back(make_pair(letters[l], numbers[n]));

cout << combo << endl;
csharp
using System.Collections.Generic;
public class ListCombiner {
public static void Main() {
var letters = new List<char>() { 'a', 'b', 'c' };
var numbers = new List<int>() { 1, 2, 3 };

// result is a list that contaings lists of objects
var result = new List<List<object>>();
foreach (var l in letters) {
foreach (var n in numbers) {
result.Add(new List<object>() { l, n });
}
}
}
}
erlang
Combinations =
lists:foldl(fun (Number, Acc) -> Acc ++ lists:map(fun (Letter) -> {Letter, Number} end, Letters) end, [], Numbers),
Combinations = lists:keysort(2, sofs:to_external(sofs:product(sofs:set(Letters), sofs:set(Numbers))))
[[A, B] || A <- ["a", "b", "c"], B <- [4, 5]].

fantom
[4,5].each |Int i| { ["a","b","c"].each |Str s| { r.add([i,s]) } }
fsharp
let combinations = (List.fold_left (fun acc number -> acc @ (List.map (fun letter -> (letter, number)) letters)) [] numbers)
let combinations aa bb =
aa
|> List.map (fun a -> bb |> List.map (fun b -> (a, b)))
|> List.concat
groovy
letters = ['a', 'b', 'c']
numbers = [4, 5]
combos = [letters, numbers].combinations()
haskell
comb :: [(String, Int)]
comb = do
b <- [4,5]
a <- ["a","b","c"]
return (a,b)

main = mapM_ print comb
comb :: [(String, Int)]
comb = [(a, b) | b <- [4,5], a <- ["a","b","c"]]

main = print comb
java
List<String> combinations = new ArrayList<String>();

for (int number : numbers)
for (String letter : letters)
combinations.add(letter + ":" + Integer.toString(number));
SortedSet<AbstractMap.SimpleImmutableEntry<String, Integer> > combinations =
new TreeSet<AbstractMap.SimpleImmutableEntry<String, Integer> >(new CombinationComparator());

for (int number : numbers)
for (String letter : letters)
combinations.add(new AbstractMap.SimpleImmutableEntry<String, Integer>(letter, Integer.valueOf(number)));
ocaml
let combinations =
let l1 = ["a"; "b"; "c"]
and l2 = [4; 5] in
List.rev (
List.fold_left (fun acc y ->
List.fold_left (fun acc2 x ->
(x, y)::acc2
) acc l1
) [] l2
)
perl
@letters = qw(a b c);
@numbers = (4, 5);
@list = map { $number=$_; map [$_, $number], @letters; } @numbers;
@letters = qw(a b c);
@numbers = (4, 5);

for $number (@numbers) {
for $letter (@letters) {
push @list, [$letter, $number];
}
}
python
[(x, y) for y in [1,2] for x in ['a','b','c']]
import itertools
[x for x in itertools.product(["a", "b", "c"], [4, 5])]
ruby
common = [] ; [4, 5].each {|n| ['a', 'b', 'c'].each {|l| common << [l, n]}}
scala
val combinations =
(numbers foldLeft List[Pair[String, Int]]()) { (acc : List[Pair[String, Int]], number : Int) =>
acc ::: (letters map { (letter : String) => Pair(letter : String, number : Int) }) }
def product(set1 : List[_], set2 : List[_]) : List[Pair[_, _]] =
{
val p = new mutable.ArrayBuffer[Pair[_, _]]()
for (e1 <- set1) for (e2 <- set2) p += Pair(e1, e2)
p.toList
}

// ------

val combinations =
product(numbers, letters) map { (c) => c match { case Pair(number, letter) => Pair(letter, number) } }
val letters = List('a', 'b', 'c')
val numbers = List(4, 5)
for { l <- letters; n <- numbers } yield (l,n)

From a List Produce a List of Duplicate Entries

Taking a list:
["andrew", "bob", "chris", "bob"]

Write the code to produce a list of duplicates in the list:
["bob"]
clojure
(->> '("andrew" "bob" "chris" "bob")
(group-by identity)
(filter #(> (count (second %)) 1))
(map first))
cpp
vector<string> lst = { "andrew", "bob", "chris", "bob" };
vector<string> lst_no_dups;
vector<string> tmp;
vector<string> dups;

sort(lst.begin(), lst.end());
unique_copy(lst.begin(), lst.end(), back_inserter(lst_no_dups));
set_difference(lst.begin(), lst.end(),
lst_no_dups.begin(), lst_no_dups.end(),
back_inserter(tmp));
unique_copy(tmp.begin(), tmp.end(), back_inserter(dups));

cout << dups << endl;
list<string> lst = { "andrew", "bob", "chris", "bob" };
map<string,int> num_identical;
list<string> dups;

for (auto &s: lst)
num_identical[s]++;
for (auto &n: num_identical)
if (n.second > 1)
dups.push_back(n.first);
cout << dups << endl;
csharp
List<String> values = new List<string> {"andrew", "bob", "chris", "bob"};

var duplicates = values
.GroupBy(i => i)
.Where(j => j.Count() > 1)
.Select(s => s.Key);
foreach (var duplicate in duplicates)
{
Console.WriteLine(duplicate);
}
erlang
{_, Result} = lists:foldl(
fun(X, {Uniq, Dupl}) -> case lists:member(X, Uniq) of
true -> {Uniq,[X | Dupl]};
_ -> {[X | Uniq], Dupl}
end
end,
{[], []},
List),
Fun = fun
([X | Xs], F) -> case lists:member(X, Xs) of
true -> [X | F(Xs, F)];
_ -> F(Xs, F)
end;
([], _) -> []
end,
Result = Fun(List, Fun).
fantom
nameCounts := Str:Int[:] { def = 0 }
["andrew", "bob", "chris", "bob"].each |Str v| { nameCounts[v]++ }
results := nameCounts.findAll |Int v, Str k->Bool| { v > 1 }.keys
echo(results.join(","))
fsharp
["andrew"; "bob"; "chris"; "bob"]
|> Seq.countBy id
|> Seq.filter (fun (k,n) -> n > 1)
|> Seq.map fst
|> Seq.toList
groovy
def input = ["andrew", "bob", "chris", "bob"]

def output = input.findAll{input.count(it)>1}.unique()

assert output == ["bob"]
haskell
import Data.List

input = ["andrew", "bob", "chris", "bob"]
output = [ head l | l <- group (sort input), length l > 1]
java
List listOfDuplicates = new ArrayList(Arrays.asList(new String[]{"andrew", "bob", "chris", "bob"}));

Set set = new HashSet(listOfDuplicates);
for (Object element : set)
listOfDuplicates.remove(element);
ocaml
let rem v lst =
let rec aux acc = function
| [] -> List.rev acc
| x::xs ->
if compare v x = 0
then aux acc xs
else aux (x::acc) xs
in
aux [] lst

(** in case of a match, returns a list with the duplicate(s) removed *)
let rec mem_rem v lst =
let rec aux acc = function
| [] -> None
| x::xs ->
if compare v x = 0
then Some(List.rev_append acc (rem v xs))
else aux (x::acc) xs
in
aux [] lst

let duplicates lst =
let rec aux acc = function
| [] -> List.rev acc
| x::xs ->
match mem_rem x xs with
| Some ret -> aux (x::acc) ret
| None -> aux acc xs
in
aux [] lst

let () =
let lst = ["andrew"; "bob"; "chris"; "bob"; "mike"; "peter"; "bob"] in
let dup = duplicates lst in
List.iter print_endline dup
(* Using standard (functorized) sets *)

module SetTools(ASet: Set.S) =
struct
let find_duplicates l =
let rec aux l seen acc =
match l with
| [] -> acc
| h :: q ->
if ASet.mem h seen then
aux q seen (h :: acc)
else
aux q (ASet.add h seen) acc in
aux l (ASet.empty) []
end

module StringSet = Set.Make(String)

module StringSetTools = SetTools(StringSet)

StringSetTools.find_duplicates ["andrew"; "bob"; "chris"; "bob"];;
perl
my @input = ("andrew", "bob", "chris", "bob", "bob");

my %input_count;
my @output = grep { $input_count{$_}++; $input_count{$_} == 2 } @input;
python
import itertools
input = ["andrew", "bob", "chris", "bob"]
input.sort()
output = [k for k, g in itertools.groupby(input, lambda x: x) if len(list(g)) > 1]
ruby
foo = ['andrew', 'bob', 'chris', 'bob']
foo.inject({}) {|h,v| h[v]=h[v].to_i+1; h}.reject{|k,v| v==1}.keys
scala
List("andrew", "bob", "chris", "bob")
.groupBy(identity)
.filter( person => person._2.size > 1)
.map(_._1)
val l = List("andrew", "bob", "chris", "bob")
l.diff(l.distinct)

Fetch an element of a list by index

Given the list [One, Two, Three, Four, Five], fetch the third element ('Three')
clojure
(nth '[One Two Three Four Five] 2)
cpp
String^ result = list[2];
csharp
string[] items = new string[] { "One", "Two", "Three", "Four", "Five" };
List<string> list = new List<string>(items);
string third = list[2]; // "Three"
// Make sure you import the System.Linq namespace.
// This is not the preferred way of indexing if you are using Lists.
string[] items = new string[] { "One", "Two", "Three", "Four", "Five" };
IEnumerable<string> list = new List<string>(items);
string third = list.ElementAt(2); // Three
erlang
Result = lists:nth(3, List),
Result = element(3, list_to_tuple(List)),
{Left, _} = lists:split(3, List), Result = lists:last(Left),
Result = nth0(2, List),
fantom
["One", "Two", "Three", "Four", "Five"][2]
["One", "Two", "Three", "Four", "Five"].get(2)
fsharp
let result = List.nth ["One"; "Two"; "Three"; "Four"; "Five"] 2
groovy
list = ['One', 'Two', 'Three', 'Four', 'Five']
result = list[2] // index starts at 0
haskell
let a = [1..5]
let b = a !! 2
print b
java
String result = list.get(2);
ocaml
let third = List.nth [ "One"; "Two"; "Three"; "Four"; "Five" ] 3;;
perl
qw(One Two Three Four Five)[2];
@list = qw(One Two Three Four Five);
$list[2];
python
list = ['One', 'Two', 'Three', 'Four', 'Five']
list[2]
ruby
list = ['One', 'Two', 'Three', 'Four', 'Five']
list[2]
['One', 'Two', 'Three', 'Four', 'Five'].fetch(2)
list = ['One', 'Two', 'Three', 'Four', 'Five']
list.at(2)
['One', 'Two', 'Three', 'Four', 'Five'][2] # <= note the [2] at end of array
scala
val result = list(2)

Fetch the last element of a list

Given the list [Red, Green, Blue], access the last element ('Blue')
clojure
(last '[One Two Three Four Five])
cpp
String^ result = list[list->Count - 1];
string last_elem = lst.back();
csharp
string[] items = new string[] { "Red", "Green", "Blue" };
List<string> list = new List<string>(items);
string last = list[list.Count - 1]; // "Blue"
// Make sure you import the System.Linq namespace.
// This is not the preferred way of finding the last element if you are using Lists.
string[] items = new string[] { "Red", "Green", "Blue" };
IEnumerable<string> list = new List<string>(items);
string last = list.Last(); // "Blue"
erlang
Result = lists:last(List),
Result = last(List),
Result = hd(lists:reverse(List)),
Result = lists:nth(length(List), List),
fantom
["Red", "Green", "Blue"][-1]
["One", "Two", "Three", "Four", "Five"].last
fsharp
let last list =
let rec last' list' =
match list' with
| [x] -> x
| x :: xs -> last' xs
if List.is_empty list then failwith "empty list" else last' list

// ------

let result = last list
let result = (List.nth list ((List.length list) - 1))
let result = (List.hd (List.rev list))
groovy
list = ['Red', 'Green', 'Blue']
result = list[-1]
haskell
last ["Red", "Green", "Blue"]
java
String result = list.get(list.size() - 1);
ocaml
let list = [ "Red"; "Green"; "Blue" ] in
let last = List.nth list ( (List.length list) - 1 );;
let list = [ "Red"; "Green"; "Blue" ] in
let last = List.hd (List.rev list);;
let list_last l =
let rec aux h q =
match q with
| [] -> h
| h :: q -> aux h q in
match l with
| [] -> invalid_arg "list_last"
| h :: q -> aux h q
;;
list_last ["Red"; "Green"; "Blue"]
perl
qw(Red Green Blue)[-1];
@list = qw(Red Green Blue);
$list[-1];
python
list = ['Red', 'Green', 'Blue']
list[-1]
ruby
['Red', 'Green', 'Blue'][-1]
['Red', 'Green', 'Blue'].at(-1)
['Red', 'Green', 'Blue'].last
['Red', 'Green', 'Blue'].fetch(-1)
scala
val result = list.last
val result = (list.drop(list.length - 1)).head

Find the common items in two lists

Given two lists, find the common items. E.g. given beans = ['broad', 'mung', 'black', 'red', 'white'] and colors = ['black', 'red', 'blue', 'green'], what are the bean varieties that are also color names?
clojure
(use 'clojure.set)

(let [beans '[broad mung black red white]
colors '[black red blue green]]
(intersection (set beans) (set colors)))
cpp
array<String^>^ inbeans = {"broad", "mung", "black", "red", "white"};
Generic::ICollection<String^>^ beans = makeSET<String^>(gcnew Generic::List<String^>((Generic::IEnumerable<String^>^) inbeans));

array<String^>^ incolors = {"black", "red", "blue", "green"};
Generic::ICollection<String^>^ colors = makeSET<String^>(gcnew Generic::List<String^>((Generic::IEnumerable<String^>^) incolors));

Generic::ICollection<String^>^ result = intersectSET<String^>(beans, colors);
csharp
// Make sure you import the System.Linq namespace.
// This example uses arrays as the underlying implementation, but any IEnumerable type can be used - including List.
IEnumerable<string> beans = new string[] { "beans", "mung", "black", "red", "white" };
IEnumerable<string> colors = new string[] { "black", "red", "blue", "green" };
var intersect = beans.Intersect(colors); // ['red', 'black']
erlang
Beans = sets:from_list([broad, mung, black, red, white]), Colors = sets:from_list([black, red, blue, green]),

Common = sets:to_list(sets:intersection(Beans, Colors)),
fantom
beans := ["broad", "mung", "black", "red", "white"]
colors := ["black", "red", "blue", "green"]
echo(beans.intersection(colors))
fsharp
let beans = (Set.of_list ["broad"; "mung"; "black"; "red"; "white"])
let colors = (Set.of_list ["black"; "red"; "blue"; "green"])
let common = (Set.intersect beans colors)
let beans = Set ["broad"; "mung"; "black"; "red"; "white"]
let colors = Set ["black"; "red"; "blue"; "green"]
let common = Set.intersect beans colors
// Iterates elements of
// list1 across Elements of list2 returning a list of string options
// as generated by List.tryFind
let findCommon(list1 : 'a list, list2 : 'a list) : 'a list =
list1 |> List.map(fun y -> list2 |> List.tryFind(fun x -> y = x))
// Iterates elements of string option list generated above
// returning a string list containing common elements of List1 and List2
|> List.fold(fun acc x -> if x <> None then x.Value::acc else acc) []
// reverse order of list (can't seem to make List.foldBack work for this
|> List.rev

let beans = ["broad"; "mung"; "black"; "red"; "white"]
let colors = ["black"; "red"; "blue"; "green"]
printfn "%A" (findCommon(beans, colors)) ;;
groovy
beans = ['broad', 'mung', 'black', 'red', 'white']
colors = ['black', 'red', 'blue', 'green']
common = beans.intersect(colors)
assert common == ['black', 'red']
haskell
import Data.List

beans = ["broad", "mung", "black", "red", "white"]
colors = ["black", "red", "blue", "green"]

main = print (intersect beans colors)
java
List beans = Arrays.asList(new String[]{"broad", "mung", "black", "red", "white"});
List colors = Arrays.asList(new String[]{"black", "red", "blue", "green"});

List common = ListUtils.intersection(beans, colors);
ocaml
let beans = ["broad"; "mung"; "black"; "red"; "white"]

let colors = ["black"; "red"; "blue"; "green"]

let f common c = if List.mem c beans then c::common else common

let common = List.fold_left f [] colors;;

(* common will contain a list with the common elements *)
(* using standard (functorized) sets *)

module SetTools(ASet: Set.S) =
struct
let of_list l =
List.fold_left (fun acc e -> ASet.add e acc) ASet.empty l

let find_common l1 l2 =
ASet.elements (ASet.inter (of_list l1) (of_list l2))
end

module StringSet = Set.Make(String)

module StringSetTools = SetTools(StringSet)
;;
let beans = ["broad"; "mung"; "black"; "red"; "white"] in
let colors = ["black"; "red"; "blue"; "green"] in
StringSetTools.find_common beans colors;;
perl
@beans = qw(broad mung black red white);
@colors = qw(black red blue green);
@seen{@beans} = ();
for (@colors) {
push(@intersection, $_) if exists($seen{$_});
}
print join(', ', @intersection);
@beans = qw(broad mung black red white);
@colors = qw(black red blue green);

my %colors_hash = map { $_ => 1 } @colors;
my @intersection = grep { $colors_hash{$_} } @beans;
print join(', ', @intersection),"\n";
@beans = qw/broad mung black red white/;
@colors = qw/black red blue green/;

print join ', ', grep { $_ ~~ @colors } @beans;
python
beans = ['broad', 'mung', 'black', 'red', 'white']
colors = ['black', 'red', 'blue', 'green']

common = [b for b in beans if b in colors]
beans = ['broad', 'mung', 'black', 'red', 'white']
colors = ['black', 'red', 'blue', 'green']

common = set(beans) & set(colors)
ruby
common = (beans.intersection(colors)).to_a
scala
val beans = "broad" :: "mung" :: "black" :: "red" :: "white" :: Nil
val colors = "black" :: "red" :: "blue" :: "green" :: Nil
val common = beans intersect colors

Display the unique items in a list

Display the unique items in a list, e.g. given ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18], display the unique elements, i.e. with duplicates removed.
clojure
;; returns a set
(set [18, 16, 17, 18, 16, 19, 14, 17, 19, 18])
;;#{14 16 17 18 19}

;; returns a lazy sequence of the unique elements
(distinct [18, 16, 17, 18, 16, 19, 14, 17, 19, 18])
;;(18 16 17 19 14)


cpp
array<int>^ input = {18, 16, 17, 18, 16, 19, 14, 17, 19, 18};
Generic::List<int>^ ages = gcnew Generic::List<int>((Generic::IEnumerable<int>^) input);

Generic::ICollection<int>^ result = makeSET<int>(ages);
list<int> input;
input += 18, 16, 17, 18, 16, 19, 14, 17, 19, 18;
input.sort();
unique_copy(input.begin(), input.end(), ostream_iterator<int>(cout, "\n"));
csharp
using System.Collections.Generic;
using System.Linq;
public class UniqueElements {
public static void Main() {
var list = new List<int>() { 18, 16, 17, 18, 16, 19, 14, 17, 19, 18 };
var uniques = list.Distinct();
}
}
erlang
Ages = sets:to_list(sets:from_list([18, 16, 17, 18, 16, 19, 14, 17, 19, 18])), io:format("~w~n", [Ages]).
lists:usort([18, 16, 17, 18, 16, 19, 14, 17, 19, 18]).
fantom
uniqueAges := [18, 16, 17, 18, 16, 19, 14, 17, 19, 18].unique
echo(uniqueAges)
fsharp
(Set.ofList [18; 16; 17; 18; 16; 19; 14; 17; 19; 18]) |> Set.iter (fun age -> printf "%d, " age)
groovy
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
println ages.unique()
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
unique = ages as Set
println unique
haskell
import Data.List

ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]

uniqueAges = nub ages
java
Set<Integer> ages = new TreeSet<Integer>(Arrays.asList(new Integer[]{18, 16, 17, 18, 16, 19, 14, 17, 19, 18}));

System.out.println(ages);
ocaml
let ages = [18; 16; 17; 18; 16; 19; 14; 17; 19; 18]

let f res e = if List.mem e res then res else e::res

let unique = List.fold_left f [] ages;;
(* using standard (functorized) sets *)

module SetTools(ASet: Set.S) =
struct
let of_list l =
List.fold_left (fun acc e -> ASet.add e acc) ASet.empty l

let unique l =
ASet.elements (of_list l)
end

module Integer =
struct
type t = int
let compare (x:t) y = Pervasives.compare x y
end

module IntegerSet = Set.Make(Integer)
module IntegerSetTools = SetTools(IntegerSet)
;;
IntegerSetTools.unique [18; 16; 17; 18; 16; 19; 14; 17; 19; 18];;
perl
@ages = (18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
@seen{@ages} = ();
@unique = keys %seen;
print join(', ', @unique);
@ages = (18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
@unique = grep(!$seen{$_}++, @ages);
print join(', ', @unique);
@ages = (18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
print join(', ', grep(!$seen{$_}++, @ages));
@ages = (18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
for (@ages) {
push(@unique, $_) unless $seen{$_}++;
}
print join(', ', @unique);
use List::MoreUtils qw(uniq);

@ages = (18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
print join(', ', uniq(@ages));
python
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]

unique_ages = list(set(ages))
ruby
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
p ages.uniq
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
ages.uniq!
p ages
ages = (Set.new [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]).to_a
p ages
scala
val ages = (18 :: 16 :: 17 :: 18 :: 16 :: 19 :: 14 :: 17 :: 19 :: 18 :: Nil) removeDuplicates

Remove an element from a list by index

Given the list [Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
clojure
(let [fruit ["Apple" "Banana" "Carrot"]
index 0]
(concat
(take index fruit)
(drop (+ index 1) fruit)))
cpp
fruit->RemoveAt(0);
csharp
class Solution1516
{
static void Main()
{
List<string> fruit = new List<string>() { "Apple", "Banana", "Carrot" };
fruit.RemoveAt(0);
}
}
erlang
Result = tl(List),
[_|Result] = List,
N = 1, {Left, Right} = lists:split(N - 1, List), Result = Left ++ tl(Right),
Result = drop(1, List),
fantom
list := ["Apple", "Banana", "Carrot"]
list.removeAt(0)
fsharp
let split_at list n =
let rec split_at' list' n' left right =
match list' with
| [] -> (List.rev left, List.rev right)
| x :: xs -> if n' <= n then split_at' xs (n' + 1) (x :: left) right else split_at' xs (n' + 1) left (x :: right)
split_at' list 0 [] []

// ------

let (_, right) = split_at fruit 0
let drop list n =
if n <= 0 then
list
else
let (_, right) = split_at list (n - 1)
right

// ------

let result = (drop fruit 1)
groovy
// to produce a new list
newlist = list.tail() // for 'Apple' at start
newlist = list - 'Apple' // for 'Apple' anywhere
// mutate original list
list.remove(0)
haskell
deleteNth n xs | n > 0 = take (n-1) xs ++ drop n xs

main = print $ deleteNth 1 [1..3]
fruit :: [String]
fruit = ["Apple", "Banana", "Carrot"]

main :: IO ()
main = putStrLn $ show $ tail fruit
java
list.remove(0);
ocaml
let delete_at i al =
if i < 0 || i >= List.length al then
invalid_arg "delete_at"
else
let rec del i l =
match l with
| [] -> []
| h::t when i = 0 -> t
| h::t -> h :: del (i-1) t
in
del i al
;;
let rem_first l =
match l with
| [] -> []
| h::t -> t
;;
List.tl ["Apple"; "Banana"; "Carrot"]
perl
@list = qw(Apple Banana Carrot);
shift @list;
@list = qw(Apple Banana Carrot);
$offset = 0;
splice(@list, $offset, 1);
python
myList = ['Apple', 'Banana', 'Carrot']
print myList
del myList[0]
# or
myList.pop(0) # returns 'Apple'
print myList
ruby
['Apple', 'Banana', 'Carrot'].shift
fruit.delete_at(0)
scala
val (fl, fr) = fruit.splitAt(0) ; fruit = fl ::: fr.tail
fruit = fruit.tail
fruit = fruit.drop(1)
fruits = fruits.remove(fruits.indexOf(_) == 0)

Remove the last element of a list

clojure
(pop ["Apple" "Banana" "Carrot"])
cpp
fruit->RemoveAt(fruit->Count - 1);
csharp
List<string> fruits = new List() { "apple", "banana", "cherry" };
fruits.RemoveAt(fruits.Length - 1);
erlang
Result = init(List),
Result = take(length(List) - 1, List),
Result = lists:reverse(tl(lists:reverse(List))),
fantom
list := ["Apple", "Banana", "Carrot"]
list.removeAt(-1)
list := ["Apple", "Banana", "Carrot"]¨
list.pop
fsharp
let take list n =
if n <= 0 then
list
else
let (left, _) = split_at list (n - 1)
left

// ------

let result = (take fruit ((List.length fruit) - 1))
let but_last list =
let rec but_last' list' acc =
match list' with
| [x] -> List.rev acc
| x :: xs -> but_last' xs (x :: acc)
if List.is_empty list then [] else but_last' list []

// ------

let result = (but_last fruit)
groovy
list = ['Apple', 'Banana', 'Carrot']
// to produce a new list
newlist = list[0,1]
// to modify original list
list.remove(2)
haskell
ages = [1,2,3,4]

init ages
java
list.remove(list.size() - 1);
ocaml
let remove_last list =
match (List.rev list) with
| h::t -> List.rev t
| [] -> []
let remove_last lst =
List.rev (List.tl (List.rev lst))
let list_remove_last l =
let rec aux h q acc =
match q with
| [] -> List.rev acc
| h2 :: q -> aux h2 q (h :: acc) in
match l with
| [] -> invalid_arg "list_remove_last"
| h :: q -> aux h q []
perl
pop @list;
python
myList = ['Apple', 'Banana', 'Carrot']
myList.pop()

ruby
list = ['Apple', 'Banana', 'Carrot']
list.delete_at(-1)
list = ['Apple', 'Banana', 'Carrot']
list.pop
scala
fruit = fruit.init
fruit = fruit.take(fruit.length - 1)

Rotate a list

Given a list ["apple", "orange", "grapes", "bananas"], rotate it by removing the first item and placing it on the end to yield ["orange", "grapes", "bananas", "apple"]
clojure
(let [fruit ["apple" "orange" "grapes" "bananas"]]
(concat (rest fruit) [(first fruit)])
cpp
fruit->Add(fruit[0]); fruit->RemoveAt(0);
rotate(fruit.begin(), fruit.begin()+1, fruit.end());
csharp
var lst = new LinkedList<String>(new String[] {"apple", "orange", "grapes", "banana"});
lst.AddLast(lst.First());
lst.DeleteFirst();
erlang
N = 1, {Left, Right} = lists:split(N, List), Result = Right ++ Left,
N = 1, Result = rotate(N, List),
fantom
list := ["apple", "orange", "grapes", "bananas"]
list.add(list.removeAt(0))
fsharp
let rotate list n =
if n <= 0 then
list
else
let (left, right) = split_at list (n - 1)
right @ left

// ------

let result = (rotate fruit 1)
groovy
first = items.head()
items = items.tail() + first
items = items[1..-1] + items[0]
items = items + items.remove(0)
haskell
main = print $ rotate ["apple", "orange", "grapes", "bananas"]

rotate xs | length xs < 2 = xs
| otherwise = tail xs ++ [head xs]
java
list.add(list.remove(0));
Collections.rotate(list, -1);
ocaml
let rotate list =
match list with
| head::tail -> tail@[head]
| [] -> []
perl
@list = qw(apple, orange, grapes, bananas);
push @list, shift @list;
@list = qw(apple orange grapes bananas);
@list = @list[1..$#list,0];
python
l = ["apple", "orange", "grapes", "bananas"]
first, l = l[0], l[1:] + l[:1]
fruit = ['apple', 'orange', 'grapes', 'bananas']
fruit.append(fruit.pop(0))
ruby
items = ["apple", "orange", "grapes", "bananas"]
items << first = items.shift

# items is rotated
# first contains the first value in the list
scala
items = items.tail ::: List(items.head)
items = (items.head :: ((items.tail).reverse)).reverse

Gather together corresponding elements from multiple lists

Given several lists, gather together the first element from every list, the second element from every list, and so on for all corresponding index values in the lists. E.g. for these three lists, first = ['Bruce', 'Tommy Lee', 'Bruce'], last = ['Willis', 'Jones', 'Lee'], years = [1955, 1946, 1940] the result should produce 3 actors. The middle actor should be Tommy Lee Jones.
clojure
(defn gatherer [listOfLists]
(if (empty? (first listOfLists))
() ; the base case for recursion
(cons
(map first listOfLists) ; get the first element of each of the lists
(gatherer (map rest listOfLists)) ; gather all the subsequent ones
)
)
)

(def firstnames '("Bruce" "Tommy Lee" "Bruce"))
(def lastnames '("Willis" "Jones" "Lee"))
(def years '(1955 1946 1940))

(println (gatherer [firstnames lastnames years]))

; -> ((Bruce Willis 1955) (Tommy Lee Jones 1946) (Bruce Lee 1940))
(def firstnames ["Bruce" "Tommy Lee" "Bruce"])
(def lastnames ["Willis" "Jones" "Lee"])
(def years [1955 1946 1940])
(println (map (fn [f l y] [f l y]) firstnames lastnames years))
cpp
array<String^>^ first = {"Bruce", "Tommy Lee", "Bruce"}; array<String^>^ last = {"Willis", "Jones", "Lee"}; array<String^>^ years = {"1955", "1946", "1940"};

array<String^>^ result = zip<String^>(",", first, last, years);
list<string> first = { "Bruce", "Tommy Lee", "Bruce" };
list<string> last = {"Willis", "Jones", "Lee"};
list<int> years = {1955, 1946, 1940};
list<tuple<string,string,int> > actors;

for (firstIt = first.begin(), lastIt = last.begin(), yearIt = years.begin();
firstIt != first.end() && lastIt != last.end() && yearIt != years.end();
++firstIt, ++lastIt, ++yearIt)
actors.push_back(make_tuple(*firstIt, *lastIt, *yearIt));
csharp
String[] first = { "Bruce", "Tommy Lee", "Bruce" };
String[] last = { "Willis", "Jones", "Lee" };
int[] years = { 1955, 1946, 1940 };
var actors = first.Zip(last, (f, l) => Tuple.Create(f, l)).Zip(years, (t, y) => Tuple.Create(t.Item1, t.Item2, y)).ToArray();
Debug.Assert(actors[1].Equals(Tuple.Create("Tommy Lee", "Jones", 1946)));
erlang
First = ['Bruce', 'Tommy Lee', 'Bruce'], Last = ['Willis', 'Jones', 'Lee'], Years = [1955, 1946, 1940],

Result = lists:zip3(First, Last, Years),
fantom
r := [,]
first.size.times |Int i| { r.add([first[i], last[i], years[i]]) }

echo(r)
fsharp
let result = (List.zip3 first last years)
groovy
first = ['Bruce', 'Tommy Lee', 'Bruce']
last = ['Willis', 'Jones', 'Lee']
years = [1955, 1946, 1940]
actors = [first, last, years].transpose()
assert actors.size() == 3
assert actors[1] == ['Tommy Lee', 'Jones', 1946]
haskell
import Prelude hiding (last)

first = ["Bruce", "Tommy Lee", "Bruce"]
last = ["Willis", "Jones", "Lee"]
years = [1955, 1946, 1940]

actors = zip3 first last years
java
String[] first = new String[]{"Bruce", "Tommy Lee", "Bruce"};
String[] last = new String[]{"Willis", "Jones", "Lee"};
String[] years = new String[]{"1955", "1946", "1940"};

List<String[]> list = new ArrayList<String[]>(); list.add(first); list.add(last); list.add(years);

String[] result = zip(",", list);
ocaml
let rec combine3 f l y =
match f, l, y with
| [], [], [] -> []
| fh :: fq, lh :: lq, yh :: yq ->
(fh, lh, yh) :: combine3 fq lq yq
| _ -> invalid_arg "combine3"
;;
let first = ["Bruce"; "Tommy Lee"; "Bruce"] in
let last = ["Willis"; "Jones"; "Lee"] in
let years = [1955; 1946; 1940] in
combine3 first last years
perl
my @first = ('Bruce', 'Tommy Lee', 'Bruce');
my @last = ('Willis', 'Jones', 'Lee');
my @years = (1955, 1946, 1940);

my @actors;

my $max = scalar @first;
for my $index (0 .. $max) {
push @actors, [ $first[$index], $last[$index], $years[$index] ];
};
python
first = ['Bruce', 'Tommy Lee', 'Bruce']
last = ['Willis', 'Jones', 'Lee']
years = [1955, 1946, 1940]

actors = zip(first, last, years)

assert len(actors) == 3
assert actors[1] == ('Tommy Lee', 'Jones', 1946)
ruby
first = ['Bruce', 'Tommy Lee', 'Bruce']; last = ['Willis', 'Jones', 'Lee']; years = [1955, 1946, 1940]

result = first.zip(last, years)
first = ['Bruce', 'Tommy Lee', 'Bruce']; last = ['Willis', 'Jones', 'Lee']; years = [1955, 1946, 1940]

result = [first, last, years].transpose
scala
def zip3(l1 : List[_], l2 : List[_],l3 : List[_]) : List[Tuple3[_, _, _]] =
{
def zip3$ (l1$ : List[_], l2$ : List[_], l3$ : List[_], acc : List[Tuple3[_, _, _]]) : List[Tuple3[_, _, _]] = l1$ match
{
case Nil => acc reverse
case l1$head :: l1$tail => zip3$(l1$tail, l2$.tail, l3$.tail, Tuple3(l1$head, l2$.head, l3$.head) :: acc)
}

zip3$(l1, l2, l3, List[Tuple3[_,_,_]]())
}

// ------

val result = zip3(first, last, years)
val first = List("Bruce", "Tommy Lee", "Bruce")
val last = List("Willis", "Jones", "Lee")
val years = List(1955, 1946, 1940)
val results = (first, last, years).zipped.toList
println(results)

List Combinations

Given two source lists (or sets), generate a list (or set) of all the pairs derived by combining elements from the individual lists (sets). E.g. given suites = ['H', 'D', 'C', 'S'] and faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'], generate the deck of 52 cards, confirm the deck size and check it contains an expected card, say 'Ace of Hearts'.
clojure
(def suites ["H" "D" "C" "S"])
(def faces [2 3 4 5 6 7 8 9 10 "J" "Q" "K" "A"])
(defn listCards [] (for [s suites f faces] [f s]))
(some (partial = ["A" "H"]) (listCards))
; -> true
(count (listCards))
; -> 52
cpp
Specialized::StringCollection^ cards = gcnew Specialized::StringCollection;

for each(String^ suite in suites)
for each(String^ face in faces)
cards->Add(makeCard(suite, face));

Console::WriteLine("Deck has {0} cards", cards.Count);
if (cards->Contains(makeCard("h", "A"))) Console::WriteLine("Deck contains 'Ace of hearts'"); else Console::WriteLine("'Ace of hearts' not in deck");
auto suites = {"h", "d", "c", "s"};
auto faces = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
list<card> cards;

for (auto s: suites)
for (auto f: faces)
cards.push_back(make_pair(s,f));

cout << "Deck has " << cards.size() << " cards." << endl;

card ace_of_harts = make_pair("h", "A");
if (end(cards) != find_if(begin(cards), end(cards),
[&](const card& c) { return c == ace_of_harts; }))
cout << "Deck contain 'Ace of Harts'" << endl;
else
cout << "Deck lacks 'Ace of Harts'" << endl;
csharp
using System;
using System.Collections.Generic;
using System.Linq;

namespace Combinations
{
class Program
{
public static void Main(string[] args)
{
// Define the given lists
// Since List`1 implements the interface IEnumerable`1, this can easily be redefined as List`1.
IEnumerable<string> suites = new string[] { "H", "D", "C", "S" };
IEnumerable<string> faces = new string[] { "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" };

// LINQ Query to perform a Cartesian product and create an anonymous type to hold the results.
// "var" is required to define this as an IEnumerable`1
var deck =
from suite in suites // For each suite in suites
from face in faces // Match it with a face in face.
select new
{
Suite = suite,
Face = face
};

// Verify the count (uses LINQ extension)
if (deck.Count() == 52)
{
Console.WriteLine("Count matches!");
}

// Verify that the Ace of Hearts is in the deck (uses LINQ extension)
if (deck.Contains(new {Suite = "H", Face = "A"}))
{
Console.WriteLine("Ace of Hearts found!");
}

// Example of how to iterate through the list.
// "var" here is required since we are using an anonymous type
foreach(var card in deck)
{
Console.WriteLine("Suite: {0} Face: {1}", card.Suite, card.Face);
}

// If you desire to work with a List`1, you can convert this to a normal list at any time:
Console.WriteLine("\nConverting to list!");
var list = deck.ToList();
Console.WriteLine("Suite: {0} Face: {1}", list[5].Suite, list[5].Face);
Console.WriteLine("List count: {0}", list.Count); // 52

Console.ReadLine();
}
}
}
erlang
Cards = lists:foldl(fun (Suite, Acc) -> Acc ++ lists:flatmap(fun (Face) -> [{Suite, Face}] end, Faces) end, [], Suites),

io:format("Deck has ~B cards~n", [length(Cards)]),
IsMember = lists:member({h, 'A'}, Cards),
io:format("~s~n", [if IsMember -> "Deck contains 'Ace of Hearts'" ; true -> "'Ace of Hearts' not in deck" end]),
Cards = sofs:to_external(sofs:product(sofs:set(Suites), sofs:set(Faces))),

io:format("Deck has ~B cards~n", [length(Cards)]),
IsMember = lists:member({h, 'A'}, Cards),
io:format("~s~n", [if IsMember -> "Deck contains 'Ace of Hearts'" ; true -> "'Ace of Hearts' not in deck" end]),
Deck2 = [{S, V} || S <- [d, c, h, s], V <- [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A']],
52 = length(Deck2),
true = lists:member({h, 'A'}, Deck2).

fantom
r := [,]
["2","3","4","5","6","7","8","9","10","J","Q","K","A"].each |Str c|
{ ["H","D","C","S"].each |Str s| { r.add([c,s]) } }

q := ["A","H"]
result := r.contains(q)
echo("Deck size=${r.size}, contains $q? -> $result")
fsharp
let cards = (List.fold_left (fun acc suite -> acc @ (List.map (fun face -> (suite, face)) faces)) [] suites)

printfn "Deck has %d cards" (List.length cards)
printfn "%s" (if (List.exists (fun e -> e = ("h", "A")) cards) then "Deck contains 'Ace of Hearts'" ; else "'Ace of Hearts' not in deck")
let product (set1 : List<'a>) (set2 : List<'a>) : List<'a * 'a> =
let p = new ResizeArray<'a * 'a>()
for e1 in set1 do for e2 in set2 do p.Add(e1, e2) done done
Array.to_list (p.ToArray())

// ------

let cards = product suites faces

printfn "Deck has %d cards" (List.length cards)
printfn "%s" (if (List.exists (fun e -> e = ("h", "A")) cards) then "Deck contains 'Ace of Hearts'" ; else "'Ace of Hearts' not in deck")
let deck =
suites
|> List.map (fun s -> faces |> List.map (fun f -> (s, f)))
|> List.concat

printfn "Deck has %d cards" (List.length deck)
match deck |> List.exists (fun e -> e = ("h", "A")) with
| true -> printfn "Deck contains 'Ace of Hearts'"
| _ -> printfn "'Ace of Hearts' not in deck"
groovy
faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
suites = ['H', 'D', 'C', 'S']
deck = [faces, suites].combinations()
assert deck.size() == 52
assert ['A', 'H'] in deck
haskell
import Data.List

suites = ["H", "D", "C", "S"]
faces = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]

main = do
let cards = [(s,f) | s <- suites, f <- faces ]
print (length cards)
print $ hasCard ("H", "A") "Ace of Hearts" cards
where hasCard t name cards = (if elem t cards then "Contains "
else "Does not contain") ++ name
java
SortedSet<AbstractMap.SimpleImmutableEntry<String, String> > cards =
new TreeSet<AbstractMap.SimpleImmutableEntry<String, String> >(new CardComparator());

for (String suite : suites)
for (String face : faces)
cards.add(new AbstractMap.SimpleImmutableEntry<String, String>(suite, face));

Boolean containsEntry = cards.contains(new AbstractMap.SimpleImmutableEntry<String, String>("h", "A"));

if (containsEntry) System.out.println("Deck contains 'Ace of Hearts'");
else System.out.println("'Ace of Hearts' not in deck");
ocaml
let suites = ["H"; "D"; "C"; "S"]
let faces = ["2";"3";"4";"5";"6";"7";"8";"9";"10";"J";"Q";"K";"A"]

let desk =
List.fold_left (fun acc y ->
List.fold_left (fun acc2 x ->
(x, y)::acc2
) acc faces
) [] suites

let () =
assert (List.length desk = 52);
if List.mem ("A", "H") desk
then print_endline "Ace of Hearts found!"
else print_endline "Ace of Hearts not found :("
perl
@suites = qw(H D C S);
@faces = qw(2 3 4 5 6 7 8 9 10 J Q K A);
@deck = map { $suite=$_; map $suite.$_, @faces; } @suites;
print 'checking deck size: ' . (@deck == 52 ? 'pass' : 'fail') . "\n";
print 'deck contains "Ace of Hearts": ' . (grep(/^HA$/, @deck) ? 'true' : 'false') . "\n";
python
suites = ('H', 'D', 'C', 'S')
faces = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A')
deck = [(face,suite) for suite in suites for face in faces]
assert len(deck) == 52
assert ('A', 'H') in deck
ruby
suites.each {|s| faces.each {|f| cards << [s, f]}}
puts "Deck %s \'Ace of Hearts\'" % if cards.include?(['h', 'A']) then "contains" else "does not contain" end
scala
def product(set1 : List[_], set2 : List[_]) : List[Pair[_, _]] =
{
val p = new mutable.ArrayBuffer[Pair[_, _]]()
for (e1 <- set1) for (e2 <- set2) p += Pair(e1, e2)
p.toList
}

// ------

val cards = product(suites, faces)

printf("Deck has %d cards\n", cards.length)
if (cards.contains(Pair("h", "A"))) println("Deck contains 'Ace of Hearts'")
else println("'Ace of Hearts' not in this deck")

Perform an operation on every item of a list

Perform an operation on every item of a list, e.g.
for the list ["ox", "cat", "deer", "whale"] calculate
the list of sizes of the strings, e.g. [2, 3, 4, 5]
clojure
(map count ["ox" "cat" "deer" "whale"])
cpp
list<string> words;

words.push_back("ox");
words.push_back("cat");
words.push_back("deer");
words.push_back("whale");

for (list<string>::iterator it = words.begin(); it != words.end(); ++it)
cout << it->size() << ' ';
cout << endl;
auto words = { "ox", "cat", "deer", "whale" };
list<size_t> word_sizes;

transform(begin(words),
end(words),
back_inserter(word_sizes),
[](const string& s) { return s.size(); });
csharp
using System.Collections.Generic;
public class OperationOnEach {
public static void Main() {
var list = new List<string>() { "ox", "cat", "deer", "whale" };
list.ForEach( System.Console.WriteLine );
}
}
erlang
lists:map(fun (X) ->length(X) end, List).
fantom
["ox", "cat", "deer", "whale"].map { it.size }
fsharp
let lengths = List.map String.length ["ox"; "cat"; "deer"; "whale"]
groovy
animals = ["ox", "cat", "deer", "whale"]
assert animals*.size() == [2, 3, 4, 5]
haskell
map length ["ox", "cat", "deer", "whale"]
java
public class SolutionXX {
public static void main(String[] args) {
String[] list = {"ox", "cat", "deer", "whale"};
for (String str : list) {
System.out.println(str.length() + " ");
}
}
}
ocaml
List.map String.length ["ox"; "cat"; "deer"; "whale"];;
perl
my @list = qw{ox cat deer whale};

my @lengths = map {length($_)} @list;

print "@list\n";
print "@lengths\n";
python
print map(lambda x: len(x), ["ox", "cat", "deer", "whale"])
print [len(x) for x in ['ox', 'cat', 'deer', 'whale']]
ruby
["ox", "cat", "deer", "whale"].map{|i| i.length}
scala

val sizes = List("ox", "cat", "deer", "whale") map {_ size}
assert(sizes == List(2, 3, 4, 5))

Split a list of things into numbers and non-numbers

Given a list that might contain e.g. a string, an integer, a float and a date,
split the list into numbers and non-numbers.
clojure
(def jumble [3 "Bill" 5.7 '("A" "B" "C")]) ; int, string, float, list

(defn numberNonNumberSorter [jumbledList]
(if (empty? jumbledList)
(hash-map :numbers [], :nonnumbers []) ; recursion base case - return two empty lists
(let [head (first jumbledList)] ; let <head> be the first element in the list
(let [tailresult (numberNonNumberSorter (rest jumbledList))] ; tailresult applies recursively to the remainder
(if (number? head) ; is head a number?
(hash-map
:numbers (cons head (tailresult :numbers)) ; add <head> to the numbers
:nonnumbers (tailresult :nonnumbers)) ; leave nonnumbers the same
(hash-map
:numbers (tailresult :numbers) ; leave numbers the same
:nonnumbers (cons head (tailresult :nonnumbers))) ; add <head> to nonnumbers
)
)
)
)
)

(println (numberNonNumberSorter jumble))

; -> {:nonnumbers (Bill (A B C)), :numbers (3 5.7)}
(group-by number? ["hello" 42 3.14 (Date.)])
cpp
typedef variant<int,float,string,date> dynamic;

class is_number : public static_visitor<bool>
{
public:
bool operator()(int &) const {
return true;
}
bool operator()(float &) const {
return true;
}
bool operator()(string &) const {
return false;
}
bool operator()(date &) const {
return false;
}
};

int main()
{
list<dynamic> lst;
list<dynamic> numbers;
list<dynamic> non_numbers;

lst += "hello", 3.14f, 42, date(2011,Aug,23);

BOOST_FOREACH(dynamic v, lst)
if (apply_visitor(is_number(), v))
numbers += v;
else
non_numbers += v;
#include <iostream>
#include <list>

#include <boost/any.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/foreach.hpp>

using namespace boost;
using namespace boost::gregorian;
using namespace std;

int main()
{
list<any> lst;
list<any> numbers;
list<any> non_numbers;

lst.push_back(string("hello"));
lst.push_back(42);
lst.push_back(3.14f);
lst.push_back(date(day_clock::local_day()));

BOOST_FOREACH(const any &a, lst)
try
{
numbers.push_back(any_cast<int>(a));
}
catch (bad_any_cast &e)
{
try
{
numbers.push_back(any_cast<float>(a));
}
catch (bad_any_cast &e)
{
non_numbers.push_back(a);
}
}

// float and int are now in 'numbers' and the rest in 'non_numbers'
}
csharp
using System;
using System.Collections.Generic;
using System.Linq;

// AFAIK, there just isn't a good way to do this in C#
public class ListSplitter {
public static bool IsNumeric(object o) {
var d = new Decimal();
return decimal.TryParse(o.ToString(), out d);
}
public static void Main() {
var list = new List<object>() { "foo", DateTime.Now, 1, "bar", 2.4 };

// the Where method does the work...
var numbers = list.Where( el => IsNumeric(el) );
var nonNumbers = list.Where( el => ! IsNumeric(el) );
}

}
erlang
% Wrapped call to the auxiliary function
number_split(Xs) ->
number_split(Xs, [], []).

% The auxiliary function
number_split([], Num, NonNum) ->
{Num, NonNum};
number_split([X|Xs], Num, NonNum) ->
case is_number(X) of
true ->
number_split(Xs, [X|Num], NonNum);
false ->
number_split(Xs, Num, [X|NonNum])
end.
List = ["hello", 25, 3.14, calendar:local_time()],
{Numbers, NonNumbers} = lists:partition(fun(E) -> is_number(E) end, List)
fantom
things := ["hello", 25, 3.14, Time.now]
numbers := things.findType(Num#)
nonNumbers := things.exclude { numbers.contains(it) }
fsharp
let (things:obj list) = [ "hello"; 25; 3.14; System.DateTime.Now ]

let isNumber (x:obj) =
match x with
| :? int | :? float | :? byte | :? decimal | :? int16 | :? int64 -> true
| _ -> false

let numbers, nonNumbers = things |> List.partition isNumber
groovy
now = new Date()
things = ["hello", 25, 3.14, now]
(numbers, others) = things.split{ it instanceof Number }
assert numbers == [25, 3.14]
assert others == ["hello", now]
haskell
import Data.List (partition)

type Date = String
data Things = TS String | TI Int | TD Date
deriving Show

main = do
let myList = [TI 1, TI 23, TS "Joe", TD "23/04/2009"]
print $ partition isNumber myList

where isNumber (TS _) = False
isNumber (TI _) = True
isNumber (TD _) = False
java
public class NumbersSolution {
public static void main(String[] args) {
List<Object> items = Arrays.asList(new Object[] { new Date(), 12L, 15.4, 99, "x" } ) ;
List<Object> numbers = new ArrayList<Object>() ;
List<Object> nonNumbers = new ArrayList<Object>() ;
for (Object item : items )
(item instanceof Number ? numbers : nonNumbers).add(item) ;
}
}
public class NumbersSolution {
public static void main() {
List<Object> numbers = new ArrayList<Object>() ;
List<Object> nonNumbers = new ArrayList<Object>() ;
for (Object item : new Object[] { new Date(), 12L, 15.4, 99, "x" } )
(item instanceof Number ? numbers : nonNumbers).add(item) ;
}
}
ocaml
(* OCaml is a strongly statically typed language so it is not possible to mix
items of different types in a single list.
So here we use a list of strings, some of these strings represent a number *)

let is_a_number v =
try ignore(float_of_string v); true
with _ -> false

let numbers, others =
List.partition is_a_number ["Joe"; "3.14"; "8"; "hello"; "23/04/2009"]

(* ========================================================================== *)
(* If we really want to mix items of several types, we can declare a variant: *)

type item = Int of int | Float of float | String of string | Char of char

let is_a_number = function
| Float _ | Int _ -> true
| String _ | Char _ -> false

let numbers, others =
List.partition is_a_number [String "Joe"; Float 3.14; Int 8; Char 'Z']
perl
use Scalar::Util qw(looks_like_number);
my @things = ('hello',25,3.14,scalar(localtime(time)));
my @numbers;
my @others;
for ( @things ) {
if ( looks_like_number $_ ) {
push @numbers, $_;
} else {
push @other, $_;
}
}
python
import re
data = '34234aff340980adf0e0fa0fefl' ## or ''.join(array)

nonDigits = re.findall(re.compile('\D'), data)
digits = re.findall(re.compile('\d'), data)


ruby
now=Time.now
things=["hello", 25, 3.14, now]

numbers=things.select{|i| i.is_a? Numeric}
others=things-numbers
now=Time.now
things=["hello", 25, 3.14, now]

numbers, others=things.partition{|i| i.is_a? Numeric}
scala
val now = new java.util.Date()
val result = List("hello", 25, 3.14, now) partition { _.isInstanceOf[Number] }
assert(result == (List(25, 3.14), List("hello", now)))

Create a histogram map from a list

Given the list [a,b,a,c,b,b], produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list
clojure
(let [l '[a b a c b b]]
(loop [m {}
d (distinct l)]
(let [item (first d)]
(if (zero? (count d))
m
(recur
(assoc m
item
(count
(filter #(= item %) l)))
(rest d))))))
(->> [:a :b :a :c :b :b]
(group-by identity)
(reduce (fn [m e] (assoc m (first e) (count (second e)))) {}))
(reduce conj {} (for [[x xs] (group-by identity "abacbb")] [x (count xs)]))
(frequencies ["a","b","a","c","b","b"])
(frequencies '[a b a c b b])
cpp
for each(String^ entry in input) hash[entry] = hash->ContainsKey(entry)
? Convert::ToInt32(hash[entry]->ToString()) + 1 : 1;
for each(String^ entry in input) dict[entry] = dict->ContainsKey(entry) ? dict[entry] + 1 : 1;
map<string,int> hist;
for (auto e: { "a","b","a","c","b","b" })
++hist[e];
for (auto e: hist)
cout << e.first << " : " << e.second << endl;
csharp
using System.Collections.Generic;
using System.Linq;

// This is a "functional" C# approach

// NOTE: In C# "maps" are of type Dictionary<Tkey, TValue>
// so our histogram map is of type Dictionary<object, int>
public class HistogramMap {
public Dictionary<object, int> FromList(List<object> list) {
// The "Aggregate" method works like "inject" in many other languages.
return list.Aggregate(
new Dictionary<object, int>(),
(map, obj) => {
// If this is the first time we've seen this obj, set the count to 0
if (!map.ContainsKey(obj)) map[obj] = 0;

// Increment the count
map[obj]++;

// Return the map for the next iteration.
// NOTE: This does NOT return from our "FromList" method
return map;
}
);
}

public static void Main() {
// Create our Histogram Map from a new list
var map = new HistogramMap().FromList(
new List<object>() { 'a', 'b', 'a', 'c', 'b', 'b' }
);

// This just prints the result
System.Console.WriteLine (
string.Join (", ",
// "Select" works like "map" or "collect" in many other languages
map.Select( kvp =>
string.Format("{0} : {1}", kvp.Key, kvp.Value)
).ToArray()
)
);
}
}
new[] {"a","b","a","c","b","b"}
.GroupBy(s => s)
.Select(s => new { Value = s.Key, Count = s.Count() })
.ToList()
.ForEach(e => Console.WriteLine("{0} : {1} ", e.Value, e.Count));
erlang
% Imperative Solution
Histogram = histogram(List),
% Functional (1) Solution
Histogram = histogram(List),
lists:foldl(fun(Elem, OldDict) ->
dict:update_counter(Elem, 1, OldDict)
end,
dict:new(),
[a,b,a,c,b,b])).
fantom
list := ["a","b","a","c","b","b"]
map := [Str:Int][:]
list.each |Str s, Int i| { if(!map.containsKey(s)) map.add(s,1); else map[s] = ++map[s] }
echo (map)
fsharp
let histogram = (List.foldLeft (fun (acc : Map<char, int>) (e : char) -> if (Map.mem e acc) then (Map.add e ((Map.find e acc) + 1) acc) ; else (Map.add e 1 acc)) (Map.empty) list)
let histogram list =
let rec histogram' list' dict' =
match list' with
| [] -> dict'
| x :: xs ->
match Map.tryFind x dict' with
| Some(Value) -> histogram' xs (Map.add x (Value + 1) dict')
| None -> histogram' xs (Map.add x 1 dict')
histogram' list Map.empty

// ------

let histogram' = histogram list
let histogram = (List.foldLeft (fun (acc : Generic.Dictionary<char, int>) (e : char) -> (if acc.ContainsKey(e) then acc.[e] <- acc.[e] + 1 ; else acc.Add(e, 1)) ; acc) (new Generic.Dictionary<char, int>()) list)
let histogram =
list
|> Seq.groupBy (fun a -> a)
|> Seq.map(fun (key, elements) -> key, Seq.length elements)
|> Map.ofSeq
groovy
histogram = [:]
list.each { item ->
if (!histogram.containsKey(item)) histogram[item] = 0
histogram[item]++
}
histogram = [:]
list.each { histogram[it] = (histogram[it] ?: 0) + 1 }
haskell
import Data.List
import qualified Data.Map as Map

histogram :: Ord a => [a] -> Map.Map a Int
histogram xs = Map.fromList [ (head l, length l) | l <- group (sort xs) ]

output :: Map.Map String Int
output = histogram ["a","b","a","c","b","b"]
import Control.Arrow
import Data.List
import qualified Data.Map as Map
import System.Random

histogram :: Ord a => [a] -> Map.Map a Int
histogram = Map.fromList . map (head &&& length) . group . sort

main = print . histogram . take 1000 . randomRs (1::Int, 100) =<< newStdGen
java
Map map = new HashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
String s = (String) it.next();
if (!map.containsKey(s)) {
map.put(s, new Integer(1));
} else {
map.put(s, new Integer(((Integer)map.get(s)).intValue() + 1));
}
}
LinkedMap histogram = new LinkedMap();

for (Object letter : list)
histogram.put(letter, !histogram.containsKey(letter) ? 1 : MapUtils.getIntValue(histogram, letter) + 1);
ocaml
module StringMap = Map.Make (String)

let histogram lst =
List.fold_left (fun m v ->
let n =
if StringMap.mem v m
then succ (StringMap.find v m)
else 1
in
StringMap.add v n m
) StringMap.empty lst

let () =
let h = histogram ["a"; "b"; "a"; "c"; "b"; "b"] in
StringMap.iter (fun key value ->
Printf.printf " %s: %d\n" key value
) h
perl
foreach(@list) {
$histogram{$_}++;
}
$histogram{$_}++ for @list;
python
from collections import defaultdict
h = defaultdict(int)
for k in "abacbb":
h[k] += 1

h = {}
for k in "abacbb":
h[k] = h.setdefault(k, 0) + 1
from collections import Counter
h = Counter("abacbb")
print(h)
ruby
histogram = {}
list.each { |item| histogram[item] = (histogram[item] || 0) +1 }
list = %w{a b a c b b}

histogram = list.each_with_object(Hash.new(0)) do |item, hash|
hash[item] += 1
end

p histogram # => {"a"=>2, "b"=>3, "c"=>1}
list.inject(Hash.new(0)) {|h, item| h[item] += 1; h}
scala
list foreach { (x) => histogram += x -> (histogram.getOrElse(x, 0) + 1) }
val data = List("a", "b", "a", "c", "b", "b")
val keys = data removeDuplicates
val hist = Map.empty[String, Int] ++ keys.map{ k => (k, (data count (_==k)))}
assert(hist == Map("a"->2, "b"->3, "c"->1))
val histEntries = for {
key <- data.removeDuplicates
count = data.count(_ == key)
} yield (key -> count)
val hist = Map(histEntries: _*)
value.foldLeft(Map[T, Int]()){
(m, c) => m.updated(c, m.getOrElse(c, 0) + 1)
}

list.groupBy(identity).mapValues(_.size)

Categorise a list

Given the list [one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length
clojure
(loop [m {}
l ["one" "two" "three" "four" "five"]]
(if (zero? (count l))
m
(let [item (first l)
key (count item)]
(recur
(assoc m key (cons item (get m key [])))
(rest l)))))
(group-by count ["one" "two" "three" "four" "five"])
cpp
for each(String^ entry in input)
{
key = entry->Length;
if (!hash->ContainsKey(key)) hash[key] = gcnew ArrayList;
safe_cast<ArrayList^>(hash[key])->Add(entry);
}
csharp
using System.Collections.Generic;
using System.Linq;
public class ListCategorizer {
public static void Main() {
var list = new List<string>() { "one", "two", "three", "four", "five" };
var categories = list.GroupBy(el => el.Length)
.ToDictionary( g => g.Key, // key
g => g.ToList() ); // value
}
}
erlang
% Imperative Solution
CatList = categorise(List),
% Functional (1) Solution
CatList = categorise(List),
fantom
list := ["one", "two", "three", "four", "five"]
map := [Int:List][:]
list.each { List l := map[it.size] ?: [,]; map[it.size] = l.add(it) }
echo(map)
fsharp
let catmap = (List.foldLeft (fun (acc : Map<int, List<string> >) (e : string) -> if (Map.mem e.Length acc) then (Map.add e.Length ((Map.find e.Length acc) @ [e]) acc) ; else (Map.add e.Length [e] acc)) (Map.empty) list)
let lengthMap =
["one"; "two"; "three"; "four"; "five"]
|> Seq.groupBy (fun s -> s.Length)
|> Seq.map (fun (length, entries) -> (length, entries |> List.ofSeq))
|> Map.ofSeq
groovy
map = ['one', 'two', 'three', 'four', 'five'].groupBy{ it.size() }
haskell
import qualified Data.Map as Map

groupInMapBy :: Ord k => (a -> k) -> [a] -> Map.Map k [a]
groupInMapBy f = foldr (\a -> Map.insertWith (++) (f a) [a]) Map.empty

output :: Map.Map Int [String]
output = groupInMapBy length ["one", "two", "three", "four", "five"]
import Data.List (groupBy, sortBy)
import Data.Function (on)

groupInPairsBy :: Ord k => (a -> k) -> [a] -> [(k, [a])]
groupInPairsBy f = map (\xs -> (f (head xs), xs)) .
groupBy ((==) `on` f) . sortBy (compare `on` f)

output :: [(Int, [String])]
output = groupInPairsBy length ["one", "two", "three", "four", "five"]
java
SortedMap<Integer, List<String> > map = new TreeMap<Integer, List<String> >(); int key; List<String> vlist;

for (String item : list)
{
key = item.length(); vlist = map.containsKey(key) ? map.get(key) : new ArrayList<String>();
vlist.add(item); map.put(key, vlist);
}
MultiValueMap map = new MultiValueMap();
for (Object item : list) map.put(((String) item).length(), item);
ocaml
let map =
List.fold_left (fun map v ->
let len = String.length v in
let before =
try IntMap.find len map
with Not_found -> [] in
IntMap.add len (v :: before) map
) IntMap.empty ["one"; "two"; "three"; "four"; "five"]
perl
@list = qw(one two three four five);
push @{$map{length($_)}}, $_ for (@list);
python
c = defaultdict(list)
for k in ["one", "two", "four", "three", "five"]:
c[len(k)].append(k)
from itertools import groupby
lst = ["one", "two", "four", "three", "five"]
c = dict((k, list(g)) for k,g in
groupby(sorted(lst, key=lambda x: len(x)), key=lambda x: len(x)))
print(c)
ruby
lengths = {}
list.each do |x|
len = x.size
lengths[len] = (lengths[len] || [])
lengths[len] << x
end
lengths = list.group_by {|x| x.size}
list.inject({}) { |h,x| (h[x.size]||=[]) << x; h }
scala
list foreach { (x) => map += x.length -> (x :: map.getOrElse(x.length, Nil)) }
list foreach { (x) => map += x.length -> (map.getOrElse(x.length, Nil) ::: List(x)) }
List("one", "two", "three", "four", "five") groupBy (_ size)

Perform an action if a condition is true (IF .. THEN)

Given a variable name, if the value is "Bob", display the string "Hello, Bob!". Perform no action if the name is not equal.
clojure
(def person "Bob")
(if (= person "Bob")
(println "Hello, Bob!"))
cpp
if (name == "Bob") Console::WriteLine("Hello, {0}!", name);
if (name == "Bob") std::cout << "Hello, " << name << "!" << std::endl;
csharp
if (name == "Bob") Console.WriteLine("Hello, {0}!", name);
erlang
if (Name == "Bob") -> io:format("Hello, ~s!~n", [Name]) ; true -> false end.
case Name of "Bob" -> io:format("Hello, ~s!~n", [Name]) ; _ -> false end.
Name == "Bob" andalso (begin io:format("Hello, ~s!~n", [Name]), true end).
fantom
if (name=="Bob") echo("Hello, Bob!")
fsharp
if name = "Bob" then printfn "Hello, %s!" name
name = "Bob" && begin printfn "Hello, %s!" name ; true end
groovy
if (name=='Bob')
println "Hello, Bob!"
haskell
name = "Bob"
main = if name == "Bob" then putStrLn "Hello, Bob!" else return ()
java
if (name.equals("Bob")) {
System.out.println("Hello, Bob!");
}
ocaml
if name = "Bob"
then print_string "Hello, Bob!"
perl
if ($name eq "Bob") {
print "Hello, Bob!"
}
print "Hello, Bob!" if $name eq "Bob";
python
if name == 'Bob':
print 'Hello, Bob!'
ruby
if (name=='Bob')
puts "Hello, Bob!"
end
puts "Hello, Bob!" if name=='Bob'
scala
val name = "Bob"
if (name.equals("Bob")) printf("Hello, %s!\n", name)
val name = "Bob"

// Scala supports operator overloading, so the following works correctly
if (name == "Bob") printf("Hello, %s!\n", name)

Perform different actions depending on a boolean condition (IF .. THEN .. ELSE)

Given a variable age, if the value is greater than 42 display "You are old", otherwise display "You are young"
clojure
(def age 41)
(if (> age 42) "You are old" "You are young")
cpp
if (age > 42) Console::WriteLine("You are old");
else Console::WriteLine("You are young");
Console::WriteLine("You are {0}", (age > 42 ? "old" : "young"));
std::printf("You are %s\n", (age > 42 ? "old" : "young"));
csharp
int age = 41;

if (age > 42)

System.Console.WriteLine("You are old");
else
System.Console.WriteLine("You are young");


erlang
if Age > 42 -> io:format("You are old~n") ; true -> io:format("You are young~n") end.
Message = if Age > 42 -> "old" ; true -> "young" end, io:format("You are ~s~n", [Message]).
case Age > 42 of true -> io:format("You are old~n") ; false -> io:format("You are young~n") end.
case Age of _ when Age > 42 -> io:format("You are old~n") ; _ -> io:format("You are young~n") end.
Message = case Age of _ when Age > 42 -> "old" ; _ -> "young" end, io:format("You are ~s~n", [Message]).
Age > 42 andalso (begin io:format("You are old~n"), true end) orelse (begin io:format("You are young~n"), true end).
(fun (X) when X > 42 -> io:format("You are old~n"); (_) -> io:format("You are young~n") end)(Age).
(fun () when Age > 42 -> io:format("You are old~n"); () -> io:format("You are young~n") end)().
io:format("You are ~s~n", [if Age > 42 -> "old" ; true -> "young" end]).
fantom
if (age > 42)
echo("You are old")
else
echo("You are young")
echo((age > 42) ? "You are old" : "You are young")
fsharp
if age > 42 then printfn "You are old" else printfn "You are young"
let message = if age > 42 then "old" else "young"
printfn "You are %s" message
groovy
if (age > 42)
println "You are old"
else
println "You are young"
println "You are " + (age > 42 ? "old" : "young")
haskell
putStrLn ("You are " ++ if age > 42 then "old" else "young")
java
if (age > 42) {
System.out.println("You are old");
} else {
System.out.println("You are young");
}
System.out.println("You are " + ((age>42)?"old":"young"));
ocaml
if age > 42
then print_string "You are old"
else print_string "You are young"
perl
if ($age > 42) {
print "You are old"
}
else {
print "You are young"
}
print 'You are ',($age > 42) ? 'old' : 'young';
python
if age > 42:
print 'You are old'
else:
print 'You are young'
print age > 42 and 'You are old' or 'You are young'
ruby
if (age > 42)
puts "You are old"
else
puts "You are young"
end
puts (age>42) ? "You are old" : "You are young"
puts "You are #{age > 42 ? "old" : "young"}"
scala
val age = 42
if (age > 42) println("You are old") else println("You are young")
println( "You are " + ( if ( age > 42 ) "old" else "young" ) )

Replacing a conditional with many branches with a switch/case statement

Many languages support more compact forms of branching than just if ... then ... else such as switch or case or match. Use such a form to add an appropriate placing suffix to the numbers 1..40, e.g. 1st, 2nd, 3rd, 4th, ..., 11th, 12th, ... 39th, 40th
clojure
(def n 112)

(println (str n
(let [rem (mod n 100)]
(if (and (>= rem 11) (<= rem 13))
"th"
(condp = (mod n 10)
1 "st"
2 "nd"
3 "rd"
"th")))))
cpp
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num,i,x;
cout<<"Enter the range:";
cin>>num;
for(i=1;i<=num;i++)
{
x=i%10;
switch(i)
{
case 11:
case 12:
case 13:cout<<i<<"th ";
continue;
}
switch(x)
{
case 1: cout<<i<<"st ";break;
case 2: cout<<i<<"nd ";break;
case 3: cout<<i<<"rd ";break;
default: cout<<i<<"th ";
}
}
getch();
}
csharp
public static string GetOrdinal(int i)
{
if (i > 10 && i < 20) return i.ToString() + "th";
switch (i % 10)
{
case 1:
return i.ToString() + "st";
case 2:
return i.ToString() + "nd";
case 3:
return i.ToString() + "rd";
default:
return i.ToString() + "th";
}
}
public static string GetOrdinal(int i)
{
if (i > 10 && i < 20) return i.ToString() + "th";
switch (i % 10)
{
case 1:
return i.ToString() + "st";
break;
case 2:
return i.ToString() + "nd";
break;
case 3:
return i.ToString() + "rd";
break;
default:
return i.ToString() + "th";
break;
}
}
erlang
Suffix = case Num of
N when N > 10, N < 20 -> "th";
N when N rem 10 =:= 1 -> "st";
N when N rem 10 =:= 2 -> "nd";
N when N rem 10 =:= 3 -> "rd";
_ -> "th"
end,
io_lib:format("~w~s", [Num, Suffix])
fantom
suffix := |Int n -> Str|
{
if ((4..20).contains(n % 100))
return "th"

switch((n.toStr)[-1])
{
case '1': return "st"
case '2': return "nd"
case '3': return "rd"
default: return "th"
}
}

(1..40).each { echo("$it${suffix(it)}") }
fsharp
let suffix = function
| n when n > 10 && n < 20 -> "th"
| n when n % 10 = 1 -> "st"
| n when n % 10 = 2 -> "nd"
| n when n % 10 = 3 -> "rd"
| _ -> "th"

seq { 1 .. 40 }
|> Seq.iter (fun n -> printfn "%i%s" n (suffix n))
groovy
def suffix(n) {
switch(n) {
case { n % 100 in 4..20 } : return 'th'
case { n % 10 == 1 } : return 'st'
case { n % 10 == 2 } : return 'nd'
case { n % 10 == 3 } : return 'rd'
default : return 'th'
}
}
(1..40).each { n ->
println "$n${suffix(n)}"
}
haskell
suffixed n = show n ++ suffix
where
suffix
| n `mod` 100 `div` 10 == 1 = "th"
| otherwise = case n `mod` 10 of
1 -> "st"
2 -> "nd"
3 -> "rd"
_ -> "th"


result = map suffixed [1..40]
java
String[] array = new String[40];
for(int n = 1; n <= array.length; n++)
array[n-1] = Integer.toString(n);
for(int n = 0; n < array.length; n++)
{
int y = Integer.parseInt(array[n]);
if(array[n].length() > 1)
y = Integer.parseInt(array[n].substring(1));
switch(y)
{
case 1: {array[n] += "st"; break;}
case 2: {array[n] += "nd"; break;}
case 3: {array[n] += "rd"; break;}
default: array[n] += "th";
}
}
ocaml
let numsuffix i =
match i with
| 11 | 12 | 13 -> "th"
| x when x mod 10 = 1 -> "st"
| x when x mod 10 = 2 -> "nd"
| x when x mod 10 = 3 -> "rd"
| _ -> "th"
;;
(* alternate implementation without using guards:
let numsuffix i =
match i with
| 11 | 12 | 13 -> "th"
| x -> match x mod 10 with
| 1 -> "st"
| 2 -> "nd"
| 3 -> "rd"
| _ -> "th"
*)

for i = 1 to 40 do
Printf.printf "%d%s " i (numsuffix i);
done;
print_newline ()
perl
sub suffix {
my $n = shift;

return 'th' if $n % 100 >= 4 && $n % 100 <= 20;
return 'st' if $n % 10 == 1;
return 'nd' if $n % 10 == 2;
return 'rd' if $n % 10 == 3;
return 'th';

}

foreach my $n (1..40) {
print $n.suffix($n)."\n";
}
python
def affix(num):
num = num == 1 and str(num) + 'st' or num == 2 and str(num) + 'nd' or \
num == 3 and str(num) +'rd' or str(num) + 'th'
return num

print [affix(x) for x in xrange(1,41)]

ruby
def suffixed(number)
last_digit = number.to_s[-1..-1].to_i
suffix = case last_digit
when 1 then 'st'
when 2 then 'nd'
when 3 then 'rd'
else 'th'
end
suffix = 'th' if (11..13).include?(number)
"#{number}#{suffix}"
end

(1..40).each {|n| puts suffixed(n) }
scala
object FourToTwenties {
def unapply (n: Int) = (4 to 20).contains(n % 100)
}

def suffix (n: Int) = {
n match {
case FourToTwenties() => "th"
case n if n % 10 == 1 => "st"
case n if n % 10 == 2 => "nd"
case n if n % 10 == 3 => "rd"
case _ => "th"
}
}

for (n <- 1 to 40) {
println(n.toString + suffix(n))
}

Perform an action multiple times based on a boolean condition, checked before the first action (WHILE .. DO)

Starting with a variable x=1, Print the sequence "1,2,4,8,16,32,64,128," by doubling x and checking that x is less than 150.
clojure
(take-while #(< % 150) (iterate #(* 2 %) 1))
cpp
int x = 1;

while (x < 150) { x *= 2; Console::Write("{0},", x); }
Console::WriteLine();
for (int x = 1; x < 150; x *= 2) { std::cout << x << ","; }
std::cout << std::endl;
csharp
int x = 1;

while (x < 150)
{
x *= 2;
Console.Write("{0},", x);
}
erlang
X = 1, print_while_X_less_150(X).
Pred = fun (X) -> X < 150 end,
Action = fun (X) -> io:format("~B,", [X]), X * 2 end,
X = 1,

while_do(Pred, Action, X).
fantom
x := 1
while (x < 150) {
Env.cur.out.print("$x,")
x *= 2
}
echo
fsharp
let mutable x = 1
while x < 150 do printf "%d, " x ; (x <- x * 2) done
// The problem is clearly geared towards imperative languages ;-)
// No need to mutate any variable, here's how to do it loop-free functional:
let rec powers2 i = seq { if i < 150 then yield i; yield! powers2 (i*2) }
powers2 1 |> Seq.iter (fun i -> printf "%i, " i)
groovy
x = 1
while (x < 150) {
print x + ","
x *= 2
}
println()
haskell
main :: IO ()
main = loop 1
where
loop x | x < 150 = do
putStr (show x ++ ",")
loop (x * 2)
loop _ = return ()
main = mapM_ print $ takeWhile (<150) $ iterate (* 2) 1
java
int x = 1;
while (x < 150) {
System.out.println(x+",");
x*=2;
}
ocaml
let x = ref 1 ;;

while !x < 150 do
Printf.printf "%d," !x;
x := !x * 2;
done;

print_newline()
perl
my $x = 1;
while($x < 150) {
print $x, ",";
$x *=2
}
python
x = 1
while x < 150:
print '%s, ' % x,
x *= 2
ruby
x=1
while x < 150
puts x
x <<= 1
end
scala
var x = 1 ; while (x < 150) { printf("%d,", x) ; x *= 2 }

Perform an action multiple times based on a boolean condition, checked after the first action (DO .. WHILE)

Simulate rolling a die until you get a six. Produce random numbers, printing them until a six is rolled. An example output might be "4,2,1,2,6"
clojure
(loop [r (rand-int 6)]
(if (= r 5)
nil
(do
(println r)
(recur (rand-int 6)))))
cpp
Random^ rnd = gcnew Random;

int dice = rnd->Next(1, 7); Console::Write("{0}", dice);
do { Console::Write(",{0}", (dice = rnd->Next(1, 7))); } while (dice != 6);
Console::WriteLine();
csharp
System.Random die = new System.Random();
int roll;

do
{
roll = die.Next(1, 6);
Console.Write(roll);
if (roll < 6) Console.Write(",");
}
while (roll != 6);
erlang
Pred = fun (DiceRoll) -> DiceRoll =/= 6 end,
Action = fun (DiceRoll) -> io:format("~B,", [DiceRoll]), dice_roll() end,

do_while(Pred, Action, dice_roll()).
-module(dice).
-export([start/0]).

start() ->
roll(dice_roll()).

roll(6) ->
io:format("6~n", []);
roll(N) ->
io:format("~B,", [N]),
roll(dice_roll()).

dice_roll() -> random:uniform(6).
fantom
rnd := 0
while(rnd != 6) {
rnd = Int.random(1..6)
Env.cur.out.print(rnd)
if (rnd != 6)
Env.cur.out.print(",")
}
echo
fsharp
open System
let rand = Random()

Seq.initInfinite (fun _ -> rand.Next(1, 7))
|> Seq.takeWhile (fun x -> x < 6)
|> fun items -> String.Join(",", items)
|> function s when s = "" -> printfn "6" | s -> printfn "%s,6" s
groovy
// Groovy has no do..while; use a normal while
int dice = 0
while (dice != 6) {
dice = Math.random() * 6 + 1
print dice
if (dice != 6) print ','
}
haskell
import System.Random

diceRolls = do
gen <- newStdGen
print $ takeWhile (/=(6::Int)) (randomRs (1,6) gen)
java
int rnd;
do {
rnd = (int)(Math.random()*6)+1;
System.out.print(rnd);
if (rnd!=6) {
System.out.print(",");
}
} while(rnd!=6);
ocaml
let () =
Random.self_init ();
let rec loop () =
let n = (Random.int 6) + 1 in
print_int n;
if n <> 6 then (print_char ','; loop ())
else print_newline ()
in
loop ()
perl
do {
my $number = int(rand(6)+1);
print $number;
print ',' if ($number != 6);
} while ($number != 6);
python
import random, itertools

def dice():
while True:
yield random.randint(1,6)

print ", ".join(str(d) for d in itertools.takewhile(lambda x: x < 6, dice()))
ruby
# Ruby has no DO..WHILE construct. Need to write it as a WHILE
rnd = 0
while (rnd != 6)
rnd = rand(6)+1
print rnd
print "," if (rnd!=6)
end
begin
rnd = rand(6)+1
print rnd
print "," if rnd!=6
end while rnd != 6
# This uses Enumerators, ad it becomes almost functional style...

games = Enumerator.new do |yielder|
yielder.yield rand(6) + 1 while true
end

puts games.take_while {|roll| roll != 6}.join(",")
scala
val dice = new GenRandInt(1, 6) ; var rnd = 0 ; var fmt = ""
do { rnd = dice.next ; fmt = if (rnd != 6) "%d," else "%d" ; printf(fmt, rnd) } while (rnd != 6)

Perform an action a fixed number of times (FOR)

Display the string "Hello" five times like "HelloHelloHelloHelloHello"
clojure
(dotimes [_ 5]
(print "Hello"))
cpp
for(int i = 0; i < 5; ++i) Console::Write("Hello");
for(int i = 5; i > 0; --i) Console::Write("Hello");
dotimes(5, hello);
fill_n(ostream_iterator<string>(cout), 5, "Hello");
csharp
string text = "Hello";

for (int i = 0; i < 5; i++)
{
Console.Write(text);
}
erlang
dotimes(5, fun () -> io:format("Hello") end).
lists:foreach(fun (_) -> io:format("Hello") end, lists:seq(1, 5)).
fantom
5.times { Env.cur.out.print("Hello") }
for (i := 0; i < 5; i++)
Env.cur.out.print("Hello")
(1..5).each { Env.cur.out.print("Hello") }
fsharp
for i = 1 to 5 do printf "Hello" done
dotimes 5 (fun () -> printf "Hello")
// Repetition via ranging over a List type(index ignored)
for _ in list do printf "Hello" done
// Repetition via ranging over a Sequence type(index ignored)
for _ in sequence do printf "Hello" done
// Repetition via ranging over an Array type(index ignored)
for _ in array do printf "Hello" done
groovy
println "Hello" * 5
5.times { print "Hello" }; println()
haskell
import Control.Monad

hi5 = replicateM_ 5 $ putStr "Hello"
java
for(int i=0;i<5;i++) {
System.out.print("Hello");
}
ocaml
let rec write_hello = function
0 -> ()
| n ->
print_string "Hello" ;
write_hello (n-1)
;;
write_hello 5;;
let write_hello n =
for i = 1 to n do
print_string "Hello";
done

let () = write_hello 5
perl
print "Hello" x 5
print "Hello" for (1..5)
python
print "Hello" * 5
for i in range(5):
print "Hello"
ruby
puts "Hello"*5
5.times { print "Hello" }
scala
// Using overloaded '*' operator (String-specific)
print("Hello" * 5)
List.range(0, 5) foreach { (_) => print("Hello") }
for (_ <- List.range(0, 5)) print("Hello")
// Lazy version
for (_ <- Stream.range(0, 5)) print("Hello")
dotimes(5, _ => print("Hello"))
(0 until 5) foreach { (_) => print("Hello") }
5 times { print("Hello") }

Perform an action a fixed number of times with a counter

Display the string "10 .. 9 .. 8 .. 7 .. 6 .. 5 .. 4 .. 3 .. 2 .. 1 .. Liftoff!"
clojure
(dotimes [i 10]
(print (str (- 10 i) " .. ")))

(println "Liftoff!")
cpp
for(int i = 10; i != 0; --i) Console::Write("{0} .. ", i);
Console::WriteLine("Liftoff!");
csharp
for (int i = 10; i > 0; i--)
{
Console.Write("{0} .. ", i);
}

Console.WriteLine("Liftoff!");
erlang
fromto(10, 1, -1, fun (X) -> io:format("~B .. ", [X]) end), io:format("Liftoff!~n").
lists:foreach(fun (X) -> io:format("~B .. ", [X]) end, lists:seq(10, 1, -1)), io:format("Liftoff!~n").
fantom
(10..1).each { Env.cur.out.print("$it .. ") }
Env.cur.out.print("Liftoff!")
for (i := 10; i >= 1; i--)
Env.cur.out.print("$i .. ")
Env.cur.out.print("Liftoff!")
fsharp
for i = 10 downto 1 do printf "%d .. " i done
printfn "Liftoff!"
// Repetition via ranging over a Sequence type
for i in {10 .. -1 .. 1} do printf "%d .. " i done ; printfn "Liftoff!"
groovy
10.downto(1) { print it + " .. " }
println "Liftoff!"
haskell
countDown = mapM_ printN [10,9..1] >> putStr "Liftoff!"
where printN n = putStr $ show n ++ " .. "
java
for(int i=10; i>=1; i--) {
System.out.print(i + " .. ");
}
System.out.print("Liftoff!");
ocaml
for i = 10 downto 1 do
Printf.printf "%d .. " i
done;
print_endline "Liftoff!"
perl
for (my $i = 10; $i > 0; $i--) {
print "$i .. ";
}
print "Liftoff!";
print "$_ .. " for reverse 1..10;
print "Liftoff!";
python
print " .. ".join(str(i) for i in range(10, 0, -1)), ".. liftoff!"
ruby
10.downto(1) { |n| print n, " .. " }
puts "Liftoff!"
scala
for (i <- List.range(1, 11).reverse) printf("%d .. ", i) ; println("Liftoff!")
for (i <- List.range(-10, 0)) printf("%d .. ", (-i)) ; println("Liftoff!")
var i = 10 ; while (i > 0) { printf("%d .. ", i) ; i -= 1 } ; println("Liftoff!")
for (i <- -10 to -1) printf("%d .. ", (-i)) ; println("Liftoff!")

Read the contents of a file into a string

clojure
(slurp "/tmp/foobar")
cpp
IO::FileStream^ file; String^ buffer;

try
{
file = gcnew IO::FileStream("test.txt", IO::FileMode::Open);
buffer = gcnew String((gcnew IO::BinaryReader(file))->ReadChars(file->Length));
}
IO::StreamReader^ stream; String^ buffer;

try
{
stream = gcnew IO::StreamReader("test.txt");
buffer = stream->ReadToEnd();
}
String^ buffer = IO::File::ReadAllText("test.txt");
csharp
string contents = System.IO.File.ReadAllText("filename.txt");
erlang
Text = readfile("Solution607.erl"),
Text = readfile("Solution608.erl"),
fantom
contents := File(`file.text`).readAllStr
fsharp
let file = new FileStream("test.txt", FileMode.Open)
let buffer = new String((new BinaryReader(file)).ReadChars(Convert.ToInt32(file.Length)))
let stream = new StreamReader("test.txt")
let buffer = stream.ReadToEnd()
let buffer = File.ReadAllText("test.txt")
groovy
contents = file.text
haskell
readFile "c:/tmp/myFile.txt"
java
String text = FileUtils.readFileToString(new File("Solution109.java"), "UTF-8");
RandomAccessFile raf = null; byte[] buffer; String text = null;

try
{
raf = new RandomAccessFile("Solution399.java", "r");
buffer = new byte[(int)raf.length()]; raf.read(buffer);
text = new String(buffer);
}
ocaml
let read_file f =
let ic = open_in f in
let n = in_channel_length ic in
let s = String.create n in
really_input ic s 0 n;
close_in ic;
(s)

let file_contents = read_file "file.txt"
perl
@file = read()
open(my $fh, '<', $path) or die "can't open $path: $!";
$string = do { local $/; <$fh> };
close $fh;
python
contents = open('myFile.txt', 'rt').read()
ruby
file = File.new("Solution108.rb")
whole_file = file.read
scala
val text = FileUtils.readFileToString(new File("Solution467.scala"))
val text = Source.fromFile("Solution1256.scala").mkString("")

Process a file one line at a time

Open the source file to your solution and print each line in the file, prefixed by the line number, like:
1> First line of file
2> Second line of file
3> Third line of file
clojure
(defn read-line-by-line [fn]
(reduce str (map (partial format "%d> %s\n")
(iterate inc 1)
(read-lines fn))))
cpp
IO::StreamReader^ stream; String^ ln; int i = 0;

try
{
stream = gcnew IO::StreamReader("test.txt");
while ((ln = stream->ReadLine())) Console::WriteLine("{0}> {1}", ++i, ln);
}
int i = 0;
for each(String^ line in IO::File::ReadAllLines("test.txt")) Console::WriteLine("{0}> {1}", ++i, line);
csharp
int counter = 0;

// If the file is large, you would want to buffer this instead of reading everything at once
foreach (string line in System.IO.File.ReadAllLines("filename.txt"))
{
Console.WriteLine("{0}> {1}", ++counter, line);
}
erlang
Reader = fun (IODevice) -> io:get_line(IODevice, "") end,
Worker = fun (Line, N) -> io:format("~B> ~s", [N, Line]), N + 1 end,

while_not_eof("Solution609.erl", Reader, Worker, 1).
Reader = fun (Filename) -> {ok, Contents} = file:read_file(Filename), Contents end,
Transformer = fun (Line, N) -> string:concat(string:concat(integer_to_list(N), "> "), Line) end,
Printer = fun (Line) -> io:format("~s~n", [Line]) end,

Lines = string:tokens(binary_to_list(Reader("Solution610.erl")), "\n"),
NewLines = lists:zipwith(Transformer, Lines, lists:seq(1, length(Lines))),
lists:foreach(Printer, NewLines).
fantom
File(`input.text`).readAllLines.each |Str s, Int i| { echo("${i+1}> $s") }
fsharp
let stream = new StreamReader("test.txt")
let mutable i = 1
let mutable line = stream.ReadLine()
while (line <> null) do printfn "%d> %s" i line ; line <- stream.ReadLine() ; i <- i + 1 done
stream.Close()
let proc_a_line (filename : string) proc =
let stream = new StreamReader(filename)
let rec proc_a_line' count line =
match line with
| null -> stream.Close()
| _ -> proc count line ; proc_a_line' (count + 1) (stream.ReadLine())
proc_a_line' 1 (stream.ReadLine())

// ------

let _ = proc_a_line "test.txt" (fun i line -> printfn "%d> %s" i line)
let reader(filename : string) = seq {
use sr = new StreamReader(filename)
while not sr.EndOfStream do
let line = sr.ReadLine()
yield line
done
}

// ------

reader("test.txt") |> Seq.iteri (fun i line -> printfn "%d> %s" (i + 1) line)
File.ReadAllLines("test.txt") |> Array.iteri (fun i line -> printfn "%d> %s" (i + 1) line)
// Unlike ReadAllLines, ReadLines (new in .NET 4) only reads the file
// one line at a time, rather than reading the entire file into an array first.

open System.IO
File.ReadLines("test.txt") |> Seq.iteri (fun i line -> printfn "%d> %s" (i + 1) line)
groovy
int count = 0
file.eachLine { line ->
println "${++count} > $line"
}
file.eachLine { line, count ->
println "${++count} > $line"
}
haskell
import Data.List

prefixWithNumber str n = show n ++ "> " ++ str

numberStrings (x:xs) n = prefixWithNumber x n : (numberStrings xs (n+1))
numberStrings [] n = []

main = do
str <- readFile "prefix.hs"
putStrLn (intercalate "\n" (numberStrings (lines str) 1))
prefix n str = show n ++ "> " ++ str

main = readFile "prefix.hs" >>=
putStr . unlines . zipWith prefix [1..] . lines
java
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("Solution104.java"));
String line = null;
int lineNumber = 1;
while ((line=br.readLine())!=null) {
System.out.println(lineNumber + "> " + line);
lineNumber++;
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (br!=null) {
try {
br.close();
} catch (Exception e) {
// ok
}
}
}
LineNumberReader lnr = null; PrintWriter pw = null; String line;

try
{
lnr = new LineNumberReader(new FileReader("Solution400.java"));
pw = new PrintWriter(System.out);
while ((line = lnr.readLine()) != null) pw.printf("%d> %s\n", lnr.getLineNumber(), line);
}
ocaml
let () =
let ic = open_in Sys.argv.(1) in
let i = ref 1 in
try
while true do
Printf.printf "%d> %s\n" !i (input_line ic);
incr i
done
with End_of_file ->
close_in ic
let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None

let () =
let ic = open_in Sys.argv.(1) in
let rec aux i =
match input_line_opt ic with
| Some line ->
Printf.printf "%d> %s\n" i line;
aux (succ i)
| None ->
close_in ic
in
aux 1
perl
open(my $fh, '<', $path) or die "can't open $path: $!";
$c = 1;
print $c++ . "> $_" for (<$fh>);
close $fh;
open my $fh, '<', $path or die "Can't open $path: $!";
while (<$fh>) {
print "$.> $_";
}
python
for no, line in enumerate(open(__file__)):
print "{0}> {1}".format(no+1, line.rstrip())
ruby
File.open("Solution103.rb").each_with_index { |line, count|
puts "#{count} > #{line}
}
scala
val source = Source.fromFile(new File("Solution468.scala")).getLines
var n = 1 ; while (source.hasNext) { printf("%d> %s", n, source.next) ; n += 1 }
val source = Source.fromFile(new File("Solution469.scala")).getLines
for ((line, n) <- source zipWithIndex) { printf("%d> %s", (n + 1), line) }

Write a string to a file

clojure
(with-out-writer "output.txt" (println "Hello file!"))
cpp
IO::StreamWriter^ stream;

try
{
stream = gcnew IO::StreamWriter("test.txt", false);
stream->WriteLine("This line overwites file contents!");
}
csharp
System.IO.File.WriteAllText("filename.txt", "Some text to write to the file");
erlang
Line = "This line overwites file contents!\n",
{ok, IODevice} = file:open("test.txt", [write]), file:write(IODevice, Line), file:close(IODevice).
fantom
File(`out.txt`).out.writeChars("some text").flush
fsharp
let stream = new StreamWriter("test.txt", false)
stream.WriteLine("This line overwrites file contents!")
groovy
file.delete()
file << 'some text'
file.text = 'some text'
haskell
writeFile "filename" "stringe"
java
FileWriter fw = null;

try
{
fw = new FileWriter("test.txt");
fw.write("This line overwites file contents!");
}
PrintWriter pw = null;

try
{
pw = new PrintWriter(new BufferedWriter(new FileWriter("test.txt")));
pw.print("This line overwites file contents!");
}
ocaml
try
let cout = open_out filename in
let co = Format.formatter_of_out_channel cout in
Format.fprintf co "%s\n" text_to_write;
close_out cout
with Sys_error _ as e ->
Format.printf "Cannot open file \"%s\": %s\n" filename (Printexc.to_string e)
perl
open(my $fh, '>', $path) or die "can't open $path: $!";
print $fh "This line overwites file contents!";
close $fh;
python
open('test.txt', 'wt').write('Hello World!')
ruby
File.new("a_file", "w") << "some text"
scala
FileUtils.writeStringToFile(new File("test.txt"), "This line overwites file contents!")
val fw = new FileWriter("test.txt") ; fw.write("This line overwites file contents!") ; fw.close()

Append to a file

clojure
(with-out-append-writer "output.txt" (println "This is appended to the file"))
cpp
IO::StreamWriter^ stream;

try
{
stream = gcnew IO::StreamWriter("test.txt", true);
stream->WriteLine("This line appended to file!");
}
csharp
System.IO.File.AppendAllText("filename.txt", "Some text to append to the file");
erlang
Line = "This line appended to file!\n",
{ok, IODevice} = file:open("test.txt", [append]), file:write(IODevice, Line), file:close(IODevice).
fantom
File(`out.txt`).out(true).writeChars("some text").flush
fsharp
let stream = new StreamWriter("test.txt", true)
stream.WriteLine("This line appended to file!")
groovy
file << 'some text'
haskell
appendfile "filename" "string"
java
FileWriter fw = null;

try
{
fw = new FileWriter("test.txt", true);
fw.write("This line appended to file!");
}
PrintWriter pw = null;

try
{
pw = new PrintWriter(new BufferedWriter(new FileWriter("test.txt", true)));
pw.print("This line appended to file!");
}
ocaml
let () =
let oc =
open_out_gen
[Open_wronly; Open_creat; Open_append; Open_text] 0o666 "test.txt" in
output_string oc "This line appended to file!\n";
close_out oc
perl
open(my $fh, '>>', $path) or die "can't open $path: $!";
print $fh "This line is appended to the file!";
close $fh;
python
open('test.txt', 'at').write('Hello World!\n')
ruby
file = File.new('/tmp/test.txt', 'a+') ; file.puts 'This line appended to file!!' ; file.close()
scala
val fw = new FileWriter("test.txt", true) ; fw.write("This line appended to file!") ; fw.close()

Process each file in a directory

clojure
; (defn process-file [f] "process one file" body...)
(map process-file (.listFiles (File. ".")))
cpp
for each(String^ filename in IO::Directory::GetFiles(dirname)) process(filename);
csharp
foreach (string filename in System.IO.Directory.GetFiles(directory)) ProcessFile(filename);
erlang
% File basenames only - many tasks require absolute paths to work
lists:foreach(fun (FileOrDirPath) -> Worker(FileOrDirPath) end, file:list_dir(Directory)).
% Absolute paths provided - will accomodate most tasks
lists:foreach(fun (FileOrDirPath) -> Worker(FileOrDirPath) end, list_dir_path(Directory)).
fantom
File(`./`).list.each { process(it) }
fsharp
let dirname = "c:\\"

let processFile filename = printfn "%s" filename
for filename in Directory.GetFiles(dirname) do processFile filename done
let dirname = "c:\\"

Directory.GetFiles(dirname) |> Array.iter (fun filename -> printfn "%s" filename)
groovy
dir.eachFile{ f -> process(f) }
haskell
import System.Directory
import Control.Monad

process filename = putStrLn filename

main = getDirectoryContents "." >>=
filterM doesFileExist >>=
mapM_ process
java
for (File file : (new File("c:\\")).listFiles()) process(file);
ocaml
let process dir file =
if not (Sys.is_directory (Filename.concat dir file))
then print_endline file

let () =
let dir = "." in
let files = Sys.readdir dir in
Array.iter (process dir) files
perl
use File::Glob;

for (<*>) {
process_file($_) if (-f);
}
python
import os
results = (process(f) for f in os.listdir(".") if os.path.isfile(f))
ruby
directory = '/tmp' ; Dir.foreach(directory) {|file| puts "#{file}"}
scala
for (file <- new File("c:\\").listFiles) { processFile(file) }

Display the current date and time

Create a Date object representing the current date and time. Print it out.
If you can also do this without creating a Date object you can show that too.
clojure
(import 'java.util.Date)

(println (str (Date.)))
cpp
QDate now = QDate::currentData();
qDebug() << now.toString();
time_t date = time(0);
cout << ctime(&date);
csharp
// Creating a variable first:
DateTime now = DateTime.Now;
Console.WriteLine(now);

// Without creating a variable:
Console.WriteLine(DateTime.Now);
erlang
io:format("~p~n", [calendar:local_time()])
fantom
echo(DateTime.now)
fsharp
printfn "%A" System.DateTime.Now
groovy
println new Date()
haskell
import System.Time

main = do ct <- getClockTime
print ct
import Data.Time

main = do zt <- getZonedTime
print zt
java
import java.util.Date;

public class SolutionXX {
public static void main(String[] args) {
Date now = new Date();
System.out.println(now.toString());
}
}
ocaml
Unix.localtime (Unix.gettimeofday ())
perl
use Class::Date;
my $date = Class::Date->now();
print $date->string()."\n";

print localtime()."\n";
use Time::Piece ();

# Date object
my $date = Time::Piece::localtime;
print "$date\n";
# no object
print scalar(localtime),"\n";
python
from datetime import datetime
print datetime.utcnow()
ruby
puts DateTime.now
scala
println(new java.util.Date)
OOP

Define a class

Declare a class named Greeter that takes a string on creation and greets using this string if you call the "greet" method.
clojure
(defprotocol IGreeter
(greet [this]))

(deftype Greeter [whom]
IGreeter
(greet [this]
(println (str "Hello, " whom))))

(greet (Greeter. "world"))
(defn greeter [whom]
{:whom whom})

(defn greet [g]
(println (str "Hello, " (:whom g))))

(greet (greeter "world"))
cpp
class Greeter
{
public:
Greeter(const std::string& whom);
void greet() const;

private:
std::string whom;
};

int main()
{
Greeter* gp = new Greeter("world");
gp->greet();
delete gp;
}

Greeter::Greeter(const std::string& whom) : whom(whom) {}

void Greeter::greet() const
{
std::cout << "Hello, " << whom << std::endl;
}
public ref class Greeter
{
public:
Greeter(String^ whom);
void greet();

private:
initonly String^ whom;
};

int main()
{
(gcnew Greeter(L"world"))->greet();
}

Greeter::Greeter(String^ whom) : whom(whom) {}

void Greeter::greet()
{
Console::WriteLine(L"Hello, {0}", whom);
}
csharp
using System;

class Greeter
{
private string name {get;set;}

public void Greet(){
Console.WriteLine("Hello, {0}",name);
}

public Greeter(string name){
this.name = name;
}
}

class Test
{
static void Main()
{
new Greeter("Dante").Greet();
}
}
erlang
Greeter = make_greeter("world!"),
Greeter(greet).
fantom
class Greeter
{
private Str whom
new make(Str whom) { this.whom = whom }
Void greet() { echo("Hello, $whom") }
}

Greeter("world").greet
fsharp
type Greeter(whom' : string) =
member this.greet() = printfn "Hello, %s!" whom'

(new Greeter("world")).greet()
type Greeter(whom' : string) =
let whom : string = whom'
member this.greet() = printfn "Hello, %s!" whom

(new Greeter("world")).greet()
type Greeter =
class
val whom : string
new(whom') = { whom = whom' }
member this.greet() = printfn "Hello, %s!" this.whom
end

(new Greeter("world")).greet()
groovy
// version using named parameters
class Greeter {
def whom
def greet() { println "Hello, $whom" }
}
new Greeter(whom:'world').greet()
// version using traditional constructor
class Greeter {
private whom
Greeter(whom) { this.whom = whom }
def greet() { println "Hello, $whom" }
}
new Greeter('world').greet()
haskell
data Greeter = Greeter String

class Greets a where
greet :: a -> IO ()

instance Greets Greeter where
greet (Greeter s) = print s

main = greet (Greeter "Hello")
java
class Greeter
{
public Greeter(String whom) { this.whom = whom; }
public void greet() { System.out.printf("Hello, %s\n", whom); }
private String whom;
}

public class Solution381 {
public static void main(String[] args) {
(new Greeter("world")).greet();
}
}
ocaml
class greeter message =
object
method greet = print_endline message
end

let o = new greeter "Hello" in
o#greet
perl
{ package Greeter;
sub new {
my $self = {};
my $type = shift;
$self->{'whom'} = shift;
bless $self, $type;
}

sub greet {
my $self = shift;
print "Hello " . $self->{'whom'} . "!\n";
}
}

my $greeter = Greeter->new("world");
$greeter->greet();
{
package Greeter;

sub new {
my $class = shift;
my $whom = shift or die 'Need a name to greet';
bless \$whom, $class;
}

sub greet {
my $self = shift;
print "Hello $$self!\n";
}
}

my $greeter = Greeter->new("Bob");
$greeter->greet();
python
class Greeter(object):
""" Greet someone.
"""
def __init__(self, whom):
self._whom = whom
def greet(self):
print "Hello, %s!" % self._whom

Greeter("world").greet()
ruby
class Greeter
def initialize(whom) @whom = whom end
def greet() puts "Hello, #{@whom}!" end
end

(Greeter.new("world")).greet()
scala
class Greeter(whom : String) { def greet() = { printf("Hello %s\n", whom) } }

(new Greeter("world!")).greet()
XML

Process an XML document

Given the XML Document:

<shopping>
  <item name="bread" quantity="3" price="2.50"/>
  <item name="milk" quantity="2" price="3.50"/>
</shopping>

Print out the total cost of the items, e.g. $14.50
clojure
(println (format "Total cost of items are $%#.2f"
(->> (xml-seq (parse *xml-input-stream*))
(filter #(= :item (:tag %))) ; Remove all but the item tags
(map :attrs) ; Keep the attributes
(map (fn [e] (str "(* " (:quantity e) " " (:price e) ")"))) ; Get the total price as a sexp
(map read-string) ; "(* quantity price)" -> (* quantity price)
(map eval) ; (* quantity price) -> quantity*price
(apply +)))) ; Sum all elements
cpp
char input[] =
"<shopping>"
" <item name=\"bread\" quantity=\"3\" price=\"2.50\"/>"
" <item name=\"milk\" quantity=\"2\" price=\"3.50\"/>"
"</shopping>";

xml_document<> doc;
doc.parse<0>(input);
xml_node<> *shopping = doc.first_node();

float total_price = 0;
for (xml_node<> *item = shopping->first_node(); item != NULL; item = item->next_sibling())
{
float item_sum = 0;
float val;

if (string(item->name()) != "item")
continue;

for (xml_attribute<> *attr = item->first_attribute(); attr != NULL; attr = attr->next_attribute())
{
string name(attr->name());
if (name == "quantity" || name == "price")
{
stringstream v(attr->value());
v >> val;
if (item_sum)
item_sum *= val;
else
item_sum = val;
}
}
total_price += item_sum;
}

cout.setf(ios::fixed, ios::floatfield);
cout << "Total price is $" << setprecision(2) << total_price << endl;
csharp
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(
@"<shopping>
<item name='bread' quantity='3' price='2.50'/>
<item name='milk' quantity='2' price='3.50'/>
</shopping>");

string decimalSeparator= System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;

double sum=0;

foreach(System.Xml.XmlNode nodo in doc.SelectNodes("/shopping/item")){
sum += int.Parse(nodo.Attributes["quantity"].InnerText) * double.Parse(nodo.Attributes["price"].InnerText.Replace(".",decimalSeparator));
}
Console.WriteLine("{0:#.00}",sum);
erlang
-include_lib("xmerl/include/xmerl.hrl").
-export([get_total/1]).

get_total(ShoppingList) ->
{XmlElt, _} = xmerl_scan:string(ShoppingList),
Items = xmerl_xpath:string("/shopping/item", XmlElt),
Total = lists:foldl(fun(Item, Tot) ->
[#xmlAttribute{value = PriceString}] = xmerl_xpath:string("/item/@price", Item),
{Price, _} = string:to_float(PriceString),
[#xmlAttribute{value = QuantityString}] = xmerl_xpath:string("/item/@quantity", Item),
{Quantity, _} = string:to_integer(QuantityString),
Tot + Price*Quantity
end,
0, Items),
io:format("$~.2f~n", [Total]).
fantom
sum := 0.0
root := XParser(File(`shop.xml`).in).parseDoc.root
if (root.name == "shopping")
{
root.elems.each
{
if (it.name == "item")
{
quantity := Int.fromStr(it.get("quantity"))
price := Decimal.fromStr(it.get("price"))
sum += quantity * price;
}
}
}
echo("\$$sum")
fsharp
#r @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.5\System.Xml.Linq.dll"

open System
open System.Xml.Linq
//XElement Helper
let xname sname = XName.Get sname

let xmlsnippet =
let snippet = new XElement(xname "shopping")
//create bread
let bread = new XElement(xname "item")
bread.SetAttributeValue(xname "name","bread")
bread.SetAttributeValue(xname "quantity",3)
bread.SetAttributeValue(xname "price",2.50)
//add bread to snippet
snippet.Add(bread)
//create milk
let milk = new XElement(xname "item")
milk.SetAttributeValue(xname "name","milk")
milk.SetAttributeValue(xname "quantity",2)
milk.SetAttributeValue(xname "price",3.50)
//add milk to snippet
snippet.Add(milk)
snippet

let totalprice (xe: XElement) =
xe.Descendants(xname "item")
|> Seq.map(fun i -> Double.Parse(i.Attribute(xname "price").Value))
|> Seq.fold(fun acc x -> acc + x) 0.0


let xname sname = XName.Get sname
let xattr (elem: XElement) sname = elem.Attribute(xname sname).Value
let xml = XDocument.Load("xml.txt")

let shoppingCost =
xml.Descendants(xname "item")
|> Seq.map (fun i -> Double.Parse(xattr i "quantity"), Double.Parse(xattr i "price"))
|> Seq.sumBy (fun (quantity, price) -> quantity * price)
// Alternative solution that uses XML Navigation, and XPath expressions to ensure that
// the items have the required attributes
let xname sname = XName.Get sname
let xattr (elem: XElement) sname = elem.Attribute(xname sname).Value

let navigator = XPathDocument("xml.txt").CreateNavigator()
let path = XPathExpression.Compile("/shopping/item[@price][@quantity]")
let names = XmlNamespaceManager(navigator.NameTable)
path.SetContext(names)
let shoppingCost =
match path.ReturnType with
| XPathResultType.NodeSet ->
navigator.Select(path)
|> Seq.cast
|> Seq.map (fun (i: XPathNavigator) ->
if i.IsNode then
let elem = XElement.Parse(i.OuterXml)
Double.Parse(xattr elem "quantity"), Double.Parse(xattr elem "price")
else
failwith "Error in expression, expecting to see a node"
)
|> Seq.sumBy (fun (quantity, price) -> quantity * price)
| _ -> failwith "Error in expression, expecting to see a node set"
groovy
printf '$%.2f\n', new XmlSlurper().parseText(xml).item.collect{
it.@quantity.toInteger() * it.@price.toFloat()
}.sum()
haskell
File Edit Options Buffers Tools Haskell Help
import Text.ParserCombinators.Parsec
import Control.Monad
import System ( getArgs )

data Item = Item { name :: String,
quantity :: Int,
price :: Int }
deriving Show

type Basket = [Item]

item :: Parser Item
item = do string "<item name=\""
name <- manyTill letter (char '\"')
string " quantity=\""
quantity <- liftM read $ many digit
string "\" price=\""
dollars <- liftM read $ many digit
cents <- option 0 (char '.' >> (liftM read $ many digit))
string "\"/>"
return $ Item name quantity (100 * dollars + cents)

basket :: Parser Basket
basket = do string "<shopping>"
items <- manyTill item (try $ string "</shopping>")
return items

parseBasket :: String -> Basket
parseBasket input = case parse basket "Shopping Basket" input of
Left _ -> []
Right val -> val

main = do args <- getArgs
putStrLn $ show . (/100) . fromIntegral . sum . map (\(Item _ q p) -> q * p) . parseBasket $ head args
import Text.XML.HXT.Core
import Text.Printf

main :: IO ()
main = do
prices <- runX (process "basket.xml")
printf "$%.2f\n" $ sum prices

process :: FilePath -> IOSArrow XmlTree Double
process filename =
readDocument [withValidate no] filename >>>
getChildren >>>
isElem >>> hasName "shopping" >>>
getChildren >>>
isElem >>> hasName "item" >>>
getQuantity &&& getPrice >>>
arr (uncurry (*))

getQuantity :: IOSArrow XmlTree Double
getQuantity =
getAttrl >>> hasName "quantity" >>> getChildren >>>
getText >>> arr read

getPrice :: IOSArrow XmlTree Double
getPrice =
getAttrl >>> hasName "price" >>> getChildren >>>
getText >>> arr read
java
// solution uses JAXP and SAX included in Java API since version >= 1.5
class ShoppingContentHandler extends DefaultHandler {
Double priceSum = 0d;
@Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
if(name.equals("item")) {
String quantityString = attributes.getValue(attributes.getIndex("quantity"));
String priceString = attributes.getValue(attributes.getIndex("price"));
Integer quantity = Integer.parseInt(quantityString);
Double price = Double.parseDouble(priceString);
priceSum += (quantity * price);
}
}
public Double getPriceSum() {
return priceSum;
}
}

SAXParserFactory parserFactory = SAXParserFactory.newInstance();
try {
SAXParser parser = parserFactory.newSAXParser();
XMLReader reader = parser.getXMLReader();
ShoppingContentHandler contentHandler = new ShoppingContentHandler();
reader.setContentHandler(contentHandler);
reader.parse(new InputSource(new FileReader("shopping.xml")));
System.out.printf("$%.2f", contentHandler.getPriceSum());

} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ocaml
let () =
let xml = Xml.parse_file "shopping.xml" in
let res =
Xml.fold (fun total xml ->
match xml with
| Xml.Element ("item", attrs, _) ->
let quantity = float_of_string (List.assoc "quantity" attrs)
and price = float_of_string (List.assoc "price" attrs) in
total +. (quantity *. price)
| _ -> total
) 0.0 xml
in
Printf.printf "Total cost of the items: %g\n" res
perl
#! /usr/bin/perl
# -*- Mode: CPerl -*-

use strict;
use XML::Simple;
use Data::Dumper;

# Given the XML Document:
#
# <shopping>
# <item name="bread" quantity="3" price="2.50"/>
# <item name="milk" quantity="2" price="3.50"/>
# </shopping>
#
# Print out the total cost of the items, e.g. $14.50

my $xml =
" <shopping>\n"
." <item name=\"bread\" quantity=\"3\" price=\"2.50\"/>\n"
." <item name=\"milk\" quantity=\"2\" price=\"3.50\"/>\n"
." </shopping>\n";

my $xs = XML::Simple->new();
my $ref = $xs->XMLin($xml);
my $stuff = ${$ref}{item};

my $q;
my $p;
my $t;
my $z;

foreach my $item ( sort keys %{$stuff}){
$q = ${$stuff}{$item}{quantity};
$p = ${$stuff}{$item}{price};
$z = $q*$p;
printf "%5.5s %2d @\$%5.2f = \$%5.2f\n",$item,$q,$p,$z;
$t += $z;
}
printf "Total \$%5.2f\n",$t;

#eos
use strict;
use XML::Twig;

use Data::Dumper;

my $xml = <<ENDXML;
<shopping>
<item name="bread" quantity="3" price="2.50"/>
<item name="milk" quantity="2" price="3.50"/>
</shopping>
ENDXML

my $xt = XML::Twig->parse( $xml );

my $price;
foreach my $item ($xt->root->children('item')) {
$price += ($item->{att}{price} * $item->{att}{quantity})
}

printf "Total Cost: %.2f\n", $price


python
from xml.dom.minidom import parseString
document = parseString(
"""<shopping>
<item name="bread" quantity="3" price="2.50"/>
<item name="milk" quantity="2" price="3.50"/>
</shopping>""").documentElement
total = sum([float(item.getAttribute('price')) *
int(item.getAttribute('quantity'))
for item in document.getElementsByTagName('item')])
print '$%.2f' % total
ruby
#!/usr/bin/env ruby

# needed to parse xml
require 'rexml/document'

# grab the file
file = File.new('shop.xml')

# load it as an xml document
doc = REXML::Document.new(file)

# initialize the total to 0 as a float
total = 0.0

# cycle through the items
doc.elements.each('shopping/item') do |item|

# add the price to the total
total += item.attributes['price'].to_f
end

# round the total to the nearest 0.01
total = (total*100.0).round/100.0

# pad the output with the proper number of trailing 0's
printf "$%.2f\n", total
scala
val data = <shopping>
<item name="bread" quantity="3" price="2.50"/>
<item name="milk" quantity="2" price="3.50"/>
</shopping>

val res = for (
item <- data \ "item" ;
price = (item \ "@price").text.toDouble ;
qty = (item \ "@quantity").text.toInt)
yield (price * qty)

printf("$%.2f\n", res.sum)

Greatest Common Divisor

Find the largest positive integer that divides two given numbers without a remainder. For example, the GCD of 8 and 12 is 4.

clojure
(defn gcd [a b]
(if (zero? b)
a
(recur b (mod b a))))
cpp
#include <iostream>
#include <cstdlib>
#include <algorithm>

using namespace std;

int gcd_recursive(int i, int j) {
if (min(i, j) == 0)
return max(i, j);
else
return gcd_recursive(min(i, j), abs(i - j));
}

int gcd_recursive2(int x, int y) {
if (y == 0)
return x;
else
return gcd_recursive2(y, (x % y));
}

int gcd_iterative(int i, int j) {
while (min(i, j) != 0) {
i = min(i, j);
j = abs(i - j);
}
return max(i, j);
}

int main() {
std::cout << gcd_recursive(8, 12) << std::endl;
std::cout << gcd_recursive2(8, 12) << std::endl;
std::cout << gcd_iterative(8, 12) << std::endl;
return 0;
}
csharp
public static int gcd(int a, int b)
{
if (b == 0)
return a;
else
return gcd(b, a % b);
}
erlang
-module(gcd).
-export([gcd/2]).

gcd(A, 0) -> A;
gcd(A, B) -> gcd(B, A rem B).
fantom
gcd := |Int a, Int b -> Int| {
pair := [a, b].sort
while (pair.first != 0)
pair.set(1, pair.last % pair.first).swap(0, 1)
return pair.last
}
echo(gcd(12, 8)) // a>b, result == 4
echo(gcd(1029, 1071)) // a<b, result == 21
fsharp
let rec gcd x y =
if y = 0 then x
else gcd y (x % y)
groovy
static def gcd(int i, int j) {
if (Math.min(i,j)==0) return Math.max(i,j)
else return gcd(Math.min(i,j),Math.abs(i-j))
}
haskell
8 `gcd` 12
java
static int gcd(int a, int b) {
if (Math.min(a, b) == 0)
return Math.max(a, b);
else
return gcd(Math.min(a, b), Math.abs(a - b));
}
ocaml
(* tail recursive *)
let rec gcd n m =
if m = 0 then
n
else if n > m then
gcd (n-m) m
else
gcd n (m-n)
;;
perl
sub gcd {
my ($a, $b) = @_;
($a,$b) = ($b,$a) if $a > $b;

while ($a) { ($a, $b) = ($b % $a, $a) }

return $b;
}

print gcd( 8, 12 );
my $g = gcd (8, 12);
print $g;

sub gcd {
# Euclid's Algorithm - recursive
my ($c, $d) = @_;
return $c unless $d;
return gcd ($d, $c % $d);
}
my $g = gcd2 (8, 12);
print $g;

sub gcd2 {
# Dijkstra's Algorithm - recursive
my ($c, $d) = @_;
return $c if $c == $d;
return $c > $d? gcd2 ($c - $d, $d) : gcd2 ($c, $d - $c);
}
python
def gcd_recursive(i, j):
if min(i, j) == 0:
return max(i, j)
else:
return gcd_recursive(min(i, j), abs(i - j))

def gcd_iterative(i, j):
while min(i, j) != 0:
i, j = min(i, j), abs(i - j)
return max(i, j)

if __name__ == "__main__":
print gcd_recursive(8, 12)
print gcd_iterative(8, 12)
from fractions import gcd
print gcd(8, 12)
ruby
135.gcd(30)
# => 15
scala
def gcd(x: Int, y: Int): Int =
if (b == 0) x
else gcd(b, x % y)