Solved Problems
Output a string to the console
Write the string
"Hello World!" to STDOUT
perl
print "Hello World!\n"
java
System.out.println("Hello World!");
System.out.printf("Hello World!\n");
clojure
(println "Hello World!")
fantom
echo("Hello World!")
Retrieve a string containing ampersands from the variables in a url
My PHP script first does a query to obtain customer info for a form. The form has first name and last name fields among others. The customer has put entries such as
The script variable for first name $_REQUEST
I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like
Of course this fails for the same reasons. What is a better approach?
"Ron & Jean" in the first name field in the database. Then the edit form script is called with variables such as
"http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith".
The script variable for first name $_REQUEST
['firstname'] never gets beyond the "Ron" value because of the ampersand in the data.
I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like
"http://myserver/custinfo/edit.php?mode=view&fname="Ronxxnbsp;xxamp;xxnbsp;Jean"&lname=SMITH". (sorry I had to add the xx to replace the ampersand or it didn't display meaningful url contents the browser sees.)
Of course this fails for the same reasons. What is a better approach?
perl
print "http://myserver.com/custinfo/edit.php"
."?fname=".urlenc('Ron & Jean')
."&lname=".urlenc('Smith');
sub urlenc{my($s)=@_;$s=~s/([^A-Za-z0-9])/sprintf("%%%02X",ord($1))/seg;$s}
."?fname=".urlenc('Ron & Jean')
."&lname=".urlenc('Smith');
sub urlenc{my($s)=@_;$s=~s/([^A-Za-z0-9])/sprintf("%%%02X",ord($1))/seg;$s}
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());
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());
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"))
"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"))
fantom
encoded := `http://myserver.com/custinfo/edit.php`.plusQuery(
["fname":"Ron & Jean", "lname":"Smith"]).encode
echo(encoded)
["fname":"Ron & Jean", "lname":"Smith"]).encode
echo(encoded)
Define a string containing special characters
Define the literal string
"\#{'}${"}/"
perl
$special = '\#{\'}${"}/';
$special = q(\#{'}${"}/);
java
String special = "\\#{'}${\"}/";
clojure
(def special "\\#{'}${\"}/")
fantom
special := Str<|\#{'}${"}/|>
Define a multiline string
Define the string:
"This
Is
A
Multiline
String"
perl
$text = 'This
Is
A
Multiline
String';
Is
A
Multiline
String';
$text = <<EOF;
This
Is
A
Multiline
String
EOF
This
Is
A
Multiline
String
EOF
java
String text = "This\nIs\nA\nMultiline\nString";
String text =
"This\n" +
"Is\n" +
"A\n" +
"Multiline\n" +
"String"
"This\n" +
"Is\n" +
"A\n" +
"Multiline\n" +
"String"
clojure
(def multiline "This\nIs\nA\nMultiline\nString")
fantom
s := "This
Is
A
Multiline
String"
Is
A
Multiline
String"
Define a string containing variables and expressions
Given variables a=3 and b=4 output
"3+4=7"
perl
print "$a+$b=${\($a+$b)}\n";
sprintf("%d+%d=%d", $a, $b, $a + $b);
print $a, '+', $b, '=', $a + $b;
java
System.out.println(a + "+" + b + "=" + (a+b));
System.out.printf("%d+%d=%d\n", a, b, a + b);
clojure
(format "%d + %d = %d" a b (+ a b))
fantom
echo("$a+$b=${a+b}")
Reverse the characters in a string
Given the string
"reverse me", produce the string "em esrever"
perl
$_ = reverse "reverse me"; print
java
String reverse = new StringBuffer("reverse me").reverse().toString();
String reverse = new StringBuilder("reverse me").reverse().toString();
String reverse = StringUtils.reverse("reverse me");
clojure
(require '[clojure.contrib.str-utils2 :as str])
(str/reverse "reverse me")
(str/reverse "reverse me")
(apply str (reverse "reverse me"))
fantom
"reverse me".reverse
Reverse the words in a string
Given the string
"This is a end, my only friend!", produce the string "friend! only my end, the is This"
perl
$reversed = join ' ', reverse split / /, $text;
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();
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();
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!", ' ');
clojure
(require '[clojure.contrib.str-utils2 :as str])
(str/join " " (reverse (str/split "this is the end, my only friend!" #" ")))
(str/join " " (reverse (str/split "this is the end, my only friend!" #" ")))
(apply str (interpose " " (reverse (re-seq #"[^\s]+" "This is the end, my only friend!"))))
fantom
"This is a end, my only friend!".split.reverse.join(" ")
Text wrapping
Wrap the string
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog.
"The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> ", yielding this result:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog.
perl
use Text::Wrap;
$text = "The quick brown fox jumps over the lazy dog. ";
$Text::Wrap::columns = 73;
print wrap('> ', '> ', $text x 10);
$text = "The quick brown fox jumps over the lazy dog. ";
$Text::Wrap::columns = 73;
print wrap('> ', '> ', $text x 10);
$_ = "The quick brown fox jumps over the lazy dog. " x 10;
s/(.{0,70}) /> $1\n/g;
print;
s/(.{0,70}) /> $1\n/g;
print;
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);
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);
clojure
(doseq [line (re-seq #".{0,70} "
(apply str
(repeat 10 "The quick brown fox jumps over the lazy dog. ")))]
(println ">" line))
(apply str
(repeat 10 "The quick brown fox jumps over the lazy dog. ")))]
(println ">" line))
fantom
buf := Buf()
10.times { buf.writeChars("The quick brown fox jumps over the lazy dog. ") }
buf.flip
out := Env.cur.out
sep := ">"; max := 72 - sep.size - 1
acc := 0; Str? s := null
while ((s = buf.readStrToken) != null)
{
if (acc == 0)
out.print(sep)
acc += s.size
if (acc > max)
{
out.print("\n$sep")
acc = s.size
}
out.print(" $s")
buf.readStrToken(4096) { !it.isSpace }
acc++
}
10.times { buf.writeChars("The quick brown fox jumps over the lazy dog. ") }
buf.flip
out := Env.cur.out
sep := ">"; max := 72 - sep.size - 1
acc := 0; Str? s := null
while ((s = buf.readStrToken) != null)
{
if (acc == 0)
out.print(sep)
acc += s.size
if (acc > max)
{
out.print("\n$sep")
acc = s.size
}
out.print(" $s")
buf.readStrToken(4096) { !it.isSpace }
acc++
}
Remove leading and trailing whitespace from a string
Given the string
" hello " return the string "hello".
perl
my $string = " hello ";
$string =~ s{
\A\s* # Any number of spaces at the start of the string
(.+?) # Remember any number of characters until we reach
\s*\z # any number of spaces at the end of the string
}{
$1 # Leave the characters we remembered
}x;
$string =~ s{
\A\s* # Any number of spaces at the start of the string
(.+?) # Remember any number of characters until we reach
\s*\z # any number of spaces at the end of the string
}{
$1 # Leave the characters we remembered
}x;
my $string = " hello ";
$string =~ s{\A\s*}{};
$string =~ s{\s*\z}{};
$string =~ s{\A\s*}{};
$string =~ s{\s*\z}{};
#Modification History:
# 2009-MAR-17: GGARIEPY: [creation] (geoff.gariepy@gmail.com)
$string = " hello ";
$string =~ s/^\s+|\s+$//g; # All the action happens in one regex!
# Regex Notes:
# ^ - anchors to the beginning of the string
# $ - anchors to the end of the string
# g - causes regex to match as many times as possible
# | - logical OR
# 2009-MAR-17: GGARIEPY: [creation] (geoff.gariepy@gmail.com)
$string = " hello ";
$string =~ s/^\s+|\s+$//g; # All the action happens in one regex!
# Regex Notes:
# ^ - anchors to the beginning of the string
# $ - anchors to the end of the string
# g - causes regex to match as many times as possible
# | - logical OR
java
String s = " hello "; String trimmed = s.trim();
clojure
(use 'clojure.contrib.str-utils2)
(trim " hello ")
(trim " hello ")
(clojure.string/trim " hello ")
(.trim " hello ")
fantom
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
For example:
String is: Hello World #123
ROT13 returns: Uryyb Jbeyq #123
ROT47 returns: w6==@ (@C=5 R`ab
perl
sub rot13 {
my $str = shift;
$str =~ tr/A-Za-z/N-ZA-Mn-za-m/;
return $str;
}
sub rot47 {
my $str = shift;
$str =~ tr/!-~/P-~!-O/;
return $str;
}
my $string = 'Hello World #123';
print "$string\n";
print rot13($string)."\n";
print rot47($string)."\n";
my $str = shift;
$str =~ tr/A-Za-z/N-ZA-Mn-za-m/;
return $str;
}
sub rot47 {
my $str = shift;
$str =~ tr/!-~/P-~!-O/;
return $str;
}
my $string = 'Hello World #123';
print "$string\n";
print rot13($string)."\n";
print rot47($string)."\n";
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 ) )) ;
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 ) )) ;
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))))
(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))))
fantom
rot := |Str s, |Int c -> Int| remap -> Str|
{
rs := ""
s.each { rs += remap(it).toChar }
return rs
}
rot13 := |Str s -> Str|
{
rot(s) |Int c -> Int|
{
lc := c.lower
c += (lc >= 'a' && lc <= 'm') ? 13
: ((lc >= 'n' && lc <= 'z') ? -13 : 0)
return c
}
}
rot47 := |Str s -> Str|
{
rot(s) |Int c -> Int|
{
c += (c >= '!' && c <= 'O') ? 47
: ((c >= 'P' && c <= '~') ? -47 : 0)
return c
}
}
s := "Hello World #123"
echo("s=$s")
echo("rot13=${rot13(s)}")
echo("rot47=${rot47(s)}")
{
rs := ""
s.each { rs += remap(it).toChar }
return rs
}
rot13 := |Str s -> Str|
{
rot(s) |Int c -> Int|
{
lc := c.lower
c += (lc >= 'a' && lc <= 'm') ? 13
: ((lc >= 'n' && lc <= 'z') ? -13 : 0)
return c
}
}
rot47 := |Str s -> Str|
{
rot(s) |Int c -> Int|
{
c += (c >= '!' && c <= 'O') ? 47
: ((c >= 'P' && c <= '~') ? -47 : 0)
return c
}
}
s := "Hello World #123"
echo("s=$s")
echo("rot13=${rot13(s)}")
echo("rot47=${rot47(s)}")
Make a string uppercase
Transform
"Space Monkey" into "SPACE MONKEY"
perl
print uc "Space Monkey"
java
String upper = text.toUpperCase();
clojure
(.toUpperCase "Space Monkey")
fantom
s := "Space Monkey".localeUpper
Make a string lowercase
Transform
"Caps ARE overRated" into "caps are overrated"
perl
print lc "Caps ARE overRated"
java
"Caps ARE overRated".toLowerCase();
clojure
(.toLowerCase "Caps ARE overRated")
fantom
s := "Caps ARE overRated".localeLower
Capitalise the first letter of each word
Transform
"man OF stEEL" into "Man Of Steel"
perl
$text =~ s/(\w+)/\u\L$1/g;
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();
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)));
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);
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");
clojure
(use 'clojure.contrib.str-utils2)
(join " " (map capitalize (split "man OF stEEL" #" ")))
(join " " (map capitalize (split "man OF stEEL" #" ")))
fantom
"man OF stEEL".split.map { it.localeLower.localeCapitalize }.join(" ")
Find the distance between two points
perl
use Math::Complex;
$a = Math::Complex->make(0, 3);
$b = Math::Complex->make(4, 0);
$distance = abs($a - $b);
$a = Math::Complex->make(0, 3);
$b = Math::Complex->make(4, 0);
$distance = abs($a - $b);
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);
Point2D point2 = new Point2D.Double(x2, y2);
double distance = point1.distance(point2);
double distance = Math.hypot(x2-x1, y2-y1);
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"
[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])
"Euclidean distance between 2 points"
[[x1 y1] [x2 y2]]
(Math/sqrt
(+ (Math/pow (- x1 x2) 2)
(Math/pow (- y1 y2) 2))))
(distance [2 2] [3 3])
fantom
px1 := 34.0f; py1 := 78.0f; px2 := 67.0f; py2 := -45.0f
distance := |Float x1, Float y1, Float x2, Float y2 -> Float|
{ ((x2-x1).pow(2.0f) + (y2-y1).pow(2.0f)).sqrt }
distance(px1, py1, px2, py2)
distance := |Float x1, Float y1, Float x2, Float y2 -> Float|
{ ((x2-x1).pow(2.0f) + (y2-y1).pow(2.0f)).sqrt }
distance(px1, py1, px2, py2)
Zero pad a number
Given the number 42, pad it to 8 characters like 00000042
perl
sprintf("%08d", 42);
java
String formatted = new DecimalFormat("00000000").format(42);
String formatted = String.format("%08d", 42);
clojure
(defn pad
([x] (if (> 8 (.length (str x))) (pad (str 0 x)) (str x)))
)
([x] (if (> 8 (.length (str x))) (pad (str 0 x)) (str x)))
)
(defn pad [x]
(format "%08d" x))
(format "%08d" x))
(format "%08d" 42)
fantom
formatted := 42.toStr.padl(8, '0')
formatted := 42.toLocale("00000000")
Right Space pad a number
Given the number 1024 right pad it to 6 characters
"1024 "
perl
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());
}
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);
clojure
(let [s (str 1024)
l (count s)]
(str s (reduce str (repeat (- 6 l) " "))))
l (count s)]
(str s (reduce str (repeat (- 6 l) " "))))
fantom
formatted := 1024.toStr.padr(6)
Format a decimal number
Format the number 7/8 as a decimal with 2 places: 0.88
perl
sprintf("%.2f", 7/8);
java
String formatted = String.format("%3.2f", 7./8.);
clojure
(format "%3.2f" (/ 7.0 8))
(* 0.01 (Math/round (* 100 (float (/ 7 8)))))
fantom
formatted := (7.0/8.0).toLocale("0.00")
Left Space pad a number
Given the number 73 left pad it to 10 characters
" 73"
perl
sprintf("%10d", 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;
}
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);
clojure
(let [s (str 73)
l (count s)]
(str (reduce str (repeat (- 10 l) " ")) s ))
l (count s)]
(str (reduce str (repeat (- 10 l) " ")) s ))
fantom
formatted := 73.toStr.padl(10)
Generate a random integer in a given range
Produce a random integer between 100 and 200 inclusive
perl
my $range = 100;
my $minimum = 100;
my $random_number = int(rand($range)) + $minimum;
print "$random_number\n";
my $minimum = 100;
my $random_number = int(rand($range)) + $minimum;
print "$random_number\n";
java
Random random = new Random();
int randomInt = random.nextInt(200-100+1)+100;
int randomInt = random.nextInt(200-100+1)+100;
clojure
(+ (rand-int (- 201 100)) 100)
fantom
r := Int.random(100..200)
Generate a repeatable random number sequence
Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values.
perl
srand(12345);
@list1 = map(int(rand(100)+1), (1..5));
srand(12345);
@list2 = map(int(rand(100)+1), (1..5));
print join(', ', @list1) . "\n";
print join(', ', @list2) . "\n";
@list1 = map(int(rand(100)+1), (1..5));
srand(12345);
@list2 = map(int(rand(100)+1), (1..5));
print join(', ', @list1) . "\n";
print join(', ', @list2) . "\n";
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(); }
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(); }
clojure
(dotimes [_ 2]
(let [r (java.util.Random. 12345)]
(dotimes [_ 5]
(println (.nextInt r 100))))
(println))
(let [r (java.util.Random. 12345)]
(dotimes [_ 5]
(println (.nextInt r 100))))
(println))
fantom
rand := Random.makeSeeded(12345)
first := Int[,].fill(0,5).map { rand.next(100..200) }
rand2 := Random.makeSeeded(12345)
second := Int[,].fill(0,5).map { rand2.next(100..200) }
first := Int[,].fill(0,5).map { rand.next(100..200) }
rand2 := Random.makeSeeded(12345)
second := Int[,].fill(0,5).map { rand2.next(100..200) }
Check if a string matches a regular expression
Display
"ok" if "Hello" matches /[A-Z][a-z]+/
perl
print 'ok' if ('Hello' =~ /[A-Z][a-z]+/);
java
if ("Hello".matches("[A-Z][a-z]+")) {
System.out.println("ok");
}
System.out.println("ok");
}
clojure
(if (re-matches #"[A-Z][a-z]+" "Hello")
(println "ok"))
(println "ok"))
fantom
if (Regex<|[A-Z][a-z]+|>.matches("Hello"))
echo("ok")
echo("ok")
Check if a string matches with groups
Display
"two" if "one two three" matches /one (.*) three/
perl
print $1 if "one two three"=~/^one (.*) three$/
java
Pattern pattern = Pattern.compile("one (.*) three");
Matcher matcher = pattern.matcher("one two three");
if (matcher.matches()) {
System.out.println(matcher.group(1));
}
Matcher matcher = pattern.matcher("one two three");
if (matcher.matches()) {
System.out.println(matcher.group(1));
}
clojure
(if-let [groups (re-matches #"one (.*) three" "one two three")]
(println (second groups)))
(println (second groups)))
fantom
m := Regex<|one (.*) three|>.matcher("one two three")
if (m.matches)
echo("${m.group(1)}")
if (m.matches)
echo("${m.group(1)}")
Check if a string contains a match to a regular expression
Display
"ok" if "abc 123 @#$" matches /\d+/
perl
print "ok" if ("abc 123 @#\$" =~ m/\d+/)
java
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
System.out.println("ok");
}
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
System.out.println("ok");
}
clojure
(if (re-find #"\d+" "abc 123 @#$")
(println "ok"))
(println "ok"))
fantom
m := Regex<|\d+|>.matcher("abc 123 @#\$")
if (m.find)
echo("ok")
if (m.find)
echo("ok")
Loop through a string matching a regex and performing an action for each match
Create a list
[fish1,cow3,boat4] when matching "(fish):1 sausage (cow):3 tree (boat):4" with regex /\((\w+)\):(\d+)/
perl
while ($text =~ /\((\w+)\):(\d+)/g) {
push @list, "$1$2"
}
push @list, "$1$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));
}
Pattern pattern = Pattern.compile("\\((\\w+)\\):(\\d+)");
Matcher matcher = pattern.matcher(text);
while(matcher.find()) {
list.add(matcher.group(1)+matcher.group(2));
}
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)))
(loop [match (re-find matcher)
lst []]
(if match
(recur (re-find matcher) (conj lst (str (second match) (nth match 2))))
lst)))
fantom
m := Regex<|\((\w+)\):(\d+)|>.matcher(s)
list := Str[,]
while (m.find) { list.add("${m.group(1)}${m.group(2)}") }
list := Str[,]
while (m.find) { list.add("${m.group(1)}${m.group(2)}") }
Replace the first regex match in a string with a static string
Transform
"Red Green Blue" into "R*d Green Blue" by replacing /e/ with "*"
perl
$text =~s/e/*/;
java
String replaced = "Red Green Blue".replaceFirst("e", "*");
clojure
(.replaceFirst (re-matcher #"e" "Red Green Blue") "*")
fantom
replaced := Regex<|e|>.split("Red Green Blue",2).join("*")
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"
perl
$text = "She sells sea shells";
$text =~ s/se\w+/X/g;
$text =~ s/se\w+/X/g;
java
String replaced = text.replaceAll("se\\w+", "X");
clojure
(.replaceAll (re-matcher #"se\w+" "She sells sea shells") "X")
fantom
replaced := Regex<|se\w+|>.split("She sells sea shells").join("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+)\}/.
perl
$text = "The {Quick} Brown {Fox}";
$text =~ s/\{(\w+)\}/reverse($1)/ge;
$text =~ s/\{(\w+)\}/reverse($1)/ge;
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);
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);
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))))))
(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))))
#"\{(\w+)\}"
(fn [[_ word]] (apply str (reverse word))))
fantom
s := "The {Quick} Brown {Fox}"
m := Regex<|\{(\w+)\}|>.matcher(s)
buf := StrBuf(s.size)
last := 0
while (m.find)
{
buf.add(s[last..m.start-1]).add(m.group(1).reverse)
last = m.end
}
buf.add(s[last..-1])
replaced := buf.toStr
m := Regex<|\{(\w+)\}|>.matcher(s)
buf := StrBuf(s.size)
last := 0
while (m.find)
{
buf.add(s[last..m.start-1]).add(m.group(1).reverse)
last = m.end
}
buf.add(s[last..-1])
replaced := buf.toStr
Define an empty list
Assign the variable
"list" to a list with no elements
perl
@list = ();
java
List list = Collections.emptyList();
String[] list = {};
clojure
(list)
'()
fantom
list := [,]
Define a static list
Define the list
[One, Two, Three, Four, Five]
perl
@list = qw(One Two Three Four Five);
@list = ('One', 'Two', 'Three', 'Four', 'Five');
java
List<String> numbers = new ArrayList<String>();
Collections.addAll(numbers, "One", "Two", "Three", "Four", "Five");
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");
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"); }};
clojure
(def a '[One Two Three Four Five])
fantom
list := ["One", "Two", "Three", "Four", "Five"]
Join the elements of a list, separated by commas
Given the list
[Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
perl
print join ', ', qw(Apple Banana Carrot);
# Longer and less efficient than join(), but illustrates
# Perl's foreach operator, which can be useful for
# less trivial problems with lists
@list = ('Apple', 'Banana', 'Carrot');
foreach $fruit (@list) {
print "$fruit,";
}
print "\n";
# Perl's foreach operator, which can be useful for
# less trivial problems with lists
@list = ('Apple', 'Banana', 'Carrot');
foreach $fruit (@list) {
print "$fruit,";
}
print "\n";
my @a = qw/Apple Banana Carrot/;
{
local $, = ", ";
print @a
}
print "\n";
{
local $, = ", ";
print @a
}
print "\n";
my @a = qw/Apple Banana Carrot/;
{
local $" = ", ";
print "@a\n";
}
{
local $" = ", ";
print "@a\n";
}
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();
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();
for (String item : fruit.subList(1, fruit.size())) sb.append(", ").append(item);
String result = sb.toString();
String result = StringUtils.join(fruit, ", ");
clojure
(apply str (interpose ", " '("Apple" "Banana" "Carrot")))
fantom
["Apple", "Banana", "Carrot"].join(", ")
Join the elements of a list, in correct english
Create a function join that takes a List and produces a string containing an english language concatenation of the list. It should work with the following examples:
join(
join(
join(
join(
join(
[Apple, Banana, Carrot]) = "Apple, Banana, and Carrot"
join(
[One, Two]) = "One and Two"
join(
[Lonely]) = "Lonely"
join(
[]) = ""
perl
sub myjoin {
$_ = join ', ', @_;
s/, ([^,]+)$/ and $1/;
return $_;
}
# Note: I don't think this meets the spec --Geoff
$_ = join ', ', @_;
s/, ([^,]+)$/ and $1/;
return $_;
}
# Note: I don't think this meets the spec --Geoff
sub myjoin {
if ($#_ < 2) {
return join ' and ', @_;
} else {
return join(', ', @_[0..$#_-1]) . ' and ' . $_[-1];
}
}
# Note: I don't think this meets the spec --Geoff
if ($#_ < 2) {
return join ' and ', @_;
} else {
return join(', ', @_[0..$#_-1]) . ' and ' . $_[-1];
}
}
# Note: I don't think this meets the spec --Geoff
# Previous "myjoin()" responses don't meet the spec of including
# the final comma before the "and" if the list has more than
# two elements...this is one way to meet that spec...it may
# not be the most efficient...
sub AnotherMyJoin {
my @list = @_;
if ($#list == -1) {return}
elsif ($#list == 0) {return $list[0]}
elsif ($#list == 1) {return $list[0].' and '.$list[1]}
else {
return join(", ", @list[0..$#list - 1]) . ', and '. $list[$#list];
}
}
# the final comma before the "and" if the list has more than
# two elements...this is one way to meet that spec...it may
# not be the most efficient...
sub AnotherMyJoin {
my @list = @_;
if ($#list == -1) {return}
elsif ($#list == 0) {return $list[0]}
elsif ($#list == 1) {return $list[0].' and '.$list[1]}
else {
return join(", ", @list[0..$#list - 1]) . ', and '. $list[$#list];
}
}
# This is the long way, but it's kind of fun
# It illustrates the use of Perl's reverse()
# operator to work our way through the list
# elements backwards...I wrote this one before
# getting smart and looking at some of the other
# algorithms from the other languages. Still,
# it is only 12 lines of code vs 9 for my other
# solution if you disregard the comments.
sub myjoin {
my @list = reverse(@_); # Reverse original order of elements
my $retval;
# Make our exit here if we were passed an empty list
if ($#list == -1) {return}
# Loop through reversed elements in end-to-start order
for (0..$#list) {
# Add the reversed form of each element plus a space char
$retval .= reverse($list[$_]).' ';
# Add 'and' to lists with two or more elements
# placing it in between final and 'next to final'
$retval .= "dna " if ($#list > 0 and $_== 0);
# Add ',' to each element as long as there are more
# than two elements and the current element isn't the
# final element
$retval .= "," if ($#list > 1 and $_ != $#list);
}
# Remove what will end up as an extraneous leading space
chop($retval);
# Done looping, now reverse things back into correct order and return
$retval = reverse($retval);
return($retval);
}
# It illustrates the use of Perl's reverse()
# operator to work our way through the list
# elements backwards...I wrote this one before
# getting smart and looking at some of the other
# algorithms from the other languages. Still,
# it is only 12 lines of code vs 9 for my other
# solution if you disregard the comments.
sub myjoin {
my @list = reverse(@_); # Reverse original order of elements
my $retval;
# Make our exit here if we were passed an empty list
if ($#list == -1) {return}
# Loop through reversed elements in end-to-start order
for (0..$#list) {
# Add the reversed form of each element plus a space char
$retval .= reverse($list[$_]).' ';
# Add 'and' to lists with two or more elements
# placing it in between final and 'next to final'
$retval .= "dna " if ($#list > 0 and $_== 0);
# Add ',' to each element as long as there are more
# than two elements and the current element isn't the
# final element
$retval .= "," if ($#list > 1 and $_ != $#list);
}
# Remove what will end up as an extraneous leading space
chop($retval);
# Done looping, now reverse things back into correct order and return
$retval = reverse($retval);
return($retval);
}
# Yes, this doesn't meet the spec, the spec is flawed
# the serial comma (Oxford comma) is not required in a list
sub english_join {
return join(', ', @_[0..$#_-1])
. ($#_ ? ' and ' : '' )
. $_[-1];
}
# the serial comma (Oxford comma) is not required in a list
sub english_join {
return join(', ', @_[0..$#_-1])
. ($#_ ? ' and ' : '' )
. $_[-1];
}
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();
}
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));
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)))))))))
(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)))))
([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)))))
fantom
join := |List list -> Str|
{
switch(list.size)
{
case 0: return ""
case 1: return list[0]
case 2: return list.join(" and ")
default: return list[0..-2].join(", ") + ", and " + list[-1]
}
}
echo(join(["Apple", "Banana", "Carrot"]))
echo(join(["One", "Two"]))
echo(join(["Lonely"]))
echo(join([,]))
{
switch(list.size)
{
case 0: return ""
case 1: return list[0]
case 2: return list.join(" and ")
default: return list[0..-2].join(", ") + ", and " + list[-1]
}
}
echo(join(["Apple", "Banana", "Carrot"]))
echo(join(["One", "Two"]))
echo(join(["Lonely"]))
echo(join([,]))
Produce the combinations from two lists
Given two lists, produce the list of tuples formed by taking the combinations from the individual lists. E.g. given the letters
["a", "b", "c"] and the numbers [4, 5], produce the list: [["a", 4], ["b", 4], ["c", 4], ["a", 5], ["b", 5], ["c", 5]]
perl
@letters = qw(a b c);
@numbers = (4, 5);
@list = map { $number=$_; map [$_, $number], @letters; } @numbers;
@numbers = (4, 5);
@list = map { $number=$_; map [$_, $number], @letters; } @numbers;
@letters = qw(a b c);
@numbers = (4, 5);
for $number (@numbers) {
for $letter (@letters) {
push @list, [$letter, $number];
}
}
@numbers = (4, 5);
for $number (@numbers) {
for $letter (@letters) {
push @list, [$letter, $number];
}
}
java
List<String> combinations = new ArrayList<String>();
for (int number : numbers)
for (String letter : letters)
combinations.add(letter + ":" + Integer.toString(number));
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)));
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)));
clojure
(defn combine [lst1 lst2]
(mapcat (fn [x] (map #(list % x) lst1)) lst2))
(mapcat (fn [x] (map #(list % x) lst1)) lst2))
(mapcat (fn [x] (map #(list % x) ["a", "b", "c"])) [4, 5])
fantom
[4,5].each |Int i| { ["a","b","c"].each |Str s| { r.add([i,s]) } }
From a List Produce a List of Duplicate Entries
Taking a list:
Write the code to produce a list of duplicates in the list:
["andrew", "bob", "chris", "bob"]
Write the code to produce a list of duplicates in the list:
["bob"]
perl
my @input = ("andrew", "bob", "chris", "bob", "bob");
my %input_count;
my @output = grep { $input_count{$_}++; $input_count{$_} == 2 } @input;
my %input_count;
my @output = grep { $input_count{$_}++; $input_count{$_} == 2 } @input;
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);
Set set = new HashSet(listOfDuplicates);
for (Object element : set)
listOfDuplicates.remove(element);
clojure
(->> '("andrew" "bob" "chris" "bob")
(group-by identity)
(filter #(> (count (second %)) 1))
(map first))
(group-by identity)
(filter #(> (count (second %)) 1))
(map first))
fantom
nameCounts := Str:Int[:] { def = 0 }
["andrew", "bob", "chris", "bob"].each |Str v| { nameCounts[v]++ }
results := nameCounts.findAll |Int v, Str k->Bool| { v > 1 }.keys
echo(results.join(","))
["andrew", "bob", "chris", "bob"].each |Str v| { nameCounts[v]++ }
results := nameCounts.findAll |Int v, Str k->Bool| { v > 1 }.keys
echo(results.join(","))
Fetch an element of a list by index
Given the list
[One, Two, Three, Four, Five], fetch the third element ('Three')
perl
qw(One Two Three Four Five)[2];
@list = qw(One Two Three Four Five);
$list[2];
$list[2];
java
String result = list.get(2);
clojure
(nth '[One Two Three Four Five] 2)
fantom
["One", "Two", "Three", "Four", "Five"][2]
["One", "Two", "Three", "Four", "Five"].get(2)
Fetch the last element of a list
Given the list
[Red, Green, Blue], access the last element ('Blue')
perl
qw(Red Green Blue)[-1];
@list = qw(Red Green Blue);
$list[-1];
$list[-1];
java
String result = list.get(list.size() - 1);
clojure
(last '[One Two Three Four Five])
fantom
["Red", "Green", "Blue"][-1]
["One", "Two", "Three", "Four", "Five"].last
Find the common items in two lists
Given two lists, find the common items. E.g. given beans =
['broad', 'mung', 'black', 'red', 'white'] and colors = ['black', 'red', 'blue', 'green'], what are the bean varieties that are also color names?
perl
@beans = qw(broad mung black red white);
@colors = qw(black red blue green);
@seen{@beans} = ();
for (@colors) {
push(@intersection, $_) if exists($seen{$_});
}
print join(', ', @intersection);
@colors = qw(black red blue green);
@seen{@beans} = ();
for (@colors) {
push(@intersection, $_) if exists($seen{$_});
}
print join(', ', @intersection);
@beans = qw(broad mung black red white);
@colors = qw(black red blue green);
my %colors_hash = map { $_ => 1 } @colors;
my @intersection = grep { $colors_hash{$_} } @beans;
print join(', ', @intersection),"\n";
@colors = qw(black red blue green);
my %colors_hash = map { $_ => 1 } @colors;
my @intersection = grep { $colors_hash{$_} } @beans;
print join(', ', @intersection),"\n";
@beans = qw/broad mung black red white/;
@colors = qw/black red blue green/;
print join ', ', grep { $_ ~~ @colors } @beans;
@colors = qw/black red blue green/;
print join ', ', grep { $_ ~~ @colors } @beans;
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);
List colors = Arrays.asList(new String[]{"black", "red", "blue", "green"});
List common = ListUtils.intersection(beans, colors);
clojure
(use 'clojure.set)
(let [beans '[broad mung black red white]
colors '[black red blue green]]
(intersection (set beans) (set colors)))
(let [beans '[broad mung black red white]
colors '[black red blue green]]
(intersection (set beans) (set colors)))
fantom
beans := ["broad", "mung", "black", "red", "white"]
colors := ["black", "red", "blue", "green"]
echo(beans.intersection(colors))
colors := ["black", "red", "blue", "green"]
echo(beans.intersection(colors))
Display the unique items in a list
Display the unique items in a list, e.g. given ages =
[18, 16, 17, 18, 16, 19, 14, 17, 19, 18], display the unique elements, i.e. with duplicates removed.
perl
@ages = (18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
@seen{@ages} = ();
@unique = keys %seen;
print join(', ', @unique);
@seen{@ages} = ();
@unique = keys %seen;
print join(', ', @unique);
@ages = (18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
@unique = grep(!$seen{$_}++, @ages);
print join(', ', @unique);
@unique = grep(!$seen{$_}++, @ages);
print join(', ', @unique);
@ages = (18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
print join(', ', grep(!$seen{$_}++, @ages));
print join(', ', grep(!$seen{$_}++, @ages));
@ages = (18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
for (@ages) {
push(@unique, $_) unless $seen{$_}++;
}
print join(', ', @unique);
for (@ages) {
push(@unique, $_) unless $seen{$_}++;
}
print join(', ', @unique);
use List::MoreUtils qw(uniq);
@ages = (18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
print join(', ', uniq(@ages));
@ages = (18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
print join(', ', uniq(@ages));
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);
System.out.println(ages);
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)
(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)
fantom
uniqueAges := [18, 16, 17, 18, 16, 19, 14, 17, 19, 18].unique
echo(uniqueAges)
echo(uniqueAges)
Remove an element from a list by index
Given the list
[Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
perl
@list = qw(Apple Banana Carrot);
shift @list;
shift @list;
@list = qw(Apple Banana Carrot);
$offset = 0;
splice(@list, $offset, 1);
$offset = 0;
splice(@list, $offset, 1);
java
list.remove(0);
clojure
(let [fruit ["Apple" "Banana" "Carrot"]
index 0]
(concat
(take index fruit)
(drop (+ index 1) fruit)))
index 0]
(concat
(take index fruit)
(drop (+ index 1) fruit)))
fantom
list := ["Apple", "Banana", "Carrot"]
list.removeAt(0)
list.removeAt(0)
Remove the last element of a list
perl
pop @list;
java
list.remove(list.size() - 1);
clojure
(pop ["Apple" "Banana" "Carrot"])
fantom
list := ["Apple", "Banana", "Carrot"]
list.removeAt(-1)
list.removeAt(-1)
list := ["Apple", "Banana", "Carrot"]¨
list.pop
list.pop
Rotate a list
Given a list
["apple", "orange", "grapes", "bananas"], rotate it by removing the first item and placing it on the end to yield ["orange", "grapes", "bananas", "apple"]
perl
@list = qw(apple, orange, grapes, bananas);
push @list, shift @list;
push @list, shift @list;
@list = qw(apple orange grapes bananas);
@list = @list[1..$#list,0];
@list = @list[1..$#list,0];
java
list.add(list.remove(0));
Collections.rotate(list, -1);
clojure
(let [fruit ["apple" "orange" "grapes" "bananas"]]
(concat (rest fruit) [(first fruit)])
(concat (rest fruit) [(first fruit)])
fantom
list := ["apple", "orange", "grapes", "bananas"]
list.add(list.removeAt(0))
list.add(list.removeAt(0))
Gather together corresponding elements from multiple lists
Given several lists, gather together the first element from every list, the second element from every list, and so on for all corresponding index values in the lists. E.g. for these three lists, first =
['Bruce', 'Tommy Lee', 'Bruce'], last = ['Willis', 'Jones', 'Lee'], years = [1955, 1946, 1940] the result should produce 3 actors. The middle actor should be Tommy Lee Jones.
perl
my @first = ('Bruce', 'Tommy Lee', 'Bruce');
my @last = ('Willis', 'Jones', 'Lee');
my @years = (1955, 1946, 1940);
my @actors;
my $max = scalar @first;
for my $index (0 .. $max) {
push @actors, [ $first[$index], $last[$index], $years[$index] ];
};
my @last = ('Willis', 'Jones', 'Lee');
my @years = (1955, 1946, 1940);
my @actors;
my $max = scalar @first;
for my $index (0 .. $max) {
push @actors, [ $first[$index], $last[$index], $years[$index] ];
};
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);
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);
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))
(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))
(def lastnames ["Willis" "Jones" "Lee"])
(def years [1955 1946 1940])
(println (map (fn [f l y] [f l y]) firstnames lastnames years))
fantom
r := [,]
first.size.times |Int i| { r.add([first[i], last[i], years[i]]) }
echo(r)
first.size.times |Int i| { r.add([first[i], last[i], years[i]]) }
echo(r)
List Combinations
Given two source lists (or sets), generate a list (or set) of all the pairs derived by combining elements from the individual lists (sets). E.g. given suites =
['H', 'D', 'C', 'S'] and faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'], generate the deck of 52 cards, confirm the deck size and check it contains an expected card, say 'Ace of Hearts'.
perl
@suites = qw(H D C S);
@faces = qw(2 3 4 5 6 7 8 9 10 J Q K A);
@deck = map { $suite=$_; map $suite.$_, @faces; } @suites;
print 'checking deck size: ' . (@deck == 52 ? 'pass' : 'fail') . "\n";
print 'deck contains "Ace of Hearts": ' . (grep(/^HA$/, @deck) ? 'true' : 'false') . "\n";
@faces = qw(2 3 4 5 6 7 8 9 10 J Q K A);
@deck = map { $suite=$_; map $suite.$_, @faces; } @suites;
print 'checking deck size: ' . (@deck == 52 ? 'pass' : 'fail') . "\n";
print 'deck contains "Ace of Hearts": ' . (grep(/^HA$/, @deck) ? 'true' : 'false') . "\n";
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");
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");
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
(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
fantom
r := [,]
["2","3","4","5","6","7","8","9","10","J","Q","K","A"].each |Str c|
{ ["H","D","C","S"].each |Str s| { r.add([c,s]) } }
q := ["A","H"]
result := r.contains(q)
echo("Deck size=${r.size}, contains $q? -> $result")
["2","3","4","5","6","7","8","9","10","J","Q","K","A"].each |Str c|
{ ["H","D","C","S"].each |Str s| { r.add([c,s]) } }
q := ["A","H"]
result := r.contains(q)
echo("Deck size=${r.size}, contains $q? -> $result")
Perform an operation on every item of a list
Perform an operation on every item of a list, e.g.
for the list
the list of sizes of the strings, e.g.
for the list
["ox", "cat", "deer", "whale"] calculate
the list of sizes of the strings, e.g.
[2, 3, 4, 5]
perl
my @list = qw{ox cat deer whale};
my @lengths = map {length($_)} @list;
print "@list\n";
print "@lengths\n";
my @lengths = map {length($_)} @list;
print "@list\n";
print "@lengths\n";
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() + " ");
}
}
}
public static void main(String[] args) {
String[] list = {"ox", "cat", "deer", "whale"};
for (String str : list) {
System.out.println(str.length() + " ");
}
}
}
clojure
(map count ["ox" "cat" "deer" "whale"])
fantom
["ox", "cat", "deer", "whale"].map { it.size }
Split a list of things into numbers and non-numbers
Given a list that might contain e.g. a string, an integer, a float and a date,
split the list into numbers and non-numbers.
split the list into numbers and non-numbers.
perl
use Scalar::Util qw(looks_like_number);
my @things = ('hello',25,3.14,scalar(localtime(time)));
my @numbers;
my @others;
for ( @things ) {
if ( looks_like_number $_ ) {
push @numbers, $_;
} else {
push @other, $_;
}
}
my @things = ('hello',25,3.14,scalar(localtime(time)));
my @numbers;
my @others;
for ( @things ) {
if ( looks_like_number $_ ) {
push @numbers, $_;
} else {
push @other, $_;
}
}
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 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) ;
}
}
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) ;
}
}
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)}
(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.)])
fantom
things := ["hello", 25, 3.14, Time.now]
numbers := things.findType(Num#)
nonNumbers := things.exclude { numbers.contains(it) }
numbers := things.findType(Num#)
nonNumbers := things.exclude { numbers.contains(it) }
Define an empty map
perl
# %map = {}
# This was wrong, that would have created a hash with one key
# of the stringified hash reference (HASH(0xNUMBERSHERE)) and a
# value of 'undef', as well as triggering a
# "Reference found where even-sized list expected" with the warnings
# pragma enabled
my %map;
# This was wrong, that would have created a hash with one key
# of the stringified hash reference (HASH(0xNUMBERSHERE)) and a
# value of 'undef', as well as triggering a
# "Reference found where even-sized list expected" with the warnings
# pragma enabled
my %map;
java
Map map = new HashMap();
clojure
(def m {})
fantom
map := [:]
Define an unmodifiable empty map
perl
# perl does not provide unmodifiable maps/hashes, but you could use "constant
# functions", if you really need them
# 2011-07-06 Not actually true, see Hash::Util::lock_hash;
sub MAP () { {} }
# functions", if you really need them
# 2011-07-06 Not actually true, see Hash::Util::lock_hash;
sub MAP () { {} }
use Hash::Util qw/lock_hash/;
# two lines
my %hash;
lock_hash(%hash);
# or in one line
lock_hash(my %locked_hash);
# two lines
my %hash;
lock_hash(%hash);
# or in one line
lock_hash(my %locked_hash);
java
Map empty = Collections.EMPTY_MAP;
SortedMap empty = MapUtils.EMPTY_SORTED_MAP;
clojure
; Clojure maps are immutable
(def m {})
(def m {})
fantom
map := [:].ro
Define an initial map
Define the map
{circle:1, triangle:3, square:4}
perl
%map = (circle => 1, triangle => 3, square => 4);
java
Map shapes = new HashMap();
shapes.put("circle", 1);
shapes.put("triangle", 3);
shapes.put("square", 4);
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); }}
clojure
(def m '{circle 1 triangle 1 square 4})
fantom
map := ["circle":1, "triangle":2, "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"
perl
%pets = (joe => 'cat', mary => 'turtle', bill => 'canary');
print 'ok' if ($pets{'mary'});
print 'ok' if ($pets{'mary'});
%pets = (joe => 'cat', mary => 'turtle', bill => 'canary');
print 'ok' if $pets{'mary'};
print 'ok' if $pets{'mary'};
print 'ok' if $pets{mary};
print 'ok' if exists $pets{mary}
java
if (pets.containsKey("mary")) System.out.println("ok");
clojure
(if (contains? '{joe cat mary turtle bill canary} 'mary)
(println "ok"))
(println "ok"))
fantom
map := ["joe":"cat", "mary":"turtle", "bill":"canary"]
if (map.containsKey("mary")) echo("ok")
if (map.containsKey("mary")) echo("ok")
Retrieve a value from a map
Given a map pets
{joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
perl
%pets = (joe => 'cat', mary => 'turtle', bill=>'canary');
print $pets{joe};
print $pets{joe};
java
String pet = pets.get("joe");
clojure
(def pets '{joe cat mary turtle bill canary})
(println (get pets 'joe))
(println (get pets 'joe))
fantom
map := ["joe":"cat", "mary":"turtle", "bill":"canary"]
pet := map["joe"]
echo("pet=$pet")
pet := map["joe"]
echo("pet=$pet")
Add an entry to a map
Given an empty pets map, add the mapping from
"rob" to "dog"
perl
$pets{rob} = 'dog';
java
pets.put("rob", "dog");
clojure
(assoc {} 'rob 'dog)
fantom
map["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"
perl
print delete $pets{bill};
java
System.out.println(pets.remove("bill"))
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))
; 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))
fantom
pet := map.remove("bill")
echo ("pet=$pet")
echo ("pet=$pet")
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
perl
foreach(@list) {
$histogram{$_}++;
}
$histogram{$_}++;
}
$histogram{$_}++ for @list;
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));
}
}
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);
for (Object letter : list)
histogram.put(letter, !histogram.containsKey(letter) ? 1 : MapUtils.getIntValue(histogram, letter) + 1);
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))))))
(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)))) {}))
(group-by identity)
(reduce (fn [m e] (assoc m (first e) (count (second e)))) {}))
(reduce conj {} (for [[x xs] (group-by identity "abacbb")] [x (count xs)]))
(frequencies ["a","b","a","c","b","b"])
(frequencies '[a b a c b b])
fantom
list := ["a","b","a","c","b","b"]
map := [Str:Int][:]
list.each |Str s, Int i| { if(!map.containsKey(s)) map.add(s,1); else map[s] = ++map[s] }
echo (map)
map := [Str:Int][:]
list.each |Str s, Int i| { if(!map.containsKey(s)) map.add(s,1); else map[s] = ++map[s] }
echo (map)
Categorise a list
Given the list
[one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length
perl
@list = qw(one two three four five);
push @{$map{length($_)}}, $_ for (@list);
push @{$map{length($_)}}, $_ for (@list);
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);
}
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);
for (Object item : list) map.put(((String) item).length(), item);
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)))))
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"])
fantom
list := ["one", "two", "three", "four", "five"]
map := [Int:List][:]
list.each { List l := map[it.size] ?: [,]; map[it.size] = l.add(it) }
echo(map)
map := [Int:List][:]
list.each { List l := map[it.size] ?: [,]; map[it.size] = l.add(it) }
echo(map)
Perform an action if a condition is true (IF .. THEN)
Given a variable name, if the value is
"Bob", display the string "Hello, Bob!". Perform no action if the name is not equal.
perl
if ($name eq "Bob") {
print "Hello, Bob!"
}
print "Hello, Bob!"
}
print "Hello, Bob!" if $name eq "Bob";
java
if (name.equals("Bob")) {
System.out.println("Hello, Bob!");
}
System.out.println("Hello, Bob!");
}
clojure
(def person "Bob")
(if (= person "Bob")
(println "Hello, Bob!"))
(if (= person "Bob")
(println "Hello, Bob!"))
fantom
if (name=="Bob") echo("Hello, Bob!")
Perform different actions depending on a boolean condition (IF .. THEN .. ELSE)
Given a variable age, if the value is greater than 42 display
"You are old", otherwise display "You are young"
perl
if ($age > 42) {
print "You are old"
}
else {
print "You are young"
}
print "You are old"
}
else {
print "You are young"
}
print '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 old");
} else {
System.out.println("You are young");
}
System.out.println("You are " + ((age>42)?"old":"young"));
clojure
(def age 41)
(if (> age 42) "You are old" "You are young")
(if (> age 42) "You are old" "You are young")
fantom
if (age > 42)
echo("You are old")
else
echo("You are young")
echo("You are old")
else
echo("You are young")
echo((age > 42) ? "You are old" : "You are young")
Perform different actions depending on several boolean conditions (IF .. THEN .. ELSIF .. ELSE)
perl
if ($age > 84) {
print "You are really ancient";
} elsif ($age > 30) {
print "You are middle-aged";
} else {
print "You are young";
}
print "You are really ancient";
} elsif ($age > 30) {
print "You are middle-aged";
} else {
print "You are young";
}
print 'You are ',
$age > 84 ? 'really ancient!'
: $age > 30 ? 'middle-aged'
: 'young';
$age > 84 ? 'really ancient!'
: $age > 30 ? 'middle-aged'
: '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");
else if (age > 30) System.out.println("You are middle-aged");
else System.out.println("You are young");
clojure
(println
(condp <= age
84 "You are really ancient"
30 "You are middle aged"
"You are young"))
(condp <= age
84 "You are really ancient"
30 "You are middle aged"
"You are young"))
fantom
if (age > 84)
echo("You are really ancient")
else if (age > 30)
echo("You are middle-aged")
else
echo("You are young")
echo("You are really ancient")
else if (age > 30)
echo("You are middle-aged")
else
echo("You are young")
Replacing a conditional with many branches with a switch/case statement
Many languages support more compact forms of branching than just if ... then ... else such as switch or case or match. Use such a form to add an appropriate placing suffix to the numbers 1..40, e.g. 1st, 2nd, 3rd, 4th, ..., 11th, 12th, ... 39th, 40th
perl
sub suffix {
my $n = shift;
return 'th' if $n % 100 >= 4 && $n % 100 <= 20;
return 'st' if $n % 10 == 1;
return 'nd' if $n % 10 == 2;
return 'rd' if $n % 10 == 3;
return 'th';
}
foreach my $n (1..40) {
print $n.suffix($n)."\n";
}
my $n = shift;
return 'th' if $n % 100 >= 4 && $n % 100 <= 20;
return 'st' if $n % 10 == 1;
return 'nd' if $n % 10 == 2;
return 'rd' if $n % 10 == 3;
return 'th';
}
foreach my $n (1..40) {
print $n.suffix($n)."\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";
}
}
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";
}
}
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")))))
(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")))))
fantom
suffix := |Int n -> Str|
{
if ((4..20).contains(n % 100))
return "th"
switch((n.toStr)[-1])
{
case '1': return "st"
case '2': return "nd"
case '3': return "rd"
default: return "th"
}
}
(1..40).each { echo("$it${suffix(it)}") }
{
if ((4..20).contains(n % 100))
return "th"
switch((n.toStr)[-1])
{
case '1': return "st"
case '2': return "nd"
case '3': return "rd"
default: return "th"
}
}
(1..40).each { echo("$it${suffix(it)}") }
Perform an action multiple times based on a boolean condition, checked before the first action (WHILE .. DO)
Starting with a variable x=1, Print the sequence
"1,2,4,8,16,32,64,128," by doubling x and checking that x is less than 150.
perl
my $x = 1;
while($x < 150) {
print $x, ",";
$x *=2
}
while($x < 150) {
print $x, ",";
$x *=2
}
java
int x = 1;
while (x < 150) {
System.out.println(x+",");
x*=2;
}
while (x < 150) {
System.out.println(x+",");
x*=2;
}
clojure
(take-while #(< % 150) (iterate #(* 2 %) 1))
fantom
x := 1
while (x < 150) {
Env.cur.out.print("$x,")
x *= 2
}
echo
while (x < 150) {
Env.cur.out.print("$x,")
x *= 2
}
echo
Perform an action multiple times based on a boolean condition, checked after the first action (DO .. WHILE)
Simulate rolling a die until you get a six. Produce random numbers, printing them until a six is rolled. An example output might be
"4,2,1,2,6"
perl
do {
my $number = int(rand(6)+1);
print $number;
print ',' if ($number != 6);
} while ($number != 6);
my $number = int(rand(6)+1);
print $number;
print ',' if ($number != 6);
} while ($number != 6);
java
int rnd;
do {
rnd = (int)(Math.random()*6)+1;
System.out.print(rnd);
if (rnd!=6) {
System.out.print(",");
}
} while(rnd!=6);
do {
rnd = (int)(Math.random()*6)+1;
System.out.print(rnd);
if (rnd!=6) {
System.out.print(",");
}
} while(rnd!=6);
clojure
(loop [r (rand-int 6)]
(if (= r 5)
nil
(do
(println r)
(recur (rand-int 6)))))
(if (= r 5)
nil
(do
(println r)
(recur (rand-int 6)))))
fantom
rnd := 0
while(rnd != 6) {
rnd = Int.random(1..6)
Env.cur.out.print(rnd)
if (rnd != 6)
Env.cur.out.print(",")
}
echo
while(rnd != 6) {
rnd = Int.random(1..6)
Env.cur.out.print(rnd)
if (rnd != 6)
Env.cur.out.print(",")
}
echo
Perform an action a fixed number of times (FOR)
Display the string
"Hello" five times like "HelloHelloHelloHelloHello"
perl
print "Hello" x 5
print "Hello" for (1..5)
java
for(int i=0;i<5;i++) {
System.out.print("Hello");
}
System.out.print("Hello");
}
clojure
(dotimes [_ 5]
(print "Hello"))
(print "Hello"))
fantom
5.times { Env.cur.out.print("Hello") }
for (i := 0; i < 5; i++)
Env.cur.out.print("Hello")
Env.cur.out.print("Hello")
(1..5).each { Env.cur.out.print("Hello") }
Perform an action a fixed number of times with a counter
Display the string
"10 .. 9 .. 8 .. 7 .. 6 .. 5 .. 4 .. 3 .. 2 .. 1 .. Liftoff!"
perl
for (my $i = 10; $i > 0; $i--) {
print "$i .. ";
}
print "Liftoff!";
print "$i .. ";
}
print "Liftoff!";
print "$_ .. " for reverse 1..10;
print "Liftoff!";
print "Liftoff!";
java
for(int i=10; i>=1; i--) {
System.out.print(i + " .. ");
}
System.out.print("Liftoff!");
System.out.print(i + " .. ");
}
System.out.print("Liftoff!");
clojure
(dotimes [i 10]
(print (str (- 10 i) " .. ")))
(println "Liftoff!")
(print (str (- 10 i) " .. ")))
(println "Liftoff!")
fantom
(10..1).each { Env.cur.out.print("$it .. ") }
Env.cur.out.print("Liftoff!")
Env.cur.out.print("Liftoff!")
for (i := 10; i >= 1; i--)
Env.cur.out.print("$i .. ")
Env.cur.out.print("Liftoff!")
Env.cur.out.print("$i .. ")
Env.cur.out.print("Liftoff!")
Read the contents of a file into a string
perl
@file = read()
open(my $fh, '<', $path) or die "can't open $path: $!";
$string = do { local $/; <$fh> };
close $fh;
$string = do { local $/; <$fh> };
close $fh;
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);
}
try
{
raf = new RandomAccessFile("Solution399.java", "r");
buffer = new byte[(int)raf.length()]; raf.read(buffer);
text = new String(buffer);
}
clojure
(slurp "/tmp/foobar")
fantom
contents := File(`file.text`).readAllStr
Process a file one line at a time
Open the source file to your solution and print each line in the file, prefixed by the line number, like:
1> First line of file
2> Second line of file
3> Third line of file
1> First line of file
2> Second line of file
3> Third line of file
perl
open(my $fh, '<', $path) or die "can't open $path: $!";
$c = 1;
print $c++ . "> $_" for (<$fh>);
close $fh;
$c = 1;
print $c++ . "> $_" for (<$fh>);
close $fh;
open my $fh, '<', $path or die "Can't open $path: $!";
while (<$fh>) {
print "$.> $_";
}
while (<$fh>) {
print "$.> $_";
}
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
}
}
}
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);
}
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);
}
clojure
(defn read-line-by-line [fn]
(reduce str (map (partial format "%d> %s\n")
(iterate inc 1)
(read-lines fn))))
(reduce str (map (partial format "%d> %s\n")
(iterate inc 1)
(read-lines fn))))
fantom
File(`input.text`).readAllLines.each |Str s, Int i| { echo("${i+1}> $s") }
Write a string to a file
perl
open(my $fh, '>', $path) or die "can't open $path: $!";
print $fh "This line overwites file contents!";
close $fh;
print $fh "This line overwites file contents!";
close $fh;
java
FileWriter fw = null;
try
{
fw = new FileWriter("test.txt");
fw.write("This line overwites file contents!");
}
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!");
}
try
{
pw = new PrintWriter(new BufferedWriter(new FileWriter("test.txt")));
pw.print("This line overwites file contents!");
}
clojure
(with-out-writer "output.txt" (println "Hello file!"))
fantom
File(`out.txt`).out.writeChars("some text").flush
Append to a file
perl
open(my $fh, '>>', $path) or die "can't open $path: $!";
print $fh "This line is appended to the file!";
close $fh;
print $fh "This line is appended to the file!";
close $fh;
java
FileWriter fw = null;
try
{
fw = new FileWriter("test.txt", true);
fw.write("This line appended to file!");
}
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!");
}
try
{
pw = new PrintWriter(new BufferedWriter(new FileWriter("test.txt", true)));
pw.print("This line appended to file!");
}
clojure
(with-out-append-writer "output.txt" (println "This is appended to the file"))
fantom
File(`out.txt`).out(true).writeChars("some text").flush
Process each file in a directory
perl
use File::Glob;
for (<*>) {
process_file($_) if (-f);
}
for (<*>) {
process_file($_) if (-f);
}
java
for (File file : (new File("c:\\")).listFiles()) process(file);
clojure
; (defn process-file [f] "process one file" body...)
(map process-file (.listFiles (File. ".")))
(map process-file (.listFiles (File. ".")))
fantom
File(`./`).list.each { process(it) }
Process each file in a directory recursively
perl
use File::Glob;
process_directory(".");
sub process_directory {
my $dir = shift;
for my $file (<$dir/*>) {
next unless (-r $file);
if (-f $file) {
process_file($file);
} elsif (-d $file) {
process_directory($file);
}
}
}
process_directory(".");
sub process_directory {
my $dir = shift;
for my $file (<$dir/*>) {
next unless (-r $file);
if (-f $file) {
process_file($file);
} elsif (-d $file) {
process_directory($file);
}
}
}
use File::Find ();
# Traverse desired filesystems
sub process_directory {
my $directory = shift;
File::Find::find({wanted => \&wanted}, $directory);
}
sub wanted {
process_file( $File::Find::name );
}
# Traverse desired filesystems
sub process_directory {
my $directory = shift;
File::Find::find({wanted => \&wanted}, $directory);
}
sub wanted {
process_file( $File::Find::name );
}
java
processDirectory(new File("c:\\"));
clojure
; (defn process-file [f] "process one file" body...)
(map process-file (file-seq (File. ".")))
(map process-file (file-seq (File. ".")))
fantom
File(`./`).walk { process(it) }
Parse a date and time from a string
Given the string
"2008-05-06 13:29", parse it as a date representing 6th March, 2008 1:29:00pm in the local time zone.
perl
#! /usr/bin/perl
# -*- Mode: CPerl -*-
use strict;
use POSIX;
# Given the string "2008-05-06 13:29", parse it as a date
# representing 6th March, 2008 1:29:00pm in the local time zone.
my $ds = "2008-05-06 13:29";
my $y;
my $m;
my $d;
my $hr;
my $mn;
print "Original: ",$ds,"\n";
if ( $ds =~ /(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})/ ){
$y = $1 - 1900;
$m = $2;
$d = $3;
$hr = $4;
$mn = $5;
printf "Nominal: %s\n",
strftime("%e %B, %Y %l:%M:%S%P",0, $mn , $hr, $d, $m,$y);
my $eth = "";
if ( $d == 1 ){
$eth = "st";
} elsif ( $d == 2 ){
$eth = "nd";
} elsif ( $d == 3 ){
$eth = "rd";
} else {
$eth = "th";
}
printf "As required: %d%s %s\n",$d,$eth,
strftime("%B, %Y %l:%M:%S%P",0, $mn , $hr, $d, $m,$y);
}
#eos
# -*- Mode: CPerl -*-
use strict;
use POSIX;
# Given the string "2008-05-06 13:29", parse it as a date
# representing 6th March, 2008 1:29:00pm in the local time zone.
my $ds = "2008-05-06 13:29";
my $y;
my $m;
my $d;
my $hr;
my $mn;
print "Original: ",$ds,"\n";
if ( $ds =~ /(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})/ ){
$y = $1 - 1900;
$m = $2;
$d = $3;
$hr = $4;
$mn = $5;
printf "Nominal: %s\n",
strftime("%e %B, %Y %l:%M:%S%P",0, $mn , $hr, $d, $m,$y);
my $eth = "";
if ( $d == 1 ){
$eth = "st";
} elsif ( $d == 2 ){
$eth = "nd";
} elsif ( $d == 3 ){
$eth = "rd";
} else {
$eth = "th";
}
printf "As required: %d%s %s\n",$d,$eth,
strftime("%B, %Y %l:%M:%S%P",0, $mn , $hr, $d, $m,$y);
}
#eos
# Shurely you mean 6th MAY? If not, oh well
use Time::Piece;
my $dt_str = '2008-05-06 13:29';
my $tp = Time::Piece->strptime( $dt_str, '%Y-%m-%d %H:%M');
print $tp,"\n";
use Time::Piece;
my $dt_str = '2008-05-06 13:29';
my $tp = Time::Piece->strptime( $dt_str, '%Y-%m-%d %H:%M');
print $tp,"\n";
java
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = df.parse("2008-05-06 13:29");
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");
DateTime dt = fmt.parseDateTime("2008-05-06 13:29");
clojure
(.. (SimpleDateFormat. "yyyy-MM-dd HH:mm")
(parse "2008-05-06 13:29"))
(parse "2008-05-06 13:29"))
fantom
dt := DateTime.fromLocale("2008-05-06 13:29", "YYYY-MM-DD hh:mm")
Display information about a date
Display the day of month, day of year, month name and day name of the day 8 days from now.
perl
#! /usr/bin/perl
# -*- Mode: CPerl -*-
use strict;
use Date::Calc qw(:all);
my $days_in_future = $ARGV[0];
$days_in_future = 8 unless $days_in_future;
my ($year,$month,$day, $hour,$min,$sec, $doy,$dow,$dst) = Localtime();
my ($fyear,$fmonth,$fday) = Add_Delta_Days($year,$month,$day,$days_in_future);
printf "Now: %d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d\n",
$year,$month,$day,$hour,$min,$sec;
printf "Then: %d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d\n",
$fyear,$fmonth,$fday,$hour,$min,$sec;
printf "Then: day of month: %d\n",$fday;
printf "Then: day of year: %d\n",Day_of_Year($fyear,$fmonth,$fday);
printf "Then: day of name: %s\n",
Day_of_Week_to_Text(Day_of_Week($fyear,$fmonth,$fday));
printf "Then: month name: %s\n",Month_to_Text($fmonth);
#eos
# -*- Mode: CPerl -*-
use strict;
use Date::Calc qw(:all);
my $days_in_future = $ARGV[0];
$days_in_future = 8 unless $days_in_future;
my ($year,$month,$day, $hour,$min,$sec, $doy,$dow,$dst) = Localtime();
my ($fyear,$fmonth,$fday) = Add_Delta_Days($year,$month,$day,$days_in_future);
printf "Now: %d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d\n",
$year,$month,$day,$hour,$min,$sec;
printf "Then: %d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d\n",
$fyear,$fmonth,$fday,$hour,$min,$sec;
printf "Then: day of month: %d\n",$fday;
printf "Then: day of year: %d\n",Day_of_Year($fyear,$fmonth,$fday);
printf "Then: day of name: %s\n",
Day_of_Week_to_Text(Day_of_Week($fyear,$fmonth,$fday));
printf "Then: month name: %s\n",Month_to_Text($fmonth);
#eos
use Time::Piece;
use Time::Seconds;
my $t = localtime;
my $t_8 = $t + (ONE_DAY * 8);
printf "Now: %d, %d, %s, %s\n",
$t->day_of_month, $t->day_of_year, $t->fullmonth, $t->fullday;
printf "Then: %d, %d, %s, %s\n",
$t_8->day_of_month, $t_8->day_of_year, $t_8->fullmonth, $t_8->fullday;
use Time::Seconds;
my $t = localtime;
my $t_8 = $t + (ONE_DAY * 8);
printf "Now: %d, %d, %s, %s\n",
$t->day_of_month, $t->day_of_year, $t->fullmonth, $t->fullday;
printf "Then: %d, %d, %s, %s\n",
$t_8->day_of_month, $t_8->day_of_year, $t_8->fullmonth, $t_8->fullday;
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()));
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()));
clojure
(let [cal (Calendar/getInstance)]
(.add cal Calendar/DAY_OF_YEAR 8)
(println (.format (SimpleDateFormat. "d, D, MMMM, EEEE")
(.getTime cal))))
(.add cal Calendar/DAY_OF_YEAR 8)
(println (.format (SimpleDateFormat. "d, D, MMMM, EEEE")
(.getTime cal))))
fantom
date := Date.today + 8day
echo(date.day)
echo(date.dayOfYear)
echo(date.month.localeFull)
echo(date.weekday.localeFull)
echo(date.day)
echo(date.dayOfYear)
echo(date.month.localeFull)
echo(date.weekday.localeFull)
Display a date in different locales
Display a language/locale friendly version of New Year's Day for 2009 for several languages/locales. E.g. for languages English, French, German, Italian, Dutch the output might be something like:
Thursday, January 1, 2009
jeudi 1 janvier 2009
giovedì 1 gennaio 2009
Donnerstag, 1. Januar 2009
donderdag 1 januari 2009
(Indicate in comments where possible if any language specific or operating system configuration needs to be in place.)
Thursday, January 1, 2009
jeudi 1 janvier 2009
giovedì 1 gennaio 2009
Donnerstag, 1. Januar 2009
donderdag 1 januari 2009
(Indicate in comments where possible if any language specific or operating system configuration needs to be in place.)
perl
#!/usr/bin/perl
use warnings;
use strict;
use locale;
use POSIX qw(strftime);
use Time::Local;
my $date=timegm(0,0,0, 1,0,101); #00:00:00 01/01/2001
my $str_time = strftime "%c", gmtime;
print "Date: $str_time\n";
use warnings;
use strict;
use locale;
use POSIX qw(strftime);
use Time::Local;
my $date=timegm(0,0,0, 1,0,101); #00:00:00 01/01/2001
my $str_time = strftime "%c", gmtime;
print "Date: $str_time\n";
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()));
}
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()));
}
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))))
(doseq [locale ["en" "fr" "it" "de" "nl"]]
(println (.format (DateFormat/getDateInstance DateFormat/FULL
(Locale. locale))
time))))
fantom
// May require modification of Fantom distribution t
// for undefined locales - basically just create a '<locale-name>.props' plain text file with values like this:
// sunAbbr=Sun
// ..
// sunFull=Sunday
["en", "fr", "ru"].map { Locale(it) }.each |Locale l| {
l.use { echo(Date(2009, Month.jan, 1).toLocale("WWWW, MMMM D, YYYY")) }
}
// for undefined locales - basically just create a '<locale-name>.props' plain text file with values like this:
// sunAbbr=Sun
// ..
// sunFull=Sunday
["en", "fr", "ru"].map { Locale(it) }.each |Locale l| {
l.use { echo(Date(2009, Month.jan, 1).toLocale("WWWW, MMMM D, YYYY")) }
}
Display the current date and time
Create a Date object representing the current date and time. Print it out.
If you can also do this without creating a Date object you can show that too.
If you can also do this without creating a Date object you can show that too.
perl
use Class::Date;
my $date = Class::Date->now();
print $date->string()."\n";
print localtime()."\n";
my $date = Class::Date->now();
print $date->string()."\n";
print localtime()."\n";
use Time::Piece ();
# Date object
my $date = Time::Piece::localtime;
print "$date\n";
# no object
print scalar(localtime),"\n";
# Date object
my $date = Time::Piece::localtime;
print "$date\n";
# no object
print scalar(localtime),"\n";
java
import java.util.Date;
public class SolutionXX {
public static void main(String[] args) {
Date now = new Date();
System.out.println(now.toString());
}
}
public class SolutionXX {
public static void main(String[] args) {
Date now = new Date();
System.out.println(now.toString());
}
}
clojure
(import 'java.util.Date)
(println (str (Date.)))
(println (str (Date.)))
fantom
echo(DateTime.now)
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.
perl
{ package Greeter;
sub new {
my $self = {};
my $type = shift;
$self->{'whom'} = shift;
bless $self, $type;
}
sub greet {
my $self = shift;
print "Hello " . $self->{'whom'} . "!\n";
}
}
my $greeter = Greeter->new("world");
$greeter->greet();
sub new {
my $self = {};
my $type = shift;
$self->{'whom'} = shift;
bless $self, $type;
}
sub greet {
my $self = shift;
print "Hello " . $self->{'whom'} . "!\n";
}
}
my $greeter = Greeter->new("world");
$greeter->greet();
{
package Greeter;
sub new {
my $class = shift;
my $whom = shift or die 'Need a name to greet';
bless \$whom, $class;
}
sub greet {
my $self = shift;
print "Hello $$self!\n";
}
}
my $greeter = Greeter->new("Bob");
$greeter->greet();
package Greeter;
sub new {
my $class = shift;
my $whom = shift or die 'Need a name to greet';
bless \$whom, $class;
}
sub greet {
my $self = shift;
print "Hello $$self!\n";
}
}
my $greeter = Greeter->new("Bob");
$greeter->greet();
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();
}
}
{
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();
}
}
clojure
(defprotocol IGreeter
(greet [this]))
(deftype Greeter [whom]
IGreeter
(greet [this]
(println (str "Hello, " whom))))
(greet (Greeter. "world"))
(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"))
{:whom whom})
(defn greet [g]
(println (str "Hello, " (:whom g))))
(greet (greeter "world"))
fantom
class Greeter
{
private Str whom
new make(Str whom) { this.whom = whom }
Void greet() { echo("Hello, $whom") }
}
Greeter("world").greet
{
private Str whom
new make(Str whom) { this.whom = whom }
Void greet() { echo("Hello, $whom") }
}
Greeter("world").greet
Instantiate object with mutable state
Reimplement the Greeter class so that the
For example, if the greetee is changed to
Hello, Tommy!
The getter would then be used to display the line:
I have just greeted Tommy.
'whom' property or data member remains private but is mutable, and is provided with getter and setter methods. Invoke the setter to change the greetee, invoke 'greet', then use the getter in displaying the line, "I have just greeted {whom}.".
For example, if the greetee is changed to
'Tommy' using the setter, the 'greet' method would display:
Hello, Tommy!
The getter would then be used to display the line:
I have just greeted Tommy.
perl
package Greeter;
sub new {
my ($class, $whom) = @_;
bless {whom => $whom}, $class;
}
sub whom {
my ($self, $whom) = @_;
if ($whom) { $self->{whom} = $whom; }
else { return $self->{whom} }
}
sub greet {
my ($self) = @_;
my $whom = $self->{whom};
print "Hello, $whom!\n";
}
package main;
my $g = new Greeter ("world");
$g->greet;
$g->whom("Tommy");
$g->greet;
print "I have just greeted " . $g->whom . "\n";
sub new {
my ($class, $whom) = @_;
bless {whom => $whom}, $class;
}
sub whom {
my ($self, $whom) = @_;
if ($whom) { $self->{whom} = $whom; }
else { return $self->{whom} }
}
sub greet {
my ($self) = @_;
my $whom = $self->{whom};
print "Hello, $whom!\n";
}
package main;
my $g = new Greeter ("world");
$g->greet;
$g->whom("Tommy");
$g->greet;
print "I have just greeted " . $g->whom . "\n";
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() + ".");
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() + ".");
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)))
"."))
(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)))
"."))
fantom
class Greeter
{
new make(Str whom) { this.whom = whom }
Void greet() { echo("Hello, $whom!") }
Str whom
}
greeter := Greeter("world")
greeter.greet
greeter.whom = "Tommy"
echo("I have just greeted ${greeter.whom}.")
{
new make(Str whom) { this.whom = whom }
Void greet() { echo("Hello, $whom!") }
Str whom
}
greeter := Greeter("world")
greeter.greet
greeter.whom = "Tommy"
echo("I have just greeted ${greeter.whom}.")
Implement Inheritance Heirarchy
Implement a Shape abstract class which will form the base of an inheritance hierarchy that models 2D geometric shapes. It will have:
* A non-mutable
* A
* A
* A non-mutable
'name' property or data member set by derived or descendant classes at construction time
* A
'area' method intended to be overridden by derived or descendant classes ( double precision floating point return value)
* A
'print' method (also for overriding) will display the shape's name, area, and all shape-specific values
Two derived or descendant classes will be created:
* Circle -> Constructor requires a 'radius' argument, and a 'circumference' method to be implemented
* Rectangle -> Constructor requires 'length' and 'breadth' arguments, and a 'perimeter' method to be implemented
Instantiate an object of each class, and invoke each objects 'print' method to show relevant details.
perl
package Shapes;
use MooseX::Declare;
class Shape {
use MooseX::ABC;
requires qw/area print/;
has 'name' => (is => 'ro', isa => 'Str', default => '', required => 0, init_arg => undef );
}
class Circle extends Shape {
use constant PI => 4 * atan2(1, 1);
has '+name' => ( default => 'circle' );
has 'radius' => (is => 'ro', isa => 'Num', required => 1, init_arg => 'r' );
sub area { PI * ( $_[0]->radius ** 2 ) }
sub circumference { 2 * PI * ( $_[0]->radius ** 2 ) }
sub print {
my $self = shift;
printf <<"END_OF_BLOCK", map { $self->$_ } qw/name radius area circumference/;
I am a '%s' with
Radius: %.2f
Area: %.2f
Circumference: %.2f
END_OF_BLOCK
}
}
class Rectangle extends Shape {
has '+name' => ( default => 'rectangle' );
has 'length' => (is => 'ro', isa => 'Num', required => 1, init_arg => 'l' );
has 'breadth' => (is => 'ro', isa => 'Num', required => 1, init_arg => 'b' );
sub area { $_[0]->length * $_[0]->breadth }
sub perimeter { 2 * ( $_[0]->length + $_[0]->breadth ) }
sub print {
my $self = shift;
printf <<"END_OF_BLOCK", map { $self->$_ } qw/name length breadth area perimeter/;
I am a '%s' with
Length, Width: %.2f, %.2f
Area: %.2f
Perimeter: %.2f
END_OF_BLOCK
}
}
1;
package main;
my @shapes = ( Circle->new( r => 4.2 ), Rectangle->new(l => 2.7, b => 3.1),
Rectangle->new(l => 6.2, b => 2.6), Circle->new( r => 17.3) );
$_->print for @shapes;
use MooseX::Declare;
class Shape {
use MooseX::ABC;
requires qw/area print/;
has 'name' => (is => 'ro', isa => 'Str', default => '', required => 0, init_arg => undef );
}
class Circle extends Shape {
use constant PI => 4 * atan2(1, 1);
has '+name' => ( default => 'circle' );
has 'radius' => (is => 'ro', isa => 'Num', required => 1, init_arg => 'r' );
sub area { PI * ( $_[0]->radius ** 2 ) }
sub circumference { 2 * PI * ( $_[0]->radius ** 2 ) }
sub print {
my $self = shift;
printf <<"END_OF_BLOCK", map { $self->$_ } qw/name radius area circumference/;
I am a '%s' with
Radius: %.2f
Area: %.2f
Circumference: %.2f
END_OF_BLOCK
}
}
class Rectangle extends Shape {
has '+name' => ( default => 'rectangle' );
has 'length' => (is => 'ro', isa => 'Num', required => 1, init_arg => 'l' );
has 'breadth' => (is => 'ro', isa => 'Num', required => 1, init_arg => 'b' );
sub area { $_[0]->length * $_[0]->breadth }
sub perimeter { 2 * ( $_[0]->length + $_[0]->breadth ) }
sub print {
my $self = shift;
printf <<"END_OF_BLOCK", map { $self->$_ } qw/name length breadth area perimeter/;
I am a '%s' with
Length, Width: %.2f, %.2f
Area: %.2f
Perimeter: %.2f
END_OF_BLOCK
}
}
1;
package main;
my @shapes = ( Circle->new( r => 4.2 ), Rectangle->new(l => 2.7, b => 3.1),
Rectangle->new(l => 6.2, b => 2.6), Circle->new( r => 17.3) );
$_->print for @shapes;
{
package Shapes;
sub new {
my $class = shift;
die 'Invalid parameters' if (@_ % 2);
my %parameters = @_;
die 'Missing name' unless defined $parameters{name};
bless \%parameters, $class
}
sub area {
die
'area() method must be implemented by ',__PACKAGE__.' subclasses';
}
sub print {
my $self = shift;
printf "Name: \t%s\n", $self->{name};
printf "Area: \t%.2f\n", $self->area();
}
}
{
package Circle;
use parent -norequire, 'Shapes';
use Scalar::Util qw/looks_like_number/;
use Math::Trig;
sub new {
my $class = shift;
my $self = $class->SUPER::new(name => 'Circle', @_);
die 'Missing radius' unless defined($self->{radius});
die 'Invalid radius (not a number)'
unless looks_like_number($self->{radius});
$self
}
sub area {
my $self = shift;
pi * ($self->{radius} ** 2)
}
sub circumference {
my $self = shift;
2 * pi * $self->{radius};
}
sub print {
my $self = shift;
$self->SUPER::print;
printf "Circumference: \t%.2f\n", $self->circumference;
}
}
{
package Rectangle;
use parent -norequire, 'Shapes';
use Scalar::Util qw/looks_like_number/;
sub new {
my $class = shift;
my $self = $class->SUPER::new(name => 'Rectangle', @_);
do {
die "Missing $_" unless defined($self->{$_});
die "Invalid $_" unless looks_like_number($self->{$_});
} for qw/length breadth/;
$self;
}
sub area {
my $self = shift;
$self->{length} * $self->{breadth}
}
sub print {
my $self = shift;
$self->SUPER::print();
do {
printf ucfirst($_).": \t%.2f\n", $self->{$_}
} for qw/length breadth/;
}
}
package main;
my @shapes = ( Circle->new( radius => 4.2 ),
Rectangle->new(length => 2.7, breadth => 3.1),
Rectangle->new(length => 6.2, breadth => 2.6),
Circle->new( radius => 17.3) );
$_->print for @shapes;
package Shapes;
sub new {
my $class = shift;
die 'Invalid parameters' if (@_ % 2);
my %parameters = @_;
die 'Missing name' unless defined $parameters{name};
bless \%parameters, $class
}
sub area {
die
'area() method must be implemented by ',__PACKAGE__.' subclasses';
}
sub print {
my $self = shift;
printf "Name: \t%s\n", $self->{name};
printf "Area: \t%.2f\n", $self->area();
}
}
{
package Circle;
use parent -norequire, 'Shapes';
use Scalar::Util qw/looks_like_number/;
use Math::Trig;
sub new {
my $class = shift;
my $self = $class->SUPER::new(name => 'Circle', @_);
die 'Missing radius' unless defined($self->{radius});
die 'Invalid radius (not a number)'
unless looks_like_number($self->{radius});
$self
}
sub area {
my $self = shift;
pi * ($self->{radius} ** 2)
}
sub circumference {
my $self = shift;
2 * pi * $self->{radius};
}
sub print {
my $self = shift;
$self->SUPER::print;
printf "Circumference: \t%.2f\n", $self->circumference;
}
}
{
package Rectangle;
use parent -norequire, 'Shapes';
use Scalar::Util qw/looks_like_number/;
sub new {
my $class = shift;
my $self = $class->SUPER::new(name => 'Rectangle', @_);
do {
die "Missing $_" unless defined($self->{$_});
die "Invalid $_" unless looks_like_number($self->{$_});
} for qw/length breadth/;
$self;
}
sub area {
my $self = shift;
$self->{length} * $self->{breadth}
}
sub print {
my $self = shift;
$self->SUPER::print();
do {
printf ucfirst($_).": \t%.2f\n", $self->{$_}
} for qw/length breadth/;
}
}
package main;
my @shapes = ( Circle->new( radius => 4.2 ),
Rectangle->new(length => 2.7, breadth => 3.1),
Rectangle->new(length => 6.2, breadth => 2.6),
Circle->new( radius => 17.3) );
$_->print for @shapes;
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();
* 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();
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)))
(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)))
fantom
abstract class Shape
{
const Str name
new make(Str name) { this.name = name }
abstract Float area()
abstract Void print()
}
class Circle : Shape
{
private Float radius
new make(Float radius) : super("circle") { this.radius = radius }
Float circumference() { return 2 * Float.pi * radius }
override Float area() { return Float.pi * radius.pow(2.0f) }
override Void print()
{
echo("I am a $name with radius $radius, area $area
and circumference $circumference")
}
}
class Rectangle : Shape
{
private Float length
private Float breadth
new make(Float length, Float breadth) : super("rectangle")
{
this.length = length
this.breadth = breadth
}
Float perimeter() { return 2 * (length + breadth) }
override Float area() { return length * breadth }
override Void print()
{
echo("I am a $name with length $length, breadth $breadth,
area $area and perimeter $perimeter")
}
}
circle := Circle(4.0f)
circle.print
rectangle := Rectangle(2.0f, 5.5f)
rectangle.print
{
const Str name
new make(Str name) { this.name = name }
abstract Float area()
abstract Void print()
}
class Circle : Shape
{
private Float radius
new make(Float radius) : super("circle") { this.radius = radius }
Float circumference() { return 2 * Float.pi * radius }
override Float area() { return Float.pi * radius.pow(2.0f) }
override Void print()
{
echo("I am a $name with radius $radius, area $area
and circumference $circumference")
}
}
class Rectangle : Shape
{
private Float length
private Float breadth
new make(Float length, Float breadth) : super("rectangle")
{
this.length = length
this.breadth = breadth
}
Float perimeter() { return 2 * (length + breadth) }
override Float area() { return length * breadth }
override Void print()
{
echo("I am a $name with length $length, breadth $breadth,
area $area and perimeter $perimeter")
}
}
circle := Circle(4.0f)
circle.print
rectangle := Rectangle(2.0f, 5.5f)
rectangle.print
Implement and use an Interface
Create a Serializable interface consisting of
* Accept a stream or handle or descriptor argument for the source or destination
* Save to destination or restore from source the properties or data members of the implementing class (restrict yourself to the primitive types
Next, create a Person class which has
'save' and 'restore' methods, each of which:
* Accept a stream or handle or descriptor argument for the source or destination
* Save to destination or restore from source the properties or data members of the implementing class (restrict yourself to the primitive types
'int' and 'string')
Next, create a Person class which has
'name' and 'age' properties or data members and implements this interface. Instantiate a Person object, save it to a serial stream, and instantiate a new Person object by restoring it from the serial stream.
perl
package Person;
use Moose;
use MooseX::Storage;
with Storage('format' => 'JSON', 'io' => 'File');
has 'name' => (is => 'rw', isa => 'Str');
has 'age' => (is => 'rw', isa => 'Int');
1;
Person->new( name => 'David B.', age => 28)->store('person.json');
my $p = Person->load('person.json');
use Moose;
use MooseX::Storage;
with Storage('format' => 'JSON', 'io' => 'File');
has 'name' => (is => 'rw', isa => 'Str');
has 'age' => (is => 'rw', isa => 'Int');
1;
Person->new( name => 'David B.', age => 28)->store('person.json');
my $p = Person->load('person.json');
{
package Serializable;
use Role::Basic;
use Storable qw'store_fd retrieve_fd';
use Scalar::Util 'blessed';
use IO::Handle;
use Carp;
sub save {
my $self = shift;
my $fd = shift or croak 'Needs target file handle';
$DB::single = (1);
store_fd($self, $fd);
}
sub restore {
my $class = shift;
my $fd = shift or croak 'Needs source file handle';
my $self = retrieve_fd( $fd );
bless $self, $class
}
}
{
package Person;
use Role::Basic 'with';
use Scalar::Util 'looks_like_number';
use Carp;
with 'Serializable';
sub new {
my $class = shift;
croak 'Invalid parameters' if (@_ % 2);
%parameters = @_;
do {
croak "Missing $_" unless defined $parameters{$_}
} for qw/name age/;
croak 'Invalid age' unless looks_like_number($parameters{age});
bless \%parameters, $class
}
sub name {
$self{name}
}
sub age {
$self{age}
}
}
use IO::Handle;
my $p1 = Person->new(age => 42, name => 'Milly Fogg');
open my $fh, '+>', 'person.store';
$p1->save( $fh );
seek $fh, 0, SEEK_SET;
my $p2 = Person->restore( $fh );
package Serializable;
use Role::Basic;
use Storable qw'store_fd retrieve_fd';
use Scalar::Util 'blessed';
use IO::Handle;
use Carp;
sub save {
my $self = shift;
my $fd = shift or croak 'Needs target file handle';
$DB::single = (1);
store_fd($self, $fd);
}
sub restore {
my $class = shift;
my $fd = shift or croak 'Needs source file handle';
my $self = retrieve_fd( $fd );
bless $self, $class
}
}
{
package Person;
use Role::Basic 'with';
use Scalar::Util 'looks_like_number';
use Carp;
with 'Serializable';
sub new {
my $class = shift;
croak 'Invalid parameters' if (@_ % 2);
%parameters = @_;
do {
croak "Missing $_" unless defined $parameters{$_}
} for qw/name age/;
croak 'Invalid age' unless looks_like_number($parameters{age});
bless \%parameters, $class
}
sub name {
$self{name}
}
sub age {
$self{age}
}
}
use IO::Handle;
my $p1 = Person->new(age => 42, name => 'Milly Fogg');
open my $fh, '+>', 'person.store';
$p1->save( $fh );
seek $fh, 0, SEEK_SET;
my $p2 = Person->restore( $fh );
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();
}
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();
}
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))
{: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))
fantom
@Serializable
class Person
{
Str name
Int age
new make(|This| f) { f(this) }
}
person := Person() { name="Tom Bones"; age=23 }
File(`tommy.dump`).out.writeObj(person).close
Person tom := File(`tommy.dump`).in.readObj
class Person
{
Str name
Int age
new make(|This| f) { f(this) }
}
person := Person() { name="Tom Bones"; age=23 }
File(`tommy.dump`).out.writeObj(person).close
Person tom := File(`tommy.dump`).in.readObj
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.
perl
# requires libwww-perl
use LWP::Simple;
if (grep /perl/, get('http://langref.org/')) {
print 'perl appears on langref.org';
} else {
print 'perl does not appear on langref.org';
}
use LWP::Simple;
if (grep /perl/, get('http://langref.org/')) {
print 'perl appears on langref.org';
} else {
print 'perl does not appear on langref.org';
}
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();
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();
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")))
(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")))
fantom
language := "Fantom"
url := `http://langref.org/`
response := WebClient(url).getStr
if (Regex.fromStr("\\b$language.lower\\b").matcher(response).find)
echo("Language $language appears at ${url}.")
url := `http://langref.org/`
response := WebClient(url).getStr
if (Regex.fromStr("\\b$language.lower\\b").matcher(response).find)
echo("Language $language appears at ${url}.")
Process an XML document
Given the XML Document:
<shopping>
<item name=
<item name=
</shopping>
Print out the total cost of the items, e.g. $14.50
<shopping>
<item name=
"bread" quantity="3" price="2.50"/>
<item name=
"milk" quantity="2" price="3.50"/>
</shopping>
Print out the total cost of the items, e.g. $14.50
perl
#! /usr/bin/perl
# -*- Mode: CPerl -*-
use strict;
use XML::Simple;
use Data::Dumper;
# 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
my $xml =
" <shopping>\n"
." <item name=\"bread\" quantity=\"3\" price=\"2.50\"/>\n"
." <item name=\"milk\" quantity=\"2\" price=\"3.50\"/>\n"
." </shopping>\n";
my $xs = XML::Simple->new();
my $ref = $xs->XMLin($xml);
my $stuff = ${$ref}{item};
my $q;
my $p;
my $t;
my $z;
foreach my $item ( sort keys %{$stuff}){
$q = ${$stuff}{$item}{quantity};
$p = ${$stuff}{$item}{price};
$z = $q*$p;
printf "%5.5s %2d @\$%5.2f = \$%5.2f\n",$item,$q,$p,$z;
$t += $z;
}
printf "Total \$%5.2f\n",$t;
#eos
# -*- Mode: CPerl -*-
use strict;
use XML::Simple;
use Data::Dumper;
# 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
my $xml =
" <shopping>\n"
." <item name=\"bread\" quantity=\"3\" price=\"2.50\"/>\n"
." <item name=\"milk\" quantity=\"2\" price=\"3.50\"/>\n"
." </shopping>\n";
my $xs = XML::Simple->new();
my $ref = $xs->XMLin($xml);
my $stuff = ${$ref}{item};
my $q;
my $p;
my $t;
my $z;
foreach my $item ( sort keys %{$stuff}){
$q = ${$stuff}{$item}{quantity};
$p = ${$stuff}{$item}{price};
$z = $q*$p;
printf "%5.5s %2d @\$%5.2f = \$%5.2f\n",$item,$q,$p,$z;
$t += $z;
}
printf "Total \$%5.2f\n",$t;
#eos
use strict;
use XML::Twig;
use Data::Dumper;
my $xml = <<ENDXML;
<shopping>
<item name="bread" quantity="3" price="2.50"/>
<item name="milk" quantity="2" price="3.50"/>
</shopping>
ENDXML
my $xt = XML::Twig->parse( $xml );
my $price;
foreach my $item ($xt->root->children('item')) {
$price += ($item->{att}{price} * $item->{att}{quantity})
}
printf "Total Cost: %.2f\n", $price
use XML::Twig;
use Data::Dumper;
my $xml = <<ENDXML;
<shopping>
<item name="bread" quantity="3" price="2.50"/>
<item name="milk" quantity="2" price="3.50"/>
</shopping>
ENDXML
my $xt = XML::Twig->parse( $xml );
my $price;
foreach my $item ($xt->root->children('item')) {
$price += ($item->{att}{price} * $item->{att}{quantity})
}
printf "Total Cost: %.2f\n", $price
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();
}
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();
}
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
(->> (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
fantom
sum := 0.0
root := XParser(File(`shop.xml`).in).parseDoc.root
if (root.name == "shopping")
{
root.elems.each
{
if (it.name == "item")
{
quantity := Int.fromStr(it.get("quantity"))
price := Decimal.fromStr(it.get("price"))
sum += quantity * price;
}
}
}
echo("\$$sum")
root := XParser(File(`shop.xml`).in).parseDoc.root
if (root.name == "shopping")
{
root.elems.each
{
if (it.name == "item")
{
quantity := Int.fromStr(it.get("quantity"))
price := Decimal.fromStr(it.get("price"))
sum += quantity * price;
}
}
}
echo("\$$sum")
create some XML programmatically
Given the following CSV:
bread,3,2.50
milk,2,3.50
Produce the equivalent information in XML, e.g.:
<shopping>
<item name=
<item name=
</shopping>
bread,3,2.50
milk,2,3.50
Produce the equivalent information in XML, e.g.:
<shopping>
<item name=
"bread" quantity="3" price="2.50" />
<item name=
"milk" quantity="2" price="3.50" />
</shopping>
perl
#! /usr/bin/perl
# -*- Mode: CPerl -*-
use strict;
use XML::Simple;
use Data::Dumper;
# 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>
#
my $line;
my $item;
my $q;
my $p;
my $z;
my $xs = XML::Simple->new();
my %d = ();
while($line=<DATA>){
chomp $line;
($item,$q,$p) = split ",",$line;
$d{shopping}{item}{$item}{quantity} = $q;
$d{shopping}{item}{$item}{price} = $p;
}
$xml = $xs->XMLout(\%d, KeepRoot => 1);
print $xml,"\n";
__DATA__
bread,3,2.50
milk,2,3.50
# -*- Mode: CPerl -*-
use strict;
use XML::Simple;
use Data::Dumper;
# 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>
#
my $line;
my $item;
my $q;
my $p;
my $z;
my $xs = XML::Simple->new();
my %d = ();
while($line=<DATA>){
chomp $line;
($item,$q,$p) = split ",",$line;
$d{shopping}{item}{$item}{quantity} = $q;
$d{shopping}{item}{$item}{price} = $p;
}
$xml = $xs->XMLout(\%d, KeepRoot => 1);
print $xml,"\n";
__DATA__
bread,3,2.50
milk,2,3.50
use strict;
use XML::Writer;
use Text::CSV;
my $csv = <<ENDOFCSV;
bread,3,2.50
milk,2,3.50
ENDOFCSV
open my $fh, '<', \$csv or die "Can't open string, $!\n";
my $csv = Text::CSV->new;
my $writer = XML::Writer->new(DATA_MODE => 1, DATA_INDENT => 2);
$writer->startTag('shopping');
while (my $arr_ref = $csv->getline($fh)) {
my %attributes;
@attributes{qw/name quantity price/} =
@{$arr_ref}[0..2];
$writer->emptyTag('item' => %attributes)
}
$writer->endTag('shopping');
use XML::Writer;
use Text::CSV;
my $csv = <<ENDOFCSV;
bread,3,2.50
milk,2,3.50
ENDOFCSV
open my $fh, '<', \$csv or die "Can't open string, $!\n";
my $csv = Text::CSV->new;
my $writer = XML::Writer->new(DATA_MODE => 1, DATA_INDENT => 2);
$writer->startTag('shopping');
while (my $arr_ref = $csv->getline($fh)) {
my %attributes;
@attributes{qw/name quantity price/} =
@{$arr_ref}[0..2];
$writer->emptyTag('item' => %attributes)
}
$writer->endTag('shopping');
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();
}
// 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();
}
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*))
(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*))
fantom
sum := 0.0
rows := CsvInStream(File(`shop.csv`).in).readAllRows
doc := XDoc()
doc.root = XElem("shopping")
{
root := it
rows.each |Str[] row|
{
root.add(XElem("item")
{
XAttr("name", row[0]),
XAttr("quantity", row[1]),
XAttr("price", row[2])
})
}
}
os := File(`shop.xml`).out
doc.write(os)
os.close
rows := CsvInStream(File(`shop.csv`).in).readAllRows
doc := XDoc()
doc.root = XElem("shopping")
{
root := it
rows.each |Str[] row|
{
root.add(XElem("item")
{
XAttr("name", row[0]),
XAttr("quantity", row[1]),
XAttr("price", row[2])
})
}
}
os := File(`shop.xml`).out
doc.write(os)
os.close
Find all Pythagorean triangles with length or height less than or equal to 20
Pythagorean triangles are right angle triangles whose sides comply with the following equation:
a * a + b * b = c * c
where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides. Find all such triangles where a, b and c are non-zero integers with a and b less than or equal to 20. Sort your results by the size of the hypotenuse. The expected answer is:
a * a + b * b = c * c
where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides. Find all such triangles where a, b and c are non-zero integers with a and b less than or equal to 20. Sort your results by the size of the hypotenuse. The expected answer is:
[3, 4, 5]
[6, 8, 10]
[5, 12, 13]
[9, 12, 15]
[8, 15, 17]
[12, 16, 20]
[15, 20, 25]
perl
#!/usr/bin/perl
my @results;
for my $x (1..20) {
for my $y ($x..20) {
my $z = sqrt($x**2+$y**2);
push @results, [$x,$y,$z] if $z == int($z);
}
}
for my $triangle ( sort { $a->[2] <=> $b->[2] } @results) {
print "[".join(',',@$triangle)."]\n";
}
my @results;
for my $x (1..20) {
for my $y ($x..20) {
my $z = sqrt($x**2+$y**2);
push @results, [$x,$y,$z] if $z == int($z);
}
}
for my $triangle ( sort { $a->[2] <=> $b->[2] } @results) {
print "[".join(',',@$triangle)."]\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 }));
}
}
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 }));
}
}
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])
(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))
(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))
fantom
triangles := [,]
(1..20).each |Int a|
{
(a..20).each |Int b|
{
c := (a.pow(2) + b.pow(2)).toFloat.sqrt
if (c % c.toInt == 0.0f && !triangles.contains([b,a,c]))
triangles.add([a,b,c.toInt])
}
}
triangles.sort |Int[] x, Int[] y -> Int| { x[2]-y[2] }
echo(triangles)
(1..20).each |Int a|
{
(a..20).each |Int b|
{
c := (a.pow(2) + b.pow(2)).toFloat.sqrt
if (c % c.toInt == 0.0f && !triangles.contains([b,a,c]))
triangles.add([a,b,c.toInt])
}
}
triangles.sort |Int[] x, Int[] y -> Int| { x[2]-y[2] }
echo(triangles)
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.
perl
sub gcd {
my ($a, $b) = @_;
($a,$b) = ($b,$a) if $a > $b;
while ($a) { ($a, $b) = ($b % $a, $a) }
return $b;
}
print gcd( 8, 12 );
my ($a, $b) = @_;
($a,$b) = ($b,$a) if $a > $b;
while ($a) { ($a, $b) = ($b % $a, $a) }
return $b;
}
print gcd( 8, 12 );
my $g = gcd (8, 12);
print $g;
sub gcd {
# Euclid's Algorithm - recursive
my ($c, $d) = @_;
return $c unless $d;
return gcd ($d, $c % $d);
}
print $g;
sub gcd {
# Euclid's Algorithm - recursive
my ($c, $d) = @_;
return $c unless $d;
return gcd ($d, $c % $d);
}
my $g = gcd2 (8, 12);
print $g;
sub gcd2 {
# Dijkstra's Algorithm - recursive
my ($c, $d) = @_;
return $c if $c == $d;
return $c > $d? gcd2 ($c - $d, $d) : gcd2 ($c, $d - $c);
}
print $g;
sub gcd2 {
# Dijkstra's Algorithm - recursive
my ($c, $d) = @_;
return $c if $c == $d;
return $c > $d? gcd2 ($c - $d, $d) : gcd2 ($c, $d - $c);
}
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));
}
if (Math.min(a, b) == 0)
return Math.max(a, b);
else
return gcd(Math.min(a, b), Math.abs(a - b));
}
clojure
(defn gcd [a b]
(if (zero? b)
a
(recur b (mod b a))))
(if (zero? b)
a
(recur b (mod b a))))
fantom
gcd := |Int a, Int b -> Int| {
pair := [a, b].sort
while (pair.first != 0)
pair.set(1, pair.last % pair.first).swap(0, 1)
return pair.last
}
echo(gcd(12, 8)) // a>b, result == 4
echo(gcd(1029, 1071)) // a<b, result == 21
pair := [a, b].sort
while (pair.first != 0)
pair.set(1, pair.last % pair.first).swap(0, 1)
return pair.last
}
echo(gcd(12, 8)) // a>b, result == 4
echo(gcd(1029, 1071)) // a<b, result == 21
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.
perl
seek DATA,0,0;
print <DATA>;
__DATA__
Cheating quine.
print <DATA>;
__DATA__
Cheating quine.
$_=q(print qq(\$_=q($_);eval\n));eval
$x=q($x=q(%s);printf($x,$x););printf($x,$x);
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);
}
}
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);
}
}
clojure
(def s"(def s%s)(printf s(pr-str s))")(printf s(pr-str s))
fantom
class Q
{
static Void main()
{
r := "class Q\n{\n static Void main()\n {\n r := "
s := "\n s := \n echo (r+r.toCode+s[0..9]+s.toCode+s[10..-1])\n }\n}"
echo (r+r.toCode+s[0..9]+s.toCode+s[10..-1])
}
}
{
static Void main()
{
r := "class Q\n{\n static Void main()\n {\n r := "
s := "\n s := \n echo (r+r.toCode+s[0..9]+s.toCode+s[10..-1])\n }\n}"
echo (r+r.toCode+s[0..9]+s.toCode+s[10..-1])
}
}
class Q{static Void main(){s:="class Q{static Void main(){s:=;c:=34.toChar;echo(s[0..<30]+c+s+c+s[30..-1]);}}";c:=34.toChar;echo(s[0..<30]+c+s+c+s[30..-1]);}}
Create a multithreaded "Hello World"
Create a program which outputs the string
Example:
-Output-
Thread one says Hello World!
Thread two says Hello World!
Thread four says Hello World!
Thread three says Hello World!
-Notice that the threads can print in any order.
"Hello World" to the console, multiple times, using separate threads or processes.
Example:
-Output-
Thread one says Hello World!
Thread two says Hello World!
Thread four says Hello World!
Thread three says Hello World!
-Notice that the threads can print in any order.
perl
use threads;
foreach my $tid ("one","two","three","four") {
threads->create(
sub { print("Thread $tid says Hello World!\n"); }
)->join();
}
foreach my $tid ("one","two","three","four") {
threads->create(
sub { print("Thread $tid says Hello World!\n"); }
)->join();
}
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();
}
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();
}
clojure
(doseq [msg ["one" "two" "three" "four"]]
(future (println "Thread" msg "says Hello World!")))
(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")))
'("one" "two" "three" "four")))
fantom
pool := ActorPool()
["one", "two", "three", "four"].each
{
a := Actor(pool) |Str name| { echo("Thread $name says Hello World!") }
a.send(it)
}
["one", "two", "three", "four"].each
{
a := Actor(pool) |Str name| { echo("Thread $name says Hello World!") }
a.send(it)
}
