What is the mismatch() method in D programming?
Overview
The mismatch() function loops through an array’s elements and compares each of its values with that of another array.
The mismatch() method
-
It is a built-in method in the D language.
-
It is part of the
std.algorithmmodule. -
The
mismatch()method carries out a lockstep comparison of two arrays. -
This comparison ends when the first mismatch is encountered, and both arrays are returned as members of a tuple.
-
The returned arrays will have elements only from the point where the first mismatch was found.
For instance, the mismatch() operation output of arrays A =[1,2,3,4, 5] and B = [1,2,4,6] will be a tuple P = [[3,4,5],[4,6]].
Syntax
mismatch(comparison_conditon, value_a, value_b)
-
comparison_conditon : By default, this parameter is equality. A mismatch is where an element of
value_aandvalue_bat the same index position is not equal. This is an optional parameter. -
value_a : This is one of the values to compare.
-
value_b : This is the second value for comparison.
Return value
It returns a tuple. The value of this tuple is both the compared arrays. The element of this array will be the elements from the point of mismatch in both arrays to the end/last index.
Code
In the code below, the mismatch value between arr_a and arr_b is computed:
import std.algorithm;import std.stdio;void main(){//define variablesint[6] arr_a = [4, 5, 6, 7, 8, 9 ];float[6] arr_b = [ 4, 5, 6, 7.3, 4, 9 ];auto tuple_output = mismatch(arr_a[], arr_b[]);//output the whole tuplewriteln(tuple_output);//output individual member of the tupplewriteln(tuple_output[0]); // arr_a[7 .. $]writeln(tuple_output[1]); // arr_b[7.3.. $]}
Explanation
- Line 1–2: We import the module. The
std.algorithmis the module with themismatch()function. - Line 4: Here, we see the
mainfunction that encloses the whole program. - Line 6–7: These are declared arrays,
arr_aandarr_b, that will be compared. - Line 8: We use the mismatch function and save the output in the auto data type variable,
tuple_output. - Line 11: We print the whole tuple.
- Line 13–14: We print the individual members of the array.