View Category
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)
'()
fsharp
let list = []
let list = List.empty
let list = new Generic.List<string>()
let list = new Generic.LinkedList<string>()
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])
fsharp
let list = ["One"; "Two"; "Three"; "Four"; "Five"]
let list = (new Generic.LinkedList<string>([|"One"; "Two"; "Three"; "Four"; "Five"|]))
let list = (new Generic.LinkedList<string>())
list.AddFirst("One") ; list.AddLast("Five") ; list.AddBefore(list.Find("Five"), "Four")
list.AddAfter(list.Find("One"), "Two") ; list.AddAfter(list.Find("Two"), "Three")
list.AddFirst("One") ; list.AddLast("Five") ; list.AddBefore(list.Find("Five"), "Four")
list.AddAfter(list.Find("One"), "Two") ; list.AddAfter(list.Find("Two"), "Three")
let list = (new Generic.List<string>())
[|"One"; "Two"; "Three"; "Four"; "Five"|] |> Array.iter (fun x -> list.Add(x))
[|"One"; "Two"; "Three"; "Four"; "Five"|] |> Array.iter (fun x -> list.Add(x))
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")))
fsharp
let result = String.Join(", ", [|"Apple"; "Banana"; "Carrot"|])
let result = (List.fold_left (fun acc item -> acc ^ (", " ^ item)) (List.hd fruit) (List.tl fruit))
let result = (List.fold_left (fun (acc : StringBuilder) (item : string) -> acc.Append(", ").Append(item)) (new StringBuilder(List.hd fruit)) (List.tl fruit)).ToString()
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)))))
fsharp
let join list =
let rec join' list' s =
match list' with
| [] -> s
| [w] -> join' [] (s ^ " and " ^ w)
| w :: ws -> join' ws (s ^ ", " ^ w)
match list with
| [] -> ""
| w :: ws -> join' ws w
// ------
printfn "%s" (join fruit)
let rec join' list' s =
match list' with
| [] -> s
| [w] -> join' [] (s ^ " and " ^ w)
| w :: ws -> join' ws (s ^ ", " ^ w)
match list with
| [] -> ""
| w :: ws -> join' ws w
// ------
printfn "%s" (join fruit)
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])
fsharp
let combinations = (List.fold_left (fun acc number -> acc @ (List.map (fun letter -> (letter, number)) letters)) [] numbers)
let combinations aa bb =
aa
|> List.map (fun a -> bb |> List.map (fun b -> (a, b)))
|> List.concat
aa
|> List.map (fun a -> bb |> List.map (fun b -> (a, b)))
|> List.concat
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))
fsharp
["andrew"; "bob"; "chris"; "bob"]
|> Seq.countBy id
|> Seq.filter (fun (k,n) -> n > 1)
|> Seq.map fst
|> Seq.toList
|> Seq.countBy id
|> Seq.filter (fun (k,n) -> n > 1)
|> Seq.map fst
|> Seq.toList
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)
fsharp
let result = List.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])
fsharp
let last list =
let rec last' list' =
match list' with
| [x] -> x
| x :: xs -> last' xs
if List.is_empty list then failwith "empty list" else last' list
// ------
let result = last list
let rec last' list' =
match list' with
| [x] -> x
| x :: xs -> last' xs
if List.is_empty list then failwith "empty list" else last' list
// ------
let result = last list
let result = (List.nth list ((List.length list) - 1))
let result = (List.hd (List.rev list))
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)))
fsharp
let beans = (Set.of_list ["broad"; "mung"; "black"; "red"; "white"])
let colors = (Set.of_list ["black"; "red"; "blue"; "green"])
let common = (Set.intersect beans colors)
let colors = (Set.of_list ["black"; "red"; "blue"; "green"])
let common = (Set.intersect beans colors)
let beans = Set ["broad"; "mung"; "black"; "red"; "white"]
let colors = Set ["black"; "red"; "blue"; "green"]
let common = Set.intersect beans colors
let colors = Set ["black"; "red"; "blue"; "green"]
let common = Set.intersect beans colors
// Iterates elements of
// list1 across Elements of list2 returning a list of string options
// as generated by List.tryFind
let findCommon(list1 : 'a list, list2 : 'a list) : 'a list =
list1 |> List.map(fun y -> list2 |> List.tryFind(fun x -> y = x))
// Iterates elements of string option list generated above
// returning a string list containing common elements of List1 and List2
|> List.fold(fun acc x -> if x <> None then x.Value::acc else acc) []
// reverse order of list (can't seem to make List.foldBack work for this
|> List.rev
let beans = ["broad"; "mung"; "black"; "red"; "white"]
let colors = ["black"; "red"; "blue"; "green"]
printfn "%A" (findCommon(beans, colors)) ;;
// list1 across Elements of list2 returning a list of string options
// as generated by List.tryFind
let findCommon(list1 : 'a list, list2 : 'a list) : 'a list =
list1 |> List.map(fun y -> list2 |> List.tryFind(fun x -> y = x))
// Iterates elements of string option list generated above
// returning a string list containing common elements of List1 and List2
|> List.fold(fun acc x -> if x <> None then x.Value::acc else acc) []
// reverse order of list (can't seem to make List.foldBack work for this
|> List.rev
let beans = ["broad"; "mung"; "black"; "red"; "white"]
let colors = ["black"; "red"; "blue"; "green"]
printfn "%A" (findCommon(beans, colors)) ;;
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)
fsharp
(Set.ofList [18; 16; 17; 18; 16; 19; 14; 17; 19; 18]) |> Set.iter (fun age -> printf "%d, " age)
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)))
fsharp
let split_at list n =
let rec split_at' list' n' left right =
match list' with
| [] -> (List.rev left, List.rev right)
| x :: xs -> if n' <= n then split_at' xs (n' + 1) (x :: left) right else split_at' xs (n' + 1) left (x :: right)
split_at' list 0 [] []
// ------
let (_, right) = split_at fruit 0
let rec split_at' list' n' left right =
match list' with
| [] -> (List.rev left, List.rev right)
| x :: xs -> if n' <= n then split_at' xs (n' + 1) (x :: left) right else split_at' xs (n' + 1) left (x :: right)
split_at' list 0 [] []
// ------
let (_, right) = split_at fruit 0
let drop list n =
if n <= 0 then
list
else
let (_, right) = split_at list (n - 1)
right
// ------
let result = (drop fruit 1)
if n <= 0 then
list
else
let (_, right) = split_at list (n - 1)
right
// ------
let result = (drop fruit 1)
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"])
fsharp
let take list n =
if n <= 0 then
list
else
let (left, _) = split_at list (n - 1)
left
// ------
let result = (take fruit ((List.length fruit) - 1))
if n <= 0 then
list
else
let (left, _) = split_at list (n - 1)
left
// ------
let result = (take fruit ((List.length fruit) - 1))
let but_last list =
let rec but_last' list' acc =
match list' with
| [x] -> List.rev acc
| x :: xs -> but_last' xs (x :: acc)
if List.is_empty list then [] else but_last' list []
// ------
let result = (but_last fruit)
let rec but_last' list' acc =
match list' with
| [x] -> List.rev acc
| x :: xs -> but_last' xs (x :: acc)
if List.is_empty list then [] else but_last' list []
// ------
let result = (but_last fruit)
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)])
fsharp
let rotate list n =
if n <= 0 then
list
else
let (left, right) = split_at list (n - 1)
right @ left
// ------
let result = (rotate fruit 1)
if n <= 0 then
list
else
let (left, right) = split_at list (n - 1)
right @ left
// ------
let result = (rotate fruit 1)
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))
fsharp
let result = (List.zip3 first last 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
fsharp
let cards = (List.fold_left (fun acc suite -> acc @ (List.map (fun face -> (suite, face)) faces)) [] suites)
printfn "Deck has %d cards" (List.length cards)
printfn "%s" (if (List.exists (fun e -> e = ("h", "A")) cards) then "Deck contains 'Ace of Hearts'" ; else "'Ace of Hearts' not in deck")
printfn "Deck has %d cards" (List.length cards)
printfn "%s" (if (List.exists (fun e -> e = ("h", "A")) cards) then "Deck contains 'Ace of Hearts'" ; else "'Ace of Hearts' not in deck")
let product (set1 : List<'a>) (set2 : List<'a>) : List<'a * 'a> =
let p = new ResizeArray<'a * 'a>()
for e1 in set1 do for e2 in set2 do p.Add(e1, e2) done done
Array.to_list (p.ToArray())
// ------
let cards = product suites faces
printfn "Deck has %d cards" (List.length cards)
printfn "%s" (if (List.exists (fun e -> e = ("h", "A")) cards) then "Deck contains 'Ace of Hearts'" ; else "'Ace of Hearts' not in deck")
let p = new ResizeArray<'a * 'a>()
for e1 in set1 do for e2 in set2 do p.Add(e1, e2) done done
Array.to_list (p.ToArray())
// ------
let cards = product suites faces
printfn "Deck has %d cards" (List.length cards)
printfn "%s" (if (List.exists (fun e -> e = ("h", "A")) cards) then "Deck contains 'Ace of Hearts'" ; else "'Ace of Hearts' not in deck")
let deck =
suites
|> List.map (fun s -> faces |> List.map (fun f -> (s, f)))
|> List.concat
printfn "Deck has %d cards" (List.length deck)
match deck |> List.exists (fun e -> e = ("h", "A")) with
| true -> printfn "Deck contains 'Ace of Hearts'"
| _ -> printfn "'Ace of Hearts' not in deck"
suites
|> List.map (fun s -> faces |> List.map (fun f -> (s, f)))
|> List.concat
printfn "Deck has %d cards" (List.length deck)
match deck |> List.exists (fun e -> e = ("h", "A")) with
| true -> printfn "Deck contains 'Ace of Hearts'"
| _ -> printfn "'Ace of Hearts' not in deck"
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"])
fsharp
let lengths = List.map String.length ["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.)])
fsharp
let (things:obj list) = [ "hello"; 25; 3.14; System.DateTime.Now ]
let isNumber (x:obj) =
match x with
| :? int | :? float | :? byte | :? decimal | :? int16 | :? int64 -> true
| _ -> false
let numbers, nonNumbers = things |> List.partition isNumber
let isNumber (x:obj) =
match x with
| :? int | :? float | :? byte | :? decimal | :? int16 | :? int64 -> true
| _ -> false
let numbers, nonNumbers = things |> List.partition isNumber
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])
fsharp
let rec IsAll predicate source =
let mutable acc = true
for e in source do
acc <- acc && (predicate e)
acc
let mutable acc = true
for e in source do
acc <- acc && (predicate e)
acc
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])
fsharp
let rec IsAny predicate source =
match source with
| [] -> false
| h::t ->
if (predicate h) then true
else (IsAny predicate t )
match source with
| [] -> false
| h::t ->
if (predicate h) then true
else (IsAny predicate t )
