TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
hamming_distance.cpp
Go to the documentation of this file.
1
14
15
#include <cassert>
16
#include <cstdint>
17
#include <iostream>
18
23
namespace
bit_manipulation
{
29
namespace
hamming_distance
{
35
uint64_t
bitCount
(uint64_t value) {
36
uint64_t count = 0;
37
while
(value) {
// until all bits are zero
38
if
(value & 1) {
// check lower bit
39
count++;
40
}
41
value >>= 1;
// shift bits, removing lower bit
42
}
43
return
count;
44
}
45
52
uint64_t
hamming_distance
(uint64_t a, uint64_t b) {
return
bitCount
(a ^ b); }
53
60
uint64_t
hamming_distance
(
const
std::string& a,
const
std::string& b) {
61
assert(a.size() == b.size());
62
size_t
n = a.size();
63
uint64_t count = 0;
64
for
(
size_t
i = 0; i < n; i++) {
65
count += (b[i] != a[i]);
66
}
67
return
count;
68
}
69
}
// namespace hamming_distance
70
}
// namespace bit_manipulation
71
76
static
void
test
() {
77
assert(
bit_manipulation::hamming_distance::hamming_distance
(11, 2) == 2);
78
assert(
bit_manipulation::hamming_distance::hamming_distance
(2, 0) == 1);
79
assert(
bit_manipulation::hamming_distance::hamming_distance
(11, 0) == 3);
80
81
assert(
bit_manipulation::hamming_distance::hamming_distance
(
"1101"
,
82
"1111"
) == 1);
83
assert(
bit_manipulation::hamming_distance::hamming_distance
(
"1111"
,
84
"1111"
) == 0);
85
assert(
bit_manipulation::hamming_distance::hamming_distance
(
"0000"
,
86
"1111"
) == 4);
87
88
assert(
bit_manipulation::hamming_distance::hamming_distance
(
"alpha"
,
89
"alphb"
) == 1);
90
assert(
bit_manipulation::hamming_distance::hamming_distance
(
"abcd"
,
91
"abcd"
) == 0);
92
assert(
bit_manipulation::hamming_distance::hamming_distance
(
"dcba"
,
93
"abcd"
) == 4);
94
}
95
100
int
main
() {
101
test
();
// execute the tests
102
uint64_t a = 11;
// 1011 in binary
103
uint64_t b = 2;
// 0010 in binary
104
105
std::cout <<
"Hamming distance between "
<< a <<
" and "
<< b <<
" is "
106
<<
bit_manipulation::hamming_distance::hamming_distance
(a, b)
107
<< std::endl;
108
}
bit_manipulation::hamming_distance::bitCount
uint64_t bitCount(uint64_t value)
Definition
hamming_distance.cpp:35
test
static void test()
Function to the test hamming distance.
Definition
hamming_distance.cpp:76
bit_manipulation::hamming_distance::hamming_distance
uint64_t hamming_distance(uint64_t a, uint64_t b)
Definition
hamming_distance.cpp:52
main
int main()
Main function.
Definition
hamming_distance.cpp:100
bit_manipulation
for assert
hamming_distance
Functions for Hamming distance implementation.
bit_manipulation
hamming_distance.cpp
Generated by
1.13.2