All Problems

Output a string to the console

Write the string "Hello World!" to STDOUT
clojure
(println "Hello World!")
cpp
std::cout << "Hello World" << std::endl;
std::printf("Hello World\n");
Console::WriteLine(L"Hello World");
fsharp
printfn "Hello World!"
groovy
println "Hello World!"
java
System.out.println("Hello World!");
System.out.printf("Hello World!\n");
ocaml
print_string "Hello world!\n";;
print_endline "Hello world!";;
Printf.printf "Hello world!\n";;
python
print "Hello World!"
scala
println("Hello World!")
printf("Hello World!\n")

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 "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?
clojure
(->> {"mode" "view"
"fname" "Ron & Jean"
"lname" "Smith"}
(map #(str (URLEncoder/encode (first %) "UTF-8")
"="
(URLEncoder/encode (second %) "UTF-8")))
(reduce (fn [url e] (str url "&" e))
"http://myserver.com/custinfo/edit.php"))
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();
fsharp
//the problem arises due to the fact that you've attempted to apply HTML entities encoding rather than URL encoding to your data!
//in F#, for example, assuming you would call this function with fname and lname parameters, this would produce the desired output
let getProperUrl fname lname = sprintf "http://myserver.com/custinfo/edit.php?mode=view&fname=%s&lname=%s" (HttpUtility.UrlEncode fname) (HttpUtility.UrlEncode lname)
// Example that shows encoding and decoding:
let queryString =
let fname = HttpUtility.UrlEncode("Ron & James")
let lname = HttpUtility.UrlEncode("Smith & Jones")
sprintf "http://myserver.com/custinfo/edit.php?mode=view&fname=%s&lname=%s" fname lname
/// All parameters in the URL as a lookup map
let parameters =
let paramStart = queryString.IndexOf('?')
if paramStart < 0 then
Map.empty
else
let values =
queryString.Substring(paramStart + 1)
|> HttpUtility.ParseQueryString
values.AllKeys
|> Seq.map (fun key -> key, values.[key])
|> Map.ofSeq
let fname = parameters.TryFind("fname")
let lname = parameters.TryFind("lname")
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")
java
Map<String, String> params = new HashMap<String, String>();
params.put("mode", "view");
params.put("fname", "Ron & Jean");
params.put("lname", "Smith");

StringBuilder buffer = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
buffer.append(URLEncoder.encode(entry.getKey(), "UTF-8"))
.append("=")
.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
System.out.println(buffer.toString());
ocaml
let query =
Netencoding.Url.mk_url_encoded_parameters [
"mode", "view";
"fname", "Ron & Jean";
"lname", "Smith";
]

let url =
"http://myserver.com/custinfo/edit.php?" ^ query
python
# I'm not really sure this is what the site is for,
# but the one unsolved problem for python was grating me.
# Anyway, I think this is what you're looking for.

from urllib import urlencode

query_dict = {'mode': 'view',
'fname': 'Ron & Jean',
'lname': 'Smith'}

print urlencode(query_dict.items())

# Which will be 'lname=Smith&mode=view&fname=Ron+%26+Jean'.
scala
import java.net.URLEncoder

val params = Map("mode"->"view", "fname"->"Ron & Jean", "lname"->"Smith")
var url = ""

for ((k, v) <- params) { url += URLEncoder.encode(k) + "=" + URLEncoder.encode(v) }

println(url)
import java.net.URLEncoder
val params = Map("mode"->"view", "fname"->"Ron & Jean", "lname"->"Smith")
(for ((k, v) <- params) yield URLEncoder.encode(k) + "=" + URLEncoder.encode(v) ).mkString("&")

string-wrap

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

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.
clojure
(defn string-wrap [s]
(if (= 0 (count s))
nil
(lazy-seq (cons (apply str (take 78 s))
(string-wrap (drop 78 s))))))

(let [s (apply str (repeat 10 "The quick brown fox jumps over the lazy dog. "))]
(doseq [line (string-wrap s)]
(println "> " line)))
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);
}
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"
}
java
public class SolutionXX {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
String words = "The quick brown fox jumps over the lazy dog. ";

for (int i = 0; i < 10; i++)
{
builder.append(words);
}

String toWrap = builder.toString();
int width = 76;
while (toWrap!=null && toWrap.length()>0)
{
String first = toWrap.length() > width ? toWrap.substring(0, width+1) : toWrap;
toWrap = (!toWrap.equals(first)) ? toWrap.substring(width + 1).trim() : null;
System.out.println("> " + first);
}

}
}
ocaml
let wrapper margin =
let cur = ref 0 in
fun word ->
let len = String.length word in
let beginning_of_line () =
Printf.printf "> %s" word;
cur := len + 2 in
if !cur = 0 then
beginning_of_line ()
else begin
cur := !cur + 1 + len;
if !cur <= margin then
Printf.printf " %s" word
else begin
print_newline ();
beginning_of_line ()
end
end

let wrap_string wrapper s =
let len = String.length s in
let rec aux_out i =
if i < len then
match s.[i] with
| ' ' | '\t' | '\n' ->
aux_out (i+1)
| _ -> aux_in i (i+1)
and aux_in i0 i =
if i >= len then
wrapper (String.sub s i0 (len - i0))
else match s.[i] with
| ' ' | '\t' | '\n' ->
wrapper (String.sub s i0 (i - i0));
aux_out (i+1)
| _ ->
aux_in i0 (i+1) in
aux_out 0

let () =
let base_string = "The quick brown fox jumps over the lazy dog. " in
let w = wrapper 78 in
for i = 1 to 10 do
wrap_string w base_string
done;
print_newline ()
python
def wrap(string, length):

while len(string):
print("> " + string[0:length - 1])
string = string[length - 1:].strip()


wrap("The quick brown fox jumps over the lazy dog. " * 10, 78)
scala
object Wrap {
def wordWrap(str: String, width: Int, lineStart: String, reps: Int) = {
var strRepeated = ""
for(i <- 0 until reps) strRepeated += str
while(strRepeated.length > width) {
println(lineStart + strRepeated.substring(0, (width-1)))
strRepeated = strRepeated.substring(width)
}
println(lineStart + strRepeated)
}

def main(args: Array[String]) = {
wordWrap("The quick brown fox jumps over the lazy dog. ", 78, "> ", 10)
}
}
def stringWrap(s: String): List[String] =
if (s.length == 0) Nil else s.take(78) :: stringWrap(s.drop(78))

stringWrap("The quick brown fox jumps over the lazy dog. " * 10).foreach(line => println("> " + line))
("The quick brown fox jumps over the lazy dog. " * 10) grouped(78) foreach { line => println("> " + line) }

Define a string containing special characters

Define the literal string "\#{'}${"}/"
clojure
(def special "\\#{'}${\"}/")
cpp
std::string special = "\\#{'}${\"}/";
String^ special = L"\\#{'}${\"}/";
fsharp
let special = "\#{'}${\"}/"
groovy
special = "\\#{'}\${\"}/"
special = '\\#{\'}${"}/'
special = /\#{'}${'$'}{"}\//
java
String special = "\\#{'}${\"}/";
ocaml
"\\#{'}${\"}/"
python
# yes, Python has way too many forms of string literals :)
print "\\#{'}${\"}/"
print "\\#{'}${"'"'"}/"
print r"""\#{'}${"}/"""
print '\\#{\'}${"}/'
print '\\#{'"'"'}${"}/'
print r'''\#{'}${"}/'''
scala
val special = "\\#{'}${\"}/"
val special2 = """\#{'}${"}/"""

Define a multiline string

Define the string:
"This
Is
A
Multiline
String"
clojure
(def multiline "This\nIs\nA\nMultiline\nString")
cpp
std::string text =
"This\n"
"Is\n"
"A\n"
"Multiline\n"
"String";
String^ text = L"This\nIs\nA\nMultiline\nString";
std::string text = "This\nIs\nA\nMultiline\nString";
fsharp
let multiline = "This\nIs\nA\nMultiline\nString"
let multiline = "This
Is
A
Multiline
String"
groovy
def text =
"""This
Is
A
Multiline
String"""
def text = "This\nIs\nA\nMultiline\nString"
java
String text = "This\nIs\nA\nMultiline\nString";
String text =
"This\n" +
"Is\n" +
"A\n" +
"Multiline\n" +
"String"
ocaml
"This\nIs\nA\nMultiline\nString"
"This
Is
A
Multiline
String"
python
text = """This
Is
A
Multiline
String"""
# with proper indentation
text = (
"This\n"
"Is\n"
"A\n"
"Multiline\n"
"String"
)
scala
val text = """This
Is
A
Multiline
String"""
val text = "This\nIs\nA\nMultiline\nString"

Define a string containing variables and expressions

Given variables a=3 and b=4 output "3+4=7"
clojure
(format "%d + %d = %d" a b (+ a b))
cpp
Console::WriteLine(L"{0}+{1}={2}", a, b, a+b);
std::printf("%d+%d=%d\n", a, b, a+b);
std::cout << boost::format("%|1|+%|1|=%|1|") % a % b % (a+b) << std::endl;
fsharp
let a, b = 3, 4
let mystr = sprintf "%d+%d=%d" a b (a+b)
printfn "%s" mystr
groovy
println "$a+$b=${a+b}"
printf "%d+%d=%d\n", a, b, a + b
java
System.out.println(a + "+" + b + "=" + (a+b));
System.out.printf("%d+%d=%d\n", a, b, a + b);
ocaml
Printf.printf "%d+%d=%d" a b (a+b);;
Printf.printf "%d+%d=%d" a b (a+b);;
python
class EvalDict(dict):
def __getitem__(s, k):
return eval(k, s)

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

Reverse the characters in a string

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

Reverse the words in a string

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

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

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

Text wrapping

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

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

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

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

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

int main()
{
stringstream input;

rep(input, "The quick brown fox jumps over the lazy dog. ", 10);
wrap(cout, input.str(), "> ", 72);
}
fsharp
let prefix = "> "
let input = "The quick brown fox jumps over the lazy dog. "

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

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

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

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

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

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


python
import textwrap
print textwrap.fill("The quick brown fox jumps over the lazy dog. " * 10,
72, initial_indent="> ", subsequent_indent="> ")
scala
val prefix = "> " ; val input = "The quick brown fox jumps over the lazy dog."

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

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

Remove leading and trailing whitespace from a string

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

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

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

let () =
let res = trim " hello " in
print_endline res
python
assert 'hello' == ' hello '.strip()
scala
val s = " 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
clojure
(use 'clojure.contrib.cond)

(defn rot13 [s]
(reduce str
(map #(char (let [c (bit-and (int (char %)) 0xDF)]
(+ % (cond-let [i]
(and (>= c (int \A)) (<= c (int \M))) 13
(and (>= c (int \N)) (<= c (int \Z))) -13
true 0))))
(map #(int (char %)) s))))

(defn rot47 [s]
(reduce str
(map #(char (+ % (cond-let [i]
(and (>= % (int \!)) (<= % (int \O))) 47
(and (>= % (int \P)) (<= % (int \~))) -47
true 0)))
(map #(int (char %)) s))))
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;
}
fsharp
#light

let rotChar (s:int) (l:int) (h:int) (c:char) =
let charCode = int c
let letterCount = h - l + 1
let newCharCode = (charCode - l + s) % letterCount + l
char newCharCode

let rot13 (text:string) =
let rotChar13 = function
| (c:char) when 'A' <= c && c <= 'Z' -> rotChar 13 (int 'A') (int 'Z') c
| c when 'a' <= c && c <= 'z' -> rotChar 13 (int 'a') (int 'z') c
| c -> c
new string([| for c in text -> rotChar13 c|])

let rot47 (text:string) =
let rotChar47 = function
| ' ' as c -> c
| c -> rotChar 47 (int '!') (int '~') c
new string([| for c in text -> rotChar47 c |])
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'
java
CharArrayWriter rot13 = new CharArrayWriter() ;
for (char c : i ) {
char lc = Character.toLowerCase(c) ;
rot13.append( c += ( (lc >= 'a' && lc <= 'm') ? 13 : ( (lc >= 'n' && lc <= 'z') ? -13 : 0 ) )) ;
}

CharArrayWriter rot47 = new CharArrayWriter() ;
for (char c : i )
rot47.append( c += ( (c >= '!' && c <= 'O') ? 47 : ( (c >= 'P' && c <= '~') ? -47 : 0 ) )) ;
ocaml
let rot_char13 c = match c with
| 'A'..'M' | 'a'..'m' -> Char.chr ((Char.code c) + 13)
| 'N'..'Z' | 'n'..'z' -> Char.chr ((Char.code c) - 13)
| _ -> c

let rot_char47 c = match c with
| '!'..'N' -> Char.chr ((Char.code c) + 47)
| 'O'..'~' -> Char.chr ((Char.code c) - 47)
| _ -> c

let rot f str =
let len = String.length str in
let res = String.create len in
for i = 0 to pred len do
res.[i] <- f str.[i]
done;
(res)

let rot13 = rot rot_char13
let rot47 = rot rot_char47
python
# rot13, readable
rot13_tbl = string.maketrans("ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz", "NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm")
string.translate("Hello World #123", rot13_tbl)


#
# "a bad programmer can write bad code in any language"
#

# rot13, "clever"
string.translate("Hello World #123", string.maketrans(string.lowercase+string.uppercase, string.lowercase[13:]+string.lowercase[:13]+string.uppercase[13:]+string.uppercase[:13]))

# rot47, very "clever"
''.join([ord(c) in range(33,127) and chr(((ord(c)-33+47)%(127-33))+33) or c for c in "Hello World #123"])

"Hello World #123".encode('rot13')
scala
val uppers = 'A' to 'Z'
val lowers = 'a' to 'z'

val alpha13 = (uppers ++ lowers).mkString
val beta13 = ((uppers drop 13) ++ (uppers take 13) ++ (lowers drop 13) ++ (lowers take 13)).mkString

val alpha47 = """!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""
val beta47 = """PQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO"""

// generic translation function
def rot (alpha: String, beta: String)(c: Char) = if (alpha contains c) beta(alpha indexOf c) else c

// specific translation functions curried with the respective alphabets
val rot13 = rot(alpha13, beta13) _
val rot47 = rot(alpha47, beta47) _

assert(("Hello World #123" map rot13).toString == "Uryyb Jbeyq #123")
assert(("Hello World #123" map rot47).toString == "w6==@ (@C=5 R`ab")

Make a string uppercase

Transform "Space Monkey" into "SPACE MONKEY"
clojure
(.toUpperCase "Space Monkey")
cpp
String(L"Space Monkey").ToUpper();
std::string s = "Space Monkey";
std::transform(s.begin(), s.end(), s.begin(), std::toupper);
std::string s = "Space Monkey";
boost::to_upper(s);
fsharp
printfn "%s" ("Space Monkey".ToUpper())
printfn "%s" (String.uppercase "Space Monkey")
groovy
println "Space Monkey".toUpperCase()
java
String upper = text.toUpperCase();
ocaml
String.uppercase "Space Monkey";;
python
"Space Monkey".upper()
scala
println("Space Monkey".toUpperCase)

Make a string lowercase

Transform "Caps ARE overRated" into "caps are overrated"
clojure
(.toLowerCase "Caps ARE overRated")
cpp
std::string s = "Caps ARE overRated";
std::string sl(boost::to_lower_copy(s));
String(L"Caps ARE overRated").ToLower();
fsharp
printfn "%s" ("Caps ARE overRated".ToLower())
printfn "%s" (String.lowercase "Caps ARE overRated")
groovy
println "Caps ARE overRated".toLowerCase()
java
"Caps ARE overRated".toLowerCase();
ocaml
String.lowercase "Caps ARE overRated";;
python
"Caps ARE overRated".lower()
scala
"Caps ARE overRated".toLowerCase

Capitalise the first letter of each word

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

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

boost::split(swv, words, boost::is_any_of(" "));
std::string newwords = (std::for_each(swv.begin(), swv.end(), StringTAndJ(WordToCaps))).value();
fsharp
let words = String.Join(" ", Array.map (fun (s : String) -> (String.capitalize (s.ToLower()))) ("man OF stEEL".Split [|' '|]))
let wordlst = List.map (fun s -> (String.capitalize (String.lowercase s))) (String.split [' '] "man OF stEEL")
let words = new StringBuilder(List.hd wordlst)
for (s : String) in (List.tl wordlst) do (words.Append(" ").Append(s))
// Previous solutions used old library functions, here's something that works with F# 2.0
let s= "man OF stEEL"
let UpperFirst = function | "" -> "" | s -> s.Substring(0,1).ToUpper() + s.Substring(1).ToLower()
s.Split(' ') |> Array.map UpperFirst |> String.concat " "
let culture = System.Globalization.CultureInfo.GetCultureInfo("en-US")
let titleCase = culture.TextInfo.ToTitleCase "man oF sTeel"
groovy
def capitalize(s) { s[0].toUpperCase() + s[1..-1].toLowerCase() }
caps = "man OF stEEL".replaceAll(/\w+/) { w -> capitalize(w) }
caps = "man OF stEEL".replaceAll(/\w+/) { w -> StringUtils.capitalize(w.toLowerCase()) }
caps = WordUtils.capitalizeFully("man OF stEEL")
java
String input = "man OF stEEL";
StringTokenizer tokenizer = new StringTokenizer(input);
StringBuffer sb = new StringBuffer();
while (tokenizer.hasMoreTokens()) {
String word = tokenizer.nextToken();
sb.append(word.substring(0, 1).toUpperCase());
sb.append(word.substring(1).toLowerCase());
sb.append(' ');
}
String text = sb.toString();
StringBuilder sb = new StringBuilder("man OF stEEL"); String s = sb.toString();
int last = s.length() - 1;

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

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

let () =
print_endline (capitalize_words "man OF stEEL")
python
from string import capwords
capwords("man OF stEEL")
' '.join(s.capitalize() for s in "man OF stEEL".split())
"man OF stEEL".title()
scala
def capitalize(s: String) = { s(0).toUpperCase + s.substring(1, s.length).toLowerCase }

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

Find the distance between two points

clojure
(defstruct point :x :y)

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

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

(distance [2 2] [3 3])
cpp
Point p1 = {34, 78}, p2 = {67, -45};
double distance = ::distance(p1, p2);
Console::WriteLine("{0,3:F2}", distance);
fsharp
let distance' = distance (34, 78) (67, -45)
printfn "%3.2f" distance'
groovy
distance = distance(x1, y1, x2, y2)
distance = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1))
java
double distance = Point2D.distance(x1, y1, x2, y2);
Point2D point1 = new Point2D.Double(x1, y1);
Point2D point2 = new Point2D.Double(x2, y2);
double distance = point1.distance(point2);
double distance = Math.hypot(x2-x1, y2-y1);
ocaml
type point = { x:float; y:float };;
let distance a b = sqrt((a.x -. b.x)**2. +. (a.y -. b.y)**2.);;
python
# problem description doesn't say 2D points ;)
from math import sqrt
print sqrt(sum((x-y)**2 for x,y in zip(a, b)))
from math import hypot
print hypot(x2-x1, y2-y1)
scala
val distance$ = distance((34, 78), (67, -45))
println(distance$)
val distance$ = distance(new Point(34, 78), new Point(67, -45))
println(distance$)
def distance (p1: (Int, Int), p2: (Int, Int)) = {
val (p1x, p1y) = p1
val (p2x, p2y) = p2
val dx = p1x - p2x
val dy = p1y - p2y
Math.sqrt(dx*dx + dy*dy)
}
println(distance((34, 78), (67, -45)))

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

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042
clojure
(defn pad
([x] (if (> 8 (.length (str x))) (pad (str 0 x)) (str x)))
)
(defn pad [x]
(format "%08d" x))
(format "%08d" 42)
cpp
String^ formatted = Convert::ToString(42)->PadLeft(8, '0');
String^ formatted = String::Format("{0,8:D8}", 42);
std::printf("%08d", 42);
std::ostringstream os;
os << std::setw(8) << std::setfill('0') << 42 << std::ends;
std::cout << os.str() << std::endl;
std::cout << boost::format("%|08|") % 42 << std::endl;
fsharp
printfn "%08d" 42
let formatted = sprintf "%08d" 42
printfn "%s" formatted
let buffer = new StringBuilder()
Printf.bprintf buffer "%08d" 42
printfn "%s" (buffer.ToString())
let formatted = String.Format("{0,8:D8}", 42)
Console.WriteLine(formatted)
let formatted = Convert.ToString(42).PadLeft(8, '0')
Console.WriteLine(formatted)
groovy
formatted = new DecimalFormat('00000000').format(42)
formatted = 42.toString().padLeft(8, '0')
// to stdout
printf "%08d\n", 42
// to a string
formatted = sprintf("%08d", 42)
formatted = String.format("%08d", 42)
java
String formatted = new DecimalFormat("00000000").format(42);
String formatted = String.format("%08d", 42);
ocaml
Printf.printf "%08d" 42;;
let s = Printf.sprintf "%08d" 42 in
print_string s;;
python
"%08d" % 42
scala
val formatted = String.format("%08d", int2Integer(42))
printf("%08d\n", 42)
println("%08d".format(42))

Right Space pad a number

Given the number 1024 right pad it to 6 characters "1024  "
clojure
(let [s (str 1024)
l (count s)]
(str s (reduce str (repeat (- 6 l) " "))))
cpp
String^ formatted = Convert::ToString(1024)->PadRight(6);
String^ formatted = String::Format("{0,-6:D}", 1024);
std::printf("%-6d\n", 1024);
std::ostringstream os;
os << std::setw(6) << std::setfill(' ') << std::left << 1024 << std::ends;
std::cout << os.str() << std::endl;
std::cout << boost::format("%|-6|") % 1024 << std::endl;
fsharp
printfn "%-6d" 1024
let formatted = String.Format("{0,-6:D}", 1024)
Console.WriteLine(formatted)
let formatted = Convert.ToString(1024).PadRight(6)
Console.WriteLine(formatted)
groovy
println 1024.toString().padRight(6)
formatted = sprintf("%-6d", 1024)
java
private static String spaces(int spaces) {
StringBuffer sb = new StringBuffer();
for(int i=0; i<spaces; i++) {
sb.append(' ');
}
return sb.toString();
}

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

Format a decimal number

Format the number 7/8 as a decimal with 2 places: 0.88
clojure
(format "%3.2f" (/ 7.0 8))
(* 0.01 (Math/round (* 100 (float (/ 7 8)))))
cpp
String^ formatted = String::Format("{0,3:F2}", result);
Console::WriteLine("{0,3:F2}", (7. / 8.));
std::printf("%3.2f\n", result);
std::ostringstream os;
os.width(3); os.fill('0'); os.setf(std::ios::fixed|std::ios::showpoint); os.precision(2);
os << result << std::ends;
std::cout << os.str() << std::endl;
std::cout << boost::format("%|3.2f|") % result << std::endl;
fsharp
printfn "%3.2f" (0.7 / 0.8)
let formatted = String.Format("{0,3:F2}", (0.7 / 0.8))
Console.WriteLine(formatted)
groovy
def result = 7/8
println result.round(new MathContext(2))
def result = 7/8
printf "%.2g", result
new Double(7/8).round(2)
java
String formatted = String.format("%3.2f", 7./8.);
ocaml
Printf.printf "%4.2f" (7. /. 8.);;
let s = Printf.sprintf "%4.2f" (7. /. 8.) in
print_string s;;
python
"%.2f" % (7 / 8.0)
round(7./8., 2)
scala
val formatted = String.format("%3.2f", double2Double(7./8.))
printf("%3.2f\n", 7./8.)

Left Space pad a number

Given the number 73 left pad it to 10 characters "        73"
clojure
(let [s (str 73)
l (count s)]
(str (reduce str (repeat (- 10 l) " ")) s ))
cpp
String^ formatted = Convert::ToString(73)->PadLeft(10);
String^ formatted = String::Format("{0,10:D}", 73);
std::printf("%10d\n", 73);
std::ostringstream os;
os << std::setw(10) << std::setfill(' ') << 73 << std::ends;
std::cout << os.str() << std::endl;
std::cout << boost::format("%|10|") % 73 << std::endl;
fsharp
let formatted = sprintf "%10d" 73
printfn "%s" formatted
let formatted = String.Format("{0,10:D}", 73)
Console.WriteLine(formatted)
let formatted = Convert.ToString(73).PadLeft(10)
Console.WriteLine(formatted)
groovy
println 73.toString().padLeft(10)
printf "%10d\n", 73
java
private static String spaces(int spaces) {
StringBuffer sb = new StringBuffer();
for(int i=0; i<spaces; i++) {
sb.append(' ');
}
return sb.toString();
}

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

Generate a random integer in a given range

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

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

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

unsigned rnd = generator();
fsharp
let rnd = new Random()
let rndInt = rnd.Next(100, 201)
groovy
random = new Random()
randomInt = random.nextInt(200-100+1)+100
java
Random random = new Random();
int randomInt = random.nextInt(200-100+1)+100;
ocaml
Random.self_init ();;
let a = 100 and b = 200 in
Random.int ( b - a + 1 ) + a;;
python
import random
random.randint(100, 200)
# uses best entropy source available (e.g. /dev/urandom, CryptGenRandom, ...)

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

Generate a repeatable random number sequence

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

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

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

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

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

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

rng.seed(42L);
std::cout << std::endl;
std::generate_n(std::ostream_iterator<unsigned>(std::cout, " "), 5, generator);
fsharp
let (seed, lb, ub) = (12345, 100, 200)

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

rnd <- new Random(seed)
for i = 1 to 5 do printf "%d " (rnd.Next(lb, ub + 1)) done ; printfn ""
groovy
random = new Random(12345)
orig = (1..5).collect { random.nextInt(200-100+1)+100 }
random = new Random(12345)
repeat = (1..5).collect { random.nextInt(200-100+1)+100 }
assert orig == repeat
java
int[] arr1 = genFillRand(new int[5], new Random(12345), 100, 200);
int[] arr2 = genFillRand(new int[5], new Random(12345), 100, 200);

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

Stream.npeek 5 (random_stream 1);;
Stream.npeek 5 (random_stream 1);;
python
import random

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

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

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

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

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
clojure
(if (re-matches #"[A-Z][a-z]+" "Hello")
(println "ok"))
cpp
if ((gcnew Regex("[A-Z][a-z]+"))->IsMatch("Hello")) Console::WriteLine("ok");
if (Regex::IsMatch("Hello", "[A-Z][a-z]+")) Console::WriteLine("ok");
Regex^ rx = gcnew Regex("[A-Z][a-z]+");
if (rx->IsMatch("Hello")) Console::WriteLine("ok");
cmatch what;
if (regex_match("Hello", what, regex("[A-Z][a-z]+")))
cout << "ok" << endl;
fsharp
if (Regex.IsMatch("Hello", "[A-Z][a-z]+")) then printfn "ok"
groovy
if ("Hello" =~ /[A-Z][a-z]+/) println 'ok'
if ("Hello".find(/[A-Z][a-z]+/)) println 'ok'
// with precompiled regex
def regex = ~/[A-Z][a-z]+/
if ("Hello".find(regex)) println 'ok'
// with precompiled regex
def regex = ~/[A-Z][a-z]+/
if ("Hello".matches(regex)) println 'ok'
if ("Hello".matches("[A-Z][a-z]+")) println 'ok'
java
if ("Hello".matches("[A-Z][a-z]+")) {
System.out.println("ok");
}
ocaml
if Str.string_match (Str.regexp "[A-Z][a-z]+") "Hello" 0
then print_string "ok";;
python
found = re.match(r'[A-Z][a-z]+', 'Hello')
if found:
print 'ok'
scala
if ("Hello".matches("[A-Z][a-z]+")) println("ok")

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
clojure
(if-let [groups (re-matches #"one (.*) three" "one two three")]
(println (second groups)))
cpp
Match^ match = Regex::Match("one two three", "one (.*) three");
if (match->Success) Console::WriteLine("{0}", match->Groups[1]->Captures[0]);
cmatch what;
if (regex_match("one two three", what, regex("one (.*) three")))
cout << what[1] << endl;
fsharp
let regmatch = (Regex.Match("one two three", "one (.*) three"))
if regmatch.Success then (printfn "%s" (regmatch.Groups.[1].Captures.[0].ToString()))
groovy
matcher = ("one two three" =~ /one (.*) three/)
if (matcher) println matcher[0][1]
match = "one two three".find("one (.*) three") { it[1] }
if (match) println match
java
Pattern pattern = Pattern.compile("one (.*) three");
Matcher matcher = pattern.matcher("one two three");
if (matcher.matches()) {
System.out.println(matcher.group(1));
}
ocaml
#load "str.cma" ;;

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

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/
clojure
(if (re-find #"\d+" "abc 123 @#$")
(println "ok"))
cpp
if (Regex::IsMatch("abc 123 @#$", "\\d+")) Console::WriteLine("ok");
fsharp
if (Regex.IsMatch("abc 123 @#$", "\\d+")) then printfn "ok"
groovy
if ('abc 123 @#$' =~ /\d+/) println 'ok'
if ('abc 123 @#$'.find(/\d+/)) println 'ok'
java
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
System.out.println("ok");
}
ocaml
#load "str.cma" ;;

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

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

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

while (match->Success)
{
list->Add(match->Groups[1]->Captures[0]->ToString() + match->Groups[2]->Captures[0]->ToString());
match = match->NextMatch();
}
fsharp
let list = new ResizeArray<string>()
let mutable regmatch = (Regex.Match("(fish):1 sausage (cow):3 tree (boat):4", "\\((\\w+)\\):(\\d+)"))

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

for word in list do printfn "%s" word done
// A solution without mutation:
let results =
Regex.Matches("(fish):1 sausage (cow):3 tree (boat):4", "\\((\\w+)\\):(\\d+)")
|> Seq.cast
|> Seq.map (fun (regmatch: Match) ->
regmatch.Groups.[1].Captures.[0].ToString() + regmatch.Groups.[2].Captures.[0].ToString()
)
|> List.ofSeq
groovy
list = (text =~ /\((\w+)\):(\d+)/).collect{ it[1] + it[2] }
list = []
text.eachMatch(/\((\w+)\):(\d+)/){
list << it[1] + it[2]
}
list = []
text.eachMatch(/\((\w+)\):(\d+)/){ m, name, number ->
list << "$name$number"
}
list = (text =~ /\((\w+)\):(\d+)/).collect{ all, name, num -> "$name$num" }
list = text.findAll(regex){ _, name, num -> "$name$num" }
list = text.findAll(regex){ it[1] + it[2] }
java
List list = new ArrayList();
Pattern pattern = Pattern.compile("\\((\\w+)\\):(\\d+)");
Matcher matcher = pattern.matcher(text);
while(matcher.find()) {
list.add(matcher.group(1)+matcher.group(2));
}
ocaml
let result =
let str = "(fish):1 sausage (cow):3 tree (boat):4" in
let ms = Pcre.exec_all ~pat:"\\((\\w+)\\):(\\d+)" str in
Array.to_list (
Array.map (fun m ->
let s = Pcre.get_substrings m in
Printf.sprintf "%s%s" s.(1) s.(2);
) ms
)
python
map(''.join, re.findall(r"\((\w+)\):(\d+)", "(fish):1 sausage (cow):3 tree (boat):4"))
--------------------------------------------------------------------------
(''.join(m.groups()) for m in re.finditer(r"\((\w+)\):(\d+)", "(fish):1 sausage (cow):3 tree (boat):4"))
scala
val m = Pattern.compile("\\((\\w+)\\):(\\d+)").matcher("(fish):1 sausage (cow):3 tree (boat):4")
var list : List[String] = Nil

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

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 "*"
clojure
(.replaceFirst (re-matcher #"e" "Red Green Blue") "*")
cpp
String^ Replaced = (gcnew Regex("e"))->Replace("Red Green Blue", "*", 1);
fsharp
let replaced = ((new Regex("e")).Replace("Red Green Blue", "*", 1))
printfn "%s" replaced
groovy
replaced = "Red Green Blue".replaceFirst("e", "*")
java
String replaced = "Red Green Blue".replaceFirst("e", "*");
ocaml
let replaced = Str.replace_first (Str.regexp "e") "*" "Red Green Blue" in
print_endline replaced ;;
python
print re.sub(r'e', '*', 'Red Green Blue', 1)
scala
val 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"
clojure
(.replaceAll (re-matcher #"se\w+" "She sells sea shells") "X")
cpp
String^ Replaced = (gcnew Regex("se\\w+"))->Replace("She sells sea shells", "X");
String^ Replaced = Regex::Replace("She sells sea shells", "se\\w+", "X");
fsharp
let replaced = ((new Regex("se\\w+")).Replace("She sells sea shells", "X"))
printfn "%s" replaced
groovy
replaced = text.replaceAll(/se\w+/,"X")
java
String replaced = text.replaceAll("se\\w+", "X");
ocaml
let s = "She sells sea shells" in
Str.global_replace (Str.regexp "se[^ \\t\\n]*") "X" s
python
transformed = re.sub(r'se\w+', 'X', 'She sells sea shells')
scala
val replaced = "She sells sea shells".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+)\}/.
clojure
(def *string* "The {Quick} Brown {Fox}")
(def *regex* (re-pattern #"\{(\w+)\}"))

(println
(loop [result ""
src *string*
replace-strs (re-seq *regex* *string*)]
(if (empty? src)
result
(let [[match replacement] (first replace-strs)]
(if (= (first src) (first match))
; At the beginning of a sequence that should be replaced.
; Do replacement of a single match
(recur (str result (apply str (reverse replacement)))
(drop (count match) src)
(rest replace-strs))
; else, just copy one char from the source to the result
(recur (str result (first src))
(rest src)
replace-strs))))))
(clojure.string/replace "The {Quick} Brown {Fox}"
#"\{(\w+)\}"
(fn [[_ word]] (apply str (reverse word))))
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));
fsharp
open System
open System.Text.RegularExpressions
let reverseMatch (m:Match) =
String(m.Groups.[1].Value.ToCharArray() |> Array.rev)
let output = Regex.Replace("The {Quick} Brown {Fox}", @"\{(\w+)\}", reverseMatch)
groovy
replaced = "The {Quick} Brown {Fox}".replaceAll(/\{(\w+)\}/, { full, word -> word.reverse() } )
java
Matcher m = Pattern.compile("\\{(\\w+)\\}").matcher("The {Quick} Brown {Fox}");
StringBuffer sb = new StringBuffer(32), rsb = new StringBuffer(8);

while (m.find())
{
rsb.replace(0, rsb.length(), m.group(1)); rsb.reverse(); m.appendReplacement(sb, rsb.toString());
}
m.appendTail(sb);
ocaml
let s = "The {Quick} Brown {Fox}" in
let r = Str.regexp "{\\([^ \\t\\n]*\\)}" in
Str.global_substitute r (fun m -> string_rev (Str.matched_group 1 m)) s
python
transformed = re.sub(r'\{(\w+)\}',
lambda match: match.group(1)[::-1],
'The {Quick} Brown {Fox}')
scala
val m = Pattern.compile("\\{(\\w+)\\}").matcher("The {Quick} Brown {Fox}")
val sb = new StringBuffer(32) ; val rsb = new StringBuffer(8)

while (m.find) { rsb.replace(0, rsb.length, m.group(1)) ; m.appendReplacement(sb, rsb.reverse.toString) }
m.appendTail(sb)

Define an empty list

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

java
List list = Collections.emptyList();
String[] list = {};
ocaml
let list = [];;
python
list = []
scala
val list = Nil
val list = List()
val list : List[String] = List()

Define a static list

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

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

list.push_back("One");
list.push_back("Two");
list.push_back("Three");
list.push_back("Four");
list.push_back("Five");
list<string> lst = { "One", "Two", "Three", "Four", "Five" };
list<string> lst;
lst += "One", "Two", "Three", "Four", "Five";
fsharp
let list = ["One"; "Two"; "Three"; "Four"; "Five"]
let list = (new Generic.LinkedList<string>([|"One"; "Two"; "Three"; "Four"; "Five"|]))
let list = (new Generic.LinkedList<string>())

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

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

Join the elements of a list, separated by commas

Given the list [Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
clojure
(apply str (interpose ", " '("Apple" "Banana" "Carrot")))
cpp
String^ result = String::Join(L", ", fruit->ToArray());
string fruits[] = {"Apple", "Banana", "Carrot"};
string result = boost::algorithm::join(fruits, ", ");
fsharp
let result = String.Join(", ", [|"Apple"; "Banana"; "Carrot"|])
let result = (List.fold_left (fun acc item -> acc ^ (", " ^ item)) (List.hd fruit) (List.tl fruit))
let result = (List.fold_left (fun (acc : StringBuilder) (item : string) -> acc.Append(", ").Append(item)) (new StringBuilder(List.hd fruit)) (List.tl fruit)).ToString()
groovy
string = fruit.join(', ')
string = fruit.toString()[1..-2]
java
StringBuffer sb = new StringBuffer();
for (Iterator it = fruit.iterator(); it.hasNext();) {
sb.append(it.next());
if (it.hasNext()) {
sb.append(", ");
}
}
String result = sb.toString();
StringBuilder sb = new StringBuilder(fruit.get(0));
for (String item : fruit.subList(1, fruit.size())) sb.append(", ").append(item);
String result = sb.toString();
String result = StringUtils.join(fruit, ", ");
ocaml
let () =
let lst = ["Apple"; "Banana"; "Carrot"] in
let str = String.concat ", " lst in
print_endline str
python
print ", ".join(['Apple', 'Banana', 'Carrot'])
scala
val result =
((fruit.tail foldLeft (new StringBuilder(fruit.head))) {(acc, e) => acc.append(", ").append(e)}).toString
val result = fruit.mkString(",")
val fruit = List[String]("Apple", "Banana", "Carrot")
println(fruit.mkString(", "))

Join the elements of a list, in correct english

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

// ------

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

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

if __name__ == "__main__":
assert join("Apple", "Banana", "Carrot") == "Apple, Banana, and Carrot"
assert join("One", "Two") == "One and Two"
assert join("Lonely") == "Lonely"
assert join(*[]) == ""
scala
def join(list : List[String]) : String = list match {
case List() => ""
case List(x) => x
case List(x,y) => x + " and " + y
case List(x,y,z) => x + ", " + y + ", and " + z
case _ => list(0) + ", " + join(list.tail)
}
def join(list : List[String]) : String = list match {
case List() => ""
case List(x) => x
case List(x,y) => x + " and " + y
case List(x,y,z) => x + ", " + y + ", and " + z
case x::xs => x + ", " + join(xs)
}
def join[T](list : List[T]) = list match {
case xs if xs.size < 3 => xs.mkString(" and ")
case xs => xs.init.mkString(", ") + ", and " + xs.last
}

Produce the combinations from two lists

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

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

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

cout << combo << endl;
fsharp
let combinations = (List.fold_left (fun acc number -> acc @ (List.map (fun letter -> (letter, number)) letters)) [] numbers)
let combinations aa bb =
aa
|> List.map (fun a -> bb |> List.map (fun b -> (a, b)))
|> List.concat
groovy
letters = ['a', 'b', 'c']
numbers = [4, 5]
combos = [letters, numbers].combinations()
java
List<String> combinations = new ArrayList<String>();

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

for (int number : numbers)
for (String letter : letters)
combinations.add(new AbstractMap.SimpleImmutableEntry<String, Integer>(letter, Integer.valueOf(number)));
ocaml
let combinations =
let l1 = ["a"; "b"; "c"]
and l2 = [4; 5] in
List.rev (
List.fold_left (fun acc y ->
List.fold_left (fun acc2 x ->
(x, y)::acc2
) acc l1
) [] l2
)
python
[(x, y) for y in [1,2] for x in ['a','b','c']]
import itertools
[x for x in itertools.product(["a", "b", "c"], [4, 5])]
scala
val combinations =
(numbers foldLeft List[Pair[String, Int]]()) { (acc : List[Pair[String, Int]], number : Int) =>
acc ::: (letters map { (letter : String) => Pair(letter : String, number : Int) }) }
def product(set1 : List[_], set2 : List[_]) : List[Pair[_, _]] =
{
val p = new mutable.ArrayBuffer[Pair[_, _]]()
for (e1 <- set1) for (e2 <- set2) p += Pair(e1, e2)
p.toList
}

// ------

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

From a List Produce a List of Duplicate Entries

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

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

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

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

for (auto &s: lst)
num_identical[s]++;
for (auto &n: num_identical)
if (n.second > 1)
dups.push_back(n.first);
cout << dups << endl;
fsharp
["andrew"; "bob"; "chris"; "bob"]
|> Seq.countBy id
|> Seq.filter (fun (k,n) -> n > 1)
|> Seq.map fst
|> Seq.toList
groovy
def input = ["andrew", "bob", "chris", "bob"]

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

assert output == ["bob"]
java
List listOfDuplicates = new ArrayList(Arrays.asList(new String[]{"andrew", "bob", "chris", "bob"}));

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

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

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

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

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

module StringSet = Set.Make(String)

module StringSetTools = SetTools(StringSet)

StringSetTools.find_duplicates ["andrew"; "bob"; "chris"; "bob"];;
python
import itertools
input = ["andrew", "bob", "chris", "bob"]
input.sort()
output = [k for k, g in itertools.groupby(input, lambda x: x) if len(list(g)) > 1]
scala
List("andrew", "bob", "chris", "bob")
.groupBy(identity)
.filter( person => person._2.size > 1)
.map(_._1)
val l = List("andrew", "bob", "chris", "bob")
l.diff(l.distinct)

Fetch an element of a list by index

Given the list [One, Two, Three, Four, Five], fetch the third element ('Three')
clojure
(nth '[One Two Three Four Five] 2)
cpp
String^ result = list[2];
fsharp
let result = List.nth ["One"; "Two"; "Three"; "Four"; "Five"] 2
groovy
list = ['One', 'Two', 'Three', 'Four', 'Five']
result = list[2] // index starts at 0
java
String result = list.get(2);
ocaml
let third = List.nth [ "One"; "Two"; "Three"; "Four"; "Five" ] 3;;
python
list = ['One', 'Two', 'Three', 'Four', 'Five']
list[2]
scala
val result = list(2)

Fetch the last element of a list

Given the list [Red, Green, Blue], access the last element ('Blue')
clojure
(last '[One Two Three Four Five])
cpp
String^ result = list[list->Count - 1];
string last_elem = lst.back();
fsharp
let last list =
let rec last' list' =
match list' with
| [x] -> x
| x :: xs -> last' xs
if List.is_empty list then failwith "empty list" else last' list

// ------

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

Find the common items in two lists

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

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

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

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

let beans = ["broad"; "mung"; "black"; "red"; "white"]
let colors = ["black"; "red"; "blue"; "green"]
printfn "%A" (findCommon(beans, colors)) ;;
groovy
beans = ['broad', 'mung', 'black', 'red', 'white']
colors = ['black', 'red', 'blue', 'green']
common = beans.intersect(colors)
assert common == ['black', 'red']
java
List beans = Arrays.asList(new String[]{"broad", "mung", "black", "red", "white"});
List colors = Arrays.asList(new String[]{"black", "red", "blue", "green"});

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

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

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

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

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

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

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

module StringSet = Set.Make(String)

module StringSetTools = SetTools(StringSet)
;;
let beans = ["broad"; "mung"; "black"; "red"; "white"] in
let colors = ["black"; "red"; "blue"; "green"] in
StringSetTools.find_common beans colors;;
python
beans = ['broad', 'mung', 'black', 'red', 'white']
colors = ['black', 'red', 'blue', 'green']

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

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

Display the unique items in a list

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

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


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

Generic::ICollection<int>^ result = makeSET<int>(ages);
list<int> input;
input += 18, 16, 17, 18, 16, 19, 14, 17, 19, 18;
input.sort();
unique_copy(input.begin(), input.end(), ostream_iterator<int>(cout, "\n"));
fsharp
(Set.ofList [18; 16; 17; 18; 16; 19; 14; 17; 19; 18]) |> Set.iter (fun age -> printf "%d, " age)
groovy
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
println ages.unique()
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
unique = ages as Set
println unique
java
Set<Integer> ages = new TreeSet<Integer>(Arrays.asList(new Integer[]{18, 16, 17, 18, 16, 19, 14, 17, 19, 18}));

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

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

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

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

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

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

module IntegerSet = Set.Make(Integer)
module IntegerSetTools = SetTools(IntegerSet)
;;
IntegerSetTools.unique [18; 16; 17; 18; 16; 19; 14; 17; 19; 18];;
python
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]

unique_ages = list(set(ages))
scala
val ages = (18 :: 16 :: 17 :: 18 :: 16 :: 19 :: 14 :: 17 :: 19 :: 18 :: Nil) removeDuplicates

Remove an element from a list by index

Given the list [Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
clojure
(let [fruit ["Apple" "Banana" "Carrot"]
index 0]
(concat
(take index fruit)
(drop (+ index 1) fruit)))
cpp
fruit->RemoveAt(0);
fsharp
let split_at list n =
let rec split_at' list' n' left right =
match list' with
| [] -> (List.rev left, List.rev right)
| x :: xs -> if n' <= n then split_at' xs (n' + 1) (x :: left) right else split_at' xs (n' + 1) left (x :: right)
split_at' list 0 [] []

// ------

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

// ------

let result = (drop fruit 1)
groovy
// to produce a new list
newlist = list.tail() // for 'Apple' at start
newlist = list - 'Apple' // for 'Apple' anywhere
// mutate original list
list.remove(0)
java
list.remove(0);
ocaml
let delete_at i al =
if i < 0 || i >= List.length al then
invalid_arg "delete_at"
else
let rec del i l =
match l with
| [] -> []
| h::t when i = 0 -> t
| h::t -> h :: del (i-1) t
in
del i al
;;
let rem_first l =
match l with
| [] -> []
| h::t -> t
;;
List.tl ["Apple"; "Banana"; "Carrot"]
python
myList = ['Apple', 'Banana', 'Carrot']
print myList
del myList[0]
# or
myList.pop(0) # returns 'Apple'
print myList
scala
val (fl, fr) = fruit.splitAt(0) ; fruit = fl ::: fr.tail
fruit = fruit.tail
fruit = fruit.drop(1)
fruits = fruits.remove(fruits.indexOf(_) == 0)

Remove the last element of a list

clojure
(pop ["Apple" "Banana" "Carrot"])
cpp
fruit->RemoveAt(fruit->Count - 1);
fsharp
let take list n =
if n <= 0 then
list
else
let (left, _) = split_at list (n - 1)
left

// ------

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

// ------

let result = (but_last fruit)
groovy
list = ['Apple', 'Banana', 'Carrot']
// to produce a new list
newlist = list[0,1]
// to modify original list
list.remove(2)
java
list.remove(list.size() - 1);
ocaml
let remove_last list =
match (List.rev list) with
| h::t -> List.rev t
| [] -> []
let remove_last lst =
List.rev (List.tl (List.rev lst))
let list_remove_last l =
let rec aux h q acc =
match q with
| [] -> List.rev acc
| h2 :: q -> aux h2 q (h :: acc) in
match l with
| [] -> invalid_arg "list_remove_last"
| h :: q -> aux h q []
python
myList = ['Apple', 'Banana', 'Carrot']
myList.pop()

scala
fruit = fruit.init
fruit = fruit.take(fruit.length - 1)

Rotate a list

Given a list ["apple", "orange", "grapes", "bananas"], rotate it by removing the first item and placing it on the end to yield ["orange", "grapes", "bananas", "apple"]
clojure
(let [fruit ["apple" "orange" "grapes" "bananas"]]
(concat (rest fruit) [(first fruit)])
cpp
fruit->Add(fruit[0]); fruit->RemoveAt(0);
rotate(fruit.begin(), fruit.begin()+1, fruit.end());
fsharp
let rotate list n =
if n <= 0 then
list
else
let (left, right) = split_at list (n - 1)
right @ left

// ------

let result = (rotate fruit 1)
groovy
first = items.head()
items = items.tail() + first
items = items[1..-1] + items[0]
items = items + items.remove(0)
java
list.add(list.remove(0));
Collections.rotate(list, -1);
ocaml
let rotate list =
match list with
| head::tail -> tail@[head]
| [] -> []
python
l = ["apple", "orange", "grapes", "bananas"]
first, l = l[0], l[1:] + l[:1]
fruit = ['apple', 'orange', 'grapes', 'bananas']
fruit.append(fruit.pop(0))
scala
items = items.tail ::: List(items.head)
items = (items.head :: ((items.tail).reverse)).reverse

Gather together corresponding elements from multiple lists

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

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

(println (gatherer [firstnames lastnames years]))

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

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

for (firstIt = first.begin(), lastIt = last.begin(), yearIt = years.begin();
firstIt != first.end() && lastIt != last.end() && yearIt != years.end();
++firstIt, ++lastIt, ++yearIt)
actors.push_back(make_tuple(*firstIt, *lastIt, *yearIt));
fsharp
let result = (List.zip3 first last years)
groovy
first = ['Bruce', 'Tommy Lee', 'Bruce']
last = ['Willis', 'Jones', 'Lee']
years = [1955, 1946, 1940]
actors = [first, last, years].transpose()
assert actors.size() == 3
assert actors[1] == ['Tommy Lee', 'Jones', 1946]
java
String[] first = new String[]{"Bruce", "Tommy Lee", "Bruce"};
String[] last = new String[]{"Willis", "Jones", "Lee"};
String[] years = new String[]{"1955", "1946", "1940"};

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

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

actors = zip(first, last, years)

assert len(actors) == 3
assert actors[1] == ('Tommy Lee', 'Jones', 1946)
scala
def zip3(l1 : List[_], l2 : List[_],l3 : List[_]) : List[Tuple3[_, _, _]] =
{
def zip3$ (l1$ : List[_], l2$ : List[_], l3$ : List[_], acc : List[Tuple3[_, _, _]]) : List[Tuple3[_, _, _]] = l1$ match
{
case Nil => acc reverse
case l1$head :: l1$tail => zip3$(l1$tail, l2$.tail, l3$.tail, Tuple3(l1$head, l2$.head, l3$.head) :: acc)
}

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

// ------

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

List Combinations

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

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

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

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

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

card ace_of_harts = make_pair("h", "A");
if (end(cards) != find_if(begin(cards), end(cards),
[&](const card& c) { return c == ace_of_harts; }))
cout << "Deck contain 'Ace of Harts'" << endl;
else
cout << "Deck lacks 'Ace of Harts'" << endl;
fsharp
let cards = (List.fold_left (fun acc suite -> acc @ (List.map (fun face -> (suite, face)) faces)) [] suites)

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

// ------

let cards = product suites faces

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

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

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

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

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

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

let () =
assert (List.length desk = 52);
if List.mem ("A", "H") desk
then print_endline "Ace of Hearts found!"
else print_endline "Ace of Hearts not found :("
python
suites = ('H', 'D', 'C', 'S')
faces = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A')
deck = [(face,suite) for suite in suites for face in faces]
assert len(deck) == 52
assert ('A', 'H') in deck
scala
def product(set1 : List[_], set2 : List[_]) : List[Pair[_, _]] =
{
val p = new mutable.ArrayBuffer[Pair[_, _]]()
for (e1 <- set1) for (e2 <- set2) p += Pair(e1, e2)
p.toList
}

// ------

val cards = product(suites, faces)

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

Perform an operation on every item of a list

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

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

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

transform(begin(words),
end(words),
back_inserter(word_sizes),
[](const string& s) { return s.size(); });
fsharp
let lengths = List.map String.length ["ox"; "cat"; "deer"; "whale"]
groovy
animals = ["ox", "cat", "deer", "whale"]
assert animals*.size() == [2, 3, 4, 5]
java
public class SolutionXX {
public static void main(String[] args) {
String[] list = {"ox", "cat", "deer", "whale"};
for (String str : list) {
System.out.println(str.length() + " ");
}
}
}
ocaml
List.map String.length ["ox"; "cat"; "deer"; "whale"];;
python
print map(lambda x: len(x), ["ox", "cat", "deer", "whale"])
print [len(x) for x in ['ox', 'cat', 'deer', 'whale']]
scala

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

Split a list of things into numbers and non-numbers

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

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

(println (numberNonNumberSorter jumble))

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

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

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

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

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

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

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

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

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

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

// float and int are now in 'numbers' and the rest in 'non_numbers'
}
fsharp
let (things:obj list) = [ "hello"; 25; 3.14; System.DateTime.Now ]

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

let numbers, nonNumbers = things |> List.partition isNumber
groovy
now = new Date()
things = ["hello", 25, 3.14, now]
(numbers, others) = things.split{ it instanceof Number }
assert numbers == [25, 3.14]
assert others == ["hello", now]
java
public class NumbersSolution {
public static void main(String[] args) {
List<Object> items = Arrays.asList(new Object[] { new Date(), 12L, 15.4, 99, "x" } ) ;
List<Object> numbers = new ArrayList<Object>() ;
List<Object> nonNumbers = new ArrayList<Object>() ;
for (Object item : items )
(item instanceof Number ? numbers : nonNumbers).add(item) ;
}
}
public class NumbersSolution {
public static void main() {
List<Object> numbers = new ArrayList<Object>() ;
List<Object> nonNumbers = new ArrayList<Object>() ;
for (Object item : new Object[] { new Date(), 12L, 15.4, 99, "x" } )
(item instanceof Number ? numbers : nonNumbers).add(item) ;
}
}
ocaml
(* OCaml is a strongly statically typed language so it is not possible to mix
items of different types in a single list.
So here we use a list of strings, some of these strings represent a number *)

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

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

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

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

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

let numbers, others =
List.partition is_a_number [String "Joe"; Float 3.14; Int 8; Char 'Z']
python
import re
data = '34234aff340980adf0e0fa0fefl' ## or ''.join(array)

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


scala
val now = new java.util.Date()
val result = List("hello", 25, 3.14, now) partition { _.isInstanceOf[Number] }
assert(result == (List(25, 3.14), List("hello", now)))

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.
clojure
(every? #(> % 1) [2 3 4])
cpp
template <typename InputIterator, typename Predicate>
bool match_all(InputIterator first, InputIterator last, Predicate pred)
{
return find_if(first, last, !pred(_1)) == last;
}
fsharp
let rec IsAll predicate source =
let mutable acc = true
for e in source do
acc <- acc && (predicate e)
acc
groovy
[2,3,4].every{it > 1}
ocaml
(* from the interactive loop *)
# List.for_all (fun x -> x > 1) [2; 3; 4] ;;
- : bool = true
python
all(x > 1 for x in [2,3,4])
scala
List(2, 3, 4).forall { _ > 1 }
List(2, 3, 4).forall { x => x > 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.
clojure
; The standard library in Clojure has "not-any?" but (oddly enough) no "any?"
(defn any? [pred coll]
((complement not-any?) pred coll))

(any? #(> % 3) [2 3 4])
(some #(> % 3) [2 3 4])
cpp
template <typename InputIterator, typename Predicate>
bool match_any(InputIterator first, InputIterator last, Predicate pred)
{
return find_if(first, last, pred) != last;
}
fsharp
let rec IsAny predicate source =
match source with
| [] -> false
| h::t ->
if (predicate h) then true
else (IsAny predicate t )
groovy
[2,3,4].any{it > 3}
ocaml
(* from the interactive loop: *)
# List.exists (fun x -> x > 3) [2; 3; 4] ;;
- : bool = true
python
any(x > 3 for x in [2, 3, 4])
scala
List(2, 3, 4).exists { _ > 3 }
List(2, 3, 4).exists { x => x > 3 }

Define an empty map

clojure
(def m {})
cpp
Hashtable^ hash = gcnew Hashtable;
Generic::Dictionary<String^, String^>^ dict = gcnew Generic::Dictionary<String^, String^>();
std::map<int, std::string> m;
fsharp
let map = Map.empty
let map = new Generic.Dictionary<string, string>()
let map = new Hashtable()
groovy
def map = [:]
Map map = new HashMap();
java
Map map = new HashMap();
ocaml
module StringMap = Map.Make (String)
let m = StringMap.empty
let m = Hashtbl.create 42
python
map = {}
scala
val map = mutable.Map.empty
val map = mutable.HashMap.empty[String, Int]
val map = Map()

Define an unmodifiable empty map

clojure
; Clojure maps are immutable
(def m {})
cpp
const std::map<T1,T2> immutable_map_instance_of_type_t1_to_t2;
fsharp
// Most native fsharp data structures are immutable - updating a 'map' sees a modified copy created
let map = Map.empty
groovy
empty = Collections.EMPTY_MAP
map = [:].asImmutable()
def empty = MapUtils.EMPTY_SORTED_MAP
def empty = ImmutableMap.of()
java
Map empty = Collections.EMPTY_MAP;
SortedMap empty = MapUtils.EMPTY_SORTED_MAP;
ocaml
(* OCaml maps are functional data structures (so are immutable) *)
module StringMap = Map.Make (String)
let m = StringMap.empty
python
import collections
EmptyDict = collections.namedtuple("EmptyDict", "")
e = EmptyDict()
scala
val map = immutable.Map.empty
val map = immutable.TreeMap.empty[String, Int]
val map = Map()

Define an initial map

Define the map {circle:1, triangle:3, square:4}
clojure
(def m '{circle 1 triangle 1 square 4})
cpp
Hashtable^ shapes = gcnew Hashtable;

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);
map<string, int> shapes;

shapes["circle"] = 1;
shapes["triangle"] = 3;
shapes["square"] = 4;
fsharp
let shapes = Map.ofList [("circle", 1); ("triangle", 3); ("square", 4)]
let shapes = Map.empty.Add("circle", 1).Add("triangle", 3).Add("square", 4)
let shapes = new Generic.Dictionary<string, int>()
shapes.Add("circle", 1)
shapes.Add("triangle", 3)
shapes.Add("square", 4)
let shapes = Map [("circle", 1); ("triangle", 3); ("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
java
Map shapes = new HashMap();
shapes.put("circle", 1);
shapes.put("triangle", 3);
shapes.put("square", 4);
Map shapes = new HashMap() {{ put("circle",1); put("triangle",3); put("square",4); }}
ocaml
module StringMap = Map.Make (String)

let m0 = StringMap.empty

let m1 = StringMap.add "circle" 1 m0
let m2 = StringMap.add "triangle" 3 m1
let m3 = StringMap.add "square" 4 m2
let m = Hashtbl.create 42;;

Hashtbl.replace m "circle" 1;;
Hashtbl.replace m "triangle" 3;;
Hashtbl.replace m "square" 4;;
python
shapes = {'circle': 1, 'square': 4, 'triangle': 2}
scala
val shapes = immutable.TreeMap("circle" -> 1, "triangle" -> 3, "square" -> 4)
val shapes = mutable.Map.empty[String, Int]

shapes += "circle" -> 1
shapes += "triangle" -> 3
shapes += "square" -> 4
var shapes = immutable.Map.empty[String, Int]

shapes = shapes + ("circle" -> 1)
shapes = shapes + ("triangle" -> 3)
shapes = shapes + ("square" -> 4)
val shapes = immutable.Map(
"circle" -> 1,
"triangle" -> 3,
"square" -> 4
)
val map = Map("circle" -> 1, "triangle" -> 3, "square" -> 4)

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"
clojure
(if (contains? '{joe cat mary turtle bill canary} 'mary)
(println "ok"))
cpp
if (pets->ContainsKey("mary")) Console::WriteLine("ok");
if (pets.find("mary") != pets.end()){
std::cout << "ok" << std::endl;
}
if (pets.count("mary") > 0)
cout << "ok" << endl;
fsharp
if (Map.mem "mary" pets) then printfn "ok"
if pets.ContainsKey("mary") then printfn "ok"
groovy
pets = [joe:'cat', mary:'turtle', bill:'canary']
if(pets.containsKey('mary')) println 'ok'
pets = [joe:'cat', mary:'turtle', bill:'canary']
if(pets.mary) println 'ok'
java
if (pets.containsKey("mary")) System.out.println("ok");
ocaml
module StringMap = Map.Make (String)

let map =
List.fold_left (fun map (key, value) ->
StringMap.add key value map
) StringMap.empty [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")]

let () =
if StringMap.mem "mary" map
then print_endline "OK"
let () =
let map = Hashtbl.create 42 in
List.iter (fun (key, value) ->
Hashtbl.add map key value
) [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")];

if Hashtbl.mem map "mary" then print_endline "OK"
python
pets = dict(joe='cat', mary='turtle', bill='canary')
if ("mary" in pets) print "ok"
scala
if (pets.contains("mary")) println("ok")
map.get("mary").foreach(println("ok"))

Retrieve a value from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
clojure
(def pets '{joe cat mary turtle bill canary})

(println (get pets 'joe))
cpp
if (pets->ContainsKey("joe")) Console::WriteLine(pets["joe"]);
cout << pets["joe"] << endl;
fsharp
if (Map.mem "joe" pets) then printfn "%s" (Map.find "joe" pets)
if (pets |> Map.exists (fun key _ -> key = "joe")) then printfn "%s" (Map.find "joe" pets)
let key = "joe"
match (pets |> Map.tryfind key) with
| Some(value) -> printfn "%s" value
| None -> printfn "Key %s not found" key
if pets.ContainsKey("joe") then printfn "%s" pets.["joe"]
if pets.ContainsKey("joe") then printfn "%s" (pets.["joe"] :?> string)
groovy
pets = [joe:'cat', mary:'turtle', bill:'canary']
assert pets['joe'] == 'cat'
assert pets.joe == 'cat'
java
String pet = pets.get("joe");
ocaml
module StringMap = Map.Make (String)

let map =
List.fold_left (fun map (key, value) ->
StringMap.add key value map
) StringMap.empty [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")]

let () =
try
let pet = StringMap.find "joe" map in
Printf.printf "Joe's pet is a %s.\n" pet
with Not_found ->
prerr_endline "No pet found for Joe."
let () =
let map = Hashtbl.create 42 in
List.iter (fun (key, value) ->
Hashtbl.add map key value
) [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")];

try
let pet = Hashtbl.find map "joe" in
Printf.printf "Joe's pet is a %s.\n" pet
with Not_found ->
prerr_endline "No pet found for Joe."
python
print pets['joe']
scala
if (pets.contains("joe")) println(pets("joe"))
println(pets.getOrElse("joe", "*** no pet owned ***"))
pets("joe")

Add an entry to a map

Given an empty pets map, add the mapping from "rob" to "dog"
clojure
(assoc {} 'rob 'dog)
cpp
pets->Add("rob", "dog");
pets["rob"] = "dog";
fsharp
pets <- (Map.add "rob" "dog" pets)
pets.Add("rob", "dog")
groovy
pets['rob'] = 'dog'
pets.rob = 'dog'
pets.put('rob', 'dog')
java
pets.put("rob", "dog");
ocaml
module StringMap = Map.Make (String)

let pets = StringMap.add "rob" "dog" StringMap.empty
let () =
let map = Hashtbl.create 42 in
Hashtbl.replace map "rob" "dog"
python
pets['rob'] = 'dog'
scala
pets += "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"
clojure
; Maps are immutable
; The following expression will return a new map without the 'bill key
(let [pets '{joe cat mary turtle bill canary}]
(println (get pets 'bill))
(dissoc pets 'bill))
cpp
if (pets->ContainsKey("bill"))
{
String^ value = safe_cast<String^>(pets["bill"]); pets->Remove("bill");
Console::WriteLine("{0}", value);
}
fsharp
let key = "bill"
match (pets |> Map.tryFind key) with
| Some(value) -> pets <- (Map.remove key pets) ; printfn "%s : %s removed" key value
| None -> printfn "Key %s not found" key
let key = "bill"
let entry = if (pets.ContainsKey(key)) then Some(pets.[key]) ; else None
pets.Remove(key)

match entry with
| Some(value) -> printfn "%s" value
| None -> printfn "key not found"
groovy
pets = [joe:'cat', mary:'turtle', bill:'canary']
println pets.remove('bill')
java
System.out.println(pets.remove("bill"))
ocaml
module StringMap = Map.Make (String)

let pets =
List.fold_left (fun map (key, value) ->
StringMap.add key value map
) StringMap.empty [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")]

let get_and_rem key m =
try
let value = StringMap.find key m in
let rm = StringMap.remove key m in
Some (value, rm)
with Not_found ->
None

let () =
let key = "bill" in
match get_and_rem key pets with
| Some (found, new_pets) ->
Printf.printf "%s : %s removed\n" key found
| None ->
Printf.printf "Key %s not found" key
let get_and_rem m key =
try
let value = Hashtbl.find m key in
Hashtbl.remove m key;
Some value
with Not_found ->
None

let () =
let pets = Hashtbl.create 42 in
List.iter (fun (key, value) ->
Hashtbl.add pets key value
) [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")];

let key = "bill" in
match get_and_rem pets key with
| Some found ->
Printf.printf "%s : %s removed\n" key found
| None ->
Printf.printf "Key %s not found" key
python
print pets.pop('bill')
scala
val pet = pets("bill") ; pets -= "bill" ; println(pet)
println(pets.removeKey("bill") match { case Some(pet) => pet ; case None => "***" })

Create a histogram map from a list

Given the list [a,b,a,c,b,b], produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list
clojure
(let [l '[a b a c b b]]
(loop [m {}
d (distinct l)]
(let [item (first d)]
(if (zero? (count d))
m
(recur
(assoc m
item
(count
(filter #(= item %) l)))
(rest d))))))
(->> [:a :b :a :c :b :b]
(group-by identity)
(reduce (fn [m e] (assoc m (first e) (count (second e)))) {}))
(reduce conj {} (for [[x xs] (group-by identity "abacbb")] [x (count xs)]))
(frequencies ["a","b","a","c","b","b"])
(frequencies '[a b a c b b])
cpp
for each(String^ entry in input) hash[entry] = hash->ContainsKey(entry)
? Convert::ToInt32(hash[entry]->ToString()) + 1 : 1;
for each(String^ entry in input) dict[entry] = dict->ContainsKey(entry) ? dict[entry] + 1 : 1;
map<string,int> hist;
for (auto e: { "a","b","a","c","b","b" })
++hist[e];
for (auto e: hist)
cout << e.first << " : " << e.second << endl;
fsharp
let histogram = (List.foldLeft (fun (acc : Map<char, int>) (e : char) -> if (Map.mem e acc) then (Map.add e ((Map.find e acc) + 1) acc) ; else (Map.add e 1 acc)) (Map.empty) list)
let histogram list =
let rec histogram' list' dict' =
match list' with
| [] -> dict'
| x :: xs ->
match Map.tryFind x dict' with
| Some(Value) -> histogram' xs (Map.add x (Value + 1) dict')
| None -> histogram' xs (Map.add x 1 dict')
histogram' list Map.empty

// ------

let histogram' = histogram list
let histogram = (List.foldLeft (fun (acc : Generic.Dictionary<char, int>) (e : char) -> (if acc.ContainsKey(e) then acc.[e] <- acc.[e] + 1 ; else acc.Add(e, 1)) ; acc) (new Generic.Dictionary<char, int>()) list)
let histogram =
list
|> Seq.groupBy (fun a -> a)
|> Seq.map(fun (key, elements) -> key, Seq.length elements)
|> Map.ofSeq
groovy
histogram = [:]
list.each { item ->
if (!histogram.containsKey(item)) histogram[item] = 0
histogram[item]++
}
histogram = [:]
list.each { histogram[it] = (histogram[it] ?: 0) + 1 }
java
Map map = new HashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
String s = (String) it.next();
if (!map.containsKey(s)) {
map.put(s, new Integer(1));
} else {
map.put(s, new Integer(((Integer)map.get(s)).intValue() + 1));
}
}
LinkedMap histogram = new LinkedMap();

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

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

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

h = {}
for k in "abacbb":
h[k] = h.setdefault(k, 0) + 1
from collections import Counter
h = Counter("abacbb")
print(h)
scala
list foreach { (x) => histogram += x -> (histogram.getOrElse(x, 0) + 1) }
val data = List("a", "b", "a", "c", "b", "b")
val keys = data removeDuplicates
val hist = Map.empty[String, Int] ++ keys.map{ k => (k, (data count (_==k)))}
assert(hist == Map("a"->2, "b"->3, "c"->1))
val histEntries = for {
key <- data.removeDuplicates
count = data.count(_ == key)
} yield (key -> count)
val hist = Map(histEntries: _*)
value.foldLeft(Map[T, Int]()){
(m, c) => m.updated(c, m.getOrElse(c, 0) + 1)
}

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

Categorise a list

Given the list [one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length
clojure
(loop [m {}
l ["one" "two" "three" "four" "five"]]
(if (zero? (count l))
m
(let [item (first l)
key (count item)]
(recur
(assoc m key (cons item (get m key [])))
(rest l)))))
(group-by count ["one" "two" "three" "four" "five"])
cpp
for each(String^ entry in input)
{
key = entry->Length;
if (!hash->ContainsKey(key)) hash[key] = gcnew ArrayList;
safe_cast<ArrayList^>(hash[key])->Add(entry);
}
fsharp
let catmap = (List.foldLeft (fun (acc : Map<int, List<string> >) (e : string) -> if (Map.mem e.Length acc) then (Map.add e.Length ((Map.find e.Length acc) @ [e]) acc) ; else (Map.add e.Length [e] acc)) (Map.empty) list)
let lengthMap =
["one"; "two"; "three"; "four"; "five"]
|> Seq.groupBy (fun s -> s.Length)
|> Seq.map (fun (length, entries) -> (length, entries |> List.ofSeq))
|> Map.ofSeq
groovy
map = ['one', 'two', 'three', 'four', 'five'].groupBy{ it.size() }
java
SortedMap<Integer, List<String> > map = new TreeMap<Integer, List<String> >(); int key; List<String> vlist;

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

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

Given a variable name, if the value is "Bob", display the string "Hello, Bob!". Perform no action if the name is not equal.
clojure
(def person "Bob")
(if (= person "Bob")
(println "Hello, Bob!"))
cpp
if (name == "Bob") Console::WriteLine("Hello, {0}!", name);
if (name == "Bob") std::cout << "Hello, " << name << "!" << std::endl;
fsharp
if name = "Bob" then printfn "Hello, %s!" name
name = "Bob" && begin printfn "Hello, %s!" name ; true end
groovy
if (name=='Bob')
println "Hello, Bob!"
java
if (name.equals("Bob")) {
System.out.println("Hello, Bob!");
}
ocaml
if name = "Bob"
then print_string "Hello, Bob!"
python
if name == 'Bob':
print 'Hello, Bob!'
scala
val name = "Bob"
if (name.equals("Bob")) printf("Hello, %s!\n", name)
val name = "Bob"

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

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

Given a variable age, if the value is greater than 42 display "You are old", otherwise display "You are young"
clojure
(def age 41)
(if (> age 42) "You are old" "You are young")
cpp
if (age > 42) Console::WriteLine("You are old");
else Console::WriteLine("You are young");
Console::WriteLine("You are {0}", (age > 42 ? "old" : "young"));
std::printf("You are %s\n", (age > 42 ? "old" : "young"));
fsharp
if age > 42 then printfn "You are old" else printfn "You are young"
let message = if age > 42 then "old" else "young"
printfn "You are %s" message
groovy
if (age > 42)
println "You are old"
else
println "You are young"
println "You are " + (age > 42 ? "old" : "young")
java
if (age > 42) {
System.out.println("You are old");
} else {
System.out.println("You are young");
}
System.out.println("You are " + ((age>42)?"old":"young"));
ocaml
if age > 42
then print_string "You are old"
else print_string "You are young"
python
if age > 42:
print 'You are old'
else:
print 'You are young'
print age > 42 and 'You are old' or 'You are young'
scala
val age = 42
if (age > 42) println("You are old") else println("You are young")
println( "You are " + ( if ( age > 42 ) "old" else "young" ) )

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

clojure
(println
(condp <= age
84 "You are really ancient"
30 "You are middle aged"
"You are young"))
cpp
if (age > 84) Console::WriteLine("You are really ancient");
else if (age > 30) Console::WriteLine("You are middle-aged");
else Console::WriteLine("You are young");
Console::WriteLine("You are {0}", (age > 84 ? "really ancient" : age > 30 ? "middle-aged" : "young"));
std::cout << "You are " << (age > 84 ? "really ancient" : age > 30 ? "middle-aged" : "young") << std::endl;
fsharp
if age > 84 then printfn "You are really ancient"
elif age > 30 then printfn "You are middle-aged"
else printfn "You are young"
let message = match age with
| _ when age > 84 -> "really ancient"
| _ when age > 30 -> "middle-aged"
| _ -> "young"
printfn "You are %s" message
groovy
if (age > 84)
println "You are really ancient"
else if (age > 30)
println "You are middle-aged"
else
println "You are young"
java
if (age > 84) System.out.println("You are really ancient");
else if (age > 30) System.out.println("You are middle-aged");
else System.out.println("You are young");
ocaml
if age > 84 then
print_endline "You are really ancient"
else if age > 30 then
print_endline "You are middle-aged"
else
print_endline "You are young"
python
if age > 84:
print 'You are really ancient'
elif age > 30:
print 'You are middle-aged'
else:
print 'You are young'
scala
val age = 65

if (age > 84) 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
clojure
(def n 112)

(println (str n
(let [rem (mod n 100)]
(if (and (>= rem 11) (<= rem 13))
"th"
(condp = (mod n 10)
1 "st"
2 "nd"
3 "rd"
"th")))))
cpp
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num,i,x;
cout<<"Enter the range:";
cin>>num;
for(i=1;i<=num;i++)
{
x=i%10;
switch(i)
{
case 11:
case 12:
case 13:cout<<i<<"th ";
continue;
}
switch(x)
{
case 1: cout<<i<<"st ";break;
case 2: cout<<i<<"nd ";break;
case 3: cout<<i<<"rd ";break;
default: cout<<i<<"th ";
}
}
getch();
}
fsharp
let suffix = function
| n when n > 10 && n < 20 -> "th"
| n when n % 10 = 1 -> "st"
| n when n % 10 = 2 -> "nd"
| n when n % 10 = 3 -> "rd"
| _ -> "th"

seq { 1 .. 40 }
|> Seq.iter (fun n -> printfn "%i%s" n (suffix n))
groovy
def suffix(n) {
switch(n) {
case { n % 100 in 4..20 } : return 'th'
case { n % 10 == 1 } : return 'st'
case { n % 10 == 2 } : return 'nd'
case { n % 10 == 3 } : return 'rd'
default : return 'th'
}
}
(1..40).each { n ->
println "$n${suffix(n)}"
}
java
String[] array = new String[40];
for(int n = 1; n <= array.length; n++)
array[n-1] = Integer.toString(n);
for(int n = 0; n < array.length; n++)
{
int y = Integer.parseInt(array[n]);
if(array[n].length() > 1)
y = Integer.parseInt(array[n].substring(1));
switch(y)
{
case 1: {array[n] += "st"; break;}
case 2: {array[n] += "nd"; break;}
case 3: {array[n] += "rd"; break;}
default: array[n] += "th";
}
}
ocaml
let numsuffix i =
match i with
| 11 | 12 | 13 -> "th"
| x when x mod 10 = 1 -> "st"
| x when x mod 10 = 2 -> "nd"
| x when x mod 10 = 3 -> "rd"
| _ -> "th"
;;
(* alternate implementation without using guards:
let numsuffix i =
match i with
| 11 | 12 | 13 -> "th"
| x -> match x mod 10 with
| 1 -> "st"
| 2 -> "nd"
| 3 -> "rd"
| _ -> "th"
*)

for i = 1 to 40 do
Printf.printf "%d%s " i (numsuffix i);
done;
print_newline ()
python
def affix(num):
num = num == 1 and str(num) + 'st' or num == 2 and str(num) + 'nd' or \
num == 3 and str(num) +'rd' or str(num) + 'th'
return num

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

scala
object FourToTwenties {
def unapply (n: Int) = (4 to 20).contains(n % 100)
}

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

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

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

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

while (x < 150) { x *= 2; Console::Write("{0},", x); }
Console::WriteLine();
for (int x = 1; x < 150; x *= 2) { std::cout << x << ","; }
std::cout << std::endl;
fsharp
let mutable x = 1
while x < 150 do printf "%d, " x ; (x <- x * 2) done
// The problem is clearly geared towards imperative languages ;-)
// No need to mutate any variable, here's how to do it loop-free functional:
let rec powers2 i = seq { if i < 150 then yield i; yield! powers2 (i*2) }
powers2 1 |> Seq.iter (fun i -> printf "%i, " i)
groovy
x = 1
while (x < 150) {
print x + ","
x *= 2
}
println()
java
int x = 1;
while (x < 150) {
System.out.println(x+",");
x*=2;
}
ocaml
let x = ref 1 ;;

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

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

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

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

int dice = rnd->Next(1, 7); Console::Write("{0}", dice);
do { Console::Write(",{0}", (dice = rnd->Next(1, 7))); } while (dice != 6);
Console::WriteLine();
fsharp
open System
let rand = Random()

Seq.initInfinite (fun _ -> rand.Next(1, 7))
|> Seq.takeWhile (fun x -> x < 6)
|> fun items -> String.Join(",", items)
|> function s when s = "" -> printfn "6" | s -> printfn "%s,6" s
groovy
// Groovy has no do..while; use a normal while
int dice = 0
while (dice != 6) {
dice = Math.random() * 6 + 1
print dice
if (dice != 6) print ','
}
java
int rnd;
do {
rnd = (int)(Math.random()*6)+1;
System.out.print(rnd);
if (rnd!=6) {
System.out.print(",");
}
} while(rnd!=6);
ocaml
let () =
Random.self_init ();
let rec loop () =
let n = (Random.int 6) + 1 in
print_int n;
if n <> 6 then (print_char ','; loop ())
else print_newline ()
in
loop ()
python
import random, itertools

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

print ", ".join(str(d) for d in itertools.takewhile(lambda x: x < 6, dice()))
scala
val dice = new GenRandInt(1, 6) ; var rnd = 0 ; var fmt = ""
do { rnd = dice.next ; fmt = if (rnd != 6) "%d," else "%d" ; printf(fmt, rnd) } while (rnd != 6)

Perform an action a fixed number of times (FOR)

Display the string "Hello" five times like "HelloHelloHelloHelloHello"
clojure
(dotimes [_ 5]
(print "Hello"))
cpp
for(int i = 0; i < 5; ++i) Console::Write("Hello");
for(int i = 5; i > 0; --i) Console::Write("Hello");
dotimes(5, hello);
fill_n(ostream_iterator<string>(cout), 5, "Hello");
fsharp
for i = 1 to 5 do printf "Hello" done
dotimes 5 (fun () -> printf "Hello")
// Repetition via ranging over a List type(index ignored)
for _ in list do printf "Hello" done
// Repetition via ranging over a Sequence type(index ignored)
for _ in sequence do printf "Hello" done
// Repetition via ranging over an Array type(index ignored)
for _ in array do printf "Hello" done
groovy
println "Hello" * 5
5.times { print "Hello" }; println()
java
for(int i=0;i<5;i++) {
System.out.print("Hello");
}
ocaml
let rec write_hello = function
0 -> ()
| n ->
print_string "Hello" ;
write_hello (n-1)
;;
write_hello 5;;
let write_hello n =
for i = 1 to n do
print_string "Hello";
done

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

Perform an action a fixed number of times with a counter

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

(println "Liftoff!")
cpp
for(int i = 10; i != 0; --i) Console::Write("{0} .. ", i);
Console::WriteLine("Liftoff!");
fsharp
for i = 10 downto 1 do printf "%d .. " i done
printfn "Liftoff!"
// Repetition via ranging over a Sequence type
for i in {10 .. -1 .. 1} do printf "%d .. " i done ; printfn "Liftoff!"
groovy
10.downto(1) { print it + " .. " }
println "Liftoff!"
java
for(int i=10; i>=1; i--) {
System.out.print(i + " .. ");
}
System.out.print("Liftoff!");
ocaml
for i = 10 downto 1 do
Printf.printf "%d .. " i
done;
print_endline "Liftoff!"
python
print " .. ".join(str(i) for i in range(10, 0, -1)), ".. liftoff!"
scala
for (i <- List.range(1, 11).reverse) printf("%d .. ", i) ; println("Liftoff!")
for (i <- List.range(-10, 0)) printf("%d .. ", (-i)) ; println("Liftoff!")
var i = 10 ; while (i > 0) { printf("%d .. ", i) ; i -= 1 } ; println("Liftoff!")
for (i <- -10 to -1) printf("%d .. ", (-i)) ; println("Liftoff!")

Read the contents of a file into a string

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

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

try
{
stream = gcnew IO::StreamReader("test.txt");
buffer = stream->ReadToEnd();
}
String^ buffer = IO::File::ReadAllText("test.txt");
fsharp
let file = new FileStream("test.txt", FileMode.Open)
let buffer = new String((new BinaryReader(file)).ReadChars(Convert.ToInt32(file.Length)))
let stream = new StreamReader("test.txt")
let buffer = stream.ReadToEnd()
let buffer = File.ReadAllText("test.txt")
groovy
contents = file.text
java
String text = FileUtils.readFileToString(new File("Solution109.java"), "UTF-8");
RandomAccessFile raf = null; byte[] buffer; String text = null;

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

let file_contents = read_file "file.txt"
python
contents = open('myFile.txt', 'rt').read()
scala
val text = FileUtils.readFileToString(new File("Solution467.scala"))
val text = Source.fromFile("Solution1256.scala").mkString("")

Process a file one line at a time

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

try
{
stream = gcnew IO::StreamReader("test.txt");
while ((ln = stream->ReadLine())) Console::WriteLine("{0}> {1}", ++i, ln);
}
int i = 0;
for each(String^ line in IO::File::ReadAllLines("test.txt")) Console::WriteLine("{0}> {1}", ++i, line);
fsharp
let stream = new StreamReader("test.txt")
let mutable i = 1
let mutable line = stream.ReadLine()
while (line <> null) do printfn "%d> %s" i line ; line <- stream.ReadLine() ; i <- i + 1 done
stream.Close()
let proc_a_line (filename : string) proc =
let stream = new StreamReader(filename)
let rec proc_a_line' count line =
match line with
| null -> stream.Close()
| _ -> proc count line ; proc_a_line' (count + 1) (stream.ReadLine())
proc_a_line' 1 (stream.ReadLine())

// ------

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

// ------

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

open System.IO
File.ReadLines("test.txt") |> Seq.iteri (fun i line -> printfn "%d> %s" (i + 1) line)
groovy
int count = 0
file.eachLine { line ->
println "${++count} > $line"
}
file.eachLine { line, count ->
println "${++count} > $line"
}
java
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("Solution104.java"));
String line = null;
int lineNumber = 1;
while ((line=br.readLine())!=null) {
System.out.println(lineNumber + "> " + line);
lineNumber++;
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (br!=null) {
try {
br.close();
} catch (Exception e) {
// ok
}
}
}
LineNumberReader lnr = null; PrintWriter pw = null; String line;

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

let () =
let ic = open_in Sys.argv.(1) in
let rec aux i =
match input_line_opt ic with
| Some line ->
Printf.printf "%d> %s\n" i line;
aux (succ i)
| None ->
close_in ic
in
aux 1
python
for no, line in enumerate(open(__file__)):
print "{0}> {1}".format(no+1, line.rstrip())
scala
val source = Source.fromFile(new File("Solution468.scala")).getLines
var n = 1 ; while (source.hasNext) { printf("%d> %s", n, source.next) ; n += 1 }
val source = Source.fromFile(new File("Solution469.scala")).getLines
for ((line, n) <- source zipWithIndex) { printf("%d> %s", (n + 1), line) }

Write a string to a file

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

try
{
stream = gcnew IO::StreamWriter("test.txt", false);
stream->WriteLine("This line overwites file contents!");
}
fsharp
let stream = new StreamWriter("test.txt", false)
stream.WriteLine("This line overwrites file contents!")
groovy
file.delete()
file << 'some text'
file.text = 'some text'
java
FileWriter fw = null;

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

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

Append to a file

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

try
{
stream = gcnew IO::StreamWriter("test.txt", true);
stream->WriteLine("This line appended to file!");
}
fsharp
let stream = new StreamWriter("test.txt", true)
stream.WriteLine("This line appended to file!")
groovy
file << 'some text'
java
FileWriter fw = null;

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

try
{
pw = new PrintWriter(new BufferedWriter(new FileWriter("test.txt", true)));
pw.print("This line appended to file!");
}
ocaml
let () =
let oc =
open_out_gen
[Open_wronly; Open_creat; Open_append; Open_text] 0o666 "test.txt" in
output_string oc "This line appended to file!\n";
close_out oc
python
open('test.txt', 'at').write('Hello World!\n')
scala
val fw = new FileWriter("test.txt", true) ; fw.write("This line appended to file!") ; fw.close()

Process each file in a directory

clojure
; (defn process-file [f] "process one file" body...)
(map process-file (.listFiles (File. ".")))
cpp
for each(String^ filename in IO::Directory::GetFiles(dirname)) process(filename);
fsharp
let dirname = "c:\\"

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

Directory.GetFiles(dirname) |> Array.iter (fun filename -> printfn "%s" filename)
groovy
dir.eachFile{ f -> process(f) }
java
for (File file : (new File("c:\\")).listFiles()) process(file);
ocaml
let process dir file =
if not (Sys.is_directory (Filename.concat dir file))
then print_endline file

let () =
let dir = "." in
let files = Sys.readdir dir in
Array.iter (process dir) files
python
import os
results = (process(f) for f in os.listdir(".") if os.path.isfile(f))
scala
for (file <- new File("c:\\").listFiles) { processFile(file) }

Process each file in a directory recursively

clojure
; (defn process-file [f] "process one file" body...)
(map process-file (file-seq (File. ".")))
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:\\");
}
fsharp
let processDirectory dirname proc =
let rec processDirectory' dirname' =
Directory.GetFiles(dirname') |> Array.iter proc
Directory.GetDirectories(dirname') |> Array.iter processDirectory'
processDirectory' dirname

// ------

let dirname = "c:\\"

processDirectory dirname (fun filename -> printfn "%s" filename)
groovy
dir.eachFileRecurse{ f -> process(f) }
java
processDirectory(new File("c:\\"));
ocaml
let rec recurse_dir dir f =
let filenames = Sys.readdir dir in
Array.iter (fun name ->
let fullname = Filename.concat dir name in
if Sys.is_directory fullname then
recurse_dir fullname f
else
f fullname
) filenames
;;
recurse_dir (Sys.getenv "HOME") print_endline ;;
python
import os
results = (process(os.path.join(p, n)) for p,d,l in os.walk(".") for n in l)
scala
processDirectory(new File("c:\\"))

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.
clojure
(.. (SimpleDateFormat. "yyyy-MM-dd HH:mm")
(parse "2008-05-06 13:29"))
cpp
DateTimeOffset^ dateTime = DateTimeOffset::Parse("2008-05-06 13:29");

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

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

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

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

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

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

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

printfn "%s" (dsb.ToString())
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")
java
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = df.parse("2008-05-06 13:29");
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");
DateTime dt = fmt.parseDateTime("2008-05-06 13:29");
ocaml
let s = "2008-05-06 13:29" in
let r = Str.regexp "\\([0-9][0-9][0-9][0-9]\\)-\\([0-9][0-9]\\)-\\([0-9][0-9]\\) \\([0-9][0-9]\\):\\([0-9][0-9]\\)" in
assert (Str.string_match r s 0);
Unix.mktime { Unix.tm_sec = 0;
tm_min = int_of_string (Str.matched_group 5 s);
tm_hour = int_of_string (Str.matched_group 4 s);
tm_mday = int_of_string (Str.matched_group 3 s);
tm_mon = int_of_string (Str.matched_group 2 s) - 1;
tm_year = int_of_string (Str.matched_group 1 s) - 1900;
tm_wday = -1;
tm_yday = -1;
tm_isdst = true; (** Daylight time savings in effect *)
}
python
import time
time.strptime("2008-05-06 13:29", "%Y-%m-%d %H:%M")
scala
val date = new SimpleDateFormat("yyy-MM-dd HH:mm").parse("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.
clojure
(let [cal (Calendar/getInstance)]
(.add cal Calendar/DAY_OF_YEAR 8)
(println (.format (SimpleDateFormat. "d, D, MMMM, EEEE")
(.getTime cal))))
cpp
QDate dateEightDaysFromNow = QDate::currentDate().addDays(8);
fsharp
Using F# interactive

> let Then = DateTime.Now.AddDays(8.0)
- let dayNumber = Then.DayOfYear.ToString()
- let solution = Then.ToString("dd " + dayNumber + " MMMM dddd");;

val Then : DateTime = 08/08/2010 08:58:05
val dayNumber : string = "220"
val solution : string = "08 220 August Sunday"

>
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')
java
Calendar cal = Calendar.getInstance();
cal.add(DAY_OF_YEAR, 8);
System.out.println(cal.get(DAY_OF_MONTH));
System.out.println(cal.get(DAY_OF_YEAR));
System.out.println(new SimpleDateFormat("MMMM").format(cal.getTime()));
System.out.println(new SimpleDateFormat("EEEE").format(cal.getTime()));
ocaml
let days = [| "Sunday"; "Monday"; "Tuesday"; "Wednesday"; "Thursday"; "Friday"; "Saturday" |]
let months = [| "January"; "February"; "March"; "April"; "May"; "June"; "July"; "August"; "September"; "October"; "November"; "December" |]

let current_time = Unix.time () in
let one_day = 86400. (* seconds *) in
let future_time = Unix.localtime (current_time +. 8. *. one_day) in
Printf.printf "day of month = %d, day of year = %d, month name = %s, day name = %s\n"
future_time.Unix.tm_mday
future_time.Unix.tm_yday
months.(future_time.Unix.tm_mon)
days.(future_time.Unix.tm_wday)
python
from datetime import datetime, timedelta

eightDaysFromNow = datetime.now() + timedelta(days=8)

print eightDaysFromNow.strftime('%d') # day of month
print eightDaysFromNow.strftime('%j') # day of year
print eightDaysFromNow.strftime('%B') # month name FULL
print eightDaysFromNow.strftime('%A') # day of week name FULL
scala
import java.util.Calendar
import java.text.SimpleDateFormat

val formatString = "d, D, MMMM, EEEE"
val cal = Calendar.getInstance

cal.add(Calendar.DAY_OF_YEAR, 8)

println(new SimpleDateFormat(formatString) format cal.getTime)

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.)
clojure
(let [time (.getTime (GregorianCalendar. 2009 Calendar/JANUARY 1))]
(doseq [locale ["en" "fr" "it" "de" "nl"]]
(println (.format (DateFormat/getDateInstance DateFormat/FULL
(Locale. locale))
time))))
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);
}
fsharp
open System
open System.Globalization

let jan1 = DateTime(2009, 1, 1)

[ "en-US"; "fr-FR"; "de-DE"; "it-IT"; "nl-NL" ]
|> List.map CultureInfo.CreateSpecificCulture
|> List.map (fun c -> jan1.ToString("D", c))
|> List.iter (printfn "%s")
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
java
Calendar cal = Calendar.getInstance();
cal.set(2009, Calendar.JANUARY, 1);
Locale[] locales = { ENGLISH, FRENCH, ITALIAN, GERMAN, new Locale("nl") };

for (Locale l : locales) {
System.out.println(getDateInstance(FULL, l).format(cal.getTime()));
}
python
from datetime import datetime
from locale import setlocale, LC_TIME

now = datetime(2009, 1, 1)

locales = ('en_us', 'fr_fr', 'it_it', 'de_de', 'nl_nl')
for locale in locales:
setlocale(LC_TIME, locale)
print now.strftime('%A, %B %d %Y')

scala
val date = new GregorianCalendar(2009, JANUARY, 1).getTime
val locales = List(ENGLISH, FRENCH, ITALIAN, GERMAN, new Locale("nl"))
println(locales.map{getDateInstance(FULL, _).format(date)}.mkString("\n"))

Display the current date and time

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

(println (str (Date.)))
cpp
QDate now = QDate::currentData();
qDebug() << now.toString();
time_t date = time(0);
cout << ctime(&date);
fsharp
printfn "%A" System.DateTime.Now
groovy
println new Date()
java
import java.util.Date;

public class SolutionXX {
public static void main(String[] args) {
Date now = new Date();
System.out.println(now.toString());
}
}
ocaml
Unix.localtime (Unix.gettimeofday ())
python
from datetime import datetime
print datetime.utcnow()
scala
println(new java.util.Date)
OOP

Define a class

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

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

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

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

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

private:
std::string whom;
};

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

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

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

private:
initonly String^ whom;
};

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

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

void Greeter::greet()
{
Console::WriteLine(L"Hello, {0}", whom);
}
fsharp
type Greeter(whom' : string) =
member this.greet() = printfn "Hello, %s!" whom'

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

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

(new Greeter("world")).greet()
groovy
// version using named parameters
class Greeter {
def whom
def greet() { println "Hello, $whom" }
}
new Greeter(whom:'world').greet()
// version using traditional constructor
class Greeter {
private whom
Greeter(whom) { this.whom = whom }
def greet() { println "Hello, $whom" }
}
new Greeter('world').greet()
java
class Greeter
{
public Greeter(String whom) { this.whom = whom; }
public void greet() { System.out.printf("Hello, %s\n", whom); }
private String whom;
}

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

let o = new greeter "Hello" in
o#greet
python
class Greeter(object):
""" Greet someone.
"""
def __init__(self, whom):
self._whom = whom
def greet(self):
print "Hello, %s!" % self._whom

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

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

Instantiate object with mutable state

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

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

Hello, Tommy!

The getter would then be used to display the line:

I have just greeted Tommy.
clojure
(defn greeter [whom]
(atom {:whom whom}))

(defn get-whom [g]
(:whom @g))

(defn set-whom [g whom]
(swap! g #(conj % {:whom whom})))

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

; using the "class"
(let [g (greeter "world")]
(greet g)
(set-whom g "Tommy")
(greet g)
(println (str "I have just greeted " (get-whom g) ".")))

; or same effect without using any variables
(println (str "I have just greeted "
(get-whom (doto (greeter "world")
(greet)
(set-whom "Tommy")
(greet)))
"."))
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;
}
fsharp
type Greeter(name:string) =
let mutable whom = name

member this.Whom
with get () = whom
and set v = whom <- v

member this.Greet() =
printfn "Hello, %s!" whom

let greeter = Greeter("World")
greeter.Greet()
greeter.Whom <- "Tommy"
greeter.Greet()
printfn "I have just greeted %s." greeter.Whom
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"
java
class Greeter {
private String whom;

public Greeter(String whom) {
this.whom = whom;
}

public String getWhom() {
return whom;
}

public void setWhom(String whom) {
this.whom = whom;
}

public void greet() {
System.out.println("Hello " + whom + "!");
}
}
Greeter greeter = new Greeter("World");
greeter.greet();
greeter.setWhom("Tommy");
greeter.greet();
System.out.println("I have just greeted " + greeter.getWhom() + ".");
ocaml
class greeter =
object
val mutable whom = "someone"
method set_whom greetee = whom <- greetee
method get_whom = whom
method greet = Printf.printf "Hello, %s!\n" whom
end;;

let o = new greeter in
o#set_whom "Tommy";
o#greet;
Printf.printf "I have just greeted %s.\n" o#get_whom
python

class Greeter(object):
_whom = None

def __init__(self, whom):
self._whom = whom

@property
def whom(self):
return self._whom

@propset(whom)
def whom(self, value=None):
self._whom = value

def greet(self):
print 'Helo, %s!' % self._whom

greeter = Greeter('Winston')
greeter.greet()
greeter.whom = 'Tommy'
greeter.greet()
# required for Python 2.5 or less
def propset(prop):
assert isinstance(prop, property)
def helper(func):
return property(prop.fget, func, prop.fdel, prop.__doc__)
return helper

class Greeter(object):
_whom = None

def __init__(self, whom):
self._whom = whom

@property
def whom(self):
return self._whom

@propset(whom)
def whom(self, value=None):
self._whom = value

def greet(self):
print 'Helo, %s!' % self._whom

greeter = Greeter('Winston')
greeter.greet()
greeter.whom = 'Tommy'
greeter.greet()
scala
class Greeter(var whom: String) {
def greet() = println("Hello " + whom + "!")
}

// Is this really a private value with getter and setter methods,
// or just a public mutable value?

val greeter = new Greeter("World")
greeter.greet()
greeter.whom = "Tommy"
greeter.greet()
printf("I have just greeted %s.\n", greeter.whom)

Implement Inheritance Heirarchy

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

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

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

Instantiate an object of each class, and invoke each objects '
print' method to show relevant details.
clojure
(defmulti area :Shape)
(defmulti print :Shape)

; Circle methods
(defn circle [r]
{:Shape :Circle
:name "Circle"
:radius r})

(defn circumference [c]
(* 2 Math/PI (:radius c)))

(defmethod area :Circle [c]
(* Math/PI (:radius c) (:radius c)))

(defmethod print :Circle [c]
(println (format "I am a %s with ->" (:name c)))
(println (format "Radius: %.2f" (:radius c)))
(println (format "Area: %.2f" (area c)))
(println (format "Circumference: %.2f" (circumference c))))

; Rectangle methods
(defn rectangle [l b]
{:Shape :Rectangle
:name "Rectangle"
:length l
:breadth b})

(defn perimeter [r]
(+ (* 2 (:length r)) (* 2 (:breadth r))))

(defmethod area :Rectangle [r]
(* (:length r) (:breadth r)))

(defmethod print :Rectangle [r]
(println (format "I am a %s with ->" (:name r)))
(println (format "Length, Width: %.2f, %.2f" (:length r) (:breadth r)))
(println (format "Area: %.2f" (area r)))
(println (format "Perimeter: %.2f" (perimeter r))))

; usage of the "classes"
(let [shapes (list (circle 4.2) (rectangle 2.7 3.1) (rectangle 6.2 2.6) (circle 17.3))]
(doseq [shape shapes]
(print shape)))
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();
}
fsharp
[<AbstractClass>]
type Shape(name:string) =
member this.Name = name
abstract Area : float
abstract Print : unit -> unit

type Circle(name, radius:float) =
inherit Shape(name)
member this.Radius = radius
member this.Circumference =
System.Math.PI * radius * 2.
override this.Area =
System.Math.PI * radius * radius
override this.Print() =
printfn "Circle: %s" this.Name
printfn "Area: %f" this.Area
printfn "Circumference: %f" this.Circumference
printfn "Radius: %f" this.Radius

type Rectangle(name, length:float, breadth:float) =
inherit Shape(name)
member this.Length = length
member this.Breadth = breadth
member this.Perimiter =
(length * 2.) + (breadth * 2.)
override this.Area =
length * breadth
override this.Print() =
printfn "Rectangle: %s" this.Name
printfn "Area: %f" this.Area
printfn "Perimiter: %f" this.Perimiter
printfn "Length: %f" this.Length
printfn "Breadth: %f" this.Breadth

let c = Circle("Foo", 2.1)
let r = Rectangle("Bar", 2.2, 3.3)

c.Print()
printfn ""
r.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() }
java
/*
* Will work with version 1.4 if you remove the @Override annotation
* and declare floating point numbers using the primitive "double"
*/
abstract class Shape {
protected final String name;
public Shape(String name) {
this.name = name;
}
public abstract Double area();
public abstract void print();
}
class Circle extends Shape {
private Double radius;
public Circle(Double radius) {
super("circle");
this.radius = radius;
}
@Override
public Double area() {
return Math.PI * Math.pow(radius, 2);
}
@Override
public void print() {
System.out.println("A " + name + " with radius " + radius
+ ", area " + area() + " and circumference "
+ circumference() + ".");
}
public Double circumference() {
return 2 * Math.PI * radius;
}
}
class Rectangle extends Shape {
private Double length, breadth;
public Rectangle(Double length, Double breadth) {
super("Rectangle");
this.length = length;
this.breadth = breadth;
}
@Override
public Double area() {
return length * breadth;
}
public Double perimeter() {
return 2 * length + 2 * breadth;
}
@Override
public void print() {
System.out.println("A " + name + " with length " + length
+ ", breadth " + breadth + ", area " + area()
+ " and perimeter " + perimeter() + ".");
}
}
Circle circle = new Circle(4d);
circle.print();
Rectangle rectangle = new Rectangle(2d, 5.5);
rectangle.print();
ocaml
class virtual shape =
object(self)
method name = "shape"
method virtual area : float
method print = Printf.sprintf "%s, area %f" self#name self#area
end ;;

let pi = 4. *. atan 1.

class circle radius =
object(self)
inherit shape as super
method name = "circle"
method area = radius *. radius *. pi
method circumference = radius *. 2. *. pi
method print = Printf.sprintf "%s, circumference %f" super#print self#circumference
end

class rectangle length breadth =
object(self)
inherit shape as super
method name = "rectangle"
method area = length *. breadth
method perimeter = 2. *. ( length +. breadth)
method print = Printf.sprintf "%s, perimeter %f" super#print self#perimeter
end

let c = new circle 5. in
let r = new rectangle 7. 3. in
print_endline c#print;
print_endline r#print
python
#Start with the import statements.
import math # necessary to get the value of pi

class Shape(object):
"""Shape Class"""
def __init__(self):
"""Constructor method"""
pass #Do nothing here
def area(self):
"""The area method"""
pass #Do nothing here
def print_(self):
"""
The print method. Note the trailing underscore - this is because
there is a reserved statement called 'print' in python 2.x. The
trailing underscore is the accepted method of re-using names without
rebinding them
"""
print 'The name is: %s' % self.name #Print the only property we currently have

def _getName(self):
"""The getter method for the 'name' property.
Note that getter methods are generally discouraged in python"""
return self._name

_name = None # The leading underscore gives a weak non-public value
# to a variable. Two leading underscores will mangle its
# name at runtime, to make it more difficult to access.
# Note there is no real 'private' variable type in python.
name = property(_getName, doc='The name of this object')
# property statements work like: property(fget=None, fset=None, fdel=None, doc=None)

class Circle(Shape):
"""Circle Class - a sub class of shape"""
def __init__(self, radius, name='Circle'):
"""Constructor method again"""
Shape.__init__(self) # init the super class
self.radius = radius # Store the radius
self._setCircumference()# Function call
self._name = name

def _setCircumference(self):
self.circumference = 2*math.pi*self.radius

def area(self):
'''Return the area of this circle'''
tmpAera = math.pi * self.radius**2
return tmpAera
def print_(self):
'''The print method'''
super(Circle, self).print_() # This calls the print_ method in
# the super classes of Circle, in
# this case Shape
print 'The radius is: %f' % self.radius
print 'The circumference is %f' % self.circumference
print 'The area is: %f' % self.area()

class Rectangle(Shape):
"""The Rectangle Class"""
def __init__(self, length, breadth, name='Rectangle'):
Shape.__init__(self)
self._name = name
self.length = length
self.breadth = breadth
self.perimeter()
def area(self):
return self.breadth*self.length
def perimeter(self):
self._perimeter = self.breadth*2+self.length*2
return self._perimeter # You have a method return a value and still
# safely call it without handling the return
# value. This would be collected by garbage
# collection.
def print_(self):
super(Rectangle, self).print_()
print 'The length is %f and the breadth is %f' %(self.length, self.breadth)
print 'The perimeter is: %f' %self._perimeter
print 'The area is: %f' % self.area()

if __name__ == '__main__':
rectangle = Rectangle(5,3)
circle = Circle(5, name='Round and Round')
rectangle.print_()
circle.print_()
scala
abstract class Shape (val name: String) {
def area : Double
def print()
}

class Circle (val radius: Double) extends Shape("Circle") {
def area = Math.Pi * radius * radius
def circumference = 2 * Math.Pi * radius
def print() {
println("I'm a " + name + " with")
printf(" * radius = %.2f\n", radius)
printf(" * area = %.2f\n", area)
printf(" * circumference = %.2f\n\n", circumference)
}
}

class Rectangle (val length: Double, val breadth: Double) extends Shape("Rectangle") {
def area = length * breadth
def perimeter = 2 * (length + breadth)
def print() {
println("I'm a " + name + " with")
printf(" * length = %.2f\n", length)
printf(" * breadth = %.2f\n", breadth)
printf(" * area = %.2f\n", area)
printf(" * perimeter = %.2f\n\n", perimeter)
}
}

val shapes = List(new Circle(5.4), new Rectangle(7.8, 6.5))
shapes foreach (_.print)

Implement and use an Interface

Create a Serializable interface consisting of '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.
clojure
(defn person [name age]
{:name name :age age})

(defn show [p]
(println (format "Name=%s Age=%d" (:name p) (:age p))))

(defn save [p filename]
(with-out-writer filename (pr p)))

(defn restore [filename]
(read (PushbackReader. (reader filename))))

(let [p (person "Ken" 38)]
(show p)
(save p *person-fn*))

(let [ser-p (restore *person-fn*)]
(show ser-p))
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;
}
fsharp
// Since everyone else is using built-in functionality instead of
// defining an interface as required, I won't buck the trend.
// Maybe this problem should be named "Use serialization features" instead
// of "Implement and use an Interface"

open System
open System.IO
open System.Runtime.Serialization.Formatters.Binary

[<Serializable>]
type Person(name:string, age:int) =
member this.Name = name
member this.Age = age

let serialize x =
use ms = new MemoryStream()
let bf = new BinaryFormatter()
bf.Serialize(ms, x)
ms.ToArray()

let deserialize<'a> bytes =
use ms = new MemoryStream(bytes:byte[])
let bf = new BinaryFormatter()
bf.Deserialize(ms) :?> 'a

let before = Person("Joel", 35)
let bytes = serialize before
let after = deserialize<Person> bytes

printfn "Before: %s, %i" before.Name before.Age
printfn "After: %s, %i" after.Name after.Age
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
java
// Serialization to a file
class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean equals(Object obj) {
if(obj == this) return true;
if(obj instanceof Person) {
Person p = (Person) obj;
return (p.getName().equals(this.getName())
& p.getAge() == this.getAge());
}
return false;
}
public String toString() {
return "Name: " + name + ", age: " + age;
}
}
Person person = new Person();
person.setName("Gaylord Focker");
person.setAge(21);

try {
File file = new File("ser.obj");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(person);
oos.close();
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
Person deserializedPerson = (Person) ois.readObject();
ois.close();
System.out.println(deserializedPerson);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ocaml
(* in OCaml, interfaces are class types, and have nothing to do with inheritance,
so I'm not sure what's the correct answer to this problem (if any) *)

class type serializable =
object
method save: out_channel -> unit
method restore: in_channel -> unit
end

class person name age =
object
val mutable my_name = name
val mutable my_age = age
method save oc = output_value oc my_name; output_value oc my_age
method restore ic = my_name <- input_value ic; my_age <- input_value ic
method print = Printf.printf "I'm %s, %d\n" my_name my_age
end

let transfer (o1: serializable) (o2: serializable) =
let temp_filename = "_person" in
let backing_store_save = open_out_bin temp_filename in
o1#save backing_store_save;
close_out backing_store_save;

let backing_store_restore = open_in_bin temp_filename in
o2#restore backing_store_restore;
close_in backing_store_restore


let o = new person "john" 42 in
let o2 = new person "nobody" 0 in
transfer (o :> serializable) (o2 :> serializable);
o2#print
python
import pickle

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return "Name: {name}, age: {age}".format(name=self.name, age=self.age)


person = Person("Gaylord Focker", 21)
with open("person.pickle", "wb") as outstream:
pickle.dump(person, outstream)
with open("person.pickle", "rb") as instream:
deserialized_person = pickle.load(instream)
print(deserialized_person)
scala
class Person (var name: String, var age: Int) extends Serializable

val p1 = new Person("John", 21)
val output = new ByteArrayOutputStream()
val oos = new ObjectOutputStream(output)
oos.writeObject(p1)
oos.flush
oos.close

val input = new ByteArrayInputStream(output.toByteArray())
val ois = new ObjectInputStream(input)
val p2 = ois.readObject().asInstanceOf[Person]

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.
clojure
(def *url* "http://langref.org/")
(def *lang* "clojure")

(with-open [ stream (.openStream (URL. *url*)) ]
(let [ body (str (line-seq (BufferedReader. (InputStreamReader. stream)))) ]
(str "Language " *lang* " does "
(if-not (re-matches (re-pattern (str ".*" *url* *lang* ".*")) body) "not ")
"exist")))
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);
fsharp
let httpReq = (WebRequest.Create(url) :?> HttpWebRequest)
httpReq.KeepAlive <- false
let httpStream = new StreamReader(httpReq.GetResponse().GetResponseStream())
let htmlPage = httpStream.ReadToEnd()
httpStream.Close()

let offerStatus = (if (htmlPage.IndexOf(url ^ language) > 0) then "offers" ; else "does not offer")
Console.WriteLine("{0} {1} {2}", url, offerStatus, language)
groovy
assert new URL('http://langref.org').text.contains('groovy')
java
String url = "http://langref.org/", language = "java", line = null, regexp = ".*" + url + language + ".*";

BufferedReader in = new BufferedReader(new InputStreamReader((new URL(url)).openStream()));
while ((line = in.readLine()) != null)
if (line.matches(regexp)) { System.out.printf("Language %s exists @ %s\n", language, url); break; }

in.close();
python
from urllib import urlopen
print urlopen('http://langref.org').read().find('python') >= 0 and 'found' or 'not found'
scala
val url = "http://langref.org/" ; val language = "scala" ; val srchexp = url + language;

val source = Source.fromURL(url).getLines

while (source.hasNext) if (source.next.contains(srchexp)) printf("Language %s exists @ %s\n", language, url)

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.
fsharp
open System
open System.Net
open System.Net.Mail
open System.Net.Mime

let subject = "Greetings from langref.org"
let from = "username@gmail.com"
let destination = "username@gmail.com"

printfn "Write mail body (press 'Enter' when finished):"
let mutable body = Console.ReadLine()
if body = null || body.Length = 0 then
body <- "Hello World"

let mail = new MailMessage(from, destination, subject, body)

let smtpHost = "smtp.gmail.com"
let clientCredentials = new NetworkCredential("username@gmail.com", "password")
let smtpClient = new SmtpClient(smtpHost,587)
smtpClient.EnableSsl <- true
smtpClient.UseDefaultCredentials <- false
smtpClient.Credentials <- clientCredentials

printfn "Send email? y/n"
match Console.ReadLine() with
| "y" -> smtpClient.Send(mail);mail.Dispose();printfn "email delivered"
| "n" -> smtpClient.Dispose()
| _ -> smtpClient.Dispose()
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}')
}
}
java
// requires Java Mail API (mail.jar), which must be in classpath
try {
Properties props = System.getProperties();
props.put("mail.smtp.host", "smtp.sampledomain.com");
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("gaylord.focker@hollywood.com"));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("father@family.com"));
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse("mother@family.com"));
msg.setSubject("subject");
msg.setText("message body");
msg.setHeader("X-Mailer", "jAVAmAILER");
msg.setSentDate(new Date());
Transport.send(msg);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
ocaml
(* Using the library smtp-mail-0.1.3:
http://www.linux-nantes.org/%7Efmonnier/OCaml/smtp-mail/ *)

let () =
let h = Smtp.connect "smtp.example.com" in
Smtp.helo h "hostname";
Smtp.mail h "<john.smith@example.com>";
Smtp.rcpt h "<jane.smith@example.com>";
let email_header = "\
From: John Smith <john.smith@example.com>\r\n\
To: Jane Smith <jane.smith@example.com>\r\n\
Subject: Greetings from langref.org" in
let email_msg = "Hi,\n\nHow are you?" in
Smtp.data h (email_header ^ "\r\n\r\n" ^ email_msg);
Smtp.quit h;
;;
python
import smtplib
import locale

from email.mime.text import MIMEText

encoding = locale.getpreferredencoding()

def main():
smtp_servername = "smtp.example.com"

from_addr = "ernie@example.com"
to_addr = "cookie.monster@mailinator.com"

body = raw_input("Enter the email message ")
if not raw_input("Send email? y/N ") in ["y", "Y"]:
print "aborting"
return

message = MIMEText(body, _charset=encoding)

message["From"] = from_addr
message["To"] = to_addr
message["Subject"] = "Greetings from langref.org"

server = smtplib.SMTP(smtp_servername)
server.sendmail(from_addr, to_addr, message.as_string())


if __name__ == "__main__":
main()
scala
// requires Java Mail API (mail.jar), which must be in classpath

import javax.mail._
import javax.mail.internet._
import java.util.Properties._

// Get the user's message
println("Enter the text you wish to send in the message (hit Ctrl-D to finish):")
var bodyText = ""
var line = readLine
while (line != null) {
bodyText += line
line = readLine
}

// Confirm they want to send
println("Are you sure you want to send the message? [y/N]")
val yesOrNo = readLine
if (yesOrNo != "y" && yesOrNo != "Y") {
println("Aborted")
exit
}

// Set up the mail object
val properties = System.getProperties
properties.put("mail.smtp.host", "localhost")
val session = Session.getDefaultInstance(properties)
val message = new MimeMessage(session)

// Set the from, to, subject, body text
message.setFrom(new InternetAddress("test@example.org"))
message.setRecipients(Message.RecipientType.TO, "spam@mopoke.co.uk")
message.setSubject("Greetings from langref.org")
message.setText(bodyText)

// And send it
Transport.send(message)
XML

Process an XML document

Given the XML Document:

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

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

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

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

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

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

cout.setf(ios::fixed, ios::floatfield);
cout << "Total price is $" << setprecision(2) << total_price << endl;
fsharp
#r @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.5\System.Xml.Linq.dll"

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

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

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


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

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

let navigator = XPathDocument("xml.txt").CreateNavigator()
let path = XPathExpression.Compile("/shopping/item[@price][@quantity]")
let names = XmlNamespaceManager(navigator.NameTable)
path.SetContext(names)
let shoppingCost =
match path.ReturnType with
| XPathResultType.NodeSet ->
navigator.Select(path)
|> Seq.cast
|> Seq.map (fun (i: XPathNavigator) ->
if i.IsNode then
let elem = XElement.Parse(i.OuterXml)
Double.Parse(xattr elem "quantity"), Double.Parse(xattr elem "price")
else
failwith "Error in expression, expecting to see a node"
)
|> Seq.sumBy (fun (quantity, price) -> quantity * price)
| _ -> failwith "Error in expression, expecting to see a node set"
groovy
printf '$%.2f\n', new XmlSlurper().parseText(xml).item.collect{
it.@quantity.toInteger() * it.@price.toFloat()
}.sum()
java
// solution uses JAXP and SAX included in Java API since version >= 1.5
class ShoppingContentHandler extends DefaultHandler {
Double priceSum = 0d;
@Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
if(name.equals("item")) {
String quantityString = attributes.getValue(attributes.getIndex("quantity"));
String priceString = attributes.getValue(attributes.getIndex("price"));
Integer quantity = Integer.parseInt(quantityString);
Double price = Double.parseDouble(priceString);
priceSum += (quantity * price);
}
}
public Double getPriceSum() {
return priceSum;
}
}

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

} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ocaml
let () =
let xml = Xml.parse_file "shopping.xml" in
let res =
Xml.fold (fun total xml ->
match xml with
| Xml.Element ("item", attrs, _) ->
let quantity = float_of_string (List.assoc "quantity" attrs)
and price = float_of_string (List.assoc "price" attrs) in
total +. (quantity *. price)
| _ -> total
) 0.0 xml
in
Printf.printf "Total cost of the items: %g\n" res
python
from xml.dom.minidom import parseString
document = parseString(
"""<shopping>
<item name="bread" quantity="3" price="2.50"/>
<item name="milk" quantity="2" price="3.50"/>
</shopping>""").documentElement
total = sum([float(item.getAttribute('price')) *
int(item.getAttribute('quantity'))
for item in document.getElementsByTagName('item')])
print '$%.2f' % total
scala
val data = <shopping>
<item name="bread" quantity="3" price="2.50"/>
<item name="milk" quantity="2" price="3.50"/>
</shopping>

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

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

create some XML programmatically

Given the following CSV:

bread,3,2.50
milk,2,3.50

Produce the equivalent information in XML, e.g.:

<shopping>
  <item name="bread" quantity="3" price="2.50" />
  <item name="milk" quantity="2" price="3.50" />
</shopping>
clojure
(defn list->xml-item [lst]
(let [[name quantity price] (map str lst)]
{:tag :item
:attrs {:name name
:quantity quantity
:price price}}))

(defn cvs->xml [r]
(->> (map #(read-string (str "(" % ")")) (line-seq r))
(map list->xml-item)
(assoc {:tag :shopping} :content)
(emit)
(with-out-str)))

(println (cvs->xml *cvs-reader*))
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;
fsharp
#r "System.Xml.dll"
#r "System.Xml.Linq.dll"

open System
open System.Xml
open System.Xml.Linq

let data = "bread,3,2.50
milk,2,3.50"

let X name =
XName.Get(name)

let lines = data.Split( [|"\n" |], StringSplitOptions.RemoveEmptyEntries)

let document = new XDocument()
let element = new XElement(X "shopping")
document.Add(element)

lines
|> Seq.iter (fun line ->
let items = line.Split([|','|])
let item = new XElement(X "item",
new XAttribute(X "name", items.[0]),
new XAttribute(X "quantity", items.[1]),
new XAttribute(X "price", items.[2]))
element.Add(item))

let output = document.ToString();;
groovy
b = new groovy.xml.MarkupBuilder()
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
java
// In this solution JAXB is used to created the xml output.
// JAXB is included in Java 1.6. Runs with 1.5 if you include JAXB Jars
// in the classpath.
class Item {
// Of course you use getters and setters and declare attributes private.
// In this sample a "dirty" way is chosen to keep LOC low.
@XmlAttribute
String name;
@XmlAttribute
Integer quantity;
@XmlAttribute
Double price;
}

@XmlRootElement
class Shopping {
@XmlElement
Set<Item> items = new HashSet<Item>();
}

String line = null;
Shopping shopping = new Shopping();
try {
BufferedReader reader = new BufferedReader(new FileReader("shopping.csv"));
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
Item item = new Item();
item.name = parts[0];
item.quantity = Integer.parseInt(parts[1]);
item.price = Double.parseDouble(parts[2]);
shopping.items.add(item);

}
JAXB.marshal(shopping, "D:" + File.separatorChar + "shopping.auto.xml");
} catch (IOException e) {
e.printStackTrace();
}
ocaml
(* Compilation (native):
$ ocamlopt -I +csv csv.cmxa -I +xml-light xml-light.cmxa csv2xml.ml -o csv2xml
*)

let () =
let table = Csv.load "shopping.csv" in
let columns = ["name"; "quantity"; "price"] in

let xml = Xml.Element ("shopping", [],
List.rev (
List.fold_left (fun acc row ->
Xml.Element ("item",
List.combine columns row, []) :: acc) [] table)) in

print_endline (Xml.to_string_fmt xml)
python
from xml.dom import minidom

csv = """bread,3,2.50
milk,2,3.50"""

doc = minidom.Document()
shopping = doc.createElement("shopping")

for line in csv.split("\n"):
name, quantity, price = line.split(",")
el = doc.createElement("item")
el.setAttribute("name", name)
el.setAttribute("quantity", quantity)
el.setAttribute("price", price)
shopping.appendChild(el)

print shopping.toprettyxml()
from xml.etree.ElementTree import Element, SubElement, tostring

csv = """bread,3,2.50
milk,2,3.50"""

root = Element('shopping')

for line in csv.split("\n"):
name, quantity, price = line.split(",")
SubElement(root,'item', {'name' : name,
'quantity' : quantity,
'price' : price })

print tostring(root)
scala
<shopping>
{List("bread,3,2.50", "milk,2,3.50") map { row =>
row split ","
} map { item =>
<item name={item(0)} quantity={item(1)} price={item(2)}/>
}}
</shopping>

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:

[3, 4, 5]
[6, 8, 10]
[5, 12, 13]
[9, 12, 15]
[8, 15, 17]
[12, 16, 20]
[15, 20, 25]
clojure
(defn pythagorean [a b c] (= (+ (* a a) (* b b)) (* c c)))

(defn intsqrt [cc]
(. (. Math sqrt cc) intValue)
)

(defn triples [maxSize]
(filter not-empty
(for [a (range 1 20) b (range a 20)]
(let [c (intsqrt (+ (* a a) (* b b)))]
(if (pythagorean a b c)
[a b c]
()
)))))

(triples 20)
; -> ([3 4 5] [5 12 13] [6 8 10] [8 15 17] [9 12 15] [12 16 20] [15 20 25])

(defn sortByHypotenuse [triples]
(sort-by #(first (rest (rest %))) triples)
)

(sortByHypotenuse (triples 20))
; -> ([3 4 5] [6 8 10] [5 12 13] [9 12 15] [8 15 17] [12 16 20] [15 20 25])
(doseq [pt (sort-by #(% 2)
(for [a (range 1 21)
b (range a 21)
:let [aa+bb (+ (* a a) (* b b))
c (Math/round (Math/sqrt aa+bb))]
:when (= aa+bb (* c c))]
[a b c]))]
(println pt))
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;
fsharp
let getGoodTri (a,b) =
let h = int(System.Math.Sqrt(float(a*a + b*b)))
if a*a + b*b = h*h then Some(a,b,h)
else None

seq{ for i in 1..20 do yield! seq{for j in i..20 do yield i,j} } |> Seq.choose(getGoodTri) |> Seq.sortBy(fun (_,_,c) -> c);;
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')
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')
java
SortedSet<List<Integer>> results = new TreeSet<List<Integer>>(new Comparator<List<Integer>>() {
public int compare(List<Integer> o1, List<Integer> o2) {
return o1.get(2).compareTo(o2.get(2));
}
});
for (int x = 1; x <= 20; x++) {
for (int y = 1; y <= 20; y++) {
double z = Math.hypot(x, y) ;
if ((int) z == z)
results.add(Arrays.asList( new Integer[] { x, y, (int) z }));
}
}
ocaml
let is_int v =
v = (snd (modf v))

let sort_by_third tup =
let third (_,_,v) = v in
let cmp a b = compare (third a) (third b) in
List.sort cmp tup

let hypi ia ib =
let hyp a b = sqrt(a**2.0 +. b**2.0) in
hyp (float_of_int ia) (float_of_int ib)

let find_pythag max =
let rec py t = match t with
| (a,_) when a > max -> []
| (a,b) when b > max -> py (a+1,a+1)
| (a,b) ->
let next = (a,b+1) in
let cf = hypi a b in
if (is_int cf) then
( a,b,(int_of_float cf) ) :: (py next)
else
py next
in
sort_by_third ( py (1,1) )
python
from math import sqrt

a = 1
ret = []
while a <= 20:
b = 1
while b <= 20:
c = sqrt((a**2)+(b**2))
if int(c) == c and sorted([a,b,int(c)]) not in ret:
ret.append(sorted([a,b,int(c)]))
b +=1
a +=1
print ret


or if you wanna get snarky..

print sorted(set([tuple(sorted((a,b,int(sqrt((a**2)+(b**2)))))) for a in xrange(1,21) for \
b in xrange(1,21) if int(sqrt((a**2)+(b**2))) == sqrt((a**2)+(b**2))]))

scala
val res = for (
x <- 1 to 20 ;
y <- x to 20 ;
z = Math.sqrt(x*x + y*y) ;
if (z.toInt == z) )
yield (x, y, z.toInt)

res.toList.sortWith { (t1, t2) =>
t1._3 < t2._3
} foreach (println(_))
(for(x <- 1 to 20;
y<- x to 20;
z<- 1 to 30;
if(z*z == x*x + y*y)) yield(x, y, z)
).sortWith(_._3 < _._3) foreach println
( for (
a <- 1 to 20 ;
b <- a to 20 ;
c = math.sqrt( a*a + b*b )
if c.toInt == c
) yield ( a, b, c.toInt )
).sortBy {_._3} foreach println

Greatest Common Divisor

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

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

using namespace std;

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

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

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

int main() {
std::cout << gcd_recursive(8, 12) << std::endl;
std::cout << gcd_recursive2(8, 12) << std::endl;
std::cout << gcd_iterative(8, 12) << std::endl;
return 0;
}
fsharp
let rec gcd x y =
if y = 0 then x
else gcd y (x % y)
groovy
static def gcd(int i, int j) {
if (Math.min(i,j)==0) return Math.max(i,j)
else return gcd(Math.min(i,j),Math.abs(i-j))
}
java
static int gcd(int a, int b) {
if (Math.min(a, b) == 0)
return Math.max(a, b);
else
return gcd(Math.min(a, b), Math.abs(a - b));
}
ocaml
(* tail recursive *)
let rec gcd n m =
if m = 0 then
n
else if n > m then
gcd (n-m) m
else
gcd n (m-n)
;;
python
def gcd_recursive(i, j):
if min(i, j) == 0:
return max(i, j)
else:
return gcd_recursive(min(i, j), abs(i - j))

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

if __name__ == "__main__":
print gcd_recursive(8, 12)
print gcd_iterative(8, 12)
from fractions import gcd
print gcd(8, 12)
scala
def gcd(x: Int, y: Int): Int =
if (b == 0) x
else gcd(b, x % y)
Fun

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.
clojure
(def s"(def s%s)(printf s(pr-str s))")(printf s(pr-str s))
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")) }
fsharp
(fun s -> printf "%s %s" s s) "(fun s -> printf \"%s %s\" s s)"
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,_
java
public class Quine {public static void main(String[] args) {String s = "public class Quine {public static void main(String[] args) {String s = %c%s%c;System.out.printf(s, 34, s, 34);}}";System.out.printf(s, 34, s, 34);}}
public class Quine {
public static void main(String[] args) {
Character cq = (char) 34;
Character cn = (char) 10;
Character cs = (char) 92;
String s = "public class Quine {\n public static void main(String[] args) {\n Character cq = (char) 34;\n Character cn = (char) 10;\n Character cs = (char) 92;\n String s = %c%s%c;\n System.out.printf(s, cq, s.replace(cn.toString(), cs.toString() + 'n'), cq);\n }\n}";
System.out.printf(s, cq, s.replace(cn.toString(), cs.toString() + 'n'), cq);
}
}
ocaml
(fun s -> Printf.printf "%s %S" s s) "(fun s -> Printf.printf \"%s %S\" s s)"
(fun p -> Printf.printf p (string_of_format p)) "(fun p -> Printf.printf p (string_of_format p)) %S"
python
# adapted from a Quine by Sean B. Palmer

print (lambda s='print (lambda s=%r: (s %% s))()': (s % s))()
x='x=%r;print(x%%x)';print(x%x)
scala
val s="val s=%c%s%c; printf(s, 34, s, 34)"; printf(s, 34, s, 34)

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)

["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.
clojure
(defn perm-chars [l]
"Returns a list of all possible permutations of strings with the
same size as the input string. This function will return duplicates
if the same character occurs multiple time in the string.
Ex: ab -> (aa ab ba ab)"
(if (string? l)
(recur (repeat (count l) l))
(let [s (first l)
r (rest l)]
(if (empty? r)
(map identity s)
(->> s
(map (fn [c] (map #(str c %) (perm-chars r))))
(flatten))))))

(defn perm-sz [s]
"Returns a list of all possible permutations of the input
string. May return duplicats.
Ex: ab -> (aa ab ba bb a b a b)"
(if-not (empty? s)
(let [r (perm-chars s)]
(if (= (count s) 1)
r
(->> r
(map #(perm-sz (apply str (rest %))))
(flatten)
(lazy-cat r))))))


(defn perm [s]
"Returns a list of all possible permutations of the input
string. The list of string is sorted and does not contain
duplicates.
Ex: ab -> (a aa ab b ba bb)"
(->> (reduce (fn [s e] (conj s e)) #{} (perm-sz s))
(map str)
(sort)))

(println (pmap perm ["ab" "we" "tfe" "aoj"]))
(require 'cojure.contrib.combinatorics)

(pmap (fn [str]
(apply concat (map #(selections str (inc %))
(range (count str)))))
["ab", "we", "tfe", "aoj"])
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;
fsharp
open System
let input = [| "ab"; "we"; "tfe"; "aoj" |]

/// Computes all permutations of an array
let rec permute = function
| [| |] -> [| [| |] |]
| a ->
a
|> Array.mapi (fun i ai ->
// Take all elements in the array apart from the i.th, compute
// their permutations, then attach element i at the front of each perm
Array.sub a 0 i
|> Array.append (Array.sub a (i + 1) (a.Length - i - 1))
|> permute
|> Array.map (fun perm -> Array.append [| ai |] perm)
)
|> Array.concat

/// Computes all permutations of a string
let permuteString (s: string) =
s.ToCharArray()
|> permute
|> Array.map (fun p -> new String(p))

let output =
input
|> Array.map (fun word -> async { return (permuteString word) })
|> Async.Parallel
|> Async.RunSynchronously
// like the Java and Groovy solutions, does not duplicate letters
open System
open System.Threading.Tasks

let input = [| "ab"; "we"; "tfe"; "aoj" |]

let factorial n =
seq { 1 .. n } |> Seq.reduce (*)

let swap (arr:'a[]) i j =
[| for k = 0 to arr.Length - 1 do
yield if k = i then arr.[j] elif k = j then arr.[i] else arr.[k] |]

let rec permutation (k:int,j:int) (r:'a[]) =
if j = (r.Length + 1) then r
else permutation (k/j+1, j+1) (swap r (j-1) (k%j))

let permutations (source:'a[]) = seq {
for k = 0 to (factorial source.Length) - 1 do
yield permutation (k,2) source
}

let permute (word:string) =
let letters = word.ToCharArray()
permutations letters
|> Seq.map (fun chars -> String(chars))
|> Array.ofSeq

let tasks =
input |> Array.map (fun word -> Task.Factory.StartNew(fun () -> permute word))

let taskResult (t:Task<_>) =
t.Result

let output = Task.Factory.ContinueWhenAll(tasks, fun ts -> Array.map taskResult ts).Result
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
// 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
java
public class ParallelPermutations {

final AtomicInteger cnt = new AtomicInteger(0);

final List<Set<String>> permutations = new ArrayList<Set<String>>();

public static void main(String[] args) {
new ParallelPermutations(Arrays.asList(args));
}

public ParallelPermutations(List<String> words) {
for (final String word : words) {
new Thread(new Runnable() {
public void run() {
cnt.incrementAndGet() ;
Set<String> permutationSet = new HashSet<String>();
for (int i = 0; i < word.length(); i++)
for (int j = i + 1; j <= word.length(); j++)
permutations("", word.substring(i, j),
permutationSet);
permutations.add(permutationSet);
if (cnt.decrementAndGet() == 0)
synchronized (ParallelPermutations.this) {
ParallelPermutations.this.notify();
}
}
private void permutations(String prefix, String word, Set<String> permutations) {
int N = word.length();
if (N == 0)
permutations.add(prefix);
else
for (int i = 0; i < N; i++)
permutations(
prefix + word.charAt(i),
word.substring(0, i) + word.substring(i + 1, N),
permutations);
}
}).start();
}

synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().isInterrupted();
}
}

System.out.println(permutations);
}

}
public class ParallelPermutations {
public static void main(String[] words) throws Exception {
if(words.length==0)
words = new String[] {"ab", "we", "tfe", "aoj"};

ParallelPermutations permutations = new ParallelPermutations();
Map<String,Set<String>> wordPermutationSet =
permutations.calculate(words);

for(Map.Entry<String,Set<String>> e : wordPermutationSet.entrySet())
System.out.println(e.getKey()+" > "+e.getValue());

System.out.println(permutations.getNumberOfJobSpawned ()+" job(s) have been spawned");
}

private AtomicInteger jobSpawnedCounter = new AtomicInteger();
private ExecutorService workers ;
private ConcurrentLinkedQueue<Future<PermutationTask>> jobSpawned = newQueue();

public ParallelPermutations () {
int availableProcessors = Runtime.getRuntime().availableProcessors();
// create a thread pool according to the number of proc.
workers = Executors.newFixedThreadPool(availableProcessors);
}

private void spawn(PermutationTask task) {
Future<PermutationTask> spawned = workers.submit(task);
jobSpawnedCounter.incrementAndGet();
jobSpawned.add(spawned);
}
public int getNumberOfJobSpawned () {
return jobSpawnedCounter.get();
}

public Map<String,Set<String>> calculate (String[] words)
throws InterruptedException, ExecutionException
{
// submit all tasks, they will spawn sub-tasks by themselves
for(String word:words)
spawn(new PermutationTask(word));

Map<String,Set<String>> wordPermutationSet = newMap ();
Future<PermutationTask> spawned;
while( (spawned=jobSpawned.poll()) != null) {
// this will wait until the result is available
// this should also handle the fact that a sub-task is spawn
// and then added in the 'jobSpawned' before its parent is done
PermutationTask task = spawned.get();

String word = task.getWord();
Set<String> founds = task.getPermutationSet();
Set<String> alreadyFounds = wordPermutationSet.get(word);
if(alreadyFounds!=null)
alreadyFounds.addAll(founds);
else
wordPermutationSet.put(word, founds);
}
return wordPermutationSet;
}

private class PermutationTask implements Callable<PermutationTask> {
private final Set<String> permutationSet = new HashSet<String>();
private final String word;
private final int initialPos;
private final Stack<Integer> indicesUsed;
public PermutationTask(String word) {
this(word, 0, new Stack<Integer>());
}

/** sub task entry point */
public PermutationTask(String word,
int initialPos,
Stack<Integer> indicesUsed) {
this.word = word;
this.initialPos = 0;
this.indicesUsed = indicesUsed;
}

/** the word this task is working on*/
public String getWord() {
return word;
}

/** permutations set of this task */
public Set<String> getPermutationSet() {
return permutationSet;
}

/**
* perform the task specific calculation
* @see Callable
*/
public PermutationTask call() throws Exception {
calculatePermutation(initialPos, indicesUsed);
return this;
}

/**
* The algorithm part of the problem. The main interest is the sub-task
* spawning. When Java 7 will be available there would be a better
* alternative with the built-in fork/join framework.
*/
private void calculatePermutation(int currentPos, Stack<Integer> indicesUsed) {
final int maxLetterPerWord = word.length();
if(indicesUsed.size()>=maxLetterPerWord) {
return;
}

final StringBuilder builder = new StringBuilder();
for (int i = 0, length = word.length(); i < length; i++) {
if(indicesUsed.contains(i) && distinctIndices)
continue;
indicesUsed.push(i);
if(indicesUsed.size()>=MIN_LETTER_PER_WORD) {
builder.setLength(0);
for(Integer index: indicesUsed)
builder.append(word.charAt(index));
permutationSet.add(builder.toString());
}
// spawn a sub task to perform the next pos. calculation
spawn(new PermutationTask(word, currentPos+1, copy(indicesUsed)));
indicesUsed.pop();
}
}
}

/* algorithm parameters : the minimum number of letter per word */
private static int MIN_LETTER_PER_WORD = 1;
/* allow duplicated letters in the word found */
private static boolean distinctIndices = true;

/* factory method */
private static <T> ConcurrentLinkedQueue<T> newQueue () {
return new ConcurrentLinkedQueue<T>();
}
/* factory method */
private static <K,V> Map<K,V> newMap () {
return new HashMap<K,V>();
}
/* factory method */
private static Stack<Integer> copy(Stack<Integer> stack) {
Stack<Integer> copy = new Stack<Integer>();
copy.addAll(stack);
return copy;
}
}
python
import multiprocessing
import itertools

task_input = ["ab", "we", "tfe", "aoj"]

def all_subperms(s):
return set(reduce(
list.__add__,
([''.join(p) for p in itertools.product(s, repeat=r) if p]
for r in xrange(len(s) + 1))))

p = multiprocessing.Pool(len(task_input))
task_output = p.map(all_subperms, task_input)
print map(list, task_output)
scala
// as per Java answer, doesn't duplicate chars from input string, i.e. no 'aa'

// future detaches a computation whose result can
// be applied for at a later time
import scala.actors.Futures.future

def perm(s: String): IndexedSeq[String] =
if (s.length == 1)
IndexedSeq(s)
else
s map { c =>
future {
val subperms = perm(s filter (c !=))
(subperms map (c +)) ++ subperms
}
} flatMap (_ apply ())

def perms(l: Traversable[String]) =
l map (s => future(perm(s))) map (_ apply ())

val args = Seq("ab", "we", "tfe", "aoj")
println(perms(args))

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 "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.
clojure
; This is a "glider"
(def *start*
[".O......"
"..O....."
"OOO....."
"........"
"........"
"........"
"........"])
(def *width* (count (first *start*)))
(def *height* (count *start*))
(def *live* \O)
(def *dead* \.)
(def *n-generations-to-show* 3)

(defn cell-at
([b coord]
(cell-at b coord {:col 0 :row 0}))
([b coord offset]
(let [x (mod (+ (:col coord) (:col offset)) *width*)
y (mod (+ (:row coord) (:row offset)) *height*)]
(nth (nth b y) x))))

(defn neighbor-count [b coord]
(->> (for [x (range -1 2) y (range -1 2)] {:col x :row y})
(filter #(not (= {:col 0 :row 0} %)))
(map (partial cell-at b coord))
(reduce (fn [sum n] (+ sum (if (= *live* n) 1 0))) 0)))

(defn next-generation-cell [b coord]
(let [nc (neighbor-count b coord)]
(cond (< nc 2) *dead*
(> nc 3) *dead*
(= nc 3) *live*
true (cell-at b coord))))

(defn next-generation-row [b row]
(->> (range *width*)
(map #(next-generation-cell b {:col % :row row}))
(apply str)))

(defn next-generation [b]
(->> (range *height*)
(pmap #(next-generation-row b %))))

(defn generation-seq [b]
(let [ng (next-generation b)]
(lazy-seq (cons ng (generation-seq ng)))))

(doseq [g (take *n-generations-to-show* (generation-seq *start*))]
(doseq [l g]
(println l))
(println))

(shutdown-agents)

; This version calculates each separate line on a separate thread (pmap in next-generation)
fsharp
/// Represents a single cell, along with the basic transition rule
type State =
| Alive
| Dead
member this.Transition numLiveNeighbors =
match this with
| Alive when numLiveNeighbors < 2 -> Dead
| Alive when numLiveNeighbors > 3 -> Dead
| Alive -> Alive
| Dead when numLiveNeighbors = 3 -> Alive
| _ -> Dead
member this.ToChar() =
match this with
| Alive -> '*'
| Dead -> ' '
static member OfChar = function
| ' ' -> Dead
| _ -> Alive

type Board (board: State[,]) =
member this.Item
with get(i,j) = board.[i,j]
and set (i,j) v = board.[i,j] <- v
member this.Length1 = Array2D.length1 board
member this.Length2 = Array2D.length2 board
member this.CountLiveNeighbors(i, j) =
[| (-1,-1); (-1,0); (-1,1); (0,-1); (0,1); (1,-1); (1,0); (1,1) |]
|> Array.sumBy (fun (di,dj) ->
if (i + di) > 0 && (i + di) < this.Length1 && (j+dj) > 0 && (j+dj) < this.Length2 then
match board.[i+di,j+dj] with
| Alive -> 1
| _ -> 0
else
0
)
member this.Clone() = Board(Array2D.copy board)
override this.ToString() =
[|
for i in 0 .. this.Length1 - 1 do
let l = [| for j in 0 .. this.Length2 - 1 do yield board.[i,j].ToChar() |]
yield new String(l)
|]
|> String.concat ("\n")
static member OfString (s: string) =
let states =
s.Split('\n')
|> Array.map (fun line -> line.ToCharArray() |> Array.map State.OfChar)
Board (Array2D.init states.Length states.[0].Length (fun i j -> states.[i].[j]))
static member Update (inboard: Board) =
let outboard = inboard.Clone()
let Worker (i1,i2,j1,j2) =
for i in i1 .. i2 do
for j in j1 .. j2 do
outboard.[i,j] <-
inboard.CountLiveNeighbors(i, j)
|> inboard.[i,j].Transition
let N1 = inboard.Length1 / 2
let N2 = inboard.Length2 / 2
[| (0,N1,0,N2); (N1+1,inboard.Length1-1,0,N2); (0,N1,N2+1,inboard.Length2-1); (N1+1,inboard.Length1-1,N2+1,inboard.Length2-1) |]
|> Array.map (fun bounds -> async { Worker bounds})
|> Async.Parallel
|> Async.RunSynchronously
|> ignore
outboard

let blinker = " \n * \n * \n * \n " |> Board.OfString

do
let after1cycles =
blinker
|> Board.Update
let after3cycles =
after1cycles
|> Board.Update
|> Board.Update
printfn "%s" (after3cycles.ToString())
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
}
java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Life {
private static final int K = 4;
private static final int ITERATIONS = 10;

private static final boolean ALIVE = true;
private static final boolean DEAD = false;

private static final Board SEED = new Board(new boolean[][] {
{ DEAD, DEAD, DEAD, DEAD, DEAD, ALIVE, DEAD, ALIVE },
{ DEAD, ALIVE, ALIVE, DEAD, DEAD, DEAD, ALIVE, ALIVE },
{ DEAD, ALIVE, ALIVE, DEAD, DEAD, DEAD, ALIVE, DEAD },
{ DEAD, DEAD, DEAD, DEAD, ALIVE, DEAD, DEAD, DEAD },
{ DEAD, DEAD, DEAD, DEAD, ALIVE, ALIVE, DEAD, DEAD },
{ DEAD, DEAD, DEAD, DEAD, DEAD, ALIVE, ALIVE, ALIVE },
{ DEAD, DEAD, DEAD, DEAD, ALIVE, ALIVE, DEAD, DEAD },
{ DEAD, DEAD, DEAD, DEAD, ALIVE, DEAD, DEAD, DEAD } });

public static void main(String[] args) {
Life life = new Life(K, SEED);

System.out.println(life);

for (int i = 0; i < ITERATIONS; i++) {
life.tick();
System.out.println(life);
}
}

private final Board board, oldBoard;

public Life(int k, Board seed) {
int width = 1 << k;
int height = 1 << k;
board = new Board(width, height);
oldBoard = new Board(width, height);

seed.copyTo(board);
}

private void tick() {
board.copyTo(oldBoard);

ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

for (int y = 0; y < board.height; y++)
for (int x = 0; x < board.width; x++)
executor.execute(new Evaluator(x, y));

executor.shutdown();

try {
executor.awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public Board getBoard() {
return board;
}

@Override
public String toString() {
return getBoard().toString();
}

private class Evaluator implements Runnable {
private final int x, y;

Evaluator(int x, int y) {
this.x = x;
this.y = y;
}

@Override
public void run() {
boolean state = DEAD;

int neighbors = oldBoard.countNeighbors(x, y);

switch (neighbors) {
case 2:
if (oldBoard.get(x, y) == DEAD)
break;
case 3:
state = ALIVE;
}

board.set(x, y, state);
}
}

public static class Board {
private final boolean[][] data;
private final int width, height;

public Board(boolean[][] data) {
this.data = data;
height = data.length;
width = data[0].length;
}

public Board(int width, int height) {
this.width = width;
this.height = height;
data = new boolean[height][width];
clear();
}

public void clear() {
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
set(x, y, DEAD);
}

public void copyTo(Board target) {
int yo = (target.height - height) / 2;
int xo = (target.width - width) / 2;

for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++) {
int dx = x + xo;
int dy = y + yo;

if (0 <= dx && dx < target.width && 0 <= dy && dy < target.height)
target.set(dx, dy, get(x, y));
}
}

public void set(int x, int y, boolean state) {
data[y][x] = state;
}

public boolean get(int x, int y) {
return data[y][x];
}

public int countNeighbors(int x, int y) {
int count = 0;

for (int y1 = Math.max(y - 1, 0), y2 = Math.min(y + 1, height - 1); y1 <= y2; y1++)
for (int x1 = Math.max(x - 1, 0), x2 = Math.min(x + 1, width - 1); x1 <= x2; x1++)
if (((y1 != y) || (x1 != x)) && get(x1, y1) == ALIVE)
count++;

return count;
}

@Override
public String toString() {
StringBuilder sb = new StringBuilder();

for (int x = 0; x < width + 2; x++)
sb.append('#');

sb.append('\n');

for (int y = 0; y < height; y++) {
sb.append('#');

for (int x = 0; x < width; x++)
sb.append(get(x, y) == ALIVE ? '*' : ' ');

sb.append("#\n");
}

for (int x = 0; x < width + 2; x++)
sb.append('#');

return sb.toString();
}

public int getWidth() {
return width;
}

public int getHeight() {
return height;
}
}
}
scala
import scala.actors.Futures.future

class Generation(gen: Array[String]) {
val width = gen(0).length
val hight = gen.length

override def toString = gen.reduceLeft(_ + "\n" + _)

def nextGen = {
// Calculate each row separately as a "future"
val ngFuture = (0 until hight).map(row => future(nextRow(row)))
// Wait for each row to finish
val ng = ngFuture.map(_ apply ())
new Generation(ng.toArray)
}

private def nextRow(row: Int): String =
(0 until width).map(nextCell(row, _)).foldLeft("")(_ + _)

private def nextCell(row: Int, col: Int) = {
liveNeighbors(row, col) match {
case 2 => cellAt(row, col)
case 3 => gameOfLife.liveCell
case _ => gameOfLife.deadCell
}
}

private def cellAt(row: Int, col: Int) =
gen((row + hight) % hight)((col + width) % width)

private def liveNeighbors(row: Int, col: Int) =
// Generate coordinate to all adjacent cells
((row-1) to (row+1)).flatMap(x => ((col-1) to (col+1)).map((x,_)))
// Remove our own cell and all dead neighbor cells
.filter(p => p != (row,col) && cellAt(p._1, p._2) == gameOfLife.liveCell)
// Get the number of cells we kept
.length
}


object gameOfLife {
val liveCell = 'O'
val deadCell = '.'
val firstGen = new Generation(Array(".O......",
"..O.....",
"OOO.....",
"........",
"........",
"........",
"........"))

def main(args: Array[String]) {
val numGens = if (args.length > 0) args(0).toInt else 3
var thisGen = firstGen
for (genNr <- 0 to numGens) {
println("Generation " + genNr)
println(thisGen)
thisGen = thisGen.nextGen
}
}
}

Create a multithreaded "Hello World"

Create a program which outputs the string "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.
clojure
(doseq [msg ["one" "two" "three" "four"]]
(future (println "Thread" msg "says Hello World!")))
(dorun (pmap #(println (str "Thread " % " says Hello World!")) '("one" "two" "three" "four")))
(dorun (map (fn [n] (.start (Thread. #(println (str "Thread " n " says Hello World!")))))
'("one" "two" "three" "four")))
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 <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;
}
}
fsharp
let mappedString =
["Thread one says Hello World!";
"Thread two says Hello World!";
"Thread four says Hello World!";
"Thread three says Hello World!"]
|> Seq.map (fun str -> async { printfn "%s" str })

Async.RunSynchronously (Async.Parallel mappedString)
groovy
["one","two","three","four"].each { tid ->
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!"
}
}
java
for (int i = 0; i < 4; i++) {
final int nr = i ;
new Thread(new Runnable() {
public void run() {
System.out.println("Thread " + new String[] { "one", "two", "three", "four" }[nr] + " says Hello World!");
}
}).start();
}
ocaml

(* Compilation (native):
$ ocamlopt -thread unix.cmxa threads.cmxa threads_hello.ml -o threads_hello
*)

let say_hello (i, msg) =
Printf.printf "Thread %d says %s\n" i msg
;;
let thread_ids = Array.init 4 (fun i ->
Thread.create say_hello (i, "Hello World!")) in
Array.iter Thread.join thread_ids;
flush_all ()
python
#!/usr/bin/python
from threading import Thread
Nthread = ['one','two','three','four']
def ThreadSpeaks(number):
print "Thread", number, "says Hello World!"
if __name__ == "__main__":
for n in range(0,len(Nthread)):
th =Thread(target=ThreadSpeaks, args=(Nthread[n],))
th.start()
scala
import scala.actors.Actor

List("one", "two", "three", "four").foreach { name =>
new Actor { override def act() = { println("Thread " + name + " says Hello World!") } }.start
}
List("one", "two", "three", "four").foreach { name =>
new Thread { override def run() = { println("Thread " + name + " says Hello World!") } }.start
}
import scala.actors.Futures._
List("one", "two", "three", "four").foreach(name => future(println("Thread " + name + " says hi")))

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.
clojure
; NOTE! Using explicit locking is NOT the Clojure way. It was done
; this way in order to comply exactly with the problem
; specification. Sharing data in Clojure would normally be done by
; using "atom", "agent" or "ref" depending on situation. None of those
; methods would ever result in the reader not being able to read (as
; required by the problem) since reading is wait-free in clojure.

(def *readers* (map #(agent %) '("one" "two" "three")))
(def *writers* (map #(agent %) '("four" "five")))
(def *mutex* (agent :unlocked))
(def *value* 0)

; mutex implementation
(defn lock [state who success-fn fail-fn]
(send who (if (= state :locked) fail-fn success-fn))
:locked)

(defn unlock [mutex]
:unlocked)

; Must be invoked with send-off since this handler blocks
(defn rand-sleep [state next-fn]
(Thread/sleep (rand-int 5))
(send *agent* next-fn)
state)

; Reader functions
(declare try-read)

(defn reader-got-lock [name]
(println (format "Thread %s says that the value is %d." name *value*))
(send *mutex* unlock)
(send-off *agent* rand-sleep try-read)
name)

(defn reader-did-not-get-lock [name]
(println (format "Thread %s tried to read the value, but could not." name))
(send-off *agent* rand-sleep try-read)
name)

(defn try-read [name]
(send *mutex* lock *agent* reader-got-lock reader-did-not-get-lock)
name)

; Writer functions
(declare try-write)

(defn writer-got-lock [name]
(println (format "Thread %s is taking the lock." name))
(def *value* (rand-int 10))
(println (format "Thread %s is changing the value to %d." name *value*))
(send *mutex* unlock)
(println (format "Thread %s is relasing the lock." name))
(send-off *agent* rand-sleep try-write)
name)

(defn writer-did-not-get-lock [name]
(println (format "Thread %s tried to write the value, but could not." name))
(send-off *agent* rand-sleep try-write)
name)

(defn try-write [name]
(send *mutex* lock *agent* writer-got-lock writer-did-not-get-lock)
name)

(dorun (map #(send % try-write) *writers*))
(dorun (map #(send % try-read) *readers*))
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")();
}
fsharp
open System.Threading
let lock = new ReaderWriterLock()
let mutable value = 0
let lockTimeout = 1

let ReaderThread t =
let random = new System.Random()
for i in 0 .. 100 do
try
lock.AcquireReaderLock(lockTimeout)
try
printfn "Thread %i says that the value is %i" t value
finally
lock.ReleaseReaderLock()
with _ ->
printfn "Thread %i tried to read the value, but could not (timeout)." t
Thread.Sleep(random.Next(50))

let WriterThread t =
let random = new System.Random()
for i in 0 .. 100 do
try
lock.AcquireWriterLock(lockTimeout)
try
value <- random.Next(10)
printfn "Thread %i is changing the value to %i" t value
Thread.MemoryBarrier()
finally
lock.ReleaseWriterLock()
printfn "Thread %i is releasing the lock." t
with _ ->
printfn "Thread %i tried to write the value, but could not (timeout)." t
Thread.Sleep(random.Next(50))

[| 0 .. 20 |]
|> Array.iter (fun t ->
async {
if t % 3 = 0 then
WriterThread t
else
ReaderThread t
}
|> Async.Start
)
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()
}
}
}
java
public class ParallelPermutations {

Lock lock = new ReentrantLock();

Integer value = 8;

public static void main(String[] args) {
new ParallelPermutations(Arrays.asList(args));
}

public ParallelPermutations(List<String> words) {
for (int i = 0; i < 20; i++) {
final Integer cnt = i ;
if ( i % 3 == 0) {
new Thread(new Runnable() {
public void run() {
if ( ! lock.tryLock() ) {
System.out.println("Thread " + cnt + " tried to write the value, but could not.") ;
lock.lock();
}
value = (int) (Math.random() * 10);
System.out.println("Thread " + cnt + " is changing the value to " + value ) ;
lock.unlock();
System.out.println("Thread " + cnt + " is releasing the lock.") ;
}
}).start();
} else {
new Thread(new Runnable() {
public void run() {
if ( ! lock.tryLock() ) {
System.out.println("Thread " + cnt + " tried to read the value, but could not.") ;
lock.lock() ;
}
System.out.println("Thread " + cnt + " says that the value is " + value + ".") ;
lock.unlock();
}
}).start();
}
}
}
}
ocaml

(* Compilation (native):
$ ocamlopt -thread unix.cmxa threads.cmxa threads_lock.ml -o threads_lock
*)

let value = ref 8
let mutex = Mutex.create ()

let create_writer i =
if not (Mutex.try_lock mutex) then begin
Printf.printf "Thread %d tried to write the value but could not.\n" i;
Mutex.lock mutex
end;
value := Random.int 10;
Printf.printf "Thread %d is changing the value to %d\n" i !value;
Mutex.unlock mutex;
Printf.printf "Thread %d is releasing the lock.\n" i

let create_reader i =
if not (Mutex.try_lock mutex) then begin
Printf.printf "Thread %d tried to read the value but could not.\n" i;
Mutex.lock mutex
end;
Printf.printf "Thread %d says that the value is %d\n" i !value;
Mutex.unlock mutex
;;

let thread_ids = Array.init 20 (fun i ->
Thread.create (if i mod 3 == 0 then create_writer else create_reader) i) in
Array.iter Thread.join thread_ids
python
#!/usr/bin/python
from threading import Thread, Lock
import time
thread_readers = ['one','two','three']
thread_writer = ['four','five']
lock = Lock()
value = 0

def Threadread(number):
global value
while True:
if lock.acquire(False):
print "Thread", number, "is taking the lock"
value += 1
print "Thread", number, "is changing the value to", value
print "Thread", number, "is releasing the lock."
lock.release()
else:
print "Thread", number, "tried to write to the value, but could not."
def Threadwrite(number):
global value
while True:
if lock.acquire(False):
print "Thread", number ,"four says that the value is", value
else:
print "Thread", number ,"tried to read the value, but could not."
if __name__ == "__main__":
for n in range(0,len(thread_readers)):
th =Thread(target=Threadread, args=(thread_readers[n],))
th.start()
for n in range(0,len(thread_writer)):
th =Thread(target=Threadwrite, args=(thread_writer[n],))
th.start()
scala
import java.util.concurrent.locks.ReentrantReadWriteLock
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock
import scala.util.Random

class Reader(name: String, lock: ReadLock) extends Thread {
override def run() = {
println(name)
while (true) {
if (!lock.tryLock)
{
println("Thread " + name + " tried to read the value, but could not.")
lock.lock
}
println("Thread " + name + " says that the value is " + rwLockOnSharedResource.value)
lock.unlock
Thread.sleep(3) // Generates output more similar to the problem description
}
}
}

class Writer(name: String, lock: WriteLock) extends Thread {
override def run() = {
while (true) {
if (!lock.tryLock) {
println("Thread " + name + " tried to write the value, but could not.")
lock.lock
}
println("Thread " + name + " is taking the lock.")
rwLockOnSharedResource.value = rwLockOnSharedResource.nextValue
println("Thread " + name + " is changing the value to " + rwLockOnSharedResource.value)
lock.unlock
println("Thread " + name + " is releasing the lock.")
Thread.sleep(3) // Generates output more similar to the problem description
}
}
}

object rwLockOnSharedResource {
private val maxValue = 10
private val randomVal = new Random
var value = nextValue

def nextValue = randomVal.nextInt(maxValue)

def main(args: Array[String]) = {
val rwLock = new ReentrantReadWriteLock(true)
val threadNames = List("one", "two", "three", "four", "five")
val readerCnt = threadNames.length * 2 / 3
val readerNames = threadNames.take(readerCnt)
val writerNames = threadNames.drop(readerCnt)

readerNames.foreach(new Reader(_, rwLock.readLock).start)
writerNames.foreach(new Writer(_, rwLock.writeLock).start)
}
}

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)
["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.
clojure
(defn background-computation [_ s]
(let [res (permutations s)]
(println (format "Done Work On %s!" s))
(println res)))

(defn shutdown-app [_]
(println "We're quitting! Alright!")
(shutdown-agents))

(println "Hello user! Please input a string to permute: ")
(let [worker-agent (agent nil)]
(loop [input (str (read))]
(if (= input "EXIT")
(do (println "Quitting, I'll let my worker thread know...")
(send worker-agent shutdown-app))
(do (println (format "Passing on %s..." input))
(send worker-agent background-computation input)
(println "Please input another string to permute: ")
(recur (str (read)))))))
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();
}
fsharp
open System

/// Computes all permutations of an array
let rec permute = function
| [| |] -> [| [| |] |]
| a ->
a
|> Array.mapi (fun i ai ->
Array.sub a 0 i
|> Array.append (Array.sub a (i + 1) (a.Length - i - 1))
|> permute
|> Array.map (fun perm -> Array.append [| ai |] perm)
)
|> Array.concat

/// Computes all permutations of a string
let permuteString (s: string) =
s.ToCharArray()
|> permute
|> Array.map (fun p -> new String(p))


type PermuteMessage =
| PermuteString of string
| Cancel

let mailbox = new MailboxProcessor<PermuteMessage>(fun inbox ->
let rec loop() =
async {
let! msg = inbox.Receive()
match msg with
| PermuteString s ->
printfn "[Worker] Starting to work on %s" s
let p = permuteString s
printfn "[Worker] Done my work on %s" s
let firstElems =
if s.Length > 4 then
let first = p |> Seq.truncate 4 |> Seq.toArray
String.Join(", ", first) + ", ..."
else
String.Join(", ", p)
printfn "[Worker] Result is %s" firstElems
return! loop()
| Cancel ->
printfn "[Worker] Nuff done, I'm quitting!"
return ()
}
loop()
)

do
printfn "[Input] Setting up worker."
mailbox.Start()
let loop = ref true
while !loop do
printfn "[Input] Please enter a word, or EXIT to exit"
let s = Console.ReadLine()
match s with
| "EXIT" ->
printfn "[Input] Sending worker the cancellation notice."
mailbox.Post(Cancel)
loop := false
| _ ->
printfn "[Input] Sending task to the worker."
mailbox.Post(PermuteString s)
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!'
}
}
}
}
java
public class BackgroundComputation {

final protected Queue<Thread> threads = new ConcurrentLinkedQueue<Thread>() ;

public BackgroundComputation() {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
try {
while (true) {
System.out.print("Enter string to permutate: ");
final String word = r.readLine();
if ("EXIT".equals(word) ) {
System.out.println("I'll let my worker thread know... (input thread)") ;
while (! threads.isEmpty())
threads.poll().stop(new ThreadDeath()) ;
break ;
}
Thread t = new Thread(new Runnable() {
public void run() {
try {
Set<String> permutationSet = new HashSet<String>();
for (int i = 0; i < word.length(); i++)
for (int j = i + 1; j <= word.length(); j++)
permutations("", word.substring(i, j), permutationSet);
System.out.println();
System.out.println("Received results: " + permutationSet);
System.out.print("Enter string to permutate: ");
} catch (ThreadDeath e) {
System.out.println("We're quitting! Alright!");
}
}

private void permutations(String prefix, String word, Set<String> permutations) {
int N = word.length();
if (N == 0)
permutations.add(prefix);
else
for (int i = 0; i < N; i++)
permutations(
prefix + word.charAt(i),
word.substring(0, i) + word.substring(i + 1, N),
permutations
);
}
});
t.start();
threads.add(t);
}
} catch (IOException ioe) {
System.out.println("IO error trying to read your name!");
System.exit(1);
}
}


public static void main(String[] args) {
new BackgroundComputation() ;
}
}
ocaml
(* Compile (native):
$ ocamlopt -thread unix.cmxa threads.cmxa async_interface.ml -o async_interface
*)

module Mailbox =
struct

type 'a t = {
lock: Mutex.t;
notempty_condition: Condition.t;
queue: 'a Queue.t;
}

let create () = {
lock = Mutex.create ();
notempty_condition = Condition.create ();
queue = Queue.create ();
}

let add mb v =
Mutex.lock mb.lock;
Queue.add v mb.queue;
Condition.signal mb.notempty_condition;
Mutex.unlock mb.lock

let take mb =
Mutex.lock mb.lock;
while Queue.is_empty mb.queue do
Printf.printf "(waiting)\n%!";
Condition.wait mb.notempty_condition mb.lock
done;
let v = Queue.take mb.queue in
Mutex.unlock mb.lock;
v
end

type 'a orders =
Process of 'a
| Terminate

let permute_string s buf =
let len = String.length s in
let sep = ref "" in
let rec aux i =
if i = 0 then begin
Buffer.add_string buf !sep;
Buffer.add_char buf '"';
Buffer.add_string buf s;
Buffer.add_char buf '"';
sep := ","
end
else
let c = s.[i] in
for j = 0 to i - 1 do
s.[i] <- s.[j];
s.[j] <- c;
aux (i - 1);
s.[j] <- s.[i]
done;
s.[i] <- c;
aux (i - 1)
in
if len > 0 then
aux (len - 1)

let rec slave_loop mailbox =
match Mailbox.take mailbox with
| Process s ->
Printf.printf "Working on %s...%!" s;
let len = String.length s in
let fact n =
let rec aux i acc =
if i < 2 then acc
else aux (i - 1) (acc * i) in
aux n 1 in
(* Buffers reallocate as needed, but since we know the size beforehand... *)
let expected_output_size = (len + 3) * (fact len) + 2 in
let buf = Buffer.create expected_output_size in
Buffer.add_char buf '[';
permute_string s buf;
Buffer.add_string buf "]\n";
Printf.printf " Done Work On %s!\n" s;
Buffer.output_buffer stdout buf;
flush stdout;
slave_loop mailbox
| Terminate ->
Printf.printf "%s\n%!" "We're quitting! Alright!"


let rec master_loop mailbox article =
Printf.printf "Please input %s string to permute: %!" article;
let exit_string = "EXIT" in
let s =
try
read_line ()
with End_of_file -> exit_string in
if s = exit_string then begin
Printf.printf "%s\n%!" "Quitting, I'll let my worker thread know";
Mailbox.add mailbox Terminate
end
else begin
Printf.printf "Passing on %s...\n%!" s;
Mailbox.add mailbox (Process s);
master_loop mailbox "another"
end

let () =
let mailbox = Mailbox.create () in
let slave_thread_id = Thread.create slave_loop mailbox in

print_string "Hello user! ";
master_loop mailbox "a";

Thread.join slave_thread_id
scala
import scala.actors.Actor

object Worker extends Actor {
def perm(s: String): List[String] =
s.length match {
case 0 => Nil
case 1 => s :: Nil
case sLen => (0 to sLen-1).map(i => perm(s.take(i) + s.drop(i+1)).map(s(i) + _)).toList.flatten
}

def act() = react {
case "EXIT" =>
println("We're quitting! Alright!")
case (s: String) =>
val r = perm(s)
println("Done working on " + s + "!")
print("[ ")
r.foreach(s => print("\"" + s + "\", "))
println("]")
act()
}
}

object userInteractBackgroundCalc {
def main(args: Array[String]) {
print("Hello user! ")
Worker.start
var str = ""

do {
println("Please input a string to permute:")
str = readLine()
Worker ! str
} while (str != "EXIT")
}
}

Put a internationalizate of HelloWorld program

Set locale to "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)

}
scala
import scala.collection.mutable

object SolutionXX {

// START

class I18N(s: String) {
def translate = {
Locale.current match {
case None => s
case Some(loc) => loc.translate(s).getOrElse(s)
}
}
}

implicit def stringToI18N(s: String) = new I18N(s)

class Locale(val name: String, map: Map[String, String]) {
Locale.registerLocale(this)

def translate(s: String) = map.get(s)
}

object Locale {
var current: Option[Locale] = None
var locales: mutable.Map[String, Locale] = mutable.Map()

def registerLocale(locale: Locale) {
locales += (locale.name -> locale)
//NOTE : here we could check locale translation completeness against others and prints whose entries are missing
}

def set(locale: String) {
current = locales.get(locale)
}
}

val helloworld = "Hello World!";
//NOTE :: just read out properties files in maps below
val en = new Locale("en", Map(helloworld -> "Hello World!"))
val fr = new Locale("fr", Map(helloworld -> "Bonjour le Monde !"))
val es = new Locale("es", Map(helloworld -> "¡Hola Mundo!"))

def main(args: Array[String]) {
def printIn(locale: Option[String]) {
locale match {
case None =>
case Some(l) => Locale.set(l)
}
println(helloworld.translate)
}

printIn(None)
printIn(Some("en"))
printIn(Some("fr"))
printIn(Some("es"))
printIn(Some("alien"))
}


// END
}
180
180

180


Low Cost Custom-Made bretelles sexy mariage mariée robe de mariée Robes <code>[Mall3411]</code> - $175.01 : <<code>/title> <br/><meta http-equiv="Content-Type" content="text/</code>html; charset=utf-8<code>" /> <br/><meta name="</code>keywords<code>" content="</code>Low Cost Custom-Made bretelles sexy mariage mariée robe de mariée Robes <code>[Mall3411]</code> 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 <code>" /> <br/><meta name="</code>description<code>" content="</code> Low Cost Custom-Made bretelles sexy mariage mariée robe de mariée Robes <code>[Mall3411]</code> - Nom de l<code>'article: " /> <br/><meta http-equiv="imagetoolbar" content="no" /> <br/><meta name="author" content="Zen Cart China" /> <br/><meta name="generator" content="Zen Cart, http://www.zen-cart.cn" /> <br/> <br/> <br/><link rel="canonical" href="http://fr.weddingdressescompany.com/low-cost-custommade-bretelles-sexy-mariage-mariée-robe-de-mariée-robes-p-456.html" /> <br/> <br/><link rel="stylesheet" type="text/css" href="http://fr.weddingdressescompany.com/includes/templates/weddingdress-7/css/style_imagehover.css" /><br/><link rel="stylesheet" type="text/css" href="http://fr.weddingdressescompany.com/includes/templates/weddingdress-7/css/stylesheet.css" /><br/><link rel="stylesheet" type="text/css" href="http://fr.weddingdressescompany.com/includes/templates/weddingdress-7/css/stylesheet_css_buttons.css" /><br/><link rel="stylesheet" type="text/css" media="print" href="http://fr.weddingdressescompany.com/includes/templates/weddingdress-7/css/print_stylesheet.css" /><br/><br/><br/><br/> <br/><link type="text/css" href="http://fr.weddingdressescompany.com/includes/templates/weddingdress-7/css/magiczoomplus.css" rel="stylesheet" media="screen" /> <br/> <br/><br/><br/> <br/> <br/> <br/> <br/> <br/><div id="mainWrapper "> <br/> <br/> <br/> <br/><br/> <br/> <br/><div id="headerWrapper "><div id="lang_main_page" style="padding-top:10px; float:right; "><b>language:</b> <br/> <br/> <a href="http://de.weddingdressescompany.com "> <br/> <img src="http://fr.weddingdressescompany.com/langimg/gericon.gif" alt="Deutsch" title=" Deutsch " height="15" width="24 "></a>   <br/> <a href="http://fr.weddingdressescompany.com "> <br/> <img src="http://fr.weddingdressescompany.com/langimg/fricon.gif" alt="Français" title=" Français " height="15" width="24 "></a>   <br/> <a href="http://it.weddingdressescompany.com "> <br/> <img src="http://fr.weddingdressescompany.com/langimg/iticon.gif" alt="italiano" title=" italiano " height="15" width="24 "></a>   <br/> <a href="http://es.weddingdressescompany.com ">         <br/> <img src="http://fr.weddingdressescompany.com/langimg/esicon.gif" alt="Español" title=" Español " height="15" width="24 "></a>   <br/> <a href="http://pt.weddingdressescompany.com "> <br/> <img src="http://fr.weddingdressescompany.com/langimg/pticon.gif" alt="Português" title=" Português " height="15" width="24 "></a>   <br/> <a href="http://jp.weddingdressescompany.com "> <br/> <img src="http://fr.weddingdressescompany.com/langimg/jpicon.gif" alt="日本語" title=" æ—¥æœ¬èªž " height="14" width="24 "></a>   <br/> <a href="http://www.weddingdressescompany.com "> <br/> <img src="http://fr.weddingdressescompany.com/langimg/icon.gif" alt="English" title=" English " height="15" width="24 "></a>   <br/></div> <br/><br/> <br/><div class="topper-menu float-left" style="background:#333333; width:100%; text-align:right; padding:0px; "> <br/> <br/><div id="navEZPagesTop "> <br/> <ul style="list-style-image: none;list-style-type: none; padding:0px; height:28px; line-height:28px;margin-top: 0px; margin-bottom:0px;margin-left:55%; "> <br/> <li><a href="http://fr.weddingdressescompany.com/index.php?main_page=login "><font style="color:#FFFFFF ">My Account</font></a></li> <br/> <li><a href="http://fr.weddingdressescompany.com/index.php?main_page=shopping_cart "><font style="color:#FFFFFF ">View Cart</font></a></li> <br/> <li><a href="http://fr.weddingdressescompany.com/index.php?main_page=login "><font style="color:#FFFFFF ">Checkout</font></a></li> <br/> <br/>   <li> <a href="http://fr.weddingdressescompany.com/index.php?main_page=login "><font style="color:#FFFFFF ">Se connecter</font></a> <br/> <font style="color:#FFFFFF "> HEADER_OR </font> <br/>    <a href="http://fr.weddingdressescompany.com/index.php?main_page=create_account "><font style="color:#FFFFFF ">HEADER_TITLE_REGISTER</font></a></li> <br/> <br/> <br/> <br/> </ul> <br/></div> <br/></div> <br/><div class="clearBoth" /></div> <br/><br/> <br/> <br/> <br/><br/> <br/><br/> <br/> <br/><br/> <br/> <br/><div id="logoWrapper "> <br/><div id="logo"  style="margin-top:5px; margin-bottom:5px; "><a href="http://fr.weddingdressescompany.com/ "><img src="http://fr.weddingdressescompany.com/includes/templates/weddingdress-7/images/logo.gif" alt="" width="250" height="73" /></a></div> <br/><div class="td-search-header "> <br/><div class="search-header float-left "> <br/><form name="quick_find_header" action="http://fr.weddingdressescompany.com/index.php?main_page=advanced_search_result" method="get "><input type="hidden" name="main_page" value="advanced_search_result" /><input type="hidden" name="search_in_description" value="1" /><div class="search-header-input"  style="padding-top:10px;padding-bottom:0px; "><input type="text" name="keyword" size="6" maxlength="30" value="Entrez vos mots clefs ici" onfocus="if (this.value == '</code>Entrez vos mots clefs ici<code>') this.value = ';" onblur="if (this.value == ') this.value = '</code>Entrez vos mots clefs ici<code>';" /></div><div style="float:left "><input  style="float:left;width:47px; height:35px;"  type="image" src="http://fr.weddingdressescompany.com/includes/templates/weddingdress-7/images/search-bg_02.gif" value="Serch" /></div></form></div> <br/></div> <br/><div style=" float:left; margin-left:10px; height:58px; width:270px; "> <br/><br/> <br/><div style="float:left; padding-top:15px; "> <br/><img src="http://fr.weddingdressescompany.com/includes/templates/weddingdress-7/images/shipping.gif"/><a href="http://fr.weddingdressescompany.com/index.php?main_page=shopping_cart "><img src="http://fr.weddingdressescompany.com/includes/templates/weddingdress-7/images/cart.gif" style="border:0px;"/></a> <br/></div> <br/><br/> <br/><div style="height:10px; "></div> <br/><div style="padding-top:0px; "> <br/><div style="float:left; width:120px; "><font style=" font-size:0.96em; background:#FFFFFF; color:#000000; ">Choisissez votre devise</font></div> <br/><div style="float:left; width:100px; "> <br/><form name="currencies" action="http://fr.weddingdressescompany.com/" method="get "><select name="currency" onchange="this.form.submit();" style="width: 100% "><br/>  <option value="USD" selected="selected ">US Dollar</option><br/>  <option value="CNY ">CNY</option><br/>  <option value="EUR ">Euro</option><br/>  <option value="GBP ">GB Pound</option><br/>  <option value="CAD ">Canadian Dollar</option><br/>  <option value="AUD ">Australian Dollar</option><br/></select><br/><input type="hidden" name="main_page" value="product_info" /><input type="hidden" name="products_id" value="456" /></form></div> <br/></div> <br/><br/> <br/></div> <br/></div> <br/><div class="clearBoth" /></div> <br/><br/> <br/> <br/><br/> <br/> <br/><br/> <br/><br/> <br/> <br/> <br/><div id="top_nav "> <br/><div id="tab_nav "> <br/><br/> <br/><div class="top-nav-right "></div> <br/><div style=" float:left; "> <br/> <a href="http://fr.weddingdressescompany.com/low-cost-custommade-bretelles-sexy-mariage-mariée-robe-de-mariée-robes-p-456.html" ><img src="http://fr.weddingdressescompany.com/includes/templates/weddingdress-7/images/home.jpg"/></a> <br/></div> <br/><ul class="list-style-none "> <br/><li class="home-link "><a href="http://fr.weddingdressescompany.com/" >TOP_MENU_HOME</a></li> <br/><li id="" ><a href="http://fr.weddingdressescompany.com/cocktail-dresses-c-28.html ">Robes de cocktail</a></li> <br/><li id="" ><a href="http://fr.weddingdressescompany.com/evening-dresses-c-27.html ">Robes de soirée</a></li> <br/><li id="" ><a href="http://fr.weddingdressescompany.com/wedding-dresses-c-1.html ">Robes de mariée</a></li> <br/><li id="" ><a href="http://fr.weddingdressescompany.com/prom-dresses-c-24.html ">Robes de bal</a></li> <br/><li id="" ><a href="http://fr.weddingdressescompany.com/index.php?main_page=contact_us ">Contactez-nous</a></li> <br/><li id="" ><a href="http://fr.weddingdressescompany.com/javascript:__Bookmark('</code>http:<code>//</code>fr.weddingdressescompany.com<code>/»,«http:/fr.weddingdressescompany.com/</code><code>' ) " > Marque page</a></li> <br/></ul> <br/></div> <br/></div> <br/><hr style="border:2px solid #666666;"/> <br/><br/> <br/><br/> <br/> <br/></div> <br/><br/> <br/><table width="100%" border="0" cellspacing="0" cellpadding="0" id="contentMainWrapper "> <br/><tr> <br/> <br/><td id="navColumnOne" class="columnLeft" style="width:210px "> <br/><div id="navColumnOneWrapper" style="width: 220px" > <br/><div class="leftBoxContainer" id="categories" style="width: 220px "> <br/><div class="sidebox-header-left main-sidebox-header-left "><h3 class="leftBoxHeading main-sidebox-header-right" id="categoriesHeading ">Catégories</h3></div> <br/><div id="categoriesContent" class="sideBoxContent "><br/><div class="categories-top-list no-dots "><a class="category-top" href="http://fr.weddingdressescompany.com/robes-de-mariée-c-1.html "><span class="category-subs-parent ">Robes de Mariée</span></a></div><br/><div class="subcategory "><a class="category-products" href="http://fr.weddingdressescompany.com/robes-de-mariée-meilleures-robes-de-mariée-de-vente-c-1_19.html ">MEILLEURES robes de mariée de Vente</a></div><br/><div class="subcategory "><a class="category-products" href="http://fr.weddingdressescompany.com/robes-de-mariée-mini-robes-de-mariée-c-1_11.html ">Mini robes de mariée</a></div><br/><div class="subcategory "><a class="category-products" href="http://fr.weddingdressescompany.com/robes-de-mariée-petites-robes-noires-c-1_13.html ">Petites robes noires</a></div><br/><div class="subcategory "><a class="category-products" href="http://fr.weddingdressescompany.com/robes-de-mariée-robe-de-mariée-amie-c-1_3.html ">Robe de mariée amie</a></div><br/><div class="subcategory "><a class="category-products" href="http://fr.weddingdressescompany.com/robes-de-mariée-robe-de-mariée-sexy-c-1_30.html ">Robe de mariée sexy</a></div><br/><div class="subcategory "><a class="category-products" href="http://fr.weddingdressescompany.com/robes-de-mariée-robes-de-mariage-de-plage-c-1_20.html ">Robes de mariage de plage</a></div><br/><div class="subcategory "><a class="category-products" href="http://fr.weddingdressescompany.com/robes-de-mariée-robes-de-mariage-empire-c-1_15.html ">Robes de mariage Empire</a></div><br/><div class="subcategory "><a class="category-products" href="http://fr.weddingdressescompany.com/robes-de-mariée-robes-de-mariage-gaine-c-1_6.html ">Robes de mariage gaine</a></div><br/><div class="subcategory "><a class="category-products" href="http://fr.weddingdressescompany.com/robes-de-mariée-robes-de-mariage-robe-boule-c-1_21.html ">Robes de mariage robe boule</a></div><br/><div class="subcategory "><a class="category-products" href="http://fr.weddingdressescompany.com/robes-de-mariée-robes-de-mariée-2012-c-1_29.html ">Robes de mariée 2012</a></div><br/><div class="subcategory "><a class="category-products" href="http://fr.weddingdressescompany.com/robes-de-mariée-robes-de-mariée-a-ligne-c-1_22.html ">Robes de mariée A- ligne</a></div><br/><div class="subcategory "><a class="category-products" href="http://fr.weddingdressescompany.com/robes-de-mariée-robes-de-mariée-bustier-c-1_4.html ">Robes de mariée bustier</a></div><br/><div class="subcategory "><a class="category-products" href="http://fr.weddingdressescompany.com/robes-de-mariée-robes-de-mariée-colonne-c-1_17.html ">Robes de mariée Colonne</a></div><br/><div class="subcategory "><a class="category-products" href="http://fr.weddingdressescompany.com/robes-de-mariée-robes-de-mariée-courtes-c-1_5.html ">Robes de Mariée courtes</a></div><br/><div class="subcategory "><a class="category-products" href="http://fr.weddingdressescompany.com/robes-de-mariée-robes-de-mariée-de-couleur-c-1_18.html ">Robes de mariée de Couleur</a></div><br/><div class="subcategory "><a class="category-products" href="http://fr.weddingdressescompany.com/robes-de-mariée-robes-de-mariée-de-princesse-c-1_8.html ">Robes de mariée de princesse</a></div><br/><div class="subcategory "><a class="category-products" href="http://fr.weddingdressescompany.com/robes-de-mariée-robes-de-mariée-designer-c-1_16.html ">Robes de mariée Designer</a></div><br/><div class="subcategory "><a class="category-products" href="http://fr.weddingdressescompany.com/robes-de-mariée-robes-de-mariée-en-dentelle-c-1_14.html ">Robes de mariée en dentelle</a></div><br/><div class="subcategory "><a class="category-products" href="http://fr.weddingdressescompany.com/robes-de-mariée-robes-de-mariée-épaule-c-1_10.html ">Robes de mariée Ã©paule</a></div><br/><div class="subcategory "><a class="category-products" href="http://fr.weddingdressescompany.com/robes-de-mariée-robes-de-mariée-sirène-c-1_12.html ">Robes de Mariée Sirène</a></div><br/><div class="categories-top-list  "><a class="category-top" href="http://fr.weddingdressescompany.com/robe-de-mariée-sexy-c-7.html ">Robe de mariée sexy</a></div><br/><div class="categories-top-list  "><a class="category-top" href="http://fr.weddingdressescompany.com/robes-de-bal-c-26.html ">Robes de bal</a></div><br/><div class="categories-top-list  "><a class="category-top" href="http://fr.weddingdressescompany.com/robes-de-bal-c-24.html ">Robes de bal</a></div><br/><div class="categories-top-list  "><a class="category-top" href="http://fr.weddingdressescompany.com/robes-de-cocktail-c-28.html ">Robes de cocktail</a></div><br/><div class="categories-top-list  "><a class="category-top" href="http://fr.weddingdressescompany.com/robes-de-mariée-c-9.html ">Robes de mariée</a></div><br/><div class="categories-top-list  "><a class="category-top" href="http://fr.weddingdressescompany.com/robes-de-mariée-2012-c-2.html ">Robes de mariée 2012</a></div><br/><div class="categories-top-list  "><a class="category-top" href="http://fr.weddingdressescompany.com/robes-de-soirée-c-25.html ">Robes de soirée</a></div><br/><div class="categories-top-list  "><a class="category-top" href="http://fr.weddingdressescompany.com/robes-de-soirée-c-27.html ">Robes de soirée</a></div><br/><div class="categories-top-list  "><a class="category-top" href="http://fr.weddingdressescompany.com/robes-quinceanera-c-23.html ">robes Quinceanera</a></div><br/></div></div> <br/> <br/> <br/><div class="leftBoxContainer" id="whatsnew" style="width: 220px "> <br/><div class="sidebox-header-left  "><h3 class="leftBoxHeading " id="whatsnewHeading ">Nouveaux produits - <a href="http://fr.weddingdressescompany.com/products_new.html ">  [plus]</a></h3></div> <br/><div class="sideBoxContent centeredContent "><a href="http://fr.weddingdressescompany.com/asymétrique-sweetheart-siren-applique-ruché-de-mariage-sweep-longueur-de-robe-pwd110-p-498.html "><img src="http://fr.weddingdressescompany.com/images/weddingdress/princess_wedding_dresses_110.jpg" alt="Asymétrique sweetheart Siren Applique ruché de mariage Sweep Longueur de robe (PWD-110)" title=" Asymétrique sweetheart Siren Applique ruché de mariage Sweep Longueur de robe (PWD-110) " width="130" height="257" style="position:relative" onmouseover="showtrail('</code>images<code>/weddingdress/princess_wedding_dresses_110.jpg','Asymétrique sweetheart Siren Applique ruché de mariage Sweep Longueur de robe (PWD-110)',130,256,304,600,this,0,0,130,256);" onmouseout="hidetrail();"  /</code>><<code>/a><a class="sidebox-products" href="http:/fr.weddingdressescompany.com/</code>asymétrique-sweetheart-siren-applique-ruché-de-mariage-sweep-longueur-de-robe-pwd110-p-498.html <code>">Asymétrique sweetheart Siren Applique ruché de mariage Sweep Longueur de robe (PWD-110)</a><div><span class="</code>normalprice <code>">$339.99 </span> <span class="</code>productSpecialPrice <code>">$169.99</span><span class="</code>productPriceDiscount <code>"><br />Economie : 50%</span></div></div><div class="</code>sideBoxContent centeredContent <code>"><a href="</code>http:<code>//</code>fr.weddingdressescompany.com<code>/2012-chubby-à-encolure-en-v-à-taille-empire-applique-bretelles-robe-cour-train-pswd001-p-500.html "><img src="http:/fr.weddingdressescompany.com/</code>images<code>/weddingdress/</code>plus_size_wedding_dresses_001.jpg<code>" alt="</code>2012 Chubby à encolure en V à taille empire Applique bretelles Robe Cour Train (PSWD-001)<code>" title="</code> 2012 Chubby à encolure en V à taille empire Applique bretelles Robe Cour Train (PSWD-001) <code>" width="</code>130<code>" height="</code>173<code>" style="</code>position:relative<code>" onmouseover="</code>showtrail(<code>'images/weddingdress//plus_size_wedding_dresses_001.jpg'</code>,<code>'2012 Chubby Ã  encolure en V Ã  taille empire Applique bretelles Robe Cour Train (PSWD-001)'</code>,130,173,300,400,this,0,0,130,173);<code>" onmouseout="</code>hidetrail();<code>"  /></a><a class="</code>sidebox-products<code>" href="</code>http:<code>//</code>fr.weddingdressescompany.com<code>/2012-chubby-à-encolure-en-v-à-taille-empire-applique-bretelles-robe-cour-train-pswd001-p-500.html ">2012 Chubby Ã  encolure en V Ã  taille empire Applique bretelles Robe Cour Train (PSWD-001)</</code>a><div><span class=<code>"normalprice "</code>>$318.99 <<code>/span> <span class="productSpecialPrice ">$158.99</</code>span><span class=<code>"productPriceDiscount "</code>><br <code>/>Economie : 50%</</code>span><<code>/div></</code>div><div class=<code>"sideBoxContent centeredContent "</code>><a href=<code>"http://fr.weddingdressescompany.com/elégant-aligne-bretelles-plus-size-sash-avec-robe-applique-longueur-de-balayage-pswd003-p-501.html "</code>><img src=<code>"http://fr.weddingdressescompany.com/images/weddingdress/plus_size_wedding_dresses_003.jpg"</code> alt=<code>"Elégant A-ligne bretelles Plus Size Sash Avec Robe Applique Longueur de balayage (PSWD-003)"</code> title=<code>" Elégant A-ligne bretelles Plus Size Sash Avec Robe Applique Longueur de balayage (PSWD-003) "</code> width=<code>"130"</code> height=<code>"173"</code> style=<code>"position:relative"</code> onmouseover=<code>"showtrail('images/weddingdress//plus_size_wedding_dresses_003.jpg','Elégant A-ligne bretelles Plus Size Sash Avec Robe Applique Longueur de balayage (PSWD-003)',130,173,1000,1333,this,0,0,130,173);"</code> onmouseout=<code>"hidetrail();"</code> <code>/></</code>a><a class=<code>"sidebox-products"</code> href=<code>"http://fr.weddingdressescompany.com/elégant-aligne-bretelles-plus-size-sash-avec-robe-applique-longueur-de-balayage-pswd003-p-501.html "</code>>Elégant A-ligne bretelles Plus Size Sash Avec Robe Applique Longueur de balayage (PSWD-003)<<code>/a><div><span class="normalprice ">$348.99 </</code>span> <span class=<code>"productSpecialPrice "</code>>$166.99<<code>/span><span class="productPriceDiscount "><br /</code>>Economie : 52%<<code>/span></</code>div><<code>/div><div class="sideBoxContent centeredContent "><a href="http:/fr.weddingdressescompany.com/</code>2012-slinky-applique-charme-sweetheart-tribunal-train-plissé-princess-dress-pwd111-p-499.html <code>"><img src="</code>http:<code>//</code>fr.weddingdressescompany.com<code>/images/</code>weddingdress<code>/princess_wedding_dresses_111.jpg" alt="2012 Slinky Applique Charme sweetheart tribunal train plissé Princess Dress (PWD-111)" title=" 2012 Slinky Applique Charme sweetheart tribunal train plissé Princess Dress (PWD-111) " width="130" height="259" style="position:relative" onmouseover="showtrail('images/</code>weddingdress<code>//</code>princess_wedding_dresses_111.jpg<code>','</code>2012 Slinky Applique Charme sweetheart tribunal train plissé Princess Dress (PWD-111)<code>',130,259,301,600,this,0,0,130,259);" onmouseout="hidetrail();"  /></a><a class="sidebox-products" href="http://fr.weddingdressescompany.com/2012-slinky-applique-charme-sweetheart-tribunal-train-plissé-princess-dress-pwd111-p-499.html ">2012 Slinky Applique Charme sweetheart tribunal train plissé Princess Dress (PWD-111)</a><div><span class="normalprice ">$326.99 </span> <span class="productSpecialPrice ">$165.99</span><span class="productPriceDiscount "><br />Economie : 49%</span></div></div></div> <br/> <br/></div></td> <br/><td id="columnCenter" valign="top "> <br/><br/> <br/><div id="navBreadCrumb ">  <a href="http://fr.weddingdressescompany.com/ ">Accueil</a> :: <br/>  <a href="http://fr.weddingdressescompany.com/robes-de-mariée-c-1.html ">Robes de Mariée</a> :: <br/>  <a href="http://fr.weddingdressescompany.com/robes-de-mariée-robe-de-mariée-sexy-c-1_30.html ">Robe de mariée sexy</a> :: <br/>Low Cost Custom-Made bretelles sexy mariage mariée robe de mariée Robes<br/></div> <br/><br/> <br/> <br/> <br/><br/> <br/><br/> <br/> <br/><div class="centerColumn" id="productGeneral "> <br/> <br/> <br/><h1 id="productName" class="productGeneral ">Low Cost Custom-Made bretelles sexy mariage mariée robe de mariée Robes</h1> <br/> <br/><form name="cart_quantity" action="http://fr.weddingdressescompany.com/low-cost-custommade-bretelles-sexy-mariage-mariée-robe-de-mariée-robes-p-456.html?action=add_product&number_of_uploads=0" method="post" enctype="multipart/form-data "><br/> <br/><div style="float:left; "> <br/> <br/> <br/>  <br/><div id="productMainImage" class="centeredContent back "> <br/> <br/><noscript> <br/><a href="http://fr.weddingdressescompany.com/index.php?main_page=popup_image&pID=456" target="_blank "> <a href="http://fr.weddingdressescompany.com/low-cost-custommade-bretelles-sexy-mariage-mariée-robe-de-mariée-robes-p-456.html" ><img src="http://fr.weddingdressescompany.com/images/weddingdress/sxw0018.jpg" alt="Low Cost Custom-Made bretelles sexy mariage mariée robe de mariée Robes" title=" Low Cost Custom-Made bretelles sexy mariage mariée robe de mariée Robes " width="240" height="329" /></a><br /><span class="imgLink ">Agrandir l'</code>image<<code>/span></</code>a><<code>/noscript> <br/></</code>div> <br/> <br/> <div id=<code>"productAdditionalImages "</code>> <br/> <div id=<code>"dfse "</code>><<code>/div> <br/>  <div class="centerBoxContent "> <br/> <br/> <br/>    <div class="additionalImages centeredContent back" style="width:100%; "><br/>      <br/>      <noscript><a href="http:/fr.weddingdressescompany.com/</code>low-cost-custommade-bretelles-sexy-mariage-mariée-robe-de-mariée-robes-p-456.html<code>" target="</code>_blank <code>"> <a href="</code>http:<code>//</code>fr.weddingdressescompany.com<code>/low-cost-custommade-bretelles-sexy-mariage-mariée-robe-de-mariée-robes-p-456.html" ><img src="http:/fr.weddingdressescompany.com/</code>images<code>/weddingdress/</code>sxw0018_01.jpg<code>" alt="</code>Low Cost Custom-Made bretelles sexy mariage mariée robe de mariée Robes<code>" title="</code> Low Cost Custom-Made bretelles sexy mariage mariée robe de mariée Robes <code>" width="</code>130<code>" height="</code>174<code>" style="</code>position:relative<code>" onmouseover="</code>showtrail(<code>'images/weddingdress//sxw0018_01.jpg'</code>,<code>'Low Cost Custom-Made bretelles sexy mariage mariée robe de mariée Robes'</code>,130,173,243,325,this,0,0,130,173);<code>" onmouseout="</code>hidetrail();<code>"  /></a><br /><span class="</code>imgLinkAdditional <code>">Agrandir l'image</span></a></noscript></div><br/><br class="</code>clearBoth<code>" /> <br/>  <br/></div></div> <br/> <br/></div> <br/> <br/><div style="</code>width:348px;float:right;<code>" id='pb-left-column'> <br/> <br/><span id="</code>productPrices<code>" class="</code>productGeneral <code>"> <br/>Price:  <br/><span class="</code>normalprice <code>">$218.77 </span> <span class="</code>productSpecialPrice <code>">$175.01</span><span class="</code>productPriceDiscount <code>"><br />Economie : 20%</span></span> <br/><div class="</code>model_number<code>" style="</code>height:14px;padding-top:7px <code>"><h4 style="</code>float: left;color:black; <code>"><label class="</code>class <code>">Modèle : </label></h4><div style="</code>float: left;margin-top:5px;margin-left:6px; <code>"><span style="</code>font-size:12px;height:20px;color:black; <code>">Mall3411</span></div><br/></div> <br/> <br/> <br/> <br/> <br/> <br/><div id="</code>productAttributes <code>"> <br/><h1 style='margin-bottom: 10px;'>Step 1 - Choose Options:</h1> <br/> <br/> <br/><div class="</code>wrapperAttribsOptions <code>"> <br/><h4 class="</code>optionName back <code>"><label>Colors</label></h4> <br/><div class="</code>back <code>"><br/><select name="</code>id<code>[8]</code><code>" id="</code>attrib-8 <code>"><br/>  <option value="</code>46 <code>">1</option><br/>  <option value="</code>52 <code>">10</option><br/>  <option value="</code>53 <code>">12</option><br/>  <option value="</code>54 <code>">16</option><br/>  <option value="</code>55 <code>">17</option><br/>  <option value="</code>56 <code>">18</option><br/>  <option value="</code>47 <code>">2</option><br/>  <option value="</code>57 <code>">20</option><br/>  <option value="</code>58 <code>">21</option><br/>  <option value="</code>59 <code>">23</option><br/>  <option value="</code>60 <code>">26</option><br/>  <option value="</code>61 <code>">27</option><br/>  <option value="</code>62 <code>">28</option><br/>  <option value="</code>63 <code>">29</option><br/>  <option value="</code>64 <code>">30</option><br/>  <option value="</code>65 <code>">31</option><br/>  <option value="</code>66 <code>">33</option><br/>  <option value="</code>67 <code>">35</option><br/>  <option value="</code>68 <code>">36</option><br/>  <option value="</code>69 <code>">37</option><br/>  <option value="</code>48 <code>">4</option><br/>  <option value="</code>70 <code>">41</option><br/>  <option value="</code>71 <code>">43</option><br/>  <option value="</code>72 <code>">44</option><br/>  <option value="</code>73 <code>">47</option><br/>  <option value="</code>74 <code>">48</option><br/>  <option value="</code>75 <code>">49</option><br/>  <option value="</code>49 <code>">5</option><br/>  <option value="</code>76 <code>">51</option><br/>  <option value="</code>77 <code>">54</option><br/>  <option value="</code>78 <code>">56</option><br/>  <option value="</code>79 <code>">60</option><br/>  <option value="</code>80 <code>">61</option><br/>  <option value="</code>81 <code>">66</option><br/>  <option value="</code>82 <code>">67</option><br/>  <option value="</code>83 <code>">69</option><br/>  <option value="</code>84 <code>">73</option><br/>  <option value="</code>85 <code>">77</option><br/>  <option value="</code>86 <code>">78</option><br/>  <option value="</code>87 <code>">79</option><br/>  <option value="</code>50 <code>">8</option><br/>  <option value="</code>51 <code>">9</option><br/>  <option value="</code>27 <code>">Ivory</option><br/>  <option value="</code>26 <code>">Same As Picture</option><br/>  <option value="</code>28 <code>">White</option><br/></select><br/><br/></div> <br/><br class="</code>clearBoth<code>" /> <br/></div> <br/> <br/> <br/> <br/> <br/><br/><br class="</code>clearBoth<code>" /> <br/> <br/><div class="</code>wrapperAttribsOptions <code>"> <br/><h4 class="</code>optionName back <code>"><label>Sizes</label></h4> <br/><div class="</code>back <code>"><br/><select name="</code>id<code>[9]</code><code>" id="</code>attrib-9 <code>"><br/>  <option value="</code>29 <code>">US 10 / UK 12 / EUR 40</option><br/>  <option value="</code>30 <code>">US 12 / UK 14 /EUR 42</option><br/>  <option value="</code>31 <code>">US 14 / UK 16 /EUR 44</option><br/>  <option value="</code>32 <code>">US 16 / UK 18 /EUR 46</option><br/>  <option value="</code>33 <code>">US 18 / UK 20 /EUR 48</option><br/>  <option value="</code>34 <code>">US 2 / UK 4 /EUR 32</option><br/>  <option value="</code>35 <code>">US 20 / UK 22 /EUR 50</option><br/>  <option value="</code>36 <code>">US 22 / UK 24 /EUR 52</option><br/>  <option value="</code>37 <code>">US 24 / UK 26 /EUR 54</option><br/>  <option value="</code>38 <code>">US 26 / UK 28 /EUR 56</option><br/>  <option value="</code>39 <code>">US 28 / UK 30 /EUR 58</option><br/>  <option value="</code>40 <code>">US 4 / UK 6 /EUR 34</option><br/>  <option value="</code>41 <code>">US 6 / UK 8 /EUR 36</option><br/>  <option value="</code>42 <code>">US 8 / UK 10 /EUR 38</option><br/></select><br/><br/></div> <br/><br class="</code>clearBoth<code>" /> <br/></div> <br/> <br/> <br/> <br/> <br/><br/><br class="</code>clearBoth<code>" /> <br/> <br/><div class="</code>wrapperAttribsOptions <code>"> <br/><h4 class="</code>optionName back <code>"><label>Back style</label></h4> <br/><div class="</code>back <code>"><br/><select name="</code>id<code>[10]</code><code>" id="</code>attrib-10 <code>"><br/>  <option value="</code>44 <code>">Lace Up</option><br/>  <option value="</code>43 <code>">Same As Picture</option><br/>  <option value="</code>45 <code>">Zip Up</option><br/></select><br/><br/></div> <br/><br class="</code>clearBoth<code>" /> <br/></div> <br/> <br/> <br/> <br/> <br/><br/><br class="</code>clearBoth<code>" /> <br/> <br/><div style="</code>padding-bottom:5px; <code>"><a href="</code>http:<code>//</code>fr.weddingdressescompany.com<code>/size.html" style="color:black;font-weight:bold;text-decoration:underline; color:#FF0000;" target="_blank ">Size Chart</</code>a> | <a href=<code>"http://fr.weddingdressescompany.com/color.html"</code> style=<code>"color:black;font-weight:bold;text-decoration:underline;color:#FF0000;"</code> target=<code>"_blank "</code>>Color Chart<<code>/a></</code>div> <br/> <br/> <br/><<code>/div> <br/><div id='quantity_cart'> <br/><h1>Step 2 - Choose Quantity:</</code>h1> <br/> <br/> <br/> <div class=<code>"wrapperAttribsOptions"</code> style=<code>"height:14px;padding-top:7px "</code>><h4 style=<code>"float:left; "</code>><label class=<code>"attribsInput "</code>>Quantity :<<code>/label></</code>h4><div style=<code>"float:left; "</code>><input type=<code>"text"</code> class=<code>"text"</code> id=<code>"quantity_wanted"</code> name=<code>"cart_quantity"</code> value=<code>"1"</code> maxlength=<code>"6"</code> size=<code>"4"</code> <code>/></</code>div><<code>/div> <br/>  <br class="clearBoth "> <br/>    <h1 style='margin-bottom: 10px;'>Step 3 - Add to cart:</</code>h1> <br/> <p id=<code>'add_to_cart'</code> class=<code>'buttons_bottom_block'</code>> <br/> <input type=<code>"hidden"</code> name=<code>"products_id"</code> value=<code>"456"</code> <code>/><input type="image" src="http:/fr.weddingdressescompany.com/</code>includes<code>/templates/</code>weddingdress-7<code>/buttons/</code>french<code>/button_in_cart.gif" alt="ajouter au panier" title=" ajouter au panier " /</code>> <<code>/p> <br/>   <br/></</code>div> <br/><div> <br/> <div class=<code>'safe_onlinechat'</code>> <br/> <div class=<code>'safe_ssl'</code>> <br/> <a target=<code>'_blank'</code> href=<code>'msnim:chat?contact=myonlineservice@msn.com'</code> style=<code>"float:left; "</code>><img src=<code>'http://fr.weddingdressescompany.com/banner/msn.jpg'</code>><<code>/a> <br/> <a target='_blank' href='callto:/meganfox59'><img border=0 align='absmiddle' src='http:/fr.weddingdressescompany.com/</code>banner<code>/skype.jpg' style="float:left; "></</code>a> <br/> <<code>/div> <br/> </</code>div> <br/> <br/><<code>/div> <br/> <br/></</code>div> <br/> <br/> <br/><br class=<code>"clearBoth"</code> <code>/> <br/><div id='descript_menu'> <br/><ul id='more_info_tabs' class='idTabs idTabsShort'> <br/> <li><a onclick='dissplay_descript(this);' style='cursor:pointer;'>Details</</code>span><<code>/a></</code>li> <br/> <li><a onclick=<code>'displaysize(this);'</code>style=<code>'cursor:pointer;'</code>>SIZE & COLOR CHART<<code>/a></</code>li> <br/> <li><a onclick=<code>'dissplay_return(this);'</code>style=<code>'cursor:pointer;'</code>>Shipping<<code>/a></</code>li> <br/> <li><a onclick=<code>'measure(this);'</code>style=<code>'cursor:pointer;'</code>>How to Measure<<code>/a></</code>li> <br/><<code>/ul> <br/><script> <br/> function displaysize(obj){ <br/> var measure = document.getElementById('idTabMeasure'); <br/> var idTabtwo = document.getElementById('idTabtwo'); <br/> var shipping_return = document.getElementById('tab_3'); <br/> var descript = document.getElementById('productDescription'); <br/> <br/> idTabtwo.setAttribute('class','block_hidden_only_for_screen'); <br/> descript.setAttribute('class','display'); <br/> shipping_return.setAttribute('class','display'); <br/> measure.setAttribute('class','display'); <br/> } <br/> function dissplay_descript(obj){ <br/> var measure = document.getElementById('idTabMeasure'); <br/> var descript = document.getElementById('productDescription'); <br/> var idTabtwo = document.getElementById('idTabtwo'); <br/> var shipping_return = document.getElementById('tab_3'); <br/> descript.setAttribute('class','block_hidden_only_for_screen'); <br/> idTabtwo.setAttribute('class','display'); <br/> shipping_return.setAttribute('class','display'); <br/> measure.setAttribute('class','display'); <br/> <br/> } <br/> function dissplay_return(obj){ <br/> var measure = document.getElementById('idTabMeasure'); <br/> var shipping_return = document.getElementById('tab_3'); <br/> var descript = document.getElementById('productDescription'); <br/> var idTabtwo = document.getElementById('idTabtwo'); <br/> shipping_return.setAttribute('class','block_hidden_only_for_screen'); <br/> idTabtwo.setAttribute('class','display'); <br/> descript.setAttribute('class','display'); <br/> measure.setAttribute('class','display'); <br/> <br/> } <br/> function measure(obj){ <br/> var measure = document.getElementById('idTabMeasure'); <br/> var shipping_return = document.getElementById('tab_3'); <br/> var descript = document.getElementById('productDescription'); <br/> var idTabtwo = document.getElementById('idTabtwo'); <br/> measure.setAttribute('class','block_hidden_only_for_screen'); <br/> idTabtwo.setAttribute('class','display'); <br/> descript.setAttribute('class','display'); <br/> shipping_return.setAttribute('class','display'); <br/> <br/> <br/> <br/> } <br/></</code>script> <br/><div id=<code>'more_info_sheets'</code> class=<code>'sheets align_justify'</code>> <br/> <br/><div id=<code>"productDescription"</code> class=<code>'displayblock'</code>>Nom de l<code>'article:</div> <br/> <br/><div id='</code>idTabtwo<code>' class='</code>display<code>'> <br/> <div class='</code>SizeKind<code>'> <br/> <div style='</code>background-attachment: scroll; background-image: none; background-position: 0pt 0pt; background-repeat: repeat; border-bottom: 1px solid rgb(238, 238, 238); margin-bottom: 10px; padding-bottom: 10px; padding-top: 10px; text-align: center;<code>'> <br/> <p style='</code>font-weight: bold; color: rgb(178, 30, 54); font-size: 14px;<code>'>Please choose your favorite color from the palette</p> <br/> <a id='</code>single_3<code>' href='</code>http:<code>//</code>fr.weddingdressescompany.com<code>/image/</code>img_ColorCard.jpg<code>'><img src='</code>http:<code>//</code>fr.weddingdressescompany.com<code>/image/</code>img_ColorCard.jpg<code>' alt='</code>wedding dress card palette<code>' width='</code>720<code>'></a> <br/> <p style='</code>text-align: left;<code>'><span style='</code>color: rgb(255, 0, 0);<code>'>Notice:</span>Since computer screens have chromatic aberration, especially between CRT screen and LCD screen, we can not guarantee the color of the dress you get will be 100% similar as the color chart. And also different fabrics will show different color degree on the same color. So we can not accept any returned dress for sake of color. Please kindly understand us.</p> <br/> </div> <br/> <div style='</code>background-attachment: scroll; background-image: none; background-position: 0pt 0pt; background-repeat: repeat; border-bottom: 1px solid rgb(238, 238, 238); margin-bottom: 20px; padding-bottom: 20px; padding-top: 10px; text-align: center;<code>'> <br/> <p style='</code>font-weight: bold; color: rgb(178, 30, 54); font-size: 14px;<code>'> Please choose your size</p> <br/> <table cellspacing="0" cellpadding="0 "> <br/>    <tbody> <br/>        <tr> <br/>            <th colspan="15 ">Standard size (in centimeter)</th> <br/>        </tr> <br/>        <tr> <br/> <br/>            <th>US size no</th> <br/>            <td>2</td> <br/>            <td>4</td> <br/>            <td>6</td> <br/>            <td>8</td> <br/>            <td>10</td> <br/> <br/>            <td>12</td> <br/>            <td>14</td> <br/>            <td>16</td> <br/>            <td>18</td> <br/>            <td>20</td> <br/>            <td>22</td> <br/> <br/>            <td>24</td> <br/>            <td>26</td> <br/>            <td>28</td> <br/>        </tr> <br/>        <tr> <br/>            <th>EUR size no</th> <br/>            <td>32</td> <br/> <br/>            <td>34</td> <br/>            <td>36</td> <br/>            <td>38</td> <br/>            <td>40</td> <br/>            <td>42</td> <br/>            <td>44</td> <br/> <br/>            <td>46</td> <br/>            <td>48</td> <br/>            <td>50</td> <br/>            <td>52</td> <br/>            <td>54</td> <br/>            <td>56</td> <br/> <br/>            <td>58</td> <br/>        </tr> <br/>        <tr> <br/>            <th>Bust</th> <br/>            <td>84</td> <br/>            <td>86</td> <br/>            <td>89</td> <br/> <br/>            <td>91</td> <br/>            <td>94</td> <br/>            <td>98</td> <br/>            <td>102</td> <br/>            <td>105</td> <br/>            <td>109</td> <br/> <br/>            <td>114</td> <br/>            <td>119</td> <br/>            <td>124</td> <br/>            <td>132</td> <br/>            <td>142</td> <br/>        </tr> <br/> <br/>        <tr> <br/>            <th>Waist</th> <br/>            <td>66</td> <br/>            <td>69</td> <br/>            <td>71</td> <br/>            <td>74</td> <br/> <br/>            <td>76</td> <br/>            <td>80</td> <br/>            <td>84</td> <br/>            <td>88</td> <br/>            <td>91</td> <br/>            <td>96</td> <br/> <br/>            <td>102</td> <br/>            <td>107</td> <br/>            <td>114</td> <br/>            <td>124</td> <br/>        </tr> <br/>        <tr> <br/>            <th>Hip</th> <br/> <br/>            <td>91</td> <br/>            <td>94</td> <br/>            <td>97</td> <br/>            <td>99</td> <br/>            <td>102</td> <br/>            <td>105</td> <br/> <br/>            <td>109</td> <br/>            <td>113</td> <br/>            <td>117</td> <br/>            <td>122</td> <br/>            <td>127</td> <br/>            <td>132</td> <br/> <br/>            <td>140</td> <br/>            <td>150</td> <br/>        </tr> <br/>        <tr> <br/>            <th>Shoulder to floor</th> <br/>            <td>150</td> <br/>            <td>150</td> <br/> <br/>            <td>151</td> <br/>            <td>152</td> <br/>            <td>152</td> <br/>            <td>153</td> <br/>            <td>154</td> <br/>            <td>154</td> <br/> <br/>            <td>155</td> <br/>            <td>156</td> <br/>            <td>156</td> <br/>            <td>156</td> <br/>            <td>156</td> <br/>            <td>156</td> <br/> <br/>        </tr> <br/>    </tbody> <br/></table> <br/><p> </p> <br/><table cellspacing="0" cellpadding="0 "> <br/>    <tbody> <br/>        <tr> <br/>            <th colspan="15 ">Standard size (in inches)</th> <br/>        </tr> <br/> <br/>        <tr> <br/>            <th>US size no</th> <br/>            <td>2</td> <br/>            <td>4</td> <br/>            <td>6</td> <br/>            <td>8</td> <br/> <br/>            <td>10</td> <br/>            <td>12</td> <br/>            <td>14</td> <br/>            <td>16</td> <br/>            <td>18</td> <br/>            <td>20</td> <br/> <br/>            <td>22</td> <br/>            <td>24</td> <br/>            <td>26</td> <br/>            <td>28</td> <br/>        </tr> <br/>        <tr> <br/>            <th>EUR size no</th> <br/> <br/>            <td>32</td> <br/>            <td>34</td> <br/>            <td>36</td> <br/>            <td>38</td> <br/>            <td>40</td> <br/>            <td>42</td> <br/> <br/>            <td>44</td> <br/>            <td>46</td> <br/>            <td>48</td> <br/>            <td>50</td> <br/>            <td>52</td> <br/>            <td>54</td> <br/> <br/>            <td>56</td> <br/>            <td>58</td> <br/>        </tr> <br/>        <tr> <br/>            <th>Bust</th> <br/>            <td>33</td> <br/>            <td>34</td> <br/> <br/>            <td>35</td> <br/>            <td>36</td> <br/>            <td>37</td> <br/>            <td>39</td> <br/>            <td>40</td> <br/>            <td>42</td> <br/> <br/>            <td>43</td> <br/>            <td>45</td> <br/>            <td>47</td> <br/>            <td>49</td> <br/>            <td>52</td> <br/>            <td>56</td> <br/> <br/>        </tr> <br/>        <tr> <br/>            <th>Waist</th> <br/>            <td>26</td> <br/>            <td>27</td> <br/>            <td>28</td> <br/>            <td>29</td> <br/> <br/>            <td>30</td> <br/>            <td>32</td> <br/>            <td>33</td> <br/>            <td>35</td> <br/>            <td>36</td> <br/>            <td>38</td> <br/> <br/>            <td>40</td> <br/>            <td>42</td> <br/>            <td>45</td> <br/>            <td>49</td> <br/>        </tr> <br/>        <tr> <br/>            <th>Hip</th> <br/> <br/>            <td>36</td> <br/>            <td>37</td> <br/>            <td>38</td> <br/>            <td>39</td> <br/>            <td>40</td> <br/>            <td>42</td> <br/> <br/>            <td>43</td> <br/>            <td>45</td> <br/>            <td>46</td> <br/>            <td>48</td> <br/>            <td>50</td> <br/>            <td>52</td> <br/> <br/>            <td>55</td> <br/>            <td>59</td> <br/>        </tr> <br/>        <tr> <br/>            <th>Shoulder to floor</th> <br/>            <td>59</td> <br/>            <td>59</td> <br/> <br/>            <td>60</td> <br/>            <td>60</td> <br/>            <td>60</td> <br/>            <td>60</td> <br/>            <td>61</td> <br/>            <td>61</td> <br/> <br/>            <td>61</td> <br/>            <td>61</td> <br/>            <td>62</td> <br/>            <td>62</td> <br/>            <td>62</td> <br/>            <td>62</td> <br/> <br/>        </tr> <br/>    </tbody> <br/></table> <br/> <br/> </div> <br/> <br class='</code>clear<code>'> <br/> </div> <br/></div> <br/> <br/> <br/>          <div id="tab_3" class='</code>display<code>'> <br/> <br/>          <h3>Shipping Time</h3> <br/><p>Total Time=Operation Time + Shipping Time</p> <br/><p>Default operation time is 30 business days from the day you place an order.  <br/>We will rush your order within 20 business days and 15 business days if you  <br/>choose rush service from  the operation time option,and you will pay extra  <br/>cost for it.Shipping time varies as: UPS , TNT 2-4 business days, Air Mail(Express) 10  <br/>business days, Air Mail(Normal) 20 business days. Please calculate the total  <br/>time carefully before you place the order.</p> <br/><p><i>Note: You can also choose Air Mail(Normal) if package weight is under 2kg.</i></p> <br/> <br/><h3>Return Tips</h3> <br/><p>If any returns, please contact our customer support within 24 hours from the time you receive your gown and fill in the Application for Refund in email. Only products in their original condition will be accepted. We do not accept returns on any custom made order. ALL SALES ARE FINAL for custom made dresses. For mis-shipped items, once confirmation got with us, we will be responsible for item exchange and have full refund returned including shipping fee and handling fee.  In principle, any emergency order isnot subject to this return policy and will be denied. Also other merchandise, such as veil ect.</p></div> <br/> <br/><div id="idTabMeasure" style="height:510px;" class='</code>display<code>'> <br/> <div class="tempnr_box "> <br/> <br/> <div class="images_zuo "> <a href="http://fr.weddingdressescompany.com/low-cost-custommade-bretelles-sexy-mariage-mariée-robe-de-mariée-robes-p-456.html" ><img width="163" height="479" src="http://fr.weddingdressescompany.com/image/wedding_size.jpg"/></a></div> <br/> <br/> <div class="nr_right "> <br/> <p style="color:#b21e36;font-size:14px;font-style:italic;font-weight:bold; padding-left:0; ">How to Measure</p> <br/> <ul><li><span class="wzys ">A.Bust:</span>Measure Around The Fullest Part Of Your Bust.</li> <br/> <br/> <li><span class="wzys ">B.Waist:</span>Measure Around The Smallest Part Of Your Waistline.</li> <br/> <li><span class="wzys ">C.Hips:</span>Measure Around The Widest Part Of Your Hips.</li> <br/> <li><span class="wzys ">D.Length:</span> Measure From Top Of The Shoulder Through The Nipple To Floor,Including The Height Of <b>Wedding Shoes</b>.</li> <br/> <li><span class="wzys ">E.Under Bust:</span>Measure Around Under Your Bust.</li> <br/> <br/> <li><span class="wzys ">F.Nipple To Nipple:</span> The Measurement Between Your Two Nipples.</li> <br/> <li><span class="wzys ">G.Shoulder To NiPPLE:</span>Measure From Top Of The Shoulder To Nipple.</li> <br/> <li><span class="wzys ">H.Shoulder TO Waist:</span>Measure From Top Of The Shoulder Through The Nipple TO Waist.</li> <br/> <li><span class="wzys ">I.Shoulder To Hips:</span>Measure From Top Of The Shoulder Through The Nipple TO Hips.</li> <br/> <br/> <li><span class="wzys ">J.Shoulder To Shoulder:</span>Measure Your Shoulder Width From The Back.</li> <br/> <li><span class="wzys ">k.Neck:</span>Measure Around The Fullest Part Of Your Neck.</li> <br/> <li><span class="wzys ">L.Biceps:</span>Measure Around The Widest Part Of Your Arm.</li> <br/> <li class="wzys" style="color:#DD0000;font-size:14px;font-weight:bold;padding:5px;text-align:right;border:1px solid #eee; ">Please Measure With Bra and Underwear On.</li> <br/> <li class="wzys" style="font-size:11px;font-weight:bold;text-align:right; ">Remember To Keep The Measuring Tape Comfortably Loose.</li></ul> <br/> <br/>            <br class="clear" /> <br/> <div><span style="color:#DD0000; margin-top:10px; ">Notice:</span>1. Please also tell us your "Height with Shoes" on (measured from top head to your wedding shoes'</code> heel).<br> <br/>2. Please remember that wear your Wedding Underwear and your Wedding Shoes.<br> <br/>3.Inches and Centimetersare both available for size, and please tell us if you use inches or centimeters.<br> <br/>4. We suggest you measure yourself by a Professional Tailor. <br> <br/>5. It is very normal to have 3CM measurement error between the sizes you give and the sizes you will receive on your dress. This kind of error can not be accepted for any returns and exchanges. <<code>/div> <br/> <br/> </</code>div> <br/> <br/> <span class=<code>"clear "</code>><<code>/span> <br/> </</code>div> <br/> <<code>/div> <br/> <br/></</code>div> <br/><<code>/div> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/>  <br class="clear" /</code>> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/><<code>/form> <br/> <br/></</code>div> <br/><<code>/td> <br/> <br/> <br/></</code>tr> <br/><<code>/table> <br/><br/> <br/> <br/><div id="navSuppWrapper "> <br/> <br/><div id="navSupp "> <br/><ul><li><a href="http:/fr.weddingdressescompany.com/</code>index.php <code>">Accueil</a></li> <br/><li><a href="</code>http:<code>//</code>fr.weddingdressescompany.com<code>/index.php?main_page=shippinginfo ">Frais de port</</code>a><<code>/li> <br/><li><a href="http:/fr.weddingdressescompany.com/</code>index.php?main_page=Wholesale <code>">Vente en gros</a></li> <br/><li><a href="</code>http:<code>//</code>fr.weddingdressescompany.com<code>/index.php?main_page=privacy ">Confidentialité</</code>a><<code>/li> <br/><li><a href="http:/fr.weddingdressescompany.com/</code>index.php?main_page=Tracking <code>">Suivi de commande</a></li> <br/><li><a href="</code>http:<code>//</code>fr.weddingdressescompany.com<code>/index.php?main_page=Coupons ">Coupons</</code>a><<code>/li> <br/><li><a href="http:/fr.weddingdressescompany.com/</code>index.php?main_page=conditions <code>">Conditions d'utilisation</a></li> <br/><li><a href="</code>http:<code>//</code>fr.weddingdressescompany.com<code>/index.php?main_page=FAQ ">FAQ</</code>a><<code>/li> <br/><li><a href="http:/fr.weddingdressescompany.com/</code>index.php?main_page=Western_Union <code>">Western Union</a></li> <br/><li><a href="</code>http:<code>//</code>fr.weddingdressescompany.com<code>/index.php?main_page=Payment_Methods ">Modes de paiement</</code>a><<code>/li> <br/><li><a href="http:/fr.weddingdressescompany.com/</code>index.php?main_page=contact_us <code>">Contactez-nous</a></li> <br/> <br/> <br/></ul> <br/> <br/></div> <br/><DIV  align="</code>center <code>"> <a href="</code>http:<code>//</code>fr.weddingdressescompany.com<code>/low-cost-custommade-bretelles-sexy-mariage-mariée-robe-de-mariée-robes-p-456.html" ><IMG src="http:/fr.weddingdressescompany.com/</code>includes<code>/templates/</code>weddingdress-7<code>/images/</code>payment.png<code>" width="</code>746<code>" height="</code>58 <code>"></a></DIV> <br/><div align="</code>center <code>">Copyright Â© 2012 Tous droits réservés .</div> <br/> <br/> <br/></div> <br/></div> <br/><br/> <br/><br/> <br/><br/> <br/><br/> <br/> <br/><br><br><a href="</code>http:<code>//</code>blog.ishirtsale.com<code>">  sexy  blog </a><br><br><a href="</code>http:<code>//</code>blog.surprisewatches.com<code>"> mariée  </a><br><br><a href="</code>http:<code>//</code>blog.bootsclubs.com"> About weddingdressescompany.com blog </a> </div> </div> </div> </div> <div class="category"> <div class="box"> <b class="rtop"> <b class="r1"></b> <b class="r2"></b> <b class="r3"></b> <b class="r4"></b> </b> <div class="content"> <a href="/clojure+cpp+fsharp+groovy+java+ocaml+python+scala/nike-air-max">nike air max</a> </div> <b class="rbottom"> <b class="r4"></b> <b class="r3"></b> <b class="r2"></b> <b class="r1"></b> </b> </div> </div> <div id="category25"> <div class="subcategory"> <div class="box"> <b class="rtop"> <b class="r1"></b> <b class="r2"></b> <b class="r3"></b> <b class="r4"></b> </b> <div class="content"> <a href="/clojure+cpp+fsharp+groovy+java+ocaml+python+scala/nike-air-max/180">180</a> </div> <b class="rbottom"> <b class="r4"></b> <b class="r3"></b> <b class="r2"></b> <b class="r1"></b> </b> </div> </div> <div style="clear:both"/> <div id="subcategory51"> <div class="problem"> <h3><a href="/clojure+cpp+fsharp+groovy+java+ocaml+python+scala/nike-air-max/180/180">180</a></h3> <div class="solutions" id="problem368"> <strong><a href=<code>"http://www.kissdrdrebeats.com/ "</code>>beats by dre headphones<<code>/a></</code>strong><br><br/><strong><a href=<code>"http://www.beatsdrdrecompany.com/ "</code>>by dre tour<<code>/a></</code>strong><br><br/><strong><a href=<code>"http://www.loginmonsterbeats.com/ "</code>>beats by dre tour<<code>/a></</code>strong><br><br/><strong><a href=<code>"http://www.bigbeatsbydre.com/ "</code>>beats by dre solo<<code>/a></</code>strong><br><br/><strong><a href=<code>"http://www.beatsdrdrecompany.com/ "</code>>monster beats by dre<<code>/a></</code>strong><br><br/><br><br/> <br/><title> 2011 Monster Beats Studio Transformers,Transformers Beats Sale,Dr Dre Transformers Online,Dr Dre Beats Outlet<<code>/title> <br/><meta http-equiv="Content-Type" content="text/</code>html; charset=UTF-8<code>" /> <br/><meta name="</code>keywords<code>" content="</code>2011 Monster Beats Studio Transformers,Transformers Beats Sale,Dr Dre Transformers Online,Dr Dre Beats Outlet <code>" /> <br/><meta name="</code>description<code>" content="</code>2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones.Buy Monster Beats Studio Transformers Online at discounted beets prices <code>" /> <br/><meta http-equiv="</code>imagetoolbar<code>" content="</code>no<code>" /> <br/><meta name="</code>author<code>" content="</code>Zen Cart China<code>" /> <br/><meta name="</code>generator<code>" content="</code>Zen Cart, http:<code>//</code>www.zen-cart.cn<code>" /> <br/> <br/> <br/><link rel="</code>canonical<code>" href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/2011-monster-beats-by-dr-dre-transformers-limited-edition-headphones-p-42.html" /</code>> <br/> <br/><link rel=<code>"stylesheet"</code> type=<code>"text/css"</code> href=<code>"http://www.kissdrdrebeats.com/includes/templates/monsterbeats/css/style_imagehover.css"</code> <code>/><br/><link rel="stylesheet" type="text/</code>css<code>" href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/includes/</code>templates<code>/monsterbeats/</code>css<code>/styles_AJAX_image_swapper.css" /</code>><br/><link rel=<code>"stylesheet"</code> type=<code>"text/css"</code> href=<code>"http://www.kissdrdrebeats.com/includes/templates/monsterbeats/css/stylesheet.css"</code> <code>/><br/><link rel="stylesheet" type="text/</code>css<code>" href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/includes/</code>templates<code>/monsterbeats/</code>css<code>/stylesheet_css_buttons.css" /</code>><br/><link rel=<code>"stylesheet"</code> type=<code>"text/css"</code> media=<code>"print"</code> href=<code>"http://www.kissdrdrebeats.com/includes/templates/monsterbeats/css/print_stylesheet.css"</code> <code>/><br/><br/><br/><br/> <br/><link type="text/</code>css<code>" href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/includes/</code>templates<code>/monsterbeats/</code>css<code>/magiczoomplus.css" rel="stylesheet" media="screen" /</code>> <br/> <br/><br/><br/> <br/> <br/> <br/> <br/><div id=<code>"mainWrapper "</code>> <br/> <br/> <br/> <br/> <br/> <br/><div id=<code>"headerWrapper "</code>> <br/> <br/> <br/> <br/><div id=<code>"logoWrapper "</code>> <br/> <div id=<code>"logo "</code>><a href=<code>"http://www.kissdrdrebeats.com/ "</code>><img src=<code>"http://www.kissdrdrebeats.com/includes/templates/monsterbeats/images/logo.gif"</code> alt=<code>"Powered by Zen Cart :: The Art of E-Commerce"</code> title=<code>" Powered by Zen Cart :: The Art of E-Commerce "</code> width=<code>"320"</code> height=<code>"72"</code> <code>/></</code>a><<code>/div> <br/> <br/><div class="list" style="float:right; "> <br/> <br/><div class="languages-wrapper "> <br/> <br/> <form name="currencies_form" action="http:/www.kissdrdrebeats.com/</code><code>" method="</code>get <code>"><select name="</code>currency<code>" onchange="</code>this.form.submit(); <code>"><br/>  <option value="</code>USD<code>" selected="</code>selected <code>">US Dollar</option><br/>  <option value="</code>CNY <code>">CNY</option><br/>  <option value="</code>EUR <code>">Euro</option><br/>  <option value="</code>GBP <code>">GB Pound</option><br/>  <option value="</code>CAD <code>">Canadian Dollar</option><br/>  <option value="</code>AUD <code>">Australian Dollar</option><br/></select><br/><input type="</code>hidden<code>" name="</code>main_page<code>" value="</code>product_info<code>" /><input type="</code>hidden<code>" name="</code>products_id<code>" value="</code>42<code>" /></form> <label class="</code>float-right<code>" style="</code>font-size:14px;font-weight:bold; <code>">  Currency:</label> <br/> <br/> <br/> <ul class="</code>list-style-none<code>" style="</code>float:left;<code>" id="</code>headlogin <code>"> <br/>    <a href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/index.php?main_page=login ">Log In</</code>a> <br/> or <a href=<code>"http://www.kissdrdrebeats.com/index.php?main_page=create_account "</code>>Register<<code>/a> <br/></</code>div> <br/> <br/><div style=<code>"float:right; margin-top:8px;"</code> > <br/> <form name=<code>"quick_find_header"</code> action=<code>"http://www.kissdrdrebeats.com/index.php?main_page=advanced_search_result"</code> method=<code>"get "</code>><input type=<code>"hidden"</code> name=<code>"main_page"</code> value=<code>"advanced_search_result"</code> <code>/><input type="hidden" name="search_in_description" value="1" /</code>><div class=<code>"search-header-input "</code>><input type=<code>"text"</code> name=<code>"keyword"</code> size=<code>"6"</code> maxlength=<code>"30"</code> style=<code>"width: 138px"</code> value=<code>"Search for..."</code> onfocus=<code>"if (this.value == 'Search for...') this.value = '';"</code> onblur=<code>"if (this.value == '') this.value = 'Search for...';"</code> <code>/></</code>div><input class=<code>"button-search-header"</code> type=<code>"image"</code> src=<code>"http://www.kissdrdrebeats.com/includes/templates/monsterbeats/images/search_header_button.gif"</code> value=<code>"Serch"</code> <code>/></</code>form><<code>/div> <br/><div style="float:right; margin-top:8px;  "> <br/>                 <div id="cartBoxEmpty "><a href="http:/www.kissdrdrebeats.com/</code>index.php?main_page=shopping_cart <code>"><img class="</code>cart-icon empty float-left<code>" src="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/includes/</code>templates<code>/monsterbeats/</code>images<code>/spacer.gif" /</code>><<code>/a>Your cart is empty</</code>div> <br/> <br/><<code>/div> <br/></</code>div> <br/><div class=<code>"clearBoth"</code> <code>/></</code>div> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/><div id=<code>"menu "</code>> <br/> <br/><div id=<code>"navEZPagesTop "</code>> <br/><ul> <br/> <li><a href=<code>"http://www.kissdrdrebeats.com/index.php "</code>>Home<<code>/a></</code>li> <br/> <li><a href=<code>"http://www.kissdrdrebeats.com/ "</code>>All Products<<code>/a></</code>li> <br/> <li><a href=<code>"http://www.kissdrdrebeats.com/index.php?main_page=shippinginfo "</code>>Shipping & Returns<<code>/a></</code>li> <br/> <li><a href=<code>"http://www.kissdrdrebeats.com/index.php?main_page=Coupons "</code>>Coupons<<code>/a></</code>li> <br/> <li><a href=<code>"http://www.kissdrdrebeats.com/index.php?main_page=Wholesale "</code>>Wholesale<<code>/a></</code>li> <br/> <li><a href=<code>"http://www.kissdrdrebeats.com/index.php?main_page=FAQ "</code>>FAQ<<code>/a></</code>li> <br/> <li><a href=<code>"http://www.kissdrdrebeats.com/index.php?main_page=contact_us "</code>>Contact Us<<code>/a></</code>li> <br/> <br/><<code>/ul> <br/></</code>div> <br/> <br/><<code>/div> <br/> <br/></</code>div> <br/> <br/><table width=<code>"100%"</code> border=<code>"0"</code> cellspacing=<code>"0"</code> cellpadding=<code>"0"</code> id=<code>"contentMainWrapper "</code>> <br/> <tr> <br/> <br/> <td id=<code>"navColumnOne"</code> class=<code>"columnLeft"</code> style=<code>"width: 190px "</code>> <br/><div id=<code>"navColumnOneWrapper"</code> style=<code>"width: 190px "</code>> <br/><div class=<code>"leftBoxContainer"</code> id=<code>"categories"</code> style=<code>"width: 190px "</code>> <br/><div class=<code>"sidebox-header-left main-sidebox-header-left "</code>><h3 class=<code>"leftBoxHeading main-sidebox-header-right"</code> id=<code>"categoriesHeading "</code>>Categories<<code>/h3></</code>div> <br/><div id=<code>"categoriesContent"</code> class=<code>"sideBoxContent "</code>><br/><div class=<code>"categories-top-list no-dots "</code>><a class=<code>"category-top"</code> href=<code>"http://www.kissdrdrebeats.com/2011-new-dr-dre-studio-for-christmas-gifts-c-4.html "</code>>2011 New Dr Dre Studio For Christmas Gifts<<code>/a></</code>div><br/><div class=<code>"categories-top-list  "</code>><a class=<code>"category-top"</code> href=<code>"http://www.kissdrdrebeats.com/2011-dr-dre-studio-teams-logo-headphones-c-6.html "</code>>2011 Dr Dre Studio Teams Logo Headphones<<code>/a></</code>div><br/><div class=<code>"categories-top-list  "</code>><a class=<code>"category-top"</code> href=<code>"http://www.kissdrdrebeats.com/2011-monster-beats-studio-nate-robinson-c-9.html "</code>>2011 Monster Beats Studio Nate Robinson<<code>/a></</code>div><br/><div class=<code>"categories-top-list  "</code>><a class=<code>"category-top"</code> href=<code>"http://www.kissdrdrebeats.com/2011-monster-beats-studio-transformers-c-8.html "</code>><span class=<code>"category-subs-selected "</code>>2011 Monster Beats Studio Transformers<<code>/span></</code>a><<code>/div><br/><div class="categories-top-list  "><a class="category-top" href="http:/www.kissdrdrebeats.com/</code>monster-beats-butterfly-c-13.html <code>">Monster Beats Butterfly</a></div><br/><div class="</code>categories-top-list <code>"><a class="</code>category-top<code>" href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/monster-beats-by-dr-dre-power-c-25.html ">Monster Beats By Dr Dre Power</</code>a><<code>/div><br/><div class="categories-top-list  "><a class="category-top" href="http:/www.kissdrdrebeats.com/</code>monster-beats-by-dr-dre-tour-c-16.html <code>">Monster Beats By Dr Dre Tour</a></div><br/><div class="</code>categories-top-list <code>"><a class="</code>category-top<code>" href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/monster-beats-dr-dre-diddy-c-10.html ">Monster Beats Dr Dre Diddy</</code>a><<code>/div><br/><div class="categories-top-list  "><a class="category-top" href="http:/www.kissdrdrebeats.com/</code>monster-beats-dr-dre-pro-c-5.html <code>">Monster Beats Dr Dre Pro</a></div><br/><div class="</code>categories-top-list <code>"><a class="</code>category-top<code>" href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/monster-beats-dr-dre-solo-c-12.html ">Monster Beats Dr Dre Solo</</code>a><<code>/div><br/><div class="categories-top-list  "><a class="category-top" href="http:/www.kissdrdrebeats.com/</code>monster-beats-dr-dre-solo-hd-c-19.html <code>">Monster Beats Dr Dre Solo HD</a></div><br/><div class="</code>categories-top-list <code>"><a class="</code>category-top<code>" href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/monster-beats-dr-dre-wireless-bluetooth-c-24.html ">Monster Beats Dr Dre Wireless Bluetooth</</code>a><<code>/div><br/><div class="categories-top-list  "><a class="category-top" href="http:/www.kissdrdrebeats.com/</code>monster-beats-miles-davis-tribute-c-20.html <code>">Monster Beats Miles Davis Tribute</a></div><br/><div class="</code>categories-top-list <code>"><a class="</code>category-top<code>" href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/monster-beats-studio-c-3.html ">Monster Beats Studio</</code>a><<code>/div><br/><div class="categories-top-list  "><a class="category-top" href="http:/www.kissdrdrebeats.com/</code>monster-beats-studio-diamond-c-14.html <code>">Monster Beats Studio Diamond</a></div><br/><div class="</code>categories-top-list <code>"><a class="</code>category-top<code>" href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/monster-beats-studio-dr-dre-ferrari-c-7.html ">Monster Beats Studio Dr Dre Ferrari</</code>a><<code>/div><br/><div class="categories-top-list  "><a class="category-top" href="http:/www.kissdrdrebeats.com/</code>monster-beats-studio-dr-dre-graffiti-c-17.html <code>">Monster Beats Studio Dr Dre Graffiti</a></div><br/><div class="</code>categories-top-list <code>"><a class="</code>category-top<code>" href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/monster-beats-studio-justin-bieber-c-1.html ">Monster Beats Studio Justin Bieber</</code>a><<code>/div><br/><div class="categories-top-list  "><a class="category-top" href="http:/www.kissdrdrebeats.com/</code>monster-beats-studio-kobe-bryant-c-2.html <code>">Monster Beats Studio Kobe Bryant</a></div><br/><div class="</code>categories-top-list <code>"><a class="</code>category-top<code>" href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/monster-beats-studio-lamborghini-c-21.html ">Monster Beats Studio Lamborghini</</code>a><<code>/div><br/><div class="categories-top-list  "><a class="category-top" href="http:/www.kissdrdrebeats.com/</code>monster-beats-studio-lebron-james-c-22.html <code>">Monster Beats Studio Lebron James</a></div><br/><div class="</code>categories-top-list <code>"><a class="</code>category-top<code>" href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/monster-beats-studio-michael-jackson-c-18.html ">Monster Beats Studio Michael Jackson</</code>a><<code>/div><br/><div class="categories-top-list  "><a class="category-top" href="http:/www.kissdrdrebeats.com/</code>monster-beats-studio-red-sox-c-15.html <code>">Monster Beats Studio Red Sox</a></div><br/><div class="</code>categories-top-list <code>"><a class="</code>category-top<code>" href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/monster-beats-turbine-c-23.html ">Monster Beats Turbine</</code>a><<code>/div><br/><div class="categories-top-list  "><a class="category-top" href="http:/www.kissdrdrebeats.com/</code>monster-lady-gaga-heartbeats-c-11.html <code>">Monster Lady Gaga Heartbeats</a></div><br/><div class="</code>categories-top-list <code>"><a class="</code>category-top<code>" href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/monster-vmoda-crossfade-lp-c-26.html ">Monster V-MODA Crossfade LP</</code>a><<code>/div><br/></</code>div><<code>/div> <br/> <br/></</code>div><<code>/td> <br/>    <td id="columnCenter" valign="top "> <br/> <br/>    <div id="navBreadCrumb ">  <a href="http:/www.kissdrdrebeats.com/</code> <code>">Home</a> :: <br/>  <a href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/2011-monster-beats-studio-transformers-c-8.html ">2011 Monster Beats Studio Transformers</</code>a> :: <br/>2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones<br/><<code>/div> <br/> <br/> <br/> <br/> <br/> <br/><div class="centerColumn" id="productGeneral "> <br/> <br/> <br/><h1 id="productName" class="productGeneral ">2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones</</code>h1> <br/> <br/> <br/> <br/><form name=<code>"cart_quantity"</code> action=<code>"http://www.kissdrdrebeats.com/2011-monster-beats-by-dr-dre-transformers-limited-edition-headphones-p-42.html?action=add_product"</code> method=<code>"post"</code> enctype=<code>"multipart/form-data "</code>><br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/><div id=<code>"productMainImage"</code> class=<code>"centeredContent back "</code>> <br/> <br/><noscript> <br/><a href=<code>"http://www.kissdrdrebeats.com/index.php?main_page=popup_image&pID=42"</code> target=<code>"_blank "</code>> <a href=<code>"http://www.kissdrdrebeats.com/2011-monster-beats-studio-transformers-c-8.html"</code> ><img src=<code>"http://www.kissdrdrebeats.com/images/monsterbeats/MonsterBeatsByDr.DreTransformersLimitedEditionHeadphones.jpg"</code> alt=<code>"2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones"</code> title=<code>" 2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones "</code> width=<code>"300"</code> height=<code>"225"</code> <code>/></</code>a><br <code>/><span class="imgLink ">larger image</</code>span><<code>/a></</code>noscript> <br/><<code>/div> <br/> <br/> <br/><span id="productPrices" class="productGeneral "> <br/><span class="normalprice ">$479.00 </</code>span> <span class=<code>"productSpecialPrice "</code>>$209.90<<code>/span><span class="productPriceDiscount "><br /</code>>Save: 56% off<<code>/span></</code>span> <br/> <br/> <br/> <br/><ul id=<code>"productDetailsList"</code> class=<code>"floatingBox back "</code>> <br/> <li>Model: monster083<<code>/li><br/>  <br/>  <br/>  <br/></</code>ul> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <div id=<code>"cartAdd "</code>> <br/> Add to Cart: <input type=<code>"text"</code> name=<code>"cart_quantity"</code> value=<code>"1"</code> maxlength=<code>"6"</code> size=<code>"4"</code> <code>/><br /</code>><br <code>/><input type="hidden" name="products_id" value="42" /</code>><input type=<code>"image"</code> src=<code>"http://www.kissdrdrebeats.com/includes/templates/monsterbeats/buttons/english/button_in_cart.gif"</code> alt=<code>"Add to Cart"</code> title=<code>" Add to Cart "</code> <code>/>          </</code>div> <br/> <br/> <br/><br class=<code>"clearBoth"</code> <code>/> <br/> <br/> <br/> <br/> <br/> <div id="productAdditionalImages "> <br/>  <div id="dfse "></</code>div> <br/> <div class=<code>"centerBoxContent "</code>> <br/> <br/> <br/> <div class=<code>"additionalImages centeredContent back"</code> style=<code>"width:33%; "</code>><br/> <br/> <noscript><a href=<code>"http://www.kissdrdrebeats.com/2011-monster-beats-studio-transformers-c-8.html"</code> target=<code>"_blank "</code>> <a href=<code>"http://www.kissdrdrebeats.com/2011-monster-beats-studio-transformers-c-8.html"</code> ><img src=<code>"http://www.kissdrdrebeats.com/images/monsterbeats/MonsterBeatsByDr.DreTransformersLimitedEditionHeadphones_001.jpg"</code> alt=<code>"2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones"</code> title=<code>" 2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones "</code> width=<code>"100"</code> height=<code>"75"</code> style=<code>"position:relative"</code> onmouseover=<code>"showtrail('images/monsterbeats//MonsterBeatsByDr.DreTransformersLimitedEditionHeadphones_001.jpg','2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones',100,75,600,450,this,0,0,100,75);"</code> onmouseout=<code>"hidetrail();"</code> <code>/></</code>a><br <code>/><span class="imgLinkAdditional ">larger image</</code>span><<code>/a></</code>noscript><<code>/div><br/>    <div class="additionalImages centeredContent back" style="width:33%; "><br/>      <br/>      <noscript><a href="http:/www.kissdrdrebeats.com/</code>2011-monster-beats-studio-transformers-c-8.html<code>" target="</code>_blank <code>"> <a href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/2011-monster-beats-studio-transformers-c-8.html" ><img src="http:/www.kissdrdrebeats.com/</code>images<code>/monsterbeats/</code>MonsterBeatsByDr.DreTransformersLimitedEditionHeadphones_002.jpg<code>" alt="</code>2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones<code>" title="</code> 2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones <code>" width="</code>100<code>" height="</code>75<code>" style="</code>position:relative<code>" onmouseover="</code>showtrail(<code>'images/monsterbeats//MonsterBeatsByDr.DreTransformersLimitedEditionHeadphones_002.jpg'</code>,<code>'2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones'</code>,100,75,600,450,this,0,0,100,75);<code>" onmouseout="</code>hidetrail();<code>"  /></a><br /><span class="</code>imgLinkAdditional <code>">larger image</span></a></noscript></div><br/>    <div class="</code>additionalImages centeredContent back<code>" style="</code>width:33%; <code>"><br/>      <br/>      <noscript><a href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/2011-monster-beats-studio-transformers-c-8.html" target="_blank "> <a href="http:/www.kissdrdrebeats.com/</code>2011-monster-beats-studio-transformers-c-8.html<code>" ><img src="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/images/</code>monsterbeats<code>/MonsterBeatsByDr.DreTransformersLimitedEditionHeadphones_003.jpg" alt="2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones" title=" 2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones " width="100" height="75" style="position:relative" onmouseover="showtrail('images/</code>monsterbeats<code>//</code>MonsterBeatsByDr.DreTransformersLimitedEditionHeadphones_003.jpg<code>','</code>2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones<code>',100,75,600,450,this,0,0,100,75);" onmouseout="hidetrail();"  /></a><br /><span class="imgLinkAdditional ">larger image</span></a></noscript></div><br/><br class="clearBoth" /> <br/> <br/>    <div class="additionalImages centeredContent back" style="width:33%; "><br/>      <br/>      <noscript><a href="http://www.kissdrdrebeats.com/2011-monster-beats-studio-transformers-c-8.html" target="_blank "> <a href="http://www.kissdrdrebeats.com/2011-monster-beats-studio-transformers-c-8.html" ><img src="http://www.kissdrdrebeats.com/images/monsterbeats/MonsterBeatsByDr.DreTransformersLimitedEditionHeadphones_004.jpg" alt="2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones" title=" 2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones " width="100" height="75" style="position:relative" onmouseover="showtrail('</code>images<code>/monsterbeats/MonsterBeatsByDr.DreTransformersLimitedEditionHeadphones_004.jpg','2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones',100,75,600,450,this,0,0,100,75);" onmouseout="hidetrail();"  /</code>><<code>/a><br /</code>><span class=<code>"imgLinkAdditional "</code>>larger image<<code>/span></</code>a><<code>/noscript></</code>div><br/> <div class=<code>"additionalImages centeredContent back"</code> style=<code>"width:33%; "</code>><br/> <br/> <noscript><a href=<code>"http://www.kissdrdrebeats.com/2011-monster-beats-studio-transformers-c-8.html"</code> target=<code>"_blank "</code>> <a href=<code>"http://www.kissdrdrebeats.com/2011-monster-beats-studio-transformers-c-8.html"</code> ><img src=<code>"http://www.kissdrdrebeats.com/images/monsterbeats/MonsterBeatsByDr.DreTransformersLimitedEditionHeadphones_005.jpg"</code> alt=<code>"2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones"</code> title=<code>" 2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones "</code> width=<code>"100"</code> height=<code>"75"</code> style=<code>"position:relative"</code> onmouseover=<code>"showtrail('images/monsterbeats//MonsterBeatsByDr.DreTransformersLimitedEditionHeadphones_005.jpg','2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones',100,75,600,450,this,0,0,100,75);"</code> onmouseout=<code>"hidetrail();"</code> <code>/></</code>a><br <code>/><span class="imgLinkAdditional ">larger image</</code>span><<code>/a></</code>noscript><<code>/div><br/>    <div class="additionalImages centeredContent back" style="width:33%; "><br/>      <br/>      <noscript><a href="http:/www.kissdrdrebeats.com/</code>2011-monster-beats-studio-transformers-c-8.html<code>" target="</code>_blank <code>"> <a href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/2011-monster-beats-studio-transformers-c-8.html" ><img src="http:/www.kissdrdrebeats.com/</code>images<code>/monsterbeats/</code>MonsterBeatsByDr.DreTransformersLimitedEditionHeadphones_006.jpg<code>" alt="</code>2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones<code>" title="</code> 2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones <code>" width="</code>100<code>" height="</code>75<code>" style="</code>position:relative<code>" onmouseover="</code>showtrail(<code>'images/monsterbeats//MonsterBeatsByDr.DreTransformersLimitedEditionHeadphones_006.jpg'</code>,<code>'2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones'</code>,100,75,600,450,this,0,0,100,75);<code>" onmouseout="</code>hidetrail();<code>"  /></a><br /><span class="</code>imgLinkAdditional <code>">larger image</span></a></noscript></div><br/><br class="</code>clearBoth<code>" /> <br/> <br/>    <div class="</code>additionalImages centeredContent back<code>" style="</code>width:33%; <code>"><br/>      <br/>      <noscript><a href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/2011-monster-beats-studio-transformers-c-8.html" target="_blank "> <a href="http:/www.kissdrdrebeats.com/</code>2011-monster-beats-studio-transformers-c-8.html<code>" ><img src="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/images/</code>monsterbeats<code>/MonsterBeatsByDr.DreTransformersLimitedEditionHeadphones_007.jpg" alt="2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones" title=" 2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones " width="100" height="75" style="position:relative" onmouseover="showtrail('images/</code>monsterbeats<code>//</code>MonsterBeatsByDr.DreTransformersLimitedEditionHeadphones_007.jpg<code>','</code>2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones<code>',100,75,600,450,this,0,0,100,75);" onmouseout="hidetrail();"  /></a><br /><span class="imgLinkAdditional ">larger image</span></a></noscript></div><br/>    <div class="additionalImages centeredContent back" style="width:33%; "><br/>      <br/>      <noscript><a href="http://www.kissdrdrebeats.com/2011-monster-beats-studio-transformers-c-8.html" target="_blank "> <a href="http://www.kissdrdrebeats.com/2011-monster-beats-studio-transformers-c-8.html" ><img src="http://www.kissdrdrebeats.com/images/monsterbeats/MonsterBeatsByDr.DreTransformersLimitedEditionHeadphones_008.jpg" alt="2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones" title=" 2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones " width="100" height="75" style="position:relative" onmouseover="showtrail('</code>images<code>/monsterbeats/MonsterBeatsByDr.DreTransformersLimitedEditionHeadphones_008.jpg','2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones',100,75,600,450,this,0,0,100,75);" onmouseout="hidetrail();"  /</code>><<code>/a><br /</code>><span class=<code>"imgLinkAdditional "</code>>larger image<<code>/span></</code>a><<code>/noscript></</code>div><br/> <div class=<code>"additionalImages centeredContent back"</code> style=<code>"width:33%; "</code>><br/> <br/> <noscript><a href=<code>"http://www.kissdrdrebeats.com/2011-monster-beats-studio-transformers-c-8.html"</code> target=<code>"_blank "</code>> <a href=<code>"http://www.kissdrdrebeats.com/2011-monster-beats-studio-transformers-c-8.html"</code> ><img src=<code>"http://www.kissdrdrebeats.com/images/monsterbeats/MonsterBeatsByDr.DreTransformersLimitedEditionHeadphones_009.jpg"</code> alt=<code>"2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones"</code> title=<code>" 2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones "</code> width=<code>"100"</code> height=<code>"75"</code> style=<code>"position:relative"</code> onmouseover=<code>"showtrail('images/monsterbeats//MonsterBeatsByDr.DreTransformersLimitedEditionHeadphones_009.jpg','2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones',100,75,600,450,this,0,0,100,75);"</code> onmouseout=<code>"hidetrail();"</code> <code>/></</code>a><br <code>/><span class="imgLinkAdditional ">larger image</</code>span><<code>/a></</code>noscript><<code>/div><br/><br class="clearBoth" /</code>> <br/> <br/> <div class=<code>"additionalImages centeredContent back"</code> style=<code>"width:33%; "</code>><br/> <br/> <noscript><a href=<code>"http://www.kissdrdrebeats.com/2011-monster-beats-studio-transformers-c-8.html"</code> target=<code>"_blank "</code>> <a href=<code>"http://www.kissdrdrebeats.com/2011-monster-beats-studio-transformers-c-8.html"</code> ><img src=<code>"http://www.kissdrdrebeats.com/images/monsterbeats/MonsterBeatsByDr.DreTransformersLimitedEditionHeadphones_010.jpg"</code> alt=<code>"2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones"</code> title=<code>" 2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones "</code> width=<code>"100"</code> height=<code>"75"</code> style=<code>"position:relative"</code> onmouseover=<code>"showtrail('images/monsterbeats//MonsterBeatsByDr.DreTransformersLimitedEditionHeadphones_010.jpg','2011 Monster Beats By Dr. Dre Transformers Limited Edition Headphones',100,75,600,450,this,0,0,100,75);"</code> onmouseout=<code>"hidetrail();"</code> <code>/></</code>a><br <code>/><span class="imgLinkAdditional ">larger image</</code>span><<code>/a></</code>noscript><<code>/div><br/><br class="clearBoth" /</code>> <br/> <br/><<code>/div></</code>div> <br/> <br/> <br/> <br/><div id=<code>"productDescription"</code> class=<code>"productGeneral biggerText "</code>><p>Advanced driver design for precise audio <br> Extra large speaker drivers for super deep bass<br> High powered digital amplifier plays hip hop, rock, R+B and more loud, without distortion<br> Monster headphone cable with Quadripole twisted pair construction for balanced sound and clarity<<code>/p><p><strong>What's In The Box</</code>strong><<code>/p><p>Beats Studio headphones<br>  Monster Cable headphone cable<br>  Rigid Tour case<br>  Anti-Microbial Cleaning cloth<br>  1/</code>8 to 1<code>/4" Adapter<br>  Monster iSoniTalk iPhone enabled headphone </</code>p><<code>/div> <br/> <br/> <br/><br class="clearBoth" /</code>> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/><<code>/form> <br/> <br/></</code>div> <br/><<code>/td> <br/> <br/> <br/>  </</code>tr> <br/><<code>/table> <br/> <br/> <br/><div id="navSuppWrapper "> <br/> <br/><div id="navSupp "> <br/><ul><li><a href="http:/www.kissdrdrebeats.com/</code>index.php <code>">Home</a></li> <br/><li>   <a href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/index.php?main_page=shippinginfo ">Shipping</</code>a><<code>/li> <br/><li>   <a href="http:/www.kissdrdrebeats.com/</code>index.php?main_page=Wholesale <code>">Wholesale</a></li> <br/><li>   <a href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/index.php?main_page=privacy ">Privacy</</code>a><<code>/li> <br/><li>   <a href="http:/www.kissdrdrebeats.com/</code>index.php?main_page=Tracking <code>">Order Tracking</a></li> <br/><li>   <a href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/index.php?main_page=Coupons ">Coupons</</code>a><<code>/li> <br/><li>   <a href="http:/www.kissdrdrebeats.com/</code>index.php?main_page=conditions <code>">Conditions of Use</a></li> <br/><li>   <a href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/index.php?main_page=FAQ ">FAQ</</code>a><<code>/li> <br/><li>   <a href="http:/www.kissdrdrebeats.com/</code>index.php?main_page=Payment_Methods <code>">Payment Methods</a></li> <br/><li>   <a href="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/index.php?main_page=contact_us ">Contact Us</</code>a><<code>/li> <br/> <br/> <br/></</code>ul> <br/> <br/><<code>/div> <br/><DIV  align="center "> <a href="http:/www.kissdrdrebeats.com/</code>2011-monster-beats-studio-transformers-c-8.html<code>" ><IMG src="</code>http:<code>//</code>www.kissdrdrebeats.com<code>/includes/</code>templates<code>/monsterbeats/</code>images<code>/paymentcart.jpg" width="473" height="37 "></</code>a> <<code>/DIV> <br/><div align="center ">Copyright Â© 2012 All Rights Reserved. </</code>div> <br/> <br/> <br/><<code>/div> <br/></</code>div> <br/> <br/> <br/> <br/> <br/><strong><a href=<code>"http://www.kissdrdrebeats.com/2011-new-dr-dre-studio-for-christmas-gifts-c-4.html "</code>>2011 New Dr Dre Studio For Christmas Gifts<<code>/a></</code>strong><br><br/><strong><a href=<code>"http://www.kissdrdrebeats.com/2011-new-dr-dre-studio-for-christmas-gifts-c-4.html "</code>>Cheap Dr Dre Studio<<code>/a></</code>strong><br><br/><strong><a href=<code>"http://www.kissdrdrebeats.com/2011-new-dr-dre-studio-for-christmas-gifts-c-4.html "</code>>Monster Studio Diamond Beats<<code>/a></</code>strong><br><br/><strong><a href=<code>"http://www.kissdrdrebeats.com/2011-new-dr-dre-studio-for-christmas-gifts-c-4.html "</code>>Dr Dre Diamond Sale<<code>/a></</code>strong><br><br/><strong><a href=<code>"http://www.kissdrdrebeats.com/2011-new-dr-dre-studio-for-christmas-gifts-c-4.html "</code>>Dr Dre Studio For Christmas<<code>/a></</code>strong><br><br/><br><br><a href=<code>"http://blog.acheapbagsale.com"</code>> headphones blog <<code>/a><br><br><a href="http:/blog.kissmbtboots.com"> headphones  </</code>a><br><br><a href=<code>"http://blog.ringsday.com"</code>> About kissdrdrebeats.com blog </a> </div> </div> </div> </div> <div class="category"> <div class="box"> <b class="rtop"> <b class="r1"></b> <b class="r2"></b> <b class="r3"></b> <b class="r4"></b> </b> <div class="content"> <a href="/clojure+cpp+fsharp+groovy+java+ocaml+python+scala/ugg">ugg</a> </div> <b class="rbottom"> <b class="r4"></b> <b class="r3"></b> <b class="r2"></b> <b class="r1"></b> </b> </div> </div> <div id="category26"> <div class="subcategory"> <div class="box"> <b class="rtop"> <b class="r1"></b> <b class="r2"></b> <b class="r3"></b> <b class="r4"></b> </b> <div class="content"> <a href="/clojure+cpp+fsharp+groovy+java+ocaml+python+scala/ugg/180">180</a> </div> <b class="rbottom"> <b class="r4"></b> <b class="r3"></b> <b class="r2"></b> <b class="r1"></b> </b> </div> </div> <div style="clear:both"/> <div id="subcategory52"> <div class="problem"> <h3><a href="/clojure+cpp+fsharp+groovy+java+ocaml+python+scala/ugg/180/180">180</a></h3> <div class="solutions" id="problem362"> <strong><a href=<code>"http://www.freshmoncler.com/ "</code>>moncler<<code>/a></</code>strong><strong><a href=<code>"http://www.freshmoncler.com/ "</code>>moncler coat<<code>/a></</code>strong>The sorts of lighting found in a area can noticeably change exactly how that room in your home looks. Lighting generally is a complicated dilemma, so let<code>'s begin by defining various lighting words. <br /><br/><br /><br/>Incandescent signals. These lights supply a nice, golden glow into a room. <strong><a href="http://www.freshmoncler.com/ ">moncler vest</a></strong>There'</code>re much nicer to utilize than this cheaper on the lookout flourescent equipment. <br <code>/><br/><br /</code>><br/>Downlights usually are round or perhaps square cannisters, commonly metal, which might be recessed directly into or secured onto a ceiling. These lights may very well be used simply because spotlights, floodlights or maybe for basic lighting. <br <code>/><br/><br /</code>><br/>Table lamps can be employed as project lighting or perhaps for overall lighting. <br <code>/><br/><br /</code>><br/>Uplights are usually one-bulb lights which can be placed on to the ground behind pieces of furniture, glass shelving or plants to supply them some sort of dramatic accentuation. <strong><a href=<code>"http://www.freshmoncler.com/ "</code>>moncler jackets<<code>/a></</code>strong><br <code>/><br/><br /</code>><br/>Strip lighting can be employed behind drawers and about stairs together with platforms to get a dramatic direct result. The networks lit in this way can seems to be floating above the ground. <br <code>/><br/><br /</code>><br/>Trail Lighting. A track can help you use a single electrical outlet to provide electricity to numerous lights along side track<code>'s length of time. The track is usually surface affixed or recessed. <strong><a href="http://www.freshmoncler.com/ ">discount moncler jackets</a></strong>Track lighting is amongst the most adaptable lighting solutions available and will be changed around for you to accent different aspects of a bedroom. <br /><br/><br /><br/>Track lighting products and recessed lighting is usually set to make an benefit called retaining wall washing which unfortunately, as that sounds, washes a total wall by using light. <br /><br/><br /><br/>Dimmer clicks give the chance to provide an alternative level about light through turning any knob. Dimmers help save electricity and gives mood lighting products for exclusive occasions. <strong><a href="http://www.freshmoncler.com/moncler-accessories-sale-c-1.html ">Moncler accessories</a></strong><br /><br/><br /><br/>Different rooms in your own home need distinctive lighting. Halls and also stairs need to be well lit to stop accidents. Livingrooms need a number of lighting solutions:background, undertaking lights and also accent lighting products. The most effective lighting to get kitchens will be bright above your head lights and extra under-counter signals for endeavor lighting. <br /><br/><br /><br/>All forms of lighting fixtures can be located for whatever your expections may get. <strong><a href="http://www.freshmoncler.com/moncler-vest-women-sale-c-10.html ">cheap Moncler Vest</a></strong>They can easily run as a result of very low-priced to remarkably high price fixtures. <br /><br/><br /><br/>You will discover special considerations when working with lighting to get art or perhaps wall hangings. <br /><br/><br /><br/>For anyone who is lighting an individual picture and painting, try to position the light so that it does not really show a good reflection in the glass of your art bit. There happen to be special snapshot lights made specifically for lighting shots but most of these are a lot of effective simply because can mainly highlight the highest or bottom with the picture. Downlights undoubtedly are a good choice. <strong><a href="http://www.freshmoncler.com/moncler-womens-hoody-sale-c-12.html ">Moncler Womens Hoody</a></strong><br /><br/><br /><br/>When lighting a gaggle of pictures, it'</code>s easier to use man or women lights inside track lighting which might be positioned on the pictures. <br <code>/><br/><br /</code>><br/>Lighting sculptures is usually particularly complex. You are able to use uplights, downlights or perhaps strip lamps, depending with the sculpture and its particular placement. Experiment by using different devices and their particular placement to discover the best impact. <strong><a href=<code>"http://www.freshmoncler.com/moncler-men-jackets-sale-c-4.html "</code>>cheap moncler jacket on sale<<code>/a></</code>strong><br <code>/><br/><br /</code>><br/>Creative by using lighting really can enhance a person<code>'s decorating venture. Make use out of all the different different types of lighting to make your home a amazing showcase. So you might have gone released and bought yourself a furry friend that you are excited concerning teaching not to mention feeding but it really suddenly occurred to you you happen to be unsure about precisely how to feed the ferret and you may be wondering just what do ferrets try to eat. That is a wonderful question because like any living thing on earth, the eating habits plays a big factor while in the health as well as the quality about life that it will have. What do ferrets eat when they are young? What do ferrets eat when they are older? What do ferrets eat when they are babies? If these are among a person'</code>s questions, keep reading and we<code>'ll touch with those content. <strong><a href="http://www.freshmoncler.com/moncler-kids-sale-c-3.html "> Moncler Jackets on sale</a></strong><br /><br/><br /><br/>What Do Ferrets Eat as Little ones? <br /><br/><br /><br/>What undertake ferrets consume as babies is a great question simply because likely if you'</code>ve owned an old-fashioned pet such as a cat or a dog a person likely wanted to feed them puppy food or become supplemental milk with the pet retail store and ferrets are only not which usually hard so that you can feed due to that. Baby ferrets feed off the mother and tend to be weaned off by the breeder or perhaps pet store so that you can ever become one still, with that said, once you may have the the baby ferret he is already familiar with a diet consists of pellets. <br <code>/><br/><br /</code>><br/>What Do Ferrets Eat as Parents? <br <code>/><br/><br /</code>><br/>What complete ferrets eat as people is a different wonderful query however it is not complicated by using a ferret like some other species of animals. The simply thing ferrets usually do not fair certainly with in the way of pet meals are foods that incorporate fish mealtime and ferrets never like this in the least. Try to stay away from every fish centered food anytime purchasing any ferret cuisine pellets and as a make a difference of matter, ferrets like shaped food quite as good as pellets that look a little like rabbit foods. <br <code>/><br/><br /</code>><br/>An excellent quality snake food that could be extremely high in protein is often fed and also to a ferret but they really demand a high amount of protein and typically you ought to look just for food comprising at lowest 25-30% healthy proteins content. Always be sure to stay from the foods which might be easily attainable at a grocery retail store or food outlet as they quite simply are generally very cheaply made and do not provide the correct nutrition in a ferret. <br <code>/><br/><br /</code>><br/>What Do Ferrets Eat as Pleasures? <br <code>/><br/><br /</code>><br/>Ferrets thrive on a goody based method when assisting them matters but there are a few things to know before serving your dig up any goodies. Acceptable treats would be things just like fruits and vegetables but manufactured! What complete ferrets eat that are bad for them? Always stay away from chocolate, dog food, any type of raw steak and dairy. . <br><br><a href=<code>"http://blog.dressever.com"</code>> stroe blog <<code>/a><br><br><a href="http:/blog.bootsvillage.com"> stroe  </</code>a><br><br><a href=<code>"http://blog.superbootsonline.com"</code>> About freshmoncler.com blog </a> </div> </div> </div> </div> <div class="category"> <div class="box"> <b class="rtop"> <b class="r1"></b> <b class="r2"></b> <b class="r3"></b> <b class="r4"></b> </b> <div class="content"> <a href="/clojure+cpp+fsharp+groovy+java+ocaml+python+scala/ebel-watches">Ebel watches</a> </div> <b class="rbottom"> <b class="r4"></b> <b class="r3"></b> <b class="r2"></b> <b class="r1"></b> </b> </div> </div> <div id="category27"> <div class="subcategory"> <div class="box"> <b class="rtop"> <b class="r1"></b> <b class="r2"></b> <b class="r3"></b> <b class="r4"></b> </b> <div class="content"> <a href="/clojure+cpp+fsharp+groovy+java+ocaml+python+scala/ebel-watches/180">180</a> </div> <b class="rbottom"> <b class="r4"></b> <b class="r3"></b> <b class="r2"></b> <b class="r1"></b> </b> </div> </div> <div style="clear:both"/> <div id="subcategory53"> <div class="problem"> <h3><a href="/clojure+cpp+fsharp+groovy+java+ocaml+python+scala/ebel-watches/180/180">180</a></h3> <div class="solutions" id="problem369"> <br><strong><a href=<code>"http://www.watchcoltd.com/ "</code>>Hugo Boss Watches<<code>/a></</code>strong><br><strong><a href=<code>"http://www.watchcoltd.com/ "</code>>Hush Puppies Watches<<code>/a></</code>strong><br><strong><a href=<code>"http://www.watchcoltd.com/ "</code>>IWC Watches<<code>/a></</code>strong><br><strong><a href=<code>"http://www.watchcoltd.com/ "</code>>Jaeger-LeCoultre Watches<<code>/a></</code>strong><br><strong><a href=<code>"http://www.watchcoltd.com/a-lange-sohne-watches-c-567.html "</code>>A. Lange & Sohne watches<<code>/a></</code>strong><br><strong><a href=<code>"http://www.watchcoltd.com/casio-watches-c-649.html "</code>>cheap Casio Watches<<code>/a></</code>strong><br><strong><a href=<code>"http://www.watchcoltd.com/breguet-watches-c-606.html "</code>>Breguet<<code>/a></</code>strong><br><strong><a href=<code>"http://www.watchcoltd.com/hermes-watches-c-751.html "</code>>Hermes<<code>/a></</code>strong><br><strong><a href=<code>"http://www.watchcoltd.com/casio-watches-c-649.html "</code>>Replica Casio Watches<<code>/a></</code>strong><br><strong><a href=<code>"http://www.watchcoltd.com/rolex-watches-c-923.html "</code>>replica Rolex Watches<<code>/a></</code>strong>. <br><br><a href=<code>"http://blog.linkpandora.com"</code>> watches blog <<code>/a><br><br><a href="http:/blog.biguggbootsoutlet.com"> watches  </</code>a><br><br><a href=<code>"http://blog.kindsofboots.com"</code>> About watchcoltd.com blog </a> </div> </div> </div> </div> <div class="category"> <div class="box"> <b class="rtop"> <b class="r1"></b> <b class="r2"></b> <b class="r3"></b> <b class="r4"></b> </b> <div class="content"> <a href="/clojure+cpp+fsharp+groovy+java+ocaml+python+scala/rolex-online">rolex online</a> </div> <b class="rbottom"> <b class="r4"></b> <b class="r3"></b> <b class="r2"></b> <b class="r1"></b> </b> </div> </div> <div id="category28"> <div class="subcategory"> <div class="box"> <b class="rtop"> <b class="r1"></b> <b class="r2"></b> <b class="r3"></b> <b class="r4"></b> </b> <div class="content"> <a href="/clojure+cpp+fsharp+groovy+java+ocaml+python+scala/rolex-online/180">180</a> </div> <b class="rbottom"> <b class="r4"></b> <b class="r3"></b> <b class="r2"></b> <b class="r1"></b> </b> </div> </div> <div style="clear:both"/> <div id="subcategory54"> <div class="problem"> <h3><a href="/clojure+cpp+fsharp+groovy+java+ocaml+python+scala/rolex-online/180/180">180</a></h3> <div class="solutions" id="problem370"> <br><strong><a href=<code>"http://www.dressreplicawatches.com/a-lange-sohne-watches-c-567.html"</code>>A. Lange & Sohne watches<<code>/a></</code>strong><strong><a href=<code>"http://www.dressreplicawatches.com/a-lange-sohne-watches-c-567.html"</code>>Replica A. Lange & Sohne watches<<code>/a></</code>strong><br><strong><a href=<code>"http://www.dressreplicawatches.com/a-lange-sohne-watches-c-567.html"</code>>fake A. Lange & Sohne watches<<code>/a></</code>strong><br><strong><a href=<code>"http://www.dressreplicawatches.com/a-lange-sohne-watches-c-567.html"</code>>copy A. Lange & Sohne watches<<code>/a></</code>strong><br><strong><a href=<code>"http://www.dressreplicawatches.com/a-lange-sohne-watches-c-567.html"</code>>cheap A. Lange & Sohne watches<<code>/a></</code>strong><br><br><br><a href=<code>"http://blog.iamjewelers.com"</code>> online blog <<code>/a><br><br><a href="http:/blog.swarovskiuk.org"> online  </</code>a><br><br><a href=<code>"http://blog.allpandoracharms.com"</code>> About dressreplicawatches.com blog </a> </div> </div> </div> </div> <div id="footer"> <div class="box"> <b class="rtop"> <b class="r1"></b> <b class="r2"></b> <b class="r3"></b> <b class="r4"></b> </b> <div class="content"> <a href="http://langref.org/submit">submit problem</a> | <a href="mailto:rob@langref.org">contact</a> | sponsored by <a href="http://refactor.com.au/"><img alt="Refactor-small" border="0" src="/images/refactor-small.png?1233409755" style="vertical-align:middle; padding-bottom:5px" /></a> </div> <b class="rbottom"> <b class="r4"></b> <b class="r3"></b> <b class="r2"></b> <b class="r1"></b> </b> </div> </div> </div> <script src="http://www.google-analytics.com/urchin.js" type="text/javascript"> </script> <script type="text/javascript"> _uacct = "UA-4264032-1"; _udn = "langref.org"; urchinTracker(); </script> </body> </html>