All Problems
Output a string to the console
Write the string
"Hello World!" to STDOUT
java
System.out.println("Hello World!");
System.out.printf("Hello World!\n");
csharp
System.Console.WriteLine("Hello World!")
clojure
(println "Hello World!")
Retrieve a string containing ampersands from the variables in a url
My PHP script first does a query to obtain customer info for a form. The form has first name and last name fields among others. The customer has put entries such as
The script variable for first name $_REQUEST
I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like
Of course this fails for the same reasons. What is a better approach?
"Ron & Jean" in the first name field in the database. Then the edit form script is called with variables such as
"http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith".
The script variable for first name $_REQUEST
['firstname'] never gets beyond the "Ron" value because of the ampersand in the data.
I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like
"http://myserver/custinfo/edit.php?mode=view&fname="Ronxxnbsp;xxamp;xxnbsp;Jean"&lname=SMITH". (sorry I had to add the xx to replace the ampersand or it didn't display meaningful url contents the browser sees.)
Of course this fails for the same reasons. What is a better approach?
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"))
string-wrap
Wrap the string
Expected output:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t
> he lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox
> jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The qui
> ck brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy
> dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps o
> ver the lazy dog. The quick brown fox jumps over the lazy dog.
"The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> "
Expected output:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t
> he lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox
> jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The qui
> ck brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy
> dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps o
> ver the lazy dog. The quick brown fox jumps over the lazy dog.
java
public class SolutionXX {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
String words = "The quick brown fox jumps over the lazy dog. ";
for (int i = 0; i < 10; i++)
{
builder.append(words);
}
String toWrap = builder.toString();
int width = 76;
while (toWrap!=null && toWrap.length()>0)
{
String first = toWrap.length() > width ? toWrap.substring(0, width+1) : toWrap;
toWrap = (!toWrap.equals(first)) ? toWrap.substring(width + 1).trim() : null;
System.out.println("> " + first);
}
}
}
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
String words = "The quick brown fox jumps over the lazy dog. ";
for (int i = 0; i < 10; i++)
{
builder.append(words);
}
String toWrap = builder.toString();
int width = 76;
while (toWrap!=null && toWrap.length()>0)
{
String first = toWrap.length() > width ? toWrap.substring(0, width+1) : toWrap;
toWrap = (!toWrap.equals(first)) ? toWrap.substring(width + 1).trim() : null;
System.out.println("> " + first);
}
}
}
clojure
(defn string-wrap [s]
(if (= 0 (count s))
nil
(lazy-seq (cons (apply str (take 78 s))
(string-wrap (drop 78 s))))))
(let [s (apply str (repeat 10 "The quick brown fox jumps over the lazy dog. "))]
(doseq [line (string-wrap s)]
(println "> " line)))
(if (= 0 (count s))
nil
(lazy-seq (cons (apply str (take 78 s))
(string-wrap (drop 78 s))))))
(let [s (apply str (repeat 10 "The quick brown fox jumps over the lazy dog. "))]
(doseq [line (string-wrap s)]
(println "> " line)))
Define a string containing special characters
Define the literal string
"\#{'}${"}/"
java
String special = "\\#{'}${\"}/";
csharp
string verbatim = @"\#{'}${""""}/";
string cStyle = "\\#{'}${\"\"}/";
string cStyle = "\\#{'}${\"\"}/";
clojure
(def special "\\#{'}${\"}/")
Define a multiline string
Define the string:
"This
Is
A
Multiline
String"
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"
csharp
string output = "This\nIs\nA\nMultiline\nString";
string output = @"This
Is
A
Multiline
String";
Is
A
Multiline
String";
clojure
(def multiline "This\nIs\nA\nMultiline\nString")
Define a string containing variables and expressions
Given variables a=3 and b=4 output
"3+4=7"
java
System.out.println(a + "+" + b + "=" + (a+b));
System.out.printf("%d+%d=%d\n", a, b, a + b);
csharp
int a = 3;
int b = 4;
Console.WriteLine("{0}+{1}={2}", a,b,a+b);
int b = 4;
Console.WriteLine("{0}+{1}={2}", a,b,a+b);
clojure
(format "%d + %d = %d" a b (+ a b))
Reverse the characters in a string
Given the string
"reverse me", produce the string "em esrever"
java
String reverse = new StringBuffer("reverse me").reverse().toString();
String reverse = new StringBuilder("reverse me").reverse().toString();
String reverse = StringUtils.reverse("reverse me");
csharp
var str = "reverse me";
Console.WriteLine(new String(str.Reverse().ToArray()));
Console.WriteLine(new String(str.Reverse().ToArray()));
clojure
(require '[clojure.contrib.str-utils2 :as str])
(str/reverse "reverse me")
(str/reverse "reverse me")
(apply str (reverse "reverse me"))
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"
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!", ' ');
csharp
var str = "This is a end, my only friend!";
str = String.Join(" ", str.Split().Reverse().ToArray());
Console.WriteLine(str);
str = String.Join(" ", str.Split().Reverse().ToArray());
Console.WriteLine(str);
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!"))))
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.
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);
csharp
using System;
using System.Text;
using System.Linq; // used for Array.ToList() extension
public class TextWrapper {
/// <summary>
/// Wrap the given text to a given width.
/// </summary>
/// <param name="text">The text to be wrapped</param>
/// <param name="width">The maximum width of each line</param>
/// <param name="prefix">Begin each line with this prefix</param>
/// <returns>The wrapped text</returns>
public string Wrap(string text, int width, string prefix) {
var words = text.Split(' ').ToList();
var result = new StringBuilder(prefix);
width = width - prefix.Length;
prefix = "\n" + prefix;
int lineSize = 0;
foreach (var word in words) {
int wordLen = word.Length;
// Do we need to start a new line?
if ((lineSize + wordLen) > width) {
result.Remove(result.Length - 1, 1); // remove trailing space
lineSize = 0;
result.Append( prefix );
}
result.Append(word).Append(' ');
lineSize += wordLen + 1;
}
return result.ToString();
}
public static void Main() {
var prefix = "> ";
var sentence = "The quick brown fox jumps over the lazy dog. ";
var text = "";
for (int i = 0; i < 10; i++)
text += sentence;
// The description said lines of length 78, but
// the example was 72...
Console.WriteLine(new TextWrapper().Wrap(text, 72, prefix));
}
}
using System.Text;
using System.Linq; // used for Array.ToList() extension
public class TextWrapper {
/// <summary>
/// Wrap the given text to a given width.
/// </summary>
/// <param name="text">The text to be wrapped</param>
/// <param name="width">The maximum width of each line</param>
/// <param name="prefix">Begin each line with this prefix</param>
/// <returns>The wrapped text</returns>
public string Wrap(string text, int width, string prefix) {
var words = text.Split(' ').ToList();
var result = new StringBuilder(prefix);
width = width - prefix.Length;
prefix = "\n" + prefix;
int lineSize = 0;
foreach (var word in words) {
int wordLen = word.Length;
// Do we need to start a new line?
if ((lineSize + wordLen) > width) {
result.Remove(result.Length - 1, 1); // remove trailing space
lineSize = 0;
result.Append( prefix );
}
result.Append(word).Append(' ');
lineSize += wordLen + 1;
}
return result.ToString();
}
public static void Main() {
var prefix = "> ";
var sentence = "The quick brown fox jumps over the lazy dog. ";
var text = "";
for (int i = 0; i < 10; i++)
text += sentence;
// The description said lines of length 78, but
// the example was 72...
Console.WriteLine(new TextWrapper().Wrap(text, 72, prefix));
}
}
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))
Remove leading and trailing whitespace from a string
Given the string
" hello " return the string "hello".
java
String s = " hello "; String trimmed = s.trim();
csharp
string str = " hello ";
str = str.Trim();
Console.WriteLine(str);
str = str.Trim();
Console.WriteLine(str);
clojure
(use 'clojure.contrib.str-utils2)
(trim " hello ")
(trim " hello ")
(clojure.string/trim " hello ")
(.trim " hello ")
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
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))))
Make a string uppercase
Transform
"Space Monkey" into "SPACE MONKEY"
java
String upper = text.toUpperCase();
csharp
string output = "Space Monkey"
System.Console.WriteLine(output.ToUpper())
System.Console.WriteLine(output.ToUpper())
clojure
(.toUpperCase "Space Monkey")
Make a string lowercase
Transform
"Caps ARE overRated" into "caps are overrated"
java
"Caps ARE overRated".toLowerCase();
csharp
string str = "Caps ARE overRated";
str = str.ToLower() ;
Console.WriteLine(str);
str = str.ToLower() ;
Console.WriteLine(str);
clojure
(.toLowerCase "Caps ARE overRated")
Capitalise the first letter of each word
Transform
"man OF stEEL" into "Man Of Steel"
java
String input = "man OF stEEL";
StringTokenizer tokenizer = new StringTokenizer(input);
StringBuffer sb = new StringBuffer();
while (tokenizer.hasMoreTokens()) {
String word = tokenizer.nextToken();
sb.append(word.substring(0, 1).toUpperCase());
sb.append(word.substring(1).toLowerCase());
sb.append(' ');
}
String text = sb.toString();
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");
csharp
System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase("man OF stEEL".ToLowerInvariant());
clojure
(use 'clojure.contrib.str-utils2)
(join " " (map capitalize (split "man OF stEEL" #" ")))
(join " " (map capitalize (split "man OF stEEL" #" ")))
Find the distance between two points
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);
csharp
System.Drawing.Point p = new System.Drawing.Point(13, 14),
p1 = new System.Drawing.Point(10, 10);
double distance = Math.Sqrt(Math.Pow(p1.X - p.X, 2) + Math.Pow(p1.Y - p.Y, 2)));
p1 = new System.Drawing.Point(10, 10);
double distance = Math.Sqrt(Math.Pow(p1.X - p.X, 2) + Math.Pow(p1.Y - p.Y, 2)));
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])
Zero pad a number
Given the number 42, pad it to 8 characters like 00000042
java
String formatted = new DecimalFormat("00000000").format(42);
String formatted = String.format("%08d", 42);
csharp
string.Format("{0,8:D8}", 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)
Right Space pad a number
Given the number 1024 right pad it to 6 characters
"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);
csharp
public class NumberRightPadding {
public static void Main() {
string withStringDotFormat = string.Format("{0,-6}", 1024);
string withToStringDotPadRight = 1024.ToString().PadRight(6);
}
}
public static void Main() {
string withStringDotFormat = string.Format("{0,-6}", 1024);
string withToStringDotPadRight = 1024.ToString().PadRight(6);
}
}
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) " "))))
Format a decimal number
Format the number 7/8 as a decimal with 2 places: 0.88
java
String formatted = String.format("%3.2f", 7./8.);
csharp
public class FormatDecimal {
public static void Main() {
decimal result = decimal.Round( 7 / 8m, 2);
System.Console.WriteLine(result);
}
}
public static void Main() {
decimal result = decimal.Round( 7 / 8m, 2);
System.Console.WriteLine(result);
}
}
clojure
(format "%3.2f" (/ 7.0 8))
(* 0.01 (Math/round (* 100 (float (/ 7 8)))))
Left Space pad a number
Given the number 73 left pad it to 10 characters
" 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);
csharp
public class NumberLeftPadding {
public static void Main() {
string withStringDotFormat = string.Format("{0,10}", 73);
string withToStringDotPadLeft = 73.ToString().PadLeft(10);
}
}
public static void Main() {
string withStringDotFormat = string.Format("{0,10}", 73);
string withToStringDotPadLeft = 73.ToString().PadLeft(10);
}
}
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 ))
Generate a random integer in a given range
Produce a random integer between 100 and 200 inclusive
java
Random random = new Random();
int randomInt = random.nextInt(200-100+1)+100;
int randomInt = random.nextInt(200-100+1)+100;
csharp
System.Random r = new System.Random();
int random = r.Next(100,201);
int random = r.Next(100,201);
clojure
(+ (rand-int (- 201 100)) 100)
Generate a repeatable random number sequence
Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values.
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(); }
csharp
using System;
public class RepeatableRandom {
public static void Main() {
var r = new Random(12); // seed is 12
for (int i = 0; i < 5; i++)
Console.WriteLine(r.Next());
r = new Random(12);
for (int i = 0; i < 5; i++)
Console.WriteLine(r.Next());
}
}
public class RepeatableRandom {
public static void Main() {
var r = new Random(12); // seed is 12
for (int i = 0; i < 5; i++)
Console.WriteLine(r.Next());
r = new Random(12);
for (int i = 0; i < 5; i++)
Console.WriteLine(r.Next());
}
}
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))
Check if a string matches a regular expression
Display
"ok" if "Hello" matches /[A-Z][a-z]+/
java
if ("Hello".matches("[A-Z][a-z]+")) {
System.out.println("ok");
}
System.out.println("ok");
}
csharp
if (Regex.IsMatch("Hello", "[A-Z][a-z]+"))
{
Console.WriteLine("ok");
}
{
Console.WriteLine("ok");
}
clojure
(if (re-matches #"[A-Z][a-z]+" "Hello")
(println "ok"))
(println "ok"))
Check if a string matches with groups
Display
"two" if "one two three" matches /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));
}
csharp
using System;
using System.Text.RegularExpressions;
public class RegexBackReference {
public static void Main() {
var oneTwoThree = "one two three";
var pattern = "one (.*) three";
Match match = Regex.Match(oneTwoThree, pattern);
// group 0 is the entire match. 1 is the first backreference
Console.WriteLine(match.Groups[1]);
}
}
using System.Text.RegularExpressions;
public class RegexBackReference {
public static void Main() {
var oneTwoThree = "one two three";
var pattern = "one (.*) three";
Match match = Regex.Match(oneTwoThree, pattern);
// group 0 is the entire match. 1 is the first backreference
Console.WriteLine(match.Groups[1]);
}
}
clojure
(if-let [groups (re-matches #"one (.*) three" "one two three")]
(println (second groups)))
(println (second groups)))
Check if a string contains a match to a regular expression
Display
"ok" if "abc 123 @#$" matches /\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");
}
csharp
if(System.Text.RegularExpressions.Regex.IsMatch("abc 123 @#$",@"\d+")){
Console.WriteLine("ok");
}
Console.WriteLine("ok");
}
clojure
(if (re-find #"\d+" "abc 123 @#$")
(println "ok"))
(println "ok"))
Loop through a string matching a regex and performing an action for each match
Create a list
[fish1,cow3,boat4] when matching "(fish):1 sausage (cow):3 tree (boat):4" with regex /\((\w+)\):(\d+)/
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));
}
csharp
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public static class extensions {
public static IList<string> Map(this string me, string pattern, Func<Match, string> action){
IList<string> matches = new List<string>();
foreach (Match match in Regex.Matches(me,pattern)){
matches.Add(action(match));
}
return matches;
}
}
class Test
{
static void Main()
{
IList<string> list = "(fish):1 sausage (cow):3 tree (boat):4".Map(@"\((\w+)\):(\d+)", (m) => {return m.Groups[1].Value + m.Groups[2].Value;});
}
}
using System.Collections.Generic;
using System.Text.RegularExpressions;
public static class extensions {
public static IList<string> Map(this string me, string pattern, Func<Match, string> action){
IList<string> matches = new List<string>();
foreach (Match match in Regex.Matches(me,pattern)){
matches.Add(action(match));
}
return matches;
}
}
class Test
{
static void Main()
{
IList<string> list = "(fish):1 sausage (cow):3 tree (boat):4".Map(@"\((\w+)\):(\d+)", (m) => {return m.Groups[1].Value + m.Groups[2].Value;});
}
}
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)))
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 "*"
java
String replaced = "Red Green Blue".replaceFirst("e", "*");
clojure
(.replaceFirst (re-matcher #"e" "Red Green Blue") "*")
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"
java
String replaced = text.replaceAll("se\\w+", "X");
csharp
using System.Text.RegularExpressions;
class SolutionXX
{
static void Main()
{
string text = "She sells sea shells";
string result = Regex.Replace(text, @"se\w+", "X");
}
}
class SolutionXX
{
static void Main()
{
string text = "She sells sea shells";
string result = Regex.Replace(text, @"se\w+", "X");
}
}
clojure
(.replaceAll (re-matcher #"se\w+" "She sells sea shells") "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+)\}/.
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))))
Define an empty list
Assign the variable
"list" to a list with no elements
java
List list = Collections.emptyList();
String[] list = {};
csharp
var list = new List<object>();
clojure
(list)
'()
Define a static list
Define the 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"); }};
csharp
IList<string> list = new string[]{"One","Two","Three","Four","Five"};
clojure
(def a '[One Two Three Four Five])
Join the elements of a list, separated by commas
Given the list
[Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
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, ", ");
csharp
using System.Collections.Generic;
public class JoinEach {
public static void Main() {
var list = new List<string>() {"Apple", "Banana", "Carrot"};
System.Console.WriteLine( string.Join(", ", list.ToArray()) );
}
}
public class JoinEach {
public static void Main() {
var list = new List<string>() {"Apple", "Banana", "Carrot"};
System.Console.WriteLine( string.Join(", ", list.ToArray()) );
}
}
clojure
(apply str (interpose ", " '("Apple" "Banana" "Carrot")))
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(
[]) = ""
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));
csharp
using System.Collections.Generic;
using System.Linq;
public class CSharpListToEnglishList {
public string JoinAsEnglishList (List<string> words) {
switch (words.Count) {
case 0: return "";
case 1: return words[0];
case 2: return string.Format("{0} and {1}", words.ToArray());
default:
return JoinAsEnglishList( new List<string>() {
string.Join(", ", words.Take(words.Count - 1).ToArray()) + ",",
words.Last()
});
}
}
// Driver...
public static void Main() {
var joiner = new CSharpListToEnglishList();
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Apple", "Banana", "Carrot", "Orange" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Apple", "Banana", "Carrot" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "One", "Two" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Lonely" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>()) );
}
}
using System.Linq;
public class CSharpListToEnglishList {
public string JoinAsEnglishList (List<string> words) {
switch (words.Count) {
case 0: return "";
case 1: return words[0];
case 2: return string.Format("{0} and {1}", words.ToArray());
default:
return JoinAsEnglishList( new List<string>() {
string.Join(", ", words.Take(words.Count - 1).ToArray()) + ",",
words.Last()
});
}
}
// Driver...
public static void Main() {
var joiner = new CSharpListToEnglishList();
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Apple", "Banana", "Carrot", "Orange" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Apple", "Banana", "Carrot" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "One", "Two" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Lonely" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>()) );
}
}
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)))))
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]]
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)));
csharp
using System.Collections.Generic;
public class ListCombiner {
public static void Main() {
var letters = new List<char>() { 'a', 'b', 'c' };
var numbers = new List<int>() { 1, 2, 3 };
// result is a list that contaings lists of objects
var result = new List<List<object>>();
foreach (var l in letters) {
foreach (var n in numbers) {
result.Add(new List<object>() { l, n });
}
}
}
}
public class ListCombiner {
public static void Main() {
var letters = new List<char>() { 'a', 'b', 'c' };
var numbers = new List<int>() { 1, 2, 3 };
// result is a list that contaings lists of objects
var result = new List<List<object>>();
foreach (var l in letters) {
foreach (var n in numbers) {
result.Add(new List<object>() { l, n });
}
}
}
}
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])
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"]
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);
csharp
List<String> values = new List<string> {"andrew", "bob", "chris", "bob"};
var duplicates = values
.GroupBy(i => i)
.Where(j => j.Count() > 1)
.Select(s => s.Key);
foreach (var duplicate in duplicates)
{
Console.WriteLine(duplicate);
}
var duplicates = values
.GroupBy(i => i)
.Where(j => j.Count() > 1)
.Select(s => s.Key);
foreach (var duplicate in duplicates)
{
Console.WriteLine(duplicate);
}
clojure
(->> '("andrew" "bob" "chris" "bob")
(group-by identity)
(filter #(> (count (second %)) 1))
(map first))
(group-by identity)
(filter #(> (count (second %)) 1))
(map first))
Fetch an element of a list by index
Given the list
[One, Two, Three, Four, Five], fetch the third element ('Three')
java
String result = list.get(2);
csharp
string[] items = new string[] { "One", "Two", "Three", "Four", "Five" };
List<string> list = new List<string>(items);
string third = list[2]; // "Three"
List<string> list = new List<string>(items);
string third = list[2]; // "Three"
// Make sure you import the System.Linq namespace.
// This is not the preferred way of indexing if you are using Lists.
string[] items = new string[] { "One", "Two", "Three", "Four", "Five" };
IEnumerable<string> list = new List<string>(items);
string third = list.ElementAt(2); // Three
// This is not the preferred way of indexing if you are using Lists.
string[] items = new string[] { "One", "Two", "Three", "Four", "Five" };
IEnumerable<string> list = new List<string>(items);
string third = list.ElementAt(2); // Three
clojure
(nth '[One Two Three Four Five] 2)
Fetch the last element of a list
Given the list
[Red, Green, Blue], access the last element ('Blue')
java
String result = list.get(list.size() - 1);
csharp
string[] items = new string[] { "Red", "Green", "Blue" };
List<string> list = new List<string>(items);
string last = list[list.Count - 1]; // "Blue"
List<string> list = new List<string>(items);
string last = list[list.Count - 1]; // "Blue"
// Make sure you import the System.Linq namespace.
// This is not the preferred way of finding the last element if you are using Lists.
string[] items = new string[] { "Red", "Green", "Blue" };
IEnumerable<string> list = new List<string>(items);
string last = list.Last(); // "Blue"
// This is not the preferred way of finding the last element if you are using Lists.
string[] items = new string[] { "Red", "Green", "Blue" };
IEnumerable<string> list = new List<string>(items);
string last = list.Last(); // "Blue"
clojure
(last '[One Two Three Four Five])
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?
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);
csharp
// Make sure you import the System.Linq namespace.
// This example uses arrays as the underlying implementation, but any IEnumerable type can be used - including List.
IEnumerable<string> beans = new string[] { "beans", "mung", "black", "red", "white" };
IEnumerable<string> colors = new string[] { "black", "red", "blue", "green" };
var intersect = beans.Intersect(colors); // ['red', 'black']
// This example uses arrays as the underlying implementation, but any IEnumerable type can be used - including List.
IEnumerable<string> beans = new string[] { "beans", "mung", "black", "red", "white" };
IEnumerable<string> colors = new string[] { "black", "red", "blue", "green" };
var intersect = beans.Intersect(colors); // ['red', 'black']
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)))
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.
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);
csharp
using System.Collections.Generic;
using System.Linq;
public class UniqueElements {
public static void Main() {
var list = new List<int>() { 18, 16, 17, 18, 16, 19, 14, 17, 19, 18 };
var uniques = list.Distinct();
}
}
using System.Linq;
public class UniqueElements {
public static void Main() {
var list = new List<int>() { 18, 16, 17, 18, 16, 19, 14, 17, 19, 18 };
var uniques = list.Distinct();
}
}
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)
Remove an element from a list by index
Given the list
[Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
java
list.remove(0);
csharp
class Solution1516
{
static void Main()
{
List<string> fruit = new List<string>() { "Apple", "Banana", "Carrot" };
fruit.RemoveAt(0);
}
}
{
static void Main()
{
List<string> fruit = new List<string>() { "Apple", "Banana", "Carrot" };
fruit.RemoveAt(0);
}
}
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)))
Remove the last element of a list
java
list.remove(list.size() - 1);
csharp
List<string> fruits = new List() { "apple", "banana", "cherry" };
fruits.RemoveAt(fruits.Length - 1);
fruits.RemoveAt(fruits.Length - 1);
clojure
(pop ["Apple" "Banana" "Carrot"])
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"]
java
list.add(list.remove(0));
Collections.rotate(list, -1);
csharp
var lst = new LinkedList<String>(new String[] {"apple", "orange", "grapes", "banana"});
lst.AddLast(lst.First());
lst.DeleteFirst();
lst.AddLast(lst.First());
lst.DeleteFirst();
clojure
(let [fruit ["apple" "orange" "grapes" "bananas"]]
(concat (rest fruit) [(first fruit)])
(concat (rest fruit) [(first fruit)])
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.
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);
csharp
String[] first = { "Bruce", "Tommy Lee", "Bruce" };
String[] last = { "Willis", "Jones", "Lee" };
int[] years = { 1955, 1946, 1940 };
var actors = first.Zip(last, (f, l) => Tuple.Create(f, l)).Zip(years, (t, y) => Tuple.Create(t.Item1, t.Item2, y)).ToArray();
Debug.Assert(actors[1].Equals(Tuple.Create("Tommy Lee", "Jones", 1946)));
String[] last = { "Willis", "Jones", "Lee" };
int[] years = { 1955, 1946, 1940 };
var actors = first.Zip(last, (f, l) => Tuple.Create(f, l)).Zip(years, (t, y) => Tuple.Create(t.Item1, t.Item2, y)).ToArray();
Debug.Assert(actors[1].Equals(Tuple.Create("Tommy Lee", "Jones", 1946)));
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))
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'.
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");
csharp
using System;
using System.Collections.Generic;
using System.Linq;
namespace Combinations
{
class Program
{
public static void Main(string[] args)
{
// Define the given lists
// Since List`1 implements the interface IEnumerable`1, this can easily be redefined as List`1.
IEnumerable<string> suites = new string[] { "H", "D", "C", "S" };
IEnumerable<string> faces = new string[] { "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" };
// LINQ Query to perform a Cartesian product and create an anonymous type to hold the results.
// "var" is required to define this as an IEnumerable`1
var deck =
from suite in suites // For each suite in suites
from face in faces // Match it with a face in face.
select new
{
Suite = suite,
Face = face
};
// Verify the count (uses LINQ extension)
if (deck.Count() == 52)
{
Console.WriteLine("Count matches!");
}
// Verify that the Ace of Hearts is in the deck (uses LINQ extension)
if (deck.Contains(new {Suite = "H", Face = "A"}))
{
Console.WriteLine("Ace of Hearts found!");
}
// Example of how to iterate through the list.
// "var" here is required since we are using an anonymous type
foreach(var card in deck)
{
Console.WriteLine("Suite: {0} Face: {1}", card.Suite, card.Face);
}
// If you desire to work with a List`1, you can convert this to a normal list at any time:
Console.WriteLine("\nConverting to list!");
var list = deck.ToList();
Console.WriteLine("Suite: {0} Face: {1}", list[5].Suite, list[5].Face);
Console.WriteLine("List count: {0}", list.Count); // 52
Console.ReadLine();
}
}
}
using System.Collections.Generic;
using System.Linq;
namespace Combinations
{
class Program
{
public static void Main(string[] args)
{
// Define the given lists
// Since List`1 implements the interface IEnumerable`1, this can easily be redefined as List`1.
IEnumerable<string> suites = new string[] { "H", "D", "C", "S" };
IEnumerable<string> faces = new string[] { "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" };
// LINQ Query to perform a Cartesian product and create an anonymous type to hold the results.
// "var" is required to define this as an IEnumerable`1
var deck =
from suite in suites // For each suite in suites
from face in faces // Match it with a face in face.
select new
{
Suite = suite,
Face = face
};
// Verify the count (uses LINQ extension)
if (deck.Count() == 52)
{
Console.WriteLine("Count matches!");
}
// Verify that the Ace of Hearts is in the deck (uses LINQ extension)
if (deck.Contains(new {Suite = "H", Face = "A"}))
{
Console.WriteLine("Ace of Hearts found!");
}
// Example of how to iterate through the list.
// "var" here is required since we are using an anonymous type
foreach(var card in deck)
{
Console.WriteLine("Suite: {0} Face: {1}", card.Suite, card.Face);
}
// If you desire to work with a List`1, you can convert this to a normal list at any time:
Console.WriteLine("\nConverting to list!");
var list = deck.ToList();
Console.WriteLine("Suite: {0} Face: {1}", list[5].Suite, list[5].Face);
Console.WriteLine("List count: {0}", list.Count); // 52
Console.ReadLine();
}
}
}
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
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]
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() + " ");
}
}
}
csharp
using System.Collections.Generic;
public class OperationOnEach {
public static void Main() {
var list = new List<string>() { "ox", "cat", "deer", "whale" };
list.ForEach( System.Console.WriteLine );
}
}
public class OperationOnEach {
public static void Main() {
var list = new List<string>() { "ox", "cat", "deer", "whale" };
list.ForEach( System.Console.WriteLine );
}
}
clojure
(map count ["ox" "cat" "deer" "whale"])
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.
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) ;
}
}
csharp
using System;
using System.Collections.Generic;
using System.Linq;
// AFAIK, there just isn't a good way to do this in C#
public class ListSplitter {
public static bool IsNumeric(object o) {
var d = new Decimal();
return decimal.TryParse(o.ToString(), out d);
}
public static void Main() {
var list = new List<object>() { "foo", DateTime.Now, 1, "bar", 2.4 };
// the Where method does the work...
var numbers = list.Where( el => IsNumeric(el) );
var nonNumbers = list.Where( el => ! IsNumeric(el) );
}
}
using System.Collections.Generic;
using System.Linq;
// AFAIK, there just isn't a good way to do this in C#
public class ListSplitter {
public static bool IsNumeric(object o) {
var d = new Decimal();
return decimal.TryParse(o.ToString(), out d);
}
public static void Main() {
var list = new List<object>() { "foo", DateTime.Now, 1, "bar", 2.4 };
// the Where method does the work...
var numbers = list.Where( el => IsNumeric(el) );
var nonNumbers = list.Where( el => ! IsNumeric(el) );
}
}
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.)])
Test if a condition holds for all items of a list
Given a list, test if a certain logical condition (i.e. predicate) holds for all items of the list.
clojure
(every? #(> % 1) [2 3 4])
Test if a condition holds for any items of a list
Given a list, test if a certain logical condition (i.e. predicate) holds for any items of the list.
clojure
; The standard library in Clojure has "not-any?" but (oddly enough) no "any?"
(defn any? [pred coll]
((complement not-any?) pred coll))
(any? #(> % 3) [2 3 4])
(defn any? [pred coll]
((complement not-any?) pred coll))
(any? #(> % 3) [2 3 4])
(some #(> % 3) [2 3 4])
Define an empty map
java
Map map = new HashMap();
clojure
(def m {})
Define an unmodifiable empty map
java
Map empty = Collections.EMPTY_MAP;
SortedMap empty = MapUtils.EMPTY_SORTED_MAP;
clojure
; Clojure maps are immutable
(def m {})
(def m {})
Define an initial map
Define the 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})
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"
java
if (pets.containsKey("mary")) System.out.println("ok");
clojure
(if (contains? '{joe cat mary turtle bill canary} 'mary)
(println "ok"))
(println "ok"))
Retrieve a value from a map
Given a map pets
{joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
java
String pet = pets.get("joe");
clojure
(def pets '{joe cat mary turtle bill canary})
(println (get pets 'joe))
(println (get pets 'joe))
Add an entry to a map
Given an empty pets map, add the mapping from
"rob" to "dog"
java
pets.put("rob", "dog");
clojure
(assoc {} '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"
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))
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
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);
csharp
using System.Collections.Generic;
using System.Linq;
// This is a "functional" C# approach
// NOTE: In C# "maps" are of type Dictionary<Tkey, TValue>
// so our histogram map is of type Dictionary<object, int>
public class HistogramMap {
public Dictionary<object, int> FromList(List<object> list) {
// The "Aggregate" method works like "inject" in many other languages.
return list.Aggregate(
new Dictionary<object, int>(),
(map, obj) => {
// If this is the first time we've seen this obj, set the count to 0
if (!map.ContainsKey(obj)) map[obj] = 0;
// Increment the count
map[obj]++;
// Return the map for the next iteration.
// NOTE: This does NOT return from our "FromList" method
return map;
}
);
}
public static void Main() {
// Create our Histogram Map from a new list
var map = new HistogramMap().FromList(
new List<object>() { 'a', 'b', 'a', 'c', 'b', 'b' }
);
// This just prints the result
System.Console.WriteLine (
string.Join (", ",
// "Select" works like "map" or "collect" in many other languages
map.Select( kvp =>
string.Format("{0} : {1}", kvp.Key, kvp.Value)
).ToArray()
)
);
}
}
using System.Linq;
// This is a "functional" C# approach
// NOTE: In C# "maps" are of type Dictionary<Tkey, TValue>
// so our histogram map is of type Dictionary<object, int>
public class HistogramMap {
public Dictionary<object, int> FromList(List<object> list) {
// The "Aggregate" method works like "inject" in many other languages.
return list.Aggregate(
new Dictionary<object, int>(),
(map, obj) => {
// If this is the first time we've seen this obj, set the count to 0
if (!map.ContainsKey(obj)) map[obj] = 0;
// Increment the count
map[obj]++;
// Return the map for the next iteration.
// NOTE: This does NOT return from our "FromList" method
return map;
}
);
}
public static void Main() {
// Create our Histogram Map from a new list
var map = new HistogramMap().FromList(
new List<object>() { 'a', 'b', 'a', 'c', 'b', 'b' }
);
// This just prints the result
System.Console.WriteLine (
string.Join (", ",
// "Select" works like "map" or "collect" in many other languages
map.Select( kvp =>
string.Format("{0} : {1}", kvp.Key, kvp.Value)
).ToArray()
)
);
}
}
new[] {"a","b","a","c","b","b"}
.GroupBy(s => s)
.Select(s => new { Value = s.Key, Count = s.Count() })
.ToList()
.ForEach(e => Console.WriteLine("{0} : {1} ", e.Value, e.Count));
.GroupBy(s => s)
.Select(s => new { Value = s.Key, Count = s.Count() })
.ToList()
.ForEach(e => Console.WriteLine("{0} : {1} ", e.Value, e.Count));
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])
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
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);
csharp
using System.Collections.Generic;
using System.Linq;
public class ListCategorizer {
public static void Main() {
var list = new List<string>() { "one", "two", "three", "four", "five" };
var categories = list.GroupBy(el => el.Length)
.ToDictionary( g => g.Key, // key
g => g.ToList() ); // value
}
}
using System.Linq;
public class ListCategorizer {
public static void Main() {
var list = new List<string>() { "one", "two", "three", "four", "five" };
var categories = list.GroupBy(el => el.Length)
.ToDictionary( g => g.Key, // key
g => g.ToList() ); // value
}
}
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"])
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.
java
if (name.equals("Bob")) {
System.out.println("Hello, Bob!");
}
System.out.println("Hello, Bob!");
}
csharp
if (name == "Bob") Console.WriteLine("Hello, {0}!", name);
clojure
(def person "Bob")
(if (= person "Bob")
(println "Hello, Bob!"))
(if (= person "Bob")
(println "Hello, Bob!"))
Perform different actions depending on a boolean condition (IF .. THEN .. ELSE)
Given a variable age, if the value is greater than 42 display
"You are old", otherwise display "You are young"
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"));
csharp
int age = 41;
if (age > 42)
System.Console.WriteLine("You are old");
else
System.Console.WriteLine("You are young");
if (age > 42)
System.Console.WriteLine("You are old");
else
System.Console.WriteLine("You are young");
clojure
(def age 41)
(if (> age 42) "You are old" "You are young")
(if (> age 42) "You are old" "You are young")
Perform different actions depending on several boolean conditions (IF .. THEN .. ELSIF .. ELSE)
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");
csharp
if (age > 84) Console.WriteLine("You are really ancient");
else if (age > 30) Console.WriteLine("You are middle-aged");
else Console.WriteLine("You are young");
else if (age > 30) Console.WriteLine("You are middle-aged");
else Console.WriteLine("You are young");
Console.WriteLine("You are {0}", ((age > 84) ? "really ancient" : (age > 30) ? "middle-aged" : "young"));
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"))
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
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";
}
}
csharp
public static string GetOrdinal(int i)
{
if (i > 10 && i < 20) return i.ToString() + "th";
switch (i % 10)
{
case 1:
return i.ToString() + "st";
case 2:
return i.ToString() + "nd";
case 3:
return i.ToString() + "rd";
default:
return i.ToString() + "th";
}
}
{
if (i > 10 && i < 20) return i.ToString() + "th";
switch (i % 10)
{
case 1:
return i.ToString() + "st";
case 2:
return i.ToString() + "nd";
case 3:
return i.ToString() + "rd";
default:
return i.ToString() + "th";
}
}
public static string GetOrdinal(int i)
{
if (i > 10 && i < 20) return i.ToString() + "th";
switch (i % 10)
{
case 1:
return i.ToString() + "st";
break;
case 2:
return i.ToString() + "nd";
break;
case 3:
return i.ToString() + "rd";
break;
default:
return i.ToString() + "th";
break;
}
}
{
if (i > 10 && i < 20) return i.ToString() + "th";
switch (i % 10)
{
case 1:
return i.ToString() + "st";
break;
case 2:
return i.ToString() + "nd";
break;
case 3:
return i.ToString() + "rd";
break;
default:
return i.ToString() + "th";
break;
}
}
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")))))
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.
java
int x = 1;
while (x < 150) {
System.out.println(x+",");
x*=2;
}
while (x < 150) {
System.out.println(x+",");
x*=2;
}
csharp
int x = 1;
while (x < 150)
{
x *= 2;
Console.Write("{0},", x);
}
while (x < 150)
{
x *= 2;
Console.Write("{0},", x);
}
clojure
(take-while #(< % 150) (iterate #(* 2 %) 1))
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"
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);
csharp
System.Random die = new System.Random();
int roll;
do
{
roll = die.Next(1, 6);
Console.Write(roll);
if (roll < 6) Console.Write(",");
}
while (roll != 6);
int roll;
do
{
roll = die.Next(1, 6);
Console.Write(roll);
if (roll < 6) Console.Write(",");
}
while (roll != 6);
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)))))
Perform an action a fixed number of times (FOR)
Display the string
"Hello" five times like "HelloHelloHelloHelloHello"
java
for(int i=0;i<5;i++) {
System.out.print("Hello");
}
System.out.print("Hello");
}
csharp
string text = "Hello";
for (int i = 0; i < 5; i++)
{
Console.Write(text);
}
for (int i = 0; i < 5; i++)
{
Console.Write(text);
}
clojure
(dotimes [_ 5]
(print "Hello"))
(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!"
java
for(int i=10; i>=1; i--) {
System.out.print(i + " .. ");
}
System.out.print("Liftoff!");
System.out.print(i + " .. ");
}
System.out.print("Liftoff!");
csharp
for (int i = 10; i > 0; i--)
{
Console.Write("{0} .. ", i);
}
Console.WriteLine("Liftoff!");
{
Console.Write("{0} .. ", i);
}
Console.WriteLine("Liftoff!");
clojure
(dotimes [i 10]
(print (str (- 10 i) " .. ")))
(println "Liftoff!")
(print (str (- 10 i) " .. ")))
(println "Liftoff!")
Read the contents of a file into a string
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);
}
csharp
string contents = System.IO.File.ReadAllText("filename.txt");
clojure
(slurp "/tmp/foobar")
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
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);
}
csharp
int counter = 0;
// If the file is large, you would want to buffer this instead of reading everything at once
foreach (string line in System.IO.File.ReadAllLines("filename.txt"))
{
Console.WriteLine("{0}> {1}", ++counter, line);
}
// If the file is large, you would want to buffer this instead of reading everything at once
foreach (string line in System.IO.File.ReadAllLines("filename.txt"))
{
Console.WriteLine("{0}> {1}", ++counter, line);
}
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))))
Write a string to a file
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!");
}
csharp
System.IO.File.WriteAllText("filename.txt", "Some text to write to the file");
clojure
(with-out-writer "output.txt" (println "Hello file!"))
Append to a file
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!");
}
csharp
System.IO.File.AppendAllText("filename.txt", "Some text to append to the file");
clojure
(with-out-append-writer "output.txt" (println "This is appended to the file"))
Process each file in a directory
java
for (File file : (new File("c:\\")).listFiles()) process(file);
csharp
foreach (string filename in System.IO.Directory.GetFiles(directory)) ProcessFile(filename);
clojure
; (defn process-file [f] "process one file" body...)
(map process-file (.listFiles (File. ".")))
(map process-file (.listFiles (File. ".")))
Process each file in a directory recursively
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. ".")))
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.
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");
csharp
DateTime parsedDate = DateTime.Parse("2008-05-06 13:29");
// Ideally, you would catch the potential FormatException or use DateTime.TryParse in production code.
// Ideally, you would catch the potential FormatException or use DateTime.TryParse in production code.
clojure
(.. (SimpleDateFormat. "yyyy-MM-dd HH:mm")
(parse "2008-05-06 13:29"))
(parse "2008-05-06 13:29"))
Display information about a date
Display the day of month, day of year, month name and day name of the day 8 days from now.
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()));
csharp
DateTime date = DateTime.Today.AddDays(8);
Console.WriteLine("Day of month: " + date.Day);
Console.WriteLine("Day of year: " + date.DayOfYear);
Console.WriteLine("Month name: " + date.ToString("MMMM"));
Console.WriteLine("Day name: " + date.ToString("dddd"));
// The two ToString calls will use the current locale.
// To get localised month and day names, see http://msdn.microsoft.com/en-us/library/8tfzyc64.aspx
Console.WriteLine("Day of month: " + date.Day);
Console.WriteLine("Day of year: " + date.DayOfYear);
Console.WriteLine("Month name: " + date.ToString("MMMM"));
Console.WriteLine("Day name: " + date.ToString("dddd"));
// The two ToString calls will use the current locale.
// To get localised month and day names, see http://msdn.microsoft.com/en-us/library/8tfzyc64.aspx
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))))
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.)
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()));
}
csharp
using System.Globalization;
DateTime newYearsDay = new DateTime(2009, 1, 1);
CultureInfo[] locales = {
CultureInfo.CreateSpecificCulture("en-US"),
CultureInfo.CreateSpecificCulture("fr-FR"),
CultureInfo.CreateSpecificCulture("de-DE"),
CultureInfo.CreateSpecificCulture("it-IT"),
CultureInfo.CreateSpecificCulture("nl-NL")
};
foreach (CultureInfo locale in locales)
{
Console.WriteLine(newYearsDay.ToString("D", locale));
}
DateTime newYearsDay = new DateTime(2009, 1, 1);
CultureInfo[] locales = {
CultureInfo.CreateSpecificCulture("en-US"),
CultureInfo.CreateSpecificCulture("fr-FR"),
CultureInfo.CreateSpecificCulture("de-DE"),
CultureInfo.CreateSpecificCulture("it-IT"),
CultureInfo.CreateSpecificCulture("nl-NL")
};
foreach (CultureInfo locale in locales)
{
Console.WriteLine(newYearsDay.ToString("D", locale));
}
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))))
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.
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());
}
}
csharp
// Creating a variable first:
DateTime now = DateTime.Now;
Console.WriteLine(now);
// Without creating a variable:
Console.WriteLine(DateTime.Now);
DateTime now = DateTime.Now;
Console.WriteLine(now);
// Without creating a variable:
Console.WriteLine(DateTime.Now);
clojure
(import 'java.util.Date)
(println (str (Date.)))
(println (str (Date.)))
Define a class
Declare a class named Greeter that takes a string on creation and greets using this string if you call the
"greet" method.
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();
}
}
csharp
using System;
class Greeter
{
private string name {get;set;}
public void Greet(){
Console.WriteLine("Hello, {0}",name);
}
public Greeter(string name){
this.name = name;
}
}
class Test
{
static void Main()
{
new Greeter("Dante").Greet();
}
}
class Greeter
{
private string name {get;set;}
public void Greet(){
Console.WriteLine("Hello, {0}",name);
}
public Greeter(string name){
this.name = name;
}
}
class Test
{
static void Main()
{
new Greeter("Dante").Greet();
}
}
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"))
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.
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() + ".");
csharp
class Greeter
{
public string Name {get;set;}
public void Greet(){
Console.WriteLine("Hello, {0}",Name);
}
public Greeter(string name){
this.Name = name;
}
// Driver
public static void Main()
{
var g = new Greeter("Dante");
g.Name = "Tommy";
g.Greet();
Console.Write("I have just greated {0}", g.Name);
}
}
{
public string Name {get;set;}
public void Greet(){
Console.WriteLine("Hello, {0}",Name);
}
public Greeter(string name){
this.Name = name;
}
// Driver
public static void Main()
{
var g = new Greeter("Dante");
g.Name = "Tommy";
g.Greet();
Console.Write("I have just greated {0}", g.Name);
}
}
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)))
"."))
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.
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();
csharp
// While abstract classes do exist in C#, it is most common to use
// an interface in this type of situation.
// It is a common idiom to prefix interface names with an I
public interface IShape {
string Name { get; }
double Area { get; }
void Print();
}
public class Circle : IShape {
private double Radius { get; set; }
public Circle(double radius) {
Name = "Circle";
Radius = radius;
}
public string Name { get; private set; }
public double Area {
get {
return Math.PI * Radius * Radius;
}
}
public double Circumference {
get {
return Math.PI * (Radius + Radius);
}
}
public void Print() {
Console.WriteLine( " Name: {0}\n Area: {1}\n Circumference: {2}\n Radius: {3}",
this.Name,
this.Area,
this.Circumference,
this.Radius
);
}
}
public class Rectangle : IShape {
private double Length { get; set; }
private double Breadth { get; set; }
public Rectangle(double length, double breadth) {
Name = "Rectangle";
Length = length;
Breadth = breadth;
}
public string Name { get; private set; }
public double Area {
get {
return Length * Breadth;
}
}
public double Perimeter {
get {
return (Length * 2) + (Breadth * 2 );
}
}
public void Print() {
Console.WriteLine( " Name: {0}\n Area: {1}\n Perimeter: {2}\n Length: {3}\n Breadth: {4}",
this.Name,
this.Area,
this.Perimeter,
this.Length,
this.Breadth
);
}
}
// Driver
public class InheritanceHeirarchy {
public static void _Main() {
var c = new Circle(2.1);
c.Print();
Console.WriteLine();
var r = new Rectangle(2.2, 3.3);
r.Print();
}
}
// an interface in this type of situation.
// It is a common idiom to prefix interface names with an I
public interface IShape {
string Name { get; }
double Area { get; }
void Print();
}
public class Circle : IShape {
private double Radius { get; set; }
public Circle(double radius) {
Name = "Circle";
Radius = radius;
}
public string Name { get; private set; }
public double Area {
get {
return Math.PI * Radius * Radius;
}
}
public double Circumference {
get {
return Math.PI * (Radius + Radius);
}
}
public void Print() {
Console.WriteLine( " Name: {0}\n Area: {1}\n Circumference: {2}\n Radius: {3}",
this.Name,
this.Area,
this.Circumference,
this.Radius
);
}
}
public class Rectangle : IShape {
private double Length { get; set; }
private double Breadth { get; set; }
public Rectangle(double length, double breadth) {
Name = "Rectangle";
Length = length;
Breadth = breadth;
}
public string Name { get; private set; }
public double Area {
get {
return Length * Breadth;
}
}
public double Perimeter {
get {
return (Length * 2) + (Breadth * 2 );
}
}
public void Print() {
Console.WriteLine( " Name: {0}\n Area: {1}\n Perimeter: {2}\n Length: {3}\n Breadth: {4}",
this.Name,
this.Area,
this.Perimeter,
this.Length,
this.Breadth
);
}
}
// Driver
public class InheritanceHeirarchy {
public static void _Main() {
var c = new Circle(2.1);
c.Print();
Console.WriteLine();
var r = new Rectangle(2.2, 3.3);
r.Print();
}
}
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)))
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.
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))
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.
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")))
Send an email
Use library functions, classes or objects to create a short email addressed to your own email address. The subject should be,
"Greetings from langref.org", and the user should be prompted for the message body, and whether to cancel or proceed with sending the email.
java
// requires Java Mail API (mail.jar), which must be in classpath
try {
Properties props = System.getProperties();
props.put("mail.smtp.host", "smtp.sampledomain.com");
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("gaylord.focker@hollywood.com"));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("father@family.com"));
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse("mother@family.com"));
msg.setSubject("subject");
msg.setText("message body");
msg.setHeader("X-Mailer", "jAVAmAILER");
msg.setSentDate(new Date());
Transport.send(msg);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
try {
Properties props = System.getProperties();
props.put("mail.smtp.host", "smtp.sampledomain.com");
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("gaylord.focker@hollywood.com"));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("father@family.com"));
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse("mother@family.com"));
msg.setSubject("subject");
msg.setText("message body");
msg.setHeader("X-Mailer", "jAVAmAILER");
msg.setSentDate(new Date());
Transport.send(msg);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
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
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();
}
csharp
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(
@"<shopping>
<item name='bread' quantity='3' price='2.50'/>
<item name='milk' quantity='2' price='3.50'/>
</shopping>");
string decimalSeparator= System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;
double sum=0;
foreach(System.Xml.XmlNode nodo in doc.SelectNodes("/shopping/item")){
sum += int.Parse(nodo.Attributes["quantity"].InnerText) * double.Parse(nodo.Attributes["price"].InnerText.Replace(".",decimalSeparator));
}
Console.WriteLine("{0:#.00}",sum);
doc.LoadXml(
@"<shopping>
<item name='bread' quantity='3' price='2.50'/>
<item name='milk' quantity='2' price='3.50'/>
</shopping>");
string decimalSeparator= System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;
double sum=0;
foreach(System.Xml.XmlNode nodo in doc.SelectNodes("/shopping/item")){
sum += int.Parse(nodo.Attributes["quantity"].InnerText) * double.Parse(nodo.Attributes["price"].InnerText.Replace(".",decimalSeparator));
}
Console.WriteLine("{0:#.00}",sum);
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
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>
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();
}
csharp
string cvs ="bread,3,2.50\nmilk,2,3.50";
IList<string> rows = cvs.Split('\n');
System.Text.StringBuilder sb = new System.Text.StringBuilder("<shopping>");
foreach(string row in rows){
IList<string> data = row.Split(',');
sb.AppendFormat("<item name='{0}' quantity='{1}' price='{2}' />",data[0],data[1],data[2]);
}
sb.Append("</shopping>");
IList<string> rows = cvs.Split('\n');
System.Text.StringBuilder sb = new System.Text.StringBuilder("<shopping>");
foreach(string row in rows){
IList<string> data = row.Split(',');
sb.AppendFormat("<item name='{0}' quantity='{1}' price='{2}' />",data[0],data[1],data[2]);
}
sb.Append("</shopping>");
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*))
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]
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))
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.
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));
}
csharp
public static int gcd(int a, int b)
{
if (b == 0)
return a;
else
return gcd(b, a % b);
}
{
if (b == 0)
return a;
else
return gcd(b, a % b);
}
clojure
(defn gcd [a b]
(if (zero? b)
a
(recur b (mod b a))))
(if (zero? b)
a
(recur b (mod b a))))
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.
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))
Subdivide A Problem To A Pool Of Workers (No Shared Data)
Take a hard to compute problem and split it up between multiple worker threads. In your solution, try to fully utilize available cores or processors. (I'm looking at you, Python!)
Note: In this question, there should be no need for shared state between worker threads while the problem is being solved. Only after every thread completes computation are the answers recombined into a single output.
Example:
-Input-
(In python syntax)
In other words, a list of random strings.
-Output-
(In python syntax)
In other words, all possible permutations of each input string are computed.
Note: In this question, there should be no need for shared state between worker threads while the problem is being solved. Only after every thread completes computation are the answers recombined into a single output.
Example:
-Input-
(In python syntax)
["ab", "we", "tfe", "aoj"]
In other words, a list of random strings.
-Output-
(In python syntax)
[ ["ab", "ba", "aa", "bb", "a", "b"], ["we", "ew", "ww", "ee", "w", "e"], ...
In other words, all possible permutations of each input string are computed.
java
public class ParallelPermutations {
final AtomicInteger cnt = new AtomicInteger(0);
final List<Set<String>> permutations = new ArrayList<Set<String>>();
public static void main(String[] args) {
new ParallelPermutations(Arrays.asList(args));
}
public ParallelPermutations(List<String> words) {
for (final String word : words) {
new Thread(new Runnable() {
public void run() {
cnt.incrementAndGet() ;
Set<String> permutationSet = new HashSet<String>();
for (int i = 0; i < word.length(); i++)
for (int j = i + 1; j <= word.length(); j++)
permutations("", word.substring(i, j),
permutationSet);
permutations.add(permutationSet);
if (cnt.decrementAndGet() == 0)
synchronized (ParallelPermutations.this) {
ParallelPermutations.this.notify();
}
}
private void permutations(String prefix, String word, Set<String> permutations) {
int N = word.length();
if (N == 0)
permutations.add(prefix);
else
for (int i = 0; i < N; i++)
permutations(
prefix + word.charAt(i),
word.substring(0, i) + word.substring(i + 1, N),
permutations);
}
}).start();
}
synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().isInterrupted();
}
}
System.out.println(permutations);
}
}
final AtomicInteger cnt = new AtomicInteger(0);
final List<Set<String>> permutations = new ArrayList<Set<String>>();
public static void main(String[] args) {
new ParallelPermutations(Arrays.asList(args));
}
public ParallelPermutations(List<String> words) {
for (final String word : words) {
new Thread(new Runnable() {
public void run() {
cnt.incrementAndGet() ;
Set<String> permutationSet = new HashSet<String>();
for (int i = 0; i < word.length(); i++)
for (int j = i + 1; j <= word.length(); j++)
permutations("", word.substring(i, j),
permutationSet);
permutations.add(permutationSet);
if (cnt.decrementAndGet() == 0)
synchronized (ParallelPermutations.this) {
ParallelPermutations.this.notify();
}
}
private void permutations(String prefix, String word, Set<String> permutations) {
int N = word.length();
if (N == 0)
permutations.add(prefix);
else
for (int i = 0; i < N; i++)
permutations(
prefix + word.charAt(i),
word.substring(0, i) + word.substring(i + 1, N),
permutations);
}
}).start();
}
synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().isInterrupted();
}
}
System.out.println(permutations);
}
}
public class ParallelPermutations {
public static void main(String[] words) throws Exception {
if(words.length==0)
words = new String[] {"ab", "we", "tfe", "aoj"};
ParallelPermutations permutations = new ParallelPermutations();
Map<String,Set<String>> wordPermutationSet =
permutations.calculate(words);
for(Map.Entry<String,Set<String>> e : wordPermutationSet.entrySet())
System.out.println(e.getKey()+" > "+e.getValue());
System.out.println(permutations.getNumberOfJobSpawned ()+" job(s) have been spawned");
}
private AtomicInteger jobSpawnedCounter = new AtomicInteger();
private ExecutorService workers ;
private ConcurrentLinkedQueue<Future<PermutationTask>> jobSpawned = newQueue();
public ParallelPermutations () {
int availableProcessors = Runtime.getRuntime().availableProcessors();
// create a thread pool according to the number of proc.
workers = Executors.newFixedThreadPool(availableProcessors);
}
private void spawn(PermutationTask task) {
Future<PermutationTask> spawned = workers.submit(task);
jobSpawnedCounter.incrementAndGet();
jobSpawned.add(spawned);
}
public int getNumberOfJobSpawned () {
return jobSpawnedCounter.get();
}
public Map<String,Set<String>> calculate (String[] words)
throws InterruptedException, ExecutionException
{
// submit all tasks, they will spawn sub-tasks by themselves
for(String word:words)
spawn(new PermutationTask(word));
Map<String,Set<String>> wordPermutationSet = newMap ();
Future<PermutationTask> spawned;
while( (spawned=jobSpawned.poll()) != null) {
// this will wait until the result is available
// this should also handle the fact that a sub-task is spawn
// and then added in the 'jobSpawned' before its parent is done
PermutationTask task = spawned.get();
String word = task.getWord();
Set<String> founds = task.getPermutationSet();
Set<String> alreadyFounds = wordPermutationSet.get(word);
if(alreadyFounds!=null)
alreadyFounds.addAll(founds);
else
wordPermutationSet.put(word, founds);
}
return wordPermutationSet;
}
private class PermutationTask implements Callable<PermutationTask> {
private final Set<String> permutationSet = new HashSet<String>();
private final String word;
private final int initialPos;
private final Stack<Integer> indicesUsed;
public PermutationTask(String word) {
this(word, 0, new Stack<Integer>());
}
/** sub task entry point */
public PermutationTask(String word,
int initialPos,
Stack<Integer> indicesUsed) {
this.word = word;
this.initialPos = 0;
this.indicesUsed = indicesUsed;
}
/** the word this task is working on*/
public String getWord() {
return word;
}
/** permutations set of this task */
public Set<String> getPermutationSet() {
return permutationSet;
}
/**
* perform the task specific calculation
* @see Callable
*/
public PermutationTask call() throws Exception {
calculatePermutation(initialPos, indicesUsed);
return this;
}
/**
* The algorithm part of the problem. The main interest is the sub-task
* spawning. When Java 7 will be available there would be a better
* alternative with the built-in fork/join framework.
*/
private void calculatePermutation(int currentPos, Stack<Integer> indicesUsed) {
final int maxLetterPerWord = word.length();
if(indicesUsed.size()>=maxLetterPerWord) {
return;
}
final StringBuilder builder = new StringBuilder();
for (int i = 0, length = word.length(); i < length; i++) {
if(indicesUsed.contains(i) && distinctIndices)
continue;
indicesUsed.push(i);
if(indicesUsed.size()>=MIN_LETTER_PER_WORD) {
builder.setLength(0);
for(Integer index: indicesUsed)
builder.append(word.charAt(index));
permutationSet.add(builder.toString());
}
// spawn a sub task to perform the next pos. calculation
spawn(new PermutationTask(word, currentPos+1, copy(indicesUsed)));
indicesUsed.pop();
}
}
}
/* algorithm parameters : the minimum number of letter per word */
private static int MIN_LETTER_PER_WORD = 1;
/* allow duplicated letters in the word found */
private static boolean distinctIndices = true;
/* factory method */
private static <T> ConcurrentLinkedQueue<T> newQueue () {
return new ConcurrentLinkedQueue<T>();
}
/* factory method */
private static <K,V> Map<K,V> newMap () {
return new HashMap<K,V>();
}
/* factory method */
private static Stack<Integer> copy(Stack<Integer> stack) {
Stack<Integer> copy = new Stack<Integer>();
copy.addAll(stack);
return copy;
}
}
public static void main(String[] words) throws Exception {
if(words.length==0)
words = new String[] {"ab", "we", "tfe", "aoj"};
ParallelPermutations permutations = new ParallelPermutations();
Map<String,Set<String>> wordPermutationSet =
permutations.calculate(words);
for(Map.Entry<String,Set<String>> e : wordPermutationSet.entrySet())
System.out.println(e.getKey()+" > "+e.getValue());
System.out.println(permutations.getNumberOfJobSpawned ()+" job(s) have been spawned");
}
private AtomicInteger jobSpawnedCounter = new AtomicInteger();
private ExecutorService workers ;
private ConcurrentLinkedQueue<Future<PermutationTask>> jobSpawned = newQueue();
public ParallelPermutations () {
int availableProcessors = Runtime.getRuntime().availableProcessors();
// create a thread pool according to the number of proc.
workers = Executors.newFixedThreadPool(availableProcessors);
}
private void spawn(PermutationTask task) {
Future<PermutationTask> spawned = workers.submit(task);
jobSpawnedCounter.incrementAndGet();
jobSpawned.add(spawned);
}
public int getNumberOfJobSpawned () {
return jobSpawnedCounter.get();
}
public Map<String,Set<String>> calculate (String[] words)
throws InterruptedException, ExecutionException
{
// submit all tasks, they will spawn sub-tasks by themselves
for(String word:words)
spawn(new PermutationTask(word));
Map<String,Set<String>> wordPermutationSet = newMap ();
Future<PermutationTask> spawned;
while( (spawned=jobSpawned.poll()) != null) {
// this will wait until the result is available
// this should also handle the fact that a sub-task is spawn
// and then added in the 'jobSpawned' before its parent is done
PermutationTask task = spawned.get();
String word = task.getWord();
Set<String> founds = task.getPermutationSet();
Set<String> alreadyFounds = wordPermutationSet.get(word);
if(alreadyFounds!=null)
alreadyFounds.addAll(founds);
else
wordPermutationSet.put(word, founds);
}
return wordPermutationSet;
}
private class PermutationTask implements Callable<PermutationTask> {
private final Set<String> permutationSet = new HashSet<String>();
private final String word;
private final int initialPos;
private final Stack<Integer> indicesUsed;
public PermutationTask(String word) {
this(word, 0, new Stack<Integer>());
}
/** sub task entry point */
public PermutationTask(String word,
int initialPos,
Stack<Integer> indicesUsed) {
this.word = word;
this.initialPos = 0;
this.indicesUsed = indicesUsed;
}
/** the word this task is working on*/
public String getWord() {
return word;
}
/** permutations set of this task */
public Set<String> getPermutationSet() {
return permutationSet;
}
/**
* perform the task specific calculation
* @see Callable
*/
public PermutationTask call() throws Exception {
calculatePermutation(initialPos, indicesUsed);
return this;
}
/**
* The algorithm part of the problem. The main interest is the sub-task
* spawning. When Java 7 will be available there would be a better
* alternative with the built-in fork/join framework.
*/
private void calculatePermutation(int currentPos, Stack<Integer> indicesUsed) {
final int maxLetterPerWord = word.length();
if(indicesUsed.size()>=maxLetterPerWord) {
return;
}
final StringBuilder builder = new StringBuilder();
for (int i = 0, length = word.length(); i < length; i++) {
if(indicesUsed.contains(i) && distinctIndices)
continue;
indicesUsed.push(i);
if(indicesUsed.size()>=MIN_LETTER_PER_WORD) {
builder.setLength(0);
for(Integer index: indicesUsed)
builder.append(word.charAt(index));
permutationSet.add(builder.toString());
}
// spawn a sub task to perform the next pos. calculation
spawn(new PermutationTask(word, currentPos+1, copy(indicesUsed)));
indicesUsed.pop();
}
}
}
/* algorithm parameters : the minimum number of letter per word */
private static int MIN_LETTER_PER_WORD = 1;
/* allow duplicated letters in the word found */
private static boolean distinctIndices = true;
/* factory method */
private static <T> ConcurrentLinkedQueue<T> newQueue () {
return new ConcurrentLinkedQueue<T>();
}
/* factory method */
private static <K,V> Map<K,V> newMap () {
return new HashMap<K,V>();
}
/* factory method */
private static Stack<Integer> copy(Stack<Integer> stack) {
Stack<Integer> copy = new Stack<Integer>();
copy.addAll(stack);
return copy;
}
}
clojure
(defn perm-chars [l]
"Returns a list of all possible permutations of strings with the
same size as the input string. This function will return duplicates
if the same character occurs multiple time in the string.
Ex: ab -> (aa ab ba ab)"
(if (string? l)
(recur (repeat (count l) l))
(let [s (first l)
r (rest l)]
(if (empty? r)
(map identity s)
(->> s
(map (fn [c] (map #(str c %) (perm-chars r))))
(flatten))))))
(defn perm-sz [s]
"Returns a list of all possible permutations of the input
string. May return duplicats.
Ex: ab -> (aa ab ba bb a b a b)"
(if-not (empty? s)
(let [r (perm-chars s)]
(if (= (count s) 1)
r
(->> r
(map #(perm-sz (apply str (rest %))))
(flatten)
(lazy-cat r))))))
(defn perm [s]
"Returns a list of all possible permutations of the input
string. The list of string is sorted and does not contain
duplicates.
Ex: ab -> (a aa ab b ba bb)"
(->> (reduce (fn [s e] (conj s e)) #{} (perm-sz s))
(map str)
(sort)))
(println (pmap perm ["ab" "we" "tfe" "aoj"]))
"Returns a list of all possible permutations of strings with the
same size as the input string. This function will return duplicates
if the same character occurs multiple time in the string.
Ex: ab -> (aa ab ba ab)"
(if (string? l)
(recur (repeat (count l) l))
(let [s (first l)
r (rest l)]
(if (empty? r)
(map identity s)
(->> s
(map (fn [c] (map #(str c %) (perm-chars r))))
(flatten))))))
(defn perm-sz [s]
"Returns a list of all possible permutations of the input
string. May return duplicats.
Ex: ab -> (aa ab ba bb a b a b)"
(if-not (empty? s)
(let [r (perm-chars s)]
(if (= (count s) 1)
r
(->> r
(map #(perm-sz (apply str (rest %))))
(flatten)
(lazy-cat r))))))
(defn perm [s]
"Returns a list of all possible permutations of the input
string. The list of string is sorted and does not contain
duplicates.
Ex: ab -> (a aa ab b ba bb)"
(->> (reduce (fn [s e] (conj s e)) #{} (perm-sz s))
(map str)
(sort)))
(println (pmap perm ["ab" "we" "tfe" "aoj"]))
(require 'cojure.contrib.combinatorics)
(pmap (fn [str]
(apply concat (map #(selections str (inc %))
(range (count str)))))
["ab", "we", "tfe", "aoj"])
(pmap (fn [str]
(apply concat (map #(selections str (inc %))
(range (count str)))))
["ab", "we", "tfe", "aoj"])
Subdivide A Problem To A Pool Of Workers (Shared Data)
Take a hard to compute problem and split it up between multiple worker threads. In your solution, try to fully utilize available cores or processors. (I'm looking at you, Python!)
Note: In this question, there should be a need for shared state between worker threads while the problem is being solved.
Example:
-Conway Game of Life-
From Wikipedia:
The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, live or dead. Every cell interacts with its eight neighbors, which are the cells that are directly horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:
1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
2. Any live cell with more than three live neighbours dies, as if by overcrowding.
3. Any live cell with two or three live neighbours lives on to the next generation.
4. Any dead cell with exactly three live neighbours becomes a live cell.
The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed—births and deaths happen simultaneously, and the discrete moment at which this happens is sometimes called a tick (in other words, each generation is a pure function of the one before). The rules continue to be applied repeatedly to create further generations.
--However, for our purposes, we will assign a size to the game
Notice that in this problem, at each step or
Note: In this question, there should be a need for shared state between worker threads while the problem is being solved.
Example:
-Conway Game of Life-
From Wikipedia:
The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, live or dead. Every cell interacts with its eight neighbors, which are the cells that are directly horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:
1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
2. Any live cell with more than three live neighbours dies, as if by overcrowding.
3. Any live cell with two or three live neighbours lives on to the next generation.
4. Any dead cell with exactly three live neighbours becomes a live cell.
The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed—births and deaths happen simultaneously, and the discrete moment at which this happens is sometimes called a tick (in other words, each generation is a pure function of the one before). The rules continue to be applied repeatedly to create further generations.
--However, for our purposes, we will assign a size to the game
"board": 2^k * 2^k . That is, the board should be easy to subdivide.
Notice that in this problem, at each step or
"tick", each thread/process will need to share data with its neighborhood.
java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Life {
private static final int K = 4;
private static final int ITERATIONS = 10;
private static final boolean ALIVE = true;
private static final boolean DEAD = false;
private static final Board SEED = new Board(new boolean[][] {
{ DEAD, DEAD, DEAD, DEAD, DEAD, ALIVE, DEAD, ALIVE },
{ DEAD, ALIVE, ALIVE, DEAD, DEAD, DEAD, ALIVE, ALIVE },
{ DEAD, ALIVE, ALIVE, DEAD, DEAD, DEAD, ALIVE, DEAD },
{ DEAD, DEAD, DEAD, DEAD, ALIVE, DEAD, DEAD, DEAD },
{ DEAD, DEAD, DEAD, DEAD, ALIVE, ALIVE, DEAD, DEAD },
{ DEAD, DEAD, DEAD, DEAD, DEAD, ALIVE, ALIVE, ALIVE },
{ DEAD, DEAD, DEAD, DEAD, ALIVE, ALIVE, DEAD, DEAD },
{ DEAD, DEAD, DEAD, DEAD, ALIVE, DEAD, DEAD, DEAD } });
public static void main(String[] args) {
Life life = new Life(K, SEED);
System.out.println(life);
for (int i = 0; i < ITERATIONS; i++) {
life.tick();
System.out.println(life);
}
}
private final Board board, oldBoard;
public Life(int k, Board seed) {
int width = 1 << k;
int height = 1 << k;
board = new Board(width, height);
oldBoard = new Board(width, height);
seed.copyTo(board);
}
private void tick() {
board.copyTo(oldBoard);
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
for (int y = 0; y < board.height; y++)
for (int x = 0; x < board.width; x++)
executor.execute(new Evaluator(x, y));
executor.shutdown();
try {
executor.awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public Board getBoard() {
return board;
}
@Override
public String toString() {
return getBoard().toString();
}
private class Evaluator implements Runnable {
private final int x, y;
Evaluator(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public void run() {
boolean state = DEAD;
int neighbors = oldBoard.countNeighbors(x, y);
switch (neighbors) {
case 2:
if (oldBoard.get(x, y) == DEAD)
break;
case 3:
state = ALIVE;
}
board.set(x, y, state);
}
}
public static class Board {
private final boolean[][] data;
private final int width, height;
public Board(boolean[][] data) {
this.data = data;
height = data.length;
width = data[0].length;
}
public Board(int width, int height) {
this.width = width;
this.height = height;
data = new boolean[height][width];
clear();
}
public void clear() {
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
set(x, y, DEAD);
}
public void copyTo(Board target) {
int yo = (target.height - height) / 2;
int xo = (target.width - width) / 2;
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++) {
int dx = x + xo;
int dy = y + yo;
if (0 <= dx && dx < target.width && 0 <= dy && dy < target.height)
target.set(dx, dy, get(x, y));
}
}
public void set(int x, int y, boolean state) {
data[y][x] = state;
}
public boolean get(int x, int y) {
return data[y][x];
}
public int countNeighbors(int x, int y) {
int count = 0;
for (int y1 = Math.max(y - 1, 0), y2 = Math.min(y + 1, height - 1); y1 <= y2; y1++)
for (int x1 = Math.max(x - 1, 0), x2 = Math.min(x + 1, width - 1); x1 <= x2; x1++)
if (((y1 != y) || (x1 != x)) && get(x1, y1) == ALIVE)
count++;
return count;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int x = 0; x < width + 2; x++)
sb.append('#');
sb.append('\n');
for (int y = 0; y < height; y++) {
sb.append('#');
for (int x = 0; x < width; x++)
sb.append(get(x, y) == ALIVE ? '*' : ' ');
sb.append("#\n");
}
for (int x = 0; x < width + 2; x++)
sb.append('#');
return sb.toString();
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
}
}
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Life {
private static final int K = 4;
private static final int ITERATIONS = 10;
private static final boolean ALIVE = true;
private static final boolean DEAD = false;
private static final Board SEED = new Board(new boolean[][] {
{ DEAD, DEAD, DEAD, DEAD, DEAD, ALIVE, DEAD, ALIVE },
{ DEAD, ALIVE, ALIVE, DEAD, DEAD, DEAD, ALIVE, ALIVE },
{ DEAD, ALIVE, ALIVE, DEAD, DEAD, DEAD, ALIVE, DEAD },
{ DEAD, DEAD, DEAD, DEAD, ALIVE, DEAD, DEAD, DEAD },
{ DEAD, DEAD, DEAD, DEAD, ALIVE, ALIVE, DEAD, DEAD },
{ DEAD, DEAD, DEAD, DEAD, DEAD, ALIVE, ALIVE, ALIVE },
{ DEAD, DEAD, DEAD, DEAD, ALIVE, ALIVE, DEAD, DEAD },
{ DEAD, DEAD, DEAD, DEAD, ALIVE, DEAD, DEAD, DEAD } });
public static void main(String[] args) {
Life life = new Life(K, SEED);
System.out.println(life);
for (int i = 0; i < ITERATIONS; i++) {
life.tick();
System.out.println(life);
}
}
private final Board board, oldBoard;
public Life(int k, Board seed) {
int width = 1 << k;
int height = 1 << k;
board = new Board(width, height);
oldBoard = new Board(width, height);
seed.copyTo(board);
}
private void tick() {
board.copyTo(oldBoard);
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
for (int y = 0; y < board.height; y++)
for (int x = 0; x < board.width; x++)
executor.execute(new Evaluator(x, y));
executor.shutdown();
try {
executor.awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public Board getBoard() {
return board;
}
@Override
public String toString() {
return getBoard().toString();
}
private class Evaluator implements Runnable {
private final int x, y;
Evaluator(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public void run() {
boolean state = DEAD;
int neighbors = oldBoard.countNeighbors(x, y);
switch (neighbors) {
case 2:
if (oldBoard.get(x, y) == DEAD)
break;
case 3:
state = ALIVE;
}
board.set(x, y, state);
}
}
public static class Board {
private final boolean[][] data;
private final int width, height;
public Board(boolean[][] data) {
this.data = data;
height = data.length;
width = data[0].length;
}
public Board(int width, int height) {
this.width = width;
this.height = height;
data = new boolean[height][width];
clear();
}
public void clear() {
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
set(x, y, DEAD);
}
public void copyTo(Board target) {
int yo = (target.height - height) / 2;
int xo = (target.width - width) / 2;
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++) {
int dx = x + xo;
int dy = y + yo;
if (0 <= dx && dx < target.width && 0 <= dy && dy < target.height)
target.set(dx, dy, get(x, y));
}
}
public void set(int x, int y, boolean state) {
data[y][x] = state;
}
public boolean get(int x, int y) {
return data[y][x];
}
public int countNeighbors(int x, int y) {
int count = 0;
for (int y1 = Math.max(y - 1, 0), y2 = Math.min(y + 1, height - 1); y1 <= y2; y1++)
for (int x1 = Math.max(x - 1, 0), x2 = Math.min(x + 1, width - 1); x1 <= x2; x1++)
if (((y1 != y) || (x1 != x)) && get(x1, y1) == ALIVE)
count++;
return count;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int x = 0; x < width + 2; x++)
sb.append('#');
sb.append('\n');
for (int y = 0; y < height; y++) {
sb.append('#');
for (int x = 0; x < width; x++)
sb.append(get(x, y) == ALIVE ? '*' : ' ');
sb.append("#\n");
}
for (int x = 0; x < width + 2; x++)
sb.append('#');
return sb.toString();
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
}
}
clojure
; This is a "glider"
(def *start*
[".O......"
"..O....."
"OOO....."
"........"
"........"
"........"
"........"])
(def *width* (count (first *start*)))
(def *height* (count *start*))
(def *live* \O)
(def *dead* \.)
(def *n-generations-to-show* 3)
(defn cell-at
([b coord]
(cell-at b coord {:col 0 :row 0}))
([b coord offset]
(let [x (mod (+ (:col coord) (:col offset)) *width*)
y (mod (+ (:row coord) (:row offset)) *height*)]
(nth (nth b y) x))))
(defn neighbor-count [b coord]
(->> (for [x (range -1 2) y (range -1 2)] {:col x :row y})
(filter #(not (= {:col 0 :row 0} %)))
(map (partial cell-at b coord))
(reduce (fn [sum n] (+ sum (if (= *live* n) 1 0))) 0)))
(defn next-generation-cell [b coord]
(let [nc (neighbor-count b coord)]
(cond (< nc 2) *dead*
(> nc 3) *dead*
(= nc 3) *live*
true (cell-at b coord))))
(defn next-generation-row [b row]
(->> (range *width*)
(map #(next-generation-cell b {:col % :row row}))
(apply str)))
(defn next-generation [b]
(->> (range *height*)
(pmap #(next-generation-row b %))))
(defn generation-seq [b]
(let [ng (next-generation b)]
(lazy-seq (cons ng (generation-seq ng)))))
(doseq [g (take *n-generations-to-show* (generation-seq *start*))]
(doseq [l g]
(println l))
(println))
(shutdown-agents)
; This version calculates each separate line on a separate thread (pmap in next-generation)
(def *start*
[".O......"
"..O....."
"OOO....."
"........"
"........"
"........"
"........"])
(def *width* (count (first *start*)))
(def *height* (count *start*))
(def *live* \O)
(def *dead* \.)
(def *n-generations-to-show* 3)
(defn cell-at
([b coord]
(cell-at b coord {:col 0 :row 0}))
([b coord offset]
(let [x (mod (+ (:col coord) (:col offset)) *width*)
y (mod (+ (:row coord) (:row offset)) *height*)]
(nth (nth b y) x))))
(defn neighbor-count [b coord]
(->> (for [x (range -1 2) y (range -1 2)] {:col x :row y})
(filter #(not (= {:col 0 :row 0} %)))
(map (partial cell-at b coord))
(reduce (fn [sum n] (+ sum (if (= *live* n) 1 0))) 0)))
(defn next-generation-cell [b coord]
(let [nc (neighbor-count b coord)]
(cond (< nc 2) *dead*
(> nc 3) *dead*
(= nc 3) *live*
true (cell-at b coord))))
(defn next-generation-row [b row]
(->> (range *width*)
(map #(next-generation-cell b {:col % :row row}))
(apply str)))
(defn next-generation [b]
(->> (range *height*)
(pmap #(next-generation-row b %))))
(defn generation-seq [b]
(let [ng (next-generation b)]
(lazy-seq (cons ng (generation-seq ng)))))
(doseq [g (take *n-generations-to-show* (generation-seq *start*))]
(doseq [l g]
(println l))
(println))
(shutdown-agents)
; This version calculates each separate line on a separate thread (pmap in next-generation)
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.
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")))
Create read/write lock on a shared resource.
Create multiple threads or processes who are either readers or writers. There should be more readers then writers.
(From Wikipedia):
Multiple readers can read the data in parallel but an exclusive lock is needed while writing the data. When a writer is writing the data, readers will be blocked until the writer is finished writing.
Example:
-Output-
Thread one says that the value is 8.
Thread three says that the value is 8.
Thread two is taking the lock.
Thread four tried to read the value, but could not.
Thread five tried to write to the value, but could not.
Thread two is changing the value to 9.
Thread two is releasing the lock.
Thread four says that the value is 9.
...
--Notice that when a needed resource is locked, a thread can set a timer and try again in the future, or wait to be notified that the resource is no longer locked.
(From Wikipedia):
Multiple readers can read the data in parallel but an exclusive lock is needed while writing the data. When a writer is writing the data, readers will be blocked until the writer is finished writing.
Example:
-Output-
Thread one says that the value is 8.
Thread three says that the value is 8.
Thread two is taking the lock.
Thread four tried to read the value, but could not.
Thread five tried to write to the value, but could not.
Thread two is changing the value to 9.
Thread two is releasing the lock.
Thread four says that the value is 9.
...
--Notice that when a needed resource is locked, a thread can set a timer and try again in the future, or wait to be notified that the resource is no longer locked.
java
public class ParallelPermutations {
Lock lock = new ReentrantLock();
Integer value = 8;
public static void main(String[] args) {
new ParallelPermutations(Arrays.asList(args));
}
public ParallelPermutations(List<String> words) {
for (int i = 0; i < 20; i++) {
final Integer cnt = i ;
if ( i % 3 == 0) {
new Thread(new Runnable() {
public void run() {
if ( ! lock.tryLock() ) {
System.out.println("Thread " + cnt + " tried to write the value, but could not.") ;
lock.lock();
}
value = (int) (Math.random() * 10);
System.out.println("Thread " + cnt + " is changing the value to " + value ) ;
lock.unlock();
System.out.println("Thread " + cnt + " is releasing the lock.") ;
}
}).start();
} else {
new Thread(new Runnable() {
public void run() {
if ( ! lock.tryLock() ) {
System.out.println("Thread " + cnt + " tried to read the value, but could not.") ;
lock.lock() ;
}
System.out.println("Thread " + cnt + " says that the value is " + value + ".") ;
lock.unlock();
}
}).start();
}
}
}
}
Lock lock = new ReentrantLock();
Integer value = 8;
public static void main(String[] args) {
new ParallelPermutations(Arrays.asList(args));
}
public ParallelPermutations(List<String> words) {
for (int i = 0; i < 20; i++) {
final Integer cnt = i ;
if ( i % 3 == 0) {
new Thread(new Runnable() {
public void run() {
if ( ! lock.tryLock() ) {
System.out.println("Thread " + cnt + " tried to write the value, but could not.") ;
lock.lock();
}
value = (int) (Math.random() * 10);
System.out.println("Thread " + cnt + " is changing the value to " + value ) ;
lock.unlock();
System.out.println("Thread " + cnt + " is releasing the lock.") ;
}
}).start();
} else {
new Thread(new Runnable() {
public void run() {
if ( ! lock.tryLock() ) {
System.out.println("Thread " + cnt + " tried to read the value, but could not.") ;
lock.lock() ;
}
System.out.println("Thread " + cnt + " says that the value is " + value + ".") ;
lock.unlock();
}
}).start();
}
}
}
}
clojure
; NOTE! Using explicit locking is NOT the Clojure way. It was done
; this way in order to comply exactly with the problem
; specification. Sharing data in Clojure would normally be done by
; using "atom", "agent" or "ref" depending on situation. None of those
; methods would ever result in the reader not being able to read (as
; required by the problem) since reading is wait-free in clojure.
(def *readers* (map #(agent %) '("one" "two" "three")))
(def *writers* (map #(agent %) '("four" "five")))
(def *mutex* (agent :unlocked))
(def *value* 0)
; mutex implementation
(defn lock [state who success-fn fail-fn]
(send who (if (= state :locked) fail-fn success-fn))
:locked)
(defn unlock [mutex]
:unlocked)
; Must be invoked with send-off since this handler blocks
(defn rand-sleep [state next-fn]
(Thread/sleep (rand-int 5))
(send *agent* next-fn)
state)
; Reader functions
(declare try-read)
(defn reader-got-lock [name]
(println (format "Thread %s says that the value is %d." name *value*))
(send *mutex* unlock)
(send-off *agent* rand-sleep try-read)
name)
(defn reader-did-not-get-lock [name]
(println (format "Thread %s tried to read the value, but could not." name))
(send-off *agent* rand-sleep try-read)
name)
(defn try-read [name]
(send *mutex* lock *agent* reader-got-lock reader-did-not-get-lock)
name)
; Writer functions
(declare try-write)
(defn writer-got-lock [name]
(println (format "Thread %s is taking the lock." name))
(def *value* (rand-int 10))
(println (format "Thread %s is changing the value to %d." name *value*))
(send *mutex* unlock)
(println (format "Thread %s is relasing the lock." name))
(send-off *agent* rand-sleep try-write)
name)
(defn writer-did-not-get-lock [name]
(println (format "Thread %s tried to write the value, but could not." name))
(send-off *agent* rand-sleep try-write)
name)
(defn try-write [name]
(send *mutex* lock *agent* writer-got-lock writer-did-not-get-lock)
name)
(dorun (map #(send % try-write) *writers*))
(dorun (map #(send % try-read) *readers*))
; this way in order to comply exactly with the problem
; specification. Sharing data in Clojure would normally be done by
; using "atom", "agent" or "ref" depending on situation. None of those
; methods would ever result in the reader not being able to read (as
; required by the problem) since reading is wait-free in clojure.
(def *readers* (map #(agent %) '("one" "two" "three")))
(def *writers* (map #(agent %) '("four" "five")))
(def *mutex* (agent :unlocked))
(def *value* 0)
; mutex implementation
(defn lock [state who success-fn fail-fn]
(send who (if (= state :locked) fail-fn success-fn))
:locked)
(defn unlock [mutex]
:unlocked)
; Must be invoked with send-off since this handler blocks
(defn rand-sleep [state next-fn]
(Thread/sleep (rand-int 5))
(send *agent* next-fn)
state)
; Reader functions
(declare try-read)
(defn reader-got-lock [name]
(println (format "Thread %s says that the value is %d." name *value*))
(send *mutex* unlock)
(send-off *agent* rand-sleep try-read)
name)
(defn reader-did-not-get-lock [name]
(println (format "Thread %s tried to read the value, but could not." name))
(send-off *agent* rand-sleep try-read)
name)
(defn try-read [name]
(send *mutex* lock *agent* reader-got-lock reader-did-not-get-lock)
name)
; Writer functions
(declare try-write)
(defn writer-got-lock [name]
(println (format "Thread %s is taking the lock." name))
(def *value* (rand-int 10))
(println (format "Thread %s is changing the value to %d." name *value*))
(send *mutex* unlock)
(println (format "Thread %s is relasing the lock." name))
(send-off *agent* rand-sleep try-write)
name)
(defn writer-did-not-get-lock [name]
(println (format "Thread %s tried to write the value, but could not." name))
(send-off *agent* rand-sleep try-write)
name)
(defn try-write [name]
(send *mutex* lock *agent* writer-got-lock writer-did-not-get-lock)
name)
(dorun (map #(send % try-write) *writers*))
(dorun (map #(send % try-read) *readers*))
Separate user interaction and computation.
Allow your program to accept user interaction while conducting a long running computation.
Example:
Hello user! Please input a string to permute: (input thread)
abcdef
Passing on abcdef... (input thread)
Please input another string to permute: (input thread)
lol
Passing on lol... (input thread)
Done Work On abcdef! (worker thread)
Please input another string to permute: (input thread)
EXIT
Quitting, I
--Notice, that this could be accomplished on the command line or within a GUI. The point is that computation and user interaction should take place on separate threads of control.
Example:
Hello user! Please input a string to permute: (input thread)
abcdef
Passing on abcdef... (input thread)
Please input another string to permute: (input thread)
lol
Passing on lol... (input thread)
Done Work On abcdef! (worker thread)
["abcdef", "abcefd", ... ] (worker thread)
Please input another string to permute: (input thread)
EXIT
Quitting, I
'll let my worker thread know... (input thread)
We're quitting! Alright! (worker thread)
--Notice, that this could be accomplished on the command line or within a GUI. The point is that computation and user interaction should take place on separate threads of control.
java
public class BackgroundComputation {
final protected Queue<Thread> threads = new ConcurrentLinkedQueue<Thread>() ;
public BackgroundComputation() {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
try {
while (true) {
System.out.print("Enter string to permutate: ");
final String word = r.readLine();
if ("EXIT".equals(word) ) {
System.out.println("I'll let my worker thread know... (input thread)") ;
while (! threads.isEmpty())
threads.poll().stop(new ThreadDeath()) ;
break ;
}
Thread t = new Thread(new Runnable() {
public void run() {
try {
Set<String> permutationSet = new HashSet<String>();
for (int i = 0; i < word.length(); i++)
for (int j = i + 1; j <= word.length(); j++)
permutations("", word.substring(i, j), permutationSet);
System.out.println();
System.out.println("Received results: " + permutationSet);
System.out.print("Enter string to permutate: ");
} catch (ThreadDeath e) {
System.out.println("We're quitting! Alright!");
}
}
private void permutations(String prefix, String word, Set<String> permutations) {
int N = word.length();
if (N == 0)
permutations.add(prefix);
else
for (int i = 0; i < N; i++)
permutations(
prefix + word.charAt(i),
word.substring(0, i) + word.substring(i + 1, N),
permutations
);
}
});
t.start();
threads.add(t);
}
} catch (IOException ioe) {
System.out.println("IO error trying to read your name!");
System.exit(1);
}
}
public static void main(String[] args) {
new BackgroundComputation() ;
}
}
final protected Queue<Thread> threads = new ConcurrentLinkedQueue<Thread>() ;
public BackgroundComputation() {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
try {
while (true) {
System.out.print("Enter string to permutate: ");
final String word = r.readLine();
if ("EXIT".equals(word) ) {
System.out.println("I'll let my worker thread know... (input thread)") ;
while (! threads.isEmpty())
threads.poll().stop(new ThreadDeath()) ;
break ;
}
Thread t = new Thread(new Runnable() {
public void run() {
try {
Set<String> permutationSet = new HashSet<String>();
for (int i = 0; i < word.length(); i++)
for (int j = i + 1; j <= word.length(); j++)
permutations("", word.substring(i, j), permutationSet);
System.out.println();
System.out.println("Received results: " + permutationSet);
System.out.print("Enter string to permutate: ");
} catch (ThreadDeath e) {
System.out.println("We're quitting! Alright!");
}
}
private void permutations(String prefix, String word, Set<String> permutations) {
int N = word.length();
if (N == 0)
permutations.add(prefix);
else
for (int i = 0; i < N; i++)
permutations(
prefix + word.charAt(i),
word.substring(0, i) + word.substring(i + 1, N),
permutations
);
}
});
t.start();
threads.add(t);
}
} catch (IOException ioe) {
System.out.println("IO error trying to read your name!");
System.exit(1);
}
}
public static void main(String[] args) {
new BackgroundComputation() ;
}
}
clojure
(defn background-computation [_ s]
(let [res (permutations s)]
(println (format "Done Work On %s!" s))
(println res)))
(defn shutdown-app [_]
(println "We're quitting! Alright!")
(shutdown-agents))
(println "Hello user! Please input a string to permute: ")
(let [worker-agent (agent nil)]
(loop [input (str (read))]
(if (= input "EXIT")
(do (println "Quitting, I'll let my worker thread know...")
(send worker-agent shutdown-app))
(do (println (format "Passing on %s..." input))
(send worker-agent background-computation input)
(println "Please input another string to permute: ")
(recur (str (read)))))))
(let [res (permutations s)]
(println (format "Done Work On %s!" s))
(println res)))
(defn shutdown-app [_]
(println "We're quitting! Alright!")
(shutdown-agents))
(println "Hello user! Please input a string to permute: ")
(let [worker-agent (agent nil)]
(loop [input (str (read))]
(if (= input "EXIT")
(do (println "Quitting, I'll let my worker thread know...")
(send worker-agent shutdown-app))
(do (println (format "Passing on %s..." input))
(send worker-agent background-computation input)
(println "Please input another string to permute: ")
(recur (str (read)))))))
Put a internationalizate of HelloWorld program
Set locale to
In pseudocode:
Void main ()
"es" (spanish) and provide a program that changes outputs ("Helloworld") depending of locale.
In pseudocode:
Void main ()
{
Locale.set("es")
print.translate("Helloworld, Locale.get)
}
180
"http://www.ecigarettefresh.com/cartomizer-ecigarette-c-7.html ">Cartomizer E-Cigarette<
/a>strong>"http://www.ecigarettefresh.com/cartomizer-ecigarette-c-7.html ">Electronic Cigarette<
/a>strong>"http://www.ecigarettefresh.com/cartomizer-ecigarette-c-7.html ">Smokeless Cigarettes<
/a>strong>"http://www.ecigarettefresh.com/cartomizer-ecigarette-c-7.html ">discount Electronic Cigarette<
/a>strong>"http://www.ecigarettefresh.com/disposable-ecigarette-c-8.html ">Disposable E-Cigarette<
/a>strong>"http://www.ecigarettefresh.com/accessories-c-6.html ">Accessories<
/a>strong>"http://www.ecigarettefresh.com/mini-ecigarette-c-13.html ">Mini E-cigarette<
/a>strong>"http://www.ecigarettefresh.com/esmoking-c-11.html ">electric cigarette outlet<
/a>strong>"http://www.ecigarettefresh.com/smokeless-cigarettes-c-12.html ">Smokeless Cigarettes online<
/a>strong>"http://www.ecigarettefresh.com/ecigarette-c-9.html ">Electronic Cigarette online<
/a>strong>. "http://blog.allluxurywatches.com"> outlet blog <
/a>
outlet a>"http://blog.linksoflondonshopping.com"> About ecigarettefresh.com blog
180
"http://www.lovembtshoes.com/ ">mbt boots<
/a>strong>"http://www.lovembtshoes.com/ ">mbt shoes<
/a>strong>"http://www.lovembtshoes.com/ ">buy mbt boots<
/a>strong>"http://www.lovembtshoes.com/ ">discount mbt shoes<
/a>strong>"http://www.lovembtshoes.com/ ">mbt shoes online<
/a>strong>"http://www.lovembtshoes.com/mbt-tariki-c-50.html ">MBT Tariki shoes outlet<
/a>strong>"http://www.lovembtshoes.com/mbt-karibu-c-18.html ">wholesale MBT Karibu shoes<
/a>strong>"http://www.lovembtshoes.com/mbt-kafala-black-leather-women-shoes-p-68.html ">buy MBT Kafala shoes<
/a>strong>"http://www.lovembtshoes.com/mbt-meli-c-33.html ">MBT Meli<
/a>strong>"http://www.lovembtshoes.com/mbt-kifundo-c-25.html ">discount MBT Kifundo<
/a>strong>. "http://blog.bootsonlinecompany.com"> Bia blog <
/a>
Bia a>"http://blog.linkuggbootsoutlet.com"> About lovembtshoes.com blog
180
[Mall3411] - $175.01 : </title>
html; charset=utf-8" />
keywords" content="Low Cost Custom-Made bretelles sexy mariage mariée robe de mariée Robes [Mall3411] Robes de Mariée Robes de mariée 2012 Robe de mariée sexy Robes de mariée robes Quinceanera Robes de bal Robes de soirée Robes de bal Robes de soirée Robes de cocktail " />
description" content=" Low Cost Custom-Made bretelles sexy mariage mariée robe de mariée Robes [Mall3411] - Nom de l'article: " />
- TOP_MENU_HOME
- Robes de cocktail
- Robes de soirée
- Robes de mariée
- Robes de bal
- Contactez-nous
- http:
//fr.weddingdressescompany.com/»,«http:/fr.weddingdressescompany.com/' ) " > Marque page