chore: import upstream snapshot with attribution
Awesome CI Workflow / Code Formatter (push) Has been cancelled
Awesome CI Workflow / Compile checks (macOS-latest) (push) Has been cancelled
Awesome CI Workflow / Compile checks (ubuntu-latest) (push) Has been cancelled
Awesome CI Workflow / Compile checks (windows-latest) (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 12:37:28 +08:00
commit 29cfe479ab
432 changed files with 68491 additions and 0 deletions
+18
View File
@@ -0,0 +1,18 @@
# If necessary, use the RELATIVE flag, otherwise each source file may be listed
# with full pathname. RELATIVE may makes it easier to extract an executable name
# automatically.
file( GLOB APP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp )
# file( GLOB APP_SOURCES ${CMAKE_SOURCE_DIR}/*.c )
# AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} APP_SOURCES)
foreach( testsourcefile ${APP_SOURCES} )
# I used a simple string replace, to cut off .cpp.
string( REPLACE ".cpp" "" testname ${testsourcefile} )
add_executable( ${testname} ${testsourcefile} )
set_target_properties(${testname} PROPERTIES LINKER_LANGUAGE CXX)
if(OpenMP_CXX_FOUND)
target_link_libraries(${testname} OpenMP::OpenMP_CXX)
endif()
install(TARGETS ${testname} DESTINATION "bin/bit_manipulation")
endforeach( testsourcefile ${APP_SOURCES} )
+93
View File
@@ -0,0 +1,93 @@
/**
* @file
* @brief Implementation to [Check if a number is Even or Odd using Bitwise Operator]
* (https://www.log2base2.com/c-examples/bitwise/odd-or-even-program-in-c-using-bitwise-operator.html)
*
* @details
* Given an integer N, determine whether it is even or odd using bitwise manipulation.
* The least significant bit (LSB) of a binary number determines its parity:
* - If the LSB is 0, the number is even.
* - If the LSB is 1, the number is odd.
*
* This can be checked efficiently using the bitwise AND operator (&) with 1.
* - If (N & 1) == 0, N is even.
* - If (N & 1) == 1, N is odd.
*
* Example:
* Consider 8-bit binary representations of two numbers:
* Number: 10 (decimal) -> 00001010 (binary)
* LSB = 0 -> Even number
*
* Number: 13 (decimal) -> 00001101 (binary)
* LSB = 1 -> Odd number
*
* In both cases, evaluating (N & 1) isolates the LSB:
* - For 10: 00001010 & 00000001 = 0 (Even)
* - For 13: 00001101 & 00000001 = 1 (Odd)
*
* Worst Case Time Complexity: O(1)
* Space Complexity: O(1)
*
* @author [Vedant Mukhedkar](https://github.com/git5v)
*/
#include <cassert> /// for assert
#include <cstdint> /// for uint32_t
#include <iostream> /// for IO operations
#include <string> /// for std::string
/**
* @namespace bit_manipulation
* @brief Bit manipulation algorithms
*/
namespace bit_manipulation {
/**
* @namespace even_odd
* @brief Functions for checking if a number is even or odd using bitwise operations
*/
namespace even_odd {
/**
* @brief Checks if a number is even or odd using bitwise AND.
* @param N The number to check.
* @returns "Even" if N is even, "Odd" if N is odd.
*/
bool is_even(std::int64_t N) {
return (N & 1) == 0 ? true : false;
}
} // namespace even_odd
} // namespace bit_manipulation
/**
* @brief Self-test implementations
* @returns void
*/
static void test() {
using bit_manipulation::even_odd::is_even;
// Test Even numbers
assert(is_even(0) == true);
assert(is_even(2) == true);
assert(is_even(100) == true);
assert(is_even(-4) == true);
assert(is_even(-1000) == true);
// Test Odd numbers
assert(is_even(1) == false);
assert(is_even(3) == false);
assert(is_even(101) == false);
assert(is_even(-5) == false);
assert(is_even(-999) == false);
std::cout << "All test cases successfully passed!" << std::endl;
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); // run self-test implementations
return 0;
}
+89
View File
@@ -0,0 +1,89 @@
/**
* @file
* @brief Implementation to
* [Count number of bits to be flipped to convert A to B]
* (https://www.geeksforgeeks.org/count-number-of-bits-to-be-flipped-to-convert-a-to-b/)
* in an integer.
*
* @details
* We are given two numbers A and B. Our task is to count the number of bits
* needed to be flipped to convert A to B.
*
* Explanation:
*
* A = 01010 B = 10100
* As we can see, the bits of A that need to be flipped are 01010.
* If we flipthese bits, we get 10100, which is B.
*
* Worst Case Time Complexity: O(log n)
* Space complexity: O(1)
* @author [Yash Raj Singh](https://github.com/yashrajyash)
*/
#include <cassert> /// for assert
#include <cstdint>
#include <iostream> /// for IO operations
/**
* @namespace bit_manipulation
* @brief Bit manipulation algorithms
*/
namespace bit_manipulation {
/**
* @namespace count_bits_flip
* @brief Functions for the [count bits
* flip](https://www.geeksforgeeks.org/count-set-bits-in-an-integer/)
* implementation
*/
namespace count_bits_flip {
/**
* @brief The main function implements count of bits flip required
* @param A is the given number whose bits will be flipped to get number B
* @param B is the given target number
* @returns total number of bits needed to be flipped to convert A to B
*/
std::uint64_t countBitsFlip(
std::int64_t A,
std::int64_t B) { // int64_t is preferred over int so that
// no Overflow can be there.
int count =
0; // "count" variable is used to count number of bits flip of the
// number A to form B in binary representation of number 'n'
A = A ^ B;
while (A) {
A = A & (A - 1);
count++;
}
return count;
}
} // namespace count_bits_flip
} // namespace bit_manipulation
/**
* @brief Self-test implementations
* @returns void
*/
static void test() {
// A = 10, B = 20 return 4
assert(bit_manipulation::count_bits_flip::countBitsFlip(10, 20) == 4);
// A = 20, B = 25 return 3
assert(bit_manipulation::count_bits_flip::countBitsFlip(20, 25) == 3);
// A = 7, B = 10 return 3
assert(bit_manipulation::count_bits_flip::countBitsFlip(7, 10) == 3);
// A = 17, B = 25 return 1
assert(bit_manipulation::count_bits_flip::countBitsFlip(17, 25) == 1);
// A = 11, B = 8 return 2
assert(bit_manipulation::count_bits_flip::countBitsFlip(11, 8) == 2);
// A = 21, B = 22 return 2
assert(bit_manipulation::count_bits_flip::countBitsFlip(21, 22) == 2);
// A = 7, B = 786 return 5
assert(bit_manipulation::count_bits_flip::countBitsFlip(7, 786) == 5);
std::cout << "All test cases successfully passed!" << std::endl;
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); // run self-test implementations
return 0;
}
+91
View File
@@ -0,0 +1,91 @@
/**
* @file
* @brief Implementation to [count number of set bits of a number]
* (https://www.geeksforgeeks.org/count-set-bits-in-an-integer/) in an
* integer.
*
* @details
* We are given an integer number. We need to calculate the number of set bits
* in it.
*
* A binary number consists of two digits. They are 0 & 1. Digit 1 is known as
* set bit in computer terms.
* Worst Case Time Complexity: O(log n)
* Space complexity: O(1)
* @author [Swastika Gupta](https://github.com/Swastyy)
* @author [Prashant Thakur](https://github.com/prashant-th18)
*/
#include <cassert> /// for assert
#include <cstdint>
#include <iostream> /// for IO operations
/**
* @namespace bit_manipulation
* @brief Bit manipulation algorithms
*/
namespace bit_manipulation {
/**
* @namespace count_of_set_bits
* @brief Functions for the [count sets
* bits](https://www.geeksforgeeks.org/count-set-bits-in-an-integer/)
* implementation
*/
namespace count_of_set_bits {
/**
* @brief The main function implements set bit count
* @param n is the number whose set bit will be counted
* @returns total number of set-bits in the binary representation of number `n`
*/
std::uint64_t countSetBits(
std ::uint64_t n) { // uint64_t is preferred over int so that
// no Overflow can be there.
//It's preferred over int64_t because it Guarantees that inputs are always non-negative,
//which matches the algorithmic problem statement.
//set bit counting is conceptually defined only for non-negative numbers.
//Provides a type Safety: Using an unsigned type helps prevent accidental negative values,
std::uint64_t count = 0; // "count" variable is used to count number of set-bits('1')
// in binary representation of number 'n'
//Count is uint64_t because it Prevents theoretical overflow if someone passes very large integers.
// Behavior stays the same for all normal inputs.
// Safer for edge cases.
while (n != 0) {
++count;
n = (n & (n - 1));
}
return count;
// Why this algorithm is better than the standard one?
// Because this algorithm runs the same number of times as the number of
// set-bits in it. Means if my number is having "3" set bits, then this
// while loop will run only "3" times!!
}
} // namespace count_of_set_bits
} // namespace bit_manipulation
static void test() {
// n = 4 return 1
assert(bit_manipulation::count_of_set_bits::countSetBits(4) == 1);
// n = 6 return 2
assert(bit_manipulation::count_of_set_bits::countSetBits(6) == 2);
// n = 13 return 3
assert(bit_manipulation::count_of_set_bits::countSetBits(13) == 3);
// n = 9 return 2
assert(bit_manipulation::count_of_set_bits::countSetBits(9) == 2);
// n = 15 return 4
assert(bit_manipulation::count_of_set_bits::countSetBits(15) == 4);
// n = 25 return 3
assert(bit_manipulation::count_of_set_bits::countSetBits(25) == 3);
// n = 97 return 3
assert(bit_manipulation::count_of_set_bits::countSetBits(97) == 3);
// n = 31 return 5
assert(bit_manipulation::count_of_set_bits::countSetBits(31) == 5);
std::cout << "All test cases successfully passed!" << std::endl;
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); // run self-test implementations
return 0;
}
@@ -0,0 +1,99 @@
/**
* @file
* @brief [Count the number of
* ciphers](https://www.tutorialspoint.com/count-trailing-zeros-in-factorial-of-a-number-in-cplusplus) in `n!` implementation
* @details
* Given an integer number as input. The goal is to find the number of trailing
zeroes in the factorial calculated for
* that number. A factorial of a number N is a product of all numbers in the
range [1, N].
* We know that we get a trailing zero only if the number is multiple of 10 or
has a factor pair (2,5). In all factorials of
* any number greater than 5, we have many 2s more than 5s in the prime
factorization of that number. Dividing a
* number by powers of 5 will give us the count of 5s in its factors. So, the
number of 5s will tell us the number of trailing zeroes.
* @author [Swastika Gupta](https://github.com/Swastyy)
*/
#include <cassert> /// for assert
#include <cstdint>
#include <iostream> /// for IO operations
/**
* @namespace bit_manipulation
* @brief Bit manipulation algorithms
*/
namespace bit_manipulation {
/**
* @namespace count_of_trailing_ciphers_in_factorial_n
* @brief Functions for the [Count the number of
* ciphers](https://www.tutorialspoint.com/count-trailing-zeros-in-factorial-of-a-number-in-cplusplus)
* in `n!` implementation
*/
namespace count_of_trailing_ciphers_in_factorial_n {
/**
* @brief Function to count the number of the trailing ciphers
* @param n number for which `n!` ciphers are returned
* @return count, Number of ciphers in `n!`.
*/
uint64_t numberOfCiphersInFactorialN(uint64_t n) {
// count is to store the number of 5's in factorial(n)
uint64_t count = 0;
// Keep dividing n by powers of
// 5 and update count
for (uint64_t i = 5; n / i >= 1; i *= 5) {
count += static_cast<uint64_t>(n) / i;
}
return count;
}
} // namespace count_of_trailing_ciphers_in_factorial_n
} // namespace bit_manipulation
/**
* @brief Self-test implementations
* @returns void
*/
static void test() {
// 1st test
std::cout << "1st test ";
assert(bit_manipulation::count_of_trailing_ciphers_in_factorial_n::
numberOfCiphersInFactorialN(395) == 97);
std::cout << "passed" << std::endl;
// 2nd test
std::cout << "2nd test ";
assert(bit_manipulation::count_of_trailing_ciphers_in_factorial_n::
numberOfCiphersInFactorialN(977) == 242);
std::cout << "passed" << std::endl;
// 3rd test
std::cout << "3rd test ";
assert(bit_manipulation::count_of_trailing_ciphers_in_factorial_n::
numberOfCiphersInFactorialN(871) == 215);
std::cout << "passed" << std::endl;
// 4th test
std::cout << "4th test ";
assert(bit_manipulation::count_of_trailing_ciphers_in_factorial_n::
numberOfCiphersInFactorialN(239) == 57);
std::cout << "passed" << std::endl;
// 5th test
std::cout << "5th test ";
assert(bit_manipulation::count_of_trailing_ciphers_in_factorial_n::
numberOfCiphersInFactorialN(0) == 0);
std::cout << "passed" << std::endl;
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); // run self-test implementations
return 0;
}
@@ -0,0 +1,88 @@
/**
* @file
* @brief Implementation to find the non repeating integer
* in an array of repeating integers. [Single
* Number](https://leetcode.com/problems/single-number/)
*
* @details
* Given an array of integers in which all of the numbers occur exactly
* twice except one integer which occurs only once. Find the non-repeating
* integer.
*
* Worst Case Time Complexity: O(n)
* Space complexity: O(1)
* @author [Ravidev Pandey](https://github.com/literalEval)
*/
#include <cassert> /// for assert
#include <iostream> /// for IO operations
#include <vector> /// storing the numbers
/**
* @namespace bit_manipulation
* @brief Bit manipulation algorithms
*/
namespace bit_manipulation {
/**
* @namespace find_non_repeating_integer
* @brief Functions to find the non repeating integer
* in an array of repeating integers. [Single
* Number](https://leetcode.com/problems/single-number/)
*/
namespace find_non_repeating_integer {
/**
* @brief The main function implements find single number
* @param nums vector of integers
* @returns returns the integer that occurs only once
*/
int64_t find_non_repeating_integer(const std::vector<int>& nums) {
// The idea is based on the property of XOR.
// We know that 'a' XOR 'a' is '0' and '0' XOR 'b'
// is b.
// Using this, if we XOR all the elements of the array,
// the repeating elements will give '0' and this '0'
// with the single number will give the number itself.
int _xor = 0;
for (const int& num: nums) {
_xor ^= num;
}
return _xor;
}
} // namespace find_non_repeating_integer
} // namespace bit_manipulation
/**
* @brief Self-test implementations
* @returns void
*/
static void test() {
// n = 10,2 return 14
std::vector<int> nums_one{1, 1, 2, 2, 4, 5, 5};
std::vector<int> nums_two{203, 3434, 4545, 3434, 4545};
std::vector<int> nums_three{90, 1, 3, 90, 3};
assert(bit_manipulation::find_non_repeating_integer::
find_non_repeating_integer(nums_one) ==
4); // 4 is non repeating
assert(bit_manipulation::find_non_repeating_integer::
find_non_repeating_integer(nums_two) ==
203); // 203 is non repeating
assert(bit_manipulation::find_non_repeating_integer::
find_non_repeating_integer(nums_three) ==
1); // 1 is non repeating
std::cout << "All test cases successfully passed!" << std::endl;
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); // run self-test implementations
return 0;
}
+113
View File
@@ -0,0 +1,113 @@
/**
* @brief Program to generate n-bit [Gray
* code](https://en.wikipedia.org/wiki/Gray_code)
*
* @details
* Gray code is a binary numeral system
* where consecutive values differ in exactly 1 bit.
* The following code offers one of many possible Gray codes
* given some pre-determined number of bits.
*/
#include <bitset> /// for gray code representation
#include <cassert> /// for assert
#include <iostream> /// for IO operations
#include <vector> /// for vector data structure
/**
* @namespace bit_manipulation
* @brief Bit manipulation algorithms
*/
namespace bit_manipulation {
/**
* @namespace gray_code
* @brief Generate n-bit Gray code
*/
namespace gray_code {
/**
* @brief The main function to generate n-bit Gray code
*
* @param n Number of bits
* @return A vector that stores the n-bit Gray code
*/
std::vector<std::bitset<32>> gray_code_generation(int n) {
std::vector<std::bitset<32>> gray_code = {}; // Initialise empty vector
// No Gray codes for non-positive values of n
if (n <= 0) {
return gray_code;
}
int total_codes = 1 << n; // Number of n-bit gray codes
for (int i = 0; i < total_codes; i++) {
int gray_num = i ^ (i >> 1); // Gray code formula
gray_code.push_back(std::bitset<32>(gray_num)); // Store the value
}
return gray_code;
}
} // namespace gray_code
} // namespace bit_manipulation
/**
* @brief Self-test implementation
*
* @returns void
*/
static void test() {
std::vector<std::bitset<32>> gray_code_negative_1 = {};
std::vector<std::bitset<32>> gray_code_0 = {};
std::vector<std::bitset<32>> gray_code_1 = {
std::bitset<32>(0), std::bitset<32>(1)
};
std::vector<std::bitset<32>> gray_code_2 = {
std::bitset<32>(0), std::bitset<32>(1), std::bitset<32>(3), std::bitset<32>(2)
};
std::vector<std::bitset<32>> gray_code_3 = {
std::bitset<32>(0), std::bitset<32>(1), std::bitset<32>(3), std::bitset<32>(2),
std::bitset<32>(6), std::bitset<32>(7), std::bitset<32>(5), std::bitset<32>(4)
};
std::vector<std::bitset<32>> gray_code_4 = {
std::bitset<32>(0), std::bitset<32>(1), std::bitset<32>(3), std::bitset<32>(2),
std::bitset<32>(6), std::bitset<32>(7), std::bitset<32>(5), std::bitset<32>(4),
std::bitset<32>(12), std::bitset<32>(13), std::bitset<32>(15), std::bitset<32>(14),
std::bitset<32>(10), std::bitset<32>(11), std::bitset<32>(9), std::bitset<32>(8)
};
std::vector<std::bitset<32>> gray_code_5 = {
std::bitset<32>(0), std::bitset<32>(1), std::bitset<32>(3), std::bitset<32>(2),
std::bitset<32>(6), std::bitset<32>(7), std::bitset<32>(5), std::bitset<32>(4),
std::bitset<32>(12), std::bitset<32>(13), std::bitset<32>(15), std::bitset<32>(14),
std::bitset<32>(10), std::bitset<32>(11), std::bitset<32>(9), std::bitset<32>(8),
std::bitset<32>(24), std::bitset<32>(25), std::bitset<32>(27), std::bitset<32>(26),
std::bitset<32>(30), std::bitset<32>(31), std::bitset<32>(29), std::bitset<32>(28),
std::bitset<32>(20), std::bitset<32>(21), std::bitset<32>(23), std::bitset<32>(22),
std::bitset<32>(18), std::bitset<32>(19), std::bitset<32>(17), std::bitset<32>(16)
};
// invalid values for n
assert(bit_manipulation::gray_code::gray_code_generation(-1) == gray_code_negative_1);
assert(bit_manipulation::gray_code::gray_code_generation(0) == gray_code_0);
// valid values for n
assert(bit_manipulation::gray_code::gray_code_generation(1) == gray_code_1);
assert(bit_manipulation::gray_code::gray_code_generation(2) == gray_code_2);
assert(bit_manipulation::gray_code::gray_code_generation(3) == gray_code_3);
assert(bit_manipulation::gray_code::gray_code_generation(4) == gray_code_4);
assert(bit_manipulation::gray_code::gray_code_generation(5) == gray_code_5);
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); //Run self-test implementation
return 0;
}
+108
View File
@@ -0,0 +1,108 @@
/**
* @file
* @brief Returns the [Hamming
* distance](https://en.wikipedia.org/wiki/Hamming_distance) between two
* integers
*
* @details
* To find hamming distance between two integers, we take their xor, which will
* have a set bit iff those bits differ in the two numbers.
* Hence, we return the number of such set bits.
*
* @author [Ravishankar Joshi](https://github.com/ravibitsgoa)
*/
#include <cassert> /// for assert
#include <cstdint>
#include <iostream> /// for io operations
/**
* @namespace bit_manipulation
* @brief Bit Manipulation algorithms
*/
namespace bit_manipulation {
/**
* @namespace hamming_distance
* @brief Functions for [Hamming
* distance](https://en.wikipedia.org/wiki/Hamming_distance) implementation
*/
namespace hamming_distance {
/**
* This function returns the number of set bits in the given number.
* @param value the number of which we want to count the number of set bits.
* @returns the number of set bits in the given number.
*/
uint64_t bitCount(uint64_t value) {
uint64_t count = 0;
while (value) { // until all bits are zero
if (value & 1) { // check lower bit
count++;
}
value >>= 1; // shift bits, removing lower bit
}
return count;
}
/**
* This function returns the hamming distance between two integers.
* @param a the first number
* @param b the second number
* @returns the number of bits differing between the two integers.
*/
uint64_t hamming_distance(uint64_t a, uint64_t b) { return bitCount(a ^ b); }
/**
* This function returns the hamming distance between two strings.
* @param a the first string
* @param b the second string
* @returns the number of characters differing between the two strings.
*/
uint64_t hamming_distance(const std::string& a, const std::string& b) {
assert(a.size() == b.size());
size_t n = a.size();
uint64_t count = 0;
for (size_t i = 0; i < n; i++) {
count += (b[i] != a[i]);
}
return count;
}
} // namespace hamming_distance
} // namespace bit_manipulation
/**
* @brief Function to the test hamming distance.
* @returns void
*/
static void test() {
assert(bit_manipulation::hamming_distance::hamming_distance(11, 2) == 2);
assert(bit_manipulation::hamming_distance::hamming_distance(2, 0) == 1);
assert(bit_manipulation::hamming_distance::hamming_distance(11, 0) == 3);
assert(bit_manipulation::hamming_distance::hamming_distance("1101",
"1111") == 1);
assert(bit_manipulation::hamming_distance::hamming_distance("1111",
"1111") == 0);
assert(bit_manipulation::hamming_distance::hamming_distance("0000",
"1111") == 4);
assert(bit_manipulation::hamming_distance::hamming_distance("alpha",
"alphb") == 1);
assert(bit_manipulation::hamming_distance::hamming_distance("abcd",
"abcd") == 0);
assert(bit_manipulation::hamming_distance::hamming_distance("dcba",
"abcd") == 4);
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); // execute the tests
uint64_t a = 11; // 1011 in binary
uint64_t b = 2; // 0010 in binary
std::cout << "Hamming distance between " << a << " and " << b << " is "
<< bit_manipulation::hamming_distance::hamming_distance(a, b)
<< std::endl;
}
@@ -0,0 +1,101 @@
/**
* @file
* @brief [Next higher number with same number of set bits]
* (https://www.geeksforgeeks.org/next-higher-number-with-same-number-of-set-bits/)
* implementation
*
* @details
* Given a number x, find next number with same number of 1 bits in its binary
* representation. For example, consider x = 12, whose binary representation is
* 1100 (excluding leading zeros on 32 bit machine). It contains two logic 1
* bits. The next higher number with two logic 1 bits is 17 (100012).
*
* A binary number consists of two digits. They are 0 & 1. Digit 1 is known as
* set bit in computer terms.
* @author [Kunal Nayak](https://github.com/Kunal766)
*/
#include <cassert> /// for assert
#include <cstdint>
#include <iostream> /// for IO operations
/**
* @namespace bit_manipulation
* @brief Bit manipulation algorithms
*/
namespace bit_manipulation {
/**
* @brief The main function implements checking the next number
* @param x the number that will be calculated
* @returns a number
*/
uint64_t next_higher_number(uint64_t x) {
uint64_t rightOne = 0;
uint64_t nextHigherOneBit = 0;
uint64_t rightOnesPattern = 0;
uint64_t next = 0;
if (x) {
// right most set bit
rightOne = x & -static_cast<signed>(x);
// reset the pattern and set next higher bit
// left part of x will be here
nextHigherOneBit = x + rightOne;
// nextHigherOneBit is now part [D] of the above explanation.
// isolate the pattern
rightOnesPattern = x ^ nextHigherOneBit;
// right adjust pattern
rightOnesPattern = (rightOnesPattern) / rightOne;
// correction factor
rightOnesPattern >>= 2;
// rightOnesPattern is now part [A] of the above explanation.
// integrate new pattern (Add [D] and [A])
next = nextHigherOneBit | rightOnesPattern;
}
return next;
}
} // namespace bit_manipulation
/**
* @brief Self-test implementations
* @returns void
*/
static void test() {
// x = 4 return 8
assert(bit_manipulation::next_higher_number(4) == 8);
// x = 6 return 9
assert(bit_manipulation::next_higher_number(6) == 9);
// x = 13 return 14
assert(bit_manipulation::next_higher_number(13) == 14);
// x = 64 return 128
assert(bit_manipulation::next_higher_number(64) == 128);
// x = 15 return 23
assert(bit_manipulation::next_higher_number(15) == 23);
// x= 32 return 64
assert(bit_manipulation::next_higher_number(32) == 64);
// x = 97 return 98
assert(bit_manipulation::next_higher_number(97) == 98);
// x = 1024 return 2048
assert(bit_manipulation::next_higher_number(1024) == 2048);
std::cout << "All test cases have successfully passed!" << std::endl;
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); // run self-test implementations
return 0;
}
+75
View File
@@ -0,0 +1,75 @@
/**
* @file
* @brief [Find whether a given number is power of 2]
* (https://www.geeksforgeeks.org/program-to-find-whether-a-given-number-is-power-of-2/)
* implementation
*
* @details
* We are given a positive integer number. We need to check whether the number
* is power of 2 or not.
*
* A binary number consists of two digits. They are 0 & 1. Digit 1 is known as
* set bit in computer terms.
* Worst Case Time Complexity: O(1)
* Space complexity: O(1)
* @author [Prafful Gupta](https://github.com/EcstaticPG-25811)
*/
#include <cassert> /// for assert
#include <cstdint>
#include <iostream> /// for IO operations
/**
* @namespace bit_manipulation
* @brief Bit manipulation algorithms
*/
namespace bit_manipulation {
/**
* @brief The main function implements check for power of 2
* @param n is the number who will be checked
* @returns either true or false
*/
bool isPowerOfTwo(std ::int64_t n) { // int64_t is preferred over int so that
// no Overflow can be there.
return n > 0 && !(n & n - 1); // If we subtract a power of 2 numbers by 1
// then all unset bits after the only set bit become set; and the set bit
// becomes unset.
// If a number n is a power of 2 then bitwise and of n-1 and n will be zero.
// The expression n&(n-1) will not work when n is 0.
// To handle this case also, our expression will become n& (!n&(n-1))
}
} // namespace bit_manipulation
/**
* @brief Self-test implementations
* @returns void
*/
static void test() {
// n = 4 return true
assert(bit_manipulation::isPowerOfTwo(4) == true);
// n = 6 return false
assert(bit_manipulation::isPowerOfTwo(6) == false);
// n = 13 return false
assert(bit_manipulation::isPowerOfTwo(13) == false);
// n = 64 return true
assert(bit_manipulation::isPowerOfTwo(64) == true);
// n = 15 return false
assert(bit_manipulation::isPowerOfTwo(15) == false);
// n = 32 return true
assert(bit_manipulation::isPowerOfTwo(32) == true);
// n = 97 return false
assert(bit_manipulation::isPowerOfTwo(97) == false);
// n = 1024 return true
assert(bit_manipulation::isPowerOfTwo(1024) == true);
std::cout << "All test cases successfully passed!" << std::endl;
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); // run self-test implementations
return 0;
}
+80
View File
@@ -0,0 +1,80 @@
/**
* @file
* @brief Implementation to [From the right, set the Kth bit in the binary
* representation of N]
* (https://practice.geeksforgeeks.org/problems/set-kth-bit3724/1/) in an
* integer.
*
* @details
* Given a number N and a value K. From the right, set the Kth bit in the binary
* representation of N. The position of Least Significant Bit(or last bit) is 0,
* the second last bit is 1 and so on. in it.
*
* A binary number consists of two digits. They are 0 & 1. Digit 1 is known as
* set bit in computer terms.
* Worst Case Time Complexity: O(1)
* Space complexity: O(1)
* @author [Aman Raj](https://github.com/aman2000raj)
*/
#include <cassert> /// for assert
#include <cstdint>
#include <iostream> /// for IO operations
/**
* @namespace bit_manipulation
* @brief Bit manipulation algorithms
*/
namespace bit_manipulation {
/**
* @namespace setKthBit
* @brief Functions for the [From the right, set the Kth bit in the binary
* representation of N]
* (https://practice.geeksforgeeks.org/problems/set-kth-bit3724/1/)
* implementation
*/
namespace set_kth_bit {
/**
* @brief The main function implements set kth bit
* @param N is the number whose kth bit will be set
* @returns returns an integer after setting the K'th bit in N
*/
std::uint64_t setKthBit(std ::int64_t N,
std ::int64_t k) { // int64_t is preferred over int so
// that no Overflow can be there.
int pos =
1 << k; // "pos" variable is used to store 1 at kth postion and
// rest bits are 0. in binary representation of number 'n'
return N | pos; // by taking or with the pos and the N we set the bit of N
// at kth position.
}
} // namespace set_kth_bit
} // namespace bit_manipulation
/**
* @brief Self-test implementations
* @returns void
*/
static void test() {
// n = 10,2 return 14
assert(bit_manipulation::set_kth_bit::setKthBit(10, 2) == 14);
// n = 25,1 return 27
assert(bit_manipulation::set_kth_bit::setKthBit(25, 1) == 27);
// n = 400001,5 return 400033
assert(bit_manipulation::set_kth_bit::setKthBit(400001, 5) == 400033);
// n = 123 return 123
assert(bit_manipulation::set_kth_bit::setKthBit(123, 3) == 123);
std::cout << "All test cases successfully passed!" << std::endl;
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); // run self-test implementations
return 0;
}
@@ -0,0 +1,142 @@
/**
* @file
* @brief Implementation to
* [Travelling Salesman problem using bit-masking]
* (https://www.geeksforgeeks.org/travelling-salesman-problem-set-1/)
*
* @details
* Given the distance/cost(as and adjacency matrix) between each city/node to
* the other city/node , the problem is to find the shortest possible route that
* visits every city exactly once and returns to the starting point or we can
* say the minimum cost of whole tour.
*
* Explanation:
* INPUT -> You are given with a adjacency matrix A = {} which contains the
* distance between two cities/node.
*
* OUTPUT -> Minimum cost of whole tour from starting point
*
* Worst Case Time Complexity: O(n^2 * 2^n)
* Space complexity: O(n)
* @author [Utkarsh Yadav](https://github.com/Rytnix)
*/
#include <algorithm> /// for std::min
#include <cassert> /// for assert
#include <cstdint>
#include <iostream> /// for IO operations
#include <limits> /// for limits of integral types
#include <vector> /// for std::vector
/**
* @namespace bit_manipulation
* @brief Bit manipulation algorithms
*/
namespace bit_manipulation {
/**
* @namespace travellingSalesman_bitmanipulation
* @brief Functions for the [Travelling Salesman
* Bitmask](https://www.geeksforgeeks.org/travelling-salesman-problem-set-1/)
* implementation
*/
namespace travelling_salesman_using_bit_manipulation {
/**
* @brief The function implements travellingSalesman using bitmanipulation
* @param dist is the cost to reach between two cities/nodes
* @param setOfCitites represents the city in bit form.\
* @param city is taken to track the current city movement.
* @param n is the no of citys .
* @param dp vector is used to keep a record of state to avoid the
* recomputation.
* @returns minimum cost of traversing whole nodes/cities from starting point
* back to starting point
*/
std::uint64_t travelling_salesman_using_bit_manipulation(
std::vector<std::vector<uint32_t>>
dist, // dist is the adjacency matrix containing the distance.
// setOfCities as a bit represent the cities/nodes. Ex: if
// setOfCities = 2 => 0010(in binary) means representing the
// city/node B if city/nodes are represented as D->C->B->A.
std::uint64_t setOfCities,
std::uint64_t city, // city is taken to track our current city/node
// movement,where we are currently.
std::uint64_t n, // n is the no of cities we have.
std::vector<std::vector<uint32_t>>
&dp) // dp is taken to memorize the state to avoid recomputition
{
// base case;
if (setOfCities == (1 << n) - 1) { // we have covered all the cities
return dist[city][0]; // return the cost from the current city to the
// original city.
}
if (dp[setOfCities][city] != -1) {
return dp[setOfCities][city];
}
// otherwise try all possible options
uint64_t ans = 2147483647;
for (int choice = 0; choice < n; choice++) {
// check if the city is visited or not.
if ((setOfCities & (1 << choice)) ==
0) { // this means that this perticular city is not visited.
std::uint64_t subProb =
dist[city][choice] +
travelling_salesman_using_bit_manipulation(
dist, setOfCities | (1 << choice), choice, n, dp);
// Here we are doing a recursive call to tsp with the updated set of
// city/node and choice which tells that where we are currently.
ans = std::min(ans, subProb);
}
}
dp[setOfCities][city] = ans;
return ans;
}
} // namespace travelling_salesman_using_bit_manipulation
} // namespace bit_manipulation
/**
* @brief Self-test implementations
* @returns void
*/
static void test() {
// 1st test-case
std::vector<std::vector<uint32_t>> dist = {
{0, 20, 42, 35}, {20, 0, 30, 34}, {42, 30, 0, 12}, {35, 34, 12, 0}};
uint32_t V = dist.size();
std::vector<std::vector<uint32_t>> dp(1 << V, std::vector<uint32_t>(V, -1));
assert(bit_manipulation::travelling_salesman_using_bit_manipulation::
travelling_salesman_using_bit_manipulation(dist, 1, 0, V, dp) ==
97);
std::cout << "1st test-case: passed!"
<< "\n";
// 2nd test-case
dist = {{0, 5, 10, 15}, {5, 0, 20, 30}, {10, 20, 0, 35}, {15, 30, 35, 0}};
V = dist.size();
std::vector<std::vector<uint32_t>> dp1(1 << V,
std::vector<uint32_t>(V, -1));
assert(bit_manipulation::travelling_salesman_using_bit_manipulation::
travelling_salesman_using_bit_manipulation(dist, 1, 0, V, dp1) ==
75);
std::cout << "2nd test-case: passed!"
<< "\n";
// 3rd test-case
dist = {{0, 10, 15, 20}, {10, 0, 35, 25}, {15, 35, 0, 30}, {20, 25, 30, 0}};
V = dist.size();
std::vector<std::vector<uint32_t>> dp2(1 << V,
std::vector<uint32_t>(V, -1));
assert(bit_manipulation::travelling_salesman_using_bit_manipulation::
travelling_salesman_using_bit_manipulation(dist, 1, 0, V, dp2) ==
80);
std::cout << "3rd test-case: passed!"
<< "\n";
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); // run self-test implementations
return 0;
}