What is the group() method in D language?
Overview
The group() method will scan through an array of values and return an array of tuples that contains all consecutively placed unique characters in the scanned array and their number of appearances in the scanned array.
For example, the grouping of the array A = [3, 5, 5, 4, 5] will return something like this [(3,1), (5,2), (4,1), (5,1)], effectively grouping each consecutively recurring number with the count of its occurrences in A.
Syntax
group(predicate, array_to_group)
Parameters
Following parameters are required by the group() method.
-
predicate: An optional parameter. It is a binary predicate used to determine the equivalence of two elements. It has a default value ofa==b. D language has a special way of writing predicates, so we have to clearly understand how this is done to change the default to custom. -
array_to_group: This is the array whose elements are to be grouped.
Example
import std.algorithm.iteration;import std.stdio;void main() {//declare an array valueint[] arr = [ 1, 2, 2, 2, 2, 3, 4, 4, 4, 5 ];//print to screen the group of some valueswriteln(group([2,4,4,4,5]));//print to screen the group of array "arr"writeln(group(arr));}
Explanation
- Lines 1–2: We import the necessary module.
- Line 4: We start the main wrapper function.
- Line 6: We declare an array
arrand assign values to it. - Line 9: We print the group of some values to the screen.
- Line 12: We print to screen the group of array
arr.