All Problems
Output a string to the console
Write the string
"Hello World!" to STDOUT
ruby
puts "Hello World!"
$stdout<<"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");
groovy
println "Hello World!"
Retrieve a string containing ampersands from the variables in a url
My PHP script first does a query to obtain customer info for a form. The form has first name and last name fields among others. The customer has put entries such as
The script variable for first name $_REQUEST
I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like
Of course this fails for the same reasons. What is a better approach?
"Ron & Jean" in the first name field in the database. Then the edit form script is called with variables such as
"http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith".
The script variable for first name $_REQUEST
['firstname'] never gets beyond the "Ron" value because of the ampersand in the data.
I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like
"http://myserver/custinfo/edit.php?mode=view&fname="Ronxxnbsp;xxamp;xxnbsp;Jean"&lname=SMITH". (sorry I had to add the xx to replace the ampersand or it didn't display meaningful url contents the browser sees.)
Of course this fails for the same reasons. What is a better approach?
ruby
gem 'uri-query_params'
require 'uri/query_params'
url = URI("http://myserver.com/custinfo/edit.php?mode=view&fname=Ron%20&%20Jean&lname=Smith")
url.query_params['fname']
# => "Ron & Jean"
require 'uri/query_params'
url = URI("http://myserver.com/custinfo/edit.php?mode=view&fname=Ron%20&%20Jean&lname=Smith")
url.query_params['fname']
# => "Ron & Jean"
url = "http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith"
url = URI.parse(URI.encode(url))
url = URI.parse(URI.encode(url))
erlang
% encode ampersand in your string using %XX where XX is hex code for ampersand
% optionally encode spaces for completeness sake to keep URL solid
URL = "http://myserver.com/custinfo/edit.php?mode=view&fname=Ron%20%26%20Jean&lname=Smith",
{_, Query} = string:tokens(URL, "?"),
KeyValuePairs = string:tokens(Query, "&"),...
% optionally encode spaces for completeness sake to keep URL solid
URL = "http://myserver.com/custinfo/edit.php?mode=view&fname=Ron%20%26%20Jean&lname=Smith",
{_, Query} = string:tokens(URL, "?"),
KeyValuePairs = string:tokens(Query, "&"),...
cpp
QUrl url("http://myserver.com/custinfo/edit.php");
url.addQueryItem("mode", "view");
url.addQueryItem("fname", "Ron & Jean");
url.addQueryItem("lname", "Smith");
QByteArray encodedUrl = url.toEncoded();
url.addQueryItem("mode", "view");
url.addQueryItem("fname", "Ron & Jean");
url.addQueryItem("lname", "Smith");
QByteArray encodedUrl = url.toEncoded();
groovy
// Given the nature of the question text, I am assuming the question
// is how to produce a application/x-www-form-urlencoded compliant string
def basename = 'http://somedomain.com/somebase/'
def parameter = 'Bart & Lisa'
// equivalent to php
println basename + URLEncoder.encode(parameter)
// recommended approach is to specify encoding
println basename + URLEncoder.encode(parameter, "UTF-8")
// is how to produce a application/x-www-form-urlencoded compliant string
def basename = 'http://somedomain.com/somebase/'
def parameter = 'Bart & Lisa'
// equivalent to php
println basename + URLEncoder.encode(parameter)
// recommended approach is to specify encoding
println basename + URLEncoder.encode(parameter, "UTF-8")
string-wrap
Wrap the string
Expected output:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t
> he 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 qui
> ck 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 o
> ver 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 "> "
Expected output:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t
> he 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 qui
> ck 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 o
> ver the lazy dog. The quick brown fox jumps over the lazy dog.
ruby
str = "The quick brown fox jumps over the lazy dog. " * 10
outarr = str.scan(/[^ ].{0,76}/)
outarr.each{ |line| puts "> %s" % line }
outarr = str.scan(/[^ ].{0,76}/)
outarr.each{ |line| puts "> %s" % line }
erlang
wrapper(String, Times, Length) ->
StrList = lists:reverse(formatter(string:copies(String, Times), Length, [])),
lists:foreach(fun(Str) -> io:format("~p~n", [Str]) end, StrList).
formatter([], _Length, Acc) -> Acc;
formatter(String, Length, Acc) when length(String) > Length - 1->
{Head, Tail} = lists:split(Length - 1, String),
formatter(string:strip(Tail), Length, [[$>, $ | Head] | Acc]);
formatter(String, Length, Acc) ->
formatter([], Length, [[$>, $ | String] | Acc]).
StrList = lists:reverse(formatter(string:copies(String, Times), Length, [])),
lists:foreach(fun(Str) -> io:format("~p~n", [Str]) end, StrList).
formatter([], _Length, Acc) -> Acc;
formatter(String, Length, Acc) when length(String) > Length - 1->
{Head, Tail} = lists:split(Length - 1, String),
formatter(string:strip(Tail), Length, [[$>, $ | Head] | Acc]);
formatter(String, Length, Acc) ->
formatter([], Length, [[$>, $ | String] | Acc]).
cpp
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
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)
{
for (int offset = 0; offset < str.size(); offset += width)
os << prefix << str.substr(offset, width) << endl;
}
int main()
{
stringstream input;
rep(input, "The quick brown fox jumps over the lazy dog. ", 10);
wrap(cout, input.str(), "> ", 78);
}
#include <sstream>
#include <string>
using namespace std;
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)
{
for (int offset = 0; offset < str.size(); offset += width)
os << prefix << str.substr(offset, width) << endl;
}
int main()
{
stringstream input;
rep(input, "The quick brown fox jumps over the lazy dog. ", 10);
wrap(cout, input.str(), "> ", 78);
}
groovy
'The quick brown fox jumps over the lazy dog. '.multiply(10).split('(?<=\\G.{76})').each{println '> ' + it}
st = "The quick brown fox jumps over the lazy dog. " * 10
width = 76
while(st){
(first, st) = st.length() > width? [st[0..width], st[(width+1)..-1].trim()] : [st, null]
println "> $first"
}
width = 76
while(st){
(first, st) = st.length() > width? [st[0..width], st[(width+1)..-1].trim()] : [st, null]
println "> $first"
}
Define a string containing special characters
Define the literal string
"\#{'}${"}/"
ruby
special = '\#{\'}${"}/'
erlang
Special = "\\#{'}\${\"}/",
cpp
std::string special = "\\#{'}${\"}/";
String^ special = L"\\#{'}${\"}/";
groovy
special = "\\#{'}\${\"}/"
special = '\\#{\'}${"}/'
special = /\#{'}${'$'}{"}\//
Define a multiline string
Define the string:
"This
Is
A
Multiline
String"
ruby
text = <<"HERE"
This
Is
A
Multiline
String
HERE
This
Is
A
Multiline
String
HERE
text = "This\nIs\nA\nMultiline\nString"
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";
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"
ruby
puts "#{a}+#{b}=#{a+b}"
puts "#{a}+#{b}=%s" % (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;
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"
ruby
puts "reverse me".reverse
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());
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"
ruby
reversed = text.split.reverse.join(' ')
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();
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.
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")
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")
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);
}
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".
ruby
puts " hello ".strip
" hello ".strip!
erlang
Trimmed = string:strip(S),
cpp
String^ s = " hello "; String^ trimmed = s->Trim();
groovy
assert "hello" == " hello ".trim()
Simple substitution cipher
Take a string and return the ROT13 and ROT47 (Check Wikipedia) version of the string.
For example:
String is: Hello World #123
ROT13 returns: Uryyb Jbeyq #123
ROT47 returns: w6==@ (@C=5 R`ab
For example:
String is: Hello World #123
ROT13 returns: Uryyb Jbeyq #123
ROT47 returns: w6==@ (@C=5 R`ab
ruby
rot13 = "Hello World #123".tr!("A-Za-z", "N-ZA-Mn-za-m")
rot47 = "Hello World #123".tr!("\x21-\x7e", "\x50-\x7e\x21-\x4f")
rot47 = "Hello World #123".tr!("\x21-\x7e", "\x50-\x7e\x21-\x4f")
erlang
rot13(Str) ->
lists:map(fun(A) ->
if
A >= $A, A =< $Z -> ((A - $A + 13) rem 26) + $A;
A >= $a, A =< $z -> ((A - $a + 13) rem 26) + $a;
true -> A
end
end, Str).
rot47(Str) ->
lists:map(fun(A) ->
if
A >= $!, A =< $~ ->
((A - $! + 47) rem 94) + $!;
true -> A
end
end, Str).
lists:map(fun(A) ->
if
A >= $A, A =< $Z -> ((A - $A + 13) rem 26) + $A;
A >= $a, A =< $z -> ((A - $a + 13) rem 26) + $a;
true -> A
end
end, Str).
rot47(Str) ->
lists:map(fun(A) ->
if
A >= $!, A =< $~ ->
((A - $! + 47) rem 94) + $!;
true -> A
end
end, Str).
cpp
#include <algorithm>
#include <iostream>
#include <cctype>
using namespace std;
int rot13(int c) {
if (!isalpha(c)) {
return c;
} else {
char start = islower(c) ? 'a' : 'A';
return ((c - start) + 13) % 26 + start;
}
}
int rot47(int c) {
if (c < 33 || c > 126) {
return c;
} else {
return ((c - 33) + 47) % 94 + 33;
}
}
int main(int argc, char **argv) {
for (int i = 0; i < argc; ++i) {
string original = argv[i];
string rot13enc = original;
transform(original.begin(), original.end(), rot13enc.begin(), rot13);
string rot47enc = original;
transform(original.begin(), original.end(), rot47enc.begin(), rot47);
cout << "original: " << original << endl
<< "rot 13: " << rot13enc << endl
<< "rot 47: " << rot47enc << endl;
}
return 0;
}
#include <iostream>
#include <cctype>
using namespace std;
int rot13(int c) {
if (!isalpha(c)) {
return c;
} else {
char start = islower(c) ? 'a' : 'A';
return ((c - start) + 13) % 26 + start;
}
}
int rot47(int c) {
if (c < 33 || c > 126) {
return c;
} else {
return ((c - 33) + 47) % 94 + 33;
}
}
int main(int argc, char **argv) {
for (int i = 0; i < argc; ++i) {
string original = argv[i];
string rot13enc = original;
transform(original.begin(), original.end(), rot13enc.begin(), rot13);
string rot47enc = original;
transform(original.begin(), original.end(), rot47enc.begin(), rot47);
cout << "original: " << original << endl
<< "rot 13: " << rot13enc << endl
<< "rot 47: " << rot47enc << endl;
}
return 0;
}
groovy
char rot13(s) {
char c = s
switch(c) {
case 'A'..'M': case 'a'..'m': return c+13
case 'N'..'Z': case 'n'..'z': return c-13
default : return c
}
}
String.metaClass.rot13 = {
delegate.collect(this.&rot13).join()
}
from = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
to = 'PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO'
String.metaClass.rot47 = {
delegate.collect{ int found = from.indexOf(it); found < 0 ? it : to[found] }.join()
}
assert 'Hello World #123'.rot13() == 'Uryyb Jbeyq #123'
assert 'Hello World #123'.rot47() == 'w6==@ (@C=5 R`ab'
char c = s
switch(c) {
case 'A'..'M': case 'a'..'m': return c+13
case 'N'..'Z': case 'n'..'z': return c-13
default : return c
}
}
String.metaClass.rot13 = {
delegate.collect(this.&rot13).join()
}
from = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
to = 'PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO'
String.metaClass.rot47 = {
delegate.collect{ int found = from.indexOf(it); found < 0 ? it : to[found] }.join()
}
assert 'Hello World #123'.rot13() == 'Uryyb Jbeyq #123'
assert 'Hello World #123'.rot47() == 'w6==@ (@C=5 R`ab'
Make a string uppercase
Transform
"Space Monkey" into "SPACE MONKEY"
ruby
uppper = text.upcase
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);
groovy
println "Space Monkey".toUpperCase()
Make a string lowercase
Transform
"Caps ARE overRated" into "caps are overrated"
ruby
"Caps ARE overRated".downcase
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();
groovy
println "Caps ARE overRated".toLowerCase()
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) * ' '
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();
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
ruby
# the hypotenuse sqrt(x**2+y**2)
distance = Math.hypot(x2-x1,y2-y1)
distance = Math.hypot(x2-x1,y2-y1)
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);
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
ruby
42.to_s.rjust(8,"0")
"%08d" % 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;
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 "
ruby
1024.to_s.ljust(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;
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
ruby
(7.0/8.0*100).round/100.0
(7.0/8.0).round(2)
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;
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"
ruby
73.to_s.rjust(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;
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
ruby
randomInt = rand(200-100+1)+100;
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();
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.
ruby
srand(12345)
first = (1..5).collect {rand}
srand(12345)
second = (1..5).collect {rand}
puts first == second
first = (1..5).collect {rand}
srand(12345)
second = (1..5).collect {rand}
puts first == second
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);
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]+/
ruby
puts "ok" if ("Hello"=~/^[A-Z][a-z]+$/)
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;
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/
ruby
puts $1 if "one two three"=~/^one (.*) three$/
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;
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+/
ruby
puts "ok" if (text=~/\d+/)
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");
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+)/
ruby
list = text.scan(/\((\w+)\):(\d+)/).collect{|x| x.join}
list=[]
text.scan(/\((\w+)\):(\d+)/) {
list << $1+$2
}
text.scan(/\((\w+)\):(\d+)/) {
list << $1+$2
}
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();
}
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 the first regex match in a string with a static string
Transform
"Red Green Blue" into "R*d Green Blue" by replacing /e/ with "*"
ruby
p "Red Green Blue".sub(/e/,'*')
erlang
{ok, Replaced, _} = regexp:sub("Red Green Blue", "e", "*"),
re:replace("Red Green Blue", "e", "*", [{return, list}]).
cpp
String^ Replaced = (gcnew Regex("e"))->Replace("Red Green Blue", "*", 1);
groovy
replaced = "Red Green Blue".replaceFirst("e", "*")
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")
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");
groovy
replaced = text.replaceAll(/se\w+/,"X")
Replace all regex matches in a string with a dynamic string
Transform
"The {Quick} Brown {Fox}" into "The kciuQ Brown xoF" by reversing words in braces using the regex /\{(\w+)\}/.
ruby
"The {Quick} Brown {Fox}".gsub(/\{(\w+)\}/) {|s| s[1..-2].reverse }
erlang
% Erlang regular expressions lack both group capture and backreferences, thus this problem is not directly
% solvable. Presented solution is close, but not on-spec
String = "The {Quick} Brown {Fox}",
{match, FieldList} = regexp:matches(String, "\{([A-Za-z0-9_]+)\}"),
NewString = lists:foldl(fun ({Start, Length}, S) -> replstr(S, lists:reverse(string:substr(S, Start, Length)), Start) end, String, FieldList),
% solvable. Presented solution is close, but not on-spec
String = "The {Quick} Brown {Fox}",
{match, FieldList} = regexp:matches(String, "\{([A-Za-z0-9_]+)\}"),
NewString = lists:foldl(fun ({Start, Length}, S) -> replstr(S, lists:reverse(string:substr(S, Start, Length)), Start) end, String, FieldList),
cpp
String^ Replaced = (gcnew Regex("{(\\w+)}"))->Replace("The {Quick} Brown {Fox}", gcnew MatchEvaluator(&RegRep::RepGroup));
String^ Replaced = Regex::Replace("The {Quick} Brown {Fox}", "{(\\w+)}", gcnew MatchEvaluator(&RegRep::RepGroup));
groovy
replaced = "The {Quick} Brown {Fox}".replaceAll(/\{(\w+)\}/, { full, word -> word.reverse() } )
Define an empty list
Assign the variable
"list" to a list with no elements
ruby
list = []
list = Array.new
erlang
List = [],
cpp
Generic::List<String^>^ list = gcnew Generic::List<String^>();
std::list<std::string> list;
groovy
list = []
// if a special kind of list is required
list = new LinkedList() // java style
LinkedList list = [] // statically typed
// using 'as' operator
list = [] as java.util.concurrent.CopyOnWriteArrayList
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]
ruby
list = ['One', 'Two', 'Three', 'Four', 'Five']
list = %w(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";
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"
ruby
string = fruit.join(', ')
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, ", ");
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(
[]) = ""
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
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
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);
}
}
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]]
ruby
common = [] ; [4, 5].each {|n| ['a', 'b', 'c'].each {|l| common << [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;
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"]
ruby
foo = ['andrew', 'bob', 'chris', 'bob']
foo.inject({}) {|h,v| h[v]=h[v].to_i+1; h}.reject{|k,v| v==1}.keys
foo.inject({}) {|h,v| h[v]=h[v].to_i+1; h}.reject{|k,v| v==1}.keys
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;
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')
ruby
list = ['One', 'Two', 'Three', 'Four', 'Five']
list[2]
list[2]
['One', 'Two', 'Three', 'Four', 'Five'].fetch(2)
list = ['One', 'Two', 'Three', 'Four', 'Five']
list.at(2)
list.at(2)
['One', 'Two', 'Three', 'Four', 'Five'][2] # <= note the [2] at end of array
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];
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')
ruby
['Red', 'Green', 'Blue'][-1]
['Red', 'Green', 'Blue'].at(-1)
['Red', 'Green', 'Blue'].last
['Red', 'Green', 'Blue'].fetch(-1)
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();
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?
ruby
common = (beans.intersection(colors)).to_a
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);
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.
ruby
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
p ages.uniq
p ages.uniq
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
ages.uniq!
p ages
ages.uniq!
p ages
ages = (Set.new [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]).to_a
p ages
p ages
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"));
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]
ruby
['Apple', 'Banana', 'Carrot'].shift
fruit.delete_at(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);
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
ruby
list = ['Apple', 'Banana', 'Carrot']
list.delete_at(-1)
list.delete_at(-1)
list = ['Apple', 'Banana', 'Carrot']
list.pop
list.pop
erlang
Result = init(List),
Result = take(length(List) - 1, List),
Result = lists:reverse(tl(lists:reverse(List))),
cpp
fruit->RemoveAt(fruit->Count - 1);
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"]
ruby
items = ["apple", "orange", "grapes", "bananas"]
items << first = items.shift
# items is rotated
# first contains the first value in the list
items << first = items.shift
# items is rotated
# first contains the first value in the list
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());
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.
ruby
first = ['Bruce', 'Tommy Lee', 'Bruce']; last = ['Willis', 'Jones', 'Lee']; years = [1955, 1946, 1940]
result = first.zip(last, years)
result = first.zip(last, years)
first = ['Bruce', 'Tommy Lee', 'Bruce']; last = ['Willis', 'Jones', 'Lee']; years = [1955, 1946, 1940]
result = [first, last, years].transpose
result = [first, last, years].transpose
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));
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'.
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
puts "Deck %s \'Ace of Hearts\'" % if cards.include?(['h', 'A']) then "contains" else "does not contain" end
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;
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]
ruby
["ox", "cat", "deer", "whale"].map{|i| i.length}
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(); });
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.
ruby
now=Time.now
things=["hello", 25, 3.14, now]
numbers=things.select{|i| i.is_a? Numeric}
others=things-numbers
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}
things=["hello", 25, 3.14, now]
numbers, others=things.partition{|i| i.is_a? Numeric}
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'
}
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]
Test if a condition holds for all items of a list
Given a list, test if a certain logical condition (i.e. predicate) holds for all items of the list.
ruby
[2, 3, 4].all? { |x| x > 1 }
erlang
Result = lists:all(Pred, List).
cpp
template <typename InputIterator, typename Predicate>
bool match_all(InputIterator first, InputIterator last, Predicate pred)
{
return find_if(first, last, !pred(_1)) == last;
}
bool match_all(InputIterator first, InputIterator last, Predicate pred)
{
return find_if(first, last, !pred(_1)) == last;
}
groovy
[2,3,4].every{it > 1}
Test if a condition holds for any items of a list
Given a list, test if a certain logical condition (i.e. predicate) holds for any items of the list.
ruby
[2, 3, 4].any? { |x| x > 3 }
erlang
Result = lists:any(Pred, List).
cpp
template <typename InputIterator, typename Predicate>
bool match_any(InputIterator first, InputIterator last, Predicate pred)
{
return find_if(first, last, pred) != last;
}
bool match_any(InputIterator first, InputIterator last, Predicate pred)
{
return find_if(first, last, pred) != last;
}
groovy
[2,3,4].any{it > 3}
Define an empty map
ruby
map = {}
erlang
Map = dict:new(),
Map = orddict:new(),
Map = gb_trees:empty(),
Map = ets:new(the_map_name, [set, private, {keypos, 1}]),
cpp
Hashtable^ hash = gcnew Hashtable;
Generic::Dictionary<String^, String^>^ dict = gcnew Generic::Dictionary<String^, String^>();
std::map<int, std::string> m;
groovy
def map = [:]
Map map = new HashMap();
Define an unmodifiable empty map
ruby
map = {}.freeze
erlang
% Erlang data structures are immutable - updating a 'map' sees a modified copy created
Map = dict:new(),
% Erlang data structures are immutable - updating a 'map' sees a modified copy created
Map = dict:new(),
cpp
const std::map<T1,T2> immutable_map_instance_of_type_t1_to_t2;
groovy
empty = Collections.EMPTY_MAP
map = [:].asImmutable()
def empty = MapUtils.EMPTY_SORTED_MAP
def empty = ImmutableMap.of()
Define an initial map
Define the map
{circle:1, triangle:3, square:4}
ruby
shapes = {'circle'=>1, 'triangle'=>3, 'square'=>4}
shapes = Hash['circle', 1, 'triangle', 3, 'square', 4]
shapes = { :circle => 1, :triangle => 3, :square => 4 }
erlang
Map = dict:from_list([{circle, 1}, {triangle, 3}, {square, 4}]),
Map0 = dict:new(),
% Erlang variables are 'single-assignment' i.e. they cannot be reassigned
Map1 = dict:store(circle, 1, Map0),
Map2 = dict:store(triangle, 3, Map1),
Map3 = dict:store(square, 4, Map2),
% Erlang variables are 'single-assignment' i.e. they cannot be reassigned
Map1 = dict:store(circle, 1, Map0),
Map2 = dict:store(triangle, 3, Map1),
Map3 = dict:store(square, 4, Map2),
Map0 = gb_trees:empty(),
Map1 = gb_trees:enter(circle, 1, Map0),
Map2 = gb_trees:enter(triangle, 3, Map1),
Map3 = gb_trees:enter(square, 4, Map2),
Map1 = gb_trees:enter(circle, 1, Map0),
Map2 = gb_trees:enter(triangle, 3, Map1),
Map3 = gb_trees:enter(square, 4, Map2),
Map = gb_trees:from_orddict(lists:keysort(1, [{circle, 1}, {triangle, 3}, {square, 4}])),
Map = ets:new(the_map_name, [ordered_set, private, {keypos, 1}]),
ets:insert(Map, [{circle, 1}, {triangle, 3}, {square, 4}]),
ets:insert(Map, [{circle, 1}, {triangle, 3}, {square, 4}]),
cpp
Hashtable^ shapes = gcnew Hashtable;
shapes->Add("circle", 1);
shapes->Add("triangle", 3);
shapes->Add("square", 4);
shapes->Add("circle", 1);
shapes->Add("triangle", 3);
shapes->Add("square", 4);
Generic::Dictionary<String^, int>^ shapes = gcnew Generic::Dictionary<String^, int>();
shapes->Add("circle", 1);
shapes->Add("triangle", 3);
shapes->Add("square", 4);
shapes->Add("circle", 1);
shapes->Add("triangle", 3);
shapes->Add("square", 4);
map<string, int> shapes;
shapes["circle"] = 1;
shapes["triangle"] = 3;
shapes["square"] = 4;
shapes["circle"] = 1;
shapes["triangle"] = 3;
shapes["square"] = 4;
groovy
shapes = [circle:1, triangle:3, square:4]
// if you require a specific type of map ...
LinkedHashMap shapes1 = [circle:1, triangle:3, square:4]
Properties shapes2 = [circle:1, triangle:3, square:4]
TreeMap shapes3 = [circle:1, triangle:3, square:4]
shapes4 = [circle:1, triangle:3, square:4] as ConcurrentHashMap // as variation
LinkedHashMap shapes1 = [circle:1, triangle:3, square:4]
Properties shapes2 = [circle:1, triangle:3, square:4]
TreeMap shapes3 = [circle:1, triangle:3, square:4]
shapes4 = [circle:1, triangle:3, square:4] as ConcurrentHashMap // as variation
Check if a key exists in a map
Given a map pets
{joe:cat,mary:turtle,bill:canary} print "ok" if an pet exists for "mary"
ruby
puts "ok" if map.has_key?('mary')
puts "ok" if map['mary'] # Only works if map entry can't be nil or false
erlang
dict:is_key(mary, Pets) andalso begin io:format("ok~n"), true end.
IsMember = ets:member(Pets, mary), if (IsMember) -> io:format("ok~n") ; true -> false end.
case gb_trees:lookup(mary, Pets) of none -> false ; _ -> io:format("ok~n") end.
cpp
if (pets->ContainsKey("mary")) Console::WriteLine("ok");
if (pets.find("mary") != pets.end()){
std::cout << "ok" << std::endl;
}
std::cout << "ok" << std::endl;
}
if (pets.count("mary") > 0)
cout << "ok" << endl;
cout << "ok" << endl;
groovy
pets = [joe:'cat', mary:'turtle', bill:'canary']
if(pets.containsKey('mary')) println 'ok'
if(pets.containsKey('mary')) println 'ok'
pets = [joe:'cat', mary:'turtle', bill:'canary']
if(pets.mary) println 'ok'
if(pets.mary) println 'ok'
Retrieve a value from a map
Given a map pets
{joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
ruby
puts map['joe']
erlang
dict:is_key(joe, Pets) andalso begin io:format("~w~n", [dict:fetch(joe, Pets)]), true end.
case dict:find(joe, Pets) of error -> false ; {ok, Pet} -> io:format("~w~n", [Pet]) end.
IsMember = ets:member(Pets, joe), if (IsMember) -> io:format("~w~n", [ets:lookup_element(Pets, joe, 2)]) ; true -> false end.
case ets:match(Pets, {joe, '$1'}) of [] -> false ; [[Pet]] -> io:format("~w~n", [Pet]) end.
case gb_trees:lookup(joe, Pets) of none -> false ; {value, Pet} -> io:format("~w~n", [Pet]) end.
cpp
if (pets->ContainsKey("joe")) Console::WriteLine(pets["joe"]);
cout << pets["joe"] << endl;
groovy
pets = [joe:'cat', mary:'turtle', bill:'canary']
assert pets['joe'] == 'cat'
assert pets['joe'] == 'cat'
assert pets.joe == 'cat'
Add an entry to a map
Given an empty pets map, add the mapping from
"rob" to "dog"
ruby
pets['rob']='dog'
erlang
Pets1 = dict:store(rob, dog, Pets0).
ets:insert(Pets, {rob, dog}).
Pets1 = gb_trees:enter(rob, dog, Pets0).
cpp
pets->Add("rob", "dog");
pets["rob"] = "dog";
groovy
pets['rob'] = 'dog'
pets.rob = 'dog'
pets.put('rob', 'dog')
Remove an entry from a map
Given a map pets
{joe:cat,mary:turtle,bill:canary} remove the mapping for "bill" and print "canary"
ruby
puts map.delete :bill
erlang
Pet = dict:fetch(bill, Pets0), Pets1 = dict:erase(bill, Pets0), io:format("~w~n", [Pet]),
Pet = ets:lookup_element(Pets, bill, 2), ets:delete(Pets, bill), io:format("~w~n", [Pet]),
{value, Pet} = gb_trees:lookup(bill, Pets0), Pets1 = gb_trees:delete(bill, Pets0), io:format("~w~n", [Pet]),
cpp
if (pets->ContainsKey("bill"))
{
String^ value = safe_cast<String^>(pets["bill"]); pets->Remove("bill");
Console::WriteLine("{0}", value);
}
{
String^ value = safe_cast<String^>(pets["bill"]); pets->Remove("bill");
Console::WriteLine("{0}", value);
}
groovy
pets = [joe:'cat', mary:'turtle', bill:'canary']
println pets.remove('bill')
println pets.remove('bill')
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.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}
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}
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;
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
ruby
lengths = {}
list.each do |x|
len = x.size
lengths[len] = (lengths[len] || [])
lengths[len] << x
end
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 }
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);
}
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.
ruby
if (name=='Bob')
puts "Hello, Bob!"
end
puts "Hello, Bob!"
end
puts "Hello, Bob!" if name=='Bob'
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;
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"
ruby
if (age > 42)
puts "You are old"
else
puts "You are young"
end
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"}"
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"));
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)
ruby
if age > 84
puts "You are really ancient"
elsif age > 30
puts "You are middle-aged"
else
puts "You are young"
end
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
when age > 84 then puts "You are really ancient"
when age > 30 then puts "You are middle-aged"
else puts "You are young"
end
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;
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
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) }
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) }
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();
}
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.
ruby
x=1
while x < 150
puts x
x <<= 1
end
while x < 150
puts x
x <<= 1
end
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;
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"
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
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
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(",")
games = Enumerator.new do |yielder|
yielder.yield rand(6) + 1 while true
end
puts games.take_while {|roll| roll != 6}.join(",")
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();
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"
ruby
puts "Hello"*5
5.times { print "Hello" }
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");
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!"
ruby
10.downto(1) { |n| print n, " .. " }
puts "Liftoff!"
puts "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!");
groovy
10.downto(1) { print it + " .. " }
println "Liftoff!"
println "Liftoff!"
Read the contents of a file into a string
ruby
file = File.new("Solution108.rb")
whole_file = file.read
whole_file = file.read
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");
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
ruby
File.open("Solution103.rb").each_with_index { |line, count|
puts "#{count} > #{line}
}
puts "#{count} > #{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);
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
ruby
File.new("a_file", "w") << "some text"
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!");
}
groovy
file.delete()
file << 'some text'
file << 'some text'
file.text = 'some text'
Append to a file
ruby
file = File.new('/tmp/test.txt', 'a+') ; file.puts 'This line appended to file!!' ; file.close()
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!");
}
groovy
file << 'some text'
Process each file in a directory
ruby
directory = '/tmp' ; Dir.foreach(directory) {|file| puts "#{file}"}
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);
groovy
dir.eachFile{ f -> process(f) }
Process each file in a directory recursively
ruby
def procdir(dirname)
Dir.foreach(dirname) do |dir|
dirpath = dirname + '/' + dir
if File.directory?(dirpath) then
if dir != '.' && dir != '..' then
puts "DIRECTORY: #{dirpath}" ; procdir(dirpath)
end
else
puts "FILE: #{dirpath}"
end
end
end
# ------
procdir('/tmp')
Dir.foreach(dirname) do |dir|
dirpath = dirname + '/' + dir
if File.directory?(dirpath) then
if dir != '.' && dir != '..' then
puts "DIRECTORY: #{dirpath}" ; procdir(dirpath)
end
else
puts "FILE: #{dirpath}"
end
end
end
# ------
procdir('/tmp')
erlang
filelib:fold_files(Directory, ".*", true, fun (FileOrDirPath, Acc) -> Worker(FileOrDirPath), Acc end, []).
process_dir(Directory, Worker).
cpp
void processFile(String^ filename) { Console::WriteLine("{0}", filename); }
void processDirectory(String^ dirname)
{
for each(String^ filename in IO::Directory::GetFiles(dirname)) processFile(filename);
for each(String^ subdirname in IO::Directory::GetDirectories(dirname)) processDirectory(subdirname);
}
int main()
{
processDirectory("c:\\");
}
void processDirectory(String^ dirname)
{
for each(String^ filename in IO::Directory::GetFiles(dirname)) processFile(filename);
for each(String^ subdirname in IO::Directory::GetDirectories(dirname)) processDirectory(subdirname);
}
int main()
{
processDirectory("c:\\");
}
groovy
dir.eachFileRecurse{ 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.
ruby
# With timezone info
puts Time.parse('2008-05-06 13:29')
puts Time.parse('2008-05-06 13:29')
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);
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 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
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
cpp
QDate dateEightDaysFromNow = QDate::currentDate().addDays(8);
groovy
use (TimeCategory) {
eight_days_time = 1.week.from.now + 1.day
}
println eight_days_time[DAY_OF_MONTH]
println eight_days_time.format('d') // alternative to above
println eight_days_time[DAY_OF_YEAR]
println eight_days_time.format('MMMM')
println eight_days_time.format('EEEE')
eight_days_time = 1.week.from.now + 1.day
}
println eight_days_time[DAY_OF_MONTH]
println eight_days_time.format('d') // alternative to above
println eight_days_time[DAY_OF_YEAR]
println eight_days_time.format('MMMM')
println eight_days_time.format('EEEE')
Display a date in different locales
Display a language/locale friendly version of New Year's Day for 2009 for several languages/locales. E.g. for languages English, French, German, Italian, Dutch the output might be something like:
Thursday, January 1, 2009
jeudi 1 janvier 2009
giovedì 1 gennaio 2009
Donnerstag, 1. Januar 2009
donderdag 1 januari 2009
(Indicate in comments where possible if any language specific or operating system configuration needs to be in place.)
Thursday, January 1, 2009
jeudi 1 janvier 2009
giovedì 1 gennaio 2009
Donnerstag, 1. Januar 2009
donderdag 1 januari 2009
(Indicate in comments where possible if any language specific or operating system configuration needs to be in place.)
cpp
QList<QLocale::Language> locales;
locales << QLocale::English
<< QLocale::French
<< QLocale::German
<< QLocale::Italian
<< QLocale::Dutch;
QDate date(2009, 1, 1);
foreach (QLocale::Language ll, locales)
{
QLocale::setDefault(ll);
qDebug() << date.toString(Qt::DefaultLocaleLongDate);
}
locales << QLocale::English
<< QLocale::French
<< QLocale::German
<< QLocale::Italian
<< QLocale::Dutch;
QDate date(2009, 1, 1);
foreach (QLocale::Language ll, locales)
{
QLocale::setDefault(ll);
qDebug() << date.toString(Qt::DefaultLocaleLongDate);
}
groovy
cal = Calendar.instance
cal.set(2009, JANUARY, 1)
[ENGLISH, FRENCH, ITALIAN, GERMAN, new Locale('nl')].each { lang ->
println getDateInstance(FULL, lang).format(cal.time)
}
// relies on Java I18N capabilities which supports many locales, see:
// http://java.sun.com/javase/technologies/core/basic/intl/
// available Locales may depend on your version of Java and/or
// operating system and/or installed fonts
cal.set(2009, JANUARY, 1)
[ENGLISH, FRENCH, ITALIAN, GERMAN, new Locale('nl')].each { lang ->
println getDateInstance(FULL, lang).format(cal.time)
}
// relies on Java I18N capabilities which supports many locales, see:
// http://java.sun.com/javase/technologies/core/basic/intl/
// available Locales may depend on your version of Java and/or
// operating system and/or installed fonts
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.
ruby
puts 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);
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.
ruby
class Greeter
def initialize(whom) @whom = whom end
def greet() puts "Hello, #{@whom}!" end
end
(Greeter.new("world")).greet()
def initialize(whom) @whom = whom end
def greet() puts "Hello, #{@whom}!" end
end
(Greeter.new("world")).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);
}
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()
Instantiate object with mutable state
Reimplement the Greeter class so that the
For example, if the greetee is changed to
Hello, Tommy!
The getter would then be used to display the line:
I have just greeted Tommy.
'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
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
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;
}
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;
}
groovy
class Greeter {
def whom
def greet() { println "Hello, $whom!" }
}
greeter = new Greeter(whom:"world"); greeter.greet()
greeter.whom = 'Tommy'; greeter.greet()
println "I have just greeted $greeter.whom"
def whom
def greet() { println "Hello, $whom!" }
}
greeter = new Greeter(whom:"world"); greeter.greet()
greeter.whom = 'Tommy'; greeter.greet()
println "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
* A
* A
* 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}
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}
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();
}
#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();
}
groovy
abstract class Shape {
final name
Shape(name) { this.name = name }
abstract area()
abstract print()
}
class Circle extends Shape {
final radius
Circle(radius) {
super('circle')
this.radius = radius
}
def area() { Math.PI * radius * radius }
def circumference() { 2 * Math.PI * radius }
def print() {
println "I am a $name with ->"
printf 'Radius: %.2f\n', radius
printf 'Area: %.2f\n', area()
printf 'Circumference: %.2f\n', circumference()
}
}
class Rectangle extends Shape {
final length, breadth
def Rectangle(length, breadth) {
super("rectangle")
this.length = length
this.breadth = breadth
}
def area() { length * breadth }
def perimeter() { 2 * length + 2 * breadth }
def print() {
println "I am a $name with ->"
printf 'Length, Width: %.2f, %.2f\n', length, breadth
printf 'Area: %.2f\n', area()
printf 'Perimeter: %.2f\n', perimeter()
}
}
shapes = [new Circle(4.2), new Rectangle(2.7, 3.1), new Rectangle(6.2, 2.6), new Circle(17.3)]
shapes.each { shape -> shape.print() }
final name
Shape(name) { this.name = name }
abstract area()
abstract print()
}
class Circle extends Shape {
final radius
Circle(radius) {
super('circle')
this.radius = radius
}
def area() { Math.PI * radius * radius }
def circumference() { 2 * Math.PI * radius }
def print() {
println "I am a $name with ->"
printf 'Radius: %.2f\n', radius
printf 'Area: %.2f\n', area()
printf 'Circumference: %.2f\n', circumference()
}
}
class Rectangle extends Shape {
final length, breadth
def Rectangle(length, breadth) {
super("rectangle")
this.length = length
this.breadth = breadth
}
def area() { length * breadth }
def perimeter() { 2 * length + 2 * breadth }
def print() {
println "I am a $name with ->"
printf 'Length, Width: %.2f, %.2f\n', length, breadth
printf 'Area: %.2f\n', area()
printf 'Perimeter: %.2f\n', perimeter()
}
}
shapes = [new Circle(4.2), new Rectangle(2.7, 3.1), new Rectangle(6.2, 2.6), new Circle(17.3)]
shapes.each { shape -> shape.print() }
Implement and use an Interface
Create a Serializable interface consisting of
* Accept a stream or handle or descriptor argument for the source or destination
* Save to destination or restore from source the properties or data members of the implementing class (restrict yourself to the primitive types
Next, create a Person class which has
'save' and 'restore' methods, each of which:
* Accept a stream or handle or descriptor argument for the source or destination
* Save to destination or restore from source the properties or data members of the implementing class (restrict yourself to the primitive types
'int' and 'string')
Next, create a Person class which has
'name' and 'age' properties or data members and implements this interface. Instantiate a Person object, save it to a serial stream, and instantiate a new Person object by restoring it from the serial stream.
ruby
class Person
def initialize(name, age)
@name, @age = name, age
end
end
tom = Person.new("Tom Bones", 23)
File.open('tommy.dump', 'w+') {|f| f.write(Marshal.dump(tommy)) }
toms_clone = Marshal.load(File.read('tommy.dump'))
def initialize(name, age)
@name, @age = name, age
end
end
tom = Person.new("Tom Bones", 23)
File.open('tommy.dump', 'w+') {|f| f.write(Marshal.dump(tommy)) }
toms_clone = Marshal.load(File.read('tommy.dump'))
cpp
struct person
{
person(){}
person(const string &name, int age) : name_(name), age_(age) {}
string name_;
int age_;
template<typename Archive>
void serialize(Archive &ar, const unsigned int version) {
ar & name_ & age_;
}
};
int main()
{
const char *fn = "filename.txt";
person k("Ken", 38);
{
ofstream ofs(fn);
archive::text_oarchive oa(ofs);
oa << k;
}
person restored_person;
{
ifstream ifs(fn);
archive::text_iarchive ia(ifs);
ia >> restored_person;
}
cout << "Name : " << restored_person.name_ << endl
<< "Age : " << restored_person.age_ << endl;
}
{
person(){}
person(const string &name, int age) : name_(name), age_(age) {}
string name_;
int age_;
template<typename Archive>
void serialize(Archive &ar, const unsigned int version) {
ar & name_ & age_;
}
};
int main()
{
const char *fn = "filename.txt";
person k("Ken", 38);
{
ofstream ofs(fn);
archive::text_oarchive oa(ofs);
oa << k;
}
person restored_person;
{
ifstream ifs(fn);
archive::text_iarchive ia(ifs);
ia >> restored_person;
}
cout << "Name : " << restored_person.name_ << endl
<< "Age : " << restored_person.age_ << endl;
}
groovy
// Built-in functionality but with slightly different names. Showing usage:
class Person implements Serializable { String name; int age }
p1 = new Person(name:'John', age:21)
p2 = null
output = new ByteArrayOutputStream() // or FileOutputStream, etc.
output.withObjectOutputStream { oos -> oos << p1 }
input = new ByteArrayInputStream(output.toByteArray())
input.withObjectInputStream(getClass().classLoader){ ois -> p2 = ois.readObject() }
assert p2.name == 'John'
assert p2.age == 21
class Person implements Serializable { String name; int age }
p1 = new Person(name:'John', age:21)
p2 = null
output = new ByteArrayOutputStream() // or FileOutputStream, etc.
output.withObjectOutputStream { oos -> oos << p1 }
input = new ByteArrayInputStream(output.toByteArray())
input.withObjectInputStream(getClass().classLoader){ ois -> p2 = ois.readObject() }
assert p2.name == 'John'
assert p2.age == 21
Check your language appears on the langref.org site
Your language name should appear within the HTML found at the http:
//langreg.org main page.
ruby
Net::HTTP.start(URL, 80) do |http|
status = if http.get('/').body =~ /#{SRCHEXP}/ then "offers" else "does not offer" end
puts "http:\/\/#{URL} #{status} #{LANGUAGE}"
end
status = if http.get('/').body =~ /#{SRCHEXP}/ then "offers" else "does not offer" end
puts "http:\/\/#{URL} #{status} #{LANGUAGE}"
end
erlang
URL = "http://langref.org/", Language = "erlang", Regexp = ".*" ++ URL ++ Language ++ ".*",
case http:request(URL) of
{ok, {_, _, Body}} ->
case regexp:first_match(Body, Regexp) of
{match, _, _} -> io:format("Language ~s exists @ ~s~n", [Language, URL]);
_ -> false
end;
{error, ErrorInfo} -> throw("Error: " ++ http:format_error(ErrorInfo))
end,
case http:request(URL) of
{ok, {_, _, Body}} ->
case regexp:first_match(Body, Regexp) of
{match, _, _} -> io:format("Language ~s exists @ ~s~n", [Language, URL]);
_ -> false
end;
{error, ErrorInfo} -> throw("Error: " ++ http:format_error(ErrorInfo))
end,
cpp
HttpWebRequest^ httpReq = safe_cast<HttpWebRequest^>(WebRequest::Create(url)); httpReq->KeepAlive = false;
StreamReader^ httpStream = gcnew StreamReader(httpReq->GetResponse()->GetResponseStream());
String^ htmlPage = httpStream->ReadToEnd(); httpStream->Close();
Console::WriteLine("{0} {1} {2}", url, (htmlPage->IndexOf(url + language) > 0 ? "offers" : "does not offer"), language);
StreamReader^ httpStream = gcnew StreamReader(httpReq->GetResponse()->GetResponseStream());
String^ htmlPage = httpStream->ReadToEnd(); httpStream->Close();
Console::WriteLine("{0} {1} {2}", url, (htmlPage->IndexOf(url + language) > 0 ? "offers" : "does not offer"), language);
groovy
assert new URL('http://langref.org').text.contains('groovy')
Send an email
Use library functions, classes or objects to create a short email addressed to your own email address. The subject should be,
"Greetings from langref.org", and the user should be prompted for the message body, and whether to cancel or proceed with sending the email.
ruby
require 'net/smtp'
require 'webrick/utils'
body = <<END_OF_MESSAGE
This is a message from langref.org
END_OF_MESSAGE
SMTPSRV = 'smtp.somewhere.com'
USER = 'me' ; DOMAIN = 'somewhere.com' ; FROM = USER + '@' + DOMAIN
TO = 'dest@somewhereelse.com'
SUBJECT = 'Greetings from langref.org'
DATE = Time.now.rfc2822()
MSGID = '<' + WEBrick::Utils.random_string(21) + '.' + WEBrick::Utils.random_string(21) + '@' + SMTPSRV + '>'
Net::SMTP.start(SMTPSRV, 25) do |smtp|
smtp.open_message_stream(FROM, [TO]) do |msg|
msg.puts "From: #{FROM}"
msg.puts "To: #{TO}"
msg.puts "Subject: #{SUBJECT}"
msg.puts "Date: #{DATE}"
msg.puts "Message-ID: #{MSGID}"
msg.puts
msg.puts body
end
end
require 'webrick/utils'
body = <<END_OF_MESSAGE
This is a message from langref.org
END_OF_MESSAGE
SMTPSRV = 'smtp.somewhere.com'
USER = 'me' ; DOMAIN = 'somewhere.com' ; FROM = USER + '@' + DOMAIN
TO = 'dest@somewhereelse.com'
SUBJECT = 'Greetings from langref.org'
DATE = Time.now.rfc2822()
MSGID = '<' + WEBrick::Utils.random_string(21) + '.' + WEBrick::Utils.random_string(21) + '@' + SMTPSRV + '>'
Net::SMTP.start(SMTPSRV, 25) do |smtp|
smtp.open_message_stream(FROM, [TO]) do |msg|
msg.puts "From: #{FROM}"
msg.puts "To: #{TO}"
msg.puts "Subject: #{SUBJECT}"
msg.puts "Date: #{DATE}"
msg.puts "Message-ID: #{MSGID}"
msg.puts
msg.puts body
end
end
groovy
// numerous libraries exist, this uses ant
// needs these jars: mailapi.jar, smtp.jar, ant-javamail.jar, ant-nodeps.jar
new AntBuilder().with {
input(message:'Message to send:', addproperty:'body')
input(message:'Send email?', validargs:'y,n,Y,N', addproperty:'confirm')
condition(property:'abort') { matches(string:'${confirm}', pattern:'n|N') }
fail(if:'abort', 'Email send aborted by user')
mail(mailhost:'smtp.gmail.com', mailport:'465', ssl:'on', user:'you@gmail.com',
subject:'Greetings from langref.org', password:'your_password'){
from(address:'you@gmail.com')
to(address:'rob@langref.org')
message('${body}')
}
}
// needs these jars: mailapi.jar, smtp.jar, ant-javamail.jar, ant-nodeps.jar
new AntBuilder().with {
input(message:'Message to send:', addproperty:'body')
input(message:'Send email?', validargs:'y,n,Y,N', addproperty:'confirm')
condition(property:'abort') { matches(string:'${confirm}', pattern:'n|N') }
fail(if:'abort', 'Email send aborted by user')
mail(mailhost:'smtp.gmail.com', mailport:'465', ssl:'on', user:'you@gmail.com',
subject:'Greetings from langref.org', password:'your_password'){
from(address:'you@gmail.com')
to(address:'rob@langref.org')
message('${body}')
}
}
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
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
# 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
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;
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>
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
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
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;
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
Find all Pythagorean triangles with length or height less than or equal to 20
Pythagorean triangles are right angle triangles whose sides comply with the following equation:
a * a + b * b = c * c
where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides. Find all such triangles where a, b and c are non-zero integers with a and b less than or equal to 20. Sort your results by the size of the hypotenuse. The expected answer is:
a * a + b * b = c * c
where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides. Find all such triangles where a, b and c are non-zero integers with a and b less than or equal to 20. Sort your results by the size of the hypotenuse. The expected answer is:
[3, 4, 5]
[6, 8, 10]
[5, 12, 13]
[9, 12, 15]
[8, 15, 17]
[12, 16, 20]
[15, 20, 25]
ruby
results=[]
1.upto(20) do |a|
1.upto(20) do |b|
c=Math.sqrt(a**2+b**2)
results<<[a, b, c.to_i] if c.to_i==c && !results.index([b, a, c.to_i])
end
end
results=results.sort_by{|r| r[2]}
puts results
1.upto(20) do |a|
1.upto(20) do |b|
c=Math.sqrt(a**2+b**2)
results<<[a, b, c.to_i] if c.to_i==c && !results.index([b, a, c.to_i])
end
end
results=results.sort_by{|r| r[2]}
puts results
def find_pythag( max=20 )
r = []
1.upto max do |n|
n.upto max do |m|
h = Math.sqrt( n**2 + m**2)
r << [n,m,h.to_i] if (h.round - h).zero?
end
end
r.sort_by { |a| a[2] }
end
r = []
1.upto max do |n|
n.upto max do |m|
h = Math.sqrt( n**2 + m**2)
r << [n,m,h.to_i] if (h.round - h).zero?
end
end
r.sort_by { |a| a[2] }
end
erlang
find_all_pythagorean_triangles(L) ->
lists:sort(fun({_, _, H1}, {_, _, H2}) -> H1 =< H2 end,
[ { X, Y, Z } ||
X <- lists:seq(1,L),
Y <- lists:seq(1,L),
Z <- lists:seq(1,2*L),
X*X + Y*Y =:= Z*Z,
Y > X,
Z > Y
]).
main(_) ->
List = find_all_pythagorean_triangles(20).
lists:sort(fun({_, _, H1}, {_, _, H2}) -> H1 =< H2 end,
[ { X, Y, Z } ||
X <- lists:seq(1,L),
Y <- lists:seq(1,L),
Z <- lists:seq(1,2*L),
X*X + Y*Y =:= Z*Z,
Y > X,
Z > Y
]).
main(_) ->
List = find_all_pythagorean_triangles(20).
cpp
vector<solution> solutions;
for (int a = 1; a <= 20; ++a)
for (int b = a + 1; b <= 20; ++b)
{
int c_squared = a*a + b*b;
int c = b + 1;
while (c * c < c_squared)
++c;
if (c * c == c_squared)
solutions.push_back(make_tuple(a, b, c));
}
sort(begin(solutions), end(solutions),
[](const solution& s1, const solution& s2) { return get<2>(s1) < get<2>(s2); });
for (const auto &s: solutions)
cout << '[' << get<0>(s) << ", " << get<1>(s) << ", " << get<2>(s) << ']' << endl;
for (int a = 1; a <= 20; ++a)
for (int b = a + 1; b <= 20; ++b)
{
int c_squared = a*a + b*b;
int c = b + 1;
while (c * c < c_squared)
++c;
if (c * c == c_squared)
solutions.push_back(make_tuple(a, b, c));
}
sort(begin(solutions), end(solutions),
[](const solution& s1, const solution& s2) { return get<2>(s1) < get<2>(s2); });
for (const auto &s: solutions)
cout << '[' << get<0>(s) << ", " << get<1>(s) << ", " << get<2>(s) << ']' << endl;
groovy
Set results = []
for (x in 1..20)
for (y in x..20) {
def z = sqrt(x*x + y*y)
if (z.toInteger() == z) results << [x, y, z.toInteger()]
}
println results.sort{it[2]}.join('\n')
for (x in 1..20)
for (y in x..20) {
def z = sqrt(x*x + y*y)
if (z.toInteger() == z) results << [x, y, z.toInteger()]
}
println results.sort{it[2]}.join('\n')
Set results = []
for (x in 1..20)
for (y in x..20) {
def z = sqrt(x*x + y*y)
if (z.toInteger() == z) results << [x, y, z.toInteger()]
}
println results.sort{it[2]}.join('\n')
for (x in 1..20)
for (y in x..20) {
def z = sqrt(x*x + y*y)
if (z.toInteger() == z) results << [x, y, z.toInteger()]
}
println results.sort{it[2]}.join('\n')
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
# => 15
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;
}
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))
}
produces a copy of its own source code
In computing, a quine is a computer program which produces a copy of its own source code as its only output.
ruby
eval s=%q(puts"eval s=%q(#{s})")
x="x=%p;puts x%%x";puts x%x
cpp
#include <cstdio>
#define B(x) x; printf("{ B(" #x ") }\n");
int main()
{ B(printf("#include <cstdio>\n#define B(x) x; printf(\"{ B(\" #x \") }\\n\");\nint main()\n")) }
#define B(x) x; printf("{ B(" #x ") }\n");
int main()
{ B(printf("#include <cstdio>\n#define B(x) x; printf(\"{ B(\" #x \") }\\n\");\nint main()\n")) }
groovy
s="s=%s;printf s,s.inspect()";printf s,s.inspect()
evaluate s='char q=39;print"evaluate s=$q$s$q"'
s="s=%c%s%c;printf s,34,s,34";printf s,34,s,34
s='s=%c%s%1$c;printf s,39,s';printf s,39,s
printf _='printf _=%c%s%1$c,39,_',39,_
Subdivide A Problem To A Pool Of Workers (No Shared Data)
Take a hard to compute problem and split it up between multiple worker threads. In your solution, try to fully utilize available cores or processors. (I'm looking at you, Python!)
Note: In this question, there should be no need for shared state between worker threads while the problem is being solved. Only after every thread completes computation are the answers recombined into a single output.
Example:
-Input-
(In python syntax)
In other words, a list of random strings.
-Output-
(In python syntax)
In other words, all possible permutations of each input string are computed.
Note: In this question, there should be no need for shared state between worker threads while the problem is being solved. Only after every thread completes computation are the answers recombined into a single output.
Example:
-Input-
(In python syntax)
["ab", "we", "tfe", "aoj"]
In other words, a list of random strings.
-Output-
(In python syntax)
[ ["ab", "ba", "aa", "bb", "a", "b"], ["we", "ew", "ww", "ee", "w", "e"], ...
In other words, all possible permutations of each input string are computed.
ruby
array, threads, answers = ["ab", "we", "tfe", "aoj"], [], []
array.each { |word|
threads << Thread.new(word.split '' ) do |x|
answer = []
x.each { |a|
answer << a
x.each { |b| answer << [a, b].join }
}
answers << answer
end
}
threads.each {|thr| thr.join}
answers
array.each { |word|
threads << Thread.new(word.split '' ) do |x|
answer = []
x.each { |a|
answer << a
x.each { |b| answer << [a, b].join }
}
answers << answer
end
}
threads.each {|thr| thr.join}
answers
cpp
vector<string> input;
input.push_back("ab");
input.push_back("we");
input.push_back("tfe");
input.push_back("aoj");
// Make the capacity for 'output' the same as 'input'
vector<set<string> > output(input.size());
#pragma omp parallel for
for (int i = 0; i < input.size(); ++i) {
set<string> perms;
generate_perms(input[i], perms);
#pragma omp critical
// Must use operator[]() and not push_back() since this line
// might be called in any order with respect to 'i'
output[i] = perms;
}
cout << output << endl;
input.push_back("ab");
input.push_back("we");
input.push_back("tfe");
input.push_back("aoj");
// Make the capacity for 'output' the same as 'input'
vector<set<string> > output(input.size());
#pragma omp parallel for
for (int i = 0; i < input.size(); ++i) {
set<string> perms;
generate_perms(input[i], perms);
#pragma omp critical
// Must use operator[]() and not push_back() since this line
// might be called in any order with respect to 'i'
output[i] = perms;
}
cout << output << endl;
groovy
// as per Java answer, doesn't duplicate chars from input string, i.e. no 'aa'
def ans = [].asSynchronized()
def words = ["ab", "we", "tfe", "aoj"]
def threads = []
void permutations(String prefix, String w, Set<String> permSet) {
int n = w.size()
if (!n) permSet << prefix
else n.times { i ->
permutations(prefix + w[i], w[0..<i] + w[i+1..<n], permSet)
}
}
words.each { word ->
def t = Thread.start {
def wordAns = [] as Set
for (int i = 0; i < word.size(); i++)
for (int j = i + 1; j <= word.size(); j++)
permutations("", word[i..<j], wordAns)
ans << wordAns
}
threads << t
}
threads.each{ it.join() }
println ans
def ans = [].asSynchronized()
def words = ["ab", "we", "tfe", "aoj"]
def threads = []
void permutations(String prefix, String w, Set<String> permSet) {
int n = w.size()
if (!n) permSet << prefix
else n.times { i ->
permutations(prefix + w[i], w[0..<i] + w[i+1..<n], permSet)
}
}
words.each { word ->
def t = Thread.start {
def wordAns = [] as Set
for (int i = 0; i < word.size(); i++)
for (int j = i + 1; j <= word.size(); j++)
permutations("", word[i..<j], wordAns)
ans << wordAns
}
threads << t
}
threads.each{ it.join() }
println ans
// as per Java answer, doesn't duplicate chars from input string, i.e. no 'aa'
def ans = [].asSynchronized()
def words = ["ab", "we", "tfe", "aoj"]
void permutations(String prefix, String w, Set<String> permSet) {
int n = w.size()
if (!n) permSet << prefix
else n.times { i ->
permutations(prefix + w[i], w[0..<i] + w[i+1..<n], permSet)
}
}
withParallelizer {
words.eachParallel { word ->
def wordAns = [] as Set
for (int i = 0; i < word.size(); i++)
for (int j = i + 1; j <= word.size(); j++)
permutations("", word[i..<j], wordAns)
ans << wordAns
}
}
println ans
def ans = [].asSynchronized()
def words = ["ab", "we", "tfe", "aoj"]
void permutations(String prefix, String w, Set<String> permSet) {
int n = w.size()
if (!n) permSet << prefix
else n.times { i ->
permutations(prefix + w[i], w[0..<i] + w[i+1..<n], permSet)
}
}
withParallelizer {
words.eachParallel { word ->
def wordAns = [] as Set
for (int i = 0; i < word.size(); i++)
for (int j = i + 1; j <= word.size(); j++)
permutations("", word[i..<j], wordAns)
ans << wordAns
}
}
println ans
Subdivide A Problem To A Pool Of Workers (Shared Data)
Take a hard to compute problem and split it up between multiple worker threads. In your solution, try to fully utilize available cores or processors. (I'm looking at you, Python!)
Note: In this question, there should be a need for shared state between worker threads while the problem is being solved.
Example:
-Conway Game of Life-
From Wikipedia:
The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, live or dead. Every cell interacts with its eight neighbors, which are the cells that are directly horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:
1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
2. Any live cell with more than three live neighbours dies, as if by overcrowding.
3. Any live cell with two or three live neighbours lives on to the next generation.
4. Any dead cell with exactly three live neighbours becomes a live cell.
The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed—births and deaths happen simultaneously, and the discrete moment at which this happens is sometimes called a tick (in other words, each generation is a pure function of the one before). The rules continue to be applied repeatedly to create further generations.
--However, for our purposes, we will assign a size to the game
Notice that in this problem, at each step or
Note: In this question, there should be a need for shared state between worker threads while the problem is being solved.
Example:
-Conway Game of Life-
From Wikipedia:
The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, live or dead. Every cell interacts with its eight neighbors, which are the cells that are directly horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:
1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
2. Any live cell with more than three live neighbours dies, as if by overcrowding.
3. Any live cell with two or three live neighbours lives on to the next generation.
4. Any dead cell with exactly three live neighbours becomes a live cell.
The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed—births and deaths happen simultaneously, and the discrete moment at which this happens is sometimes called a tick (in other words, each generation is a pure function of the one before). The rules continue to be applied repeatedly to create further generations.
--However, for our purposes, we will assign a size to the game
"board": 2^k * 2^k . That is, the board should be easy to subdivide.
Notice that in this problem, at each step or
"tick", each thread/process will need to share data with its neighborhood.
groovy
// some crude assumptions made for size and amount of parallelism
enum State { ALIVE, DEAD }
import static State.*
seed = '''\
* *
** **
** *
*
**
***
**
* \
'''
def computeNextGen(inboard, outboard, n) {
// crudely split into 4 chunks but could be smarter if we wanted
int half = n/2
def t1 = Thread.start { computeNextGen(inboard, outboard, n, 0, half, 0, half) }
def t2 = Thread.start { computeNextGen(inboard, outboard, n, 0, half, half, n) }
def t3 = Thread.start { computeNextGen(inboard, outboard, n, half, n, 0, half) }
def t4 = Thread.start { computeNextGen(inboard, outboard, n, half, n, half, n) }
[t1, t2, t3, t4].each{ it.join() }
}
def computeNextGen(inboard, outboard, n, minx, maxx, miny, maxy) {
for (int i = minx; i < maxx; i++)
for (int j = 0; j < maxy; j++)
if (i == 0 || i == n-1 || j == 0 || j == n-1)
outboard[i][j] = DEAD
for (int i = minx; i < maxx; i++) {
for (int j = miny; j < maxy; j++) {
if (i == 0 || i == n-1 || j == 0 || j == n-1)
continue
int count = 0
[[-1, 0, 1], [-1, 0, 1]].combinations().each{ dx, dy ->
if ((dx || dy) && inboard[i+dx][j+dy] == ALIVE) count++
}
switch(count) {
case {count == 3}:
case {inboard[i][j] == ALIVE && count == 2}:
outboard[i][j] = ALIVE; break
default:
outboard[i][j] = DEAD
}
}
}
}
void printBoard(board) {
println '--------'
println board*.collect{ it == DEAD ? ' ' : '*' }*.join().join('\n')
}
void initBoard(seed, board) {
def row = 0
seed.readLines().each { line ->
def col = 0
line.each { ch ->
board[row][col++] = ch == '*' ? ALIVE : DEAD
}
row++
}
}
def N = 8
def NUM_CYCLES = 3
def board1 = new State[N][N]
def board2 = new State[N][N]
initBoard(seed, board1)
NUM_CYCLES.times {
computeNextGen board1, board2, N
printBoard board2
computeNextGen board2, board1, N
printBoard board1
}
enum State { ALIVE, DEAD }
import static State.*
seed = '''\
* *
** **
** *
*
**
***
**
* \
'''
def computeNextGen(inboard, outboard, n) {
// crudely split into 4 chunks but could be smarter if we wanted
int half = n/2
def t1 = Thread.start { computeNextGen(inboard, outboard, n, 0, half, 0, half) }
def t2 = Thread.start { computeNextGen(inboard, outboard, n, 0, half, half, n) }
def t3 = Thread.start { computeNextGen(inboard, outboard, n, half, n, 0, half) }
def t4 = Thread.start { computeNextGen(inboard, outboard, n, half, n, half, n) }
[t1, t2, t3, t4].each{ it.join() }
}
def computeNextGen(inboard, outboard, n, minx, maxx, miny, maxy) {
for (int i = minx; i < maxx; i++)
for (int j = 0; j < maxy; j++)
if (i == 0 || i == n-1 || j == 0 || j == n-1)
outboard[i][j] = DEAD
for (int i = minx; i < maxx; i++) {
for (int j = miny; j < maxy; j++) {
if (i == 0 || i == n-1 || j == 0 || j == n-1)
continue
int count = 0
[[-1, 0, 1], [-1, 0, 1]].combinations().each{ dx, dy ->
if ((dx || dy) && inboard[i+dx][j+dy] == ALIVE) count++
}
switch(count) {
case {count == 3}:
case {inboard[i][j] == ALIVE && count == 2}:
outboard[i][j] = ALIVE; break
default:
outboard[i][j] = DEAD
}
}
}
}
void printBoard(board) {
println '--------'
println board*.collect{ it == DEAD ? ' ' : '*' }*.join().join('\n')
}
void initBoard(seed, board) {
def row = 0
seed.readLines().each { line ->
def col = 0
line.each { ch ->
board[row][col++] = ch == '*' ? ALIVE : DEAD
}
row++
}
}
def N = 8
def NUM_CYCLES = 3
def board1 = new State[N][N]
def board2 = new State[N][N]
initBoard(seed, board1)
NUM_CYCLES.times {
computeNextGen board1, board2, N
printBoard board2
computeNextGen board2, board1, N
printBoard board1
}
Create a multithreaded "Hello World"
Create a program which outputs the string
Example:
-Output-
Thread one says Hello World!
Thread two says Hello World!
Thread four says Hello World!
Thread three says Hello World!
-Notice that the threads can print in any order.
"Hello World" to the console, multiple times, using separate threads or processes.
Example:
-Output-
Thread one says Hello World!
Thread two says Hello World!
Thread four says Hello World!
Thread three says Hello World!
-Notice that the threads can print in any order.
ruby
%w[one two three four].each do |number|
Thread.new(number) { |number|
puts "Thread #{number} says Hello World!"
}.join
end
Thread.new(number) { |number|
puts "Thread #{number} says Hello World!"
}.join
end
erlang
-module(spam).
-export([spam/1]).
spam(N) when N<5 ->
spawn(fun() -> io:format("Hello World from thread ~p~n",[N]) end),
spam(N+1);
spam(_) -> void.
-export([spam/1]).
spam(N) when N<5 ->
spawn(fun() -> io:format("Hello World from thread ~p~n",[N]) end),
spam(N+1);
spam(_) -> void.
cpp
#include <iostream>
#include <string>
using namespace std;
int main(){
int pid;
string text[4]={"one","two","three","four"};
for (int i=0;i<4;i++){
pid=fork();
if (pid>0){
//cout << "Process("<<pid<<") - " << "Thread " << text[i] << " says Hello World!" << endl;
cout << "Thread " << text[i] << " says Hello World!" << endl;
exit(0);
}
}
return 0;
}
#include <string>
using namespace std;
int main(){
int pid;
string text[4]={"one","two","three","four"};
for (int i=0;i<4;i++){
pid=fork();
if (pid>0){
//cout << "Process("<<pid<<") - " << "Thread " << text[i] << " says Hello World!" << endl;
cout << "Thread " << text[i] << " says Hello World!" << endl;
exit(0);
}
}
return 0;
}
#include <iostream>
#include <string>
#include <omp.h>
int main() {
unsigned int const num_threads = 4;
std::string const names[] = { "one", "two", "three", "four" };
# pragma omp parallel num_threads(num_threads)
{
unsigned const id = omp_get_thread_num();
// Stream concatenation isn't thread-safe so we use a critical section.
# pragma omp critical
std::cout << "Thread " << names[id] << " says Hello World!" << std::endl;
}
}
#include <string>
#include <omp.h>
int main() {
unsigned int const num_threads = 4;
std::string const names[] = { "one", "two", "three", "four" };
# pragma omp parallel num_threads(num_threads)
{
unsigned const id = omp_get_thread_num();
// Stream concatenation isn't thread-safe so we use a critical section.
# pragma omp critical
std::cout << "Thread " << names[id] << " says Hello World!" << std::endl;
}
}
groovy
["one","two","three","four"].each { tid ->
Thread.start {
println "Thread $tid says Hello World!"
}
}
Thread.start {
println "Thread $tid says Hello World!"
}
}
import static groovyx.gpars.Parallelizer.*
withParallelizer {
["one","two","three","four"].eachParallel {
println "Thread $it says Hello World!"
}
}
withParallelizer {
["one","two","three","four"].eachParallel {
println "Thread $it says Hello World!"
}
}
Create read/write lock on a shared resource.
Create multiple threads or processes who are either readers or writers. There should be more readers then writers.
(From Wikipedia):
Multiple readers can read the data in parallel but an exclusive lock is needed while writing the data. When a writer is writing the data, readers will be blocked until the writer is finished writing.
Example:
-Output-
Thread one says that the value is 8.
Thread three says that the value is 8.
Thread two is taking the lock.
Thread four tried to read the value, but could not.
Thread five tried to write to the value, but could not.
Thread two is changing the value to 9.
Thread two is releasing the lock.
Thread four says that the value is 9.
...
--Notice that when a needed resource is locked, a thread can set a timer and try again in the future, or wait to be notified that the resource is no longer locked.
(From Wikipedia):
Multiple readers can read the data in parallel but an exclusive lock is needed while writing the data. When a writer is writing the data, readers will be blocked until the writer is finished writing.
Example:
-Output-
Thread one says that the value is 8.
Thread three says that the value is 8.
Thread two is taking the lock.
Thread four tried to read the value, but could not.
Thread five tried to write to the value, but could not.
Thread two is changing the value to 9.
Thread two is releasing the lock.
Thread four says that the value is 9.
...
--Notice that when a needed resource is locked, a thread can set a timer and try again in the future, or wait to be notified that the resource is no longer locked.
cpp
class reader
{
string name_;
public:
reader(const string& name) : name_(name) {}
void operator()() {
for (;;this_thread::sleep(posix_time::milliseconds(1)))
{
shared_lock<shared_mutex> lock(m, try_to_lock);
lock_guard<mutex> cout_lock(io_m);
cout << "Thread " << name_;
if (lock)
cout << " says that the value is " << shared_value << "." << endl;
else
cout << " tried to read the value, but could not." << endl;
}
}
};
class writer
{
string name_;
public:
writer(const string& name) : name_(name) {}
void operator()() {
for (;;this_thread::sleep(posix_time::milliseconds(1)))
{
unique_lock<shared_mutex> lock(m, try_to_lock);
lock_guard<mutex> cout_lock(io_m);
cout << "Thread " << name_;
if (lock)
{
cout << " is taking the lock." << endl;
shared_value = rand() % 10;
cout << "Thread " << name_ << " is changing the value to " << shared_value << endl;
cout << "Thread " << name_ << " is releasing the lock. " << endl;
}
else
cout << " tried to write to the value, but could not." << endl;
}
}
};
int main()
{
thread t1 = thread(reader("one"));
thread t2 = thread(reader("two"));
thread t3 = thread(reader("three"));
thread t4 = thread(writer("four"));
writer("five")();
}
{
string name_;
public:
reader(const string& name) : name_(name) {}
void operator()() {
for (;;this_thread::sleep(posix_time::milliseconds(1)))
{
shared_lock<shared_mutex> lock(m, try_to_lock);
lock_guard<mutex> cout_lock(io_m);
cout << "Thread " << name_;
if (lock)
cout << " says that the value is " << shared_value << "." << endl;
else
cout << " tried to read the value, but could not." << endl;
}
}
};
class writer
{
string name_;
public:
writer(const string& name) : name_(name) {}
void operator()() {
for (;;this_thread::sleep(posix_time::milliseconds(1)))
{
unique_lock<shared_mutex> lock(m, try_to_lock);
lock_guard<mutex> cout_lock(io_m);
cout << "Thread " << name_;
if (lock)
{
cout << " is taking the lock." << endl;
shared_value = rand() % 10;
cout << "Thread " << name_ << " is changing the value to " << shared_value << endl;
cout << "Thread " << name_ << " is releasing the lock. " << endl;
}
else
cout << " tried to write to the value, but could not." << endl;
}
}
};
int main()
{
thread t1 = thread(reader("one"));
thread t2 = thread(reader("two"));
thread t3 = thread(reader("three"));
thread t4 = thread(writer("four"));
writer("five")();
}
groovy
def lock = new ReentrantLock()
Integer value = 8
20.times { i ->
if (i % 3 == 0) {
Thread.start {
if (!lock.tryLock()) {
println "Thread " + i + " tried to write the value, but could not."
lock.lock()
}
value = (int) (Math.random() * 10)
println "Thread " + i + " is changing the value to " + value
lock.unlock()
println "Thread " + i + " is releasing the lock."
}
} else {
Thread.start {
if (!lock.tryLock()) {
println "Thread " + i + " tried to read the value, but could not."
lock.lock()
}
println "Thread " + i + " says that the value is " + value + "."
lock.unlock()
}
}
}
Integer value = 8
20.times { i ->
if (i % 3 == 0) {
Thread.start {
if (!lock.tryLock()) {
println "Thread " + i + " tried to write the value, but could not."
lock.lock()
}
value = (int) (Math.random() * 10)
println "Thread " + i + " is changing the value to " + value
lock.unlock()
println "Thread " + i + " is releasing the lock."
}
} else {
Thread.start {
if (!lock.tryLock()) {
println "Thread " + i + " tried to read the value, but could not."
lock.lock()
}
println "Thread " + i + " says that the value is " + value + "."
lock.unlock()
}
}
}
Separate user interaction and computation.
Allow your program to accept user interaction while conducting a long running computation.
Example:
Hello user! Please input a string to permute: (input thread)
abcdef
Passing on abcdef... (input thread)
Please input another string to permute: (input thread)
lol
Passing on lol... (input thread)
Done Work On abcdef! (worker thread)
Please input another string to permute: (input thread)
EXIT
Quitting, I
--Notice, that this could be accomplished on the command line or within a GUI. The point is that computation and user interaction should take place on separate threads of control.
Example:
Hello user! Please input a string to permute: (input thread)
abcdef
Passing on abcdef... (input thread)
Please input another string to permute: (input thread)
lol
Passing on lol... (input thread)
Done Work On abcdef! (worker thread)
["abcdef", "abcefd", ... ] (worker thread)
Please input another string to permute: (input thread)
EXIT
Quitting, I
'll let my worker thread know... (input thread)
We're quitting! Alright! (worker thread)
--Notice, that this could be accomplished on the command line or within a GUI. The point is that computation and user interaction should take place on separate threads of control.
cpp
class bg_worker
{
mutex bg_mutex_;
condition_variable work_present_;
deque<string> work_queue_;
result calc_perm(string s) {
result perms = result(new list<string>());
// sleep to simulate lots of work...
this_thread::sleep(posix_time::seconds(3));
sort(s.begin(), s.end());
do {
perms->push_back(s);
} while (next_permutation(s.begin(), s.end()));
return perms;
}
public:
void submit_work(const string &s) {
lock_guard<mutex> lock(bg_mutex_);
work_queue_.push_back(s);
work_present_.notify_one();
}
void operator()() {
for (;;) {
unique_lock<mutex> lock(bg_mutex_);
while (work_queue_.empty())
work_present_.wait(lock);
string s = work_queue_.front();
work_queue_.pop_front();
lock.unlock();
if (s == "EXIT") {
lock_guard<mutex> cout_lock(cout_mutex);
cout << "We're quitting! Alright!" << endl;
break;
}
result perm = calc_perm(s);
lock_guard<mutex> cout_lock(cout_mutex);
cout << "Done Work On " << s << "!" << endl;
cout << perm << endl;
}
}
};
int main()
{
bg_worker worker;
thread bg_thr(boost::ref(worker));
bool done = false;
{
lock_guard<mutex> cout_lock(cout_mutex);
cout << "Hello user! Please input a string to permute:" << endl;
}
while (!done)
{
string input;
cin >> input;
{
lock_guard<mutex> cout_lock(cout_mutex);
if (input == "EXIT") {
cout << "Quitting, I'll let my worker thread know..." << endl;
done = true;
} else {
cout << "Passing on " << input << "..." << endl;
cout << "Please input another string to permute:" << endl;
}
}
worker.submit_work(input);
}
bg_thr.join();
}
{
mutex bg_mutex_;
condition_variable work_present_;
deque<string> work_queue_;
result calc_perm(string s) {
result perms = result(new list<string>());
// sleep to simulate lots of work...
this_thread::sleep(posix_time::seconds(3));
sort(s.begin(), s.end());
do {
perms->push_back(s);
} while (next_permutation(s.begin(), s.end()));
return perms;
}
public:
void submit_work(const string &s) {
lock_guard<mutex> lock(bg_mutex_);
work_queue_.push_back(s);
work_present_.notify_one();
}
void operator()() {
for (;;) {
unique_lock<mutex> lock(bg_mutex_);
while (work_queue_.empty())
work_present_.wait(lock);
string s = work_queue_.front();
work_queue_.pop_front();
lock.unlock();
if (s == "EXIT") {
lock_guard<mutex> cout_lock(cout_mutex);
cout << "We're quitting! Alright!" << endl;
break;
}
result perm = calc_perm(s);
lock_guard<mutex> cout_lock(cout_mutex);
cout << "Done Work On " << s << "!" << endl;
cout << perm << endl;
}
}
};
int main()
{
bg_worker worker;
thread bg_thr(boost::ref(worker));
bool done = false;
{
lock_guard<mutex> cout_lock(cout_mutex);
cout << "Hello user! Please input a string to permute:" << endl;
}
while (!done)
{
string input;
cin >> input;
{
lock_guard<mutex> cout_lock(cout_mutex);
if (input == "EXIT") {
cout << "Quitting, I'll let my worker thread know..." << endl;
done = true;
} else {
cout << "Passing on " << input << "..." << endl;
cout << "Please input another string to permute:" << endl;
}
}
worker.submit_work(input);
}
bg_thr.join();
}
groovy
def threads = new ConcurrentLinkedQueue<Thread>()
void permutations(String prefix, String w, Set<String> permSet) {
int n = w.size()
if (!n) permSet << prefix
else n.times { i ->
permutations(prefix + w[i], w[0..<i] + w[i+1..<n], permSet)
}
}
println 'Welcome to the parallel permuter'
System.in.withReader { r ->
while (true) {
print 'Enter word:'
def word = r.readLine()
if (word == 'EXIT') {
while (!threads.isEmpty())
threads.poll().stop(new ThreadDeath())
break
} else
threads << Thread.start {
try {
def wordAns = [] as Set
for (int i = 0; i < word.size(); i++)
for (int j = i + 1; j <= word.size(); j++)
permutations("", word[i..<j], wordAns)
println '\nAnswer:' + wordAns
print 'Enter word:'
} catch (ThreadDeath td) {
println 'Thread aborted!'
}
}
}
}
void permutations(String prefix, String w, Set<String> permSet) {
int n = w.size()
if (!n) permSet << prefix
else n.times { i ->
permutations(prefix + w[i], w[0..<i] + w[i+1..<n], permSet)
}
}
println 'Welcome to the parallel permuter'
System.in.withReader { r ->
while (true) {
print 'Enter word:'
def word = r.readLine()
if (word == 'EXIT') {
while (!threads.isEmpty())
threads.poll().stop(new ThreadDeath())
break
} else
threads << Thread.start {
try {
def wordAns = [] as Set
for (int i = 0; i < word.size(); i++)
for (int j = i + 1; j <= word.size(); j++)
permutations("", word[i..<j], wordAns)
println '\nAnswer:' + wordAns
print 'Enter word:'
} catch (ThreadDeath td) {
println 'Thread aborted!'
}
}
}
}
Put a internationalizate of HelloWorld program
Set locale to
In pseudocode:
Void main ()
"es" (spanish) and provide a program that changes outputs ("Helloworld") depending of locale.
In pseudocode:
Void main ()
{
Locale.set("es")
print.translate("Helloworld, Locale.get)
}
180
"http://www.ecigarettefresh.com/cartomizer-ecigarette-c-7.html ">Cartomizer E-Cigarette<
/a>strong>"http://www.ecigarettefresh.com/cartomizer-ecigarette-c-7.html ">Electronic Cigarette<
/a>strong>"http://www.ecigarettefresh.com/cartomizer-ecigarette-c-7.html ">Smokeless Cigarettes<
/a>strong>"http://www.ecigarettefresh.com/cartomizer-ecigarette-c-7.html ">discount Electronic Cigarette<
/a>strong>"http://www.ecigarettefresh.com/disposable-ecigarette-c-8.html ">Disposable E-Cigarette<
/a>strong>"http://www.ecigarettefresh.com/accessories-c-6.html ">Accessories<
/a>strong>"http://www.ecigarettefresh.com/mini-ecigarette-c-13.html ">Mini E-cigarette<
/a>strong>"http://www.ecigarettefresh.com/esmoking-c-11.html ">electric cigarette outlet<
/a>strong>"http://www.ecigarettefresh.com/smokeless-cigarettes-c-12.html ">Smokeless Cigarettes online<
/a>strong>"http://www.ecigarettefresh.com/ecigarette-c-9.html ">Electronic Cigarette online<
/a>strong>. "http://blog.allluxurywatches.com"> outlet blog <
/a>
outlet a>"http://blog.linksoflondonshopping.com"> About ecigarettefresh.com blog
180
"http://www.lovembtshoes.com/ ">mbt boots<
/a>strong>"http://www.lovembtshoes.com/ ">mbt shoes<
/a>strong>"http://www.lovembtshoes.com/ ">buy mbt boots<
/a>strong>"http://www.lovembtshoes.com/ ">discount mbt shoes<
/a>strong>"http://www.lovembtshoes.com/ ">mbt shoes online<
/a>strong>"http://www.lovembtshoes.com/mbt-tariki-c-50.html ">MBT Tariki shoes outlet<
/a>strong>"http://www.lovembtshoes.com/mbt-karibu-c-18.html ">wholesale MBT Karibu shoes<
/a>strong>"http://www.lovembtshoes.com/mbt-kafala-black-leather-women-shoes-p-68.html ">buy MBT Kafala shoes<
/a>strong>"http://www.lovembtshoes.com/mbt-meli-c-33.html ">MBT Meli<
/a>strong>"http://www.lovembtshoes.com/mbt-kifundo-c-25.html ">discount MBT Kifundo<
/a>strong>. "http://blog.bootsonlinecompany.com"> Bia blog <
/a>
Bia a>"http://blog.linkuggbootsoutlet.com"> About lovembtshoes.com blog
180
[Mall3411] - $175.01 : </title>
html; charset=utf-8" />
keywords" content="Low Cost Custom-Made bretelles sexy mariage mariée robe de mariée Robes [Mall3411] Robes de Mariée Robes de mariée 2012 Robe de mariée sexy Robes de mariée robes Quinceanera Robes de bal Robes de soirée Robes de bal Robes de soirée Robes de cocktail " />
description" content=" Low Cost Custom-Made bretelles sexy mariage mariée robe de mariée Robes [Mall3411] - Nom de l'article: " />
- TOP_MENU_HOME
- Robes de cocktail
- Robes de soirée
- Robes de mariée
- Robes de bal
- Contactez-nous
- http:
//fr.weddingdressescompany.com/»,«http:/fr.weddingdressescompany.com/' ) " > Marque page