Solved Problems

Output a string to the console

Write the string "Hello World!" to STDOUT
ruby
puts "Hello World!"
$stdout<<"Hello World!"
java
System.out.println("Hello World!");
System.out.printf("Hello World!\n");
perl
print "Hello World!\n"
groovy
println "Hello World!"
scala
println("Hello World!")
printf("Hello World!\n")
python
print "Hello World!"
# python 3 requires parentheses for print

print('Hello, world!\n')
cpp
std::cout << "Hello World" << std::endl;
std::printf("Hello World\n");
Console::WriteLine(L"Hello World");
fsharp
printfn "Hello World!"
erlang
io:format("Hello, World!~n").
ocaml
print_string "Hello world!\n";;
print_endline "Hello world!";;
Printf.printf "Hello world!\n";;
csharp
System.Console.WriteLine("Hello World!")
php
echo 'Hello World!';
/****
* For some (security)reason I couldn't
* submit this without adding a space to
* the functionname. Please remove it :)
****/

// The correct way in command line-mode. :)
f write(STDOUT, "Hello World!\n");
haskell
main = putStrLn "Hello World!"
clojure
(println "Hello World!")
fantom
echo("Hello World!")
go
fmt.Printf("Hello, world\n")
fmt.Println("Hello, World!")

Define a string containing special characters

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

Define a multiline string

Define the string:
"This
Is
A
Multiline
String"
ruby
text = <<"HERE"
This
Is
A
Multiline
String
HERE
text = "This\nIs\nA\nMultiline\nString"
java
String text = "This\nIs\nA\nMultiline\nString";
String text =
"This\n" +
"Is\n" +
"A\n" +
"Multiline\n" +
"String"
perl
$text = 'This
Is
A
Multiline
String';
$text = <<EOF;
This
Is
A
Multiline
String
EOF
groovy
def text =
"""This
Is
A
Multiline
String"""
def text = "This\nIs\nA\nMultiline\nString"
scala
val text = """This
Is
A
Multiline
String"""
val text = "This\nIs\nA\nMultiline\nString"
python
text = """This
Is
A
Multiline
String"""
# with proper indentation
text = (
"This\n"
"Is\n"
"A\n"
"Multiline\n"
"String"
)
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";
fsharp
let multiline = "This\nIs\nA\nMultiline\nString"
let multiline = "This
Is
A
Multiline
String"
erlang
Text = "This\nIs\nA\nMultiline\nString",
ocaml
"This\nIs\nA\nMultiline\nString"
"This
Is
A
Multiline
String"
csharp
string output = "This\nIs\nA\nMultiline\nString";
string output = @"This
Is
A
Multiline
String";
php
$multiline = <<<ML
This
Is
A
Multiline
String
ML;
$multiline = "This
Is
A
Multiline
String";
$multiline = "This\nIs\nA\nMultiline\nString";
haskell
s = "This \
\Is \
\A \
\Multiline \
\String"
clojure
(def multiline "This\nIs\nA\nMultiline\nString")
fantom
s := "This
Is
A
Multiline
String"
go
text := "This\nIs\nA\nMultiline\nString\n"
text := "This\n" + "Is\n" + "A\n" + "Multiline\n" + "String\n"
var s = `This
Is
A
Multiline
String`

Define a string containing variables and expressions

Given variables a=3 and b=4 output "3+4=7"
ruby
puts "#{a}+#{b}=#{a+b}"
puts "#{a}+#{b}=%s" % (a + b)
java
System.out.println(a + "+" + b + "=" + (a+b));
System.out.printf("%d+%d=%d\n", a, b, a + b);
perl
print "$a+$b=${\($a+$b)}\n";
sprintf("%d+%d=%d", $a, $b, $a + $b);
print $a, '+', $b, '=', $a + $b;
groovy
println "$a+$b=${a+b}"
printf "%d+%d=%d\n", a, b, 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}"
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)
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;
fsharp
let a, b = 3, 4
let mystr = sprintf "%d+%d=%d" a b (a+b)
printfn "%s" mystr
erlang
A = 3, B = 4,
io:format("~B+~B=~B~n", [A, B, (A+B)]).
ocaml
Printf.printf "%d+%d=%d" a b (a+b);;
Printf.printf "%d+%d=%d" a b (a+b);;
csharp
int a = 3;
int b = 4;
Console.WriteLine("{0}+{1}={2}", a,b,a+b);
php
echo "$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
clojure
(format "%d + %d = %d" a b (+ a b))
fantom
echo("$a+$b=${a+b}")
go
a, b := 3, 4
fmt.Printf("%d+%d=%d\n", a, b, a + b)
a, b := 3, 4
fmt.Println(a, "+", b, "=", a+b)

Reverse the characters in a string

Given the string "reverse me", produce the string "em esrever"
ruby
puts "reverse me".reverse
java
String reverse = new StringBuffer("reverse me").reverse().toString();
String reverse = new StringBuilder("reverse me").reverse().toString();
String reverse = StringUtils.reverse("reverse me");
perl
$_ = reverse "reverse me"; print
groovy
reversed = "reverse me".reverse()
scala
val reversed = "reverse me".reverse
python
"reverse me"[::-1]
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());
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) []
erlang
Reversed = lists:reverse("reverse me"),
Reversed = revchars("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
;;
csharp
var str = "reverse me";
Console.WriteLine(new String(str.Reverse().ToArray()));
php
$reversed = strrev("reverse me");
haskell
reverse "reverse me"
clojure
(require '[clojure.contrib.str-utils2 :as str])
(str/reverse "reverse me")
(apply str (reverse "reverse me"))
fantom
"reverse me".reverse
go
package main;
import "utf8";
import "fmt";

func reverse(s string) string {
o := make([]int, utf8.RuneCountInString(s))
i := len(o)
for _, c := range s {
i--
o[i] = c
}
return string(o)
}

func main() {
fmt.Print(reverse("reverse me"));
}
func Reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}

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"
ruby
reversed = text.split.reverse.join(' ')
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!", ' ');
perl
$reversed = join ' ', reverse split / /, $text;
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)
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(" ")
python
' '.join(reversed("This is a end, my only friend!".split()))
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();
fsharp
let reversed = String.Join(" ", Array.rev("This is the end, my only friend!".Split [|' '|]))
erlang
Reversed = string:join(lists:reverse(string:tokens("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)
;;
csharp
var str = "This is a end, my only friend!";
str = String.Join(" ", str.Split().Reverse().ToArray());
Console.WriteLine(str);
php
$reversed_words = implode(" ", array_reverse(explode(" ", "This is the end, my only friend!")));
haskell
unwords (reverse (words "This is the end, my only friend!"))
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!"))))
fantom
"This is a end, my only friend!".split.reverse.join(" ")
go
words := strings.Split("This is the end, my only friend!", " ")
nr := len(words)
reversed := make([]string, nr)
for i, word := range words {
reversed[nr - i - 1] = word
}
s := strings.Join(reversed, " ")
fmt.Println(s)
func reverse(list []string) ([]string) {
if len(list) == 1 {
return list
}

return append(reverse(list[1:]), list[0])
}

func main() {
words := strings.Split("This is the end, my only friend!", " ")
s := strings.Join(reverse(words), " ")
fmt.Println(s)
}

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.
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")
# the same output is achieved with:
puts ("The quick brown fox jumps over the lazy dog. " * 10).gsub(/(.{1,70})(\s+|\Z)/, "> \\1\n")
# however
# "> The quick brown fox jumps over the lazy dog. The quick brown fox jumps".size => 72
# "> over the lazy dog. The quick brown fox jumps over the lazy dog. The".size + "quick".size # first line + first word of second line => 74
# where does 78 come from?
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);
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;
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 }
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(" "))
}
python
import textwrap
print textwrap.fill("The quick brown fox jumps over the lazy dog. " * 10,
72, initial_indent="> ", subsequent_indent="> ")
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);
}
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
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")).
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


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));
}
}
php
$s = str_repeat("The quick brown fox jumps over the lazy dog. ", 10);
$s = wordwrap($s, 76, "WRAP");
$s = explode("WRAP", $s);
foreach ($s as $part) {
$res .= "> " . $part . "\n";
}
echo $res;
echo '> '.wordwrap(str_repeat('The quick brown fox jumps over the lazy dog. ', 10), 70,"\n> ")."\n";
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))
clojure
(doseq [line (re-seq #".{0,70} "
(apply str
(repeat 10 "The quick brown fox jumps over the lazy dog. ")))]
(println ">" line))
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++
}
go
import "fmt"
import "strings"

const WIDTH = 72

func main() {
s := "The quick brown fox jumps over the lazy dog."

words := strings.Split(s, " ")
tmp := words

for i, pos := 0, 0; i < 10; i++ {
for len(words) > 0 {
if pos == 0 {
fmt.Printf("> ")
}

if pos + len(words[0]) > WIDTH {
fmt.Printf("\n")
pos = 0
} else {
fmt.Printf("%s ", words[0])
pos += len(words[0]) + 1
words = words[1:]
}
}
words = tmp
}

fmt.Printf("\n")
}

Remove leading and trailing whitespace from a string

Given the string "  hello    " return the string "hello".
ruby
puts " hello ".strip
" hello ".strip!
java
String s = " hello "; String trimmed = s.trim();
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
groovy
assert "hello" == " hello ".trim()
scala
val s = " hello ".trim
python
assert 'hello' == ' hello '.strip()
cpp
String^ s = " hello "; String^ trimmed = s->Trim();
fsharp
let s = " hello "
let trimmed = s.Trim()
let trimmed = " hello ".Trim()
erlang
Trimmed = string:strip(S),
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
String.trim " hello "
csharp
string str = " hello ";
str = str.Trim();
Console.WriteLine(str);
php
$hello_trimmed = trim(" hello ");
haskell
unwords (words " hello ")
clojure
(use 'clojure.contrib.str-utils2)
(trim " hello ")
(clojure.string/trim " hello ")
(.trim " hello ")
fantom
s := " hello ".trim
go
s := strings.TrimSpace(" hello ")

Make a string uppercase

Transform "Space Monkey" into "SPACE MONKEY"
ruby
uppper = text.upcase
java
String upper = text.toUpperCase();
perl
print uc "Space Monkey"
groovy
println "Space Monkey".toUpperCase()
def lower = 'Space Monkey'
assert lower.toUpperCase() == 'SPACE MONKEY'
scala
println("Space Monkey".toUpperCase)
python
"Space Monkey".upper()
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);
fsharp
printfn "%s" ("Space Monkey".ToUpper())
printfn "%s" (String.uppercase "Space Monkey")
erlang
io:format("~s~n", [string:to_upper("Space Monkey")]).
ocaml
String.uppercase "Space Monkey";;
csharp
string output = "Space Monkey"

System.Console.WriteLine(output.ToUpper())
php
echo strtoupper("Space Monkey");
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"
clojure
(.toUpperCase "Space Monkey")
fantom
s := "Space Monkey".localeUpper
go
strings.ToUpper("Space Monkey")

Make a string lowercase

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

Capitalise the first letter of each word

Transform "man OF stEEL" into "Man Of Steel"
ruby
caps = text.gsub(/\w+/) { $&.capitalize }
caps = text.split.each{|i| i.capitalize!}.join(' ')
text.split.map(&:capitalize) * ' '
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");
perl
$text =~ s/(\w+)/\u\L$1/g;
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")
"man OF stEEL".toLowerCase().tokenize().collect { it.capitalize() }.join(' ')
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 " "
(" " + "man OF stEEL").sliding(2).toList.map( x => x(0) match {
case ' ' => x(1).toUpper
case _ => x(1).toLower
}).mkString
python
from string import capwords
capwords("man OF stEEL")
' '.join(s.capitalize() for s in "man OF stEEL".split())
"man OF stEEL".title()
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();
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"
erlang
Caps = string:join(lists:map(fun(S) -> to_caps(S) end, string:tokens("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")
let capitalize_words str =
let capitalize_word w =
String.capitalize (String.lowercase w) in
let l = Str.split (Str.regexp " ") str in
String.concat " " (List.map (capitalize_word) l)
;;


let () =
print_endline (capitalize_words "man OF stEEL");;
csharp
System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase("man OF stEEL".ToLowerInvariant());
php
echo ucwords(strtolower("man OF stEEL"));
haskell
import Data.Char

capitalizeWords = unwords . map capitalizeWord . words
where capitalizeWord [] = []
capitalizeWord (c:cs) = toUpper c : map toLower cs
clojure
(use 'clojure.contrib.str-utils2)
(join " " (map capitalize (split "man OF stEEL" #" ")))
fantom
"man OF stEEL".split.map { it.localeLower.localeCapitalize }.join(" ")
go
strings.Title(strings.ToLower("man OF stEEL"))

Find the distance between two points

ruby
# the hypotenuse sqrt(x**2+y**2)
distance = Math.hypot(x2-x1,y2-y1)
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);
perl
use Math::Complex;
$a = Math::Complex->make(0, 3);
$b = Math::Complex->make(4, 0);
$distance = abs($a - $b);
my @a=(0, 3);
my @b=(4, 0);
my $distance = sqrt( ($a[0]-$b[0])**2 + ($a[1]-$b[1])**2 );
groovy
distance = distance(x1, y1, x2, y2)
distance = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(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)})
}
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)
cpp
Point p1 = {34, 78}, p2 = {67, -45};
double distance = ::distance(p1, p2);
Console::WriteLine("{0,3:F2}", distance);
fsharp
let distance' = distance (34, 78) (67, -45)
printfn "%3.2f" distance'
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]).
ocaml
type point = { x:float; y:float };;
let distance a b = sqrt((a.x -. b.x)**2. +. (a.y -. b.y)**2.);;
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)));
php
$distance = sqrt( pow(($x2 - $x1), 2) + pow(($y2 - $y1),2) );
class Point2D {
var $x;
var $y;
function __construct($x, $y) {
$this->x = $x;
$this->y = $y;
}
}
$a = new Point2D($x1,$y1);
$b = new Point2D($x2,$y2);
$distance = sqrt( pow(($b->x - $a->x), 2) + pow(($b->y - $a->y),2) );
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...
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])
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)
go
import "fmt"
import "math"

type Point struct {
x, y float64
}

func (p Point) distance(other Point) (float64) {
dx := p.x - other.x
dy := p.y - other.y
return math.Sqrt(dx * dx + dy * dy)
}

func main() {
origin := Point{ 0, 0 }
point := Point{ 1, 1 }

fmt.Println(point.distance(origin))
}

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042
ruby
42.to_s.rjust(8,"0")
"%08d" % 42
java
String formatted = new DecimalFormat("00000000").format(42);
String formatted = String.format("%08d", 42);
perl
sprintf("%08d", 42);
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)
scala
val formatted = String.format("%08d", int2Integer(42))
printf("%08d\n", 42)
println("%08d".format(42))

val num = 42
println(f"$num%08d")
println(f"${42}%08d")
python
"%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;
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)
erlang
Formatted = io_lib:format("~8..0B", [42]),
io:format("~8..0B~n", [42]).
ocaml
Printf.printf "%08d" 42;;
let s = Printf.sprintf "%08d" 42 in
print_string s;;
csharp
string.Format("{0,8:D8}", 42);
php
echo str_pad(42, 8, 0, STR_PAD_LEFT);
printf("%08d", 42);
haskell
import Text.Printf

printf "%08d" 42
clojure
(defn pad
([x] (if (> 8 (.length (str x))) (pad (str 0 x)) (str x)))
)
(defn pad [x]
(format "%08d" x))
(format "%08d" 42)
fantom
formatted := 42.toStr.padl(8, '0')
formatted := 42.toLocale("00000000")
go
fmt.Printf("%08d", 42)

Right Space pad a number

Given the number 1024 right pad it to 6 characters "1024  "
ruby
1024.to_s.ljust(6)
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);
perl
sprintf("%-6d", 1024);
groovy
println 1024.toString().padRight(6)
formatted = sprintf("%-6d", 1024)
scala
val formatted = String.format("%-6d", int2Integer(1024))
printf("%-6d\n", 1024)
println("%-6d".format(1024))
python
"%-6s" % 1024
str(1024).rjust(6)
'{0: <6}'.format(1024)
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;
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)
erlang
Formatted = io_lib:format("~-6B", [1024]),
io:format("~-6B~n", [1024]).
ocaml
Printf.printf "%-6i" 1024;;
csharp
public class NumberRightPadding {
public static void Main() {
string withStringDotFormat = string.Format("{0,-6}", 1024);
string withToStringDotPadRight = 1024.ToString().PadRight(6);
}
}
php
echo str_pad(1024, 6, " ");
printf("%s ", 1024);
haskell
let s = show 1024
p = 6
in s ++ (replicate (p - length s) ' ')
import Text.Printf

main = do
putStrLn $ printf "%-6d" (1024::Int)
clojure
(let [s (str 1024)
l (count s)]
(str s (reduce str (repeat (- 6 l) " "))))
(format "%-6d" 1024)
fantom
formatted := 1024.toStr.padr(6)
go
fmt.Printf("%-6d", 1024)

Format a decimal number

Format the number 7/8 as a decimal with 2 places: 0.88
ruby
(7.0/8.0*100).round/100.0
(7.0/8.0).round(2)
java
String formatted = String.format("%3.2f", 7./8.);
perl
sprintf("%.2f", 7/8);
groovy
def result = 7/8
println result.round(new MathContext(2))
def result = 7/8
printf "%.2g", result
new Double(7/8).round(2)
scala
val formatted = String.format("%3.2f", double2Double(7./8.))
printf("%3.2f\n", 7./8.)
python
"%.2f" % (7 / 8.0)
round(7./8., 2)
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;
fsharp
printfn "%3.2f" (0.7 / 0.8)
let formatted = String.Format("{0,3:F2}", (0.7 / 0.8))
Console.WriteLine(formatted)
erlang
Formatted = io_lib:format("~.2f", [7/8]),
io:format("~.2f~n", [7/8]).
ocaml
Printf.printf "%4.2f" (7. /. 8.);;
let s = Printf.sprintf "%4.2f" (7. /. 8.) in
print_string s;;
csharp
public class FormatDecimal {
public static void Main() {
decimal result = decimal.Round( 7 / 8m, 2);
System.Console.WriteLine(result);
}
}
php
printf("%.2g", 7/8);
echo round(7/8, 2);
haskell
import Text.Printf

printf "%3.2f" (7/8)
main = putStrLn $ Numeric.showFFloat (Just 2) (7/8) ""
clojure
(format "%3.2f" (/ 7.0 8))
(* 0.01 (Math/round (* 100 (float (/ 7 8)))))
fantom
formatted := (7.0/8.0).toLocale("0.00")
go
fmt.Printf("%.2f", 7.0 / 8.0)

Left Space pad a number

Given the number 73 left pad it to 10 characters "        73"
ruby
73.to_s.rjust(10)
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);
perl
sprintf("%10d", 73);
groovy
println 73.toString().padLeft(10)
printf "%10d\n", 73
scala
val formatted = String.format("%10d", int2Integer(73))
printf("%10d\n", 73)
python
"%10s" % 73
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;
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)
erlang
Formatted = io_lib:format("~10B", [73]),
io:format("~10B~n", [73]).
ocaml
Printf.printf "%10d" 73;;
csharp
public class NumberLeftPadding {
public static void Main() {
string withStringDotFormat = string.Format("{0,10}", 73);
string withToStringDotPadLeft = 73.ToString().PadLeft(10);
}
}
php
echo str_pad(73, 10, " ", STR_PAD_LEFT);
printf("%10d", 73);
haskell
import Text.Printf

formatted :: String
formatted = printf "%10d" 73
clojure
(let [s (str 73)
l (count s)]
(str (reduce str (repeat (- 10 l) " ")) s ))
fantom
formatted := 73.toStr.padl(10)
go
fmt.Printf("%10d", 73)

Generate a random integer in a given range

Produce a random integer between 100 and 200 inclusive
ruby
randomInt = rand(200-100+1)+100;
rand(100..200)
java
Random random = new Random();
int randomInt = random.nextInt(200-100+1)+100;
perl
my $range = 100;
my $minimum = 100;

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

print "$random_number\n";
groovy
random = new Random()
randomInt = random.nextInt(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)))
val start = 100
val end = 200
val rnd = new scala.util.Random

println( start + rnd.nextInt( (end - start) + 1 ) )
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)
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();
fsharp
let rnd = new Random()
let rndInt = rnd.Next(100, 201)
erlang
RandomInt = gen_rand_integer(100, 200),
99 + rand:uniform(101).
ocaml
Random.self_init ();;
let a = 100 and b = 200 in
Random.int ( b - a + 1 ) + a;;
csharp
System.Random r = new System.Random();
int random = r.Next(100,201);
php
$r = mt_rand(100, 200);
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
clojure
(+ (rand-int (- 201 100)) 100)
fantom
r := Int.random(100..200)
go
rand.Intn(100) + 100

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.
ruby
srand(12345)
first = (1..5).collect {rand}
srand(12345)
second = (1..5).collect {rand}
puts first == second
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(); }
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";
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
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()
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)
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);
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 ""
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))]).
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);;
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());
}
}

php
mt_srand(9876);
$r1 = array();
foreach(range(1,5) as $i) {
$r1[$i] = mt_rand(1,100);
}
mt_srand(9876);
$r2 = array();
foreach(range(1,5) as $i) {
$r2[$i] = mt_rand(1,100);
}
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])

clojure
(dotimes [_ 2]
(let [r (java.util.Random. 12345)]
(dotimes [_ 5]
(println (.nextInt r 100))))
(println))
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) }
go
rand.Seed(0xdeadbeef)
for i := 0; i < 5; i++ {
fmt.Printf("%v ", rand.Int())
}
fmt.Println()

rand.Seed(0xdeadbeef)
for i := 0; i < 5; i++ {
fmt.Printf("%v ", rand.Int())
}
fmt.Println()

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
ruby
puts "ok" if ("Hello"=~/^[A-Z][a-z]+$/)
java
if ("Hello".matches("[A-Z][a-z]+")) {
System.out.println("ok");
}
perl
print 'ok' if ('Hello' =~ /[A-Z][a-z]+/);
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'
scala
if ("Hello".matches("[A-Z][a-z]+")) println("ok")
python
found = re.match(r'[A-Z][a-z]+', 'Hello')
if found:
print '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;
fsharp
if (Regex.IsMatch("Hello", "[A-Z][a-z]+")) then printfn "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.
ocaml
if Str.string_match (Str.regexp "[A-Z][a-z]+") "Hello" 0
then print_string "ok";;
csharp
if (Regex.IsMatch("Hello", "[A-Z][a-z]+"))
{
Console.WriteLine("ok");
}
php
if(ereg('[A-Za-z]+', 'Hello')) {
echo "ok";
}
if(preg_match('/[A-Za-z]+/', 'Hello')>0) {
echo "ok";
}
haskell
import Text.Regex.Posix
main = if "Hello" =~ "[A-Z][a-z]+" then putStrLn "OK" else return ()
clojure
(if (re-matches #"[A-Z][a-z]+" "Hello")
(println "ok"))
fantom
if (Regex<|[A-Z][a-z]+|>.matches("Hello"))
echo("ok")
go
result, _ := regexp.MatchString("[A-Z][a-z]+", "Hello")
if result {
fmt.Println("ok")
}

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
ruby
puts $1 if "one two three"=~/^one (.*) three$/
java
Pattern pattern = Pattern.compile("one (.*) three");
Matcher matcher = pattern.matcher("one two three");
if (matcher.matches()) {
System.out.println(matcher.group(1));
}
perl
print $1 if "one two three"=~/^one (.*) three$/
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
scala
val m = Pattern.compile("one (.*) three").matcher("one two three")
if (m.matches) println(m.group(1))
python
match = re.match(r'one (.*) three', 'one two three')
if match:
print match.group(1)
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;
fsharp
let regmatch = (Regex.Match("one two three", "one (.*) three"))
if regmatch.Success then (printfn "%s" (regmatch.Groups.[1].Captures.[0].ToString()))
erlang
case re:run("one two three", "one (.*) three", [{capture, [1], list}]) of {match, Res} -> hd(Res) end.
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)
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]);
}
}
php
preg_match('/one (.*) three/', 'one two three', $matches);
echo $matches[1];
ereg('one (.*) three', 'one two three', $regs);
echo $regs[1];
haskell
import Text.Regex
main = case matchRegex (mkRegex "one (.*) three") "one two three" of
Nothing -> return ()
Just (x:_) -> putStrLn x
clojure
(if-let [groups (re-matches #"one (.*) three" "one two three")]
(println (second groups)))
fantom
m := Regex<|one (.*) three|>.matcher("one two three")
if (m.matches)
echo("${m.group(1)}")
go
re, _ := regexp.Compile("one (.*) three")
groups := re.FindStringSubmatch("one two three")
if len(groups) > 0 {
fmt.Println(groups[1])
}

Define an empty list

Assign the variable "list" to a list with no elements
ruby
list = []
list = Array.new
java
List list = Collections.emptyList();
String[] list = {};
perl
@list = ();
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

scala
val list = Nil
val list = List()
val list : List[String] = List()
val list = List.empty
python
list = []
cpp
Generic::List<String^>^ list = gcnew Generic::List<String^>();
std::list<std::string> list;
fsharp
let list = []
let list = List.empty
let list = new Generic.List<string>()
let list = new Generic.LinkedList<string>()
erlang
List = [],
ocaml
let list = [];;
csharp
var list = new List<object>();
php
$list = array();
haskell
let list = []
clojure
(list)
'()
fantom
list := [,]
go
var l []string;

Define a static list

Define the list [One, Two, Three, Four, Five]
ruby
list = ['One', 'Two', 'Three', 'Four', 'Five']
list = %w(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"); }};
perl
@list = qw(One Two Three Four Five);
@list = ('One', 'Two', 'Three', 'Four', 'Five');
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+
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")
python
list = ['One', 'Two', 'Three', 'Four', 'Five']
print list
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";
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))
erlang
List = [one, two, three, four, five],
List = ['One', 'Two', 'Three', 'Four', 'Five'],
ocaml
let list = [ "One"; "Two"; "Three"; "Four"; "Five" ];;
csharp
IList<string> list = new string[]{"One","Two","Three","Four","Five"};
php
$list = array("One", "Two", "Three", "Four", "Five");
$list = array();
$list[] = "One";
$list[] = "Two";
$list[] = "Three";
$list[] = "Four";
$list[] = "Five";
<?php
$list = new SplFixedArray(5);

$list[0] = "One";
$list[1] = "Two";
$list[2] = "Three";
$list[3] = "Four";
$list[4] = "Five";
?>
haskell
let a = ["One", "Two", "Three", "Four", "Five"]
clojure
(def a '[One Two Three Four Five])
(def a (list "One" "Two" "Three" "Four" "Five"))
fantom
list := ["One", "Two", "Three", "Four", "Five"]
go
var l = []string{"One", "Two", "Three", "Four", "Five"}

Join the elements of a list, separated by commas

Given the list [Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
ruby
string = fruit.join(', ')
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, ", ");
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";
}
groovy
string = fruit.join(', ')
string = fruit.toString()[1..-2]
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(", "))
python
print ", ".join(['Apple', 'Banana', 'Carrot'])
cpp
String^ result = String::Join(L", ", fruit->ToArray());
string fruits[] = {"Apple", "Banana", "Carrot"};
string result = boost::algorithm::join(fruits, ", ");
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()
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)]]).
ocaml
let () =
let lst = ["Apple"; "Banana"; "Carrot"] in
let str = String.concat ", " lst in
print_endline str
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()) );
}
}
php
$string = implode(", ", $fruits);
haskell
import Data.List

let join = intercalate ", " ["Apple", "Banana", "Carrot"]
clojure
(apply str (interpose ", " '("Apple" "Banana" "Carrot")))
fantom
["Apple", "Banana", "Carrot"].join(", ")
go
s := strings.Join([]string {"Apple", "Banana", "Carrot"}, ", ")

Fetch an element of a list by index

Given the list [One, Two, Three, Four, Five], fetch the third element ('Three')
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
java
String result = list.get(2);
perl
qw(One Two Three Four Five)[2];
@list = qw(One Two Three Four Five);
$list[2];
groovy
list = ['One', 'Two', 'Three', 'Four', 'Five']
result = list[2] // index starts at 0
scala
val result = list(2)
python
list = ['One', 'Two', 'Three', 'Four', 'Five']
list[2]
cpp
String^ result = list[2];
fsharp
let result = List.nth ["One"; "Two"; "Three"; "Four"; "Five"] 2
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),
ocaml
let third = List.nth [ "One"; "Two"; "Three"; "Four"; "Five" ] 3;;
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
php
$list = array("One", "Two", "Three", "Four", "Five");
$three = $list[2];
haskell
let a = [1..5]
let b = a !! 2
print b
clojure
(nth '[One Two Three Four Five] 2)
fantom
["One", "Two", "Three", "Four", "Five"][2]
["One", "Two", "Three", "Four", "Five"].get(2)
go
fmt.Println(list[2])

Remove an element from a list by index

Given the list [Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
ruby
['Apple', 'Banana', 'Carrot'].shift
fruit.delete_at(0)
java
list.remove(0);
perl
@list = qw(Apple Banana Carrot);
shift @list;
@list = qw(Apple Banana Carrot);
$offset = 0;
splice(@list, $offset, 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)
scala
val (fl, fr) = fruit.splitAt(0) ; fruit = fl ::: fr.tail
fruit = fruit.tail
fruit = fruit.drop(1)
fruits = fruits.remove(fruits.indexOf(_) == 0)
fruits.filterNot(fruits.indexOf(_) == 0)
python
myList = ['Apple', 'Banana', 'Carrot']
print myList
del myList[0]
# or
myList.pop(0) # returns 'Apple'
print myList
Easy trick

a=[Apple, Banana, Carrot]
a=a[1:]

remove first n entry:

a=[n:]

remove last n entry=>

a=[0:-n]
cpp
fruit->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)
erlang
Result = tl(List),
[_|Result] = List,
N = 1, {Left, Right} = lists:split(N - 1, List), Result = Left ++ tl(Right),
Result = drop(1, List),
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"]
csharp
class Solution1516
{
static void Main()
{
List<string> fruit = new List<string>() { "Apple", "Banana", "Carrot" };
fruit.RemoveAt(0);
}
}
php
$list = array("Apple", "Banana", "Carrot");
unset($list[0]);

// Be aware of that $list[0] isn't set. "Banana" is still $list[1]
$list = array("Apple", "Banana", "Carrot");
array_shift($list);

// Be aware of that $list[0] is set to "Banana"
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
clojure
(let [fruit ["Apple" "Banana" "Carrot"]
index 0]
(concat
(take index fruit)
(drop (+ index 1) fruit)))
(let [v ["Apple" "Banana" "Carrot"]
index 0]
(into (subvec v 0 n) (subvec v (inc n))))
fantom
list := ["Apple", "Banana", "Carrot"]
list.removeAt(0)
go
offset := 0
list = append(list[:offset], list[offset+1:]...)

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
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}
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);
perl
foreach(@list) {
$histogram{$_}++;
}
$histogram{$_}++ for @list;
groovy
histogram = [:]
list.each { item ->
if (!histogram.containsKey(item)) histogram[item] = 0
histogram[item]++
}
histogram = [:]
list.each { histogram[it] = (histogram[it] ?: 0) + 1 }
def histogram = [:].withDefault{ 0 }
list.each { histogram[it] += 1 }
histogram
list.inject([:].withDefault{ 0 }) { map, nr -> map[nr] += 1; map}
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)
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)
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;
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
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])).
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
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));
php
$list = array("a","b","a","c","b","b");
$map = array_count_values($list);
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
import qualified Data.Map as Map

histogram :: [String] -> Map.Map String Int
histogram ss = foldl addElem Map.empty ss
where addElem m e = Map.insertWith (+) e 1 m

output :: Map.Map String Int
output = histogram ["a","b","a","c","b","b"]
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])
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)
go
var maplist = make(map[string]int)
var list = [6]string{"a","b","a","c","b","b"}
for _, v := range list {
maplist[v] += 1
}
fmt.Println(maplist)

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.
ruby
if (name=='Bob')
puts "Hello, Bob!"
end
puts "Hello, Bob!" if name=='Bob'
java
if (name.equals("Bob")) {
System.out.println("Hello, Bob!");
}
perl
if ($name eq "Bob") {
print "Hello, Bob!"
}
print "Hello, Bob!" if $name eq "Bob";
groovy
if (name=='Bob')
println "Hello, 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)
python
if name == 'Bob':
print 'Hello, Bob!'
cpp
if (name == "Bob") Console::WriteLine("Hello, {0}!", name);
if (name == "Bob") std::cout << "Hello, " << name << "!" << std::endl;
fsharp
if name = "Bob" then printfn "Hello, %s!" name
name = "Bob" && begin printfn "Hello, %s!" name ; true end
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).
ocaml
if name = "Bob"
then print_string "Hello, Bob!"
csharp
if (name == "Bob") Console.WriteLine("Hello, {0}!", name);
php
if($name == "Bob") {
echo "Hello, Bob!";
}
haskell
name = "Bob"
main = if name == "Bob" then putStrLn "Hello, Bob!" else return ()
clojure
(def person "Bob")
(if (= person "Bob")
(println "Hello, Bob!"))
fantom
if (name=="Bob") echo("Hello, Bob!")
go
if name == "Bob" {
fmt.Println("Hello", name)
}

Parse a date and time from a string

Given the string "2008-05-06 13:29", parse it as a date representing 6th March, 2008 1:29:00pm in the local time zone.
ruby
# With timezone info
puts Time.parse('2008-05-06 13:29')
java
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = df.parse("2008-05-06 13:29");
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");
DateTime dt = fmt.parseDateTime("2008-05-06 13:29");
perl
#! /usr/bin/perl
# -*- Mode: CPerl -*-

use strict;
use POSIX;

# Given the string "2008-05-06 13:29", parse it as a date
# representing 6th March, 2008 1:29:00pm in the local time zone.

my $ds = "2008-05-06 13:29";

my $y;
my $m;
my $d;
my $hr;
my $mn;

print "Original: ",$ds,"\n";

if ( $ds =~ /(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})/ ){
$y = $1 - 1900;
$m = $2;
$d = $3;
$hr = $4;
$mn = $5;

printf "Nominal: %s\n",
strftime("%e %B, %Y %l:%M:%S%P",0, $mn , $hr, $d, $m,$y);

my $eth = "";
if ( $d == 1 ){
$eth = "st";
} elsif ( $d == 2 ){
$eth = "nd";
} elsif ( $d == 3 ){
$eth = "rd";
} else {
$eth = "th";
}

printf "As required: %d%s %s\n",$d,$eth,
strftime("%B, %Y %l:%M:%S%P",0, $mn , $hr, $d, $m,$y);
}

#eos
# Shurely you mean 6th MAY? If not, oh well
use Time::Piece;

my $dt_str = '2008-05-06 13:29';
my $tp = Time::Piece->strptime( $dt_str, '%Y-%m-%d %H:%M');
print $tp,"\n";
groovy
def date = new SimpleDateFormat("yyy-MM-dd HH:mm").parse("2008-05-06 13:29")
def date = Date.parse("yyy-MM-dd HH:mm", "2008-05-06 13:29")
scala
val date = new SimpleDateFormat("yyy-MM-dd HH:mm").parse("2008-05-06 13:29")
import scala.util.parsing.combinator.RegexParsers
import java.util.{GregorianCalendar, Date}

class DateParser extends RegexParsers {

val fd = """\d{4}""".r
val td = """\d{2}""".r

def parseDate: Parser[Date] =
year ~ ("-" ~> other) ~ ("-" ~> other) ~ other ~ (":" ~> other) ^^ {
case y ~ mo ~ d ~ h ~ mi => (new GregorianCalendar(y, mo - 1, d, h, mi)).getTime
}

def year: Parser[Int] = fd ^^ { _.toInt }
def other: Parser[Int] = td ^^ { _.toInt }

}
python
import time
time.strptime("2008-05-06 13:29", "%Y-%m-%d %H:%M")
cpp
DateTimeOffset^ dateTime = DateTimeOffset::Parse("2008-05-06 13:29");

// Use format specifiers to appropriately format string
// 1. Default culture
Console::WriteLine("{0}", dateTime->ToString("d MMMM, yyyy h:mm:sstt"));

// 2. Nominated culture
Console::WriteLine("{0}", dateTime->ToString("d MMMM, yyyy h:mm:sstt"), Globalization::CultureInfo::CreateSpecificCulture("en-us"));
DateTimeOffset^ dateTime = DateTimeOffset::Parse("2008-05-06 13:29");

// Customize date/time string
Text::StringBuilder^ dsb = gcnew Text::StringBuilder(40);
dsb->Append(dateTime->ToString("%d"))->Append("th ")->Append(dateTime->ToString("MMMM, yyyy h:mm:ss"))->Append(dateTime->ToString("tt")->ToLower());

Console::WriteLine("{0}", dsb);
fsharp
let dateTime = DateTimeOffset.Parse("2008-05-06 13:29")

// Use format specifiers to appropriately format string
// 1. Default culture
printfn "%s" (dateTime.ToString("d MMMM, yyyy h:mm:sstt"))

// 2. Nominated culture
Console.WriteLine("{0}", dateTime.ToString("d MMMM, yyyy h:mm:sstt"), Globalization.CultureInfo.CreateSpecificCulture("en-us"))
let dateTime = DateTimeOffset.Parse("2008-05-06 13:29")

// Customize date/time string
let dsb = ((new StringBuilder(40)).Append(dateTime.ToString("%d")).Append("th ").Append(dateTime.ToString("MMMM, yyyy h:mm:ss")).Append(dateTime.ToString("tt").ToLower()))

printfn "%s" (dsb.ToString())
erlang
% AFAIK, no datetime-parsing library exists; 'parse_to_datetime' is a simplistic, problem-specific hack
LocalDateTime = erlang:universaltime_to_localtime(parse_to_datetime("2008-05-06 13:29:34")),
ocaml
let s = "2008-05-06 13:29" in
let r = Str.regexp "\\([0-9][0-9][0-9][0-9]\\)-\\([0-9][0-9]\\)-\\([0-9][0-9]\\) \\([0-9][0-9]\\):\\([0-9][0-9]\\)" in
assert (Str.string_match r s 0);
Unix.mktime { Unix.tm_sec = 0;
tm_min = int_of_string (Str.matched_group 5 s);
tm_hour = int_of_string (Str.matched_group 4 s);
tm_mday = int_of_string (Str.matched_group 3 s);
tm_mon = int_of_string (Str.matched_group 2 s) - 1;
tm_year = int_of_string (Str.matched_group 1 s) - 1900;
tm_wday = -1;
tm_yday = -1;
tm_isdst = true; (** Daylight time savings in effect *)
}
csharp
DateTime parsedDate = DateTime.Parse("2008-05-06 13:29");
// Ideally, you would catch the potential FormatException or use DateTime.TryParse in production code.
php
echo date("jS F, Y g:i:sa", strtotime("2008-05-06 13:29")); // small version
haskell
import Data.Time

main = print (parseTimeOrError True defaultTimeLocale "%Y-%m-%d %H:%M" "2008-05-06 13:29" :: UTCTime)
clojure
(.. (SimpleDateFormat. "yyyy-MM-dd HH:mm")
(parse "2008-05-06 13:29"))
fantom
dt := DateTime.fromLocale("2008-05-06 13:29", "YYYY-MM-DD hh:mm")
go
t, err := time.Parse("2006-01-02 15:04", "2008-05-06 13:29")
if err == nil {
fmt.Println(t)
}

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.
ruby
puts DateTime.now
java
import java.util.Date;

public class SolutionXX {
public static void main(String[] args) {
Date now = new Date();
System.out.println(now.toString());
}
}
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";
groovy
println new Date()
scala
println(new java.util.Date)
python
from datetime import datetime
print datetime.utcnow()
cpp
QDate now = QDate::currentData();
qDebug() << now.toString();
time_t date = time(0);
cout << ctime(&date);
fsharp
printfn "%A" System.DateTime.Now
erlang
io:format("~p~n", [calendar:local_time()])
ocaml
Unix.localtime (Unix.gettimeofday ())
csharp
// Creating a variable first:
DateTime now = DateTime.Now;
Console.WriteLine(now);

// Without creating a variable:
Console.WriteLine(DateTime.Now);
php
echo date('r') . "\n";
$d = new DateTime();
echo $d->format('r') . "\n";
haskell
import System.Time

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

main = do zt <- getZonedTime
print zt
import System.Time

main = print =<< getClockTime
clojure
(import 'java.util.Date)

(println (str (Date.)))
(prn (java.util.Date.))
fantom
echo(DateTime.now)
go
fmt.Println(time.Now())
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.
ruby
class Greeter
def initialize(whom) @whom = whom end
def greet() puts "Hello, #{@whom}!" end
end

(Greeter.new("world")).greet()
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();
}
}
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();
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()
scala
class Greeter(whom : String) { def greet() = { printf("Hello %s\n", whom) } }

(new Greeter("world!")).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()
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);
}
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()
erlang
Greeter = make_greeter("world!"),
Greeter(greet).
ocaml
class greeter message =
object
method greet = print_endline message
end

let o = new greeter "Hello" in
o#greet
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();
}
}
php
class Greeter {
private $whom;
public function __construct($whom) {
$this->whom = $whom;
}
public function greet() {
echo "Hello $this->whom.";
}
}
$g = new Greeter("Giacomo Girolamo");
$g->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")
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"))
fantom
class Greeter
{
private Str whom
new make(Str whom) { this.whom = whom }
Void greet() { echo("Hello, $whom") }
}

Greeter("world").greet
go
type Greeter struct {
whom string
}

func (g Greeter) greet() {
fmt.Printf("Hello %s\n", g.whom)
}

func main() {
Greeter{"world"}.greet()
}