Solved Problems
Output a string to the console
Write the string
"Hello World!" to STDOUT
csharp
System.Console.WriteLine("Hello World!")
erlang
io:format("Hello, World!~n").
cpp
std::cout << "Hello World" << std::endl;
std::printf("Hello World\n");
Console::WriteLine(L"Hello World");
fsharp
printfn "Hello World!"
groovy
println "Hello World!"
Define a string containing special characters
Define the literal string
"\#{'}${"}/"
csharp
string verbatim = @"\#{'}${""""}/";
string cStyle = "\\#{'}${\"\"}/";
string cStyle = "\\#{'}${\"\"}/";
erlang
Special = "\\#{'}\${\"}/",
cpp
std::string special = "\\#{'}${\"}/";
String^ special = L"\\#{'}${\"}/";
fsharp
let special = "\#{'}${\"}/"
groovy
special = "\\#{'}\${\"}/"
special = '\\#{\'}${"}/'
special = /\#{'}${'$'}{"}\//
Define a multiline string
Define the string:
"This
Is
A
Multiline
String"
csharp
string output = "This\nIs\nA\nMultiline\nString";
string output = @"This
Is
A
Multiline
String";
Is
A
Multiline
String";
erlang
Text = "This\nIs\nA\nMultiline\nString",
cpp
std::string text =
"This\n"
"Is\n"
"A\n"
"Multiline\n"
"String";
"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"
Is
A
Multiline
String"
groovy
def text =
"""This
Is
A
Multiline
String"""
"""This
Is
A
Multiline
String"""
def text = "This\nIs\nA\nMultiline\nString"
Define a string containing variables and expressions
Given variables a=3 and b=4 output
"3+4=7"
csharp
int a = 3;
int b = 4;
Console.WriteLine("{0}+{1}={2}", a,b,a+b);
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)]).
io:format("~B+~B=~B~n", [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
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
Reverse the characters in a string
Given the string
"reverse me", produce the string "em esrever"
csharp
var str = "reverse me";
Console.WriteLine(new String(str.Reverse().ToArray()));
Console.WriteLine(new String(str.Reverse().ToArray()));
erlang
Reversed = lists:reverse("reverse me"),
Reversed = revchars("reverse me"),
cpp
String^ s = "reverse me";
array<Char>^ sa = s->ToCharArray();
Array::Reverse(sa);
String^ sr = gcnew String(sa);
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::reverse(s.begin(), s.end());
std::string s = "reverse me";
std::string sr(s.rbegin(), s.rend());
std::string sr(s.rbegin(), s.rend());
std::string s = "reverse me";
std::swap_ranges(s.begin(), (s.begin() + s.size() / 2), s.rbegin());
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) []
//reverse the word
let reversedword =
word.ToCharArray()
|> Array.fold(fun acc x -> x::acc) []
groovy
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"
csharp
var str = "This is a end, my only friend!";
str = String.Join(" ", str.Split().Reverse().ToArray());
Console.WriteLine(str);
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!", " ")), " "),
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);
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();
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 [|' '|]))
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!")
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)
Text wrapping
Wrap the string
> 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.
"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.
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));
}
}
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")).
lists:foreach(fun (Line) -> io:format("~s~n", [string:concat(Prefix, Line)]) end, string:tokens(TextWrap, "\n")).
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);
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);
}
{
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 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
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, '> ')
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, '> ')
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 }
input = 'The quick brown fox jumps over the lazy dog. '
wrap(input * 10, 72 - prefix.size()).eachLine{ println prefix + it }
Remove leading and trailing whitespace from a string
Given the string
" hello " return the string "hello".
csharp
string str = " hello ";
str = str.Trim();
Console.WriteLine(str);
str = str.Trim();
Console.WriteLine(str);
erlang
Trimmed = string:strip(S),
cpp
String^ s = " hello "; String^ trimmed = s->Trim();
fsharp
let s = " hello "
let trimmed = s.Trim()
let trimmed = s.Trim()
let trimmed = " hello ".Trim()
groovy
assert "hello" == " hello ".trim()
Make a string uppercase
Transform
"Space Monkey" into "SPACE MONKEY"
csharp
string output = "Space Monkey"
System.Console.WriteLine(output.ToUpper())
System.Console.WriteLine(output.ToUpper())
erlang
io:format("~s~n", [string:to_upper("Space Monkey")]).
cpp
String(L"Space Monkey").ToUpper();
std::string s = "Space Monkey";
std::transform(s.begin(), s.end(), s.begin(), std::toupper);
std::transform(s.begin(), s.end(), s.begin(), std::toupper);
std::string s = "Space Monkey";
boost::to_upper(s);
boost::to_upper(s);
fsharp
printfn "%s" ("Space Monkey".ToUpper())
printfn "%s" (String.uppercase "Space Monkey")
groovy
println "Space Monkey".toUpperCase()
Make a string lowercase
Transform
"Caps ARE overRated" into "caps are overrated"
csharp
string str = "Caps ARE overRated";
str = str.ToLower() ;
Console.WriteLine(str);
str = str.ToLower() ;
Console.WriteLine(str);
erlang
io:format("~s~n", [string:to_lower("Caps ARE overRated")]).
cpp
std::string s = "Caps ARE overRated";
std::string sl(boost::to_lower_copy(s));
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")
groovy
println "Caps ARE overRated".toLowerCase()
Capitalise the first letter of each word
Transform
"man OF stEEL" into "Man Of Steel"
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", " ")), " "),
cpp
std::string words = "mAn OF stEEL";
std::transform(words.begin(), words.end(), words.begin(), ToCaps<>());
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]);
}
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();
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))
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 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"
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 -> capitalize(w) }
caps = "man OF stEEL".replaceAll(/\w+/) { w -> StringUtils.capitalize(w.toLowerCase()) }
caps = WordUtils.capitalizeFully("man OF stEEL")
Find the distance between two points
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)));
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]).
io:format("~.2f~n", [Distance]).
Distance = distance(point:new(34, 78), point:new(67, -45)),
io:format("~.2f~n", [Distance]).
io:format("~.2f~n", [Distance]).
cpp
Point p1 = {34, 78}, p2 = {67, -45};
double distance = ::distance(p1, p2);
Console::WriteLine("{0,3:F2}", distance);
double distance = ::distance(p1, p2);
Console::WriteLine("{0,3:F2}", distance);
fsharp
let distance' = distance (34, 78) (67, -45)
printfn "%3.2f" distance'
printfn "%3.2f" distance'
groovy
distance = distance(x1, y1, x2, y2)
distance = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1))
Zero pad a number
Given the number 42, pad it to 8 characters like 00000042
csharp
string.Format("{0,8:D8}", 42);
erlang
Formatted = io_lib:format("~8..0B", [42]),
io:format("~8..0B~n", [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;
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
printfn "%s" formatted
let buffer = new StringBuilder()
Printf.bprintf buffer "%08d" 42
printfn "%s" (buffer.ToString())
Printf.bprintf buffer "%08d" 42
printfn "%s" (buffer.ToString())
let formatted = String.Format("{0,8:D8}", 42)
Console.WriteLine(formatted)
Console.WriteLine(formatted)
let formatted = Convert.ToString(42).PadLeft(8, '0')
Console.WriteLine(formatted)
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)
printf "%08d\n", 42
// to a string
formatted = sprintf("%08d", 42)
formatted = String.format("%08d", 42)
Right Space pad a number
Given the number 1024 right pad it to 6 characters
"1024 "
csharp
public class NumberRightPadding {
public static void Main() {
string withStringDotFormat = string.Format("{0,-6}", 1024);
string withToStringDotPadRight = 1024.ToString().PadRight(6);
}
}
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]).
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;
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)
Console.WriteLine(formatted)
let formatted = Convert.ToString(1024).PadRight(6)
Console.WriteLine(formatted)
Console.WriteLine(formatted)
groovy
println 1024.toString().padRight(6)
formatted = sprintf("%-6d", 1024)
Format a decimal number
Format the number 7/8 as a decimal with 2 places: 0.88
csharp
public class FormatDecimal {
public static void Main() {
decimal result = decimal.Round( 7 / 8m, 2);
System.Console.WriteLine(result);
}
}
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]).
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;
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)
Console.WriteLine(formatted)
groovy
def result = 7/8
println result.round(new MathContext(2))
println result.round(new MathContext(2))
def result = 7/8
printf "%.2g", result
printf "%.2g", result
new Double(7/8).round(2)
Left Space pad a number
Given the number 73 left pad it to 10 characters
" 73"
csharp
public class NumberLeftPadding {
public static void Main() {
string withStringDotFormat = string.Format("{0,10}", 73);
string withToStringDotPadLeft = 73.ToString().PadLeft(10);
}
}
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]).
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;
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
printfn "%s" formatted
let formatted = String.Format("{0,10:D}", 73)
Console.WriteLine(formatted)
Console.WriteLine(formatted)
let formatted = Convert.ToString(73).PadLeft(10)
Console.WriteLine(formatted)
Console.WriteLine(formatted)
groovy
println 73.toString().padLeft(10)
printf "%10d\n", 73
Generate a random integer in a given range
Produce a random integer between 100 and 200 inclusive
csharp
System.Random r = new System.Random();
int random = r.Next(100,201);
int random = r.Next(100,201);
erlang
RandomInt = gen_rand_integer(100, 200),
cpp
Random^ rnd = gcnew Random;
int rndInt = rnd->Next(100, 201);
int rndInt = rnd->Next(100, 201);
std::srand(std::time(NULL));
unsigned lb = 100, ub = 200;
unsigned rnd = lb + (rand() % ((ub - lb) + 1));
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();
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)
let rndInt = rnd.Next(100, 201)
groovy
random = new Random()
randomInt = random.nextInt(200-100+1)+100
randomInt = random.nextInt(200-100+1)+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.
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());
}
}
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))]).
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))]).
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();
}
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);
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 ""
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
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
Check if a string matches a regular expression
Display
"ok" if "Hello" matches /[A-Z][a-z]+/
csharp
if (Regex.IsMatch("Hello", "[A-Z][a-z]+"))
{
Console.WriteLine("ok");
}
{
Console.WriteLine("ok");
}
erlang
String = "Hello", Regexp = "[A-Z][a-z]+",
is_match(String, Regexp) andalso (begin io:format("ok~n"), true end).
is_match(String, Regexp) andalso (begin io:format("ok~n"), true end).
case re:run("Hello", "[A-Z][a-z]+") of {match, _} -> ok end.
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");
if (rx->IsMatch("Hello")) Console::WriteLine("ok");
cmatch what;
if (regex_match("Hello", what, regex("[A-Z][a-z]+")))
cout << "ok" << endl;
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"
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'
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'
def regex = ~/[A-Z][a-z]+/
if ("Hello".matches(regex)) println 'ok'
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/
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]);
}
}
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.
cpp
Match^ match = Regex::Match("one two three", "one (.*) three");
if (match->Success) Console::WriteLine("{0}", match->Groups[1]->Captures[0]);
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;
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()))
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]
if (matcher) println matcher[0][1]
match = "one two three".find("one (.*) three") { it[1] }
if (match) println match
if (match) println match
Check if a string contains a match to a regular expression
Display
"ok" if "abc 123 @#$" matches /\d+/
csharp
if(System.Text.RegularExpressions.Regex.IsMatch("abc 123 @#$",@"\d+")){
Console.WriteLine("ok");
}
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).
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.
cpp
if (Regex::IsMatch("abc 123 @#$", "\\d+")) Console::WriteLine("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'
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+)/
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;});
}
}
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].
R = "\\((\\w+?)\\):(\\d+)",
{match, M} = re:run(S,R, [global, {capture, all_but_first, list}]),
[ A++N || [A, N] <- M].
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();
}
while (match->Success)
{
list->Add(match->Groups[1]->Captures[0]->ToString() + match->Groups[2]->Captures[0]->ToString());
match = match->NextMatch();
}
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
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
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]
}
text.eachMatch(/\((\w+)\):(\d+)/){
list << it[1] + it[2]
}
list = []
text.eachMatch(/\((\w+)\):(\d+)/){ m, name, number ->
list << "$name$number"
}
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] }
Replace all regex matches in a string with a static string
Transform
"She sells sea shells" into "She X X shells" by replacing /se\w+/ with "X"
csharp
using System.Text.RegularExpressions;
class SolutionXX
{
static void Main()
{
string text = "She sells sea shells";
string result = Regex.Replace(text, @"se\w+", "X");
}
}
class SolutionXX
{
static void Main()
{
string text = "She sells sea shells";
string result = Regex.Replace(text, @"se\w+", "X");
}
}
erlang
% Erlang uses 'egrep'-compatible regular expressions, so shortcuts like '\w' not supported
{ok, Replaced, _} = regexp:gsub("She sells sea shells", "se[A-Za-z0-9_]+", "X"),
{ok, Replaced, _} = regexp:gsub("She sells sea shells", "se[A-Za-z0-9_]+", "X"),
re:replace("She sells sea shells", "se\\w+", "X", [global, {return, list}]).
cpp
String^ Replaced = (gcnew Regex("se\\w+"))->Replace("She sells sea shells", "X");
String^ Replaced = Regex::Replace("She sells sea shells", "se\\w+", "X");
fsharp
let replaced = ((new Regex("se\\w+")).Replace("She sells sea shells", "X"))
printfn "%s" replaced
printfn "%s" replaced
groovy
replaced = text.replaceAll(/se\w+/,"X")
Define an empty list
Assign the variable
"list" to a list with no elements
csharp
var list = new List<object>();
erlang
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>()
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
list = new LinkedList() // java style
LinkedList list = [] // statically typed
// using 'as' operator
list = [] as java.util.concurrent.CopyOnWriteArrayList
Define a static list
Define the list
[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'],
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^>((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");
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(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.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";
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")
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))
[|"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+
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+
Join the elements of a list, separated by commas
Given the list
[Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
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()) );
}
}
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)]]).
cpp
String^ result = String::Join(L", ", fruit->ToArray());
string fruits[] = {"Apple", "Banana", "Carrot"};
string result = boost::algorithm::join(fruits, ", ");
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()
groovy
string = fruit.join(', ')
string = fruit.toString()[1..-2]
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(
join(
join(
join(
join(
[Apple, Banana, Carrot]) = "Apple, Banana, and Carrot"
join(
[One, Two]) = "One and Two"
join(
[Lonely]) = "Lonely"
join(
[]) = ""
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>()) );
}
}
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).
% ------
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)].
%% 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)].
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);
}
}
{
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);
}
}
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)
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]
}
}
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() == ""
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() == ""
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]]
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 });
}
}
}
}
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),
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]].
cpp
Specialized::StringCollection^ combinations = gcnew Specialized::StringCollection;
for each(int number in numbers)
for each(String^ letter in letters)
combinations->Add(makeCombo(letter, number));
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;
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;
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
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()
numbers = [4, 5]
combos = [letters, numbers].combinations()
From a List Produce a List of Duplicate Entries
Taking a list:
Write the code to produce a list of duplicates in the list:
["andrew", "bob", "chris", "bob"]
Write the code to produce a list of duplicates in the list:
["bob"]
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);
}
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(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).
([X | Xs], F) -> case lists:member(X, Xs) of
true -> [X | F(Xs, F)];
_ -> F(Xs, F)
end;
([], _) -> []
end,
Result = Fun(List, Fun).
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;
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;
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;
fsharp
["andrew"; "bob"; "chris"; "bob"]
|> Seq.countBy id
|> Seq.filter (fun (k,n) -> n > 1)
|> Seq.map fst
|> Seq.toList
|> 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"]
def output = input.findAll{input.count(it)>1}.unique()
assert output == ["bob"]
Fetch an element of a list by index
Given the list
[One, Two, Three, Four, Five], fetch the third element ('Three')
csharp
string[] items = new string[] { "One", "Two", "Three", "Four", "Five" };
List<string> list = new List<string>(items);
string third = list[2]; // "Three"
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
// 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),
cpp
String^ result = list[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
result = list[2] // index starts at 0
Fetch the last element of a list
Given the list
[Red, Green, Blue], access the last element ('Blue')
csharp
string[] items = new string[] { "Red", "Green", "Blue" };
List<string> list = new List<string>(items);
string last = list[list.Count - 1]; // "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"
// 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),
cpp
String^ result = list[list->Count - 1];
string last_elem = lst.back();
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 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]
result = list[-1]
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?
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']
// 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)),
Common = sets:to_list(sets:intersection(Beans, 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);
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);
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 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
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)) ;;
// 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']
colors = ['black', 'red', 'blue', 'green']
common = beans.intersect(colors)
assert common == ['black', 'red']
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.
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();
}
}
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]).
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);
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"));
input += 18, 16, 17, 18, 16, 19, 14, 17, 19, 18;
input.sort();
unique_copy(input.begin(), input.end(), ostream_iterator<int>(cout, "\n"));
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()
println ages.unique()
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
unique = ages as Set
println unique
unique = ages as Set
println unique
Remove an element from a list by index
Given the list
[Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
csharp
class Solution1516
{
static void Main()
{
List<string> fruit = new List<string>() { "Apple", "Banana", "Carrot" };
fruit.RemoveAt(0);
}
}
{
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),
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 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)
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
newlist = list.tail() // for 'Apple' at start
newlist = list - 'Apple' // for 'Apple' anywhere
// mutate original list
list.remove(0)
list.remove(0)
Remove the last element of a list
csharp
List<string> fruits = new List() { "apple", "banana", "cherry" };
fruits.RemoveAt(fruits.Length - 1);
fruits.RemoveAt(fruits.Length - 1);
erlang
Result = init(List),
Result = take(length(List) - 1, List),
Result = lists:reverse(tl(lists:reverse(List))),
cpp
fruit->RemoveAt(fruit->Count - 1);
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))
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)
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)
// to produce a new list
newlist = list[0,1]
// to modify original list
list.remove(2)
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"]
csharp
var lst = new LinkedList<String>(new String[] {"apple", "orange", "grapes", "banana"});
lst.AddLast(lst.First());
lst.DeleteFirst();
lst.AddLast(lst.First());
lst.DeleteFirst();
erlang
N = 1, {Left, Right} = lists:split(N, List), Result = Right ++ Left,
N = 1, Result = rotate(N, List),
cpp
fruit->Add(fruit[0]); fruit->RemoveAt(0);
rotate(fruit.begin(), fruit.begin()+1, fruit.end());
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)
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.tail() + first
items = items[1..-1] + items[0]
items = items + items.remove(0)
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.
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)));
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),
Result = lists:zip3(First, Last, 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);
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));
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));
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]
last = ['Willis', 'Jones', 'Lee']
years = [1955, 1946, 1940]
actors = [first, last, years].transpose()
assert actors.size() == 3
assert actors[1] == ['Tommy Lee', 'Jones', 1946]
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'.
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();
}
}
}
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]),
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]),
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).
52 = length(Deck2),
true = lists:member({h, 'A'}, Deck2).
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");
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;
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;
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")
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 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"
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
suites = ['H', 'D', 'C', 'S']
deck = [faces, suites].combinations()
assert deck.size() == 52
assert ['A', 'H'] in deck
Perform an operation on every item of a list
Perform an operation on every item of a list, e.g.
for the list
the list of sizes of the strings, e.g.
for the list
["ox", "cat", "deer", "whale"] calculate
the list of sizes of the strings, e.g.
[2, 3, 4, 5]
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 );
}
}
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).
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;
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(); });
list<size_t> word_sizes;
transform(begin(words),
end(words),
back_inserter(word_sizes),
[](const string& s) { return s.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]
assert animals*.size() == [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.
split the list into numbers and 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) );
}
}
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.
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)
{Numbers, NonNumbers} = lists:partition(fun(E) -> is_number(E) end, List)
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;
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'
}
#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'
}
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
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]
things = ["hello", 25, 3.14, now]
(numbers, others) = things.split{ it instanceof Number }
assert numbers == [25, 3.14]
assert others == ["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
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()
)
);
}
}
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));
.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),
Histogram = histogram(List),
% Functional (1) Solution
Histogram = histogram(List),
Histogram = histogram(List),
lists:foldl(fun(Elem, OldDict) ->
dict:update_counter(Elem, 1, OldDict)
end,
dict:new(),
[a,b,a,c,b,b])).
dict:update_counter(Elem, 1, OldDict)
end,
dict:new(),
[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;
? 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;
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 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
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]++
}
list.each { item ->
if (!histogram.containsKey(item)) histogram[item] = 0
histogram[item]++
}
histogram = [:]
list.each { histogram[it] = (histogram[it] ?: 0) + 1 }
list.each { histogram[it] = (histogram[it] ?: 0) + 1 }
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
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
}
}
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),
CatList = categorise(List),
% Functional (1) Solution
CatList = categorise(List),
CatList = categorise(List),
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);
}
{
key = entry->Length;
if (!hash->ContainsKey(key)) hash[key] = gcnew ArrayList;
safe_cast<ArrayList^>(hash[key])->Add(entry);
}
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
["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() }
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.
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).
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
groovy
if (name=='Bob')
println "Hello, Bob!"
println "Hello, Bob!"
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"
csharp
int age = 41;
if (age > 42)
System.Console.WriteLine("You are old");
else
System.Console.WriteLine("You are young");
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]).
cpp
if (age > 42) Console::WriteLine("You are old");
else Console::WriteLine("You are young");
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"));
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
printfn "You are %s" message
groovy
if (age > 42)
println "You are old"
else
println "You are young"
println "You are old"
else
println "You are young"
println "You are " + (age > 42 ? "old" : "young")
Perform different actions depending on several boolean conditions (IF .. THEN .. ELSIF .. ELSE)
csharp
if (age > 84) Console.WriteLine("You are really ancient");
else if (age > 30) Console.WriteLine("You are middle-aged");
else Console.WriteLine("You are young");
else if (age > 30) Console.WriteLine("You are middle-aged");
else Console.WriteLine("You are young");
Console.WriteLine("You are {0}", ((age > 84) ? "really ancient" : (age > 30) ? "middle-aged" : "young"));
erlang
if
Age > 84 -> io:format("You are really ancient~n");
Age > 30 -> io:format("You are middle-aged~n");
true -> io:format("You are young~n")
end.
Age > 84 -> io:format("You are really ancient~n");
Age > 30 -> io:format("You are middle-aged~n");
true -> io:format("You are young~n")
end.
case Age of
_ when Age > 84 -> io:format("You are really ancient~n");
_ when Age > 30 -> io:format("You are middle-aged~n");
true -> io:format("You are young~n")
end.
_ when Age > 84 -> io:format("You are really ancient~n");
_ when Age > 30 -> io:format("You are middle-aged~n");
true -> io:format("You are young~n")
end.
cpp
if (age > 84) Console::WriteLine("You are really ancient");
else if (age > 30) Console::WriteLine("You are middle-aged");
else Console::WriteLine("You are young");
else if (age > 30) Console::WriteLine("You are middle-aged");
else Console::WriteLine("You are young");
Console::WriteLine("You are {0}", (age > 84 ? "really ancient" : age > 30 ? "middle-aged" : "young"));
std::cout << "You are " << (age > 84 ? "really ancient" : age > 30 ? "middle-aged" : "young") << std::endl;
fsharp
if age > 84 then printfn "You are really ancient"
elif age > 30 then printfn "You are middle-aged"
else printfn "You are young"
elif age > 30 then printfn "You are middle-aged"
else printfn "You are young"
let message = match age with
| _ when age > 84 -> "really ancient"
| _ when age > 30 -> "middle-aged"
| _ -> "young"
printfn "You are %s" message
| _ when age > 84 -> "really ancient"
| _ when age > 30 -> "middle-aged"
| _ -> "young"
printfn "You are %s" message
groovy
if (age > 84)
println "You are really ancient"
else if (age > 30)
println "You are middle-aged"
else
println "You are young"
println "You are really ancient"
else if (age > 30)
println "You are middle-aged"
else
println "You are 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
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";
}
}
{
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;
}
}
{
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])
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])
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();
}
#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();
}
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))
| 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)}"
}
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)}"
}
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.
csharp
int x = 1;
while (x < 150)
{
x *= 2;
Console.Write("{0},", x);
}
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).
Action = fun (X) -> io:format("~B,", [X]), X * 2 end,
X = 1,
while_do(Pred, Action, X).
cpp
int x = 1;
while (x < 150) { x *= 2; Console::Write("{0},", x); }
Console::WriteLine();
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;
std::cout << std::endl;
fsharp
let mutable x = 1
while x < 150 do printf "%d, " x ; (x <- x * 2) done
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)
// 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()
while (x < 150) {
print x + ","
x *= 2
}
println()
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"
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);
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()).
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).
-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).
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();
int dice = rnd->Next(1, 7); Console::Write("{0}", dice);
do { Console::Write(",{0}", (dice = rnd->Next(1, 7))); } while (dice != 6);
Console::WriteLine();
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
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 ','
}
int dice = 0
while (dice != 6) {
dice = Math.random() * 6 + 1
print dice
if (dice != 6) print ','
}
Perform an action a fixed number of times (FOR)
Display the string
"Hello" five times like "HelloHelloHelloHelloHello"
csharp
string text = "Hello";
for (int i = 0; i < 5; i++)
{
Console.Write(text);
}
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)).
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");
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
for _ in list do printf "Hello" done
// Repetition via ranging over a Sequence type(index ignored)
for _ in sequence do printf "Hello" done
for _ in sequence do printf "Hello" done
// Repetition via ranging over an Array type(index ignored)
for _ in array do printf "Hello" done
for _ in array do printf "Hello" done
groovy
println "Hello" * 5
5.times { print "Hello" }; println()
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!"
csharp
for (int i = 10; i > 0; i--)
{
Console.Write("{0} .. ", i);
}
Console.WriteLine("Liftoff!");
{
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").
cpp
for(int i = 10; i != 0; --i) Console::Write("{0} .. ", i);
Console::WriteLine("Liftoff!");
Console::WriteLine("Liftoff!");
fsharp
for i = 10 downto 1 do printf "%d .. " i done
printfn "Liftoff!"
printfn "Liftoff!"
// Repetition via ranging over a Sequence type
for i in {10 .. -1 .. 1} do printf "%d .. " i done ; printfn "Liftoff!"
for i in {10 .. -1 .. 1} do printf "%d .. " i done ; printfn "Liftoff!"
groovy
10.downto(1) { print it + " .. " }
println "Liftoff!"
println "Liftoff!"
Read the contents of a file into a string
csharp
string contents = System.IO.File.ReadAllText("filename.txt");
erlang
Text = readfile("Solution607.erl"),
Text = readfile("Solution608.erl"),
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));
}
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();
}
try
{
stream = gcnew IO::StreamReader("test.txt");
buffer = stream->ReadToEnd();
}
String^ buffer = IO::File::ReadAllText("test.txt");
fsharp
let file = new FileStream("test.txt", FileMode.Open)
let buffer = new String((new BinaryReader(file)).ReadChars(Convert.ToInt32(file.Length)))
let buffer = new String((new BinaryReader(file)).ReadChars(Convert.ToInt32(file.Length)))
let stream = new StreamReader("test.txt")
let buffer = stream.ReadToEnd()
let buffer = stream.ReadToEnd()
let buffer = File.ReadAllText("test.txt")
groovy
contents = file.text
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
1> First line of file
2> Second line of file
3> Third line of file
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);
}
// 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).
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).
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).
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);
}
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);
for each(String^ line in IO::File::ReadAllLines("test.txt")) Console::WriteLine("{0}> {1}", ++i, line);
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 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 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)
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)
// 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 ->
println "${++count} > $line"
}
file.eachLine { line, count ->
println "${++count} > $line"
}
println "${++count} > $line"
}
Write a string to a file
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).
{ok, IODevice} = file:open("test.txt", [write]), file:write(IODevice, Line), file:close(IODevice).
cpp
IO::StreamWriter^ stream;
try
{
stream = gcnew IO::StreamWriter("test.txt", false);
stream->WriteLine("This line overwites file contents!");
}
try
{
stream = gcnew IO::StreamWriter("test.txt", false);
stream->WriteLine("This line overwites file contents!");
}
fsharp
let stream = new StreamWriter("test.txt", false)
stream.WriteLine("This line overwrites file contents!")
stream.WriteLine("This line overwrites file contents!")
groovy
file.delete()
file << 'some text'
file << 'some text'
file.text = 'some text'
Append to a 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).
{ok, IODevice} = file:open("test.txt", [append]), file:write(IODevice, Line), file:close(IODevice).
cpp
IO::StreamWriter^ stream;
try
{
stream = gcnew IO::StreamWriter("test.txt", true);
stream->WriteLine("This line appended to file!");
}
try
{
stream = gcnew IO::StreamWriter("test.txt", true);
stream->WriteLine("This line appended to file!");
}
fsharp
let stream = new StreamWriter("test.txt", true)
stream.WriteLine("This line appended to file!")
stream.WriteLine("This line appended to file!")
groovy
file << 'some text'
Process each file in a directory
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)).
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)).
lists:foreach(fun (FileOrDirPath) -> Worker(FileOrDirPath) end, list_dir_path(Directory)).
cpp
for each(String^ filename in IO::Directory::GetFiles(dirname)) process(filename);
fsharp
let dirname = "c:\\"
let processFile filename = printfn "%s" filename
for filename in Directory.GetFiles(dirname) do processFile filename done
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)
Directory.GetFiles(dirname) |> Array.iter (fun filename -> printfn "%s" filename)
groovy
dir.eachFile{ f -> process(f) }
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.
csharp
DateTime parsedDate = DateTime.Parse("2008-05-06 13:29");
// Ideally, you would catch the potential FormatException or use DateTime.TryParse in production code.
// Ideally, you would catch the potential FormatException or use DateTime.TryParse in production code.
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")),
LocalDateTime = erlang:universaltime_to_localtime(parse_to_datetime("2008-05-06 13:29:34")),
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"));
// 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);
// 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"))
// 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())
// 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())
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")
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.
If you can also do this without creating a Date object you can show that too.
csharp
// Creating a variable first:
DateTime now = DateTime.Now;
Console.WriteLine(now);
// Without creating a variable:
Console.WriteLine(DateTime.Now);
DateTime now = DateTime.Now;
Console.WriteLine(now);
// Without creating a variable:
Console.WriteLine(DateTime.Now);
erlang
io:format("~p~n", [calendar:local_time()])
cpp
QDate now = QDate::currentData();
qDebug() << now.toString();
qDebug() << now.toString();
time_t date = time(0);
cout << ctime(&date);
cout << ctime(&date);
fsharp
printfn "%A" System.DateTime.Now
groovy
println new Date()
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.
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();
}
}
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).
Greeter(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:
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);
}
{
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()
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()
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()
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()
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()
class Greeter {
private whom
Greeter(whom) { this.whom = whom }
def greet() { println "Hello, $whom" }
}
new Greeter('world').greet()
Process an XML document
Given the XML Document:
<shopping>
<item name=
<item name=
</shopping>
Print out the total cost of the items, e.g. $14.50
<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
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);
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]).
-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]).
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;
"<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;
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
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)
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"
// 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()
it.@quantity.toInteger() * it.@price.toFloat()
}.sum()
create some XML programmatically
Given the following CSV:
bread,3,2.50
milk,2,3.50
Produce the equivalent information in XML, e.g.:
<shopping>
<item name=
<item name=
</shopping>
bread,3,2.50
milk,2,3.50
Produce the equivalent information in XML, e.g.:
<shopping>
<item name=
"bread" quantity="3" price="2.50" />
<item name=
"milk" quantity="2" price="3.50" />
</shopping>
csharp
string cvs ="bread,3,2.50\nmilk,2,3.50";
IList<string> rows = cvs.Split('\n');
System.Text.StringBuilder sb = new System.Text.StringBuilder("<shopping>");
foreach(string row in rows){
IList<string> data = row.Split(',');
sb.AppendFormat("<item name='{0}' quantity='{1}' price='{2}' />",data[0],data[1],data[2]);
}
sb.Append("</shopping>");
IList<string> rows = cvs.Split('\n');
System.Text.StringBuilder sb = new System.Text.StringBuilder("<shopping>");
foreach(string row in rows){
IList<string> data = row.Split(',');
sb.AppendFormat("<item name='{0}' quantity='{1}' price='{2}' />",data[0],data[1],data[2]);
}
sb.Append("</shopping>");
erlang
to_xml(ShoppingList) ->
Items = lists:map(fun(L) ->
[Name, Quantity, Price] = string:tokens(L, ","),
{item, [{name, Name}, {quantity, Quantity}, {price, Price}], []}
end, string:tokens(ShoppingList, "\n")),
xmerl:export_simple([{shopping, [], Items}], xmerl_xml).
Items = lists:map(fun(L) ->
[Name, Quantity, Price] = string:tokens(L, ","),
{item, [{name, Name}, {quantity, Quantity}, {price, Price}], []}
end, string:tokens(ShoppingList, "\n")),
xmerl:export_simple([{shopping, [], Items}], xmerl_xml).
cpp
string input("bread,3,2.50\nmilk,2,3.50\n");
tokenizer<char_separator<char> > tokens(input, char_separator<char>(", \n"));
tokenizer<char_separator<char> >::iterator it = tokens.begin();
xml_document<> doc;
xml_node<> *shopping = doc.allocate_node(node_element, "shopping");
doc.append_node(shopping);
while (it != tokens.end()) {
xml_node<> *item = doc.allocate_node(node_element, "item");
shopping->append_node(item);
item->append_attribute(doc.allocate_attribute("name", doc.allocate_string((*it++).c_str())));
item->append_attribute(doc.allocate_attribute("quantity", doc.allocate_string((*it++).c_str())));
item->append_attribute(doc.allocate_attribute("price", doc.allocate_string((*it++).c_str())));
}
cout << doc << endl;
tokenizer<char_separator<char> > tokens(input, char_separator<char>(", \n"));
tokenizer<char_separator<char> >::iterator it = tokens.begin();
xml_document<> doc;
xml_node<> *shopping = doc.allocate_node(node_element, "shopping");
doc.append_node(shopping);
while (it != tokens.end()) {
xml_node<> *item = doc.allocate_node(node_element, "item");
shopping->append_node(item);
item->append_attribute(doc.allocate_attribute("name", doc.allocate_string((*it++).c_str())));
item->append_attribute(doc.allocate_attribute("quantity", doc.allocate_string((*it++).c_str())));
item->append_attribute(doc.allocate_attribute("price", doc.allocate_string((*it++).c_str())));
}
cout << doc << endl;
fsharp
#r "System.Xml.dll"
#r "System.Xml.Linq.dll"
open System
open System.Xml
open System.Xml.Linq
let data = "bread,3,2.50
milk,2,3.50"
let X name =
XName.Get(name)
let lines = data.Split( [|"\n" |], StringSplitOptions.RemoveEmptyEntries)
let document = new XDocument()
let element = new XElement(X "shopping")
document.Add(element)
lines
|> Seq.iter (fun line ->
let items = line.Split([|','|])
let item = new XElement(X "item",
new XAttribute(X "name", items.[0]),
new XAttribute(X "quantity", items.[1]),
new XAttribute(X "price", items.[2]))
element.Add(item))
let output = document.ToString();;
#r "System.Xml.Linq.dll"
open System
open System.Xml
open System.Xml.Linq
let data = "bread,3,2.50
milk,2,3.50"
let X name =
XName.Get(name)
let lines = data.Split( [|"\n" |], StringSplitOptions.RemoveEmptyEntries)
let document = new XDocument()
let element = new XElement(X "shopping")
document.Add(element)
lines
|> Seq.iter (fun line ->
let items = line.Split([|','|])
let item = new XElement(X "item",
new XAttribute(X "name", items.[0]),
new XAttribute(X "quantity", items.[1]),
new XAttribute(X "price", items.[2]))
element.Add(item))
let output = document.ToString();;
groovy
b = new groovy.xml.MarkupBuilder()
b.shopping {
csv.eachLine { line ->
(n, q, p) = line.split(',')
item(name:n, quantity:q, price:p)
}
}
b.shopping {
csv.eachLine { line ->
(n, q, p) = line.split(',')
item(name:n, quantity:q, price:p)
}
}
// Groovy equivalent of Java JAXB solution
@XmlAccessorType(NONE)
class Item {
@XmlAttribute String name
@XmlAttribute Integer quantity
@XmlAttribute Double price
}
@XmlAccessorType(NONE)
@XmlRootElement
class Shopping {
@XmlElement Set<Item> items = []
}
Shopping shopping = new Shopping()
csvtext.eachLine{ line ->
(n, q, p) = line.split(',')
shopping.items << new Item(name:n, quantity:q.toInteger(), price:p.toDouble())
}
JAXB.marshal shopping, System.out
@XmlAccessorType(NONE)
class Item {
@XmlAttribute String name
@XmlAttribute Integer quantity
@XmlAttribute Double price
}
@XmlAccessorType(NONE)
@XmlRootElement
class Shopping {
@XmlElement Set<Item> items = []
}
Shopping shopping = new Shopping()
csvtext.eachLine{ line ->
(n, q, p) = line.split(',')
shopping.items << new Item(name:n, quantity:q.toInteger(), price:p.toDouble())
}
JAXB.marshal shopping, System.out
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.
csharp
public static int gcd(int a, int b)
{
if (b == 0)
return a;
else
return gcd(b, a % 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).
-export([gcd/2]).
gcd(A, 0) -> A;
gcd(A, B) -> gcd(B, A rem B).
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;
}
#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;
}
fsharp
let rec gcd x y =
if y = 0 then x
else gcd y (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))
}
if (Math.min(i,j)==0) return Math.max(i,j)
else return gcd(Math.min(i,j),Math.abs(i-j))
}
