Solved Problems

Output a string to the console

Write the string "Hello World!" to STDOUT
ruby
puts "Hello World!"
$stdout<<"Hello World!"
csharp
System.Console.WriteLine("Hello World!")
cpp
std::cout << "Hello World" << std::endl;
std::printf("Hello World\n");
Console::WriteLine(L"Hello World");
fantom
echo("Hello World!")

Define a string containing special characters

Define the literal string "\#{'}${"}/"
ruby
special = '\#{\'}${"}/'
csharp
string verbatim = @"\#{'}${""""}/";
string cStyle = "\\#{'}${\"\"}/";
cpp
std::string special = "\\#{'}${\"}/";
String^ special = L"\\#{'}${\"}/";
fantom
special := Str<|\#{'}${"}/|>

Define a multiline string

Define the string:
"This
Is
A
Multiline
String"
ruby
text = <<"HERE"
This
Is
A
Multiline
String
HERE
text = "This\nIs\nA\nMultiline\nString"
csharp
string output = "This\nIs\nA\nMultiline\nString";
string output = @"This
Is
A
Multiline
String";
cpp
std::string text =
"This\n"
"Is\n"
"A\n"
"Multiline\n"
"String";
String^ text = L"This\nIs\nA\nMultiline\nString";
std::string text = "This\nIs\nA\nMultiline\nString";
fantom
s := "This
Is
A
Multiline
String"

Define a string containing variables and expressions

Given variables a=3 and b=4 output "3+4=7"
ruby
puts "#{a}+#{b}=#{a+b}"
puts "#{a}+#{b}=%s" % (a + b)
csharp
int a = 3;
int b = 4;
Console.WriteLine("{0}+{1}={2}", 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;
fantom
echo("$a+$b=${a+b}")

Reverse the characters in a string

Given the string "reverse me", produce the string "em esrever"
ruby
puts "reverse me".reverse
csharp
var str = "reverse me";
Console.WriteLine(new String(str.Reverse().ToArray()));
cpp
String^ s = "reverse me";
array<Char>^ sa = s->ToCharArray();
Array::Reverse(sa);
String^ sr = gcnew String(sa);
std::string s = "reverse me";
std::reverse(s.begin(), s.end());
std::string s = "reverse me";
std::string sr(s.rbegin(), s.rend());
std::string s = "reverse me";
std::swap_ranges(s.begin(), (s.begin() + s.size() / 2), s.rbegin());
fantom
"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"
ruby
reversed = text.split.reverse.join(' ')
csharp
var str = "This is a end, my only friend!";
str = String.Join(" ", str.Split().Reverse().ToArray());
Console.WriteLine(str);
cpp
array<Char>^ sep = {L' '};
array<String^>^ words =
String(L"This is the end, my only friend!").Split(sep, StringSplitOptions::RemoveEmptyEntries);

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

boost::split(swv, words, boost::is_any_of(" ")); std::reverse(swv.begin(), swv.end());
std::string newwords = (std::for_each(swv.begin(), swv.end(), StringTAndJ())).value();
fantom
"This is a end, my only friend!".split.reverse.join(" ")

Text wrapping

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

> The quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog.
ruby
prefix = "> "
string = "The quick brown fox jumps over the lazy dog. " * 10
width = 78
realwidth = width - prefix.length
print string.gsub(/(.{1,#{realwidth}})(?: +|$)\n?|(.{#{realwidth}})/, "#{prefix}\\1\\2\n")
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));
}
}
cpp
String^ input = ::copies("The quick brown fox jumps over the lazy dog. ", 10);
String^ sep = " "; String^ prefix = "> ";

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

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

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

int main()
{
stringstream input;

rep(input, "The quick brown fox jumps over the lazy dog. ", 10);
wrap(cout, input.str(), "> ", 72);
}
fantom
buf := Buf()
10.times { buf.writeChars("The quick brown fox jumps over the lazy dog. ") }
buf.flip

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

acc += s.size
if (acc > max)
{
out.print("\n$sep")
acc = s.size
}
out.print(" $s")
buf.readStrToken(4096) { !it.isSpace }
acc++
}

Remove leading and trailing whitespace from a string

Given the string "  hello    " return the string "hello".
ruby
puts " hello ".strip
" hello ".strip!
csharp
string str = " hello ";
str = str.Trim();
Console.WriteLine(str);
cpp
String^ s = " hello "; String^ trimmed = s->Trim();
fantom
s := " hello ".trim

Make a string uppercase

Transform "Space Monkey" into "SPACE MONKEY"
ruby
uppper = text.upcase
csharp
string output = "Space Monkey"

System.Console.WriteLine(output.ToUpper())
cpp
String(L"Space Monkey").ToUpper();
std::string s = "Space Monkey";
std::transform(s.begin(), s.end(), s.begin(), std::toupper);
std::string s = "Space Monkey";
boost::to_upper(s);
fantom
s := "Space Monkey".localeUpper

Make a string lowercase

Transform "Caps ARE overRated" into "caps are overrated"
ruby
"Caps ARE overRated".downcase
csharp
string str = "Caps ARE overRated";
str = str.ToLower() ;
Console.WriteLine(str);
cpp
std::string s = "Caps ARE overRated";
std::string sl(boost::to_lower_copy(s));
String(L"Caps ARE overRated").ToLower();
fantom
s := "Caps ARE overRated".localeLower

Capitalise the first letter of each word

Transform "man OF stEEL" into "Man Of Steel"
ruby
caps = text.gsub(/\w+/) { $&.capitalize }
caps = text.split.each{|i| i.capitalize!}.join(' ')
text.split.map(&:capitalize) * ' '
csharp
System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase("man OF stEEL".ToLowerInvariant());
cpp
std::string words = "mAn OF stEEL";
std::transform(words.begin(), words.end(), words.begin(), ToCaps<>());
StringBuilder^ sb = gcnew StringBuilder(L"man OF stEEL");

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

boost::split(swv, words, boost::is_any_of(" "));
std::string newwords = (std::for_each(swv.begin(), swv.end(), StringTAndJ(WordToCaps))).value();
fantom
"man OF stEEL".split.map { it.localeLower.localeCapitalize }.join(" ")

Find the distance between two points

ruby
# the hypotenuse sqrt(x**2+y**2)
distance = Math.hypot(x2-x1,y2-y1)
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)));
cpp
Point p1 = {34, 78}, p2 = {67, -45};
double distance = ::distance(p1, p2);
Console::WriteLine("{0,3:F2}", distance);
fantom
px1 := 34.0f; py1 := 78.0f; px2 := 67.0f; py2 := -45.0f
distance := |Float x1, Float y1, Float x2, Float y2 -> Float|
{ ((x2-x1).pow(2.0f) + (y2-y1).pow(2.0f)).sqrt }

distance(px1, py1, px2, py2)

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042
ruby
42.to_s.rjust(8,"0")
"%08d" % 42
csharp
string.Format("{0,8:D8}", 42);
cpp
String^ formatted = Convert::ToString(42)->PadLeft(8, '0');
String^ formatted = String::Format("{0,8:D8}", 42);
std::printf("%08d", 42);
std::ostringstream os;
os << std::setw(8) << std::setfill('0') << 42 << std::ends;
std::cout << os.str() << std::endl;
std::cout << boost::format("%|08|") % 42 << std::endl;
fantom
formatted := 42.toStr.padl(8, '0')
formatted := 42.toLocale("00000000")

Right Space pad a number

Given the number 1024 right pad it to 6 characters "1024  "
ruby
1024.to_s.ljust(6)
csharp
public class NumberRightPadding {
public static void Main() {
string withStringDotFormat = string.Format("{0,-6}", 1024);
string withToStringDotPadRight = 1024.ToString().PadRight(6);
}
}
cpp
String^ formatted = Convert::ToString(1024)->PadRight(6);
String^ formatted = String::Format("{0,-6:D}", 1024);
std::printf("%-6d\n", 1024);
std::ostringstream os;
os << std::setw(6) << std::setfill(' ') << std::left << 1024 << std::ends;
std::cout << os.str() << std::endl;
std::cout << boost::format("%|-6|") % 1024 << std::endl;
fantom
formatted := 1024.toStr.padr(6)

Format a decimal number

Format the number 7/8 as a decimal with 2 places: 0.88
ruby
(7.0/8.0*100).round/100.0
(7.0/8.0).round(2)
csharp
public class FormatDecimal {
public static void Main() {
decimal result = decimal.Round( 7 / 8m, 2);
System.Console.WriteLine(result);
}
}
cpp
String^ formatted = String::Format("{0,3:F2}", result);
Console::WriteLine("{0,3:F2}", (7. / 8.));
std::printf("%3.2f\n", result);
std::ostringstream os;
os.width(3); os.fill('0'); os.setf(std::ios::fixed|std::ios::showpoint); os.precision(2);
os << result << std::ends;
std::cout << os.str() << std::endl;
std::cout << boost::format("%|3.2f|") % result << std::endl;
fantom
formatted := (7.0/8.0).toLocale("0.00")

Left Space pad a number

Given the number 73 left pad it to 10 characters "        73"
ruby
73.to_s.rjust(10)
csharp
public class NumberLeftPadding {
public static void Main() {
string withStringDotFormat = string.Format("{0,10}", 73);
string withToStringDotPadLeft = 73.ToString().PadLeft(10);
}
}
cpp
String^ formatted = Convert::ToString(73)->PadLeft(10);
String^ formatted = String::Format("{0,10:D}", 73);
std::printf("%10d\n", 73);
std::ostringstream os;
os << std::setw(10) << std::setfill(' ') << 73 << std::ends;
std::cout << os.str() << std::endl;
std::cout << boost::format("%|10|") % 73 << std::endl;
fantom
formatted := 73.toStr.padl(10)

Generate a random integer in a given range

Produce a random integer between 100 and 200 inclusive
ruby
randomInt = rand(200-100+1)+100;
csharp
System.Random r = new System.Random();
int random = r.Next(100,201);
cpp
Random^ rnd = gcnew Random;
int rndInt = rnd->Next(100, 201);
std::srand(std::time(NULL));

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

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

unsigned rnd = generator();
fantom
r := Int.random(100..200)

Generate a repeatable random number sequence

Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values.
ruby
srand(12345)
first = (1..5).collect {rand}
srand(12345)
second = (1..5).collect {rand}
puts first == second
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());
}
}

cpp
void printAction(int i) { Console::Write("{0} ", i); }

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

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

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

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

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

rng.seed(42L);
std::cout << std::endl;
std::generate_n(std::ostream_iterator<unsigned>(std::cout, " "), 5, generator);
fantom
rand := Random.makeSeeded(12345)
first := Int[,].fill(0,5).map { rand.next(100..200) }

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

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
ruby
puts "ok" if ("Hello"=~/^[A-Z][a-z]+$/)
csharp
if (Regex.IsMatch("Hello", "[A-Z][a-z]+"))
{
Console.WriteLine("ok");
}
cpp
if ((gcnew Regex("[A-Z][a-z]+"))->IsMatch("Hello")) Console::WriteLine("ok");
if (Regex::IsMatch("Hello", "[A-Z][a-z]+")) Console::WriteLine("ok");
Regex^ rx = gcnew Regex("[A-Z][a-z]+");
if (rx->IsMatch("Hello")) Console::WriteLine("ok");
cmatch what;
if (regex_match("Hello", what, regex("[A-Z][a-z]+")))
cout << "ok" << endl;
fantom
if (Regex<|[A-Z][a-z]+|>.matches("Hello"))
echo("ok")

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
ruby
puts $1 if "one two three"=~/^one (.*) three$/
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]);
}
}
cpp
Match^ match = Regex::Match("one two three", "one (.*) three");
if (match->Success) Console::WriteLine("{0}", match->Groups[1]->Captures[0]);
cmatch what;
if (regex_match("one two three", what, regex("one (.*) three")))
cout << what[1] << endl;
fantom
m := Regex<|one (.*) three|>.matcher("one two three")
if (m.matches)
echo("${m.group(1)}")

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/
ruby
puts "ok" if (text=~/\d+/)
csharp
if(System.Text.RegularExpressions.Regex.IsMatch("abc 123 @#$",@"\d+")){
Console.WriteLine("ok");
}
cpp
if (Regex::IsMatch("abc 123 @#$", "\\d+")) Console::WriteLine("ok");
fantom
m := Regex<|\d+|>.matcher("abc 123 @#\$")
if (m.find)
echo("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+)/
ruby
list = text.scan(/\((\w+)\):(\d+)/).collect{|x| x.join}
list=[]
text.scan(/\((\w+)\):(\d+)/) {
list << $1+$2
}
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;});
}
}
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();
}
fantom
m := Regex<|\((\w+)\):(\d+)|>.matcher(s)
list := Str[,]
while (m.find) { list.add("${m.group(1)}${m.group(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"
ruby
replaced = text.gsub(/se\w+/,"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");
}
}
cpp
String^ Replaced = (gcnew Regex("se\\w+"))->Replace("She sells sea shells", "X");
String^ Replaced = Regex::Replace("She sells sea shells", "se\\w+", "X");
fantom
replaced := Regex<|se\w+|>.split("She sells sea shells").join("X")

Define an empty list

Assign the variable "list" to a list with no elements
ruby
list = []
list = Array.new
csharp
var list = new List<object>();
cpp
Generic::List<String^>^ list = gcnew Generic::List<String^>();
std::list<std::string> list;
fantom
list := [,]

Define a static list

Define the list [One, Two, Three, Four, Five]
ruby
list = ['One', 'Two', 'Three', 'Four', 'Five']
list = %w(One Two Three Four Five)
csharp
IList<string> list = new string[]{"One","Two","Three","Four","Five"};
cpp
array<String^>^ input = {"One", "Two", "Three", "Four", "Five"};
Generic::List<String^>^ list = gcnew Generic::List<String^>((Generic::IEnumerable<String^>^) input);
Generic::List<String^>^ list = gcnew Generic::List<String^>();

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

list.push_back("One");
list.push_back("Two");
list.push_back("Three");
list.push_back("Four");
list.push_back("Five");
list<string> lst = { "One", "Two", "Three", "Four", "Five" };
list<string> lst;
lst += "One", "Two", "Three", "Four", "Five";
fantom
list := ["One", "Two", "Three", "Four", "Five"]

Join the elements of a list, separated by commas

Given the list [Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
ruby
string = fruit.join(', ')
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()) );
}
}
cpp
String^ result = String::Join(L", ", fruit->ToArray());
string fruits[] = {"Apple", "Banana", "Carrot"};
string result = boost::algorithm::join(fruits, ", ");
fantom
["Apple", "Banana", "Carrot"].join(", ")

Join the elements of a list, in correct english

Create a function join that takes a List and produces a string containing an english language concatenation of the list. It should work with the following examples:
join([Apple, Banana, Carrot]) = "Apple, Banana, and Carrot"
join([One, Two]) = "One and Two"
join([Lonely]) = "Lonely"
join([]) = ""
ruby
def join(arr)
return '' if not arr
case arr.size
when 0 then ''
when 1 then arr[0]
when 2 then arr.join(' and ')
else arr[0..-2].join(', ') + ', and ' + arr[-1]
end
end
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>()) );
}
}
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);
}
}
fantom
join := |List list -> Str|
{
switch(list.size)
{
case 0: return ""
case 1: return list[0]
case 2: return list.join(" and ")
default: return list[0..-2].join(", ") + ", and " + list[-1]
}
}

echo(join(["Apple", "Banana", "Carrot"]))
echo(join(["One", "Two"]))
echo(join(["Lonely"]))
echo(join([,]))

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]]
ruby
common = [] ; [4, 5].each {|n| ['a', 'b', 'c'].each {|l| common << [l, n]}}
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 });
}
}
}
}
cpp
Specialized::StringCollection^ combinations = gcnew Specialized::StringCollection;

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

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

cout << combo << endl;
fantom
[4,5].each |Int i| { ["a","b","c"].each |Str s| { r.add([i,s]) } }

From a List Produce a List of Duplicate Entries

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

Write the code to produce a list of duplicates in the list:
["bob"]
ruby
foo = ['andrew', 'bob', 'chris', 'bob']
foo.inject({}) {|h,v| h[v]=h[v].to_i+1; h}.reject{|k,v| v==1}.keys
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);
}
cpp
vector<string> lst = { "andrew", "bob", "chris", "bob" };
vector<string> lst_no_dups;
vector<string> tmp;
vector<string> dups;

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

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

for (auto &s: lst)
num_identical[s]++;
for (auto &n: num_identical)
if (n.second > 1)
dups.push_back(n.first);
cout << dups << endl;
fantom
nameCounts := Str:Int[:] { def = 0 }
["andrew", "bob", "chris", "bob"].each |Str v| { nameCounts[v]++ }
results := nameCounts.findAll |Int v, Str k->Bool| { v > 1 }.keys
echo(results.join(","))

Fetch an element of a list by index

Given the list [One, Two, Three, Four, Five], fetch the third element ('Three')
ruby
list = ['One', 'Two', 'Three', 'Four', 'Five']
list[2]
['One', 'Two', 'Three', 'Four', 'Five'].fetch(2)
list = ['One', 'Two', 'Three', 'Four', 'Five']
list.at(2)
['One', 'Two', 'Three', 'Four', 'Five'][2] # <= note the [2] at end of array
csharp
string[] items = new string[] { "One", "Two", "Three", "Four", "Five" };
List<string> list = new List<string>(items);
string third = list[2]; // "Three"
// Make sure you import the System.Linq namespace.
// This is not the preferred way of indexing if you are using Lists.
string[] items = new string[] { "One", "Two", "Three", "Four", "Five" };
IEnumerable<string> list = new List<string>(items);
string third = list.ElementAt(2); // Three
cpp
String^ result = list[2];
fantom
["One", "Two", "Three", "Four", "Five"][2]
["One", "Two", "Three", "Four", "Five"].get(2)

Fetch the last element of a list

Given the list [Red, Green, Blue], access the last element ('Blue')
ruby
['Red', 'Green', 'Blue'][-1]
['Red', 'Green', 'Blue'].at(-1)
['Red', 'Green', 'Blue'].last
['Red', 'Green', 'Blue'].fetch(-1)
csharp
string[] items = new string[] { "Red", "Green", "Blue" };
List<string> list = new List<string>(items);
string last = list[list.Count - 1]; // "Blue"
// Make sure you import the System.Linq namespace.
// This is not the preferred way of finding the last element if you are using Lists.
string[] items = new string[] { "Red", "Green", "Blue" };
IEnumerable<string> list = new List<string>(items);
string last = list.Last(); // "Blue"
cpp
String^ result = list[list->Count - 1];
string last_elem = lst.back();
fantom
["Red", "Green", "Blue"][-1]
["One", "Two", "Three", "Four", "Five"].last

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?
ruby
common = (beans.intersection(colors)).to_a
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']
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);
fantom
beans := ["broad", "mung", "black", "red", "white"]
colors := ["black", "red", "blue", "green"]
echo(beans.intersection(colors))

Display the unique items in a list

Display the unique items in a list, e.g. given ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18], display the unique elements, i.e. with duplicates removed.
ruby
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
p ages.uniq
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
ages.uniq!
p ages
ages = (Set.new [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]).to_a
p ages
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();
}
}
cpp
array<int>^ input = {18, 16, 17, 18, 16, 19, 14, 17, 19, 18};
Generic::List<int>^ ages = gcnew Generic::List<int>((Generic::IEnumerable<int>^) input);

Generic::ICollection<int>^ result = makeSET<int>(ages);
list<int> input;
input += 18, 16, 17, 18, 16, 19, 14, 17, 19, 18;
input.sort();
unique_copy(input.begin(), input.end(), ostream_iterator<int>(cout, "\n"));
fantom
uniqueAges := [18, 16, 17, 18, 16, 19, 14, 17, 19, 18].unique
echo(uniqueAges)

Remove an element from a list by index

Given the list [Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
ruby
['Apple', 'Banana', 'Carrot'].shift
fruit.delete_at(0)
csharp
class Solution1516
{
static void Main()
{
List<string> fruit = new List<string>() { "Apple", "Banana", "Carrot" };
fruit.RemoveAt(0);
}
}
cpp
fruit->RemoveAt(0);
fantom
list := ["Apple", "Banana", "Carrot"]
list.removeAt(0)

Remove the last element of a list

ruby
list = ['Apple', 'Banana', 'Carrot']
list.delete_at(-1)
list = ['Apple', 'Banana', 'Carrot']
list.pop
csharp
List<string> fruits = new List() { "apple", "banana", "cherry" };
fruits.RemoveAt(fruits.Length - 1);
cpp
fruit->RemoveAt(fruit->Count - 1);
fantom
list := ["Apple", "Banana", "Carrot"]
list.removeAt(-1)
list := ["Apple", "Banana", "Carrot"]ยจ
list.pop

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"]
ruby
items = ["apple", "orange", "grapes", "bananas"]
items << first = items.shift

# items is rotated
# first contains the first value in the list
csharp
var lst = new LinkedList<String>(new String[] {"apple", "orange", "grapes", "banana"});
lst.AddLast(lst.First());
lst.DeleteFirst();
cpp
fruit->Add(fruit[0]); fruit->RemoveAt(0);
rotate(fruit.begin(), fruit.begin()+1, fruit.end());
fantom
list := ["apple", "orange", "grapes", "bananas"]
list.add(list.removeAt(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.
ruby
first = ['Bruce', 'Tommy Lee', 'Bruce']; last = ['Willis', 'Jones', 'Lee']; years = [1955, 1946, 1940]

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

result = [first, last, years].transpose
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)));
cpp
array<String^>^ first = {"Bruce", "Tommy Lee", "Bruce"}; array<String^>^ last = {"Willis", "Jones", "Lee"}; array<String^>^ years = {"1955", "1946", "1940"};

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

for (firstIt = first.begin(), lastIt = last.begin(), yearIt = years.begin();
firstIt != first.end() && lastIt != last.end() && yearIt != years.end();
++firstIt, ++lastIt, ++yearIt)
actors.push_back(make_tuple(*firstIt, *lastIt, *yearIt));
fantom
r := [,]
first.size.times |Int i| { r.add([first[i], last[i], years[i]]) }

echo(r)

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'.
ruby
suites.each {|s| faces.each {|f| cards << [s, f]}}
puts "Deck %s \'Ace of Hearts\'" % if cards.include?(['h', 'A']) then "contains" else "does not contain" end
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();
}
}
}
cpp
Specialized::StringCollection^ cards = gcnew Specialized::StringCollection;

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

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

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

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

card ace_of_harts = make_pair("h", "A");
if (end(cards) != find_if(begin(cards), end(cards),
[&](const card& c) { return c == ace_of_harts; }))
cout << "Deck contain 'Ace of Harts'" << endl;
else
cout << "Deck lacks 'Ace of Harts'" << endl;
fantom
r := [,]
["2","3","4","5","6","7","8","9","10","J","Q","K","A"].each |Str c|
{ ["H","D","C","S"].each |Str s| { r.add([c,s]) } }

q := ["A","H"]
result := r.contains(q)
echo("Deck size=${r.size}, contains $q? -> $result")

Perform an operation on every item of a list

Perform an operation on every item of a list, e.g.
for the list ["ox", "cat", "deer", "whale"] calculate
the list of sizes of the strings, e.g. [2, 3, 4, 5]
ruby
["ox", "cat", "deer", "whale"].map{|i| i.length}
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 );
}
}
cpp
list<string> words;

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

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

transform(begin(words),
end(words),
back_inserter(word_sizes),
[](const string& s) { return s.size(); });
fantom
["ox", "cat", "deer", "whale"].map { it.size }

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.
ruby
now=Time.now
things=["hello", 25, 3.14, now]

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

numbers, others=things.partition{|i| i.is_a? Numeric}
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) );
}

}
cpp
typedef variant<int,float,string,date> dynamic;

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

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

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

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

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

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

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

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

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

// float and int are now in 'numbers' and the rest in 'non_numbers'
}
fantom
things := ["hello", 25, 3.14, Time.now]
numbers := things.findType(Num#)
nonNumbers := things.exclude { numbers.contains(it) }

Create a histogram map from a list

Given the list [a,b,a,c,b,b], produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list
ruby
histogram = {}
list.each { |item| histogram[item] = (histogram[item] || 0) +1 }
list = %w{a b a c b b}

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

p histogram # => {"a"=>2, "b"=>3, "c"=>1}
list.inject(Hash.new(0)) {|h, item| h[item] += 1; h}
csharp
using System.Collections.Generic;
using System.Linq;

// This is a "functional" C# approach

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

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

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

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

// This just prints the result
System.Console.WriteLine (
string.Join (", ",
// "Select" works like "map" or "collect" in many other languages
map.Select( kvp =>
string.Format("{0} : {1}", kvp.Key, kvp.Value)
).ToArray()
)
);
}
}
new[] {"a","b","a","c","b","b"}
.GroupBy(s => s)
.Select(s => new { Value = s.Key, Count = s.Count() })
.ToList()
.ForEach(e => Console.WriteLine("{0} : {1} ", e.Value, e.Count));
cpp
for each(String^ entry in input) hash[entry] = hash->ContainsKey(entry)
? Convert::ToInt32(hash[entry]->ToString()) + 1 : 1;
for each(String^ entry in input) dict[entry] = dict->ContainsKey(entry) ? dict[entry] + 1 : 1;
map<string,int> hist;
for (auto e: { "a","b","a","c","b","b" })
++hist[e];
for (auto e: hist)
cout << e.first << " : " << e.second << endl;
fantom
list := ["a","b","a","c","b","b"]
map := [Str:Int][:]
list.each |Str s, Int i| { if(!map.containsKey(s)) map.add(s,1); else map[s] = ++map[s] }
echo (map)

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
ruby
lengths = {}
list.each do |x|
len = x.size
lengths[len] = (lengths[len] || [])
lengths[len] << x
end
lengths = list.group_by {|x| x.size}
list.inject({}) { |h,x| (h[x.size]||=[]) << x; h }
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
}
}
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);
}
fantom
list := ["one", "two", "three", "four", "five"]
map := [Int:List][:]
list.each { List l := map[it.size] ?: [,]; map[it.size] = l.add(it) }
echo(map)

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

Given a variable name, if the value is "Bob", display the string "Hello, Bob!". Perform no action if the name is not equal.
ruby
if (name=='Bob')
puts "Hello, Bob!"
end
puts "Hello, Bob!" if name=='Bob'
csharp
if (name == "Bob") Console.WriteLine("Hello, {0}!", name);
cpp
if (name == "Bob") Console::WriteLine("Hello, {0}!", name);
if (name == "Bob") std::cout << "Hello, " << name << "!" << std::endl;
fantom
if (name=="Bob") echo("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"
ruby
if (age > 42)
puts "You are old"
else
puts "You are young"
end
puts (age>42) ? "You are old" : "You are young"
puts "You are #{age > 42 ? "old" : "young"}"
csharp
int age = 41;

if (age > 42)

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


cpp
if (age > 42) Console::WriteLine("You are old");
else Console::WriteLine("You are young");
Console::WriteLine("You are {0}", (age > 42 ? "old" : "young"));
std::printf("You are %s\n", (age > 42 ? "old" : "young"));
fantom
if (age > 42)
echo("You are old")
else
echo("You are young")
echo((age > 42) ? "You are old" : "You are young")

Perform different actions depending on several boolean conditions (IF .. THEN .. ELSIF .. ELSE)

ruby
if age > 84
puts "You are really ancient"
elsif age > 30
puts "You are middle-aged"
else
puts "You are young"
end
case
when age > 84 then puts "You are really ancient"
when age > 30 then puts "You are middle-aged"
else puts "You are young"
end
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");
Console.WriteLine("You are {0}", ((age > 84) ? "really ancient" : (age > 30) ? "middle-aged" : "young"));
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");
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;
fantom
if (age > 84)
echo("You are really ancient")
else if (age > 30)
echo("You are middle-aged")
else
echo("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
ruby
def suffixed(number)
last_digit = number.to_s[-1..-1].to_i
suffix = case last_digit
when 1 then 'st'
when 2 then 'nd'
when 3 then 'rd'
else 'th'
end
suffix = 'th' if (11..13).include?(number)
"#{number}#{suffix}"
end

(1..40).each {|n| puts suffixed(n) }
csharp
public static string GetOrdinal(int i)
{
if (i > 10 && i < 20) return i.ToString() + "th";
switch (i % 10)
{
case 1:
return i.ToString() + "st";
case 2:
return i.ToString() + "nd";
case 3:
return i.ToString() + "rd";
default:
return i.ToString() + "th";
}
}
public static string GetOrdinal(int i)
{
if (i > 10 && i < 20) return i.ToString() + "th";
switch (i % 10)
{
case 1:
return i.ToString() + "st";
break;
case 2:
return i.ToString() + "nd";
break;
case 3:
return i.ToString() + "rd";
break;
default:
return i.ToString() + "th";
break;
}
}
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();
}
fantom
suffix := |Int n -> Str|
{
if ((4..20).contains(n % 100))
return "th"

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

(1..40).each { echo("$it${suffix(it)}") }

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.
ruby
x=1
while x < 150
puts x
x <<= 1
end
csharp
int x = 1;

while (x < 150)
{
x *= 2;
Console.Write("{0},", x);
}
cpp
int x = 1;

while (x < 150) { x *= 2; Console::Write("{0},", x); }
Console::WriteLine();
for (int x = 1; x < 150; x *= 2) { std::cout << x << ","; }
std::cout << std::endl;
fantom
x := 1
while (x < 150) {
Env.cur.out.print("$x,")
x *= 2
}
echo

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"
ruby
# Ruby has no DO..WHILE construct. Need to write it as a WHILE
rnd = 0
while (rnd != 6)
rnd = rand(6)+1
print rnd
print "," if (rnd!=6)
end
begin
rnd = rand(6)+1
print rnd
print "," if rnd!=6
end while rnd != 6
# This uses Enumerators, ad it becomes almost functional style...

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

puts games.take_while {|roll| roll != 6}.join(",")
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);
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();
fantom
rnd := 0
while(rnd != 6) {
rnd = Int.random(1..6)
Env.cur.out.print(rnd)
if (rnd != 6)
Env.cur.out.print(",")
}
echo

Perform an action a fixed number of times (FOR)

Display the string "Hello" five times like "HelloHelloHelloHelloHello"
ruby
puts "Hello"*5
5.times { print "Hello" }
csharp
string text = "Hello";

for (int i = 0; i < 5; i++)
{
Console.Write(text);
}
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");
fantom
5.times { Env.cur.out.print("Hello") }
for (i := 0; i < 5; i++)
Env.cur.out.print("Hello")
(1..5).each { Env.cur.out.print("Hello") }

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!"
ruby
10.downto(1) { |n| print n, " .. " }
puts "Liftoff!"
csharp
for (int i = 10; i > 0; i--)
{
Console.Write("{0} .. ", i);
}

Console.WriteLine("Liftoff!");
cpp
for(int i = 10; i != 0; --i) Console::Write("{0} .. ", i);
Console::WriteLine("Liftoff!");
fantom
(10..1).each { Env.cur.out.print("$it .. ") }
Env.cur.out.print("Liftoff!")
for (i := 10; i >= 1; i--)
Env.cur.out.print("$i .. ")
Env.cur.out.print("Liftoff!")

Read the contents of a file into a string

ruby
file = File.new("Solution108.rb")
whole_file = file.read
csharp
string contents = System.IO.File.ReadAllText("filename.txt");
cpp
IO::FileStream^ file; String^ buffer;

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

try
{
stream = gcnew IO::StreamReader("test.txt");
buffer = stream->ReadToEnd();
}
String^ buffer = IO::File::ReadAllText("test.txt");
fantom
contents := File(`file.text`).readAllStr

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
ruby
File.open("Solution103.rb").each_with_index { |line, count|
puts "#{count} > #{line}
}
csharp
int counter = 0;

// If the file is large, you would want to buffer this instead of reading everything at once
foreach (string line in System.IO.File.ReadAllLines("filename.txt"))
{
Console.WriteLine("{0}> {1}", ++counter, line);
}
cpp
IO::StreamReader^ stream; String^ ln; int i = 0;

try
{
stream = gcnew IO::StreamReader("test.txt");
while ((ln = stream->ReadLine())) Console::WriteLine("{0}> {1}", ++i, ln);
}
int i = 0;
for each(String^ line in IO::File::ReadAllLines("test.txt")) Console::WriteLine("{0}> {1}", ++i, line);
fantom
File(`input.text`).readAllLines.each |Str s, Int i| { echo("${i+1}> $s") }

Write a string to a file

ruby
File.new("a_file", "w") << "some text"
csharp
System.IO.File.WriteAllText("filename.txt", "Some text to write to the file");
cpp
IO::StreamWriter^ stream;

try
{
stream = gcnew IO::StreamWriter("test.txt", false);
stream->WriteLine("This line overwites file contents!");
}
fantom
File(`out.txt`).out.writeChars("some text").flush

Append to a file

ruby
file = File.new('/tmp/test.txt', 'a+') ; file.puts 'This line appended to file!!' ; file.close()
csharp
System.IO.File.AppendAllText("filename.txt", "Some text to append to the file");
cpp
IO::StreamWriter^ stream;

try
{
stream = gcnew IO::StreamWriter("test.txt", true);
stream->WriteLine("This line appended to file!");
}
fantom
File(`out.txt`).out(true).writeChars("some text").flush

Process each file in a directory

ruby
directory = '/tmp' ; Dir.foreach(directory) {|file| puts "#{file}"}
csharp
foreach (string filename in System.IO.Directory.GetFiles(directory)) ProcessFile(filename);
cpp
for each(String^ filename in IO::Directory::GetFiles(dirname)) process(filename);
fantom
File(`./`).list.each { process(it) }

Parse a date and time from a string

Given the string "2008-05-06 13:29", parse it as a date representing 6th March, 2008 1:29:00pm in the local time zone.
ruby
# With timezone info
puts Time.parse('2008-05-06 13:29')
csharp
DateTime parsedDate = DateTime.Parse("2008-05-06 13:29");
// Ideally, you would catch the potential FormatException or use DateTime.TryParse in production code.
cpp
DateTimeOffset^ dateTime = DateTimeOffset::Parse("2008-05-06 13:29");

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

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

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

Console::WriteLine("{0}", dsb);
fantom
dt := DateTime.fromLocale("2008-05-06 13:29", "YYYY-MM-DD hh:mm")

Display information about a date

Display the day of month, day of year, month name and day name of the day 8 days from now.
ruby
require 'date'

next_week = Date.today + 8

puts next_week.day # day of month
puts next_week.yday # day of year
puts next_week.strftime('%B') # month name
puts next_week.strftime('%A') # day name
csharp
DateTime date = DateTime.Today.AddDays(8);

Console.WriteLine("Day of month: " + date.Day);
Console.WriteLine("Day of year: " + date.DayOfYear);
Console.WriteLine("Month name: " + date.ToString("MMMM"));
Console.WriteLine("Day name: " + date.ToString("dddd"));

// The two ToString calls will use the current locale.
// To get localised month and day names, see http://msdn.microsoft.com/en-us/library/8tfzyc64.aspx
cpp
QDate dateEightDaysFromNow = QDate::currentDate().addDays(8);
fantom
date := Date.today + 8day
echo(date.day)
echo(date.dayOfYear)
echo(date.month.localeFull)
echo(date.weekday.localeFull)

Display the current date and time

Create a Date object representing the current date and time. Print it out.
If you can also do this without creating a Date object you can show that too.
ruby
puts DateTime.now
csharp
// Creating a variable first:
DateTime now = DateTime.Now;
Console.WriteLine(now);

// Without creating a variable:
Console.WriteLine(DateTime.Now);
cpp
QDate now = QDate::currentData();
qDebug() << now.toString();
time_t date = time(0);
cout << ctime(&date);
fantom
echo(DateTime.now)
OOP

Define a class

Declare a class named Greeter that takes a string on creation and greets using this string if you call the "greet" method.
ruby
class Greeter
def initialize(whom) @whom = whom end
def greet() puts "Hello, #{@whom}!" end
end

(Greeter.new("world")).greet()
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();
}
}
cpp
class Greeter
{
public:
Greeter(const std::string& whom);
void greet() const;

private:
std::string whom;
};

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

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

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

private:
initonly String^ whom;
};

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

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

void Greeter::greet()
{
Console::WriteLine(L"Hello, {0}", whom);
}
fantom
class Greeter
{
private Str whom
new make(Str whom) { this.whom = whom }
Void greet() { echo("Hello, $whom") }
}

Greeter("world").greet

Instantiate object with mutable state

Reimplement the Greeter class so that the 'whom' property or data member remains private but is mutable, and is provided with getter and setter methods. Invoke the setter to change the greetee, invoke 'greet', then use the getter in displaying the line, "I have just greeted {whom}.".

For example, if the greetee is changed to 'Tommy' using the setter, the 'greet' method would display:

Hello, Tommy!

The getter would then be used to display the line:

I have just greeted Tommy.
ruby
class Greeter
attr_accessor :whom
def initialize(whom) @whom = whom end
def greet() puts "Hello, #{@whom}!" end
end

greeter = Greeter.new("world") ; greeter.greet()

greeter.whom = 'Tommy' ; greeter.greet()
puts "I have just greeted %s" % greeter.whom
csharp
class Greeter
{
public string Name {get;set;}

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

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

// Driver
public static void Main()
{
var g = new Greeter("Dante");

g.Name = "Tommy";
g.Greet();
Console.Write("I have just greated {0}", g.Name);
}
}
cpp
#include <iostream>

using namespace std;

class Greeter {
string whom_;

public:
Greeter(const string &whom) : whom_(whom) {}

string get_whom() const {
return whom_;
}

void set_whom(const string &whom) {
whom_ = whom;
}

void greet() const {
cout << "Hello " << whom_ << "!" << endl;
}
};

int main()
{
Greeter greeter("world");
greeter.greet();
greeter.set_whom("Tommy");
greeter.greet();
cout << "I have just greeted " + greeter.get_whom() << "." << endl;
}
fantom
class Greeter
{
new make(Str whom) { this.whom = whom }
Void greet() { echo("Hello, $whom!") }
Str whom
}

greeter := Greeter("world")
greeter.greet
greeter.whom = "Tommy"
echo("I have just greeted ${greeter.whom}.")

Implement Inheritance Heirarchy

Implement a Shape abstract class which will form the base of an inheritance hierarchy that models 2D geometric shapes. It will have:

* A non-mutable 'name' property or data member set by derived or descendant classes at construction time
* A 'area' method intended to be overridden by derived or descendant classes ( double precision floating point return value)
* A 'print' method (also for overriding) will display the shape's name, area, and all shape-specific values

Two derived or descendant classes will be created:
* Circle    -> Constructor requires a '
radius' argument, and a 'circumference' method to be implemented  
* Rectangle -> Constructor requires '
length' and 'breadth' arguments, and a 'perimeter' method to be implemented 

Instantiate an object of each class, and invoke each objects '
print' method to show relevant details.
ruby
class Shape
def initialize(name="") @name = name end
end

class Circle < Shape
def initialize(radius) super("circle") ; @radius = radius end

def area() 3.14159 * @radius * @radius end
def circumference() 2 * 3.14159 * @radius end

def print()
puts "I am a #{@name} with ->"
puts "Radius: %.2f" % @radius
puts "Area: %.2f" % self.area()
puts "Circumference: %.2f\n" % self.circumference()
end

end

class Rectangle < Shape
def initialize(length, breadth) super("rectangle") ; @length = length ; @breadth = breadth end

def area() @length * @breadth end
def perimeter() 2 * @length + 2 * @breadth end

def print()
puts "I am a #{@name} with ->"
printf("Length, Width: %.2f, %.2f\n", @length, @breadth)
puts "Area: %.2f" % self.area()
puts "Perimeter: %.2f\n" % self.perimeter()
end
end

# ------

shapes = [Circle.new(4.2), Rectangle.new(2.7, 3.1), Rectangle.new(6.2, 2.6), Circle.new(17.3)]
shapes.each {|shape| shape.print}

csharp
// While abstract classes do exist in C#, it is most common to use
// an interface in this type of situation.
// It is a common idiom to prefix interface names with an I
public interface IShape {
string Name { get; }
double Area { get; }
void Print();
}

public class Circle : IShape {

private double Radius { get; set; }
public Circle(double radius) {
Name = "Circle";
Radius = radius;
}

public string Name { get; private set; }
public double Area {
get {
return Math.PI * Radius * Radius;
}
}
public double Circumference {
get {
return Math.PI * (Radius + Radius);
}
}

public void Print() {
Console.WriteLine( " Name: {0}\n Area: {1}\n Circumference: {2}\n Radius: {3}",
this.Name,
this.Area,
this.Circumference,
this.Radius
);
}
}

public class Rectangle : IShape {

private double Length { get; set; }
private double Breadth { get; set; }
public Rectangle(double length, double breadth) {
Name = "Rectangle";
Length = length;
Breadth = breadth;
}

public string Name { get; private set; }
public double Area {
get {
return Length * Breadth;
}
}
public double Perimeter {
get {
return (Length * 2) + (Breadth * 2 );
}
}

public void Print() {
Console.WriteLine( " Name: {0}\n Area: {1}\n Perimeter: {2}\n Length: {3}\n Breadth: {4}",
this.Name,
this.Area,
this.Perimeter,
this.Length,
this.Breadth
);
}
}

// Driver
public class InheritanceHeirarchy {
public static void _Main() {
var c = new Circle(2.1);
c.Print();

Console.WriteLine();

var r = new Rectangle(2.2, 3.3);
r.Print();
}
}
cpp
#include <string>
#include <iostream>

using namespace std;

static const double PI = 3.141592;

class Shape {
protected:
string name_;
public:
Shape(const string& name) : name_(name) { }
virtual double area() const = 0;
virtual void print() const = 0;
};

class Circle : public Shape {
double radius_;
public:
Circle(double radius) : Shape("circle"), radius_(radius) { }
double area() const {
return PI * radius_ * radius_;
}
void print() const {
cout << "A " << name_ << " with radius " << radius_ << ", area "
<< area() << " and circumference " << circumference() << "."
<< endl;
}
double circumference() const {
return 2 * PI * radius_;
}
};

class Rectangle : public Shape {
double length_;
double breadth_;
public:
Rectangle(double length, double breadth) :
Shape("rectangle"), length_(length), breadth_(breadth) { }
double area() const {
return length_ * breadth_;
}
void print() const {
cout << "A " << name_ << " with length " << length_ << ", breadth "
<< breadth_ << ", area " << area() << " and perimeter "
<< perimeter() << "." << endl;
}
double perimeter() const {
return 2 * length_ + 2 * breadth_;
}
};

int main(int argc, char *argv[])
{
Circle circle(4);
circle.print();
Rectangle rectangle(2, 5.5);
rectangle.print();
}
fantom
abstract class Shape
{
const Str name
new make(Str name) { this.name = name }
abstract Float area()
abstract Void print()
}

class Circle : Shape
{
private Float radius

new make(Float radius) : super("circle") { this.radius = radius }
Float circumference() { return 2 * Float.pi * radius }
override Float area() { return Float.pi * radius.pow(2.0f) }
override Void print()
{
echo("I am a $name with radius $radius, area $area
and circumference $circumference")
}
}

class Rectangle : Shape
{
private Float length
private Float breadth

new make(Float length, Float breadth) : super("rectangle")
{
this.length = length
this.breadth = breadth
}
Float perimeter() { return 2 * (length + breadth) }
override Float area() { return length * breadth }
override Void print()
{
echo("I am a $name with length $length, breadth $breadth,
area $area and perimeter $perimeter")
}
}


circle := Circle(4.0f)
circle.print
rectangle := Rectangle(2.0f, 5.5f)
rectangle.print
XML

Process an XML document

Given the XML Document:

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

Print out the total cost of the items, e.g. $14.50
ruby
#!/usr/bin/env ruby

# needed to parse xml
require 'rexml/document'

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

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

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

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

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

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

# pad the output with the proper number of trailing 0's
printf "$%.2f\n", total
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);
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;
fantom
sum := 0.0
root := XParser(File(`shop.xml`).in).parseDoc.root
if (root.name == "shopping")
{
root.elems.each
{
if (it.name == "item")
{
quantity := Int.fromStr(it.get("quantity"))
price := Decimal.fromStr(it.get("price"))
sum += quantity * price;
}
}
}
echo("\$$sum")

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="bread" quantity="3" price="2.50" />
  <item name="milk" quantity="2" price="3.50" />
</shopping>
ruby
# gem install builder
require 'builder'

xml = Builder::XmlMarkup.new
xml.shopping do
xml.item(:name => "bread", :quantity => 3, :price => "2.50")
xml.item(:name => "milk", :quantity => 2, :price => "3.50")
end
xml
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>");
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;
fantom
sum := 0.0
rows := CsvInStream(File(`shop.csv`).in).readAllRows

doc := XDoc()
doc.root = XElem("shopping")
{
root := it
rows.each |Str[] row|
{
root.add(XElem("item")
{
XAttr("name", row[0]),
XAttr("quantity", row[1]),
XAttr("price", row[2])
})
}
}

os := File(`shop.xml`).out
doc.write(os)
os.close

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.

ruby
135.gcd(30)
# => 15
csharp
public static int gcd(int a, int b)
{
if (b == 0)
return a;
else
return gcd(b, a % 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;
}
fantom
gcd := |Int a, Int b -> Int| {
pair := [a, b].sort
while (pair.first != 0)
pair.set(1, pair.last % pair.first).swap(0, 1)
return pair.last
}
echo(gcd(12, 8)) // a>b, result == 4
echo(gcd(1029, 1071)) // a<b, result == 21