Java
- IntStream stream1 = IntStream.of(1, 2, 3);
- IntStream stream2 = IntStream.of(2, 1, 4);
- IntStream result = IntStream.concat(stream1, stream2);
- IntStream stream1 = IntStream.of(1, 2, 3);
- IntStream stream2 = IntStream.of(2, 1, 4);
- IntStream result = Stream.of(stream1, stream2).flatMapToInt(s -> s);
Groovy
- def list1 = [1, 2, 3]
- def list2 = [2, 1, 4]
- def result = list1 + list2
Kotlin
- val list1 = listOf(1, 2, 3)
- val list2 = listOf(2, 1, 4)
- val result = list1 + list2
Scala
- val list1 = List(1, 2, 3)
- val list2 = List(2, 1, 4)
- val result = list1 ::: list2
Erlang
- List1 = [1, 2, 3],
- List2 = [2, 1, 4],
- Result = List1 ++ List2.
Haskell
- let list1 = [1, 2, 3]
- let list2 = [2, 1, 4]
- let result = list1 ++ list2
PowerShell
- $array1 = 1, 2, 3
- $array2 = 2, 1, 4
- $result = $array1 + $array2
F#
- let list1 = [1; 2; 3]
- let list2 = [2; 1; 4]
- let result = list1 @ list2
C#
- int[] array1 = { 1, 2, 3 };
- int[] array2 = { 2, 1, 4 };
- var result = array1.Concat(array2);
C++
- #include <vector>
- int array1[] = {1, 2, 3};
- int array2[] = {2, 1, 4};
- vector<int> result;
- result.insert(result.end(), array1, array1 + 3);
- result.insert(result.end(), array2, array2 + 3);
Go
- array1 := [...]int{1, 2, 3}
- array2 := [...]int{2, 1, 4}
- result := list.New()
- for _, x := range(array1) {
- result.PushBack(x)
- }
- for _, x := range(array2) {
- result.PushBack(x)
- }
Rust
- let mut vec1 = vec![1, 2, 3];
- let mut vec2 = vec![2, 1, 4];
- vec1.append(&mut vec2);
Dart
- var list1 = [1, 2, 3];
- var list2 = [2, 1, 4];
- var result = List.from(list1);
- result.addAll(list2);
TypeScript
- let array1 = [1, 2, 3];
- let array2 = [2, 1, 4];
- let result = array1.concat(array2);
- let array1 = [1, 2, 3];
- let array2 = [2, 1, 4];
- let result = [...array1, ...array2];
JavaScript
- let array1 = [1, 2, 3];
- let array2 = [2, 1, 4];
- let result = array1.concat(array2);
- let array1 = [1, 2, 3];
- let array2 = [2, 1, 4];
- let result = [...array1, ...array2];
CoffeeScript
- array1 = [1, 2, 3]
- array2 = [2, 1, 4]
- result = array1.concat array2
- array1 = [1, 2, 3]
- array2 = [2, 1, 4]
- result = [...array1, ...array2]
Ruby
- array1 = [1, 2, 3]
- array2 = [2, 1, 4]
- result = array1 + array2
Python
- list1 = [1, 2, 3]
- list2 = [2, 1, 4]
- result = list1 + list2
PHP
- $array1 = [1, 2, 3];
- $array2 = [2, 1, 4];
- $result = array_merge($array1, $array2);
PHP 7.4以降
- $array1 = [1, 2, 3];
- $array2 = [2, 1, 4];
- $result = [...$array1, ...$array2];
Perl
- my @array1 = (1, 2, 3);
- my @array2 = (2, 1, 4);
- my @result = (@array1, @array2);
Java
安定ソート
- Stream<String> stream = Stream.of("March", "April", "May", "June", "July");
- Stream<String> newStream = stream.sorted(Comparator.comparing(s -> s.length()));
- newStream.forEach(System.out::println);
Guava を使った場合
安定ソート
- List<String> list = Arrays.asList("March", "April", "May", "June", "July");
- Ordering<String> ordering = Ordering.natural().onResultOf(input -> input.length());
- List<String> result = ordering.sortedCopy(list);
- result.forEach(System.out::println);
Groovy
- def list = ['March', 'April', 'May', 'June', 'July']
- def newList = list.clone()
- newList.sort { it.length() }.each { println it }
Kotlin
安定ソート
- val list = listOf("March", "April", "May", "June", "July")
- list.sortedBy { it.length }.forEach(::println)
Scala
安定ソート
- val list = List("March", "April", "May", "June", "July")
- list.sortBy(_.length).foreach(println)
- val list = List("March", "April", "May", "June", "July")
- list.sortWith(_.length < _.length).foreach(println)
Erlang
安定でないソート
- List = ["March", "April", "May", "June", "July"],
- Sorted = lists:sort(fun(X, Y) -> length(X) =< length(Y) end, List),
- lists:foreach(fun(S) -> io:format("~s~n", [S]) end, Sorted).
Haskell
安定ソート
- let list = ["March", "April", "May", "June", "July"]
- let result = sortBy (\ x y -> compare (length x) (length y)) list
- mapM_ putStrLn result
PowerShell
- $array = 'March', 'April', 'May', 'June', 'July'
- $array | sort Length
F#
- let list = ["March"; "April"; "May"; "June"; "July"]
- list |> List.sortBy String.length |> List.iter (printfn "%s")
- let list = ["March"; "April"; "May"; "June"; "July"]
- for s in List.sortBy String.length list do printfn "%s" s
F# 3.0以降
- let list = ["March"; "April"; "May"; "June"; "July"]
- Seq.iter ignore <| query { for s in list do
- sortBy s.Length
- select (printfn "%s" s) }
C#
安定ソート
- string[] array = { "March", "April", "May", "June", "July" };
- foreach (string s in array.OrderBy(s => s.Length)) {
- Console.WriteLine(s);
- }
- string[] array = { "March", "April", "May", "June", "July" };
- var query = from s in array orderby s.Length select s;
- foreach (string s in query) {
- Console.WriteLine(s);
- }
C++
- bool length_ascending(const string& x, const string& y) {
- return x.length() < y.length();
- }
安定でないソート
- #include <algorithm>
- #include <vector>
- const int N = 5;
- string array[N] = {"March", "April", "May", "June", "July"};
- vector<string> v(array, array + N);
- sort(v.begin(), v.end(), length_ascending);
- for (vector<string>::iterator it = v.begin(); it != v.end(); it++) {
- cout << *it << endl;
- }
安定ソート
- #include <algorithm>
- #include <vector>
- const int N = 5;
- string array[N] = {"March", "April", "May", "June", "July"};
- vector<string> v(array, array + N);
- stable_sort(v.begin(), v.end(), length_ascending);
- for (vector<string>::iterator it = v.begin(); it != v.end(); it++) {
- cout << *it << endl;
- }
Go
専用の型を用意する
- type LengthAscending []string
- func (this LengthAscending) Len() int {
- return len(this)
- }
- func (this LengthAscending) Less(i, j int) bool {
- return len(this[i]) < len(this[j])
- }
- func (this LengthAscending) Swap(i, j int) {
- this[i], this[j] = this[j], this[i]
- }
- array := [...]string{"March", "April", "May", "June", "July"}
- newArray := array
- sort.Sort(LengthAscending(newArray[:]))
- for _, s := range newArray {
- fmt.Printf("%s\n", s)
- }
汎用的な型を用意する
- type StringSort struct {
- array []string
- less func(a, b *string) bool
- }
- func (this *StringSort) Len() int {
- return len(this.array)
- }
- func (this *StringSort) Less(i, j int) bool {
- return this.less(&this.array[i], &this.array[j])
- }
- func (this *StringSort) Swap(i, j int) {
- this.array[i], this.array[j] = this.array[j], this.array[i]
- }
- array := [...]string{"March", "April", "May", "June", "July"}
- newArray := array
- sort.Sort(&StringSort{newArray[:], func(a, b *string) bool {
- return len(*a) < len(*b)
- }})
- for _, s := range newArray {
- fmt.Printf("%s\n", s)
- }
Rust
安定ソート
- let array = ["March", "April", "May", "June", "July"];
- let mut vec = array.to_vec();
- vec.sort_by_key(|s| s.chars().count());
Dart
安定でないソート
- var list = ['March', 'April', 'May', 'June', 'July'];
- var newList = List.from(list);
- newList.sort((a, b) => a.length - b.length);
- newList.forEach(print);
TypeScript
安定ソート(ただし Internet Explorer を除く)
- let array = ['March', 'April', 'May', 'June', 'July'];
- let newArray = array.slice(0);
- newArray.sort((x, y) => x.length - y.length);
- newArray.forEach(s => console.log(s));
Underscore を使った場合
- let array = ['March', 'April', 'May', 'June', 'July'];
- _.sortBy(array, s => s.length).forEach(s => console.log(s));
JavaScript
安定ソート(ただし Internet Explorer を除く)
- let array = ['March', 'April', 'May', 'June', 'July'];
- let newArray = array.slice(0);
- newArray.sort((x, y) => x.length - y.length);
- newArray.forEach(s => console.log(s));
Underscore を使った場合
- let array = ['March', 'April', 'May', 'June', 'July'];
- _.sortBy(array, s => s.length).forEach(s => console.log(s));
CoffeeScript
安定ソート(ただし Internet Explorer を除く)
- array = ['March', 'April', 'May', 'June', 'July']
- newArray = array.slice 0
- newArray.sort (x, y) -> x.length - y.length
- console.log s for s in newArray
Underscore を使った場合
- array = ['March', 'April', 'May', 'June', 'July']
- console.log s for s in _.sortBy array, (s) -> s.length
Ruby
安定でないソート
- array = %w[March April May June July]
- puts array.sort_by {|s| s.length }
安定でないソート
Ruby 2.7以降
- array = %w[March April May June July]
- puts array.sort_by { _1.length }
Python
安定ソート
- l = ['March', 'April', 'May', 'June', 'July']
- for s in sorted(l, key = len):
- print(s)
PHP
安定でないソート
- $array = ['March', 'April', 'May', 'June', 'July'];
- $newArray = $array;
- usort($newArray, function($a, $b) { return strlen($a) - strlen($b); });
- foreach ($newArray as $s) {
- echo $s, "\n";
- }
PHP 7.4以降
- $array = ['March', 'April', 'May', 'June', 'July'];
- $newArray = $array;
- usort($newArray, fn($a, $b) => strlen($a) - strlen($b));
- foreach ($newArray as $s) {
- echo $s, "\n";
- }
Perl
Perl 5.6までは安定でないソート、Perl 5.7以降は安定ソート
- my @array = qw/March April May June July/;
- for (sort { length($a) <=> length($b) } @array) {
- print "$_\n";
- }
- my @array = qw/March April May June July/;
- print "$_\n" for sort { length($a) <=> length($b) } @array;
- my @array = qw/March April May June July/;
- print "$_\n" for
- map $_->[0],
- sort { $a->[1] <=> $b->[1] }
- map [$_, length], @array;
Java
- Stream<String> stream = Stream.of("March", "April", "May", "June", "July");
- Stream<String> newStream = stream.sorted(
- Comparator.comparing((String s) -> s.length()).thenComparing(s -> s));
- newStream.forEach(System.out::println);
Guava を使った場合
- List<String> list = Arrays.asList("March", "April", "May", "June", "July");
- Ordering<String> ordering = Ordering.natural()
- .onResultOf((String input) -> input.length()).compound(Ordering.natural());
- List<String> result = ordering.sortedCopy(list);
- result.forEach(System.out::println);
Groovy
- def list = ['March', 'April', 'May', 'June', 'July']
- list.sort { x, y ->
- x.length() <=> y.length() ?: x <=> y
- }.each { println it }
Kotlin
安定ソート
- val list = listOf("March", "April", "May", "June", "July")
- list.sortedWith(compareBy({ it.length }, { it })).forEach(::println)
Scala
安定ソート
- val list = List("March", "April", "May", "June", "July")
- list.sortBy(s => (s.length, s)).foreach(println)
Erlang
- List = ["March", "April", "May", "June", "July"],
- F = fun(X, Y) ->
- LenX = length(X),
- LenY = length(Y),
- LenX < LenY orelse LenX =:= LenY andalso X =< Y
- end,
- Sorted = lists:sort(F, List),
- lists:foreach(fun(S) -> io:format("~s~n", [S]) end, Sorted).
Haskell
安定ソート
- let list = ["March", "April", "May", "June", "July"]
- let result = sortBy (\ x y -> compare (length x, x) (length y, y)) list
- mapM_ putStrLn result
PowerShell
- $array = 'March', 'April', 'May', 'June', 'July'
- $array | sort Length, { $_ }
F#
- let list = ["March"; "April"; "May"; "June"; "July"]
- list |> List.sortBy (fun s -> (s.Length, s)) |> List.iter (printfn "%s")
- let list = ["March"; "April"; "May"; "June"; "July"]
- for s in list |> List.sortBy (fun s -> (s.Length, s)) do printfn "%s" s
F# 3.0以降
- let list = ["March"; "April"; "May"; "June"; "July"]
- Seq.iter ignore <| query { for s in list do
- sortBy s.Length
- thenBy s
- select (printfn "%s" s) }
C#
安定ソート
- string[] array = { "March", "April", "May", "June", "July" };
- foreach (var s in array.OrderBy(s => s.Length).ThenBy(s => s)) {
- Console.WriteLine(s);
- }
- string[] array = { "March", "April", "May", "June", "July" };
- var query = from s in array orderby s.Length, s select s;
- foreach (var s in query) {
- Console.WriteLine(s);
- }
C++
- bool length_value_ascending(const string& x, const string& y) {
- int result = x.length() - y.length();
- return result == 0 ? x < y : result < 0;
- }
安定でないソート
- #include <algorithm>
- const int N = 5;
- string array[N] = {"March", "April", "May", "June", "July"};
- sort(array, array + N, length_value_ascending);
- for (int i = 0; i < N; i++) {
- cout << array[i] << endl;
- }
安定ソート
- #include <algorithm>
- const int N = 5;
- string array[N] = {"March", "April", "May", "June", "July"};
- stable_sort(array, array + N, length_value_ascending);
- for (int i = 0; i < N; i++) {
- cout << array[i] << endl;
- }
Go
専用の型を用意する
- type LengthValueAscending []string
- func (this LengthValueAscending) Len() int {
- return len(this)
- }
- func (this LengthValueAscending) Less(i, j int) bool {
- result := len(this[i]) - len(this[j])
- if result == 0 {
- return this[i] < this[j]
- }
- return result < 0
- }
- func (this LengthValueAscending) Swap(i, j int) {
- this[i], this[j] = this[j], this[i]
- }
- array := [...]string{"March", "April", "May", "June", "July"}
- sort.Sort(LengthValueAscending(array[:]))
- for _, s := range array {
- fmt.Printf("%s\n", s)
- }
汎用的な型を用意する
- type StringSort struct {
- array []string
- less func(a, b *string) bool
- }
- func (this *StringSort) Len() int {
- return len(this.array)
- }
- func (this *StringSort) Less(i, j int) bool {
- return this.less(&this.array[i], &this.array[j])
- }
- func (this *StringSort) Swap(i, j int) {
- this.array[i], this.array[j] = this.array[j], this.array[i]
- }
- array := [...]string{"March", "April", "May", "June", "July"}
- sort.Sort(&StringSort{array[:], func(a, b *string) bool {
- result := len(*a) - len(*b)
- if result == 0 {
- return *a < *b
- }
- return result < 0
- }})
- for _, s := range array {
- fmt.Printf("%s\n", s)
- }
Rust
安定ソート
- let mut vec = vec!["March", "April", "May", "June", "July"];
- vec.sort_by(|a, b| {
- let ta = (a.chars().count(), a);
- let tb = (b.chars().count(), b);
- ta.cmp(&tb)
- });
Dart
安定でないソート
- var list = ['March', 'April', 'May', 'June', 'July'];
- list.sort((a, b) {
- var result = a.length - b.length;
- if (result == 0) {
- result = a.compareTo(b);
- }
- return result;
- });
- list.forEach(print);
TypeScript
安定ソート(ただし Internet Explorer を除く)
- let array = ['March', 'April', 'May', 'June', 'July'];
- array.sort((x, y) => {
- let result = x.length - y.length;
- if (result == 0) {
- result = x < y ? -1 : x > y ? 1 : 0;
- }
- return result;
- });
- for (let i in array) {
- console.log(array[i]);
- }
Underscore を使った場合
- let array = ['March', 'April', 'May', 'June', 'July'];
- _.sortBy(array, s => [s.length, s]).forEach(s => console.log(s));
JavaScript
安定ソート(ただし Internet Explorer を除く)
- let array = ['March', 'April', 'May', 'June', 'July'];
- array.sort((x, y) => {
- let result = x.length - y.length;
- if (result == 0) {
- result = x < y ? -1 : x > y ? 1 : 0;
- }
- return result;
- });
- for (let i in array) {
- console.log(array[i]);
- }
Underscore を使った場合
- let array = ['March', 'April', 'May', 'June', 'July'];
- _.sortBy(array, s => [s.length, s]).forEach(s => console.log(s));
CoffeeScript
安定ソート(ただし Internet Explorer を除く)
- array = ['March', 'April', 'May', 'June', 'July']
- array.sort (x, y) ->
- result = x.length - y.length
- result = (if x < y then -1 else
- if x > y then 1 else 0) if result == 0
- result
- console.log s for s in array
Underscore を使った場合
- array = ['March', 'April', 'May', 'June', 'July']
- console.log s for s in _.sortBy array, (s) -> [s.length, s]
Ruby
安定でないソート
- array = %w[March April May June July]
- puts array.sort_by {|s| [s.length, s] }
安定でないソート
Ruby 2.7以降
- array = %w[March April May June July]
- puts array.sort_by { [_1.length, _1] }
Python
安定ソート
- l = ['March', 'April', 'May', 'June', 'July']
- l.sort(key = lambda s: [len(s), s])
- for s in l:
- print(s)
PHP
安定でないソート
- $array = ['March', 'April', 'May', 'June', 'July'];
- usort($array, function($a, $b) {
- $result = strlen($a) - strlen($b);
- return $result === 0 ? strcmp($a, $b) : $result;
- });
- foreach ($array as $s) {
- echo $s, "\n";
- }
Perl
Perl 5.6までは安定でないソート、Perl 5.7以降は安定ソート
- my @array = qw/March April May June July/;
- for (sort { length($a) <=> length($b) or $a cmp $b } @array) {
- print "$_\n";
- }
- my @array = qw/March April May June July/;
- print "$_\n" for sort { length($a) <=> length($b) or $a cmp $b } @array;
- my @array = qw/March April May June July/;
- print "$_\n" for
- map $_->[0],
- sort { $a->[1] <=> $b->[1] or $a->[0] cmp $b->[0] }
- map [$_, length], @array;
Java
- Stream<String> stream = Stream.of("March", "April", "May", "June", "July");
- String result = stream.max(Comparator.comparing(s -> s.length())).get();
- List<String> list = Arrays.asList("March", "April", "May", "June", "July");
- String result = Collections.max(list, Comparator.comparing(s -> s.length()));
Guava を使った場合
- List<String> list = Arrays.asList("March", "April", "May", "June", "July");
- Ordering<String> ordering = Ordering.natural().onResultOf(input -> input.length());
- String result = ordering.max(list);
Groovy
- def list = ['March', 'April', 'May', 'June', 'July']
- def result = list.max { it.length() }
Kotlin
Kotlin 1.4以降
- val list = listOf("March", "April", "May", "June", "July")
- val result = list.maxByOrNull { it.length }!!
Kotlin 1.3まで
- val list = listOf("March", "April", "May", "June", "July")
- val result = list.maxBy { it.length }!!
Scala
- val list = List("March", "April", "May", "June", "July")
- val result = list.maxBy(_.length)
- val list = List("March", "April", "May", "June", "July")
- val result = list.max(Ordering.by((_: String).length))
- val list = List("March", "April", "May", "June", "July")
- val result = list.reduceLeft((x, y) => if (x.length > y.length) x else y)
- val list = List("March", "April", "May", "June", "July")
- val result = list.sortBy(_.length).last
Erlang
- List = ["March", "April", "May", "June", "July"],
- [Result|_] = lists:sort(fun(X, Y) -> length(X) > length(Y) end, List).
- List = ["March", "April", "May", "June", "July"],
- Longer = fun(X, Y) ->
- if
- length(X) > length(Y) -> X;
- true -> Y
- end
- end,
- Result = lists:foldl(Longer, "", List).
Haskell
- let list = ["March", "April", "May", "June", "July"]
- let result = maximumBy (\ x y -> compare (length x) (length y)) list
PowerShell
- $array = 'March', 'April', 'May', 'June', 'July'
- $result = ($array | sort Length -Descending)[0]
F#
- let list = ["March"; "April"; "May"; "June"; "July"]
- let result = List.maxBy String.length list
- let list = ["March"; "April"; "May"; "June"; "July"]
- let result = list |> List.maxBy String.length
F# 3.0以降
- let list = ["March"; "April"; "May"; "June"; "July"]
- let result = query { for s in list do
- sortByDescending s.Length
- head }
C#
- string[] array = { "March", "April", "May", "June", "July" };
- var result = array.Aggregate((x, y) => x.Length > y.Length ? x : y);
- string[] array = { "March", "April", "May", "June", "July" };
- var result = (from s in array orderby s.Length descending select s).First();
- string[] array = { "March", "April", "May", "June", "July" };
- var result = array.OrderByDescending(s => s.Length).First();
- string[] array = { "March", "April", "May", "June", "July" };
- var maxLength = array.Max(s => s.Length);
- var result = array.First(s => s.Length == maxLength);
C++
- bool length_ascending(const string& x, const string& y) {
- return x.length() < y.length();
- }
- #include <algorithm>
- const int N = 5;
- string array[N] = {"March", "April", "May", "June", "July"};
- string* result = max_element(array, array + N, length_ascending);
Go
- array := [...]string{"March", "April", "May", "June", "July"}
- var result string
- maxLength := -1
- for _, s := range(array) {
- if len(s) > maxLength {
- maxLength = len(s)
- result = s
- }
- }
Rust
- let array = ["March", "April", "May", "June", "July"];
- let result = array.iter().max_by_key(|s| s.chars().count()).unwrap();
Dart
- var list = ['March', 'April', 'May', 'June', 'July'];
- list.sort((a, b) => b.length - a.length);
- var result = list[0];
TypeScript
- let array = ['March', 'April', 'May', 'June', 'July'];
- array.sort((x, y) => x.length - y.length);
- let result = array.pop();
Underscore を使った場合
- let array = ['March', 'April', 'May', 'June', 'July'];
- let result = _.max(array, s => s.length);
JavaScript
- let array = ['March', 'April', 'May', 'June', 'July'];
- array.sort((x, y) => x.length - y.length);
- let result = array.pop();
Underscore を使った場合
- let array = ['March', 'April', 'May', 'June', 'July'];
- let result = _.max(array, s => s.length);
CoffeeScript
- array = ['March', 'April', 'May', 'June', 'July']
- array.sort (x, y) -> x.length - y.length
- result = array.pop()
Underscore を使った場合
- array = ['March', 'April', 'May', 'June', 'July']
- result = _.max array, (s) => s.length
Ruby
- array = %w[March April May June July]
- result = array.max_by {|s| s.length }
Ruby 2.7以降
- array = %w[March April May June July]
- result = array.max_by { _1.length }
Python
- l = ['March', 'April', 'May', 'June', 'July']
- result = max(l, key = len)
PHP
- $array = ['March', 'April', 'May', 'June', 'July'];
- $result = array_reduce($array, function($a, $b) { return strlen($a) > strlen($b) ? $a : $b; });
PHP 7.4以降
- $array = ['March', 'April', 'May', 'June', 'July'];
- $result = array_reduce($array, fn($a, $b) => strlen($a) > strlen($b) ? $a : $b);
Perl
- my @array = qw/March April May June July/;
- my ($result) = sort { length $b <=> length $a } @array;
- my @array = qw/March April May June July/;
- my $result = List::Util::reduce { length $a > length $b ? $a : $b } @array;
- my @array = qw/March April May June July/;
- my $max_length = List::Util::max(map length, @array);
- my $result = List::Util::first { length == $max_length } @array;
Java
- Stream<String> stream = Stream.of("March", "April", "May", "June", "July");
- List<String> result = stream.collect(Collectors.groupingBy(s -> s.length()))
- .entrySet().stream()
- .max(Comparator.comparing(e -> e.getKey()))
- .get().getValue();
Groovy
- def list = ['March', 'April', 'May', 'June', 'July']
- def maxLength = list.collect { it.length() }.max()
- def result = list.findAll { it.length() == maxLength }
- def list = ['March', 'April', 'May', 'June', 'July']
- def maxLength = list*.length().max()
- def result = list.findAll { it.length() == maxLength }
- def list = ['March', 'April', 'May', 'June', 'July']
- def map = list.groupBy { it.length() }
- def maxLength = map.keySet().max()
- def result = map[maxLength]
Kotlin
Kotlin 1.4以降
- val list = listOf("March", "April", "May", "June", "July")
- val maxLength = list.maxOf { it.length }
- val result = list.filter { it.length == maxLength }
Kotlin 1.3まで
- val list = listOf("March", "April", "May", "June", "July")
- val maxLength = list.maxBy { it.length }!!.length
- val result = list.filter { it.length == maxLength }
Scala
- val list = List("March", "April", "May", "June", "July")
- val maxLength = list.map(_.length).max
- val result = list.filter(_.length == maxLength)
- val list = List("March", "April", "May", "June", "July")
- val map = list.groupBy(_.length)
- val result = map(map.keys.max)
- val list = List("March", "April", "May", "June", "July")
- val tupleList = for (s <- list) yield (s, s.length)
- val maxLength = (for ((_, length) <- tupleList) yield length).max
- val result = for ((s, `maxLength`) <- tupleList) yield s
- val list = List("March", "April", "May", "June", "July")
- val tupleList = list.map(s => (s, s.length)).sortBy(_._2).reverse
- val (_, maxLength) :: _ = tupleList
- val result = tupleList.takeWhile(_._2 == maxLength).map(_._1)
Erlang
- List = ["March", "April", "May", "June", "July"],
- TupleList = [{S, length(S)} || S <- List],
- MaxLength = lists:max([Length || {_, Length} <- TupleList]),
- Result = [S || {S, Length} <- TupleList, Length =:= MaxLength].
Haskell
- let list = ["March", "April", "May", "June", "July"]
- let result = [s | s <- list, length s == maxLength] where
- maxLength = maximum $ map length list
- let list = ["March", "April", "May", "June", "July"]
- let maxLength = maximum $ map length list
- let result = do
- s <- list
- guard $ length s == maxLength
- return s
- let list = ["March", "April", "May", "June", "July"]
- let result = [s | (s, length) <- tupleList, length == maxLength] where
- tupleList = [(s, length s) | s <- list]
- maxLength = maximum [length | (_, length) <- tupleList]
PowerShell
- $array = 'March', 'April', 'May', 'June', 'July'
- $result = ($array | group Length | sort Name -Descending)[0].Group
- $array = 'March', 'April', 'May', 'June', 'July'
- $m = $array | measure Length -Maximum
- $result = $array | where { $_.Length -eq $m.Maximum }
F#
- let list = ["March"; "April"; "May"; "June"; "July"]
- let result = list |> Seq.groupBy String.length |> Seq.maxBy fst |> snd
- let list = ["March"; "April"; "May"; "June"; "July"]
- let maxLength = list |> List.map (fun s -> s.Length) |> List.max
- let result = list |> List.filter (fun s -> s.Length = maxLength)
- let list = ["March"; "April"; "May"; "June"; "July"]
- let maxLength = List.max [for s in list -> s.Length]
- let result = [for s in list do if s.Length = maxLength then yield s]
- let list = ["March"; "April"; "May"; "June"; "July"]
- let tupleList = [for s in list -> (s, s.Length)]
- let maxLength = tupleList |> List.map snd |> List.max
- let result = [for (s, length) in tupleList do if length = maxLength then yield s]
F# 3.0以降
- let list = ["March"; "April"; "May"; "June"; "July"]
- let result = query { for s in list do
- groupBy s.Length into grp
- sortByDescending grp.Key
- head }
- let list = ["March"; "April"; "May"; "June"; "July"]
- let maxLength = query { for s in list do
- maxBy s.Length }
- let result = query { for s in list do
- where (s.Length = maxLength) }
C#
- string[] array = { "March", "April", "May", "June", "July" };
- var result = array.GroupBy(s => s.Length).OrderByDescending(grp => grp.Key).First();
- string[] array = { "March", "April", "May", "June", "July" };
- var groups = array.GroupBy(s => s.Length);
- var maxLength = groups.Max(grp => grp.Key);
- var result = groups.First(grp => grp.Key == maxLength);
- string[] array = { "March", "April", "May", "June", "July" };
- var sorted = array.OrderByDescending(s => s.Length);
- var maxLength = sorted.First().Length;
- var result = sorted.TakeWhile(s => s.Length == maxLength);
- string[] array = { "March", "April", "May", "June", "July" };
- var query = from s in array
- group s by s.Length into grp
- orderby grp.Key descending
- select grp;
- var result = query.First();
C++
- #include <vector>
- int get_length(const string& s) {
- return s.size();
- }
- struct shorter {
- int max_length;
- shorter(const vector<string>& v) {
- vector<int> lengths(v.size());
- transform(v.begin(), v.end(), lengths.begin(), get_length);
- max_length = *max_element(lengths.begin(), lengths.end());
- }
- bool operator()(const string& s) {
- return s.size() < max_length;
- }
- };
- const int N = 5;
- string array[] = {"March", "April", "May", "June", "July"};
- vector<string> v(array, array + N);
- vector<string> result(N);
- vector<string>::iterator result_end = remove_copy_if(v.begin(), v.end(), result.begin(), shorter(v));
- result.resize(result_end - result.begin());
Go
- array := [...]string{"March", "April", "May", "June", "July"}
- m := map[int][]string{}
- for _, s := range array {
- m[len(s)] = append(m[len(s)], s)
- }
- maxLength := 0
- for k := range m {
- if maxLength < k {
- maxLength = k
- }
- }
- result := m[maxLength]
Rust
itertools を使った場合
- let array = ["March", "April", "May", "June", "July"];
- let groups = array.to_vec().into_iter().into_group_map_by(|s| s.chars().count());
- let keys: Vec<_> = groups.clone().into_keys().collect();
- let max_length = keys.iter().max().unwrap();
- let result = &groups[max_length];
Dart
- var list = ['March', 'April', 'May', 'June', 'July'];
- var map = Map<int, List<String>>();
- for (var s in list) {
- map.putIfAbsent(s.length, () => []).add(s);
- }
- var keys = List.from(map.keys);
- keys.sort((a, b) => b - a);
- var result = map[keys[0]];
TypeScript
- let array = ['March', 'April', 'May', 'June', 'July'];
- let result = array.reduce((arr, s) => {
- if (arr[0].length === s.length) {
- arr.push(s);
- } else if (arr[0].length < s.length) {
- arr = [s];
- }
- return arr;
- }, ['']);
Underscore を使った場合
- let array = ['March', 'April', 'May', 'June', 'July'];
- let maxLength = _.max(array.map(s => s.length));
- let result = array.filter(s => s.length === maxLength);
- let array = ['March', 'April', 'May', 'June', 'July'];
- let maxLength = _.max(array.map(s => s.length));
- let result = _.where(array, { length: maxLength });
JavaScript
- let array = ['March', 'April', 'May', 'June', 'July'];
- let result = array.reduce((arr, s) => {
- if (arr[0].length === s.length) {
- arr.push(s);
- } else if (arr[0].length < s.length) {
- arr = [s];
- }
- return arr;
- }, ['']);
Underscore を使った場合
- let array = ['March', 'April', 'May', 'June', 'July'];
- let maxLength = _.max(array.map(s => s.length));
- let result = array.filter(s => s.length === maxLength);
- let array = ['March', 'April', 'May', 'June', 'July'];
- let maxLength = _.max(array.map(s => s.length));
- let result = _.where(array, { length: maxLength });
CoffeeScript
- array = ['March', 'April', 'May', 'June', 'July']
- result = array.reduce (arr, s) ->
- if arr[0].length == s.length
- arr.push s
- else if arr[0].length < s.length
- arr = [s]
- arr
- , ['']
Underscore を使った場合
- array = ['March', 'April', 'May', 'June', 'July']
- maxLength = _.max array.map (s) -> s.length
- result = array.filter (s) -> s.length == maxLength
- array = ['March', 'April', 'May', 'June', 'July']
- maxLength = _.max array.map (s) -> s.length
- result = _.where array, { length: maxLength }
Ruby
- array = %w[March April May June July]
- hash = {}
- array.each {|s| (hash[s.size] ||= []) << s }
- result = hash[hash.keys.max]
- array = %w[March April May June July]
- hash = Hash.new {|h, key| h[key] = [] }
- array.each {|s| hash[s.size] << s }
- result = hash[hash.keys.max]
Ruby on Rails の場合
- array = %w[March April May June July]
- result = array.group_by {|s| s.size }.max_by {|grp| grp[0] }[1]
Python
- l = ['March', 'April', 'May', 'June', 'July']
- max_length = max(map(len, l))
- result = [s for s in l if len(s) == max_length]
- l = ['March', 'April', 'May', 'June', 'July']
- d = dict((key, list(values)) for key, values in itertools.groupby(l, len))
- result = d[max(d)]
PHP
- $array = ['March', 'April', 'May', 'June', 'July'];
- $dict = [];
- foreach ($array as $s) {
- $len = strlen($s);
- if (! array_key_exists($len, $dict)) {
- $dict[$len] = [];
- }
- array_push($dict[$len], $s);
- }
- krsort($dict);
- $result = current($dict);
Perl
- my @array = qw/March April May June July/;
- my $max_length = List::Util::max(map length, @array);
- my @result = grep { length == $max_length } @array;
- my @array = qw/March April May June July/;
- my $max_length = List::Util::max(map length, @array);
- my @result = map { length == $max_length ? $_ : () } @array;
- my @array = qw/March April May June July/;
- my %hash;
- push @{$hash{length $_}}, $_ for @array;
- my @result = @{$hash{List::Util::max keys %hash}};
Java
- IntStream stream = IntStream.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
- IntStream result = stream.filter(x -> x % 2 == 0);
Groovy
- def list = 0..9
- def result = list.findAll { it % 2 == 0 }
Kotlin
- val range = 0..9
- val result = range.filter { it % 2 == 0 }
Scala
- val range = 0 to 9
- val result = range.filter(_ % 2 == 0)
- val range = 0 to 9
- val result = for (x <- range if x % 2 == 0) yield x
Erlang
- List = lists:seq(0, 9),
- Result = [X || X <- List, X rem 2 =:= 0].
- List = lists:seq(0, 9),
- Result = lists:filter(fun(X) -> X rem 2 =:= 0 end, List).
Haskell
- let list = [0..9]
- let result = [x | x <- list, x `mod` 2 == 0]
- let list = [0..9]
- let result = filter (\ x -> x `mod` 2 == 0) list
PowerShell
- $array = 0..9
- $result = $array | where { $_ % 2 -eq 0 }
F#
- let list = [0..9]
- let result = List.filter (fun x -> x % 2 = 0) list
- let list = [0..9]
- let result = list |> List.filter (fun x -> x % 2 = 0)
- let list = [0..9]
- let result = [for x in list do if x % 2 = 0 then yield x]
- let list = [0..9]
- let result = List.choose (fun x -> if x % 2 = 0 then Some x else None) list
- let list = [0..9]
- let result = List.choose (function x when x % 2 = 0 -> Some x | _ -> None) list
F# 3.0以降
- let list = [0..9]
- let result = query { for x in list do
- where (x % 2 = 0) }
C#
- var e = Enumerable.Range(0, 10);
- var result = e.Where(x => x % 2 == 0);
- var e = Enumerable.Range(0, 10);
- var result = from x in e where x % 2 == 0 select x;
C++
- bool is_odd(const int& x) {
- return x % 2 != 0;
- }
- const int N = 10;
- int array[N] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
- int result[N];
- int* result_end = remove_copy_if(array, array + N, result, is_odd);
Boost を使った場合
- #include <algorithm>
- #include <boost/lambda/lambda.hpp>
- const int N = 10;
- int array[N] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
- int result[N];
- int* result_end = remove_copy_if(array, array + N, result, _1 % 2 != 0);
Go
- array := [...]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
- result := []int{}
- for _, x := range array {
- if x % 2 == 0 {
- result = append(result, x)
- }
- }
go-funk を使った場合
- array := [...]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
- result := funk.Filter(array, func(x int) bool {
- return x % 2 == 0
- }).([]int)
Rust
- let range = Range { start: 0, end: 9 };
- let result: Vec<_> = range.filter(|x| x % 2 == 0).collect();
Dart
- var list = List.generate(10, (i) => i);
- var result = list.where((x) => x % 2 == 0);
TypeScript
- let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
- let result = array.filter(x => x % 2 === 0);
JavaScript
- let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
- let result = array.filter(x => x % 2 === 0);
CoffeeScript
- array = [0..9]
- result = (x for x in array when x % 2 == 0)
Ruby
- range = 0..9
- result = range.select {|x| x % 2 == 0 }
Ruby 2.6以降
- range = 0..9
- result = range.filter {|x| x % 2 == 0 }
Python
- l = range(0, 10)
- result = [x for x in l if x % 2 == 0]
- l = range(0, 10)
- result = filter(lambda x: x % 2 == 0, l)
PHP
- $array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
- $result = array_filter($array, function($x) { return $x % 2 === 0; });
PHP 7.4以降
- $array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
- $result = array_filter($array, fn($x) => $x % 2 === 0);
Perl
- my @array = (0..9);
- my @result = grep { $_ % 2 == 0 } @array;
- my @array = (0..9);
- my @result = grep !($_ % 2), @array;
- my @array = (0..9);
- my @result = map { $_ % 2 ? () : $_ } @array;
Java
- @SuppressWarnings("unchecked")
- public static List<Integer>[] evensAndOdds(Stream<Integer> ints) {
- Map<Boolean, List<Integer>> map = ints.collect(Collectors.partitioningBy(i -> i % 2 == 0));
- return new List[] {map.get(true), map.get(false)};
- }
- List<Integer>[] evensAndOdds = evensAndOdds(Stream.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9));
- List<Integer> evens = evensAndOdds[0];
- List<Integer> odds = evensAndOdds[1];
Groovy
- def evensAndOdds(ints) {
- ints.split { it % 2 == 0 }
- }
- def (evens, odds) = evensAndOdds(0..9)
Kotlin
- fun evensAndOdds(iter: Iterable<Int>) = iter.partition { it % 2 == 0 }
- val (evens, odds) = evensAndOdds(0..9)
Scala
- def evensAndOdds(iter: Iterable[Int]) = iter.partition(_ % 2 == 0)
- val (evens, odds) = evensAndOdds(0 to 9)
Erlang
- evens_and_odds(List) -> lists:partition(fun(X) -> X rem 2 =:= 0 end, List).
- evens_and_odds(List) -> evens_and_odds(List, [], []).
- evens_and_odds([Head|Tail], Evens, Odds) ->
- case Head rem 2 of
- 0 -> evens_and_odds(Tail, [Head|Evens], Odds);
- 1 -> evens_and_odds(Tail, Evens, [Head|Odds])
- end;
- evens_and_odds([], Evens, Odds) -> {lists:reverse(Evens), lists:reverse(Odds)}.
- {Evens, Odds} = evens_and_odds([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).
Haskell
- evensAndOdds = partition (\ x -> x `mod` 2 == 0)
- let (evens, odds) = evensAndOdds [0..9]
PowerShell
- function EvensAndOdds($ints) {
- $result = @(@(), @());
- $ints | foreach { $result[$_ % 2] += $_ }
- $result
- }
- ($evens, $odds) = EvensAndOdds @(0..9)
F#
- let evensAndOdds = List.partition (fun x -> x % 2 = 0)
- let evensAndOdds = List.partition <| fun x -> x % 2 = 0
- let evens, odds = evensAndOdds [0..9]
F# 4.5以降
- let evensAndOdds(list: int list, evens: outref<int list>, odds: outref<int list>) =
- let (e, o) = List.partition (fun x -> x % 2 = 0) list
- evens <- e
- odds <- o
- let mutable evens = []
- let mutable odds = []
- evensAndOdds([0..9], &evens, &odds)
C#
- public static void EvensAndOdds(IEnumerable<int> ints, out IEnumerable<int> evens, out IEnumerable<int> odds) {
- var lookup = ints.ToLookup(x => x % 2);
- evens = lookup[0];
- odds = lookup[1];
- }
- IEnumerable<int> evens;
- IEnumerable<int> odds;
- EvensAndOdds(Enumerable.Range(0, 10), out evens, out odds);
C# 7.0以降
- EvensAndOdds(Enumerable.Range(0, 10), out var evens, out var odds);
- public static (IEnumerable<int> evens, IEnumerable<int> odds) EvensAndOdds(IEnumerable<int> ints) {
- var lookup = ints.ToLookup(x => x % 2);
- return (lookup[0], lookup[1]);
- }
- var (evens, odds) = EvensAndOdds(Enumerable.Range(0, 10));
C++
vector 専用
- #include <algorithm>
- #include <vector>
- struct is_even : unary_function<int, bool> {
- bool operator()(const int& x) const {
- return x % 2 == 0;
- }
- };
- void evens_and_odds(vector<int>& ints, vector<int>& evens, vector<int>& odds) {
- vector<int>::iterator it = partition(ints.begin(), ints.end(), is_even());
- evens = vector<int>(ints.begin(), it);
- odds = vector<int>(it, ints.end());
- }
- const int N = 10;
- int array[N] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
- vector<int> ints(array, array + N);
- vector<int> evens, odds;
- evens_and_odds(ints, evens, odds);
vector のほか list などにも対応
- #include <algorithm>
- #include <vector>
- struct is_even : unary_function<int, bool> {
- bool operator()(const int& x) const {
- return x % 2 == 0;
- }
- };
- template <class T, typename I>
- void evens_and_odds(I begin, I end, T& evens, T& odds) {
- I i = partition(begin, end, is_even());
- evens = T(begin, i);
- odds = T(i, end);
- }
- const int N = 10;
- int array[N] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
- vector<int> ints(array, array + N);
- vector<int> evens, odds;
- evens_and_odds(ints.begin(), ints.end(), evens, odds);
Go
- func EvensAndOdds(ints []int) (evens []int, odds []int) {
- for _, x := range ints {
- if x % 2 == 0 {
- evens = append(evens, x)
- } else {
- odds = append(odds, x)
- }
- }
- return evens, odds
- }
- evens, odds := EvensAndOdds([]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
Rust
- fn evens_and_odds(iter: &mut dyn Iterator<Item = i32>) -> (Vec<i32>, Vec<i32>) {
- iter.partition(|x| x % 2 == 0)
- }
- let (evens, odds) = evens_and_odds(&mut Range { start: 0, end: 9 }.collect());
Dart
- List<List<int>> evensAndOdds(Iterable<int> iter) {
- List<List<int>> result = [[], []];
- for (var x in iter) {
- result[x % 2].add(x);
- }
- return result;
- }
- var list = List.generate(10, (i) => i);
- var result = evensAndOdds(list);
- var evens = result[0];
- var odds = result[1];
TypeScript
Underscore を使った場合
- function evensAndOdds(array) {
- return _.partition(array, x => x % 2 === 0);
- }
- let [evens, odds] = evensAndOdds([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
JavaScript
Underscore を使った場合
- function evensAndOdds(array) {
- return _.partition(array, x => x % 2 === 0);
- }
- let [evens, odds] = evensAndOdds([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
CoffeeScript
Underscore を使った場合
- evensAndOdds = (array) ->
- _.partition array, (x) -> x % 2 == 0
- [evens, odds] = evensAndOdds [0..9]
Ruby
- def evens_and_odds array
- array.partition {|x| x % 2 == 0 }
- end
- evens, odds = evens_and_odds 0..9
Python
- def evens_and_odds(iter):
- def keyfunc(x):
- return x % 2
- groups = {}
- for mod, values in itertools.groupby(sorted(iter, key = keyfunc), key = keyfunc):
- groups[mod] = list(values)
- return groups[0], groups[1]
- evens, odds = evens_and_odds(range(0, 10))
PHP
- function evens_and_odds($array) {
- $result = [[], []];
- foreach ($array as $n) {
- array_push($result[$n % 2], $n);
- }
- return $result;
- }
- list($evens, $odds) = evens_and_odds([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
Perl
- sub evens_and_odds {
- my @result = ([], []);
- push @{$result[$_ % 2]}, $_ for @_;
- @result;
- }
- sub evens_and_odds {
- my @evens, @odds;
- for (@_) {
- my $ref = $_ % 2 ? \@odds : \@evens;
- push @$ref, $_;
- }
- \@evens, \@odds;
- }
- my ($evens, $odds) = &evens_and_odds(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
Java
- IntStream stream = IntStream.of(2, 4, 5, 2, 1, 7, 4, 0);
- IntStream result = stream.distinct();
Groovy
- def list = [2, 4, 5, 2, 1, 7, 4, 0]
- def result = list.unique()
Kotlin
- val list = listOf(2, 4, 5, 2, 1, 7, 4, 0)
- val result = list.distince()
- val list = listOf(2, 4, 5, 2, 1, 7, 4, 0)
- val result = list.toSet()
Scala
- val list = List(2, 4, 5, 2, 1, 7, 4, 0)
- val result = list.distinct
- val list = List(2, 4, 5, 2, 1, 7, 4, 0)
- val result = Set(list: _*)
Erlang
- List = [2, 4, 5, 2, 1, 7, 4, 0],
- Result = sets:from_list(List).
Haskell
- let list = [2, 4, 5, 2, 1, 7, 4, 0]
- let result = nub list
Cabal の
MissingH を使った場合
- let list = [2, 4, 5, 2, 1, 7, 4, 0]
- let result = uniq list
PowerShell
- $array = 2, 4, 5, 2, 1, 7, 4, 0
- $result = $array | sort | Get-Unique
F#
- let list = [2; 4; 5; 2; 1; 7; 4; 0]
- let result = Seq.distinct list
- let list = [2; 4; 5; 2; 1; 7; 4; 0]
- let result = set list
- let list = [2; 4; 5; 2; 1; 7; 4; 0]
- let result = Set.ofList list
F# 3.0以降
- let list = [2; 4; 5; 2; 1; 7; 4; 0]
- let result = query { for x in list do
- distinct }
C#
- int[] array = { 2, 4, 5, 2, 1, 7, 4, 0 };
- var result = array.Distinct();
C++
- #include <algorithm>
- const int N = 10;
- int array[N] = {2, 4, 5, 2, 1, 7, 4, 0};
- int result[N];
- copy(array, array + N, result);
- sort(result, result + N);
- int* result_end = unique(result, result + N);
Go
- array := [...]int{2, 4, 5, 2, 1, 7, 4, 0}
- result := []int{}
- for _, x := range array {
- exists := false
- for _, y := range result {
- exists = x == y
- if exists { break }
- }
- if ! exists {
- result = append(result, x)
- }
- }
- array := [...]int{2, 4, 5, 2, 1, 7, 4, 0}
- newArray := array
- sort.Ints(newArray[:])
- result := []int{}
- for i, x := range newArray {
- if i == 0 || x != result[len(result) - 1] {
- result = append(result, x)
- }
- }
go-funk を使った場合
- array := [...]int{2, 4, 5, 2, 1, 7, 4, 0}
- result := funk.Uniq(array).([]int)
Rust
- let array = [2, 4, 5, 2, 1, 7, 4, 0];
- let result: HashSet<_> = array.iter().collect();
Dart
- var list = [2, 4, 5, 2, 1, 7, 4, 0];
- var result = Set.from(list);
TypeScript
Underscore を使った場合
- let array = [2, 4, 5, 2, 1, 7, 4, 0];
- let result = _.uniq(array);
jQuery を使った場合
- let array = [2, 4, 5, 2, 1, 7, 4, 0];
- let result = $.unique(array);
JavaScript
Underscore を使った場合
- let array = [2, 4, 5, 2, 1, 7, 4, 0];
- let result = _.uniq(array);
jQuery を使った場合
- let array = [2, 4, 5, 2, 1, 7, 4, 0];
- let result = $.unique(array);
CoffeeScript
Underscore を使った場合
- array = [2, 4, 5, 2, 1, 7, 4, 0]
- result = _.uniq array
jQuery を使った場合
- array = [2, 4, 5, 2, 1, 7, 4, 0]
- result = $.unique array
Ruby
- array = [2, 4, 5, 2, 1, 7, 4, 0]
- result = array.uniq
Python
- list = [2, 4, 5, 2, 1, 7, 4, 0]
- s = set(list)
PHP
- $array = [2, 4, 5, 2, 1, 7, 4, 0];
- $result = array_unique($array);
Perl
- my @array = (2, 4, 5, 2, 1, 7, 4, 0);
- my %hash;
- my @result = grep { $hash{$_}++ == 0 } @array;
- my @array = (2, 4, 5, 2, 1, 7, 4, 0);
- my %hash;
- my @result = grep ! $hash{$_}++, @array;
CPAN の
List::MoreUtils を使った場合
- my @array = (2, 4, 5, 2, 1, 7, 4, 0);
- my @result = List::MoreUtils::uniq @array;
CPAN の
Array::Uniq を使った場合
- my @array = (2, 4, 5, 2, 1, 7, 4, 0);
- my @result = uniq sort @array;
Java
- IntStream stream = IntStream.of(2, -3, 5);
- int result = stream.reduce(1, (left, right) -> left * right);
Groovy
- def list = [2, -3, 5]
- def result = list.inject(1) { x, y -> x * y }
Kotlin
- val list = listOf(2, -3, 5)
- val result = list.reduce { x, y -> x * y }
- val list = listOf(2, -3, 5)
- val result = list.fold(1) { x, y -> x * y }
Scala
- val list = List(2, -3, 5)
- val result = list.product
- val list = List(2, -3, 5)
- val result = list.reduceLeft(_ * _)
- val list = List(2, -3, 5)
- val result = list.foldLeft(1)(_ * _)
Erlang
- List = [2, -3, 5],
- Result = lists:foldl(fun(X, Y) -> X * Y end, 1, List).
Haskell
- let list = [2, -3, 5]
- let result = product list
- let list = [2, -3, 5]
- let result = foldl1 (*) list
- let list = [2, -3, 5]
- let result = foldl (*) 1 list
PowerShell
- $array = 2, -3, 5
- $result = 1
- $array | foreach { $result *= $_ }
F#
- let list = [2; -3; 5]
- let result = List.reduce (*) list
- let list = [2; -3; 5]
- let result = list |> List.reduce (*)
- let list = [2; -3; 5]
- let result = List.fold (*) 1 list
- let list = [2; -3; 5]
- let result = list |> List.fold (*) 1
C#
- int[] array = { 2, -3, 5 };
- var result = array.Aggregate((x, y) => x * y);
C++
- #include <numeric>
- const int N = 3;
- int array[N] = {2, -3, 5};
- int result = accumulate(array, array + N, 1, multiplies<int>());
Boost を使った場合
- #include <numeric>
- #include <boost/lambda/lambda.hpp>
- const int N = 3;
- int array[N] = {2, -3, 5};
- int result = accumulate(array, array + N, 1, _1 * _2);
Go
- array := [...]int{2, -3, 5}
- result := 1
- for _, x := range array {
- result *= x
- }
go-funk を使った場合
- array := [...]int{2, -3, 5}
- result := funk.Reduce(array, '*', 1).(int)
Rust
- let array = [2, -3, 5];
- let result: i32 = array.iter().product();
- let array = [2, -3, 5];
- let result = array.iter().fold(1, |acc, x| acc * x);
Dart
- var list = [2, -3, 5];
- var result = list.reduce((x, y) => x * y);
TypeScript
- let array = [2, -3, 5];
- let result = array.reduce((x, y) => x * y);
JavaScript
- let array = [2, -3, 5];
- let result = array.reduce((x, y) => x * y);
CoffeeScript
- array = [2, -3, 5]
- result = array.reduce (x, y) -> x * y
Ruby
- array = [2, -3, 5]
- result = array.inject &:*
- array = [2, -3, 5]
- result = array.inject {|x, y| x * y }
Ruby 2.7以降
- array = [2, -3, 5]
- result = array.inject { _1 * _2 }
Python
Python 3.0以降
- l = [2, -3, 5]
- result = functools.reduce(lambda x, y: x * y, l)
- l = [2, -3, 5]
- result = functools.reduce(operator.mul, l)
Python 2.xまで
- l = [2, -3, 5]
- result = reduce(lambda x, y: x * y, l)
- l = [2, -3, 5]
- result = reduce(operator.mul, l)
PHP
- $array = [2, -3, 5];
- $result = array_product($array);
- $array = [2, -3, 5];
- $result = array_reduce($array, function($x, $y) { return $x * $y; }, 1);
Perl
- my @array = (2, -3, 5);
- my $result = 1;
- for (@array) {
- $result *= $_;
- }
- my @array = (2, -3, 5);
- my $result = 1;
- $result *= $_ for @array;
- my @array = (2, -3, 5);
- my $result = List::Util::reduce { $a * $b } @array;
例えば "1,000+2,000+3,000" のような文字列を作る。
Java
- IntStream stream = IntStream.of(1000, 2000, 3000);
- NumberFormat nf = NumberFormat.getInstance();
- String s = stream.mapToObj(nf::format).collect(Collectors.joining("+"));
Guava を使った場合
- IntStream stream = IntStream.of(1000, 2000, 3000);
- NumberFormat nf = NumberFormat.getInstance();
- String s = Joiner.on('+').join(stream.mapToObj(nf::format).iterator());
Groovy
- def list = [1000, 2000, 3000]
- def s = list.collect(NumberFormat.instance.&format).join('+')
- def list = [1000, 2000, 3000]
- def s = list.collect { String.format '%,d', it }.join('+')
Kotlin
- val list = listOf(1000, 2000, 3000)
- val s = list.map { "%,d".format(it) }.joinToString("+")
Scala
- val list = List(1000, 2000, 3000)
- val s = list.map(NumberFormat.getInstance.format).mkString("+")
- val list = List(1000, 2000, 3000)
- val s = list.map("%,d".format(_)).mkString("+")
Erlang
- List = [1000, 2000, 3000],
- RE = "(\\d)(?=(?:\\d{3})+(?!\\d))",
- Converter = fun(X) ->
- re:replace(io_lib:format("+~b", [X]), RE, "\\1,", [{return, list}])
- end,
- [_|S] = lists:flatten(lists:map(Converter, List)).
Haskell
- intToStr :: Integral a => a -> String
- intToStr n = reverse $ insertComma $ reverse $ show n
- where insertComma (a : b : c : d : t) | (d /= '-') = a : b : c : ',' : insertComma (d : t)
- insertComma t = t
- let list = [1000, 2000, 3000]
- let s = intercalate "+" $ map intToStr list
Cabal の
MissingH を使った場合
- intToStr :: Integral a => a -> String
- intToStr n = reverse $ insertComma $ reverse $ show n
- where insertComma ('-' : s) = '-' : insertComma s
- insertComma s = join "," $ wholeMap (fixedWidth $ repeat 3) s
- let list = [1000, 2000, 3000]
- let s = join "+" $ map intToStr list
PowerShell
- $array = 1000, 2000, 3000
- $s = [string]::Join('+', ($array | foreach { $_.ToString('N0') }))
- $array = 1000, 2000, 3000
- $s = "$($array | foreach { $_.ToString('#,0') })" -replace ' ', '+'
F#
- let list = [1000; 2000; 3000]
- let s = list |> List.map (fun x -> x.ToString "N0") |> String.concat "+"
- let list = [1000; 2000; 3000]
- let s = [for x in list -> x.ToString "#,0"] |> String.concat "+"
F# 3.0以降
- let list = [1000; 2000; 3000]
- let s = String.concat "+" <| query { for x in list do
- select (x.ToString "#,0") }
C#
- int[] array = { 1000, 2000, 3000 };
- var s = string.Join("+", array.Select(x => x.ToString("N0")));
C++
Boost を使った場合
- #include <sstream>
- #include <vector>
- #include <boost/algorithm/string/join.hpp>
- #include <boost/regex.hpp>
- string number_format(const int n) {
- stringstream ss;
- ss << n;
-
- boost::regex r("(\\d)(?=(?:\\d{3})+(?!\\d))");
- return boost::regex_replace(ss.str(), r, "$1,", boost::format_all);
- }
- const int N = 3;
- int array[N] = {1000, 2000, 3000};
- vector<string> v(N);
- transform(array, array + N, v.begin(), number_format);
- string s = boost::algorithm::join(v, "+");
Go
- func IntToStr(x int) string {
- buf := bytes.NewBufferString("")
- s := strconv.Itoa(x)
- if s[0] == '-' {
- buf.WriteString("-")
- s = s[1:]
- }
- for i, c := range(s) {
- if i > 0 && (len(s) - i) % 3 == 0 {
- buf.WriteString(",")
- }
- buf.WriteString(string(c))
- }
- return buf.String()
- }
- array := [...]int{1000, 2000, 3000}
- buf := bytes.NewBufferString("")
- for i, x := range(array) {
- if i > 0 {
- buf.WriteString("+")
- }
- buf.WriteString(IntToStr(x))
- }
- s := buf.String()
Rust
- pub fn add_separator(n: &i32) -> String {
- format!("{}", n)
- .chars()
- .rev()
- .collect::<Vec<_>>()
- .chunks(3)
- .map(|cs| cs.iter().collect::<String>())
- .collect::<Vec<_>>()
- .join(",")
- .chars()
- .rev()
- .collect()
- }
- let array = [1000, 2000, 3000];
- let result = array.iter().map(|x| add_separator(x)).collect::<Vec<_>>().join("+");
Dart
- var list = [1000, 2000, 3000];
- var re = RegExp(r'\d(?=(?:\d{3})+(?!\d))');
- var s = list.map((x) => x.toString().replaceAllMapped(re, (m) => '${m[0]},')).join('+');
TypeScript
- let array = [1000, 2000, 3000];
- let s = array.map(x => x.toLocaleString()).join('+');
D3 を使った場合
- let array = [1000, 2000, 3000];
- let s = array.map(d3.format(',')).join('+');
JavaScript
- let array = [1000, 2000, 3000];
- let s = array.map(x => x.toLocaleString()).join('+');
D3 を使った場合
- let array = [1000, 2000, 3000];
- let s = array.map(d3.format(',')).join('+');
CoffeeScript
- array = [1000, 2000, 3000]
- s = (s.toLocaleString() for s in array).join '+'
D3 を使った場合
- array = [1000, 2000, 3000]
- s = array.map(d3.format ',').join '+'
Ruby
- array = [1000, 2000, 3000]
- re = /(\d)(?=(?:\d{3})+(?!\d))/
- s = array.collect {|x| x.to_s.gsub(re, '\1,') }.join('+')
Ruby on Rails の場合
- array = [1000, 2000, 3000]
- s = array.collect {|x| number_with_delimiter x }.join('+')
Python
- l = [1000, 2000, 3000]
- s = '+'.join(locale.format('%d', x, grouping = True) for x in l)
- l = [1000, 2000, 3000]
- s = '+'.join(map(lambda x: locale.format('%d', x, grouping = True), l))
PHP
- $array = [1000, 2000, 3000];
- $s = implode('+', array_map('number_format', $array));
Perl
- my @array = (1000, 2000, 3000);
- my $re = q/(\d)(?=(?:\d{3})+(?!\d))/;
- my $s = join '+', map { s/$re/$1,/g; $_ } @array;
CPAN の
Number::Format を使った場合
- my @array = (1000, 2000, 3000);
- my $s = join '+', map { Number::Format::format_number $_ } @array;
例えば下記のようになる。
- <ul class="months">
- <li>March</li>
- <li>April</li>
- <li>May</li>
- <li>June</li>
- <li>July</li>
- </ul>
Java
- String[] array = {"March", "April", "May", "June", "July"};
- Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
- Element ulElem = doc.createElement("ul");
- ulElem.setAttribute("class", "months");
- for (String s : array) {
- Element liElem = doc.createElement("li");
- liElem.appendChild(doc.createTextNode(s));
- ulElem.appendChild(liElem);
- }
- Transformer t = TransformerFactory.newInstance().newTransformer();
- t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
- StringWriter sw = new StringWriter();
- t.transform(new DOMSource(ulElem), new StreamResult(sw));
- String xml = sw.toString();
Thymeleaf を使った場合
- String[] array = {"March", "April", "May", "June", "July"};
- String template = "<ul class='months'>"
- + " <li th:each='s : ${array}' th:text='${s}'></li>"
- + "</ul>";
- Context context = new Context(Locale.getDefault(), Map.of("array", array));
- String xml = new TemplateEngine().process(template, context);
Groovy
- def list = ['March', 'April', 'May', 'June', 'July']
- def sw = new StringWriter()
- def mb = new MarkupBuilder(sw)
- mb.ul(class: 'months') {
- for (s in list) { li s }
- }
- def xml = sw as String
- def list = ['March', 'April', 'May', 'June', 'July']
- def w = new StreamingMarkupBuilder().bind {
- ul(class: 'months') {
- for (s in list) { li s }
- }
- }
- def xml = w as String
- def list = ['March', 'April', 'May', 'June', 'July']
- def b = DOMBuilder.newInstance()
- def elem = b.ul(class: 'months') {
- for (s in list) { li s }
- }
- def t = TransformerFactory.newInstance().newTransformer()
- t.setOutputProperty OutputKeys.OMIT_XML_DECLARATION, 'yes'
- def sw = new StringWriter()
- t.transform new DOMSource(elem), new StreamResult(sw)
- def xml = sw as String
Thymeleaf を使った場合
- def list = ['March', 'April', 'May', 'June', 'July']
- def template = '''
- <ul class="months">
- <li th:each="s : ${list}" th:text="${s}"></li>
- </ul>
- '''
- def context = new Context(Locale.default, ['list': list])
- def xml = new TemplateEngine().process(template, context)
Scala
- val list = List("March", "April", "May", "June", "July")
- val ulElem = <ul class="months">{ for (s <- list) yield <li>{ s }</li> }</ul>
- val xml = ulElem.toString
- val list = List("March", "April", "May", "June", "July")
- val ulElem = <ul class="months">{ list.map(s => <li>{ s }</li>) }</ul>
- val xml = ulElem.toString
Haskell
Cabal の
xml を使った場合
- let list = ["March", "April", "May", "June", "July"]
- let q name = QName name Nothing Nothing
- let li s = Element (q "li") [] [Text $ CData CDataText s Nothing] Nothing
- let ul = Element (q "ul") [Attr (q "class") "months"] (map (Elem . li) list) Nothing
- let xml = showElement ul
PowerShell
- $array = "March", "April", "May", "June", "July"
- $xml = [string]::Join("", @("<ul class=""months"">"; $array | foreach { "<li>$_</li>" }; "</ul>"))
- $array = "March", "April", "May", "June", "July"
- $xml = @"
- <ul class="months">
- $($array | foreach { "<li>$_</li>" })
- </ul>
- "@
F#
- let list = ["March"; "April"; "May"; "June"; "July"]
- let ulElem = new XElement(XName.Get "ul",
- new XAttribute(XName.Get "class", "month"),
- [| for s in list -> new XElement(XName.Get "li", s) |])
- let xml = string ulElem
C#
- string[] array = { "March", "April", "May", "June", "July" };
- var ulElem = new XElement("ul",
- new XAttribute("class", "months"),
- from s in array select new XElement("li", s));
- string xml = ulElem.ToString();
- string[] array = { "March", "April", "May", "June", "July" };
- var ulElem = new XElement("ul",
- new XAttribute("class", "months"),
- array.Select(s => new XElement("li", s)));
- string xml = ulElem.ToString();
- string[] array = { "March", "April", "May", "June", "July" };
- XmlDocument doc = new XmlDocument();
- XmlElement ulElem = doc.CreateElement("ul");
- ulElem.SetAttribute("class", "months");
- foreach (string s in array) {
- XmlElement liElem = doc.CreateElement("li");
- liElem.AppendChild(doc.CreateTextNode(s));
- ulElem.AppendChild(liElem);
- }
- string xml = ulElem.OuterXml;
TypeScript
jQuery を使った場合
- let months = ['March', 'April', 'May', 'June', 'July'];
- let ul = $('<ul class="months" />');
- $.each(months, (_, s) => ul.append($('<li />').text(s)));
- let xml = $('<x />').append(ul).html();
JavaScript
jQuery を使った場合
- let months = ['March', 'April', 'May', 'June', 'July'];
- let ul = $('<ul class="months" />');
- $.each(months, (_, s) => ul.append($('<li />').text(s)));
- let xml = $('<x />').append(ul).html();
CoffeeScript
jQuery を使った場合
- months = ['March', 'April', 'May', 'June', 'July']
- ul = $('<ul class="months" />')
- for s in months
- ul.append $('<li />').text(s)
- xml = $('<x />').append(ul).html()
Ruby
- array = %w[March April May June July]
- ul = REXML::Element.new 'ul'
- ul.add_attribute 'class', 'months'
- array.each {|s| ul.add_element('li').text = s }
- xml = ul.to_s
DOMなどを使わない場合
- array = %w[March April May June July]
- xml = "<ul class=\"months\">#{ array.collect {|s| "<li>#{s}</li>" } }</ul>"
- array = %w[March April May June July]
- erb = <<~'END'
- <ul class="months">
- <%- for s in array -%>
- <li><%= s %></li>
- <%- end -%>
- </ul>
- END
- xml = ERB.new(erb, trim_mode: '-').result_with_hash(array: array)
XML Builder を使った場合
- array = %w[March April May June July]
- x = Builder::XmlMarkup.new
- xml = x.ul(:class => :months) {
- array.each {|s| x.li s }
- }
Nokogiri を使った場合
- array = %w[March April May June July]
- builder = Nokogiri::XML::Builder.new {
- ul(:class => :months) {
- array.each {|s| li s }
- }
- }
- xml = builder.doc.root.to_xml
Python
- l = ['March', 'April', 'May', 'June', 'July']
- doc = xml.dom.getDOMImplementation().createDocument(None, None, None)
- ulElem = doc.createElement('ul')
- ulElem.setAttribute('class', 'months')
- for s in l:
- liElem = doc.createElement('li')
- liElem.appendChild(doc.createTextNode(s))
- ulElem.appendChild(liElem)
- xml = ulElem.toxml()
PHP
- $array = ['March', 'April', 'May', 'June', 'July'];
- $ulElem = new SimpleXMLElement('<ul />');
- $ulElem->addAttribute('class', 'months');
- foreach ($array as $s) {
- $ulElem->addChild('li', $s);
- }
- $xml = $ulElem->asXML();
- $array = ['March', 'April', 'May', 'June', 'July'];
- $doc = new DOMDocument();
- $ulElem = $doc->createElement('ul');
- $ulElem->setAttribute('class', 'months');
- $doc->appendChild($ulElem);
- foreach ($array as $s) {
- $ulElem->appendChild($doc->createElement('li', $s));
- }
- $xml = $doc->saveXML($ulElem);
Perl
CPAN の
XML::Generator を使った場合
- my @array = qw/March April May June July/;
- my $x = XML::Generator->new;
- my $xml = $x->ul({class => 'months'}, map { $x->li($_) } @array);
CPAN の
XML::DOM を使った場合
- my @array = qw/March April May June July/;
- my $doc = XML::DOM::Document->new;
- my $ulElem = $doc->createElement('ul');
- $ulElem->setAttribute('class', 'months');
- $doc->appendChild($ulElem);
- for (@array) {
- my $liElem = $doc->createElement('li');
- $liElem->appendChild($doc->createTextNode($_));
- $ulElem->appendChild($liElem);
- }
- my $xml = $ulElem->toString;
Java
- public static IntStream fibonacciNumbers() {
- int[] seed = {0, 1};
- Stream<int[]> stream = Stream.iterate(seed, arr -> new int[] {arr[1], arr[0] + arr[1]});
- return stream.mapToInt(arr -> arr[0]);
- }
- for (int n : (Iterable<Integer>) () -> fibonacciNumbers().iterator()) {
- if (n > 20) {
- break;
- }
- System.out.println(n);
- }
Groovy
- def fibonacciNumbers() {
- def seed = [0, 1]
- Stream.iterate(seed) { [it[1], it[0] + it[1]] }.mapToInt { it[0] }
- }
- for (n in ({ fibonacciNumbers().iterator() } as Iterable)) {
- if (n > 20) {
- break
- }
- println(n)
- }
Kotlin
- fun fibonacciNumbers() = generateSequence(Pair(0, 1)) { (x, y) -> Pair(y, x + y) }.map { (x, _) -> x }
- fun fibonacciNumbers() = sequence {
- var x = 0
- var y = 1
- while (true) {
- yield(x)
- x = y.also { y += x }
- }
- }
- fibonacciNumbers().takeWhile { it <= 20 }.forEach(::println)
Scala
- def fibonacciNumbers = {
- def f(i: Int, j: Int): Stream[Int] = i #:: f(j, i + j)
- f(0, 1)
- }
- def fibonacciNumbers = Stream.iterate((0, 1)) { case (i, j) => (j, i + j) }.map { case (i, j) => i }
- fibonacciNumbers.takeWhile(n => n <= 20).foreach(println)
Erlang
- fibonacci_numbers(Func) -> fibonacci_numbers(0, 1, Func).
- fibonacci_numbers(I, J, Func) -> Func(I) andalso fibonacci_numbers(J, I + J, Func).
- fibonacci_numbers(fun(N) ->
- if
- N > 20 -> false;
- true -> io:format("~p~n", [N]), true
- end
- end).
- fibonacci_numbers(fun(N) -> N =< 20 andalso io:format("~p~n", [N]) =:= ok end).
Haskell
- fibonacciNumbers = 0 : 1 : zipWith (+) fibonacciNumbers (tail fibonacciNumbers)
- fibonacciNumbers @(_ : t) = 0 : 1 : zipWith (+) fibonacciNumbers t
- fibonacciNumbers = unfoldr (\ (i, j) -> Just (i, (j, i + j))) (0, 1)
- mapM_ print $ takeWhile (<= 20) fibonacciNumbers
F#
- let fibonacciNumbers() =
- let f (i, j) = Some(i, (j, i + j))
- Seq.unfold f (0, 1)
- let fibonacciNumbers() =
- let rec f i j = seq {
- yield i
- yield! f j (i + j)
- }
- f 0 1
- let fibonacciNumbers() = seq {
- let state = ref (0, 1)
- while true do
- let (i, j) = !state
- yield i
- state := (j, i + j)
- }
- fibonacciNumbers() |> Seq.takeWhile (fun n -> n <= 20) |> Seq.iter (printfn "%d")
- fibonacciNumbers() |> Seq.takeWhile ((>=) 20) |> Seq.iter (printfn "%d")
F# 3.0以降
- Seq.iter (printfn "%d") <| query { for n in fibonacciNumbers() do
- takeWhile (n <= 20) }
C#
- public static IEnumerable<int> FibonacciNumbers() {
- int i = 0;
- int j = 1;
- for (;;) {
- yield return i;
- int tmp = i;
- i = j;
- j += tmp;
- }
- }
- IEnumerable<int> numbers = FibonacciNumbers();
- foreach (int n in numbers) {
- if (n > 20) {
- break;
- }
- Console.WriteLine(n);
- }
Go
- func fibonacciNumbers() <-chan int {
- ch := make(chan int)
- go func() {
- i, j := 0, 1
- for {
- ch <- i
- i, j = j, i + j
- }
- } ()
- return ch
- }
- numbers := fibonacciNumbers()
- for {
- n := <- numbers
- if n > 20 { break }
- fmt.Printf("%d\n", n)
- }
Rust
- pub fn fibonacci_numbers() -> impl Iterator<Item = u32> {
- struct Fibonacci(u32, u32);
- impl Iterator for Fibonacci {
- type Item = u32;
- fn next(&mut self) -> Option<Self::Item> {
- let result = self.0;
- self.0 = self.1;
- self.1 = result + self.1;
- Some(result)
- }
- }
- Fibonacci(0, 1)
- }
- for n in fibonacci_numbers().take_while(|&n| n <= 20) {
- println!("{}", n);
- }
Dart
- class FibonacciIterator implements Iterator<int> {
- var _list = [0, 0, 1];
- get current => _list[0];
- moveNext() {
- _list = [_list[1], _list[2], _list[1] + _list[2]];
- return true;
- }
- }
- class FibonacciIterable with Iterable<int> {
- get iterator => FibonacciIterator();
- }
- var numbers = FibonacciIterable();
- for (var n in numbers) {
- if (n > 20) break;
- print(n);
- }
TypeScript
- function fibonacciNumbers() {
- let [i, j] = [0, 1];
- return () => {
- let tmp = i;
- i = j;
- j += tmp;
- return tmp;
- };
- }
- let numbers = fibonacciNumbers();
- for (let n: number; (n = numbers()) <= 20; ) {
- console.log(n);
- }
- function* fibonacciNumbers() {
- let [i, j] = [0, 1];
- for (;;) {
- yield i;
- [i, j] = [j, i + j];
- }
- }
- for (let n of fibonacciNumbers()) {
- if (n > 20) break;
- console.log(n);
- }
JavaScript
- function fibonacciNumbers() {
- let [i, j] = [0, 1];
- return () => {
- let tmp = i;
- i = j;
- j += tmp;
- return tmp;
- };
- }
- let numbers = fibonacciNumbers();
- for (let n; (n = numbers()) <= 20; ) {
- console.log(n);
- }
- function* fibonacciNumbers() {
- let [i, j] = [0, 1];
- for (;;) {
- yield i;
- [i, j] = [j, i + j];
- }
- }
- for (let n of fibonacciNumbers()) {
- if (n > 20) break;
- console.log(n);
- }
CoffeeScript
- fibonacciNumbers = ->
- [i, j] = [0, 1]
- -> ([_, i, j] = [i, j, i + j])[0]
- numbers = fibonacciNumbers()
- while (n = numbers()) <= 20
- console.log n
- fibonacciNumbers = ->
- [i, j] = [0, 1]
- loop
- yield i
- [i, j] = [j, i + j]
- return
- for n from fibonacciNumbers()
- break if n > 20
- console.log n
Ruby
- class FibonacciNumbers
- include Enumerable
- def each
- i, j = 0, 1
- loop do
- yield i
- i, j = j, i + j
- end
- end
- end
- FibonacciNumbers.new.take_while {|n| n <= 20 }.each {|n| puts n }
- def fibonacci_numbers
- Enumerator.new do |y|
- i, j = 0, 1
- loop do
- y << i
- i, j = j, i + j
- end
- end
- end
- fibonacci_numbers.take_while {|n| n <= 20 }.each {|n| puts n }
- def fibonacci_numbers
- Fiber.new do
- i, j = 0, 1
- loop do
- Fiber.yield i
- i, j = j, i + j
- end
- end
- end
- numbers = fibonacci_numbers
- while (n = numbers.resume) <= 20
- puts n
- end
Ruby 2.7以降
- def fibonacci_numbers
- Enumerator.produce([0, 1]) {|i, j| [j, i + j] }.lazy.collect(&:first)
- end
- fibonacci_numbers.take_while {|n| n <= 20 }.eager.each {|n| puts n }
Python
- def fibonacci_numbers():
- (i, j) = (0, 1)
- while True:
- yield i
- (i, j) = (j, i + j)
- for n in fibonacci_numbers():
- if n > 20:
- break
- print(n)
PHP
- function fibonacci() {
- $arr = [0, 1];
- for (;;) {
- yield $arr[0];
- $arr = [$arr[1], $arr[0] + $arr[1]];
- }
- }
- foreach (fibonacci() as $n) {
- if ($n > 20) break;
- echo $n, "\n";
- }
Perl
- sub fibonacci_numbers {
- my ($i, $j) = (0, 1);
- return sub {
- my $tmp = $i;
- $i = $j;
- $j += $tmp;
- return $tmp;
- };
- }
- my $numbers = fibonacci_numbers();
- while (($_ = $numbers->()) <= 20) {
- print "$_\n";
- }
Scala
- case class Country(code: String, name: String)
- case class City(countryCode: String, code: String, name: String)
- val countries = List(
- Country("JP", "日本"),
- Country("US", "アメリカ"),
- Country("GB", "イギリス")
- )
- val cities = List(
- City("JP", "TYO", "東京"),
- City("US", "WAS", "ワシントンD.C."),
- City("US", "NYC", "ニューヨーク"),
- City("GB", "LON", "ロンドン"),
- City("GB", "BHX", "バーミンガム")
- )
- val result = for (ci <- cities; co @ Country(ci.countryCode, _) <- countries if co.name != "日本")
- yield Map("countryCode" -> co.code, "countryName" -> co.name, "cityCode" -> ci.code, "cityName" -> ci.name)
- result.sort(_("cityCode") < _("cityCode")).foreach(m =>
- println("%s:%s %s:%s".format(m("countryCode"), m("countryName"), m("cityCode"), m("cityName"))))
Erlang
- -record(country, {code, name}).
- -record(city, {country_code, code, name}).
- Countries = [
- #country{code = "JP", name = "日本"},
- #country{code = "US", name = "アメリカ"},
- #country{code = "GB", name = "イギリス"}
- ],
- Cities = [
- #city{country_code = "JP", code = "TYO", name = "東京"},
- #city{country_code = "US", code = "WAS", name = "ワシントンD.C."},
- #city{country_code = "US", code = "NYC", name = "ニューヨーク"},
- #city{country_code = "GB", code = "LON", name = "ロンドン"},
- #city{country_code = "GB", code = "BHX", name = "バーミンガム"}
- ],
- List = [[Co#country.code, Co#country.name, Ci#city.code, Ci#city.name] || Ci <- Cities,
- Co <- Countries,
- Ci#city.country_code =:= Co#country.code,
- Co#country.name =/= "日本"],
- Result = lists:sort(fun([_, _, CityCode1, _], [_, _, CityCode2, _]) -> CityCode1 =< CityCode2 end, List),
- [io:format("~s:~s ~s:~s~n", R) || R <- Result].
Haskell
- data Country = Country String String
- data City = City String String String
- let countries = [Country "JP" "日本",
- Country "US" "アメリカ",
- Country "GB" "イギリス"
- ]
- let cities = [City "JP" "TYO" "東京",
- City "US" "WAS" "ワシントンD.C.",
- City "US" "NYC" "ニューヨーク",
- City "GB" "LON" "ロンドン",
- City "GB" "BHX" "バーミンガム"
- ]
- let result = [(countryCode, countryName, cityCode, cityName)
- |(City countryCode cityCode cityName) <- cities,
- (Country countryCode' countryName) <- countries,
- countryCode == countryCode',
- countryName /= "日本"
- ]
- mapM_ (putStrLn . f) result
- where f (countryCode, countryName, cityCode, cityName) =
- countryCode ++ ":" ++ countryName ++ " " ++ cityCode ++ ":" ++ cityName
F#
- type Country = { Code : string; Name : string }
- type City = { CountryCode : string; Code : string; Name : string }
- let countries = [
- { Country.Code = "JP"; Name = "日本" };
- { Country.Code = "US"; Name = "アメリカ" };
- { Country.Code = "GB"; Name = "イギリス" }
- ]
- let cities = [
- { CountryCode = "JP"; Code = "TYO"; Name = "東京" };
- { CountryCode = "US"; Code = "WAS"; Name = "ワシントンD.C." };
- { CountryCode = "US"; Code = "NYC"; Name = "ニューヨーク" };
- { CountryCode = "GB"; Code = "LON"; Name = "ロンドン" };
- { CountryCode = "GB"; Code = "BHX"; Name = "バーミンガム" }
- ]
- let result = seq {
- for ci in cities do
- for co in countries do
- if ci.CountryCode = co.Code && co.Name <> "日本" then
- yield Map.ofList [("countryCode", co.Code); ("countryName", co.Name); ("cityCode", ci.Code); ("cityName", ci.Name)]
- }
- result |> Seq.sortBy (fun m -> m.["cityCode"])
- |> Seq.iter (fun m -> printfn "%s:%s %s:%s" m.["countryCode"] m.["countryName"] m.["cityCode"] m.["cityName"])
F# 3.0以降
- let result = query {
- for ci in cities do
- join co in countries on (ci.CountryCode = co.Code)
- where (co.Name <> "日本")
- select (Map.ofList [("countryCode", co.Code); ("countryName", co.Name); ("cityCode", ci.Code); ("cityName", ci.Name)])
- }
- query { for m in result do
- sortBy m.["cityCode"]
- select (printfn "%s:%s %s:%s" m.["countryCode"] m.["countryName"] m.["cityCode"] m.["cityName"])
- } |> Seq.iter ignore
C#
- var countries = new[] {
- new {Code = "JP", Name = "日本"},
- new {Code = "US", Name = "アメリカ"},
- new {Code = "GB", Name = "イギリス"},
- };
- var cities = new[] {
- new {CountryCode = "JP", Code = "TYO", Name = "東京"},
- new {CountryCode = "US", Code = "WAS", Name = "ワシントンD.C."},
- new {CountryCode = "US", Code = "NYC", Name = "ニューヨーク"},
- new {CountryCode = "GB", Code = "LON", Name = "ロンドン"},
- new {CountryCode = "GB", Code = "BHX", Name = "バーミンガム"},
- };
- var query = from ci in cities
- join co in countries on ci.CountryCode equals co.Code
- where co.Name != "日本"
- orderby ci.Code
- select new {CountryCode = co.Code, CountryName = co.Name, CityCode = ci.Code, CityName = ci.Name};
- foreach (var r in query) {
- Console.WriteLine($"{r.CountryCode}:{r.CountryName} {r.CityCode}:{r.CityName}");
- }
Ruby
リスト同士の結合を行う方法は用意されていないが、ハッシュを使って実現した例を示す。
- class Country
- attr_reader :code, :name
- def initialize(code, name)
- @code = code
- @name = name
- end
- end
- class City
- attr_reader :country_code, :code, :name
- def initialize(country_code, code, name)
- @country_code = country_code
- @code = code
- @name = name
- end
- end
- countries = [
- Country.new('JP', '日本'),
- Country.new('US', 'アメリカ'),
- Country.new('GB', 'イギリス'),
- ]
- cities = [
- City.new('JP', 'TYO', '東京'),
- City.new('US', 'WAS', 'ワシントンD.C.'),
- City.new('US', 'NYC', 'ニューヨーク'),
- City.new('GB', 'LON', 'ロンドン'),
- City.new('GB', 'BHX', 'バーミンガム'),
- ]
- hash = Hash[*countries.collect {|co| [co.code, co] }.flatten]
- array = cities.collect do |ci|
- {:ci => ci, :co => hash[ci.country_code]}
- end
- array = array.select {|r| r[:co].name != '日本' }.sort_by {|r| r[:ci].code }
- array.collect! do |r|
- {:country_code => r[:co].code, :country_name => r[:co].name, :city_code => r[:ci].code, :city_name => r[:ci].name}
- end
- puts array.collect do |r|
- "#{r[:country_code]}:#{r[:country_name]} #{r[:city_code]}:#{r[:city_name]}"
- end
Python
- class Country:
- def __init__(self, code, name):
- self.code = code
- self.name = name
- class City:
- def __init__(self, country_code, code, name):
- self.country_code = country_code
- self.code = code
- self.name = name
- countries = [
- Country('JP', '日本'),
- Country('US', 'アメリカ'),
- Country('GB', 'イギリス'),
- ]
- cities = [
- City('JP', 'TYO', '東京'),
- City('US', 'WAS', 'ワシントンD.C.'),
- City('US', 'NYC', 'ニューヨーク'),
- City('GB', 'LON', 'ロンドン'),
- City('GB', 'BHX', 'バーミンガム'),
- ]
- result = [
- {'country_code': co.code, 'country_name': co.name, 'city_code': ci.code, 'city_name': ci.name}
- for ci in cities
- for co in countries if ci.country_code == co.code and co.name != '日本'
- ]
- result.sort(key = lambda r: r['city_code'])
- for r in result:
- print('%s:%s %s:%s' % (r['country_code'], r['country_name'], r['city_code'], r['city_name']))
簡略化のため、ジョーカーはないものとして扱う。
Groovy
- enum Suit { CLUB, DIAMOND, HEART, SPADE }
- class IsSequential {
- def isCase(list) {
- def prev = list[0]
- for (i in 1 .. list.size - 1) {
- if (prev + 1 != list[i]) return false
- prev = list[i]
- }
- return true
- }
- }
- def isSequential() {
- new IsSequential()
- }
- class HasPrefix {
- private prefix
- HasPrefix(prefix) {
- this.prefix = prefix
- }
- def isCase(list) {
- for (i in 0 .. prefix.length - 1) {
- if (i >= list.size || list[i] != prefix[i]) return false
- }
- return true
- }
- }
- def hasPrefix(...prefix) {
- new HasPrefix(prefix)
- }
- def checkPokerHand(cards) {
- def suitCount = cards.collect { it[0] }.unique().size
- def numbers = cards.collect { it[1] }.sort()
- if (suitCount == 1) {
- switch (numbers) {
- case isSequential(): return 'Straight Flash'
- case [1, 10, 11, 12, 13]: return 'Royal Straight Flash'
- default: return 'Flash'
- }
- } else {
- switch (numbers) {
- case isSequential(): return 'Straight'
- default:
- def counts = numbers.groupBy { it }.values()*.size.sort().reverse()
- switch (counts) {
- case hasPrefix(4 ): return 'Four of a Kind'
- case hasPrefix(3, 2): return 'Full House'
- case hasPrefix(3 ): return 'Three of a Kind'
- case hasPrefix(2, 2): return 'Two Pair'
- case hasPrefix(2 ): return 'One Pair'
- default: return 'No Pair'
- }
- }
- }
- }
- def result = checkPokerHand([[Suit.CLUB, 8], [Suit.HEART, 8], [Suit.DIAMOND, 8], [Suit.SPADE, 4], [Suit.CLUB, 4]])
Scala
- case object Sequential {
- def apply(numbers: List[Int]): Boolean =
- numbers.sliding(2).forall { case Seq(n0, n1) => n0 + 1 == n1 }
- def unapply(numbers: List[Int]) = apply(numbers)
- }
- def checkPokerHand[Suit](cards: List[(Suit, Int)]) = {
- val suitCount = cards.map(_._1).distinct.length
- val numbers = cards.map(_._2).sorted
- if (suitCount == 1) {
- numbers match {
- case Sequential() => "Straight Flash"
- case List(1, 10, 11, 12, 13) => "Royal Straight Flash"
- case _ => "Flash"
- }
- } else {
- numbers match {
- case Sequential() => "Straight"
- case _ =>
- val counts = numbers.groupBy(identity).values.map(_.length).toList.sortWith(_ > _)
- counts match {
- case 4 :: _ => "Four of a Kind"
- case 3 :: 2 :: _ => "Full House"
- case 3 :: _ => "Three of a Kind"
- case 2 :: 2 :: _ => "Two Pair"
- case 2 :: _ => "One Pair"
- case _ => "No Pair"
- }
- }
- }
- }
- val result = checkPokerHand(List(('club, 8), ('heart, 8), ('diamond, 8), ('spade, 4), ('club, 4)))
Erlang
- count_elements(List) ->
- Fun = fun(Elem, Dict) -> dict:update_counter(Elem, 1, Dict) end,
- lists:foldl(Fun, dict:new(), List).
- is_sequential([N0, N1|T]) -> (N0 + 1 =:= N1) and is_sequential([N1|T]);
- is_sequential(_) -> true.
- check_poker_hand(Cards) ->
- Numbers = lists:sort(lists:map(fun({_, N}) -> N end, Cards)),
- Sequential = is_sequential(Numbers),
- case Cards of
- [{S, _}, {S, _}, {S, _}, {S, _}, {S, _}] ->
- if
- Sequential -> "Straight Flash";
- Numbers =:= [1, 10, 11, 12, 13] -> "Royal Straight Flash";
- true -> "Flash"
- end;
- [{_, _}, {_, _}, {_, _}, {_, _}, {_, _}] ->
- if
- Sequential -> "Straight";
- true ->
- CountList = [Count || {_, Count} <- dict:to_list(count_elements(Numbers))],
- case lists:reverse(lists:sort(CountList)) of
- [4|_] -> "Four of a Kind";
- [3, 2|_] -> "Full House";
- [3|_] -> "Three of a Kind";
- [2, 2|_] -> "Two Pair";
- [2|_] -> "One Pair";
- _ -> "No Pair"
- end
- end
- end.
- Result = check_poker_hand([{club, 8}, {heart, 8}, {diamond, 8}, {spade, 4}, {club, 4}]).
Haskell
GHC 6.10.1以降でビューパターンを使う
- data Suit = Club | Diamond | Heart | Spade deriving (Eq, Ord)
- isSequential (n0 : n1 : t) = (n0 + 1 == n1) && isSequential (n1 : t)
- isSequential _ = True
- checkPokerHand cards =
- case suitCount of
- 1 -> case numbers of
- (isSequential -> True) -> "Straight Flash"
- [1, 10, 11, 12, 13] -> "Royal Straight Flash"
- otherwise -> "Flash"
- _ -> case numbers of
- (isSequential -> True) -> "Straight"
- otherwise -> case counts of
- 4 : _ -> "Four of a Kind"
- 3 : 2 : _ -> "Full House"
- 3 : _ -> "Three of a Kind"
- 2 : 2 : _ -> "Two Pair"
- 2 : _ -> "One Pair"
- _ -> "No Pair"
- where suitCount = length $ nub $ map fst cards
- numbers = sort $ map snd cards
- counts = reverse $ sort $ map length $ group numbers
- let result = checkPokerHand [(Club, 8), (Heart, 8), (Diamond, 8), (Spade, 4), (Club, 4)]
F#
- type Suit = Club | Diamond | Heart | Spade
- let isSequential = Seq.pairwise >> Seq.forall (fun (a, b) -> a + 1 = b)
- let (|Sequential|_|) numbers = if isSequential numbers then Some() else None
- let checkPokerHand cards =
- let suitCount = cards |> Seq.map fst |> Seq.distinct |> Seq.length
- let numbers = cards |> Seq.map snd |> Seq.toList |> List.sort
- if suitCount = 1 then
- match numbers with
- | Sequential -> "Straight Flash"
- | [1; 10; 11; 12; 13] -> "Royal Straight Flash"
- | _ -> "Flash"
- else
- match numbers with
- | Sequential -> "Straight"
- | _ -> let counts = numbers |> Seq.groupBy id |> Seq.map (snd >> Seq.length) |> Seq.toList |> List.sort |> List.rev
- match counts with
- | 4 :: _ -> "Four of a Kind"
- | 3 :: 2 :: _ -> "Full House"
- | 3 :: _ -> "Three of a Kind"
- | 2 :: 2 :: _ -> "Two Pair"
- | 2 :: _ -> "One Pair"
- | _ -> "No Pair"
- let result = checkPokerHand [(Club, 8); (Heart, 8); (Diamond, 8); (Spade, 4); (Club, 4)]
C#
C# 8.0以降
- public enum Suit { Club, Diamond, Heart, Spade }
- public struct Card {
- public Suit Suit { get; set; }
- public int Number { get; set; }
- }
- public static bool IsSequential(this IEnumerable<int> e) {
- var result = true;
- e.Skip(1).Aggregate(e.First(), (prevNum, num) => {
- result &= (prevNum + 1 == num);
- return num;
- });
- return result;
- }
- public static void Deconstruct<T>(this IEnumerable<T> e, out T t0, out T t1) {
- T[] array = e.ToArray();
- t0 = array[0];
- t1 = array[1];
- }
- public static string CheckPokerHand(IEnumerable<Card> cards) {
- var suitCount = cards.Select(c => c.Suit).Distinct().Count();
- var numbers = cards.Select(c => c.Number).OrderBy(n => n);
- if (suitCount == 1) {
- if (numbers.IsSequential()) return "Straight Flash";
- if (numbers.ToArray() == new int[] { 1, 10, 11, 12, 13 }) return "Royal Straight Flash";
- return "Flash";
- } else {
- if (numbers.IsSequential()) return "Straight";
- var counts = numbers.GroupBy(n => n).Select(grp => grp.Count()).OrderByDescending(n => n);
- return counts switch {
- (4, _) => "Four of a Kind",
- (3, 2) => "Full House",
- (3, _) => "Three of a Kind",
- (2, 2) => "Two Pair",
- (2, _) => "One Pair",
- _ => "No Pair"
- };
- }
- }
- var result = CheckPokerHand(new Card[] {
- new Card { Suit = Suit.Club, Number = 8 },
- new Card { Suit = Suit.Heart, Number = 8 },
- new Card { Suit = Suit.Diamond, Number = 8 },
- new Card { Suit = Suit.Spade, Number = 4 },
- new Card { Suit = Suit.Club, Number = 4 }
- });
Ruby
- def sequential?
- -> (array) {
- result = true
- array.inject {|prev_num, num|
- result &= (prev_num + 1 == num)
- num
- }
- result
- }
- end
- def prefix? *prefix
- -> (array) { array.first(prefix.length) == prefix }
- end
- def check_poker_hand cards
- suit_count = cards.collect {|c| c[0] }.uniq.length
- numbers = cards.collect {|c| c[1] }.sort
- if suit_count == 1
- case numbers
- when sequential? ; 'Straight Flash'
- when [1, 10, 11, 12, 13] ; 'Royal Straight Flash'
- else ; 'Flash'
- end
- else
- case numbers
- when sequential? ; 'Straight'
- else
- counts = numbers.group_by(&:to_i).values.collect(&:count).sort.reverse
- case counts
- when prefix?(4) ; 'Four of a Kind'
- when prefix?(3, 2) ; 'Full House'
- when prefix?(3) ; 'Three of a Kind'
- when prefix?(2, 2) ; 'Two Pair'
- when prefix?(2) ; 'One Pair'
- else ; 'No Pair'
- end
- end
- end
- end
- result = check_poker_hand [[:club, 8], [:heart, 8], [:diamond, 8], [:spade, 4], [:club, 4]]
Python
- def pairwise(iterable):
- a, b = itertools.tee(iterable)
- next(b)
- return zip(a, b)
- def is_sequential(iterable):
- for a, b in pairwise(iterable):
- if a + 1 != b:
- return False
- return True
- def has_prefix(iterable, *prefix):
- for a, b in zip(itertools.islice(iterable, 0, len(prefix)), prefix):
- if a != b:
- return False
- return True
- def check_poker_hand(cards):
- suit_count = len(set(c[0] for c in cards))
- numbers = sorted(c[1] for c in cards)
- if suit_count == 1:
- return ('Straight Flash' if is_sequential(numbers)
- else 'Royal Straight Flash' if numbers == [1, 10, 11, 12, 13]
- else 'Flash')
- else:
- if is_sequential(numbers):
- return 'Straight'
- counts = sorted([len(list(g)) for _, g in itertools.groupby(numbers)], reverse = True)
- return ('Four of a Kind' if has_prefix(counts, 4)
- else 'Full House' if has_prefix(counts, 3, 2)
- else 'Three of a Kind' if has_prefix(counts, 3)
- else 'Two Pair' if has_prefix(counts, 2, 2)
- else 'One Pair' if has_prefix(counts, 2)
- else 'No Pair')
- result = check_poker_hand([('club', 8), ('heart', 8), ('diamond', 8), ('spade', 4), ('club', 4)])