File tree 2 files changed +53
-0
lines changed
2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Hamming Distance: https://en.wikipedia.org/wiki/Hamming_distance
3
+ *
4
+ *
5
+ * Hamming distance is a metric for comparing two binary data strings.
6
+ *
7
+ * While comparing two binary strings of equal length, Hamming distance
8
+ * is the number of bit positions in which the two bits are different.
9
+ * The Hamming distance between two strings, a and b is denoted as d(a,b)
10
+ */
11
+
12
+ /**
13
+ * @param {string } a
14
+ * @param {string } b
15
+ * @return {number }
16
+ */
17
+
18
+ export const hammingDistance = ( a , b ) => {
19
+ if ( a . length !== b . length ) {
20
+ throw new Error ( 'Strings must be of the same length' )
21
+ }
22
+
23
+ let distance = 0
24
+
25
+ for ( let i = 0 ; i < a . length ; i += 1 ) {
26
+ if ( a [ i ] !== b [ i ] ) {
27
+ distance += 1
28
+ }
29
+ }
30
+
31
+ return distance
32
+ }
Original file line number Diff line number Diff line change
1
+ import { hammingDistance } from '../HammingDistance'
2
+
3
+ test ( 'should throw an error when trying to compare the strings of different length' , ( ) => {
4
+ const compareStringsOfDifferentLength = ( ) => {
5
+ hammingDistance ( 'abc' , 'abcd' )
6
+ }
7
+
8
+ expect ( compareStringsOfDifferentLength ) . toThrowError ( )
9
+ } )
10
+
11
+ test ( 'should calculate difference between two strings' , ( ) => {
12
+ expect ( hammingDistance ( 'a' , 'a' ) ) . toBe ( 0 )
13
+ } )
14
+
15
+ test ( 'should calculate difference between two strings' , ( ) => {
16
+ expect ( hammingDistance ( 'abc' , 'add' ) ) . toBe ( 2 )
17
+ } )
18
+
19
+ test ( 'should calculate difference between two strings' , ( ) => {
20
+ expect ( hammingDistance ( '1011101' , '1001001' ) ) . toBe ( 2 )
21
+ } )
You can’t perform that action at this time.
0 commit comments