langref.org - fantom, ocaml, and javaAccesorios : Reino Unido Moncler Outlet - Moncler Oficial UK Venta Online/title>html; charset=utf-8" />keywords" content="Accesorios Moncler Moncler Abrigos Moncler 2015-2016 Chaquetas Moncler Chalecos Moncler Outlet Reino Unido , Moncler Outlet , Moncler Reino Unido Venta Accesorios" />description" content=" />imagetoolbar" content="no" />canonical" href="http://www.monclermen.biz/es/accesorios-c-13.html" />stylesheet" type="text/css" href="http:/www.monclermen.biz/es/includes/templates/polo/css/style_imagehover.css" />"stylesheet"type="text/css"href="http://www.monclermen.biz/es/includes/templates/polo/css/stylesheet.css"/>css" href="http://www.monclermen.biz/es/includes/templates/polo/css/stylesheet_css_buttons.css" />stylesheet" type="text/css" media="print" href="http:/www.monclermen.biz/es/includes/templates/polo/css/print_stylesheet.css" />"currency"onchange="this.form.submit() replica Zwitserse horloges online

All Problems Strings Printing

Output a string to the console

Write the string "Hello World!" to STDOUT fantom echo("Hello World!") ocaml print_string "Hello world!\n";;print_endline "Hello world!";;Printf.printf "Hello world!\n";; java System.out.println("Hello World!");System.out.printf("Hello World!\n");

Retrieve a string containing ampersands from the variables in a url

My PHP script first does a query to obtain customer info for a form. The form has first name and last name fields among others. The customer has put entries such as "Ron & Jean" in the first name field in the database. Then the edit form script is called with variables such as "http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith" . The script variable for first name $_REQUEST ['firstname'] never gets beyond the "Ron" value because of the ampersand in the data. I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like "http://myserver/custinfo/edit.php?mode=view&fname=" Ronxxnbsp;xxamp;xxnbsp;Jean "&lname=SMITH" . (sorry I had to add the xx to replace the ampersand or it didn't display meaningful url contents the browser sees.) Of course this fails for the same reasons. What is a better approach? fantom encoded := `http://myserver.com/custinfo/edit.php`.plusQuery( ["fname":"Ron & Jean", "lname":"Smith"]).encode echo(encoded) ocaml let query = Netencoding.Url.mk_url_encoded_parameters [ "mode", "view"; "fname", "Ron & Jean"; "lname", "Smith"; ] let url = "http://myserver.com/custinfo/edit.php?" ^ query 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());

string-wrap

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> " Expected output: > The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t > he lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox > jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The qui > ck brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy > dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps o > ver the lazy dog. The quick brown fox jumps over the lazy dog. fantom s:=Str[,].fill("The quick brown fox jumps over the lazy dog. ",10).join while(s.size>0){ echo("> "+s[0..(77.min(s.size))-1]) s=(s.size>77)?s[77..-1].trim : "" } ocaml let wrapper margin = let cur = ref 0 in fun word -> let len = String.length word in let beginning_of_line () = Printf.printf "> %s" word; cur := len + 2 in if !cur = 0 then beginning_of_line () else begin cur := !cur + 1 + len; if !cur <= margin then Printf.printf " %s" word else begin print_newline (); beginning_of_line () end end let wrap_string wrapper s = let len = String.length s in let rec aux_out i = if i < len then match s.[i] with | ' ' | '\t' | '\n' -> aux_out (i+1) | _ -> aux_in i (i+1) and aux_in i0 i = if i >= len then wrapper (String.sub s i0 (len - i0)) else match s.[i] with | ' ' | '\t' | '\n' -> wrapper (String.sub s i0 (i - i0)); aux_out (i+1) | _ -> aux_in i0 (i+1) in aux_out 0 let () = let base_string = "The quick brown fox jumps over the lazy dog. " in let w = wrapper 78 in for i = 1 to 10 do wrap_string w base_string done; print_newline () 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 class PangramWrapper { public static void main(String[] args) { int lineLimit = 78; String newLine = "\n> "; String pangram = "The quick brown fox jumps over the lazy dog. "; String repeated = new String(new char[10]).replace("\0", pangram); StringBuffer all = new StringBuffer(newLine + repeated); for(int count = 1; count*lineLimit < all.length(); count++) { all.insert(count * lineLimit, newLine); } System.out.println(all); } } public class PangramWrapperViaRegexAndJoin { public static void main(String[] args) { String newLine = "\n> ", pangram = "The quick brown fox jumps over the lazy dog. ", repeated = new String(new char[10]).replace("\0", pangram); final String[] splitted = repeated.split("(?<=\\G.{78})"); // worse performance than substring in for-loop System.out.println("> "+ String.join(newLine, Arrays.asLis dbpxkrmi. cartier shop onlinet(splitted))); } } Declaration

Define a string containing special characters

Define the literal string "\#{'}${"}/" fantom special := Str<|\#{'}${"}/|> ocaml "\\#{'}${\"}/" java String special = "\\#{'}${\"}/";

Define a multiline string

Define the string: "This Is A Multiline String" fantom s := "This Is A Multiline String" ocaml "This\nIs\nA\nMultiline\nString""This Is A Multiline String" java String text = "This\nIs\nA\nMultiline\nString";String text = "This\n" + "Is\n" + "A\n" + "Multiline\n" + "String"

Define a string containing variables and expressions

Given variables a=3 and b=4 output "3+4=7" fantom echo("$a+$b=${a+b}") ocaml Printf.printf "%d+%d=%d" a b (a+b);;Printf.printf "%d+%d=%d" a b (a+b);; java System.out.println(a + "+" + b + "=" + (a+b));System.out.printf("%d+%d=%d\n", a, b, a + b); Manipulation

Reverse the characters in a string

Given the string "reverse me" , produce the string "em esrever" fantom "reverse me".reverse ocaml let reverse str = let len = String.length str in let res = String.create len in for i = 0 to pred len do let j = pred len - i in res.[i] <- str.[j] done; (res)let rev_char str = let l = Str.split (Str.regexp "") str in List.fold_left (fun a b -> b ^ a) "" l ;; java String reverse = new StringBuffer("reverse me").reverse().toString();String reverse = new StringBuilder("reverse me").reverse().toString(); String reverse = StringUtils.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" fantom "This is a end, my only friend!".split.reverse.join(" ") ocaml let rev_words str = let l = Str.split (Str.regexp " ") str in String.concat " " (List.rev l) ;; java List list = new ArrayList(); StringTokenizer st = new StringTokenizer(text, " "); while(st.hasMoreTokens()) { list.add(0, st.nextToken()); } StringBuffer sb = new StringBuffer(); for (Iterator iterator = list.iterator(); iterator.hasNext();) { String word = (String) iterator.next(); sb.append(word); if (iterator.hasNext()) { sb.append(" "); } } String reversed = sb.toString();List<String> ls = Arrays.asList("This is the end, my only friend!".split("\\s")); Collections.reverse(ls); StringBuilder sb = new StringBuilder(32); for (String s : ls) sb.append(" ").append(s); String reversed = sb.toString().trim();String reversed = StringUtils.reverseDelimited("This is the end, my only friend!", ' ');

Text wrapping

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> " , yielding this result: > The quick brown fox jumps over the lazy dog. The quick brown fox jumps > over the lazy dog. The quick brown fox jumps over the lazy dog. The > quick brown fox jumps over the lazy dog. The quick brown fox jumps > over the lazy dog. The quick brown fox jumps over the lazy dog. The > quick brown fox jumps over the lazy dog. The quick brown fox jumps > over the lazy dog. The quick brown fox jumps over the lazy dog. The > quick brown fox jumps over the lazy dog. fantom buf := Buf() 10.times { buf.writeChars("The quick brown fox jumps over the lazy dog. ") } buf.flip out := Env.cur.out sep := ">"; max := 72 - sep.size - 1 acc := 0; Str? s := null while ((s = buf.readStrToken) != null) { if (acc == 0) out.print(sep) acc += s.size if (acc > max) { out.print("\n$sep") acc = s.size } out.print(" $s") buf.readStrToken(4096) { !it.isSpace } acc++ } ocaml (* ocamlbuild -no-hygiene textwrap.native && ./textwrap.native *) let wrap s prefix width = let width = width - (String.length prefix) in let len = String.length s in let rec loop start = if start >= len then [] else let stop = min (len - start) width in let sub = String.sub s start stop in (prefix ^ sub) :: loop (start+stop) in loop 0 in let wrap_and_print s prefix width = List.iter print_endline (wrap s prefix width) in let s = ref "" in for i = 1 to 10 do s := !s ^ "The quick brown fox jumps over the lazy dog. " done; wrap_and_print !s "> " 78 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);

Remove leading and trailing whitespace from a string

Given the string "  hello    " return the string "hello" . fantom s := " hello ".trim ocaml let left_pos s len = let rec aux i = if i >= len then None else match s.[i] with | ' ' | '\n' | '\t' | '\r' -> aux (succ i) | _ -> Some i in aux 0 let right_pos s len = let rec aux i = if i < 0 then None else match s.[i] with | ' ' | '\n' | '\t' | '\r' -> aux (pred i) | _ -> Some i in aux (pred len) let trim s = let len = String.length s in match left_pos s len, right_pos s len with | Some i, Some j -> String.sub s i (j - i + 1) | None, None -> "" | _ -> assert false let () = let res = trim " hello " in print_endline resString.trim " hello " java String s = " hello "; String trimmed = s.trim();

Simple substitution cipher

Take a string and return the ROT13 and ROT47 (Check Wikipedia) version of the string. For example: String is: Hello World #123 ROT13 returns: Uryyb Jbeyq #123 ROT47 returns: w6==@ (@C=5 R`ab fantom rot := |Str s, |Int c -> Int| remap -> Str| { rs := "" s.each { rs += remap(it).toChar } return rs } rot13 := |Str s -> Str| { rot(s) |Int c -> Int| { lc := c.lower c += (lc >= 'a' && lc <= 'm') ? 13 : ((lc >= 'n' && lc <= 'z') ? -13 : 0) return c } } rot47 := |Str s -> Str| { rot(s) |Int c -> Int| { c += (c >= '!' && c <= 'O') ? 47 : ((c >= 'P' && c <= '~') ? -47 : 0) return c } } s := "Hello World #123" echo("s=$s") echo("rot13=${rot13(s)}") echo("rot47=${rot47(s)}") ocaml let rot_char13 c = match c with | 'A'..'M' | 'a'..'m' -> Char.chr ((Char.code c) + 13) | 'N'..'Z' | 'n'..'z' -> Char.chr ((Char.code c) - 13) | _ -> c let rot_char47 c = match c with | '!'..'N' -> Char.chr ((Char.code c) + 47) | 'O'..'~' -> Char.chr ((Char.code c) - 47) | _ -> c let rot f str = let len = String.length str in let res = String.create len in for i = 0 to pred len do res.[i] <- f str.[i] done; (res) let rot13 = rot rot_char13 let rot47 = rot rot_char47 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 ) )) ; Case

Make a string uppercase

Transform "Space Monkey" into "SPACE MONKEY" fantom s := "Space Monkey".localeUpper ocaml String.uppercase "Space Monkey";; java String upper = text.toUpperCase();

Make a string lowercase

Transform "Caps ARE overRated" into "caps are overrated" fantom s := "Caps ARE overRated".localeLower ocaml String.lowercase "Caps ARE overRated";; java "Caps ARE overRated".toLowerCase();

Capitalise the first letter of each word

Transform "man OF stEEL" into "Man Of Steel" fantom "man OF stEEL".split.map { it.localeLower.localeCapitalize }.join(" ") ocaml let capitalize_words str = let len = String.length str in let res = String.copy str in let rec aux i do_up = if i >= len then res else match str.[i] with | ' ' | '\n' | '\t' | '\r' -> aux (succ i) true | _ -> res.[i] <- (if do_up then Char.uppercase else Char.lowercase) str.[i]; aux (succ i) false in aux 0 true let () = print_endline (capitalize_words "man OF stEEL")let capitalize_words str = let capitalize_word w = String.capitalize (String.lowercase w) in let l = Str.split (Str.regexp " ") str in String.concat " " (List.map (capitalize_word) l) ;; let () = print_endline (capitalize_words "man OF stEEL");; java String input = "man OF stEEL"; StringTokenizer tokenizer = new StringTokenizer(input); StringBuffer sb = new StringBuffer(); while (tokenizer.hasMoreTokens()) { String word = tokenizer.nextToken(); sb.append(word.substring(0, 1).toUpperCase()); sb.append(word.substring(1).toLowerCase()); sb.append(' '); } String text = sb.toString();StringBuilder sb = new StringBuilder("man OF stEEL"); String s = sb.toString(); int last = s.length() - 1; for (int i = 0; i <= last; ++i) if (Character.isSpaceChar(s.charAt(i)) && i < last) { ++i; sb.setCharAt(i, Character.toUpperCase(s.charAt(i))); } else if (i == 0) sb.setCharAt(i, Character.toUpperCase(s.charAt(i))); else sb.setCharAt(i, Character.toLowerCase(s.charAt(i)));Matcher m = Pattern.compile("(\\w+)").matcher("man OF stEEL"); StringBuffer sb = new StringBuffer(32), rsb = new StringBuffer(8); while (m.find()) { rsb.replace(0, rsb.length(), m.group().toLowerCase()); rsb.setCharAt(0, Character.toUpperCase(rsb.charAt(0))); m.appendReplacement(sb, rsb.toString()); } m.appendTail(sb);String text = WordUtils.capitalizeFully("man OF stEEL"); Numbers Mathematical

Find the distance between two points

fantom px1 := 34.0f; py1 := 78.0f; px2 := 67.0f; py2 := -45.0f distance := |Float x1, Float y1, Float x2, Float y2 -> Float| { ((x2-x1).pow(2.0f) + (y2-y1).pow(2.0f)).sqrt } distance(px1, py1, px2, py2) ocaml type point = { x:float; y:float };; let distance a b = sqrt((a.x -. b.x)**2. +. (a.y -. b.y)**2.);; java double distance = Point2D.distance(x1, y1, x2, y2);Point2D point1 = new Point2D.Double(x1, y1); Point2D point2 = new Point2D.Double(x2, y2); double distance = point1.distance(point2);double distance = Math.hypot(x2-x1, y2-y1); Output

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042 fantom formatted := 42.toStr.padl(8, '0') formatted := 42.toLocale("00000000") ocaml Printf.printf "%08d" 42;;let s = Printf.sprintf "%08d" 42 in print_string s;; java String formatted = new DecimalFormat("00000000").format(42); String formatted = String.format("%08d", 42);

Right Space pad a number

Given the number 1024 right pad it to 6 characters "1024  " fantom formatted := 1024.toStr.padr(6) ocaml Printf.printf "%-6i" 1024;; java private static String spaces(int spaces) { StringBuffer sb = new StringBuffer(); for(int i=0; i<spaces; i++) { sb.append(' '); } return sb.toString(); } private static String rightPad(int number, int spaces) { String numberString = String.valueOf(number); return numberString + spaces(spaces - numberString.length()); }String text = StringUtils.rightPad(String.valueOf(1024), 6)String formatted = String.format("%-6d", 1024);

Format a decimal number

Format the number 7/8 as a decimal with 2 places: 0.88 fantom formatted := (7.0/8.0).toLocale("0.00") ocaml Printf.printf "%4.2f" (7. /. 8.);;let s = Printf.sprintf "%4.2f" (7. /. 8.) in print_string s;; java String formatted = String.format("%3.2f", 7./8.);

Left Space pad a number

Given the number 73 left pad it to 10 characters "        73" fantom formatted := 73.toStr.padl(10) ocaml Printf.printf "%10d" 73;; java private static String spaces(int spaces) { StringBuffer sb = new StringBuffer(); for(int i=0; i<spaces; i++) { sb.append(' '); } return sb.toString(); } private static String leftPad(int number, int spaces) { String numberString = String.valueOf(number); return spaces(spaces - numberString.length()) + numberString; }String formatted = String.format("%10d", 73); Random

Generate a random integer in a given range

Produce a random integer between 100 and 200 inclusive fantom r := Int.random(100..200) ocaml Random.self_init ();; let a = 100 and b = 200 in Random.int ( b - a + 1 ) + a;; java Random random = new Random(); int randomInt = random.nextInt(200-100+1)+100;

Generate a repeatable random number sequence

Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values. fantom rand := Random.makeSeeded(12345) first := Int[,].fill(0,5).map { rand.next(100..200) } rand2 := Random.makeSeeded(12345) second := Int[,].fill(0,5).map { rand2.next(100..200) } ocaml let random_stream seed = Random.init seed; let state = ref (Random.get_state ()) in Stream.from (fun x -> Random.set_state !state; let res = Random.float 1. in state := Random.get_state (); Some res);; Stream.npeek 5 (random_stream 1);; Stream.npeek 5 (random_stream 1);; 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(); } Regex Matching

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/ fantom if (Regex<|[A-Z][a-z]+|>.matches("Hello")) echo("ok") ocaml if Str.string_match (Str.regexp "[A-Z][a-z]+") "Hello" 0 then print_string "ok";; java if ("Hello".matches("[A-Z][a-z]+")) { System.out.println("ok"); }

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/ fantom m := Regex<|one (.*) three|>.matcher("one two three") if (m.matches) echo("${m.group(1)}") ocaml #load "str.cma" ;; let s = "one two three" in if Str.string_match (Str.regexp "one \\(.*\\) three") s 0 then print_string (Str.matched_group 1 s) java Pattern pattern = Pattern.compile("one (.*) three"); Matcher matcher = pattern.matcher("one two three"); if (matcher.matches()) { System.out.println(matcher.group(1)); } Searching

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/ fantom m := Regex<|\d+|>.matcher("abc 123 @#\$") if (m.find) echo("ok") ocaml #load "str.cma" ;; let re = Str.regexp "[0-9]+" in try let _ = Str.search_forward re "abc 123 @#$" 0 in print_string "ok" with _ -> () java Pattern pattern = Pattern.compile("\\d+"); Matcher matcher = pattern.matcher(text); if (matcher.find()) { System.out.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+)/ fantom m := Regex<|\((\w+)\):(\d+)|>.matcher(s) list := Str[,] while (m.find) { list.add("${m.group(1)}${m.group(2)}") } ocaml let result = let str = "(fish):1 sausage (cow):3 tree (boat):4" in let ms = Pcre.exec_all ~pat:"\\((\\w+)\\):(\\d+)" str in Array.to_list ( Array.map (fun m -> let s = Pcre.get_substrings m in Printf.sprintf "%s%s" s.(1) s.(2); ) ms ) 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)); } Replacing

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 "*" fantom replaced := Regex<|e|>.split("Red Green Blue",2).join("*") ocaml let replaced = Str.replace_first (Str.regexp "e") "*" "Red Green Blue" in print_endline replaced ;; java String replaced = "Red Green Blue".replaceFirst("e", "*");

Replace all regex matches in a string with a static string

Transform "She sells sea shells" into "She X X shells" by replacing /se\w+/ with "X" fantom replaced := Regex<|se\w+|>.split("She sells sea shells").join("X") ocaml let s = "She sells sea shells" in Str.global_replace (Str.regexp "se[^ \\t\\n]*") "X" s java String replaced = text.replaceAll("se\\w+", "X");

Replace all regex matches in a string with a dynamic string

Transform "The {Quick} Brown {Fox}" into "The kciuQ Brown xoF" by reversing words in braces using the regex /\{(\w+)\}/ . fantom s := "The {Quick} Brown {Fox}" m := Regex<|\{(\w+)\}|>.matcher(s) buf := StrBuf(s.size) last := 0 while (m.find) { buf.add(s[last..m.start-1]).add(m.group(1).reverse) last = m.end } buf.add(s[last..-1]) replaced := buf.toStr ocaml let s = "The {Quick} Brown {Fox}" in let r = Str.regexp "{\\([^ \\t\\n]*\\)}" in Str.global_substitute r (fun m -> string_rev (Str.matched_group 1 m)) s 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); Lists Declaration

Define an empty list

Assign the variable "list" to a list with no elements fantom list := [,] ocaml let list = [];; java List list = Collections.emptyList();String[] list = {};

Define a static list

Define the list [One, Two, Three, Four, Five] fantom list := ["One", "Two", "Three", "Four", "Five"] ocaml let list = [ "One"; "Two"; "Three"; "Four"; "Five" ];; java List<String> numbers = new ArrayList<String>(); Collections.addAll(numbers, "One", "Two", "Three", "Four", "Five");List numbers = new ArrayList(); numbers.add("One"); numbers.add("Two"); numbers.add("Three"); numbers.add("Four"); numbers.add("Five");List numbers = Arrays.asList(new String[]{"One", "Two", "Three", "Four", "Five"});String[] numbers = {"One", "Two", "Three", "Four", "Five"};List numbers = new ArrayList(){{put("One"); put("Two"); put("Three"); put("Four"); put("Five"); }}; Output

Join the elements of a list, separated by commas

Given the list [Apple, Banana, Carrot] produce "Apple, Banana, Carrot" fantom ["Apple", "Banana", "Carrot"].join(", ") ocaml let () = let lst = ["Apple"; "Banana"; "Carrot"] in let str = String.concat ", " lst in print_endline str java StringBuffer sb = new StringBuffer(); for (Iterator it = fruit.iterator(); it.hasNext();) { sb.append(it.next()); if (it.hasNext()) { sb.append(", "); } } String result = sb.toString();StringBuilder sb = new StringBuilder(fruit.get(0)); for (String item : fruit.subList(1, fruit.size())) sb.append(", ").append(item); String result = sb.toString();String result = StringUtils.join(fruit, ", ");

Join the elements of a list, in correct english

Create a function join that takes a List and produces a string containing an english language concatenation of the list. It should work with the following examples: join( [Apple, Banana, Carrot] ) = "Apple, Banana, and Carrot" join( [One, Two] ) = "One and Two" join( [Lonely] ) = "Lonely" join( [] ) = "" fantom join := |List list -> Str| { switch(list.size) { case 0: return "" case 1: return list[0] case 2: return list.join(" and ") default: return list[0..-2].join(", ") + ", and " + list[-1] } } echo(join(["Apple", "Banana", "Carrot"])) echo(join(["One", "Two"])) echo(join(["Lonely"])) echo(join([,])) ocaml let join list = let rec join' list acc = match list with | [] -> "" | [single] -> single | one::[two] -> if acc = "" then one ^ " and " ^ two else acc ^ one ^ ", and " ^ two | first::others -> join' others (acc ^ first ^ ", ") in join' list "" java private String join(List elements) { if (elements == null || elements.size() == 0) { return ""; } else if (elements.size() == 1) { return elements.get(0).toString(); } else if (elements.size() == 2) { return elements.get(0) + " and " + elements.get(1); } StringBuffer sb = new StringBuffer(); for (Iterator it = elements.iterator(); it.hasNext();) { String next = (String) it.next(); if (sb.length() > 0) { if (it.hasNext()) { sb.append(", "); } else { sb.append(", and "); } } sb.append(next); } return sb.toString(); }System.out.println(join(fruit));

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] ] fantom [4,5].each |Int i| { ["a","b","c"].each |Str s| { r.add([i,s]) } } ocaml let combinations = let l1 = ["a"; "b"; "c"] and l2 = [4; 5] in List.rev ( List.fold_left (fun acc y -> List.fold_left (fun acc2 x -> (x, y)::acc2 ) acc l1 ) [] l2 ) java List<String> combinations = new ArrayList<String>(); for (int number : numbers) for (String letter : letters) combinations.add(letter + ":" + Integer.toString(number));SortedSet<AbstractMap.SimpleImmutableEntry<String, Integer> > combinations = new TreeSet<AbstractMap.SimpleImmutableEntry<String, Integer> >(new CombinationComparator()); for (int number : numbers) for (String letter : letters) combinations.add(new AbstractMap.SimpleImmutableEntry<String, Integer>(letter, Integer.valueOf(number)));

From a List Produce a List of Duplicate Entries

Taking a list: ["andrew", "bob", "chris", "bob"] Write the code to produce a list of duplicates in the list: ["bob"] fantom nameCounts := Str:Int[:] { def = 0 } ["andrew", "bob", "chris", "bob"].each |Str v| { nameCounts[v]++ } results := nameCounts.findAll |Int v, Str k->Bool| { v > 1 }.keys echo(results.join(",")) ocaml let rem v lst = let rec aux acc = function | [] -> List.rev acc | x::xs -> if compare v x = 0 then aux acc xs else aux (x::acc) xs in aux [] lst (** in case of a match, returns a list with the duplicate(s) removed *) let rec mem_rem v lst = let rec aux acc = function | [] -> None | x::xs -> if compare v x = 0 then Some(List.rev_append acc (rem v xs)) else aux (x::acc) xs in aux [] lst let duplicates lst = let rec aux acc = function | [] -> List.rev acc | x::xs -> match mem_rem x xs with | Some ret -> aux (x::acc) ret | None -> aux acc xs in aux [] lst let () = let lst = ["andrew"; "bob"; "chris"; "bob"; "mike"; "peter"; "bob"] in let dup = duplicates lst in List.iter print_endline dup(* Using standard (functorized) sets *) module SetTools(ASet: Set.S) = struct let find_duplicates l = let rec aux l seen acc = match l with | [] -> acc | h :: q -> if ASet.mem h seen then aux q seen (h :: acc) else aux q (ASet.add h seen) acc in aux l (ASet.empty) [] end module StringSet = Set.Make(String) module StringSetTools = SetTools(StringSet) StringSetTools.find_duplicates ["andrew"; "bob"; "chris"; "bob"];; 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); Access

Fetch an element of a list by index

Given the list [One, Two, Three, Four, Five] , fetch the third element ( 'Three' ) fantom ["One", "Two", "Three", "Four", "Five"][2] ["One", "Two", "Three", "Four", "Five"].get(2) ocaml let third = List.nth [ "One"; "Two"; "Three"; "Four"; "Five" ] 3;; java String result = list.get(2);

Fetch the last element of a list

Given the list [Red, Green, Blue] , access the last element ( 'Blue' ) fantom ["Red", "Green", "Blue"][-1] ["One", "Two", "Three", "Four", "Five"].last ocaml let list = [ "Red"; "Green"; "Blue" ] in let last = List.nth list ( (List.length list) - 1 );;let list = [ "Red"; "Green"; "Blue" ] in let last = List.hd (List.rev list);;let list_last l = let rec aux h q = match q with | [] -> h | h :: q -> aux h q in match l with | [] -> invalid_arg "list_last" | h :: q -> aux h q ;; list_last ["Red"; "Green"; "Blue"] java String result = list.get(list.size() - 1);

Find the common items in two lists

Given two lists, find the common items. E.g. given beans = ['broad', 'mung', 'black', 'red', 'white'] and colors = ['black', 'red', 'blue', 'green'] , what are the bean varieties that are also color names? fantom beans := ["broad", "mung", "black", "red", "white"] colors := ["black", "red", "blue", "green"] echo(beans.intersection(colors)) ocaml let beans = ["broad"; "mung"; "black"; "red"; "white"] let colors = ["black"; "red"; "blue"; "green"] let f common c = if List.mem c beans then c::common else common let common = List.fold_left f [] colors;; (* common will contain a list with the common elements *)(* using standard (functorized) sets *) module SetTools(ASet: Set.S) = struct let of_list l = List.fold_left (fun acc e -> ASet.add e acc) ASet.empty l let find_common l1 l2 = ASet.elements (ASet.inter (of_list l1) (of_list l2)) end module StringSet = Set.Make(String) module StringSetTools = SetTools(StringSet) ;; let beans = ["broad"; "mung"; "black"; "red"; "white"] in let colors = ["black"; "red"; "blue"; "green"] in StringSetTools.find_common beans colors;; 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);

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. fantom uniqueAges := [18, 16, 17, 18, 16, 19, 14, 17, 19, 18].unique echo(uniqueAges) ocaml let ages = [18; 16; 17; 18; 16; 19; 14; 17; 19; 18] let f res e = if List.mem e res then res else e::res let unique = List.fold_left f [] ages;;(* using standard (functorized) sets *) module SetTools(ASet: Set.S) = struct let of_list l = List.fold_left (fun acc e -> ASet.add e acc) ASet.empty l let unique l = ASet.elements (of_list l) end module Integer = struct type t = int let compare (x:t) y = Pervasives.compare x y end module IntegerSet = Set.Make(Integer) module IntegerSetTools = SetTools(IntegerSet) ;; IntegerSetTools.unique [18; 16; 17; 18; 16; 19; 14; 17; 19; 18];; let removeDuplicate list = let rec aux acc = function | [] -> acc | h :: t -> if (List.mem h t) then aux acc t else aux (h::acc) t in List.rev (aux [] list);; 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); Modification

Remove an element from a list by index

Given the list [Apple, Banana, Carrot] , remove the first element to produce the list [Banana, Carrot] fantom list := ["Apple", "Banana", "Carrot"] list.removeAt(0) ocaml let delete_at i al = if i < 0 || i >= List.length al then invalid_arg "delete_at" else let rec del i l = match l with | [] -> [] | h::t when i = 0 -> t | h::t -> h :: del (i-1) t in del i al ;;let rem_first l = match l with | [] -> [] | h::t -> t ;;List.tl ["Apple"; "Banana"; "Carrot"] java list.remove(0);

Remove the last element of a list

fantom list := ["Apple", "Banana", "Carrot"] list.removeAt(-1) list := ["Apple", "Banana", "Carrot"]¨ list.pop ocaml let remove_last list = match (List.rev list) with | h::t -> List.rev t | [] -> []let remove_last lst = List.rev (List.tl (List.rev lst))let list_remove_last l = let rec aux h q acc = match q with | [] -> List.rev acc | h2 :: q -> aux h2 q (h :: acc) in match l with | [] -> invalid_arg "list_remove_last" | h :: q -> aux h q [] java list.remove(list.size() - 1);

Rotate a list

Given a list ["apple", "orange", "grapes", "bananas"] , rotate it by removing the first item and placing it on the end to yield ["orange", "grapes", "bananas", "apple"] fantom list := ["apple", "orange", "grapes", "bananas"] list.add(list.removeAt(0)) ocaml let rotate list = match list with | head::tail -> tail@[head] | [] -> [] java list.add(list.remove(0));Collections.rotate(list, -1); Manipulation

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. fantom r := [,] first.size.times |Int i| { r.add([first[i], last[i], years[i]]) } echo(r) ocaml let rec combine3 f l y = match f, l, y with | [], [], [] -> [] | fh :: fq, lh :: lq, yh :: yq -> (fh, lh, yh) :: combine3 fq lq yq | _ -> invalid_arg "combine3" ;; let first = ["Bruce"; "Tommy Lee"; "Bruce"] in let last = ["Willis"; "Jones"; "Lee"] in let years = [1955; 1946; 1940] in combine3 first last years 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);

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' . fantom r := [,] ["2","3","4","5","6","7","8","9","10","J","Q","K","A"].each |Str c| { ["H","D","C","S"].each |Str s| { r.add([c,s]) } } q := ["A","H"] result := r.contains(q) echo("Deck size=${r.size}, contains $q? -> $result") ocaml let suites = ["H"; "D"; "C"; "S"] let faces = ["2";"3";"4";"5";"6";"7";"8";"9";"10";"J";"Q";"K";"A"] let desk = List.fold_left (fun acc y -> List.fold_left (fun acc2 x -> (x, y)::acc2 ) acc faces ) [] suites let () = assert (List.length desk = 52); if List.mem ("A", "H") desk then print_endline "Ace of Hearts found!" else print_endline "Ace of Hearts not found :(" 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");

Perform an operation on every item of a list

Perform an operation on every item of a list, e.g. for the list ["ox", "cat", "deer", "whale"] calculate the list of sizes of the strings, e.g. [2, 3, 4, 5] fantom ["ox", "cat", "deer", "whale"].map { it.size } ocaml List.map String.length ["ox"; "cat"; "deer"; "whale"];; 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() + " "); } } }

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. fantom things := ["hello", 25, 3.14, Time.now] numbers := things.findType(Num#) nonNumbers := things.exclude { numbers.contains(it) } ocaml (* OCaml is a strongly statically typed language so it is not possible to mix items of different types in a single list. So here we use a list of strings, some of these strings represent a number *) let is_a_number v = try ignore(float_of_string v); true with _ -> false let numbers, others = List.partition is_a_number ["Joe"; "3.14"; "8"; "hello"; "23/04/2009"] (* ========================================================================== *) (* If we really want to mix items of several types, we can declare a variant: *) type item = Int of int | Float of float | String of string | Char of char let is_a_number = function | Float _ | Int _ -> true | String _ | Char _ -> false let numbers, others = List.partition is_a_number [String "Joe"; Float 3.14; Int 8; Char 'Z'] java public class NumbersSolution { public static void main(String[] args) { List<Object> items = Arrays.asList(new Object[] { new Date(), 12L, 15.4, 99, "x" } ) ; List<Object> numbers = new ArrayList<Object>() ; List<Object> nonNumbers = new ArrayList<Object>() ; for (Object item : items ) (item instanceof Number ? numbers : nonNumbers).add(item) ; } } public class NumbersSolution { public static void main() { List<Object> numbers = new ArrayList<Object>() ; List<Object> nonNumbers = new ArrayList<Object>() ; for (Object item : new Object[] { new Date(), 12L, 15.4, 99, "x" } ) (item instanceof Number ? numbers : nonNumbers).add(item) ; } } Testing

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. fantom echo([2,3,4].all{ it>1 }) ocaml (* from the interactive loop *) # List.for_all (fun x -> x > 1) [2; 3; 4] ;; - : bool = true java List<String> la = Arrays.asList("a", "b", "", "c");// listWithEmptyValues List<String> lb = Arrays.asList("a", null, "", "c");// listWithNullValues List<String> lc = Arrays.asList("a", "b", "d", "c");// listWithNonEmptyValues Predicate<String> correctValue = (String s) -> s != null && !s.isEmpty(); System.out.println(la.stream().allMatch(correctValue)); // false System.out.println(lb.stream().allMatch(correctValue)); // false System.out.println(lc.stream().allMatch(correctValue)); // true int[] array = {1, 2, 3}; Arrays.stream(array).anyMatch((x) -> x > 1);

Test if a condition holds for any items of a list

Given a list, test if a certain logical condition (i.e. predicate) holds for any items of the list. fantom echo([2,3,4].any{ it==4 }) ocaml (* from the interactive loop: *) # List.exists (fun x -> x > 3) [2; 3; 4] ;; - : bool = true Maps Declaration

Define an empty map

fantom map := [:] ocaml module StringMap = Map.Make (String) let m = StringMap.emptylet m = Hashtbl.create 42 java Map map = new HashMap();

Define an unmodifiable empty map

fantom map := [:].ro ocaml (* OCaml maps are functional data structures (so are immutable) *) module StringMap = Map.Make (String) let m = StringMap.empty java Map empty = Collections.EMPTY_MAP;SortedMap empty = MapUtils.EMPTY_SORTED_MAP;

Define an initial map

Define the map {circle:1, triangle:3, square:4} fantom map := ["circle":1, "triangle":2, "square":4] ocaml module StringMap = Map.Make (String) let m0 = StringMap.empty let m1 = StringMap.add "circle" 1 m0 let m2 = StringMap.add "triangle" 3 m1 let m3 = StringMap.add "square" 4 m2let m = Hashtbl.create 42;; Hashtbl.replace m "circle" 1;; Hashtbl.replace m "triangle" 3;; Hashtbl.replace m "square" 4;; java Map shapes = new HashMap(); shapes.put("circle", 1); shapes.put("triangle", 3); shapes.put("square", 4);Map shapes = new HashMap() {{ put("circle",1); put("triangle",3); put("square",4); }} Access

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" fantom map := ["joe":"cat", "mary":"turtle", "bill":"canary"] if (map.containsKey("mary")) echo("ok") ocaml module StringMap = Map.Make (String) let map = List.fold_left (fun map (key, value) -> StringMap.add key value map ) StringMap.empty [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")] let () = if StringMap.mem "mary" map then print_endline "OK"let () = let map = Hashtbl.create 42 in List.iter (fun (key, value) -> Hashtbl.add map key value ) [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")]; if Hashtbl.mem map "mary" then print_endline "OK" java if (pets.containsKey("mary")) System.out.println("ok");

Retrieve a value from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print the pet for "joe" ( "cat" ) fantom map := ["joe":"cat", "mary":"turtle", "bill":"canary"] pet := map["joe"] echo("pet=$pet") ocaml module StringMap = Map.Make (String) let map = List.fold_left (fun map (key, value) -> StringMap.add key value map ) StringMap.empty [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")] let () = try let pet = StringMap.find "joe" map in Printf.printf "Joe's pet is a %s.\n" pet with Not_found -> prerr_endline "No pet found for Joe."let () = let map = Hashtbl.create 42 in List.iter (fun (key, value) -> Hashtbl.add map key value ) [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")]; try let pet = Hashtbl.find map "joe" in Printf.printf "Joe's pet is a %s.\n" pet with Not_found -> prerr_endline "No pet found for Joe." java String pet = pets.get("joe");

Add an entry to a map

Given an empty pets map, add the mapping from "rob" to "dog" fantom map["rob"] = "dog" ocaml module StringMap = Map.Make (String) let pets = StringMap.add "rob" "dog" StringMap.emptylet () = let map = Hashtbl.create 42 in Hashtbl.replace map "rob" "dog" java pets.put("rob", "dog");

Remove an entry from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} remove the mapping for "bill" and print "canary" fantom pet := map.remove("bill") echo ("pet=$pet") ocaml module StringMap = Map.Make (String) let pets = List.fold_left (fun map (key, value) -> StringMap.add key value map ) StringMap.empty [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")] let get_and_rem key m = try let value = StringMap.find key m in let rm = StringMap.remove key m in Some (value, rm) with Not_found -> None let () = let key = "bill" in match get_and_rem key pets with | Some (found, new_pets) -> Printf.printf "%s : %s removed\n" key found | None -> Printf.printf "Key %s not found" keylet get_and_rem m key = try let value = Hashtbl.find m key in Hashtbl.remove m key; Some value with Not_found -> None let () = let pets = Hashtbl.create 42 in List.iter (fun (key, value) -> Hashtbl.add pets key value ) [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")]; let key = "bill" in match get_and_rem pets key with | Some found -> Printf.printf "%s : %s removed\n" key found | None -> Printf.printf "Key %s not found" key java System.out.println(pets.remove("bill")) Algorithms

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 fantom list := ["a","b","a","c","b","b"] map := [Str:Int][:] list.each |Str s, Int i| { if(!map.containsKey(s)) map.add(s,1); else map[s] = ++map[s] } echo (map) ocaml module StringMap = Map.Make (String) let histogram lst = List.fold_left (fun m v -> let n = if StringMap.mem v m then succ (StringMap.find v m) else 1 in StringMap.add v n m ) StringMap.empty lst let () = let h = histogram ["a"; "b"; "a"; "c"; "b"; "b"] in StringMap.iter (fun key value -> Printf.printf " %s: %d\n" key value ) h java Map map = new HashMap(); for (Iterator it = list.iterator(); it.hasNext();) { String s = (String) it.next(); if (!map.containsKey(s)) { map.put(s, new Integer(1)); } else { map.put(s, new Integer(((Integer)map.get(s)).intValue() + 1)); } }LinkedMap histogram = new LinkedMap(); for (Object letter : list) histogram.put(letter, !histogram.containsKey(letter) ? 1 : MapUtils.getIntValue(histogram, letter) + 1);

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 fantom list := ["one", "two", "three", "four", "five"] map := [Int:List][:] list.each { List l := map[it.size] ?: [,]; map[it.size] = l.add(it) } echo(map) ocaml let map = List.fold_left (fun map v -> let len = String.length v in let before = try IntMap.find len map with Not_found -> [] in IntMap.add len (v :: before) map ) IntMap.empty ["one"; "two"; "three"; "four"; "five"] java SortedMap<Integer, List<String> > map = new TreeMap<Integer, List<String> >(); int key; List<String> vlist; for (String item : list) { key = item.length(); vlist = map.containsKey(key) ? map.get(key) : new ArrayList<String>(); vlist.add(item); map.put(key, vlist); } MultiValueMap map = new MultiValueMap(); for (Object item : list) map.put(((String) item).length(), item); Structure Conditionals

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. fantom if (name=="Bob") echo("Hello, Bob!") ocaml if name = "Bob" then print_string "Hello, Bob!" java if (name.equals("Bob")) { System.out.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" fantom if (age > 42) echo("You are old") else echo("You are young") echo((age > 42) ? "You are old" : "You are young") ocaml if age > 42 then print_string "You are old" else print_string "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 " + ((age>42)?"old":"young"));

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

fantom if (age > 84) echo("You are really ancient") else if (age > 30) echo("You are middle-aged") else echo("You are young") ocaml if age > 84 then print_endline "You are really ancient" else if age > 30 then print_endline "You are middle-aged" else print_endline "You are young" 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");

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 fantom suffix := |Int n -> Str| { if ((4..20).contains(n % 100)) return "th" switch((n.toStr)[-1]) { case '1': return "st" case '2': return "nd" case '3': return "rd" default: return "th" } } (1..40).each { echo("$it${suffix(it)}") } ocaml let numsuffix i = match i with | 11 | 12 | 13 -> "th" | x when x mod 10 = 1 -> "st" | x when x mod 10 = 2 -> "nd" | x when x mod 10 = 3 -> "rd" | _ -> "th" ;; (* alternate implementation without using guards: let numsuffix i = match i with | 11 | 12 | 13 -> "th" | x -> match x mod 10 with | 1 -> "st" | 2 -> "nd" | 3 -> "rd" | _ -> "th" *) for i = 1 to 40 do Printf.printf "%d%s " i (numsuffix i); done; print_newline () 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"; } } Loops

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


replica Zwitserse horloges online

katsella iso bang
replica di orologi di lusso
omega orologi prezzi
nep omega
grandes montres pour hommes

Replica Chopard Watches

Opgericht in 1860 door de familie Chopard, het merk Chopard is een van de laatste grote familiebedrijf Zwitserse sieraden en horloge maken van huizen, met de familie Scheufele handhaven van een zeer handen op rol sinds 1963. De iconische Gelukkig Diamond en Happy Sport assortiment wordt aangevuld door de unieke Mille Miglia collectie, die is verder gevorderd met de lancering van de Gran Turismo XL. Bekend om zijn creativiteit, technologie en excellentie, Chopard horloge wordt een van de grootste namen in de high-class horloge en sieraden industrie. Onze gradereplica Chopard horloges zijn hetzelfde als de originele horloges met de beste prijs, hoge kwaliteit en uitstekende afwerking. Het is goed in materiaal, trendy design en uitstekende in vakmanschap. Koop Chopard replica horloges die alle functies en kwaliteiten kenmerk van het origineel bezitten. Wij kunnen u verzekeren dat deze designer Chopard replica horloges niet kan geven u niet alleen het uiterlijk van de echte, maar ook het gevoel van de echte voor! replica Chopard horloges zal je populair en goed uitziende persoon te maken!


Copy Watches Chopard 1960c001 [7969]

Copy Watches Chopard 1960c001 [7969]


€915.30  €191.70
Korting: 79%


Koop nu

Copy Watches Chopard 1960c002 [6d82]

Copy Watches Chopard 1960c002 [6d82]


€900.00  €192.60
Korting: 79%


Koop nu

Copy Watches Chopard 1960c003 [b79e]

Copy Watches Chopard 1960c003 [b79e]


€914.40  €181.80
Korting: 80%


Koop nu


Copy Watches Chopard Grand Prix de Monaco Historique Chronograph 168992 - 3012A [d4f0]

Copy Watches Chopard Grand Prix de Monaco Historique Chronograph 168992 - 3012A [d4f0]


€951.30  €190.80
Korting: 80%


Koop nu

Copy Watches Chopard Grand Prix de Monaco Historique Chronograph 168992-3012 [0beb]

Copy Watches Chopard Grand Prix de Monaco Historique Chronograph 168992-3012 [0beb]


€953.10  €192.60
Korting: 80%


Koop nu

Copy Watches Chopard High Frequency LUC 8HF Horloge [0614]

Copy Watches Chopard High Frequency LUC 8HF Horloge [0614]


€326.70  €216.00
Korting: 34%


Koop nu


Copy Watches Chopard High Frequency LUC 8HF Horloge [6e14]

Copy Watches Chopard High Frequency LUC 8HF Horloge [6e14]


€1,121.40  €220.50
Korting: 80%


Koop nu

Copy Watches Chopard High Frequency LUC 8HF Horloge [9bc3]

Copy Watches Chopard High Frequency LUC 8HF Horloge [9bc3]


€1,128.60  €220.50
Korting: 80%


Koop nu

Copy Watches Chopard High Frequency LUC 8HF Horloge [ca46]

Copy Watches Chopard High Frequency LUC 8HF Horloge [ca46]


€327.60  €222.30
Korting: 32%


Koop nu


Copy Watches Chopard Jacky Ickx EDITION 4 16/8998 [4049]

Copy Watches Chopard Jacky Ickx EDITION 4 16/8998 [4049]


€927.90  €182.70
Korting: 80%


Koop nu

Copy Watches Chopard LUC Classic Mark III 168500-3002 [ad7e]

Copy Watches Chopard LUC Classic Mark III 168500-3002 [ad7e]


€943.20  €187.20
Korting: 80%


Koop nu

Copy Watches Chopard Mille Miglia GMT 16/8992 [36e7]

Copy Watches Chopard Mille Miglia GMT 16/8992 [36e7]


€908.10  €185.40
Korting: 80%


Koop nu


Copy Watches Chopard Mille Miglia GMT 16/8992/3 [a9ef]

Copy Watches Chopard Mille Miglia GMT 16/8992/3 [a9ef]


€922.50  €189.00
Korting: 80%


Koop nu

Copy Watches Chopard Mille Miglia GMT Alfa Romeo 16/8954 [869f]

Copy Watches Chopard Mille Miglia GMT Alfa Romeo 16/8954 [869f]


€940.50  €189.00
Korting: 80%


Koop nu

Copy Watches Chopard Mille Miglia Gran Turismo XL Chronograph 168459-3015 [bce1]

Copy Watches Chopard Mille Miglia Gran Turismo XL Chronograph 168459-3015 [bce1]


€910.80  €186.30
Korting: 80%


Koop nu


Copy Watches Chopard Mille Miglia Gran Turismo XL Chronograph 2007 168459-300 [2b55]

Copy Watches Chopard Mille Miglia Gran Turismo XL Chronograph 2007 168459-300 [2b55]


€899.10  €181.80
Korting: 80%


Koop nu

Copy Watches Chopard Mille Miglia Gran Turismo XL Chronograph 2008 Limited 16 [8840]

Copy Watches Chopard Mille Miglia Gran Turismo XL Chronograph 2008 Limited 16 [8840]


€900.00  €185.40
Korting: 79%


Koop nu

Copy Watches Chopard Mille Miglia Gran Turismo XL Cronometer 16 / 8997-3005 [04e6]

Copy Watches Chopard Mille Miglia Gran Turismo XL Cronometer 16 / 8997-3005 [04e6]


€921.60  €192.60
Korting: 79%


Koop nu


Copy Watches Chopard Mille Miglia Gran Turismo XL Cronometer 16 / 8997-3005A [a65e]

Copy Watches Chopard Mille Miglia Gran Turismo XL Cronometer 16 / 8997-3005A [a65e]


€894.60  €185.40
Korting: 79%


Koop nu

Copy Watches Chopard Mille Miglia GT XL Chrono Rosso Corsa C004 [4e8f]

Copy Watches Chopard Mille Miglia GT XL Chrono Rosso Corsa C004 [4e8f]


€1,092.60  €210.60
Korting: 81%


Koop nu

Copy Watches Chopard Mille Miglia GT XL Chronograph 2008 Speed ​​Black 3 168.459 [bd11]

Copy Watches Chopard Mille Miglia GT XL Chronograph 2008 Speed ​​Black 3 168.459 [bd11]


€906.30  €185.40
Korting: 80%


Koop nu


Copy Watches Chopard Mille Miglia GTXL Power Control 16 / 8457A [cb14]

Copy Watches Chopard Mille Miglia GTXL Power Control 16 / 8457A [cb14]


€914.40  €184.50
Korting: 80%


Koop nu

Copy Watches Chopard Mille Miglia GTXL Power Control 16 / 8457B [b3e7]

Copy Watches Chopard Mille Miglia GTXL Power Control 16 / 8457B [b3e7]


€903.60  €190.80
Korting: 79%


Koop nu

Copy Watches Chopard Mille Miglia GTXL Power Control 16/8457 [fc82]

Copy Watches Chopard Mille Miglia GTXL Power Control 16/8457 [fc82]


€935.10  €191.70
Korting: 79%


Koop nu



\\ n

Skip to content

Replica Merk Horloges, Rolex Submariner Replica Vs Original, Omega Constellation Dames

replica horloges te koop replica luxe mannen horloges replica. Het Grote Horloge Topic Aanraders ForumChina? 28 jan 2017 . Namaak […]

Posted in RolexLeave a Comment on Replica Merk Horloges, Rolex Submariner Replica Vs Original, Omega Constellation Dames

Nep Rolex Horloges, Panerai Marina, Namaak Horloge Kopen

8 dec 2016 . Deze top 3 Rolex Submariner replica horloges zal een artikel dat eruit spreekt veel jullie en […]

Posted in RolexLeave a Comment on Nep Rolex Horloges, Panerai Marina, Namaak Horloge Kopen

Audemars Piguet Diver Carbon Price, Omega Replica Horloges, Zwitserse Horlogemerken

audemars piguet Royal Oak Offshore diver Forged carbon Pinterest? Omega James Bond . 5 dagen geleden dit is de grootste […]

Posted in RolexLeave a Comment on Audemars Piguet Diver Carbon Price, Omega Replica Horloges, Zwitserse Horlogemerken

Goedkope Horloges Mannen, Replica Horloge Tag Heuer, Omega Seamaster Planet Ocean Chrono

Veel dress-shop winkelcentra bieden een verscheidenheid aan producten, waaronder jurken, Bestel je goedkope goedkope horloges Heren voordelig online. Groot assortiment […]

Posted in RolexLeave a Comment on Goedkope Horloges Mannen, Replica Horloge Tag Heuer, Omega Seamaster Planet Ocean Chrono

Audemars Piguet Replica Kopen, Merken Horloges Mannen, Horloge Citizen

audemars piguet replica prezzo, AAA kwaliteit replica Zwitserse horloges koop Frankrijk, goedkope replica rolex, replica horloges patrijspoort., replica Rolex Horloges […]

Posted in RolexLeave a Comment on Audemars Piguet Replica Kopen, Merken Horloges Mannen, Horloge Citizen

Audemars Piguet Automatic, Tweedehands Horloges Heren, Fossil

hoewel deze keer het begon bij 20 weken! Browse and bid on the auction of audemars piguet, automatic TOURBILLON, REF. […]

Posted in RolexLeave a Comment on Audemars Piguet Automatic, Tweedehands Horloges Heren, Fossil

Horloge Kopen, Zwitserse Horloges Kopen, Nep Horloge Laten Repareren

Koop en verkoop wereldwijd nieuwe en tweedehands horloges op Chrono24. Meer dan 315.207 merkhorloges als Rolex, Breitling, Omega enz. tegen […]

Posted in RolexLeave a Comment on Horloge Kopen, Zwitserse Horloges Kopen, Nep Horloge Laten Repareren

Horloge Onderdelen Kopen, Groothandel Sieraden Duitsland, Omega De Ville Tresor Precio

horloge; Als het gaat om samen met alle leugens merkbaar voor Frankenwatches? horloge onderdelen kopen omega de ville tresor precio,hublot […]

Posted in RolexLeave a Comment on Horloge Onderdelen Kopen, Groothandel Sieraden Duitsland, Omega De Ville Tresor Precio

Horloges Online Heren, Horloge Reparatie, Rolex Submariner Replica Swiss Grade 1

herenhorloges online | Tijd voor een nieuw horloge? | Bekijk onze collectie! | Van sporthorloges tot klassieke exemplaren | Zalando? […]

Posted in RolexLeave a Comment on Horloges Online Heren, Horloge Reparatie, Rolex Submariner Replica Swiss Grade 1

Rolex Nep Kopen, Horlogebandjes, Audemars Piguet Tourbillon Prix

Replica Horloges kopen, nep Horloges Nederland rolex, Omega, Breitling : rolex Horloge – Patek Philippe Horloge Omega Horlogees Tag Heuer […]

Posted in RolexLeave a Comment on Rolex Nep Kopen, Horlogebandjes, Audemars Piguet Tourbillon Prix




> Forever Freely - Puffer Jacket ERJJK03158
  • Forever Freely - Puffer Jacket ERJJK03158 Forever Freely - Puffer Jacket ERJJK03158
  • Forever Freely - Puffer Jacket ERJJK03158 Forever Freely - Puffer Jacket ERJJK03158
  • Forever Freely ‑ Doudoune 89,99 € Sauvegarder Aperçu Forever Freely - Puffer Jacket ERJJK03158 Forever Freely - Puffer Jacket ERJJK03158 5 Couleurs Plus de couleurs Forever Freely ‑ Doudoune 89,99 € Sauvegarder Aperçu Highlight - Insulator Jacket ERJJK03183 Highlight - Insulator Jacket ERJJK03183 2 Couleurs Plus de couleurs Highlight ‑ Veste d'Isolation thermique 169,99 € Sauvegarder Aperçu Highlight - Insulator Jacket ERJJK03183 Highlight - Insulator Jacket ERJJK03183 2 Couleurs Plus de couleurs Highlight ‑ Veste d'Isolation thermique 169,99 € Sauvegarder Aperçu Nancy - Waterproof Hooded Insulator Jacket ERJJK03187 Nancy - Waterproof Hooded Insulator Jacket ERJJK03187 3 Couleurs

    Plus de couleurs Nancy ‑ Manteau isolant imperméable à capuche 199,99 € Sauvegarder Aperçu Nancy - Waterproof Hooded Insulator Jacket ERJJK03187 Nancy - Waterproof Hooded Insulator Jacket ERJJK03187 3 Couleurs

    Plus de couleurs Nancy ‑ Manteau isolant imperméable à capuche 199,99 € Sauvegarder Aperçu Nancy - Waterproof Hooded Insulator Jacket ERJJK03187 Nancy - Waterproof Hooded Insulator Jacket ERJJK03187 3 Couleurs


    moncler manteau des femmes

    moncler manteau des femmes
    salida de Moncler milano
    salida de Moncler milano
    moncler män
    occhiali da sole moncler







    assique%20copie%20orologi,%20repliche%20orologi,%20orologi%20replica%20hlhytxki%3C/bjibueqw">osta longines kellot

  • LxlME html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> moncler manteau des femmes Veste Femme - Doudoune & Manteau Hiver - Blouson | Roxy

    Veste Femme - Doudoune & Manteau Hiver - Blouson | Roxy moncler manteau des femmes

    Page d'accueil / Vêtements / Vestes & Manteaux

    LIVRAISON OFFERTE À PARTIR DE 25€ - RETOURS GRATUITS EN MAGASIN*

    Vêtements

    • Nouveautés
    • Vestes & Manteaux
    • Robes
    • Pulls & Gilets
    • Sweatshirts
    • Chemises
    • T-shirts
    • Tops & Débardeurs
    • Jeans
    • Pantalons
    • Combis Short & Pantalon
    • Jupes
    • Shorts
    • Vestes de snow
    • Pantalons de snow
    • Voir Tout
    Filtrer par

    Toutes les couleurs

    vestes moncler pour les hommesl>
  • langref.org - fantom, ocaml, and javaAccesorios : Reino Unido Moncler Outlet - Moncler Oficial UK Venta Online/title>html; charset=utf-8" />keywords" content="Accesorios Moncler Moncler Abrigos Moncler 2015-2016 Chaquetas Moncler Chalecos Moncler Outlet Reino Unido , Moncler Outlet , Moncler Reino Unido Venta Accesorios" />description" content=" />imagetoolbar" content="no" />canonical" href="http://www.monclermen.biz/es/accesorios-c-13.html" />stylesheet" type="text/css" href="http:/www.monclermen.biz/es/includes/templates/polo/css/style_imagehover.css" />"stylesheet"type="text/css"href="http://www.monclermen.biz/es/includes/templates/polo/css/stylesheet.css"/>css" href="http://www.monclermen.biz/es/includes/templates/polo/css/stylesheet_css_buttons.css" />stylesheet" type="text/css" media="print" href="http:/www.monclermen.biz/es/includes/templates/polo/css/print_stylesheet.css" />"currency"onchange="this.form.submit() replica Zwitserse horloges online

    All Problems Strings Printing

    Output a string to the console

    Write the string "Hello World!" to STDOUT fantom echo("Hello World!") ocaml print_string "Hello world!\n";;print_endline "Hello world!";;Printf.printf "Hello world!\n";; java System.out.println("Hello World!");System.out.printf("Hello World!\n");

    Retrieve a string containing ampersands from the variables in a url

    My PHP script first does a query to obtain customer info for a form. The form has first name and last name fields among others. The customer has put entries such as "Ron & Jean" in the first name field in the database. Then the edit form script is called with variables such as "http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith" . The script variable for first name $_REQUEST ['firstname'] never gets beyond the "Ron" value because of the ampersand in the data. I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like "http://myserver/custinfo/edit.php?mode=view&fname=" Ronxxnbsp;xxamp;xxnbsp;Jean "&lname=SMITH" . (sorry I had to add the xx to replace the ampersand or it didn't display meaningful url contents the browser sees.) Of course this fails for the same reasons. What is a better approach? fantom encoded := `http://myserver.com/custinfo/edit.php`.plusQuery( ["fname":"Ron & Jean", "lname":"Smith"]).encode echo(encoded) ocaml let query = Netencoding.Url.mk_url_encoded_parameters [ "mode", "view"; "fname", "Ron & Jean"; "lname", "Smith"; ] let url = "http://myserver.com/custinfo/edit.php?" ^ query 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());

    string-wrap

    Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> " Expected output: > The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t > he lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox > jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The qui > ck brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy > dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps o > ver the lazy dog. The quick brown fox jumps over the lazy dog. fantom s:=Str[,].fill("The quick brown fox jumps over the lazy dog. ",10).join while(s.size>0){ echo(&q