id
int64 0
877k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
66
| repo_stars
int64 94
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 11
values | repo_extraction_date
stringclasses 197
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
10,095
|
problem_026.cpp
|
OpenGenus_cosmos/code/online_challenges/src/project_euler/problem_026/problem_026.cpp
|
#include <iostream>
#include <vector>
int main()
{
int remainder, value, position, sequenceLength = 0;
for (int i = 1000; i > 0; --i)
{
std::vector<int> cycleCheckArray;
for (int j = 0; j < i; ++j)
cycleCheckArray.push_back(0);
remainder = 1, value = 1, position = 0;
while (true)
{
value = remainder * 10;
remainder = value % i;
if (cycleCheckArray[remainder])
{
sequenceLength = position - cycleCheckArray[remainder];
break;
}
cycleCheckArray[remainder] = position;
++position;
}
if (sequenceLength == i - 1)
std::cout << i << "\n";
}
return 0;
}
| 772
|
C++
|
.cpp
| 28
| 18.607143
| 71
| 0.497965
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,096
|
problem_017.cpp
|
OpenGenus_cosmos/code/online_challenges/src/project_euler/problem_017/problem_017.cpp
|
#include <bits/stdc++.h>
using namespace std;
int num_letters_func(int n)
{
int num_letters[91];
num_letters[1] = 3;
num_letters[2] = 3;
num_letters[3] = 5;
num_letters[4] = 4;
num_letters[5] = 4;
num_letters[6] = 3;
num_letters[7] = 5;
num_letters[8] = 5;
num_letters[9] = 4;
num_letters[10] = 3;
num_letters[11] = 6;
num_letters[12] = 6;
num_letters[13] = 8;
num_letters[14] = 8;
num_letters[15] = 7;
num_letters[16] = 7;
num_letters[17] = 9;
num_letters[18] = 8;
num_letters[19] = 8;
num_letters[20] = 6;
num_letters[30] = 6;
num_letters[40] = 5;
num_letters[50] = 5;
num_letters[60] = 5;
num_letters[70] = 7;
num_letters[80] = 6;
num_letters[90] = 6;
if(n <= 19)
{
return num_letters[n];
}
else if(n <= 99)
{
int first = n / 10, second = n % 10;
int ret = num_letters[first * 10];
if(second != 0)
{
ret += num_letters[second];
}
return ret;
}
else if(n <= 999)
{
int first = n / 100;
int ret = num_letters[first] + 7;
if(n % 100 == 0)
{
return ret;
}
else
{
return ret + 3 + num_letters_func(n % 100);
}
}
else
{
// if n = 1000
return 11;
}
}
int main()
{
int n = 1000;
int ans = 0;
for(int i = 1; i <= n; i++)
{
ans += num_letters_func(i);
}
cout << ans;
}
| 1,530
|
C++
|
.cpp
| 75
| 14.493333
| 55
| 0.475568
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,098
|
problem_037.cpp
|
OpenGenus_cosmos/code/online_challenges/src/project_euler/problem_037/problem_037.cpp
|
#include <array>
#include <cmath>
#include <iostream>
template<std::size_t N>
std::array<bool, N> primesUpto() // Function that implements the Sieve of Eratosthenes
{
std::array<bool, N> primesList;
std::fill(primesList.begin(), primesList.end(), true);
primesList[0] = primesList[1] = false;
std::size_t sqrtLimit = std::sqrt(N) + 1;
for (std::size_t i = 0; i < sqrtLimit; ++i)
if (primesList[i])
for (std::size_t j = i + i; j < N; j += i)
primesList[j] = false;
return primesList;
}
template<std::size_t N>
bool isTruncPrime(std::size_t number, const std::array<bool, N>& primesList)
{
for (std::size_t i = 10; i < number; i *= 10)
if (!primesList[number % i]) // If the right truncated part is not prime
return false;
for (; number >= 1; number /= 10)
if (!primesList[number]) // If the left truncated part is not prime
return false;
return true; // All truncated parts are prime, so the number is a truncatable prime
}
int main()
{
const auto primesUptoMillion = primesUpto<1000000ULL>(); // Represents all the primes up to 1 million
std::size_t numberTruncatablePrimes = 0;
std::size_t currentNumber = 11; // 2, 3, 5, and 7 are not included in the search for truncatable primes
std::size_t truncatablePrimeSum = 0;
while (numberTruncatablePrimes != 11)
{
if (primesUptoMillion[currentNumber] && // If the number itself is prime
isTruncPrime(currentNumber, primesUptoMillion)) // If the number is also a truncatable prime
{
++numberTruncatablePrimes; // Increase amount of truncatable primes
truncatablePrimeSum += currentNumber; // Add the number's sum
}
currentNumber += 2; // Only odd numbers can be prime other than 2, so no need to look at every number
}
std::cout << truncatablePrimeSum << "\n";
}
| 1,931
|
C++
|
.cpp
| 45
| 36.955556
| 109
| 0.6512
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,099
|
problem_028.cpp
|
OpenGenus_cosmos/code/online_challenges/src/project_euler/problem_028/problem_028.cpp
|
#include <iostream>
#include <cmath>
bool isPerfectSquare(int num)
{
int sqrtNum = static_cast<int>(std::sqrt(num));
return sqrtNum * sqrtNum == num;
}
int main()
{
int limit = 1001 * 1001;
int incrementRate = 0;
int diagonalNumberSum = 0;
for (int i = 1; i <= limit; i += incrementRate) // Iterate over every diagonal number
{
diagonalNumberSum += i; // Add the current diagonal number
if ((i % 2 == 1) // If the current number is odd
&& isPerfectSquare(i)) // and it is a perfect square
// then we have reached the next spiral
incrementRate += 2;
}
std::cout << diagonalNumberSum << "\n";
}
| 715
|
C++
|
.cpp
| 22
| 26.318182
| 89
| 0.588406
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,100
|
problem_027.cpp
|
OpenGenus_cosmos/code/online_challenges/src/project_euler/problem_027/problem_027.cpp
|
#include <bits/stdc++.h>
using namespace std;
bool isPrime(int n)
{
bool ans = true;
for(int i = 2; i * i <= n; i++)
{
if(n % i == 0)
{
ans = false;
break;
}
}
return ans;
}
int main()
{
int max_primes = 0;
int prod;
for(int a = -999; a <= 999; a++)
{
for(int b = -1000; b <= 1000; b++)
{
int n = 0;
while(n * n + a * n + b > 1 && isPrime(n * n + a * n + b))
{
n++;
}
if(n > max_primes)
{
max_primes = n;
prod = a * b;
}
}
}
cout << prod;
}
| 691
|
C++
|
.cpp
| 37
| 10.918919
| 70
| 0.340491
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,102
|
problem_002.cpp
|
OpenGenus_cosmos/code/online_challenges/src/project_euler/problem_002/problem_002.cpp
|
#include <iostream>
int main()
{
// Variables to keep track of Fibonacci numbers
int p2 = 0;
int p1 = 0;
int current = 1;
int sum = 0;
while (current <= 4000000)
{
// Add even fibonacci numbers
sum += (current % 2 == 0) ? current : 0;
// Update fibonacci numbers
p2 = p1;
p1 = current;
current = p2 + p1;
}
std::cout << sum << "\n";
}
| 424
|
C++
|
.cpp
| 19
| 16.631579
| 51
| 0.5225
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,105
|
problem_005.cpp
|
OpenGenus_cosmos/code/online_challenges/src/project_euler/problem_005/problem_005.cpp
|
#include <iostream>
int main()
{
int d = 1;
while (!(
(d % 11 == 0) &&
(d % 12 == 0) &&
(d % 13 == 0) &&
(d % 14 == 0) &&
(d % 15 == 0) &&
(d % 16 == 0) &&
(d % 17 == 0) &&
(d % 18 == 0) &&
(d % 19 == 0) &&
(d % 20 == 0)
))
++d;
std::cout << d << "\n";
}
| 443
|
C++
|
.cpp
| 19
| 12.421053
| 31
| 0.194774
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,106
|
problem_003.cpp
|
OpenGenus_cosmos/code/online_challenges/src/project_euler/problem_003/problem_003.cpp
|
#include <iostream>
#include <vector>
#include <cmath>
int main()
{
long long int n = 600851475143;
long long int h = 0;
long long int c = 2;
while (n != 1)
{
if ((n % c == 0) && (c > h))
{
h = c;
n /= c;
}
++c;
}
std::cout << h << "\n";
}
| 326
|
C++
|
.cpp
| 19
| 11.631579
| 36
| 0.409836
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,107
|
problem_034.cpp
|
OpenGenus_cosmos/code/online_challenges/src/project_euler/problem_034/problem_034.cpp
|
#include <iostream>
#include <vector>
int factorial (std::size_t n)
{
int fact = 1;
for (std::size_t i = 1; i <= n; ++i)
fact *= i;
return fact;
}
int main()
{
std::vector<int> factorials(10);
constexpr std::size_t maxDigitFactorial = 2540162;
for (int i = 0; i < 10; ++i)
factorials[i] = factorial(i);
std::size_t num = 3, sum = 0;
while (num < maxDigitFactorial)
{
std::size_t temp = 0;
for (std::size_t i = num; i > 0; i /= 10)
temp += factorials[i % 10];
if (temp == num)
sum += num;
++num;
}
std::cout << sum << "\n";
}
| 643
|
C++
|
.cpp
| 27
| 18.444444
| 54
| 0.509772
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,108
|
problem_025.cpp
|
OpenGenus_cosmos/code/online_challenges/src/project_euler/problem_025/problem_025.cpp
|
#include <iostream>
#include <vector>
int main()
{
std::vector<int> prevFibonacci, currFibonacci;
prevFibonacci.reserve(1000);
currFibonacci.reserve(1000);
int count = 2;
prevFibonacci.push_back(1);
currFibonacci.push_back(1);
while (currFibonacci.size() < 1000)
{
std::vector<int> temp;
int carry = 0;
++count;
for (size_t i = 0; i < prevFibonacci.size(); ++i)
{
temp.push_back((currFibonacci[i] + prevFibonacci[i] + carry) % 10);
carry = (currFibonacci[i] + prevFibonacci[i] + carry) / 10;
}
for (size_t i = prevFibonacci.size(); i < currFibonacci.size(); i++)
{
temp.push_back((currFibonacci[i] + carry) % 10);
carry = (currFibonacci[i] + carry) / 10;
}
if (carry)
temp.push_back(carry);
prevFibonacci = currFibonacci;
currFibonacci = temp;
}
std:: cout << count << "\n";
return 0;
}
| 994
|
C++
|
.cpp
| 33
| 22.848485
| 79
| 0.562893
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,109
|
test_list.cpp
|
OpenGenus_cosmos/code/data_structures/test/list/test_list.cpp
|
/*
* Part of Cosmos by OpenGenus Foundation
*
* test lists for std::list-like
*/
#define CATCH_CONFIG_MAIN
#ifndef XOR_LINKED_LIST_TEST_CPP
#define XOR_LINKED_LIST_TEST_CPP
#include "../../../../test/c++/catch.hpp"
#include "../../src/list/xor_linked_list/xor_linked_list.cpp"
#include <iostream>
#include <list>
#include <vector>
using vectorContainer = std::vector<int>;
using expectListContainer = std::list<int>;
using actualListContainer = XorLinkedList<int>;
static size_t RandomSize;
static size_t SmallRandomSize;
TEST_CASE("init")
{
srand(static_cast<unsigned int>(clock()));
RandomSize = 100000 + rand() % 2;
SmallRandomSize = RandomSize / rand() % 100 + 50;
}
vectorContainer getRandomValueContainer(size_t sz = RandomSize)
{
// init
vectorContainer container(sz);
size_t i = 0 - 1;
while (++i < sz)
container.at(i) = static_cast<int>(i);
// randomize
i = 0 - 1;
while (++i < sz)
{
auto r = rand() % container.size();
auto temp = container.at(i);
container.at(i) = container.at(r);
container.at(r) = temp;
}
return container;
}
actualListContainer copyContainerToList(const vectorContainer &container)
{
actualListContainer actual;
std::for_each(container.begin(), container.end(), [&](int v)
{
actual.push_back(v);
});
return actual;
}
void copyRandomPartContainerToLists(const vectorContainer &container,
expectListContainer &expect,
actualListContainer &actual)
{
std::for_each(container.begin(), container.end(), [&](int v)
{
if (rand() % 2)
{
expect.push_back(v);
actual.push_back(v);
}
});
auto begin = container.begin();
while (expect.size() < 10)
{
expect.push_back(*begin);
actual.push_back(*begin++);
}
}
void isSame(expectListContainer expect, actualListContainer actual)
{
CHECK(expect.size() == actual.size());
CHECK(expect.empty() == actual.empty());
auto expectIt = expect.begin();
auto actualIt = actual.begin();
while (expectIt != expect.end())
CHECK(*expectIt++ == *actualIt++);
}
TEST_CASE("-ctors converts and its types")
{
expectListContainer expect;
actualListContainer actual;
const expectListContainer cExpect;
const actualListContainer cActual;
SECTION("iterator")
{
SECTION("begin")
{
expectListContainer::iterator expectIt1(expect.begin());
expectListContainer::const_iterator expectIt2(expect.begin());
expectListContainer::reverse_iterator expectIt3(expect.begin());
expectListContainer::const_reverse_iterator expectIt4(expect.begin());
expectListContainer::const_iterator expectCIt2(expect.cbegin());
expectListContainer::const_reverse_iterator expectCIt4(expect.cbegin());
expectListContainer::reverse_iterator expectRIt3(expect.rbegin());
expectListContainer::const_reverse_iterator expectRIt4(expect.rbegin());
expectListContainer::const_reverse_iterator expectCRIt4(expect.crbegin());
actualListContainer::iterator actualIt1(actual.begin());
actualListContainer::const_iterator actualIt2(actual.begin());
actualListContainer::reverse_iterator actualIt3(actual.begin());
actualListContainer::const_reverse_iterator actualIt4(actual.begin());
actualListContainer::const_iterator actualCIt2(actual.cbegin());
actualListContainer::const_reverse_iterator actualCIt4(actual.cbegin());
actualListContainer::reverse_iterator actualRIt3(actual.rbegin());
actualListContainer::const_reverse_iterator actualRIt4(actual.rbegin());
actualListContainer::const_reverse_iterator actualCRIt4(actual.crbegin());
}
SECTION("begin errors")
{
// expectListContainer::iterator expectCIt1(expect.cbegin());
// expectListContainer::reverse_iterator expectCIt3(expect.cbegin());
//
// expectListContainer::iterator expectRIt1(expect.rbegin());
// expectListContainer::const_iterator expectRIt2(expect.rbegin());
//
// expectListContainer::iterator expectCRIt1(expect.crbegin());
// expectListContainer::const_iterator expectCRIt2(expect.crbegin());
// expectListContainer::reverse_iterator expectCRIt3(expect.crbegin());
// actualListContainer::iterator actualCIt1(actual.cbegin());
// actualListContainer::reverse_iterator actualCIt3(actual.cbegin());
// actualListContainer::iterator actualRIt1(actual.rbegin());
// actualListContainer::const_iterator actualRIt2(actual.rbegin());
// actualListContainer::iterator actualCRIt1(actual.crbegin());
// actualListContainer::const_iterator actualCRIt2(actual.crbegin());
// actualListContainer::reverse_iterator actualCRIt3(actual.crbegin());
}
SECTION("end")
{
expectListContainer::iterator expectIt1(expect.end());
expectListContainer::const_iterator expectIt2(expect.end());
expectListContainer::reverse_iterator expectIt3(expect.end());
expectListContainer::const_reverse_iterator expectIt4(expect.end());
expectListContainer::const_iterator expectCIt2(expect.cend());
expectListContainer::const_reverse_iterator expectCIt4(expect.cend());
expectListContainer::reverse_iterator expectRIt3(expect.rend());
expectListContainer::const_reverse_iterator expectRIt4(expect.rend());
expectListContainer::const_reverse_iterator expectCRIt4(expect.crend());
actualListContainer::iterator actualIt1(actual.end());
actualListContainer::const_iterator actualIt2(actual.end());
actualListContainer::reverse_iterator actualIt3(actual.end());
actualListContainer::const_reverse_iterator actualIt4(actual.end());
actualListContainer::const_iterator actualCIt2(actual.cend());
actualListContainer::const_reverse_iterator actualCIt4(actual.cend());
actualListContainer::reverse_iterator actualRIt3(actual.rend());
actualListContainer::const_reverse_iterator actualRIt4(actual.rend());
actualListContainer::const_reverse_iterator actualCRIt4(actual.crend());
}
SECTION("end error")
{
// expectListContainer::iterator expectCIt1(expect.cend());
// expectListContainer::reverse_iterator expectCIt3(expect.cend());
//
// expectListContainer::iterator expectRIt1(expect.rend());
// expectListContainer::const_iterator expectRIt2(expect.rend());
//
// expectListContainer::iterator expectCRIt1(expect.crend());
// expectListContainer::const_iterator expectCRIt2(expect.crend());
// expectListContainer::reverse_iterator expectCRIt3(expect.crend());
// actualListContainer::iterator actualCIt1(actual.cend());
// actualListContainer::reverse_iterator actualCIt3(actual.cend());
//
// actualListContainer::iterator actualRIt1(actual.rend());
// actualListContainer::const_iterator actualRIt2(actual.rend());
//
// actualListContainer::iterator actualCRIt1(actual.crend());
// actualListContainer::const_iterator actualCRIt2(actual.crend());
// actualListContainer::reverse_iterator actualCRIt3(actual.crend());
}
SECTION("const begin")
{
const expectListContainer::const_iterator expectIt2(cExpect.begin());
const expectListContainer::const_reverse_iterator expectIt4(cExpect.begin());
const expectListContainer::const_iterator expectCIt2(cExpect.cbegin());
const expectListContainer::const_reverse_iterator expectCIt4(cExpect.cbegin());
const expectListContainer::const_reverse_iterator expectRIt4(cExpect.rbegin());
const expectListContainer::const_reverse_iterator expectCRIt4(cExpect.crbegin());
const actualListContainer::const_iterator actualIt2(cActual.begin());
const actualListContainer::const_reverse_iterator actualIt4(cActual.begin());
const actualListContainer::const_iterator actualCIt2(cActual.cbegin());
const actualListContainer::const_reverse_iterator actualCIt4(cActual.cbegin());
const actualListContainer::const_reverse_iterator actualRIt4(cActual.rbegin());
const actualListContainer::const_reverse_iterator actualCRIt4(cActual.crbegin());
}
SECTION("const begin errors")
{
// const expectListContainer::iterator expectIt1(cExpect.begin());
// const expectListContainer::reverse_iterator expectIt3(cExpect.begin());
//
// const expectListContainer::iterator expectCIt1(cExpect.cbegin());
// const expectListContainer::reverse_iterator expectCIt3(cExpect.cbegin());
//
// const expectListContainer::iterator expectRIt1(cExpect.rbegin());
// const expectListContainer::const_iterator expectRIt2(cExpect.rbegin());
// const expectListContainer::reverse_iterator expectRIt3(cExpect.rbegin());
//
// const expectListContainer::iterator expectCRIt1(cExpect.crbegin());
// const expectListContainer::const_iterator expectCRIt2(cExpect.crbegin());
// const expectListContainer::reverse_iterator expectCRIt3(cExpect.crbegin());
// const actualListContainer::iterator actualIt1(cActual.begin());
// const actualListContainer::reverse_iterator actualIt3(cActual.begin());
//
// const actualListContainer::iterator actualCIt1(cActual.cbegin());
// const actualListContainer::reverse_iterator actualCIt3(cActual.cbegin());
//
// const actualListContainer::iterator actualRIt1(cActual.rbegin());
// const actualListContainer::const_iterator actualRIt2(cActual.rbegin());
// const actualListContainer::reverse_iterator actualRIt3(cActual.rbegin());
//
// const actualListContainer::iterator actualCRIt1(cActual.crbegin());
// const actualListContainer::const_iterator actualCRIt2(cActual.crbegin());
// const actualListContainer::reverse_iterator actualCRIt3(cActual.crbegin());
}
SECTION("const end")
{
const expectListContainer::const_iterator expectIt2(cExpect.end());
const expectListContainer::const_reverse_iterator expectIt4(cExpect.end());
const expectListContainer::const_iterator expectCIt2(cExpect.cend());
const expectListContainer::const_reverse_iterator expectCIt4(cExpect.cend());
const expectListContainer::const_reverse_iterator expectRIt4(cExpect.rend());
const expectListContainer::const_reverse_iterator expectCRIt4(cExpect.crend());
const actualListContainer::const_iterator actualIt2(cActual.end());
const actualListContainer::const_reverse_iterator actualIt4(cActual.end());
const actualListContainer::const_iterator actualCIt2(cActual.cend());
const actualListContainer::const_reverse_iterator actualCIt4(cActual.cend());
const actualListContainer::const_reverse_iterator actualRIt4(cActual.rend());
const actualListContainer::const_reverse_iterator actualCRIt4(cActual.crend());
}
SECTION("const end error")
{
// const expectListContainer::iterator expectIt1(cExpect.end());
// const expectListContainer::reverse_iterator expectIt3(cExpect.end());
//
// const expectListContainer::iterator expectCIt1(cExpect.cend());
// const expectListContainer::reverse_iterator expectCIt3(cExpect.cend());
//
// const expectListContainer::iterator expectRIt1(cExpect.rend());
// const expectListContainer::const_iterator expectRIt2(cExpect.rend());
// const expectListContainer::reverse_iterator expectRIt3(cExpect.rend());
//
// const expectListContainer::iterator expectCRIt1(cExpect.crend());
// const expectListContainer::const_iterator expectCRIt2(cExpect.crend());
// const expectListContainer::reverse_iterator expectCRIt3(cExpect.crend());
// const actualListContainer::iterator actualIt1(cActual.end());
// const actualListContainer::reverse_iterator actualIt3(cActual.end());
//
// const actualListContainer::iterator actualCIt1(cActual.cend());
// const actualListContainer::reverse_iterator actualCIt3(cActual.cend());
//
// const actualListContainer::iterator actualRIt1(cActual.rend());
// const actualListContainer::const_iterator actualRIt2(cActual.rend());
// const actualListContainer::reverse_iterator actualRIt3(cActual.rend());
//
// const actualListContainer::iterator actualCRIt1(cActual.crend());
// const actualListContainer::const_iterator actualCRIt2(cActual.crend());
// const actualListContainer::reverse_iterator actualCRIt3(cActual.crend());
}
}
SECTION("container")
{
expectListContainer expect1;
expectListContainer expect2(expect1);
expectListContainer expect3{1, 2, 3};
actualListContainer actual1;
actualListContainer actual2(actual1);
actualListContainer actual3{1, 2, 3};
}
}
TEST_CASE("const semantic")
{
expectListContainer expect;
actualListContainer actual;
const expectListContainer cExpect;
const actualListContainer cActual;
using std::is_const;
SECTION("iterators")
{
SECTION("non-const")
{
CHECK(is_const<decltype(actual.begin())>() == is_const<decltype(expect.begin())>());
CHECK(is_const<decltype(actual.begin().operator->())>()
== is_const<decltype(expect.begin().operator->())>());
CHECK(is_const<decltype(*actual.begin())>() == is_const<decltype(*expect.begin())>());
CHECK(is_const<decltype(actual.end())>() == is_const<decltype(expect.end())>());
CHECK(is_const<decltype(actual.end().operator->())>()
== is_const<decltype(expect.end().operator->())>());
CHECK(is_const<decltype(*actual.end())>() == is_const<decltype(*expect.end())>());
CHECK(is_const<decltype(actual.cbegin())>() == is_const<decltype(expect.cbegin())>());
CHECK(is_const<decltype(actual.cbegin().operator->())>()
== is_const<decltype(expect.cbegin().operator->())>());
CHECK(is_const<decltype(*actual.cbegin())>()
== is_const<decltype(*expect.cbegin())>());
CHECK(is_const<decltype(actual.cend())>() == is_const<decltype(expect.cend())>());
CHECK(is_const<decltype(actual.cend().operator->())>()
== is_const<decltype(expect.cend().operator->())>());
CHECK(is_const<decltype(*actual.cend())>() == is_const<decltype(*expect.cend())>());
CHECK(is_const<decltype(actual.rbegin())>() == is_const<decltype(expect.rbegin())>());
CHECK(is_const<decltype(actual.rbegin().operator->())>()
== is_const<decltype(expect.rbegin().operator->())>());
CHECK(is_const<decltype(*actual.rbegin())>()
== is_const<decltype(*expect.rbegin())>());
CHECK(is_const<decltype(actual.rend())>() == is_const<decltype(expect.rend())>());
CHECK(is_const<decltype(actual.rend().operator->())>()
== is_const<decltype(expect.rend().operator->())>());
CHECK(is_const<decltype(*actual.rend())>() == is_const<decltype(*expect.rend())>());
CHECK(is_const<decltype(actual.crbegin())>()
== is_const<decltype(expect.crbegin())>());
CHECK(is_const<decltype(actual.crbegin().operator->())>()
== is_const<decltype(expect.crbegin().operator->())>());
CHECK(is_const<decltype(*actual.crbegin())>()
== is_const<decltype(*expect.crbegin())>());
CHECK(is_const<decltype(actual.crend())>() == is_const<decltype(expect.crend())>());
CHECK(is_const<decltype(actual.crend().operator->())>()
== is_const<decltype(expect.crend().operator->())>());
CHECK(is_const<decltype(*actual.crend())>() == is_const<decltype(*expect.crend())>());
CHECK(is_const<decltype(actual.rbegin().base())>()
== is_const<decltype(expect.rbegin().base())>());
CHECK(is_const<decltype(actual.rbegin().base().operator->())>()
== is_const<decltype(expect.rbegin().base().operator->())>());
CHECK(is_const<decltype(*actual.rbegin().base())>()
== is_const<decltype(*expect.rbegin().base())>());
CHECK(is_const<decltype(actual.rend().base())>()
== is_const<decltype(expect.rend().base())>());
CHECK(is_const<decltype(actual.rend().base().operator->())>()
== is_const<decltype(expect.rend().base().operator->())>());
CHECK(is_const<decltype(*actual.rend().base())>()
== is_const<decltype(*expect.rend().base())>());
CHECK(is_const<decltype(actual.crbegin().base())>()
== is_const<decltype(expect.crbegin().base())>());
CHECK(is_const<decltype(actual.crbegin().base().operator->())>()
== is_const<decltype(expect.crbegin().base().operator->())>());
CHECK(is_const<decltype(actual.crend().base())>()
== is_const<decltype(expect.crend().base())>());
CHECK(is_const<decltype(*actual.crbegin().base())>()
== is_const<decltype(*expect.crbegin().base())>());
CHECK(is_const<decltype(*actual.crbegin().base().operator->())>()
== is_const<decltype(*expect.crbegin().base().operator->())>());
CHECK(is_const<decltype(*actual.crend().base())>()
== is_const<decltype(*expect.crend().base())>());
}
SECTION("const")
{
CHECK(is_const<decltype(cActual.begin())>() == is_const<decltype(cExpect.begin())>());
CHECK(is_const<decltype(cActual.begin().operator->())>()
== is_const<decltype(cExpect.begin().operator->())>());
CHECK(is_const<decltype(*cActual.begin())>() == is_const<decltype(*cExpect.begin())>());
CHECK(is_const<decltype(cActual.end())>() == is_const<decltype(cExpect.end())>());
CHECK(is_const<decltype(cActual.end().operator->())>()
== is_const<decltype(cExpect.end().operator->())>());
CHECK(is_const<decltype(*cActual.end())>() == is_const<decltype(*cExpect.end())>());
CHECK(is_const<decltype(cActual.cbegin())>() == is_const<decltype(cExpect.cbegin())>());
CHECK(is_const<decltype(cActual.cbegin().operator->())>()
== is_const<decltype(cExpect.cbegin().operator->())>());
CHECK(is_const<decltype(*cActual.cbegin())>()
== is_const<decltype(*cExpect.cbegin())>());
CHECK(is_const<decltype(cActual.cend())>() == is_const<decltype(cExpect.cend())>());
CHECK(is_const<decltype(cActual.cend().operator->())>()
== is_const<decltype(cExpect.cend().operator->())>());
CHECK(is_const<decltype(*cActual.cend())>() == is_const<decltype(*cExpect.cend())>());
CHECK(is_const<decltype(cActual.rbegin())>() == is_const<decltype(cExpect.rbegin())>());
CHECK(is_const<decltype(cActual.rbegin().operator->())>()
== is_const<decltype(cExpect.rbegin().operator->())>());
CHECK(is_const<decltype(*cActual.rbegin())>()
== is_const<decltype(*cExpect.rbegin())>());
CHECK(is_const<decltype(cActual.rend())>() == is_const<decltype(cExpect.rend())>());
CHECK(is_const<decltype(cActual.rend().operator->())>()
== is_const<decltype(cExpect.rend().operator->())>());
CHECK(is_const<decltype(*cActual.rend())>() == is_const<decltype(*cExpect.rend())>());
CHECK(is_const<decltype(cActual.crbegin())>()
== is_const<decltype(cExpect.crbegin())>());
CHECK(is_const<decltype(cActual.crbegin().operator->())>()
== is_const<decltype(cExpect.crbegin().operator->())>());
CHECK(is_const<decltype(*cActual.crbegin())>()
== is_const<decltype(*cExpect.crbegin())>());
CHECK(is_const<decltype(cActual.crend())>() == is_const<decltype(cExpect.crend())>());
CHECK(is_const<decltype(cActual.crend().operator->())>()
== is_const<decltype(cExpect.crend().operator->())>());
CHECK(is_const<decltype(*cActual.crend())>() == is_const<decltype(*cExpect.crend())>());
CHECK(is_const<decltype(cActual.rbegin().base())>()
== is_const<decltype(cExpect.rbegin().base())>());
CHECK(is_const<decltype(cActual.rbegin().base().operator->())>()
== is_const<decltype(cExpect.rbegin().base().operator->())>());
CHECK(is_const<decltype(*cActual.rbegin().base())>()
== is_const<decltype(*cExpect.rbegin().base())>());
CHECK(is_const<decltype(cActual.rend().base())>()
== is_const<decltype(cExpect.rend().base())>());
CHECK(is_const<decltype(cActual.rend().base().operator->())>()
== is_const<decltype(cExpect.rend().base().operator->())>());
CHECK(is_const<decltype(*cActual.rend().base())>()
== is_const<decltype(*cExpect.rend().base())>());
CHECK(is_const<decltype(cActual.crbegin().base())>()
== is_const<decltype(cExpect.crbegin().base())>());
CHECK(is_const<decltype(cActual.crbegin().base().operator->())>()
== is_const<decltype(cExpect.crbegin().base().operator->())>());
CHECK(is_const<decltype(cActual.crend().base())>()
== is_const<decltype(cExpect.crend().base())>());
CHECK(is_const<decltype(*cActual.crbegin().base())>()
== is_const<decltype(*cExpect.crbegin().base())>());
CHECK(is_const<decltype(*cActual.crbegin().base().operator->())>()
== is_const<decltype(*cExpect.crbegin().base().operator->())>());
CHECK(is_const<decltype(*cActual.crend().base())>()
== is_const<decltype(*cExpect.crend().base())>());
}
}
SECTION("element access")
{
SECTION("non-const")
{
CHECK(is_const<decltype(actual.front())>() == is_const<decltype(expect.front())>());
CHECK(is_const<decltype(actual.back())>() == is_const<decltype(expect.back())>());
}
SECTION("const")
{
CHECK(is_const<decltype(cActual.front())>() == is_const<decltype(cExpect.front())>());
CHECK(is_const<decltype(cActual.back())>() == is_const<decltype(cExpect.back())>());
}
}
}
TEST_CASE("element access rely on [push]")
{
actualListContainer actual;
SECTION("push one node")
{
actual.push_back(1);
CHECK(actual.front() == 1);
CHECK(actual.back() == 1);
}
SECTION("push two nodes")
{
actual.push_back(1);
actual.push_back(2);
CHECK(actual.front() == 1);
CHECK(actual.back() == 2);
actual.push_front(3);
CHECK(actual.front() == 3);
CHECK(actual.back() == 2);
}
}
TEST_CASE("modifiers")
{
auto randomContainer = getRandomValueContainer();
auto randomSmallContainer = getRandomValueContainer(SmallRandomSize);
std::initializer_list<int> randomIlist{rand(), rand(), rand(), rand(), rand()};
expectListContainer expect;
actualListContainer actual;
expectListContainer::iterator expectReturnPos;
actualListContainer::iterator actualReturnPos;
int randomValue{};
size_t sz{};
SECTION("empty list")
{
CHECK_THROWS_AS(actual.front(), std::out_of_range);
CHECK_THROWS_AS(actual.back(), std::out_of_range);
CHECK(actual.size() == 0);
CHECK(actual.empty());
}
SECTION("[clear] rely on [push_back]")
{
SECTION("while empty")
{
actual.clear();
}
SECTION("after actions")
{
actual.push_back(1);
actual.push_back(2);
actual.clear();
actual.push_back(3);
}
SECTION("before destruct")
{
actual.push_back(1);
actual.push_back(2);
actual.push_back(3);
actual.clear();
}
SECTION("while destruct")
{
actual.push_back(1);
actual.push_back(2);
actual.push_back(3);
}
}
SECTION("[erase] rely on [push_back/begin/end/op/size]")
{
SECTION("erase(const_iterator)")
{
SECTION("from empty")
{
/*
* erase(end()) is undefined, refer to:
* http://en.cppreference.com/w/cpp/container/list/erase
*/
}
SECTION("first one")
{
SECTION("size is 1")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
expectReturnPos = expect.erase(expect.begin());
actualReturnPos = actual.erase(actual.begin());
CHECK(expectReturnPos == expect.end());
CHECK(actualReturnPos == actual.end());
isSame(expect, actual);
}
SECTION("random size")
{
copyRandomPartContainerToLists(randomContainer, expect, actual);
expectReturnPos = expect.erase(expect.begin());
actualReturnPos = actual.erase(actual.begin());
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
}
SECTION("last one")
{
SECTION("size is 1")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
expectReturnPos = expect.erase(expect.begin());
actualReturnPos = actual.erase(actual.begin());
CHECK(expectReturnPos == expect.end());
CHECK(actualReturnPos == actual.end());
isSame(expect, actual);
}
SECTION("random size")
{
copyRandomPartContainerToLists(randomContainer, expect, actual);
expectReturnPos = expect.erase(--expect.end());
actualReturnPos = actual.erase(--actual.end());
CHECK(expectReturnPos == expect.end());
CHECK(actualReturnPos == actual.end());
isSame(expect, actual);
}
}
SECTION("between of begin and end")
{
copyRandomPartContainerToLists(randomContainer, expect, actual);
expectReturnPos = expect.erase(---- expect.end());
actualReturnPos = actual.erase(---- actual.end());
CHECK(expectReturnPos == --expect.end());
CHECK(actualReturnPos == --actual.end());
isSame(expect, actual);
}
}
SECTION("erase(const_iterator, const_iterator)")
{
SECTION("from empty")
{
/*
* erase(end(), end()) is undefined, refer to:
* http://en.cppreference.com/w/cpp/container/list/erase
*/
}
SECTION("size is 1")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
expectReturnPos = expect.erase(expect.begin(), expect.end());
actualReturnPos = actual.erase(actual.begin(), actual.end());
CHECK(expectReturnPos == expect.end());
CHECK(actualReturnPos == actual.end());
isSame(expect, actual);
}
SECTION("random size")
{
copyRandomPartContainerToLists(randomContainer, expect, actual);
SECTION("[begin : end)")
{
expectReturnPos = expect.erase(expect.begin(), ++++++ expect.begin());
actualReturnPos = actual.erase(actual.begin(), ++++++ actual.begin());
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
SECTION("(begin : end)")
{
expectReturnPos = expect.erase(++++++ expect.begin(), ------ expect.end());
actualReturnPos = actual.erase(++++++ actual.begin(), ------ actual.end());
CHECK(expectReturnPos == ------ expect.end());
CHECK(actualReturnPos == ------ actual.end());
isSame(expect, actual);
}
SECTION("(begin : end]")
{
expectReturnPos = expect.erase(++++++ expect.begin(), expect.end());
actualReturnPos = actual.erase(++++++ actual.begin(), actual.end());
CHECK(expectReturnPos == expect.end());
CHECK(actualReturnPos == actual.end());
isSame(expect, actual);
}
}
}
}
SECTION("[insert] rely on [op/begin/end/size/push_back/clear]")
{
SECTION("insert(const_iterator, const value_type &)")
{
SECTION("to empty")
{
randomValue = rand();
expectReturnPos = expect.insert(expect.end(), randomValue);
actualReturnPos = actual.insert(actual.end(), randomValue);
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
SECTION("before begin")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expectReturnPos = expect.insert(expect.begin(), randomValue);
actualReturnPos = actual.insert(actual.begin(), randomValue);
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
SECTION("before end")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expectReturnPos = expect.insert(expect.end(), randomValue);
actualReturnPos = actual.insert(actual.end(), randomValue);
CHECK(expectReturnPos == --expect.end());
CHECK(actualReturnPos == --actual.end());
isSame(expect, actual);
}
SECTION("between of begin and end")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expectReturnPos = expect.insert(++expect.begin(), randomValue);
actualReturnPos = actual.insert(++actual.begin(), randomValue);
CHECK(expectReturnPos == ++expect.begin());
CHECK(actualReturnPos == ++actual.begin());
isSame(expect, actual);
}
}
SECTION("insert(const_iterator, value_type &&)")
{
SECTION("to empty")
{
randomValue = rand();
expectReturnPos = expect.insert(expect.end(), std::move(randomValue));
actualReturnPos = actual.insert(actual.end(), std::move(randomValue));
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
SECTION("before begin")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expectReturnPos = expect.insert(expect.begin(), std::move(randomValue));
actualReturnPos = actual.insert(actual.begin(), std::move(randomValue));
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
SECTION("before end")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expectReturnPos = expect.insert(expect.end(), std::move(randomValue));
actualReturnPos = actual.insert(actual.end(), std::move(randomValue));
CHECK(expectReturnPos == --expect.end());
CHECK(actualReturnPos == --actual.end());
isSame(expect, actual);
}
SECTION("between of begin and end")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expectReturnPos = expect.insert(++expect.begin(), std::move(randomValue));
actualReturnPos = actual.insert(++actual.begin(), std::move(randomValue));
CHECK(expectReturnPos == ++expect.begin());
CHECK(actualReturnPos == ++actual.begin());
isSame(expect, actual);
}
}
SECTION("insert(const_iterator, size_type, const value_type &)")
{
SECTION("to empty")
{
SECTION("size is 0")
{
randomValue = rand();
sz = 0;
auto expectReturnPos = expect.insert(expect.end(), sz, randomValue);
actualReturnPos = actual.insert(actual.end(), sz, randomValue);
CHECK(expectReturnPos == expect.end());
CHECK(actualReturnPos == actual.end());
isSame(expect, actual);
}
SECTION("size is non-zero")
{
randomValue = rand();
sz = rand() % 10 + SmallRandomSize;
expectReturnPos = expect.insert(expect.end(), sz, randomValue);
actualReturnPos = actual.insert(actual.end(), sz, randomValue);
auto tempe = expect.end();
auto tempa = actual.end();
++sz;
while (--sz)
{
--tempe;
--tempa;
}
CHECK(expectReturnPos == tempe);
CHECK(actualReturnPos == tempa);
isSame(expect, actual);
}
}
SECTION("before begin")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
SECTION("size is 0")
{
randomValue = rand();
sz = 0;
expectReturnPos = expect.insert(expect.begin(), sz, randomValue);
actualReturnPos = actual.insert(actual.begin(), sz, randomValue);
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
SECTION("size is non-zero")
{
randomValue = rand();
sz = rand() % 10 + SmallRandomSize;
expectReturnPos = expect.insert(expect.begin(), sz, randomValue);
actualReturnPos = actual.insert(actual.begin(), sz, randomValue);
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
}
SECTION("before end")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
SECTION("size is 0")
{
randomValue = rand();
sz = 0;
expectReturnPos = expect.insert(expect.end(), sz, randomValue);
actualReturnPos = actual.insert(actual.end(), sz, randomValue);
CHECK(expectReturnPos == expect.end());
CHECK(actualReturnPos == actual.end());
isSame(expect, actual);
}
SECTION("size is non-zero")
{
randomValue = rand();
sz = rand() % 10 + SmallRandomSize;
expectReturnPos = expect.insert(expect.end(), sz, randomValue);
actualReturnPos = actual.insert(actual.end(), sz, randomValue);
auto tempe = expect.end();
auto tempa = actual.end();
++sz;
while (--sz)
{
--tempe;
--tempa;
}
CHECK(expectReturnPos == tempe);
CHECK(actualReturnPos == tempa);
isSame(expect, actual);
}
}
SECTION("between of begin and end")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
SECTION("size is 0")
{
randomValue = rand();
sz = 0;
expectReturnPos = expect.insert(++expect.begin(), sz, randomValue);
actualReturnPos = actual.insert(++actual.begin(), sz, randomValue);
CHECK(expectReturnPos == ++expect.begin());
CHECK(actualReturnPos == ++actual.begin());
isSame(expect, actual);
}
SECTION("size is non-zero")
{
randomValue = rand();
sz = rand() % 10 + SmallRandomSize;
expectReturnPos = expect.insert(++expect.begin(), sz, randomValue);
actualReturnPos = actual.insert(++actual.begin(), sz, randomValue);
CHECK(expectReturnPos == ++expect.begin());
CHECK(actualReturnPos == ++actual.begin());
isSame(expect, actual);
}
}
SECTION("size is 1")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
sz = 1;
expectReturnPos = expect.insert(++expect.begin(), sz, randomValue);
actualReturnPos = actual.insert(++actual.begin(), sz, randomValue);
CHECK(expectReturnPos == ++expect.begin());
CHECK(actualReturnPos == ++actual.begin());
isSame(expect, actual);
}
}
SECTION("insert(const_iterator, initilizer_list)")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
SECTION("to empty")
{
expect.clear();
actual.clear();
SECTION("initializer_list is empty")
{
randomIlist = {};
expectReturnPos = expect.insert(expect.end(), randomIlist);
actualReturnPos = actual.insert(actual.end(), randomIlist);
CHECK(expectReturnPos == expect.end());
CHECK(actualReturnPos == actual.end());
isSame(expect, actual);
}
SECTION("initializer_list is non-empty")
{
expectReturnPos = expect.insert(expect.end(), randomIlist);
actualReturnPos = actual.insert(actual.end(), randomIlist);
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
}
SECTION("before begin")
{
SECTION("initializer_list is empty")
{
randomIlist = {};
expectReturnPos = expect.insert(expect.begin(), randomIlist);
actualReturnPos = actual.insert(actual.begin(), randomIlist);
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
SECTION("initializer_list is non-empty")
{
expectReturnPos = expect.insert(expect.begin(), randomIlist);
actualReturnPos = actual.insert(actual.begin(), randomIlist);
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
}
SECTION("before end")
{
SECTION("initializer_list is empty")
{
randomIlist = {};
expectReturnPos = expect.insert(expect.end(), randomIlist);
actualReturnPos = actual.insert(actual.end(), randomIlist);
CHECK(expectReturnPos == expect.end());
CHECK(actualReturnPos == actual.end());
isSame(expect, actual);
}
SECTION("initializer_list is non-empty")
{
expectReturnPos = expect.insert(expect.end(), randomIlist);
actualReturnPos = actual.insert(actual.end(), randomIlist);
CHECK(expectReturnPos == ++++ expect.begin());
CHECK(actualReturnPos == ++++ actual.begin());
isSame(expect, actual);
}
}
SECTION("between of begin and end")
{
SECTION("initializer_list is empty")
{
randomIlist = {};
expectReturnPos = expect.insert(++expect.begin(), randomIlist);
actualReturnPos = actual.insert(++actual.begin(), randomIlist);
CHECK(expectReturnPos == ++expect.begin());
CHECK(actualReturnPos == ++actual.begin());
isSame(expect, actual);
}
SECTION("initializer_list is non-empty")
{
expectReturnPos = expect.insert(++expect.begin(), randomIlist);
actualReturnPos = actual.insert(++actual.begin(), randomIlist);
CHECK(expectReturnPos == ++expect.begin());
CHECK(actualReturnPos == ++actual.begin());
isSame(expect, actual);
}
}
SECTION("size of initializer is 1")
{
randomIlist = {rand()};
expectReturnPos = expect.insert(++expect.begin(), randomIlist);
actualReturnPos = actual.insert(++actual.begin(), randomIlist);
CHECK(expectReturnPos == ++expect.begin());
CHECK(actualReturnPos == ++actual.begin());
isSame(expect, actual);
}
}
SECTION("insert(const_iterator, iterator, iterator)")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
SECTION("to empty")
{
expect.clear();
actual.clear();
SECTION("container is empty")
{
randomSmallContainer = {};
expectReturnPos = expect.insert(expect.end(),
randomSmallContainer.begin(),
randomSmallContainer.end());
actualReturnPos = actual.insert(actual.end(),
randomSmallContainer.begin(),
randomSmallContainer.end());
CHECK(expectReturnPos == expect.end());
CHECK(actualReturnPos == actual.end());
isSame(expect, actual);
}
SECTION("container is non-empty")
{
expectReturnPos = expect.insert(expect.end(),
randomSmallContainer.begin(),
randomSmallContainer.end());
actualReturnPos = actual.insert(actual.end(),
randomSmallContainer.begin(),
randomSmallContainer.end());
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
}
SECTION("before begin")
{
SECTION("container is empty")
{
randomSmallContainer = {};
expectReturnPos = expect.insert(expect.begin(),
randomSmallContainer.begin(),
randomSmallContainer.end());
actualReturnPos = actual.insert(actual.begin(),
randomSmallContainer.begin(),
randomSmallContainer.end());
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
SECTION("container is non-empty")
{
expectReturnPos = expect.insert(expect.begin(),
randomSmallContainer.begin(),
randomSmallContainer.end());
actualReturnPos = actual.insert(actual.begin(),
randomSmallContainer.begin(),
randomSmallContainer.end());
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
}
SECTION("before end")
{
SECTION("container is empty")
{
randomSmallContainer = {};
expectReturnPos = expect.insert(expect.end(),
randomSmallContainer.begin(),
randomSmallContainer.end());
actualReturnPos = actual.insert(actual.end(),
randomSmallContainer.begin(),
randomSmallContainer.end());
CHECK(expectReturnPos == expect.end());
CHECK(actualReturnPos == actual.end());
isSame(expect, actual);
}
SECTION("container is non-empty")
{
expectReturnPos = expect.insert(expect.end(),
randomSmallContainer.begin(),
randomSmallContainer.end());
actualReturnPos = actual.insert(actual.end(),
randomSmallContainer.begin(),
randomSmallContainer.end());
CHECK(expectReturnPos == ++++ expect.begin());
CHECK(actualReturnPos == ++++ actual.begin());
isSame(expect, actual);
}
}
SECTION("between of begin and end")
{
SECTION("container is empty")
{
randomSmallContainer = {};
expectReturnPos = expect.insert(++expect.begin(),
randomSmallContainer.begin(),
randomSmallContainer.end());
actualReturnPos = actual.insert(++actual.begin(),
randomSmallContainer.begin(),
randomSmallContainer.end());
CHECK(expectReturnPos == ++expect.begin());
CHECK(actualReturnPos == ++actual.begin());
isSame(expect, actual);
}
SECTION("container is non-empty")
{
expectReturnPos = expect.insert(++expect.begin(),
randomSmallContainer.begin(),
randomSmallContainer.end());
actualReturnPos = actual.insert(++actual.begin(),
randomSmallContainer.begin(),
randomSmallContainer.end());
CHECK(expectReturnPos == ++expect.begin());
CHECK(actualReturnPos == ++actual.begin());
isSame(expect, actual);
}
}
SECTION("size of iterator is 1")
{
randomSmallContainer = {rand()};
expectReturnPos = expect.insert(++expect.begin(),
randomSmallContainer.begin(),
randomSmallContainer.end());
actualReturnPos = actual.insert(++actual.begin(),
randomSmallContainer.begin(),
randomSmallContainer.end());
CHECK(expectReturnPos == ++expect.begin());
CHECK(actualReturnPos == ++actual.begin());
isSame(expect, actual);
}
}
}
SECTION("pop rely on [push_back/front/back]")
{
// std not throws exception while invoke pop on empty list
SECTION("pop_front")
{
actual.push_back(111);
CHECK_NOTHROW(actual.pop_front());
CHECK_THROWS_AS(actual.front(), std::out_of_range);
CHECK_THROWS_AS(actual.back(), std::out_of_range);
actual.push_back(111);
actual.push_back(222);
CHECK_NOTHROW(actual.pop_front());
CHECK_NOTHROW(actual.pop_front());
CHECK_THROWS_AS(actual.front(), std::out_of_range);
CHECK_THROWS_AS(actual.back(), std::out_of_range);
actual.push_back(111);
actual.push_back(222);
actual.push_back(333);
CHECK_NOTHROW(actual.pop_front());
CHECK_NOTHROW(actual.pop_front());
CHECK_NOTHROW(actual.pop_front());
CHECK_THROWS_AS(actual.front(), std::out_of_range);
CHECK_THROWS_AS(actual.back(), std::out_of_range);
}
SECTION("pop_back")
{
actual.push_back(111);
CHECK_NOTHROW(actual.pop_back());
CHECK_THROWS_AS(actual.front(), std::out_of_range);
CHECK_THROWS_AS(actual.back(), std::out_of_range);
actual.push_back(111);
actual.push_back(222);
CHECK_NOTHROW(actual.pop_back());
CHECK_NOTHROW(actual.pop_back());
CHECK_THROWS_AS(actual.front(), std::out_of_range);
CHECK_THROWS_AS(actual.back(), std::out_of_range);
actual.push_back(111);
actual.push_back(222);
actual.push_back(333);
CHECK_NOTHROW(actual.pop_back());
CHECK_NOTHROW(actual.pop_back());
CHECK_NOTHROW(actual.pop_back());
CHECK_THROWS_AS(actual.front(), std::out_of_range);
CHECK_THROWS_AS(actual.back(), std::out_of_range);
}
SECTION("random pop")
{
copyRandomPartContainerToLists(randomContainer, expect, actual);
while (!expect.empty())
{
CHECK(actual.front() == expect.front());
CHECK(actual.back() == expect.back());
if (rand() % 2)
{
actual.pop_back();
expect.pop_back();
}
else
{
actual.pop_front();
expect.pop_front();
}
}
}
}
SECTION("[push] rely on [clear/begin/end/front/back]")
{
SECTION("push front")
{
actual.push_front(111);
CHECK(actual.front() == 111);
CHECK(actual.back() == 111);
CHECK(*actual.begin() == 111);
CHECK(*--actual.end() == 111);
actual.push_front(222);
CHECK(actual.front() == 222);
CHECK(actual.back() == 111);
CHECK(*actual.begin() == 222);
CHECK(*++actual.begin() == 111);
CHECK(*--actual.end() == 111);
CHECK(*---- actual.end() == 222);
actual.push_front(333);
CHECK(actual.front() == 333);
CHECK(actual.back() == 111);
CHECK(*actual.begin() == 333);
CHECK(*++actual.begin() == 222);
CHECK(*++++ actual.begin() == 111);
CHECK(*--actual.end() == 111);
CHECK(*---- actual.end() == 222);
CHECK(*------ actual.end() == 333);
}
SECTION("push back")
{
actual.push_back(111);
CHECK(actual.front() == 111);
CHECK(actual.back() == 111);
CHECK(*actual.begin() == 111);
CHECK(*--actual.end() == 111);
actual.push_back(222);
CHECK(actual.front() == 111);
CHECK(actual.back() == 222);
CHECK(*actual.begin() == 111);
CHECK(*++actual.begin() == 222);
CHECK(*--actual.end() == 222);
CHECK(*---- actual.end() == 111);
actual.push_back(333);
CHECK(actual.front() == 111);
CHECK(actual.back() == 333);
CHECK(*actual.begin() == 111);
CHECK(*++actual.begin() == 222);
CHECK(*++++ actual.begin() == 333);
CHECK(*--actual.end() == 333);
CHECK(*---- actual.end() == 222);
CHECK(*------ actual.end() == 111);
}
SECTION("random push")
{
std::for_each(randomContainer.begin(), randomContainer.end(), [&](int v)
{
if (rand() % 2)
{
actual.push_back(v);
expect.push_back(v);
}
else
{
actual.push_front(v);
expect.push_front(v);
}
CHECK(actual.front() == expect.front());
CHECK(actual.back() == expect.back());
});
}
}
SECTION("random push/pop rely on [front/back]")
{
SECTION("push is more than pop")
{
std::for_each(randomContainer.begin(), randomContainer.end(), [&](int v)
{
if (rand() % 3)
{
if (rand() % 2)
{
actual.push_back(v);
expect.push_back(v);
}
else
{
actual.push_front(v);
expect.push_front(v);
}
}
else
{
if (rand() % 2)
{
if (!expect.empty())
{
CHECK_NOTHROW(actual.pop_back());
expect.pop_back();
}
}
else if (!expect.empty())
{
CHECK_NOTHROW(actual.pop_front());
expect.pop_front();
}
}
if (!expect.empty())
{
CHECK(actual.front() == expect.front());
CHECK(actual.back() == expect.back());
}
});
}
SECTION("pop is more than push")
{
std::for_each(randomContainer.begin(), randomContainer.end(), [&](int v)
{
if (!(rand() % 3))
{
if (rand() % 2)
{
actual.push_back(v);
expect.push_back(v);
}
else
{
actual.push_front(v);
expect.push_front(v);
}
}
else
{
if (rand() % 2)
{
if (!expect.empty())
{
CHECK_NOTHROW(actual.pop_back());
expect.pop_back();
}
}
else if (!expect.empty())
{
CHECK_NOTHROW(actual.pop_front());
expect.pop_front();
}
}
if (!expect.empty())
{
CHECK(actual.front() == expect.front());
CHECK(actual.back() == expect.back());
}
});
}
}
}
TEST_CASE("capcity rely on [push/pop]")
{
auto randomContainer = getRandomValueContainer();
actualListContainer actual;
CHECK(actual.empty());
CHECK(actual.size() == 0);
CHECK(actual.max_size() >= actual.size());
SECTION("random actions")
{
int expectSize = 0;
std::for_each(randomContainer.begin(), randomContainer.end(), [&](int v)
{
if (!(rand() % 3))
{
if (rand() % 2)
actual.push_back(v);
else
actual.push_front(v);
++expectSize;
}
else
{
if (rand() % 2)
{
if (expectSize != 0)
{
CHECK_NOTHROW(actual.pop_back());
--expectSize;
}
}
else if (expectSize != 0)
{
CHECK_NOTHROW(actual.pop_front());
--expectSize;
}
}
CHECK(actual.size() == expectSize);
CHECK(actual.max_size() >= expectSize);
CHECK((expectSize ^ actual.empty()));
});
}
}
TEST_CASE("iterator rely on [push_back]")
{
auto expectRandomContainer = getRandomValueContainer();
auto actual = copyContainerToList(expectRandomContainer);
SECTION("random move (i++ more than i--) rely on [push_back]")
{
SECTION("iterator")
{
auto actualIt = actual.begin();
auto expectIt = expectRandomContainer.begin();
SECTION("++i/--i")
{
while (expectIt < expectRandomContainer.end())
{
if (expectIt < expectRandomContainer.begin())
{
++expectIt;
++actualIt;
}
if (expectIt > --expectRandomContainer.begin() && expectIt
< expectRandomContainer.end())
CHECK(*actualIt == *expectIt);
if (rand() % 3) // times: ++ > --
{
auto temp = expectIt;
if (++temp < expectRandomContainer.end()) // is not lastest
CHECK(*(++actualIt) == *(++expectIt));
else
{
++actualIt;
++expectIt;
break;
}
}
else if (expectIt > expectRandomContainer.begin())
CHECK(*(--actualIt) == *(--expectIt));
if (expectIt > --expectRandomContainer.begin() && expectIt
< expectRandomContainer.end())
CHECK(*actualIt == *expectIt);
}
}
SECTION("i++/i--")
{
while (expectIt < expectRandomContainer.end())
{
if (expectIt < expectRandomContainer.begin())
{
++expectIt;
++actualIt;
}
if (expectIt > --expectRandomContainer.begin() && expectIt
< expectRandomContainer.end())
CHECK(*actualIt == *expectIt);
if (rand() % 3) // times: ++ > --
CHECK(*(actualIt++) == *(expectIt++));
else if (expectIt > expectRandomContainer.begin())
CHECK(*(actualIt--) == *(expectIt--));
if (expectIt > --expectRandomContainer.begin() && expectIt
< expectRandomContainer.end())
CHECK(*actualIt == *expectIt);
}
}
}
SECTION("reverse iterator")
{
auto actualIt = actual.rbegin();
auto expectIt = expectRandomContainer.rbegin();
SECTION("++i/--i")
{
while (expectIt < expectRandomContainer.rend())
{
if (expectIt < expectRandomContainer.rbegin())
{
++expectIt;
++actualIt;
}
if (expectIt > --expectRandomContainer.rbegin() && expectIt
< expectRandomContainer.rend())
CHECK(*actualIt == *expectIt);
if (rand() % 3) // times: ++ > --
{
auto temp = expectIt;
if (++temp < expectRandomContainer.rend()) // is not lastest
CHECK(*(++actualIt) == *(++expectIt));
else
{
++actualIt;
++expectIt;
break;
}
}
else if (expectIt > expectRandomContainer.rbegin())
CHECK(*(--actualIt) == *(--expectIt));
if (expectIt > --expectRandomContainer.rbegin() && expectIt
< expectRandomContainer.rend())
CHECK(*actualIt == *expectIt);
}
}
SECTION("i++/i--")
{
while (expectIt < expectRandomContainer.rend())
{
if (expectIt < expectRandomContainer.rbegin())
{
++expectIt;
++actualIt;
}
if (expectIt > --expectRandomContainer.rbegin() && expectIt
< expectRandomContainer.rend())
CHECK(*actualIt == *expectIt);
if (rand() % 3) // times: ++ > --
CHECK(*(actualIt++) == *(expectIt++));
else if (expectIt > expectRandomContainer.rbegin())
CHECK(*(actualIt--) == *(expectIt--));
if (expectIt > --expectRandomContainer.rbegin() && expectIt
< expectRandomContainer.rend())
CHECK(*actualIt == *expectIt);
}
}
}
}
SECTION("random move (i-- more than i++) rely on [push_back]")
{
SECTION("iterator")
{
auto actualIt = --actual.end();
auto expectIt = --expectRandomContainer.end();
SECTION("++i/--i rely on [push_back]")
{
while (expectIt > expectRandomContainer.begin())
{
if (expectIt >= expectRandomContainer.end())
{
--expectIt;
--actualIt;
}
if (expectIt > --expectRandomContainer.begin() && expectIt
< expectRandomContainer.end())
CHECK(*actualIt == *expectIt);
if (!(rand() % 3)) // times: ++ < --
{
auto temp = expectIt;
if (++temp < expectRandomContainer.end())
CHECK(*(++actualIt) == *(++expectIt));
else
{
++actualIt;
++expectIt;
break;
}
}
else if (expectIt > expectRandomContainer.begin())
CHECK(*(--actualIt) == *(--expectIt));
if (expectIt > --expectRandomContainer.begin() && expectIt
< expectRandomContainer.end())
CHECK(*actualIt == *expectIt);
}
}
SECTION("i++/i-- rely on [push_back]")
{
while (expectIt > expectRandomContainer.begin())
{
if (expectIt >= expectRandomContainer.end())
{
--expectIt;
--actualIt;
}
if (expectIt > --expectRandomContainer.begin() && expectIt
< expectRandomContainer.end())
CHECK(*actualIt == *expectIt);
if (!(rand() % 3)) // times: ++ < --
CHECK(*actualIt++ == *expectIt++);
else if (expectIt > expectRandomContainer.begin())
CHECK(*actualIt-- == *expectIt--);
if (expectIt > --expectRandomContainer.begin() && expectIt
< expectRandomContainer.end())
CHECK(*actualIt == *expectIt);
}
}
}
SECTION("reverse iterator")
{
auto actualIt = actual.rbegin();
auto expectIt = expectRandomContainer.rbegin();
SECTION("++i/--i rely on [push_back]")
{
while (expectIt > expectRandomContainer.rbegin())
{
if (expectIt >= expectRandomContainer.rend())
{
--expectIt;
--actualIt;
}
if (expectIt > --expectRandomContainer.rbegin() && expectIt
< expectRandomContainer.rend())
CHECK(*actualIt == *expectIt);
if (!(rand() % 3)) // times: ++ < --
{
auto expectItTemp = expectIt;
if (++expectItTemp < expectRandomContainer.rend())
CHECK(*(++actualIt) == *(++expectIt));
else
{
++actualIt;
++expectIt;
break;
}
}
else if (expectIt > expectRandomContainer.rbegin())
CHECK(*(--actualIt) == *(--expectIt));
if (expectIt > --expectRandomContainer.rbegin() && expectIt
< expectRandomContainer.rend())
CHECK(*actualIt == *expectIt);
}
}
SECTION("i++/i-- rely on [push_back]")
{
while (expectIt > expectRandomContainer.rbegin())
{
if (expectIt >= expectRandomContainer.rend())
{
--expectIt;
--actualIt;
}
if (expectIt > --expectRandomContainer.rbegin() && expectIt
< expectRandomContainer.rend())
CHECK(*actualIt == *expectIt);
if (!(rand() % 3)) // times: ++ < --
CHECK(*(actualIt++) == *(expectIt++));
else if (expectIt > expectRandomContainer.rbegin())
CHECK(*(actualIt--) == *(expectIt--));
if (expectIt > --expectRandomContainer.rbegin() && expectIt
< expectRandomContainer.rend())
CHECK(*actualIt == *expectIt);
}
}
}
}
SECTION("[reverse iterator: base] rely on [++/--]")
{
auto expectRandomContainer = getRandomValueContainer();
actualListContainer actual = copyContainerToList(expectRandomContainer);
vectorContainer::reverse_iterator expectReverseBegin(expectRandomContainer.begin());
actualListContainer::const_reverse_iterator actualReverseBegin(actual.begin());
auto expectBaseBegin = expectReverseBegin.base();
auto actualBaseBegin = actualReverseBegin.base();
while (expectBaseBegin != expectRandomContainer.end())
{
CHECK(*expectBaseBegin == *actualBaseBegin);
++expectBaseBegin;
++actualBaseBegin;
}
}
}
TEST_CASE("operations")
{
auto randomContainer = getRandomValueContainer();
expectListContainer expect;
actualListContainer actual;
SECTION("[reverse] rely on [empty/size/begin/end/front/back/push_back/push_front]")
{
SECTION("empty")
{
CHECK(actual.empty());
CHECK(actual.size() == 0);
CHECK(actual.begin() == actual.end());
actual.reverse();
CHECK(actual.empty());
CHECK(actual.size() == 0);
CHECK(actual.begin() == actual.end());
}
SECTION("one nodes")
{
actual.push_back(1);
CHECK(actual.front() == 1);
CHECK(actual.back() == 1);
CHECK(actual.size() == 1);
CHECK_FALSE(actual.empty());
actual.reverse();
CHECK(actual.front() == 1);
CHECK(actual.back() == 1);
CHECK(actual.size() == 1);
CHECK_FALSE(actual.empty());
actual.pop_back();
CHECK_THROWS_AS(actual.front(), std::out_of_range);
CHECK_THROWS_AS(actual.back(), std::out_of_range);
CHECK(actual.size() == 0);
CHECK(actual.empty());
}
SECTION("two nodes")
{
actual.push_back(1);
actual.push_back(2);
CHECK(actual.front() == 1);
CHECK(actual.back() == 2);
CHECK(actual.size() == 2);
CHECK_FALSE(actual.empty());
actual.reverse();
CHECK(actual.front() == 2);
CHECK(actual.back() == 1);
CHECK(actual.size() == 2);
CHECK_FALSE(actual.empty());
actual.pop_back();
CHECK(actual.front() == 2);
CHECK(actual.back() == 2);
CHECK(actual.size() == 1);
CHECK_FALSE(actual.empty());
actual.pop_back();
CHECK_THROWS_AS(actual.front(), std::out_of_range);
CHECK_THROWS_AS(actual.back(), std::out_of_range);
CHECK(actual.size() == 0);
CHECK(actual.empty());
}
SECTION("three nodes")
{
actual.push_back(1);
actual.push_back(2);
actual.push_back(3);
CHECK(actual.front() == 1);
CHECK(actual.back() == 3);
CHECK(actual.size() == 3);
CHECK_FALSE(actual.empty());
actual.reverse();
CHECK(actual.front() == 3);
CHECK(actual.back() == 1);
CHECK(actual.size() == 3);
CHECK_FALSE(actual.empty());
actual.pop_back();
CHECK(actual.front() == 3);
CHECK(actual.back() == 2);
CHECK(actual.size() == 2);
CHECK_FALSE(actual.empty());
actual.pop_back();
CHECK(actual.front() == 3);
CHECK(actual.back() == 3);
CHECK(actual.size() == 1);
CHECK_FALSE(actual.empty());
actual.pop_back();
CHECK_THROWS_AS(actual.front(), std::out_of_range);
CHECK_THROWS_AS(actual.back(), std::out_of_range);
CHECK(actual.size() == 0);
CHECK(actual.empty());
}
SECTION("random nodes")
{
while (!randomContainer.empty())
{
auto v = randomContainer.back();
if (rand() % 2)
{
if (rand() % 2)
{
actual.push_back(v);
expect.push_back(v);
}
else
{
actual.push_front(v);
expect.push_front(v);
}
}
else
{
if (rand() % 2)
{
if (!expect.empty())
{
actual.pop_back();
expect.pop_back();
}
}
else if (!expect.empty())
{
actual.pop_front();
expect.pop_front();
}
}
if (!expect.empty())
{
actual.reverse();
reverse(actual.begin(), actual.end());
actual.reverse();
reverse(actual.begin(), actual.end());
actual.reverse();
reverse(expect.begin(), expect.end());
}
CHECK(actual.size() == expect.size());
CHECK((expect.size() ^ actual.empty()));
if (!expect.empty())
{
CHECK(expect.front() == actual.front());
CHECK(expect.back() == actual.back());
}
randomContainer.pop_back();
}
}
}
}
TEST_CASE("stl algorithm-compatible")
{
vectorContainer randomContainer = getRandomValueContainer();
expectListContainer expect;
actualListContainer actual;
expectListContainer::iterator expectPos;
actualListContainer::iterator actualPos;
int randomValue;
size_t sz;
auto randomSmallContainer = getRandomValueContainer(SmallRandomSize);
copyRandomPartContainerToLists(randomContainer, expect, actual);
SECTION("std::for_each")
{
expectPos = expect.begin();
std::for_each(actual.begin(), actual.end(), [&](int v)
{
CHECK(v == *expectPos++);
});
}
SECTION("std::find")
{
CHECK(*actual.begin() == *std::find(actual.begin(), actual.end(), *expect.begin()));
CHECK(*++actual.begin() == *std::find(actual.begin(), actual.end(), *++expect.begin()));
CHECK(*--actual.end() == *std::find(actual.begin(), actual.end(), *--expect.end()));
}
SECTION("std::equal")
{
CHECK(std::equal(expect.begin(), expect.end(), actual.begin()));
}
}
TEST_CASE("others")
{
SECTION("random nodes")
{
// todo: test more functions insert/find/unique/sort/erase
auto randomContainer = getRandomValueContainer();
actualListContainer actual;
int expectSize = 1;
expectListContainer expect;
expect.push_front(randomContainer.front());
actual.push_front(randomContainer.front());
std::for_each(++randomContainer.begin(), randomContainer.end(), [&](int v)
{
if (rand() % 2)
{
if (rand() % 2)
{
actual.push_back(v);
expect.push_back(v);
}
else
{
actual.push_front(v);
expect.push_front(v);
}
++expectSize;
}
else
{
if (rand() % 2)
{
if (expectSize != 0)
{
CHECK_NOTHROW(actual.pop_back());
CHECK_NOTHROW(expect.pop_back());
--expectSize;
}
}
else if (expectSize != 0)
{
CHECK_NOTHROW(actual.pop_front());
CHECK_NOTHROW(expect.pop_front());
--expectSize;
}
}
CHECK(actual.size() == expectSize);
CHECK((expectSize ^ actual.empty()));
if (!expect.empty())
{
CHECK(expect.front() == actual.front());
CHECK(expect.back() == actual.back());
}
});
}
SECTION("efficiency")
{
// todo
}
}
#endif // XOR_LINKED_LIST_TEST_CPP
| 81,597
|
C++
|
.cpp
| 1,828
| 28.765864
| 100
| 0.489983
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,110
|
test_bag.cpp
|
OpenGenus_cosmos/code/data_structures/test/bag/test_bag.cpp
|
//Needed for random and vector
#include <vector>
#include <string>
#include <cstdlib>
#include <iostream>
using std::cout;
using std::endl;
using std::string;
using std::vector;
//Bag Class Declaration
class Bag
{
private:
vector<string> items;
int bagSize;
public:
Bag();
void add(string);
bool isEmpty();
int sizeOfBag();
string remove();
};
Bag::Bag()
{
bagSize = 0;
}
void Bag::add(string item)
{
//Store item in last element of vector
items.push_back(item);
//Increase the size
bagSize++;
}
bool Bag::isEmpty(){
//True
if(bagSize == 0){
return true;
}
//False
else{
return false;
}
}
int Bag::sizeOfBag(){
return bagSize;
}
string Bag::remove(){
//Get random item
int randIndx = rand() % bagSize;
string removed = items.at(randIndx);
//Remove from bag
items.erase(items.begin() + randIndx);
bagSize--;
//Return removed item
return removed;
}
int main()
{
//Create bag
Bag bag;
//Get current size
cout << "Bag size: " << bag.sizeOfBag() << endl;
//Bag empty?
cout << "Is bag empty? " << bag.isEmpty() << endl;
//Add some items
cout << "Adding red..." << endl;
bag.add("red");
cout << "Bag size: " << bag.sizeOfBag() << endl;
cout << "Adding blue..." << endl;
bag.add("blue");
cout << "Bag size: " << bag.sizeOfBag() << endl;
cout << "Adding yellow..." << endl;
bag.add("yellow");
cout << "Bag size: " << bag.sizeOfBag() << endl;
//Remove an item
cout << "Removed " << bag.remove() << " from bag." << endl;
//Get current size
cout << "Bag size: " << bag.sizeOfBag() << endl;
//Bag empty?
cout << "Is bag empty? " << bag.isEmpty() << endl;
//Remove an item
cout << "Removed " << bag.remove() << " from bag." << endl;
//Get current size
cout << "Bag size: " << bag.sizeOfBag() << endl;
//Bag empty?
cout << "Is bag empty? " << bag.isEmpty() << endl;
//Remove last item
cout << "Removed " << bag.remove() << " from bag." << endl;
//Get current size
cout << "Bag size: " << bag.sizeOfBag() << endl;
//Bag empty?
cout << "Is bag empty? " << bag.isEmpty() << endl;
}
| 2,159
|
C++
|
.cpp
| 93
| 20.11828
| 61
| 0.606686
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,111
|
test_generic_segment_tree.cpp
|
OpenGenus_cosmos/code/data_structures/test/tree/segment_tree/test_generic_segment_tree.cpp
|
#include <algorithm>
#include <iostream>
#include <vector>
// Note that the below line includes a translation unit and not header file
#include "../../../src/tree/segment_tree/generic_segment_tree.cpp"
#define ASSERT(value, expected_value, message) \
{ \
if (value != expected_value) \
std::cerr << "[assertion failed]\n" \
<< " Line: " << __LINE__ << '\n' \
<< " File: " << __FILE__ << '\n' \
<< "Message: " << message << std::endl; \
else \
std::cerr << "[assertion passed]: " << message << std::endl; \
}
/**
* This program tests the generic segment tree implementation that can be found in the include location above.
* The implementation requires C++20 in order to compile.
*
* Compilation: g++ test_generic_segment_tree.cpp -o test_generic_segment_tree -Wall -Wextra -pedantic -std=c++20 -O3
*/
constexpr bool is_multitest = false;
constexpr int32_t inf32 = int32_t(1) << 30;
constexpr int64_t inf64 = int64_t(1) << 60;
void test () {
std::vector <int> values = { 1, 2, 3, 4, 5 };
int n = values.size();
arrow::SegmentTree <int> binaryTreeSum (n, values, [] (auto l, auto r) {
return l + r;
});
arrow::SegmentTree <int, arrow::TreeMemoryLayout::EulerTour> eulerTourTreeSum (n, values, [] (auto l, auto r) {
return l + r;
});
ASSERT(binaryTreeSum.rangeQuery(0, 4), 15, "binaryTreeSum.rangeQuery(0, 4) == 15");
ASSERT(binaryTreeSum.rangeQuery(1, 2), 5, "binaryTreeSum.rangeQuery(1, 2) == 5");
ASSERT(binaryTreeSum.rangeQuery(4, 4), 5, "binaryTreeSum.rangeQuery(4, 4) == 5");
ASSERT(binaryTreeSum.rangeQuery(2, 4), 12, "binaryTreeSum.rangeQuery(2, 4) == 12");
ASSERT(binaryTreeSum.rangeQuery(0, 3), 10, "binaryTreeSum.rangeQuery(0, 3) == 10");
ASSERT(eulerTourTreeSum.rangeQuery(0, 4), 15, "eulerTourTreeSum.rangeQuery(0, 4) == 15");
ASSERT(eulerTourTreeSum.rangeQuery(1, 2), 5, "eulerTourTreeSum.rangeQuery(1, 2) == 5");
ASSERT(eulerTourTreeSum.rangeQuery(4, 4), 5, "eulerTourTreeSum.rangeQuery(4, 4) == 5");
ASSERT(eulerTourTreeSum.rangeQuery(2, 4), 12, "eulerTourTreeSum.rangeQuery(2, 4) == 12");
ASSERT(eulerTourTreeSum.rangeQuery(0, 3), 10, "eulerTourTreeSum.rangeQuery(0, 3) == 10");
binaryTreeSum.pointUpdate(2, 10);
eulerTourTreeSum.pointUpdate(0, 8);
ASSERT(binaryTreeSum.pointQuery(2), 10, "binaryTreeSum.pointQuery(2) == 10");
ASSERT(binaryTreeSum.rangeQuery(1, 3), 16, "binaryTreeSum.rangeQuery(1, 3) == 16");
ASSERT(binaryTreeSum.rangeQuery(0, 4), 22, "binaryTreeSum.rangeQuery(0, 4) == 22");
ASSERT(eulerTourTreeSum.pointQuery(0), 8, "euler_tour_sum.pointQuery(0) == 8");
ASSERT(eulerTourTreeSum.rangeQuery(1, 3), 9, "euler_tour_sum.rangeQuery(1, 3) == 9");
ASSERT(eulerTourTreeSum.rangeQuery(0, 4), 22, "euler_tour_sum.rangeQuery(0, 4) == 22");
values = {
2, -4, 3, -1, 4, 1, -2, 5
};
n = values.size();
struct node {
int value;
int maxPrefix;
int maxSuffix;
int maxSubsegment;
node (int v = 0) {
int m = std::max(v, 0);
value = v;
maxPrefix = m;
maxSuffix = m;
maxSubsegment = m;
}
};
std::vector <node> node_values;
for (auto i: values) {
node_values.push_back(node(i));
}
arrow::SegmentTree <node> binaryTreeMaxSubsegment (n, node_values, [] (auto l, auto r) {
node result;
result.value = l.value + r.value;
result.maxPrefix = std::max(l.maxPrefix, l.value + r.maxPrefix);
result.maxSuffix = std::max(l.maxSuffix + r.value, r.maxSuffix);
result.maxSubsegment = std::max({l.maxSubsegment, r.maxSubsegment, l.maxSuffix + r.maxPrefix});
return result;
});
ASSERT(binaryTreeMaxSubsegment.rangeQuery(0, 7).value, 8, "binaryTreeMaxSubsegment.rangeQuery(0, 7).value == 8");
ASSERT(binaryTreeMaxSubsegment.rangeQuery(3, 5).value, 4, "binaryTreeMaxSubsegment.rangeQuery(3, 5).value == 4");
ASSERT(binaryTreeMaxSubsegment.rangeQuery(2, 6).value, 5, "binaryTreeMaxSubsegment.rangeQuery(2, 6).value == 5");
ASSERT(binaryTreeMaxSubsegment.rangeQuery(1, 4).value, 2, "binaryTreeMaxSubsegment.rangeQuery(1, 4).value == 2");
ASSERT(binaryTreeMaxSubsegment.rangeQuery(7, 7).value, 5, "binaryTreeMaxSubsegment.rangeQuery(7, 7).value == 5");
ASSERT(binaryTreeMaxSubsegment.rangeQuery(0, 4).value, 4, "binaryTreeMaxSubsegment.rangeQuery(0, 4).value == 4");
binaryTreeMaxSubsegment.pointUpdate(5, 4);
binaryTreeMaxSubsegment.pointUpdate(3, -7);
binaryTreeMaxSubsegment.pointUpdate(1, 3);
ASSERT(binaryTreeMaxSubsegment.rangeQuery(0, 7).value, 12, "binaryTreeMaxSubsegment.rangeQuery(0, 7).value == 12");
ASSERT(binaryTreeMaxSubsegment.rangeQuery(3, 5).value, 1, "binaryTreeMaxSubsegment.rangeQuery(3, 5).value == 1");
ASSERT(binaryTreeMaxSubsegment.rangeQuery(2, 6).value, 2, "binaryTreeMaxSubsegment.rangeQuery(2, 6).value == 2");
ASSERT(binaryTreeMaxSubsegment.rangeQuery(1, 4).value, 3, "binaryTreeMaxSubsegment.rangeQuery(1, 4).value == 3");
ASSERT(binaryTreeMaxSubsegment.rangeQuery(7, 7).value, 5, "binaryTreeMaxSubsegment.rangeQuery(7, 7).value == 5");
ASSERT(binaryTreeMaxSubsegment.rangeQuery(0, 4).value, 5, "binaryTreeMaxSubsegment.rangeQuery(0, 4).value == 5");
}
int main () {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
test();
return 0;
}
| 5,506
|
C++
|
.cpp
| 102
| 50.137255
| 117
| 0.660216
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,112
|
test_union_find.cpp
|
OpenGenus_cosmos/code/data_structures/test/tree/multiway_tree/union_find/test_union_find.cpp
|
#include <iostream>
#include <cassert>
#include "../../../../src/tree/multiway_tree/union_find/union_find_dynamic.cpp"
int main()
{
UnionFind<int> unionFind;
unionFind.merge(3, 4);
unionFind.merge(3, 8);
unionFind.merge(0, 8);
unionFind.merge(1, 3);
unionFind.merge(7, 9);
unionFind.merge(5, 9);
// Now the components are:
// 0 1 3 4 8
// 5 7 9
assert(unionFind.connected(0, 1));
assert(unionFind.connected(0, 3));
assert(unionFind.connected(0, 4));
assert(unionFind.connected(0, 8));
assert(unionFind.connected(1, 3));
assert(unionFind.connected(1, 4));
assert(unionFind.connected(1, 8));
assert(unionFind.connected(3, 4));
assert(unionFind.connected(3, 8));
assert(unionFind.connected(4, 8));
assert(unionFind.connected(5, 7));
assert(unionFind.connected(5, 9));
assert(unionFind.connected(7, 9));
assert(!unionFind.connected(0, 5));
assert(!unionFind.connected(0, 7));
assert(!unionFind.connected(0, 9));
assert(!unionFind.connected(1, 5));
assert(!unionFind.connected(1, 7));
assert(!unionFind.connected(1, 9));
assert(!unionFind.connected(3, 5));
assert(!unionFind.connected(3, 7));
assert(!unionFind.connected(3, 9));
assert(!unionFind.connected(4, 5));
assert(!unionFind.connected(4, 7));
assert(!unionFind.connected(4, 9));
assert(!unionFind.connected(8, 5));
assert(!unionFind.connected(8, 7));
assert(!unionFind.connected(8, 9));
return 0;
}
| 1,513
|
C++
|
.cpp
| 45
| 29.044444
| 79
| 0.662338
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,113
|
test_is_same.cpp
|
OpenGenus_cosmos/code/data_structures/test/tree/binary_tree/binary_tree/is_same/test_is_same.cpp
|
#define CATCH_CONFIG_MAIN
#ifndef TEST_TREE_COMPARER
#define TEST_TREE_COMPARER
#include <memory>
#include <functional>
#include <utility>
#include "../../../../../../../test/c++/catch.hpp"
#include "../../../../../src/tree/binary_tree/binary_tree/is_same/is_same.cpp"
#include "../../../../../src/tree/binary_tree/binary_tree/serializer/serializer.cpp"
#include "../../../../../src/tree/binary_tree/binary_tree/node/node.cpp"
TEST_CASE("check two tree is same", "[isSameTree]") {
TreeSerializer serializer;
std::shared_ptr<TreeNode<int>> root_a, root_b;
TreeComparer<int> comparer;
SECTION("has empty tree") {
root_a = serializer.deserialize("# ");
root_b = serializer.deserialize("# ");
REQUIRE(comparer.isSameTree(root_a, root_b));
root_a = serializer.deserialize("1 # # ");
root_b = serializer.deserialize("1 # # ");
REQUIRE(comparer.isSameTree(root_a, root_b));
root_a = serializer.deserialize("# ");
root_b = serializer.deserialize("1 # # ");
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
}
SECTION("has same value") {
root_a = serializer.deserialize("1 # # ");
root_b = serializer.deserialize("1 # # ");
REQUIRE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE(comparer.isSameTree(root_a, root_b));
root_a = serializer.deserialize("1 # 2 # # ");
root_b = serializer.deserialize("1 # 2 # # ");
REQUIRE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE(comparer.isSameTree(root_a, root_b));
root_a = serializer.deserialize("1 2 3 4 # # 5 # # # #");
root_b = serializer.deserialize("1 2 3 4 # # 5 # # # #");
REQUIRE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE(comparer.isSameTree(root_a, root_b));
}
SECTION("has not same value") {
root_a = serializer.deserialize("# ");
root_b = serializer.deserialize("1 # # ");
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
root_a = serializer.deserialize("1 # # ");
root_b = serializer.deserialize("2 # # ");
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
root_a = serializer.deserialize("1 # 2 # # ");
root_b = serializer.deserialize("1 # 3 # # ");
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
root_a = serializer.deserialize("1 2 # # # ");
root_b = serializer.deserialize("1 3 # # # ");
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
root_a = serializer.deserialize("1 2 3 4 # # 5 # # # #");
root_b = serializer.deserialize("1 2 3 4 # # 6 # # # #");
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
}
SECTION("has reflex node") {
root_a = serializer.deserialize("1 2 # # 3 # # ");
root_b = serializer.deserialize("1 3 # # 2 # #");
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
root_a = serializer.deserialize("1 2 # 3 # # 4 # # ");
root_b = serializer.deserialize("1 4 # # 2 3 # # # ");
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
root_a = serializer.deserialize("1 2 3 # # # 4 # # ");
root_b = serializer.deserialize("1 4 # # 2 # 3 # # ");
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
}
}
#endif // TEST_TREE_COMPARER
| 4,291
|
C++
|
.cpp
| 90
| 40.133333
| 84
| 0.595363
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,114
|
test_path_sum_for_sum_of_whole_paths.cpp
|
OpenGenus_cosmos/code/data_structures/test/tree/binary_tree/binary_tree/path_sum/test_path_sum_for_sum_of_whole_paths.cpp
|
#define CATCH_CONFIG_MAIN
#include "../../../../../../../test/c++/catch.hpp"
#include <vector>
#include <memory>
#include <queue>
#include "../../../../../src/tree/binary_tree/binary_tree/node/node.cpp"
#include "../../../../../src/tree/binary_tree/binary_tree/serializer/serializer.cpp"
#include "../../../../../src/tree/binary_tree/binary_tree/path_sum/path_sum.hpp"
using Node = TreeNode<int>;
using PNode = std::shared_ptr<Node>;
TEST_CASE("sum of paths between root to bottom") {
PathSum<int> sol;
size_t (PathSum<int>::* pf)(PNode, int) = &PathSum<int>::countPathsOfSum;
TreeSerializer ts;
PNode root = nullptr;
auto res = (sol.*pf)(root, 0);
SECTION("give empty tree") {
root = ts.deserialize("# ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
CHECK(res == 0);
}
}
SECTION("give one node") {
root = ts.deserialize("1 # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 1)
CHECK(res == 1);
else
CHECK(res == 0);
}
}
SECTION("give balance tree") {
root = ts.deserialize("1 2 # # 3 # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 3 || i == 4)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 2 4 # # # 3 5 # # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 7 || i == 9)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 2 4 # # # 3 # 5 # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 7 || i == 9)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 2 # 4 # # 3 5 # # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 7 || i == 9)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 2 # 4 # # 3 # 5 # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 7 || i == 9)
CHECK(res == 1);
else
CHECK(res == 0);
}
}
SECTION("give unbalance tree") {
SECTION("left is more deep") {
root = ts.deserialize("1 2 # # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 3)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 2 3 # # # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 6)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 2 # 3 # # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 6)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 2 4 # # # 3 # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 4 || i == 7)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 2 # 4 # # 3 # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 4 || i == 7)
CHECK(res == 1);
else
CHECK(res == 0);
}
}
SECTION("right is more deep") {
root = ts.deserialize("1 # 2 # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 3)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 # 2 3 # # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 6)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 # 2 # 3 # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 6)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 2 # # 3 4 # # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 3 || i == 8)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 2 # # 3 # 4 # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 3 || i == 8)
CHECK(res == 1);
else
CHECK(res == 0);
}
}
}
}
| 5,643
|
C++
|
.cpp
| 179
| 18.681564
| 84
| 0.3277
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,115
|
test_path_sum_for_whole_paths.cpp
|
OpenGenus_cosmos/code/data_structures/test/tree/binary_tree/binary_tree/path_sum/test_path_sum_for_whole_paths.cpp
|
#define CATCH_CONFIG_MAIN
#include "../../../../../../../test/c++/catch.hpp"
#include <vector>
#include <memory>
#include <queue>
#include "../../../../../src/tree/binary_tree/binary_tree/node/node.cpp"
#include "../../../../../src/tree/binary_tree/binary_tree/serializer/serializer.cpp"
#include "../../../../../src/tree/binary_tree/binary_tree/path_sum/path_sum.hpp"
using Node = TreeNode<int>;
using PNode = std::shared_ptr<Node>;
bool isSame(std::vector<std::vector<int>> &a, std::vector<std::vector<int>> &b)
{
std::sort(a.begin(), a.end());
std::sort(b.begin(), b.end());
if (a.size() != b.size())
return false;
for (size_t i = 0; i < a.size(); ++i)
{
if (a.at(i).size() != b.at(i).size())
return false;
for (size_t j = 0; j < a.at(i).size(); ++j)
if (a.at(i).at(j) != b.at(i).at(j))
return false;
}
return true;
}
TEST_CASE("paths between root to leaf") {
PathSum<int> sol;
std::vector<std::vector<int>> (PathSum<int>::* pf)(PNode, int) = &PathSum<int>::getPathsOfSum;
TreeSerializer ts;
PNode root = nullptr;
auto res = (sol.*pf)(root, 0);
std::vector<std::vector<int>> expect{};
SECTION("give empty tree") {
root = ts.deserialize("# ");
res = (sol.*pf)(root, 0);
expect = {};
CHECK(isSame(res, expect));
}
SECTION("give one node") {
root = ts.deserialize("1 # # ");
res = (sol.*pf)(root, 0);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 1);
expect = {{1}};
CHECK(isSame(res, expect));
}
SECTION("user define") {
root = ts.deserialize("5 4 11 7 # # 2 # # # 8 13 # # 4 5 # # 1 # # ");
res = (sol.*pf)(root, 22);
expect = {{5, 4, 11, 2}, {5, 8, 4, 5}};
CHECK(isSame(res, expect));
}
SECTION("give balance tree") {
root = ts.deserialize("1 2 # # 3 # # ");
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {{1, 2}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 4);
expect = {{1, 3}};
CHECK(isSame(res, expect));
root = ts.deserialize("1 2 4 # # # 3 5 # # # ");
res = (sol.*pf)(root, 7);
expect = {{1, 2, 4}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 9);
expect = {{1, 3, 5}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 4);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 6);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 8);
expect = {};
CHECK(isSame(res, expect));
root = ts.deserialize("1 2 4 # # # 3 # 5 # # ");
res = (sol.*pf)(root, 7);
expect = {{1, 2, 4}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 9);
expect = {{1, 3, 5}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 4);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 6);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 8);
expect = {};
CHECK(isSame(res, expect));
root = ts.deserialize("1 2 # 4 # # 3 5 # # # ");
res = (sol.*pf)(root, 7);
expect = {{1, 2, 4}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 9);
expect = {{1, 3, 5}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 4);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 6);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 8);
expect = {};
CHECK(isSame(res, expect));
root = ts.deserialize("1 2 # 4 # # 3 # 5 # # ");
res = (sol.*pf)(root, 7);
expect = {{1, 2, 4}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 9);
expect = {{1, 3, 5}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 4);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 6);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 8);
expect = {};
CHECK(isSame(res, expect));
}
SECTION("give unbalance tree") {
SECTION("left is more deep") {
root = ts.deserialize("1 2 # # # ");
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {{1, 2}};
CHECK(isSame(res, expect));
root = ts.deserialize("1 2 3 # # # # ");
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 6);
expect = {{1, 2, 3}};
CHECK(isSame(res, expect));
root = ts.deserialize("1 2 # 3 # # # ");
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 6);
expect = {{1, 2, 3}};
CHECK(isSame(res, expect));
root = ts.deserialize("1 2 4 # # # 3 # # ");
res = (sol.*pf)(root, 4);
expect = {{1, 3}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 7);
expect = {{1, 2, 4}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 6);
expect = {};
CHECK(isSame(res, expect));
root = ts.deserialize("1 2 # 4 # # 3 # # ");
res = (sol.*pf)(root, 4);
expect = {{1, 3}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 7);
expect = {{1, 2, 4}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 6);
expect = {};
CHECK(isSame(res, expect));
}
SECTION("right is more deep") {
root = ts.deserialize("1 # 2 # # ");
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {{1, 2}};
CHECK(isSame(res, expect));
root = ts.deserialize("1 # 2 3 # # # ");
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 6);
expect = {{1, 2, 3}};
CHECK(isSame(res, expect));
root = ts.deserialize("1 # 2 # 3 # # ");
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 6);
expect = {{1, 2, 3}};
CHECK(isSame(res, expect));
root = ts.deserialize("1 2 # # 3 4 # # # ");
res = (sol.*pf)(root, 3);
expect = {{1, 2}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 8);
expect = {{1, 3, 4}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 4);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 7);
expect = {};
CHECK(isSame(res, expect));
root = ts.deserialize("1 2 # # 3 # 4 # # ");
res = (sol.*pf)(root, 3);
expect = {{1, 2}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 8);
expect = {{1, 3, 4}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 4);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 7);
expect = {};
CHECK(isSame(res, expect));
}
}
}
| 12,284
|
C++
|
.cpp
| 360
| 23.691667
| 98
| 0.427695
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,116
|
test_path_sum_for_sum_of_part_paths.cpp
|
OpenGenus_cosmos/code/data_structures/test/tree/binary_tree/binary_tree/path_sum/test_path_sum_for_sum_of_part_paths.cpp
|
#define CATCH_CONFIG_MAIN
#include "../../../../../../../test/c++/catch.hpp"
#include <vector>
#include <memory>
#include <queue>
#include "../../../../../src/tree/binary_tree/binary_tree/node/node.cpp"
#include "../../../../../src/tree/binary_tree/binary_tree/serializer/serializer.cpp"
#include "../../../../../src/tree/binary_tree/binary_tree/path_sum/path_sum.hpp"
using Node = TreeNode<int>;
using PNode = std::shared_ptr<Node>;
TEST_CASE("sum of paths between any node") {
PathSum<int> sol(PathSum<int>::PathType::Part);
size_t (PathSum<int>::* pf)(PNode, int) = &PathSum<int>::countPathsOfSum;
TreeSerializer ts;
PNode root = nullptr;
auto res = (sol.*pf)(root, 0);
SECTION("give empty tree") {
root = ts.deserialize("# ");
res = (sol.*pf)(root, 0);
CHECK(res == 0);
}
SECTION("give one node") {
root = ts.deserialize("1 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
}
SECTION("give balance tree") {
root = ts.deserialize("0 1 # # 1 # # ");
res = (sol.*pf)(root, 0);
CHECK(res == 1);
res = (sol.*pf)(root, 1);
CHECK(res == 4);
root = ts.deserialize("1 2 # # 3 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 4);
CHECK(res == 1);
root = ts.deserialize("0 1 1 # # # 1 1 # # # ");
res = (sol.*pf)(root, 0);
CHECK(res == 1);
res = (sol.*pf)(root, 1);
CHECK(res == 6);
res = (sol.*pf)(root, 2);
CHECK(res == 4);
root = ts.deserialize("0 1 # 1 # # 1 # 1 # # ");
res = (sol.*pf)(root, 0);
CHECK(res == 1);
res = (sol.*pf)(root, 1);
CHECK(res == 6);
res = (sol.*pf)(root, 2);
CHECK(res == 4);
root = ts.deserialize("1 2 4 # # # 3 5 # # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 4);
CHECK(res == 2);
res = (sol.*pf)(root, 5);
CHECK(res == 1);
res = (sol.*pf)(root, 6);
CHECK(res == 1);
res = (sol.*pf)(root, 7);
CHECK(res == 1);
res = (sol.*pf)(root, 8);
CHECK(res == 1);
res = (sol.*pf)(root, 9);
CHECK(res == 1);
root = ts.deserialize("1 2 4 # # # 3 # 5 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 4);
CHECK(res == 2);
res = (sol.*pf)(root, 5);
CHECK(res == 1);
res = (sol.*pf)(root, 6);
CHECK(res == 1);
res = (sol.*pf)(root, 7);
CHECK(res == 1);
res = (sol.*pf)(root, 8);
CHECK(res == 1);
res = (sol.*pf)(root, 9);
CHECK(res == 1);
root = ts.deserialize("1 2 # 4 # # 3 5 # # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 4);
CHECK(res == 2);
res = (sol.*pf)(root, 5);
CHECK(res == 1);
res = (sol.*pf)(root, 6);
CHECK(res == 1);
res = (sol.*pf)(root, 7);
CHECK(res == 1);
res = (sol.*pf)(root, 8);
CHECK(res == 1);
res = (sol.*pf)(root, 9);
CHECK(res == 1);
root = ts.deserialize("1 2 # 4 # # 3 # 5 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 4);
CHECK(res == 2);
res = (sol.*pf)(root, 5);
CHECK(res == 1);
res = (sol.*pf)(root, 6);
CHECK(res == 1);
res = (sol.*pf)(root, 7);
CHECK(res == 1);
res = (sol.*pf)(root, 8);
CHECK(res == 1);
res = (sol.*pf)(root, 9);
CHECK(res == 1);
}
SECTION("give unbalance tree") {
SECTION("left is more deep") {
root = ts.deserialize("1 2 # # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 1);
root = ts.deserialize("1 2 3 # # # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 5);
CHECK(res == 1);
root = ts.deserialize("1 2 # 3 # # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 5);
CHECK(res == 1);
root = ts.deserialize("1 1 1 # # # 1 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 4);
res = (sol.*pf)(root, 2);
CHECK(res == 3);
res = (sol.*pf)(root, 3);
CHECK(res == 1);
root = ts.deserialize("1 1 # 1 # # 1 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 4);
res = (sol.*pf)(root, 2);
CHECK(res == 3);
res = (sol.*pf)(root, 3);
CHECK(res == 1);
root = ts.deserialize("1 2 4 # # # 3 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 4);
CHECK(res == 2);
res = (sol.*pf)(root, 6);
CHECK(res == 1);
root = ts.deserialize("1 2 # 4 # # 3 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 4);
CHECK(res == 2);
res = (sol.*pf)(root, 6);
CHECK(res == 1);
}
SECTION("right is more deep") {
root = ts.deserialize("1 # 2 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 1);
root = ts.deserialize("1 # 2 3 # # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 5);
CHECK(res == 1);
root = ts.deserialize("1 # 2 # 3 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 5);
CHECK(res == 1);
root = ts.deserialize("1 1 # # 1 1 # # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 4);
res = (sol.*pf)(root, 2);
CHECK(res == 3);
res = (sol.*pf)(root, 3);
CHECK(res == 1);
root = ts.deserialize("1 1 # # 1 # 1 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 4);
res = (sol.*pf)(root, 2);
CHECK(res == 3);
res = (sol.*pf)(root, 3);
CHECK(res == 1);
root = ts.deserialize("1 2 # # 3 4 # # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 4);
CHECK(res == 2);
res = (sol.*pf)(root, 7);
CHECK(res == 1);
root = ts.deserialize("1 2 # # 3 # 4 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 4);
CHECK(res == 2);
res = (sol.*pf)(root, 7);
CHECK(res == 1);
}
}
}
| 8,833
|
C++
|
.cpp
| 261
| 23.436782
| 84
| 0.392276
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,117
|
test_diameter.cpp
|
OpenGenus_cosmos/code/data_structures/test/tree/binary_tree/binary_tree/diameter/test_diameter.cpp
|
#define CATCH_CONFIG_MAIN
#include "../../../../../../../test/c++/catch.hpp"
#include "../../../../../src/tree/binary_tree/binary_tree/serializer/serializer.cpp"
#include "../../../../../src/tree/binary_tree/binary_tree/node/node.cpp"
#include "../../../../../src/tree/binary_tree/binary_tree/diameter/diameter.cpp"
#include <string>
TEST_CASE("diameter of binary tree")
{
TreeSerializer ts;
std::string str;
SECTION("empty tree")
{
str = "#";
CHECK(diameter<std::shared_ptr<TreeNode<int>>>(ts.deserialize(str)) == 0);
}
SECTION("one-node tree")
{
str = "1 # #";
CHECK(diameter<std::shared_ptr<TreeNode<int>>>(ts.deserialize(str)) == 1);
}
SECTION("non-empty tree")
{
/*
* 1
* / \
* 2 2
* / \
* 3 3
* / \
* 4 4
* /
* 5
*/
str = "1 2 3 4 5 # # # # 3 # 4 # # 2 # #";
CHECK(diameter<std::shared_ptr<TreeNode<int>>>(ts.deserialize(str)) == 6);
/*
* 1
* / \
* 2 2
* / \
* 3 3
* / \
* 4 4
* / \
* 5 5
*/
str = "1 2 3 4 5 # # # # 3 # 4 # 5 # # 2 # #";
CHECK(diameter<std::shared_ptr<TreeNode<int>>>(ts.deserialize(str)) == 7);
/*
* 1
* / \
* 2 2
* / \ /
* 3 3 3
* / /\ /
* 4 4 4 4
* / /
* 5 5
*/
str = "1 2 3 4 5 # # # # 3 4 # # 4 # # 2 3 4 5 # # # # #";
CHECK(diameter<std::shared_ptr<TreeNode<int>>>(ts.deserialize(str)) == 9);
}
}
| 1,840
|
C++
|
.cpp
| 63
| 21.47619
| 84
| 0.370977
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,118
|
maxHeap.cpp
|
OpenGenus_cosmos/code/data_structures/src/maxHeap/maxHeap.cpp
|
#include "maxHeap.h"
using namespace std;
void maxHeap::heapifyAdd(int idx)
{
int root = (idx-1)/2;
if(heap[idx]>heap[root])
{
int temp = heap[root];
heap[root] = heap[idx];
heap[idx] = temp;
heapifyAdd(root);
}
}
void maxHeap::heapifyRemove(int idx)
{
int max = idx;
int leftIdx = idx*2+1;
int rightIdx = idx*2+2;
if(leftIdx<currSize&& heap[leftIdx]>heap[idx])
{
max=leftIdx;
}
if(rightIdx<currSize&& heap[rightIdx]>heap[max])
{
max=rightIdx;
}
if(max!=idx) // swap
{
int temp = heap[max];
heap[max] = heap[idx];
heap[idx] = temp;
heapifyRemove(max);
}
}
maxHeap::maxHeap(int capacity)
{
heap = new int[capacity] ;
currSize = 0;
this->capacity = capacity;
}
void maxHeap::insert(int itm)
{
if(currSize==capacity)
return;
heap[currSize] = itm;
currSize++;
heapifyAdd(currSize-1);
}
void maxHeap::remove()
{
if (currSize==0)
return;
heap[0] = heap[currSize-1];
currSize--;
heapifyRemove(0);
}
void maxHeap::print()
{
for(int i =0; i<currSize;i++)
{
cout<< heap[i];
}
cout<<endl;
}
| 1,211
|
C++
|
.cpp
| 64
| 14.3125
| 52
| 0.576049
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,119
|
minqueue.cpp
|
OpenGenus_cosmos/code/data_structures/src/minqueue/minqueue.cpp
|
#include <deque>
#include <iostream>
using namespace std;
//this is so the minqueue can be used with different types
//check out the templeting documentation for more info about this
//This version of minqueue is built upon the deque data structure
template <typename T>
class MinQueue {
public:
MinQueue() {}
bool is_empty() const{
//utilizes the size parameter that deque provides
if (q.size() > 0){
return false; //queue is not empty
}
return true; //queue is empty
}
int size() const{
return q.size();
}
void pop(){ //Typically pop() should only change the queue state. It should not return the item
//pop should only be called when there is an item in the
//minQueue or else a deque exception will be raised
if (q.size() > 0) { //perform check for an empty queue
q.pop_front();
}
}
const T & top(){
return q.front();
}
void push(const T &item){
q.push_back(item);
//this forloop is to determine where in the minQueue the
//new element should be placed
for (int i = q.size()-1; i > 0; --i){
if (q[i-1] > q[i]){
swap(q[i-1], q[i]);
}
else{
break;
}
}
}
private:
deque<T> q;
};
int main(){
MinQueue<int> minQ;
//Here is a testing of the algorithim
cout << minQ.size() << endl;
minQ.push(2);
cout << minQ.size() << endl;
cout << minQ.top() << endl;
minQ.push(1);
cout << minQ.top() << endl;
minQ.pop();
cout << minQ.top() << endl;
minQ.pop();
cout << minQ.size() << endl;
minQ.push(10);
cout << minQ.top() << endl;
minQ.push(8);
cout << minQ.top() << endl;
minQ.push(7);
cout << minQ.top() << endl;
minQ.push(6);
cout << minQ.top() << endl;
minQ.push(1);
cout << minQ.top() << endl;
return 0;
}
| 1,988
|
C++
|
.cpp
| 71
| 21.492958
| 99
| 0.556609
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,120
|
doublylinkedlist.cpp
|
OpenGenus_cosmos/code/data_structures/src/DoubleLinkedList/src_cpp/doublylinkedlist.cpp
|
#include <iostream>
class Node {
public:
int data;
Node* next;
Node* prev;
Node(int val) {
data = val;
next = prev = nullptr;
}
};
class DoublyLinkedList {
private:
Node* head;
Node* tail;
public:
DoublyLinkedList() {
head = tail = nullptr;
}
// Insert at the end of the list
void append(int val) {
Node* newNode = new Node(val);
if (!head) {
head = tail = newNode;
} else {
tail->next = newNode;
newNode->prev = tail;
tail = newNode;
}
}
// Insert at the beginning of the list
void prepend(int val) {
Node* newNode = new Node(val);
if (!head) {
head = tail = newNode;
} else {
head->prev = newNode;
newNode->next = head;
head = newNode;
}
}
// Delete a node by its value
void remove(int val) {
Node* current = head;
while (current) {
if (current->data == val) {
if (current == head) {
head = head->next;
if (head) head->prev = nullptr;
} else if (current == tail) {
tail = tail->prev;
if (tail) tail->next = nullptr;
} else {
current->prev->next = current->next;
current->next->prev = current->prev;
}
delete current;
return;
}
current = current->next;
}
}
// Display the list from head to tail
void display() {
Node* current = head;
while (current) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
};
int main() {
DoublyLinkedList dll;
dll.append(1);
dll.append(2);
dll.append(3);
dll.prepend(0);
dll.display(); // Output: 0 1 2 3
dll.remove(1);
dll.display(); // Output: 0 2 3
return 0;
}
| 2,082
|
C++
|
.cpp
| 83
| 16.26506
| 56
| 0.469789
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,121
|
Doubly_LL.cpp
|
OpenGenus_cosmos/code/data_structures/src/DoubleLinkedList/src_c++/Doubly_LL.cpp
|
#include <iostream>
using namespace std;
struct Node {
int data;
Node* prev;
Node* next;
Node(int value) : data(value), prev(nullptr), next(nullptr) {}
};
class DoublyLinkedList {
private:
Node* head;
Node* tail;
public:
DoublyLinkedList() : head(nullptr), tail(nullptr) {}
void insertAtTail(int value) {
Node* newNode = new Node(value);
if (tail == nullptr) {
head = tail = newNode;
} else {
tail->next = newNode;
newNode->prev = tail;
tail = newNode;
}
}
void insertAtHead(int value) {
Node* newNode = new Node(value);
if (head == nullptr) {
head = tail = newNode;
} else {
head->prev = newNode;
newNode->next = head;
head = newNode;
}
}
void printForward() {
Node* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
void printBackward() {
Node* current = tail;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->prev;
}
std::cout << std::endl;
}
};
int main() {
DoublyLinkedList dll;
int n;
cout << "Enter the number of nodes in linked list: ";
cin >> n;
int x;
cout << "Enter element no. 0: ";
cin >> x;
dll.insertAtHead(x);
for(int i=1; i<n; i++)
{
int x;
cout << "Enter element no. " << i << ": ";
cin >> x;
dll.insertAtTail(x);
}
std::cout << "Forward: ";
dll.printForward(); // Output: 0 1 2 3
std::cout << "Backward: ";
dll.printBackward(); // Output: 3 2 1 0
return 0;
}
| 1,934
|
C++
|
.cpp
| 73
| 18.109589
| 67
| 0.489303
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,122
|
DisjointSet(DS).cpp
|
OpenGenus_cosmos/code/data_structures/src/disjoint_set/DisjointSet(DS).cpp
|
#include <iostream>
using namespace std;
int f[100];
int find(int node)
{
if(f[node] == node){
return node;
}
return f[node] = find(f[node]); //path compression
}
int union_set(int x,int y)
{
return f[find(x)]=find(y);
}
int main()
{
int arr[10];
for(int i=1;i<=10;i++){
arr[i - 1] = i;
f[i] = i;
}
union_set(1, 3);
union_set(4, 5);
union_set(1, 2);
union_set(1, 5);
union_set(2, 8);
union_set(9, 10);
union_set(1, 9);
union_set(2, 7);
union_set(3, 6);
for(auto a : arr){
cout<< a << "->" << f[a] <<"\n";
}
return 0;
}
| 555
|
C++
|
.cpp
| 35
| 13.828571
| 51
| 0.58317
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,123
|
sparse_table.cpp
|
OpenGenus_cosmos/code/data_structures/src/sparse_table/sparse_table.cpp
|
/* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
#include <cassert>
#include <functional>
#include <iomanip>
#include <cmath>
template<typename T, std::size_t S>
class SparseTable
{
public:
/*!
* \brief Builds a sparse table from a set of static data. It is the user responsibility to delete any allocated memory
* \param data The static data
* \param f The function to be applied on the ranges
* \param defaultValue The default value for the function (e.g. INFINITY for Range Minimum Queries)
*/
SparseTable(const T* const data, const std::function<T(T, T)>& f, T defaultValue) : f_{f}, data_{data}, defaultValue_{defaultValue}
{
initializeSparseTable();
}
/*!
* \returns The number of elements in the set of static data
*/
constexpr std::size_t size() const { return S; }
/*!
* \brief Queries the range [l, r] in 0(1) time
* It can only be used if the function is idempotent(e.g. Range Minimum Queries)
* \param l The starting index of the range to be queried
* \param r The end index of the range to be queried
* \returns The result of the function f applied to the range [l, r]
*/
const T queryRangeIdempotent(int l, int r)
{
assert(l >= 0 && r < S);
if (l > r)
return defaultValue_;
std::size_t length = r - l + 1;
return f_(sparseTable_[logs_[length]][l], sparseTable_[logs_[length]][r - (1 << logs_[length]) + 1]);
}
/*!
* \brief Queries the range [l, r] in O(log(n)) time
* It can be used for any function(e.g. Range Sum Queries)
* \param l The starting index of the range to be queried
* \param r The end index of the range to be queried
* \returns The result of the function f applied to the range [l, r]
*/
const T queryRange(int l, int r)
{
assert(l >= 0 && r < S);
T ans = defaultValue_;
while (l < r)
{
ans = f_(ans, sparseTable_[logs_[r - l + 1]][l]);
l += (1 << logs_[r - l + 1]);
}
return ans;
}
private:
T sparseTable_ [((int)std::log2(S)) + 1][S];
const T* const data_;
const std::function<T(T, T)> f_;
T defaultValue_;
int logs_ [S + 1];
/*
* Computes and stores log2(i) for all i from 1 to S
*/
void precomputeLogs()
{
logs_[1] = 0;
for (int i = 2; i <= S; i++)
logs_[i] = logs_[i / 2] + 1;
}
/*
* Creates a sparse table from a set of static data
* This precomputation takes O(nlog(n)) time
*/
void initializeSparseTable()
{
precomputeLogs();
for (int i = 0; i <= logs_[S] + 1; i++)
{
for (int j = 0; j + (1 << i) <= S; j++)
{
if (i == 0)
sparseTable_[i][j] = data_[j];
else
sparseTable_[i][j] = f_(sparseTable_[i-1][j], sparseTable_[i-1][j + (1 << (i - 1))]);
}
}
}
};
int main()
{
// Sparse table for range sum queries with integers
{
int data [] = { 4, 4, 6, 7, 8, 10, 22, 33, 5, 7 };
std::function<int(int, int)> f = [](int a, int b) { return a + b; };
SparseTable<int, 10> st(data, f, 0);
std::cout << st.queryRange(3, 6) << std::endl;
std::cout << st.queryRange(6, 9) << std::endl;
std::cout << st.queryRange(0, 9) << std::endl;
}
// Sparse table for range minimum queries with doubles
{
double data [] = { 3.4, 5.6, 2.3, 9.4, 4.2 };
std::function<double(double, double)> f = [](double a, double b) { return std::min(a, b); };
SparseTable<double, 5> st(data, f, 10e8);
std::setprecision(4);
std::cout << st.queryRangeIdempotent(0, 3) << std::endl;
std::cout << st.queryRangeIdempotent(3, 4) << std::endl;
std::cout << st.queryRangeIdempotent(0, 4) << std::endl;
}
return 0;
}
| 4,022
|
C++
|
.cpp
| 114
| 28.114035
| 136
| 0.552482
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,124
|
circularLinkedList.cpp
|
OpenGenus_cosmos/code/data_structures/src/CircularLinkedList/circularLinkedList.cpp
|
#include <iostream>
using namespace std;
/**
* A node will be consist of a int data &
* a reference to the next node.
* The node object will be used in making linked list
*/
class Node
{
public:
int data;
Node *next;
};
/**
* Using nodes for creating a circular linked list.
*
*/
class CircularList
{
public:
/**
* stores the reference to the last node
*/
Node *last;
/**
* keeping predecessor reference while searching
*/
Node *preLoc;
/**
* current node reference while searching
*/
Node *loc;
CircularList()
{
last = NULL;
loc = NULL;
preLoc = NULL;
}
/**
* Checking if list empty
*/
bool isEmpty()
{
return last == NULL;
}
/**
* Inserting new node in front
*/
void insertAtFront(int value)
{
Node *newnode = new Node();
newnode->data = value;
if (isEmpty())
{
newnode->next = newnode;
last = newnode;
}
else
{
newnode->next = last->next;
last->next = newnode;
}
}
/**
* Inserting new node in last
*/
void insertAtLast(int value)
{
Node *newnode = new Node();
newnode->data = value;
if (isEmpty())
{
newnode->next = newnode;
last = newnode;
}
else
{
newnode->next = last->next;
last->next = newnode;
last = newnode;
}
}
/**
* Printing whole list iteratively
*/
void printList()
{
if (!isEmpty())
{
Node *temp = last->next;
do
{
cout << temp->data;
if (temp != last)
cout << " -> ";
temp = temp->next;
} while (temp != last->next);
cout << endl;
}
else
cout << "List is empty" << endl;
}
/**
* Searching a value
*/
void search(int value)
{
loc = NULL;
preLoc = NULL;
if (isEmpty())
return;
loc = last->next;
preLoc = last;
while (loc != last && loc->data < value)
{
preLoc = loc;
loc = loc->next;
}
if (loc->data != value)
{
loc = NULL;
// if(value > loc->data)
// preLoc = last;
}
}
/**
* Inserting the value in its sorted postion in the list.
*/
void insertSorted(int value)
{
Node *newnode = new Node();
newnode->data = value;
search(value);
if (loc != NULL)
{
cout << "Value already exist!" << endl;
return;
}
else
{
if (isEmpty())
insertAtFront(value);
else if (value > last->data)
insertAtLast(value);
else if (value < last->next->data)
insertAtFront(value);
else
{
newnode->next = preLoc->next;
preLoc->next = newnode;
}
}
}
void deleteValue(int value)
{
search(value);
if (loc != NULL)
{
if (loc->next == loc)
{
last = NULL;
}
else if (value == last->data)
{
preLoc->next = last->next;
last = preLoc;
}
else
{
preLoc->next = loc->next;
}
delete loc;
}
else
cout << "Value not found" << endl;
}
void destroyList()
{
Node *temp = last->next;
while (last->next != last)
{
temp = last->next;
last->next = last->next->next;
delete temp;
}
delete last; // delete the only remaining node
last = NULL;
}
};
/**
* Driver Code
*/
int main()
{
CircularList *list1 = new CircularList();
cout << "Initializing the list" << endl;
list1->insertAtLast(2);
list1->insertAtLast(3);
list1->insertAtLast(4);
list1->insertAtLast(6);
list1->insertAtLast(8);
list1->printList();
cout << "Inserting 5 in the list sorted" << endl;
list1->insertSorted(5);
list1->printList();
cout << "Deleting 3 from the list" << endl;
list1->deleteValue(3);
list1->printList();
cout << "Destroying the whole list" << endl;
list1->destroyList();
list1->printList();
}
| 4,663
|
C++
|
.cpp
| 212
| 13.811321
| 61
| 0.462616
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,125
|
infix_to_postfix2.cpp
|
OpenGenus_cosmos/code/data_structures/src/stack/infix_to_postfix/infix_to_postfix2.cpp
|
#include <iostream>
#include <stack>
class InfixToPostfix
{
public:
InfixToPostfix(const std::string &expression) : expression_(expression) {}
int getPrecedenceOfOperators(char);
std::string convertInfixToPostfix();
private:
std::string expression_;
};
int InfixToPostfix::getPrecedenceOfOperators(char ch)
{
if (ch == '+' || ch == '-')
return 1;
if (ch == '*' || ch == '/')
return 2;
if (ch == '^')
return 3;
else
return 0;
}
std::string InfixToPostfix::convertInfixToPostfix()
{
std::stack <char> stack1;
std::string infixToPostfixExp = "";
int i = 0;
while (expression_[i] != '\0')
{
//if scanned character is open bracket push it on stack
if (expression_[i] == '(' || expression_[i] == '[' || expression_[i] == '{')
stack1.push(expression_[i]);
//if scanned character is opened bracket pop all literals from stack till matching open bracket gets poped
else if (expression_[i] == ')' || expression_[i] == ']' || expression_[i] == '}')
{
if (expression_[i] == ')')
{
while (stack1.top() != '(')
{
infixToPostfixExp = infixToPostfixExp + stack1.top();
stack1.pop();
}
}
if (expression_[i] == ']')
{
while (stack1.top() != '[')
{
infixToPostfixExp = infixToPostfixExp + stack1.top();
stack1.pop();
}
}
if (expression_[i] == '}')
{
while (stack1.top() != '{')
{
infixToPostfixExp = infixToPostfixExp + stack1.top();
stack1.pop();
}
}
stack1.pop();
}
//if scanned character is operator
else if (expression_[i] == '+' || expression_[i] == '-' || expression_[i] == '*' || expression_[i] == '/' || expression_[i] == '^')
{
//very first operator of expression is to be pushed on stack
if (stack1.empty()) {
stack1.push(expression_[i]);
}
else{
/*
* check the precedence order of instack(means the one on top of stack) and incoming operator,
* if instack operator has higher priority than incoming operator pop it out of stack&put it in
* final postifix expression, on other side if precedence order of instack operator is less than i
* coming operator, push incoming operator on stack.
*/
if (getPrecedenceOfOperators(stack1.top()) >= getPrecedenceOfOperators(expression_[i]))
{
infixToPostfixExp = infixToPostfixExp + stack1.top();
stack1.pop();
stack1.push(expression_[i]);
}
else
{
stack1.push(expression_[i]);
}
}
}
else
{
//if literal is operand, put it on to final postfix expression
infixToPostfixExp = infixToPostfixExp + expression_[i];
}
i++;
}
//poping out all remainig operator literals & adding to final postfix expression
if (!stack1.empty())
{
while (!stack1.empty())
{
infixToPostfixExp = infixToPostfixExp + stack1.top();
stack1.pop();
}
}
return infixToPostfixExp;
}
int main()
{
std::string expr;
std::cout << "\nEnter the Infix Expression : ";
std::cin >> expr;
InfixToPostfix p(expr);
std::cout << "\nPostfix expression : " << p.convertInfixToPostfix();
}
| 3,860
|
C++
|
.cpp
| 113
| 23.59292
| 139
| 0.504418
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,127
|
balanced_expression.cpp
|
OpenGenus_cosmos/code/data_structures/src/stack/balanced_expression/balanced_expression.cpp
|
// Stack | Balance paraenthesis | C++
// Part of Cosmos by OpenGenus Foundation
#include <iostream>
#include <stack>
bool checkBalanced(string s)
{
// if not in pairs, then not balanced
if (s.length() % 2 != 0)
return false;
std::stack <char> st;
for (const char: s)
{
//adding opening brackets to stack
if (s[i] == '{' || s[i] == '[' || s[i] == '(')
st.push(s[i]); //if opening brackets encounter, push into stack
else
{
// checking for each closing bracket, if there is an opening bracket in stack
char temp = st.top();
if (s[i] == '}' && temp == '{')
st.pop();
else if (s[i] == ']' && temp == '[')
st.pop();
else if (s[i] == ')' && temp == '(')
st.pop();
else
return false;
}
}
return st.empty();
}
int main()
{
std::string s;
std::cin >> s;
bool res = checkBalanced(s);
if (res)
std::cout << "Expression is balanced";
else
std::cout << "Expression is not balanced";
return 0;
}
| 1,149
|
C++
|
.cpp
| 42
| 20
| 89
| 0.488225
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,128
|
stack_using_queue.cpp
|
OpenGenus_cosmos/code/data_structures/src/stack/stack_using_queue/stack_using_queue.cpp
|
/**
* @brief Stack Data Structure Using the Queue Data Structure
* @details
* Using 2 Queues inside the Stack class, we can easily implement Stack
* data structure with heavy computation in push function.
*
* Part of Cosmos by OpenGenus Foundation
*/
#include <iostream>
#include <queue>
#include <cassert>
using namespace std;
class Stack
{
private:
queue<int> main_q; // stores the current state of the stack
queue<int> auxiliary_q; // used to carry out intermediate operations to implement stack
int current_size = 0; // stores the current size of the stack
public:
int top();
void push(int val);
void pop();
int size();
};
/**
* Returns the top most element of the stack
* @returns top element of the queue
*/
int Stack :: top()
{
return main_q.front();
}
/**
* @brief Inserts an element to the top of the stack.
* @param val the element that will be inserted into the stack
* @returns void
*/
void Stack :: push(int val)
{
auxiliary_q.push(val);
while(!main_q.empty())
{
auxiliary_q.push(main_q.front());
main_q.pop();
}
swap(main_q, auxiliary_q);
current_size++;
}
/**
* @brief Removes the topmost element from the stack
* @returns void
*/
void Stack :: pop()
{
if(main_q.empty()) {
return;
}
main_q.pop();
current_size--;
}
/**
* @brief Utility function to return the current size of the stack
* @returns current size of stack
*/
int Stack :: size()
{
return current_size;
}
int main()
{
Stack s;
s.push(1); // insert an element into the stack
s.push(2); // insert an element into the stack
s.push(3); // insert an element into the stack
assert(s.size()==3); // size should be 3
assert(s.top()==3); // topmost element in the stack should be 3
s.pop(); // remove the topmost element from the stack
assert(s.top()==2); // topmost element in the stack should now be 2
s.pop(); // remove the topmost element from the stack
assert(s.top()==1);
s.push(5); // insert an element into the stack
assert(s.top()==5); // topmost element in the stack should now be 5
s.pop(); // remove the topmost element from the stack
assert(s.top()==1); // topmost element in the stack should now be 1
assert(s.size()==1); // size should be 1
return 0;
}
| 2,379
|
C++
|
.cpp
| 87
| 23.724138
| 94
| 0.660009
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,130
|
array_stack.cpp
|
OpenGenus_cosmos/code/data_structures/src/stack/abstract_stack/cpp/array_stack/array_stack.cpp
|
#include <iostream>
#include "../istack.h"
#include "arraystack.h"
int main()
{
int s;
IStack<int> *stack = new ArrayStack<int>();
try {
stack->peek();
} catch (char const *e)
{
std::cout << e << std::endl << std::endl;
}
stack->push(20);
std::cout << "Added 20" << std::endl;
IStack<int> *stack2 = stack;
std::cout << "1 " << std::endl;
std::cout << stack->toString() << std::endl;
std::cout << "2 " << std::endl;
std::cout << stack2->toString() << std::endl;
stack->push(30);
std::cout << "Added 30" << std::endl;
std::cout << std::endl << std::endl << stack->toString() << std::endl << std::endl;
s = stack->peek();
std::cout << "First element is now: " << s << std::endl;
std::cout << "removed: " << stack->pop() << std::endl;
s = stack->peek();
std::cout << "First element is now: " << s << std::endl;
delete stack;
return 0;
}
| 953
|
C++
|
.cpp
| 31
| 25.870968
| 87
| 0.532967
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,132
|
infix_to_prefix.cpp
|
OpenGenus_cosmos/code/data_structures/src/stack/infix_to_prefix/infix_to_prefix.cpp
|
// Including Library
#include <iostream>
#include <ctype.h>
#include <string.h>
#include <stack>
/** Function to check if given character is
an operator or not. **/
bool isOperator(char c)
{
return (!isalpha(c) && !isdigit(c));
}
/** Function to find priority of given
operator.**/
int getPriority(char c)
{
if (c == '-' || c == '+')
return 1;
else if (c == '*' || c == '/')
return 2;
else if (c == '^')
return 3;
return 0;
}
/** Function that converts infix
expression to prefix expression. **/
std::string infixToPrefix(std::string infix)
{
// stack for operators.
std::stack<char> operators;
// stack for operands.
std::stack<std::string> operands;
for (int i = 0; i < infix.length(); i++)
{
/** If current character is an
opening bracket, then
push into the operators stack. **/
if (infix[i] == '(')
operators.push(infix[i]);
/** If current character is a
closing bracket, then pop from
both stacks and push result
in operands stack until
matching opening bracket is
not found. **/
else if (infix[i] == ')')
{
while (!operators.empty() && operators.top() != '(')
{
// operand 1
std::string op1 = operands.top();
operands.pop();
// operand 2
std::string op2 = operands.top();
operands.pop();
// operator
char op = operators.top();
operators.pop();
/** Add operands and operator
in form operator +
operand1 + operand2. **/
std::string tmp = op + op2 + op1;
operands.push(tmp);
}
/** Pop opening bracket from stack. **/
operators.pop();
}
/** If current character is an
operand then push it into
operands stack. **/
else if (!isOperator(infix[i]))
operands.push(std::string(1, infix[i]));
/** If current character is an
operator, then push it into
operators stack after popping
high priority operators from
operators stack and pushing
result in operands stack. **/
else
{
while (!operators.empty() && getPriority(infix[i]) <= getPriority(operators.top())) {
std::string op1 = operands.top();
operands.pop();
std::string op2 = operands.top();
operands.pop();
char op = operators.top();
operators.pop();
std::string tmp = op + op2 + op1;
operands.push(tmp);
}
operators.push(infix[i]);
}
}
/** Pop operators from operators stack
until it is empty and add result
of each pop operation in
operands stack. **/
while (!operators.empty())
{
std::string op1 = operands.top();
operands.pop();
std::string op2 = operands.top();
operands.pop();
char op = operators.top();
operators.pop();
std::string tmp = op + op2 + op1;
operands.push(tmp);
}
/** Final prefix expression is
present in operands stack. **/
return operands.top();
}
// Driver code
int main()
{
std::string s;
std::cin >> s;
std::cout << infixToPrefix(s);
return 0;
}
// Input - (A-B/C)*(A/K-L)
// Output - *-A/BC-/AKL
| 3,645
|
C++
|
.cpp
| 121
| 21.099174
| 97
| 0.514115
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,133
|
quick_sort.cpp
|
OpenGenus_cosmos/code/data_structures/src/stack/Quick_sort_usingSack/quick_sort.cpp
|
#include <iostream>
#include <stack>
using namespace std;
int arr[] = {4, 1, 5, 3, 50, 30, 70, 80, 28, 22};
stack<int> higherStack, lowerStack;
void displayArray();
void quick_sort(int lower, int higher);
void partition(int lower, int higher);
int main()
{
lowerStack.push(0);
higherStack.push(9);
quick_sort(0,9);
displayArray();
}
void quick_sort(int lower, int higher)
{
if (sizeof(arr) / 4 <= 1)
{
return;
}
while (!lowerStack.empty())
{
partition(lower, higher);
quick_sort(lowerStack.top(), higherStack.top());
lowerStack.pop();
higherStack.pop();
}
}
void displayArray()
{
for (int i = 0; i < 10; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
void partition(int lower, int higher)
{
int i = lower;
int j = higher;
int pivot = arr[lower];
while (i <= j)
{
while (pivot <= arr[i] && i<=higher)
{
i++;
}
while (pivot > arr[j] && j<=lower)
{
j--;
}
if(i>j) swap(arr[i], arr[j]);
}
swap(arr[j], arr[lower]);
lowerStack.push(lower);
lowerStack.push(j + 1);
higherStack.push(j - 1);
higherStack.push(higher);
}
| 1,250
|
C++
|
.cpp
| 60
| 15.883333
| 56
| 0.548688
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,137
|
sort_stack.cpp
|
OpenGenus_cosmos/code/data_structures/src/stack/sort_stack/sort_stack.cpp
|
/* Part of Cosmos by OpenGenus Foundation */
/* Sort a stack */
#include <iostream>
#include <stack>
using namespace std;
void InputElements(stack<int> &s) //////////// Function to insert the elements in stack
{ //no. of elements to be inserted
int size;
cin >> size;
while (size--)
{
int num;
cin >> num;
s.push(num);
}
}
void PrintStack(stack<int> s) //////////// Function to print the contents of stack
{
while (!s.empty())
{
cout << s.top() << " ";
s.pop();
}
cout << endl;
}
void SortedInsert(stack<int> &s, int num) ////////// Function to insert a element at its right position in sorted way
{
if (s.empty() || s.top() > num)
{
s.push(num);
return;
}
int top_element = s.top();
s.pop();
SortedInsert(s, num);
s.push(top_element);
}
void SortStack(stack<int> &s) //////////// Function to sort the stack
{
if (s.empty())
return;
int top_element = s.top();
s.pop();
SortStack(s);
SortedInsert(s, top_element);
}
int main()
{
stack<int> s;
//Inserting elements in to the stack
InputElements(s);
//Print stack before sorting
PrintStack(s);
//Sort the stack
SortStack(s);
//Print stack after sorting
PrintStack(s);
return 0;
}
| 1,356
|
C++
|
.cpp
| 59
| 18.745763
| 118
| 0.566461
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,139
|
xor_linked_list.cpp
|
OpenGenus_cosmos/code/data_structures/src/list/xor_linked_list/xor_linked_list.cpp
|
/*
* Part of Cosmos by OpenGenus Foundation
*
* xor linked list synopsis
*
*** incomplete ***
***
***Begin *** Iterator invalidation rules are NOT applicable. ***
***[x] Insertion: all iterators and references unaffected.
***[x] Erasure: only the iterators and references to the erased element is invalidated.
***[o] Resizing: as per insert/erase.
***
***Refer to: https://stackoverflow.com/questions/6438086/iterator-invalidation-rules
***End *** Iterator invalidation rules are NOT applicable. ***
*/
#ifndef XOR_LINKED_LIST_CPP
#define XOR_LINKED_LIST_CPP
#include <iterator>
#include <algorithm>
#include <exception>
#include <cstddef>
template<typename _Type>
class XorLinkedList;
template<class _Type>
class ListIter;
template<class _Type>
class ListConstIter;
template<typename _Type>
class __Node
{
private:
using value_type = _Type;
using SPNode = __Node<value_type> *;
public:
explicit __Node(value_type value) : value_(value), around_(nullptr)
{
}
inline value_type &value()
{
return value_;
}
inline const value_type &value() const
{
return value_;
}
inline void value(value_type v)
{
value_ = v;
}
private:
value_type value_;
void *around_;
inline SPNode around(const SPNode &around)
{
return reinterpret_cast<SPNode>(reinterpret_cast<uintptr_t>(around) ^
reinterpret_cast<uintptr_t>(around_));
}
inline void around(const SPNode &prev, const SPNode &next)
{
around_ = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(prev) ^
reinterpret_cast<uintptr_t>(next));
}
friend XorLinkedList<value_type>;
friend ListIter<value_type>;
friend ListConstIter<value_type>;
};
template<class _Type>
class ListIter : public std::iterator<std::bidirectional_iterator_tag, _Type>
{
public:
using value_type = _Type;
using difference_type = std::ptrdiff_t;
using pointer = _Type *;
using reference = _Type &;
using iterator_category = std::bidirectional_iterator_tag;
private:
using NodePtr = __Node<value_type> *;
using Self = ListIter<value_type>;
public:
ListIter()
{
}
explicit ListIter(NodePtr prev, NodePtr curr) : prev_(prev), curr_(curr)
{
}
ListIter(const Self &it) : prev_(it.prev_), curr_(it.curr_)
{
}
reference operator*()
{
return curr_->value();
}
pointer operator->()
{
return &curr_->value();
}
Self &operator++()
{
auto next = curr_->around(prev_);
prev_ = curr_;
curr_ = next;
return *this;
}
Self operator++(int)
{
auto temp = *this;
++*this;
return temp;
}
Self &operator--()
{
auto prevOfprev = prev_->around(curr_);
curr_ = prev_;
prev_ = prevOfprev;
return *this;
}
Self operator--(int)
{
auto temp = *this;
--*this;
return temp;
}
bool operator==(const Self &other) const
{
return curr_ == other.curr_;
}
bool operator!=(const Self &other) const
{
return !(*this == other);
}
private:
NodePtr prev_, curr_;
friend XorLinkedList<value_type>;
friend ListConstIter<value_type>;
};
template<class _Type>
class ListConstIter : public std::iterator<std::bidirectional_iterator_tag, _Type>
{
public:
using value_type = _Type;
using difference_type = std::ptrdiff_t;
using pointer = const _Type *;
using reference = const _Type &;
using iterator_category = std::bidirectional_iterator_tag;
private:
using NodePtr = __Node<value_type> *;
using Self = ListConstIter<value_type>;
using Iter = ListIter<value_type>;
public:
ListConstIter()
{
}
explicit ListConstIter(NodePtr prev, NodePtr curr) : prev_(prev), curr_(curr)
{
}
ListConstIter(const Iter &it) : prev_(it.prev_), curr_(it.curr_)
{
}
reference operator*() const
{
return curr_->value();
}
pointer operator->() const
{
return &curr_->value();
}
Self &operator++()
{
auto next = curr_->around(prev_);
prev_ = curr_;
curr_ = next;
return *this;
}
Self operator++(int)
{
auto temp = *this;
++*this;
return temp;
}
Self &operator--()
{
auto prevOfprev = prev_->around(curr_);
curr_ = prev_;
prev_ = prevOfprev;
return *this;
}
Self operator--(int)
{
auto temp = *this;
--*this;
return temp;
}
bool operator==(const Self &other) const
{
return curr_ == other.curr_;
}
bool operator!=(const Self &other) const
{
return !(*this == other);
}
private:
NodePtr prev_, curr_;
Iter constCast()
{
return Iter(prev_, curr_);
}
friend XorLinkedList<value_type>;
};
template<typename _Type>
class XorLinkedList
{
private:
using Node = __Node<_Type>;
using NodePtr = __Node<_Type> *;
using Self = XorLinkedList<_Type>;
public:
using value_type = _Type;
using size_type = size_t;
using difference_type = std::ptrdiff_t;
using pointer = const value_type *;
using const_pointer = const value_type *;
using reference = value_type &;
using const_reference = const value_type &;
using iterator = ListIter<value_type>;
using const_iterator = ListConstIter<value_type>;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
explicit XorLinkedList() : sz_(0)
{
construct();
}
XorLinkedList(const Self &list) : sz_(0)
{
construct();
std::for_each(list.begin(), list.end(), [&](value_type v)
{
push_back(v);
});
};
XorLinkedList(std::initializer_list<value_type> &&vs) : sz_(0)
{
construct();
std::for_each(vs.begin(), vs.end(), [&](value_type v)
{
push_back(v);
});
}
~XorLinkedList()
{
clear();
destruct();
}
// element access
inline reference back();
inline const_reference back() const;
inline reference front();
inline const_reference front() const;
// modifiers
void clear();
template<class ... Args>
reference emplace_back(Args&& ... args);
template<class ... Args>
reference emplace_front(Args&& ... args);
iterator erase(const_iterator pos);
iterator erase(const_iterator begin, const_iterator end);
iterator insert(const_iterator pos, const value_type &v);
iterator insert(const_iterator pos, size_type size, const value_type &v);
iterator insert(const_iterator pos, value_type &&v);
iterator insert(const_iterator pos, std::initializer_list<value_type> il);
template<typename _InputIt>
iterator insert(const_iterator pos, _InputIt first, _InputIt last);
void pop_back();
void pop_front();
void push_back(const value_type &v);
void push_front(const value_type &v);
void resize(size_type count);
void resize(size_type count, const value_type&value);
void swap(Self&other);
// capacity
inline bool empty() const;
inline size_type max_size() const;
inline size_type size() const;
// iterators
iterator begin();
const_iterator begin() const;
const_iterator cbegin() const;
iterator end();
const_iterator end() const;
const_iterator cend() const;
reverse_iterator rbegin();
const_reverse_iterator rbegin() const;
const_reverse_iterator crbegin() const;
reverse_iterator rend();
const_reverse_iterator rend() const;
const_reverse_iterator crend() const;
// operations
void merge(Self&other);
void merge(Self&&other);
template<class Compare>
void merge(Self&other, Compare comp);
template<class Compare>
void merge(Self&&other, Compare comp);
void reverse();
void sort();
template<class Compare>
void sort(Compare comp);
void splice(const_iterator pos, Self&other);
void splice(const_iterator pos, Self&&other);
void splice(const_iterator pos, Self&other, const_iterator it);
void splice(const_iterator pos, Self&&other, const_iterator it);
void splice(const_iterator pos, Self&other, const_iterator first, const_iterator last);
void splice(const_iterator pos, Self&&other, const_iterator first, const_iterator last);
void unique();
template<class BinaryPredicate>
void unique(BinaryPredicate p);
private:
NodePtr prevOfBegin_, end_, nextOfEnd_;
size_type sz_;
inline void construct();
inline void destruct();
inline iterator insertImpl(const_iterator pos, const value_type &v);
inline iterator eraseImpl(const_iterator pos);
};
// element access
template<typename _Type>
inline auto
XorLinkedList<_Type>::back()->reference
{
if (empty())
throw std::out_of_range("access to empty list !");
return end_->around(nextOfEnd_)->value();
}
template<typename _Type>
inline auto
XorLinkedList<_Type>::back() const->const_reference
{
return const_cast<Self *>(this)->back();
}
template<typename _Type>
inline auto
XorLinkedList<_Type>::front()->reference
{
if (empty())
throw std::out_of_range("access to empty list !");
return prevOfBegin_->around(nextOfEnd_)->value();
}
template<typename _Type>
inline auto
XorLinkedList<_Type>::front() const->const_reference
{
return const_cast<Self *>(this)->front();
}
// modifiers
template<typename _Type>
inline void
XorLinkedList<_Type>::clear()
{
NodePtr begin = prevOfBegin_, nextOfBegin;
begin = begin->around(nextOfEnd_);
while (begin != end_)
{
nextOfBegin = begin->around(prevOfBegin_);
prevOfBegin_->around(nextOfEnd_, nextOfBegin);
nextOfBegin->around(prevOfBegin_, nextOfBegin->around(begin));
delete begin;
begin = nextOfBegin;
}
sz_ = 0;
}
template<typename _Type>
template<class ... Args>
auto
XorLinkedList<_Type>::emplace_back(Args&& ... args)->reference
{
}
template<typename _Type>
template<class ... Args>
auto
XorLinkedList<_Type>::emplace_front(Args&& ... args)->reference
{
}
template<typename _Type>
inline auto
XorLinkedList<_Type>::erase(const_iterator pos)->iterator
{
return eraseImpl(pos);
}
template<typename _Type>
inline auto
XorLinkedList<_Type>::erase(const_iterator first, const_iterator last)->iterator
{
auto diff = std::distance(first, last);
if (diff == 0)
return first.constCast(); // check what is std return
auto firstAfterEraseIter = first;
while (diff--)
firstAfterEraseIter = eraseImpl(firstAfterEraseIter);
return firstAfterEraseIter.constCast();
}
template<typename _Type>
inline auto
XorLinkedList<_Type>::insert(const_iterator pos, const value_type &v)->iterator
{
return insertImpl(pos, v);
}
template<typename _Type>
inline auto
XorLinkedList<_Type>::insert(const_iterator pos, size_type size, const value_type &v)
->iterator
{
if (size == 0)
return pos.constCast();
auto curr = insert(pos, v);
auto firstOfInsert = curr;
++curr;
while (--size)
curr = ++insert(curr, v);
return firstOfInsert;
}
template<typename _Type>
inline auto
XorLinkedList<_Type>::insert(const_iterator pos, value_type &&v)->iterator
{
return insertImpl(pos, v);
}
template<typename _Type>
inline auto
XorLinkedList<_Type>::insert(const_iterator pos, std::initializer_list<value_type> il)
->iterator
{
if (il.begin() == il.end())
return pos.constCast();
auto curr = insert(pos, *il.begin());
auto firstOfInsert = curr;
++curr;
auto begin = il.begin();
++begin;
std::for_each(begin, il.end(), [&](value_type v)
{
curr = ++insert(curr, v);
});
return firstOfInsert;
}
template<typename _Type>
template<typename _InputIt>
inline auto
XorLinkedList<_Type>::insert(const_iterator pos, _InputIt first, _InputIt last)
->iterator
{
if (first < last)
{
auto curr = insert(pos, *first);
auto firstOfInsert = curr;
++curr;
auto begin = first;
++begin;
std::for_each(begin, last, [&](value_type it)
{
curr = ++insert(curr, it);
});
return firstOfInsert;
}
return pos.constCast();
}
template<typename _Type>
void
XorLinkedList<_Type>::pop_back()
{
// Calling pop_back on an empty container is undefined.
erase(--end());
}
template<typename _Type>
void
XorLinkedList<_Type>::pop_front()
{
// Calling pop_front on an empty container is undefined.
erase(begin());
}
template<typename _Type>
void
XorLinkedList<_Type>::push_back(const value_type &v)
{
insert(end(), v);
}
template<typename _Type>
void
XorLinkedList<_Type>::push_front(const value_type &v)
{
insert(begin(), v);
}
template<typename _Type>
void
XorLinkedList<_Type>::resize(size_type count)
{
}
template<typename _Type>
void
XorLinkedList<_Type>::resize(size_type count, const value_type&value)
{
}
template<typename _Type>
void
XorLinkedList<_Type>::swap(Self&other)
{
}
// capacity
template<typename _Type>
inline bool
XorLinkedList<_Type>::empty() const
{
return prevOfBegin_->around(nextOfEnd_) == end_;
}
template<typename _Type>
inline auto
XorLinkedList<_Type>::max_size() const->size_type
{
return static_cast<size_type>(-1) / sizeof(value_type);
}
template<typename _Type>
inline auto
XorLinkedList<_Type>::size() const->size_type
{
return sz_;
}
// iterators
template<typename _Type>
inline auto
XorLinkedList<_Type>::begin()->iterator
{
return iterator(prevOfBegin_, prevOfBegin_->around(nextOfEnd_));
}
template<typename _Type>
auto
XorLinkedList<_Type>::begin() const->const_iterator
{
return const_iterator(prevOfBegin_, prevOfBegin_->around(nextOfEnd_));
}
template<typename _Type>
auto
XorLinkedList<_Type>::cbegin() const->const_iterator
{
return const_iterator(prevOfBegin_, prevOfBegin_->around(nextOfEnd_));
}
template<typename _Type>
inline auto
XorLinkedList<_Type>::end()->iterator
{
return iterator(end_->around(nextOfEnd_), end_);
}
template<typename _Type>
auto
XorLinkedList<_Type>::end() const->const_iterator
{
return const_iterator(end_->around(nextOfEnd_), end_);
}
template<typename _Type>
auto
XorLinkedList<_Type>::cend() const->const_iterator
{
return const_iterator(end_->around(nextOfEnd_), end_);
}
template<typename _Type>
inline auto
XorLinkedList<_Type>::rbegin()->reverse_iterator
{
return reverse_iterator(end());
}
template<typename _Type>
auto
XorLinkedList<_Type>::rbegin() const->const_reverse_iterator
{
return const_reverse_iterator(end());
}
template<typename _Type>
auto
XorLinkedList<_Type>::crbegin() const->const_reverse_iterator
{
return const_reverse_iterator(cend());
}
template<typename _Type>
inline auto
XorLinkedList<_Type>::rend()->reverse_iterator
{
return reverse_iterator(begin());
}
template<typename _Type>
auto
XorLinkedList<_Type>::rend() const->const_reverse_iterator
{
return const_reverse_iterator(begin());
}
template<typename _Type>
auto
XorLinkedList<_Type>::crend() const->const_reverse_iterator
{
return const_reverse_iterator(cbegin());
}
// operations
template<typename _Type>
inline void
XorLinkedList<_Type>::merge(Self&other)
{
}
template<typename _Type>
inline void
XorLinkedList<_Type>::merge(Self&&other)
{
}
template<typename _Type>
template<class Compare>
inline void
XorLinkedList<_Type>::merge(Self&other, Compare comp)
{
}
template<typename _Type>
template<class Compare>
inline void
XorLinkedList<_Type>::merge(Self&&other, Compare comp)
{
}
template<typename _Type>
inline void
XorLinkedList<_Type>::reverse()
{
std::swap(prevOfBegin_, end_);
}
template<typename _Type>
inline void
XorLinkedList<_Type>::sort()
{
}
template<typename _Type>
template<class Compare>
inline void
XorLinkedList<_Type>::sort(Compare comp)
{
}
template<typename _Type>
inline void
XorLinkedList<_Type>::splice(const_iterator pos, Self&other)
{
}
template<typename _Type>
inline void
XorLinkedList<_Type>::splice(const_iterator pos, Self&&other)
{
}
template<typename _Type>
inline void
XorLinkedList<_Type>::splice(const_iterator pos, Self&other, const_iterator it)
{
}
template<typename _Type>
inline void
XorLinkedList<_Type>::splice(const_iterator pos, Self&&other, const_iterator it)
{
}
template<typename _Type>
inline void
XorLinkedList<_Type>::splice(const_iterator pos,
Self&other,
const_iterator first,
const_iterator
last)
{
}
template<typename _Type>
inline void
XorLinkedList<_Type>::splice(const_iterator pos,
Self&&other,
const_iterator first,
const_iterator
last)
{
}
template<typename _Type>
inline void
XorLinkedList<_Type>::unique()
{
}
template<typename _Type>
template<class BinaryPredicate>
inline void
XorLinkedList<_Type>::unique(BinaryPredicate p)
{
}
// private functions
template<typename _Type>
inline void
XorLinkedList<_Type>::construct()
{
end_ = new Node(0);
prevOfBegin_ = new Node(0);
nextOfEnd_ = new Node(0);
end_->around(prevOfBegin_, nextOfEnd_);
prevOfBegin_->around(nextOfEnd_, end_);
nextOfEnd_->around(end_, prevOfBegin_);
}
template<typename _Type>
inline void
XorLinkedList<_Type>::destruct()
{
delete prevOfBegin_;
delete end_;
delete nextOfEnd_;
}
template<typename _Type>
inline auto
XorLinkedList<_Type>::insertImpl(const_iterator pos, const value_type &v)
->iterator
{
auto curr = pos.curr_;
auto prev = pos.prev_;
auto nextOfNext = curr->around(prev);
auto prevOfPrev = prev->around(curr);
auto newCurr = new Node(v);
newCurr->around(prev, curr);
curr->around(newCurr, nextOfNext);
prev->around(prevOfPrev, newCurr);
++sz_;
return iterator(prev, prev->around(prevOfPrev));
}
template<typename _Type>
auto
XorLinkedList<_Type>::eraseImpl(const_iterator pos)->iterator
{
auto curr = pos.curr_;
auto prev = pos.prev_;
auto nextOfCurr = curr->around(prev);
auto nextOfNext = nextOfCurr->around(curr);
auto prevOfPrev = prev->around(curr);
nextOfCurr->around(prev, nextOfNext);
prev->around(prevOfPrev, nextOfCurr);
delete curr;
--sz_;
return iterator(prev, nextOfCurr);
}
#endif // XOR_LINKED_LIST_CPP
| 18,775
|
C++
|
.cpp
| 738
| 21.276423
| 92
| 0.672438
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,140
|
doubly_linked_list.cpp
|
OpenGenus_cosmos/code/data_structures/src/list/doubly_linked_list/doubly_linked_list.cpp
|
/* Part of Cosmos by OpenGenus Foundation */
/* Contributed by Vaibhav Jain (vaibhav29498) */
#include <iostream>
#include <cstdlib>
using namespace std;
template <typename T>
struct node
{
T info;
node* pre; // Holds the pointer to the previous node
node* next; // Holds the pointer to the next node
node();
};
template <typename T> node<T>::node()
{
info = 0;
pre = nullptr;
next = nullptr;
}
template <class T>
class doubleLinkedList
{
node<T>* head;
public:
doubleLinkedList();
int listSize();
void insertNode(T, int);
void deleteNode(int);
void print();
void reversePrint();
void insertionSort();
};
template <class T> doubleLinkedList<T>::doubleLinkedList()
{
head = nullptr;
}
template <class T> int doubleLinkedList<T>::listSize()
{
int i = 0;
node<T> *ptr = head;
// The loop below traverses the list to find out the size
while (ptr != nullptr)
{
++i;
ptr = ptr->next;
}
return i;
}
template <class T> void doubleLinkedList<T>::insertNode(T i, int p)
{
node<T> *ptr = new node<T>, *cur = head;
ptr->info = i;
if (cur == nullptr)
head = ptr; // New node becomes head if the list is empty
else if (p == 1)
{
// Put the node at the beginning of the list and change head accordingly
ptr->next = head;
head->pre = ptr;
head = ptr;
}
else if (p > listSize())
{
// Navigate to the end of list and add the node to the end of the list
while (cur->next != nullptr)
cur = cur->next;
cur->next = ptr;
ptr->pre = cur;
}
else
{
// Navigate to 'p'th element of the list and insert the new node before it
int n = p - 1;
while (n--)
cur = cur->next;
ptr->pre = cur->pre;
ptr->next = cur;
cur->pre->next = ptr;
cur->pre = ptr;
}
cout << "Node inserted!" << endl;
}
template <class T> void doubleLinkedList<T>::deleteNode(int p)
{
if (p > listSize())
{
// List does not have a 'p'th node
cout << "Underflow!" << endl;
return;
}
node<T> *ptr = head;
if (p == 1)
{
// Update head when the first node is being deleted
head = head->next;
head->pre = nullptr;
delete ptr;
}
else if (p == listSize())
{
// Navigate to the end of the list and delete the last node
while (ptr->next != nullptr)
ptr = ptr->next;
ptr->pre->next = nullptr;
delete ptr;
}
else
{
// Navigate to 'p'th element of the list and delete that node
int n = p - 1;
while (n--)
ptr = ptr->next;
ptr->pre->next = ptr->next;
ptr->next->pre = ptr->pre;
delete ptr;
}
cout << "Node deleted!" << endl;
}
template <class T> void doubleLinkedList<T>::print()
{
// Traverse the entire list and print each node
node<T> *ptr = head;
while (ptr != nullptr)
{
cout << ptr->info << " -> ";
ptr = ptr->next;
}
cout << "NULL" << endl;
}
template <class T> void doubleLinkedList<T>::reversePrint()
{
node<T> *ptr = head;
// First, traverse to the last node of the list
while (ptr->next != nullptr)
ptr = ptr->next;
// From the last node, use `pre` attribute to traverse backwards and print each node in reverse order
while (ptr != nullptr)
{
cout << ptr->info << " <- ";
ptr = ptr->pre;
}
cout << "NULL" << endl;
}
template <class T> void doubleLinkedList<T>::insertionSort()
{
if (!head || !head->next)
{
// The list is empty or has only one element, which is already sorted.
return;
}
node<T> *sorted = nullptr; // Initialize a sorted sublist
node<T> *current = head;
while (current) {
node<T> *nextNode = current->next;
if (!sorted || current->info < sorted->info)
{
// If the sorted list is empty or current node's value is smaller than the
// sorted list's head,insert current node at the beginning of the sorted list.
current->next = sorted;
current->pre = nullptr;
if (sorted) {
sorted->pre = current;
}
sorted = current;
}
else
{
// Traverse the sorted list to find the appropriate position for the current node.
node<T> *temp = sorted;
while (temp->next && current->info >= temp->next->info)
{
temp = temp->next;
}
// Insert current node after temp.
current->next = temp->next;
current->pre = temp;
if (temp->next)
{
temp->next->pre = current;
}
temp->next = current;
}
current = nextNode; // Move to the next unsorted node
}
// Update the head of the list to point to the sorted sublist.
head = sorted;
cout<<"Sorting Complete"<<endl;
}
int main()
{
doubleLinkedList<int> l;
int m, i, p;
while (true)
{
system("cls");
cout << "1.Insert" << endl
<< "2.Delete" << endl
<< "3.Print" << endl
<< "4.Reverse Print" << endl
<< "5.Sort" << endl
<< "6.Exit" << endl;
cin >> m;
switch (m)
{
case 1:
cout << "Enter info and position ";
cin >> i >> p;
l.insertNode(i, p);
break;
case 2:
cout << "Enter position ";
cin >> p;
l.deleteNode(p);
break;
case 3:
l.print();
break;
case 4:
l.reversePrint();
break;
case 5:
l.insertionSort();
break;
case 6:
exit(0);
default:
cout << "Invalid choice!" << endl;
}
system("pause");
}
return 0;
}
| 6,109
|
C++
|
.cpp
| 232
| 19.125
| 105
| 0.525947
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
10,142
|
singly_linked_list.cpp
|
OpenGenus_cosmos/code/data_structures/src/list/singly_linked_list/singly_linked_list.cpp
|
#include "singly_linked_list.h"
int main()
{
Linkedlist<int> link;
for (int i = 10; i > 0; --i)
link.rearAdd(i);
link.print();
std::cout << link.size() << std::endl;
Linkedlist<int> link1(link);
link1 = link1;
link1.print();
link1.deletePos(100);
link1.modify(5, 100);
link1.insert(3, 50);
std::cout << link1.size() << std::endl;
link1.print();
link1.removeKthNodeFromEnd(3);
std::cout<<"After deleting 3rd node from the end\n";
link1.print();
link1.sort();
link1.print();
link1.destroy();
std::cout << link1.size() << std::endl;
return 0;
}
| 633
|
C++
|
.cpp
| 25
| 20.68
| 56
| 0.593388
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,143
|
singly_linked_list_with_classes.cpp
|
OpenGenus_cosmos/code/data_structures/src/list/singly_linked_list/singly_linked_list_with_classes.cpp
|
#include <iostream>
class Node {
private:
int _data;
Node *_next;
public:
Node()
{
}
void setData(int Data)
{
_data = Data;
}
void setNext(Node *Next)
{
if (Next == NULL)
_next = NULL;
else
_next = Next;
}
int Data()
{
return _data;
}
Node *Next()
{
return _next;
}
};
class LinkedList {
private:
Node *head;
public:
LinkedList()
{
head = NULL;
}
void insert_back(int data);
void insert_front(int data);
void init_list(int data);
void print_List();
};
void LinkedList::print_List()
{
Node *tmp = head;
//Checking the list if there is a node or not.
if (tmp == NULL)
{
std::cout << "List is empty\n";
return;
}
//Checking only one node situation.
if (tmp->Next() == NULL)
std::cout << "Starting: " << tmp->Data() << "Next Value > NULL\n";
else
while (tmp != NULL)
{
std::cout << tmp->Data() << " > ";
tmp = tmp->Next();
}
}
/*inserting a value infront of the */
void LinkedList::insert_back(int data)
{
//Creating a node
Node *newNode = new Node();
newNode->setData(data);
newNode->setNext(NULL);
//Creating a temporary pointer.
Node *tmp = head;
if (tmp != NULL)
{
while (tmp->Next() != NULL)
tmp = tmp->Next();
tmp->setNext(newNode);
}
else
head = newNode;
}
/*Inserting a value in front of the head node.*/
void LinkedList::insert_front(int data)
{
// creating a new node.
Node *newNode = new Node();
newNode->setData(data);
newNode->setNext(NULL);
newNode->setNext(head);
head = newNode;
}
/*Initializing the list with a value.*/
void LinkedList::init_list(int data)
{
//creating a node
Node *newNode = new Node();
newNode->setData(data);
newNode->setNext(NULL);
if (head != NULL)
head = NULL;
head = newNode;
}
int main()
{
//Creating a list
LinkedList list;
//Initilizing it with 5
list.init_list(5);
list.insert_back(6);
list.insert_front(4);
list.print_List();
}
| 2,217
|
C++
|
.cpp
| 110
| 15.090909
| 74
| 0.558683
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,144
|
rotate.cpp
|
OpenGenus_cosmos/code/data_structures/src/list/singly_linked_list/operations/rotate/rotate.cpp
|
/*
* Part of Cosmos by OpenGenus Foundation
*/
#include <iostream>
//Definition for singly-linked list.
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL)
{
}
};
ListNode* rotate(ListNode* A, int B)
{
int t = 0;
ListNode* temp = A;
ListNode* prev2 = NULL;
while (temp)
{
++t;
prev2 = temp;
temp = temp->next;
}
B = B % t; //count by which the list is to be rotated
if (B == 0)
return A;
int p = t - B;
ListNode* prev = NULL;
ListNode* head = A;
temp = A;
for (int i = 1; i < p; i++) //reaching that point from where the list is to be rotated
{
prev = temp;
temp = temp->next;
}
prev = temp;
if (temp && temp->next) //rotating the list
temp = temp->next;
if (prev2)
prev2->next = A;
if (prev)
prev->next = NULL;
head = temp;
return head;
}
int main()
{
using namespace std;
ListNode* head = new ListNode(5);
ListNode* temp = head; // Creating a linkedlist
int i = 4;
while (i > 0) //Adding values to the linkedlist
{
ListNode* t = new ListNode(i);
temp->next = t;
temp = temp->next;
--i;
}
head = rotate(head, 2); //calling rotate function
return 0;
}
| 1,433
|
C++
|
.cpp
| 62
| 18.048387
| 110
| 0.512088
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,150
|
linked_list_operations.cpp
|
OpenGenus_cosmos/code/data_structures/src/list/singly_linked_list/operations/unclassified/linked_list_operations.cpp
|
#include <iostream>
using namespace std;
//built node .... node = (data and pointer)
struct node
{
int data; //data item
node* next; //pointer to next node
};
//built linked list
class linkedlist
{
private:
node* head; //pointer to the first node
public:
linkedlist() //constructor
{
head = NULL; //head pointer points to null in the beginning == empty list
}
//declaration
void addElementFirst(int d); //add element in the beginning (one node)
void addElementEnd(int d); //add element in the end (one node)
void addElementAfter(int d, int b); //add element d before node b
void deleteElement(int d);
void display(); //display all nodes
};
//definition
//1-Push front code
void linkedlist::addElementFirst(int d)
{
node* newNode = new node;
newNode->data = d;
newNode->next = head;
head = newNode;
}
//2-Push back code
void linkedlist::addElementEnd(int x)
{
node* newNode = new node;
node* temp = new node;
temp = head;
newNode->data = x;
if (temp == NULL)
{
newNode->next = NULL;
head = newNode;
return;
}
while (temp->next != NULL)
temp = temp->next;
newNode->next = NULL;
temp->next = newNode;
}
//3-Push after code
//head->10->5->8->NULL
//if d=5,key=2
//head->10->5->2->8->NULL
void linkedlist::addElementAfter(int d, int key)
{
node* search = new node; //search is pointer must search to points to the node that we want
search = head; //firstly search must points to what head points
while (search != NULL) //if linked list has nodes and is not empty
{
if (search->data == d)
{
node* newNode = new node;
newNode->data = key; //put key in data in newNode
newNode->next = search->next; //make the next of newNode pointer to the next to search pointer
search->next = newNode; //then make search pointer to the newNode
return; //or break;
}
//else
search = search->next;
}
if (search == NULL) //if linked list empty
cout << "The link not inserted because there is not found the node " << d <<
" in the LinkedList. " << endl;
}
//4-delete code
void linkedlist::deleteElement(int d)
{
node* del;
del = head;
if (del == NULL)
{
cout << "Linked list is empty" << endl;
return;
}
if (del->data == d) //if first element in linked list is the element that we want to delete ... or one element is what we want
{
head = del->next; //make head points to the next to del
return;
}
//if(del->data!=d) .... the same
if (del->next == NULL)
{
cout << "Is not here, So not deleted." << endl;
return;
}
//if here more one nodes...one node points to another node ... bigger than 2 nodes .. at least 2 nodes
while (del->next != NULL)
{
if (del->next->data == d)
{
node* tmp = del->next;
del->next = del->next->next;
delete tmp;
return;
}
//else
del = del->next;
}
cout << "Is not here, So not deleted." << endl;
}
//void linkedlist::display(node *head)
void linkedlist::display()
{
int n = 0; //counter for number of node
node* current = head;
if (current == NULL)
cout << "This is empty linked list." << endl;
while (current != NULL)
{
cout << "The node data number " << ++n << " is " << current->data << endl;
current = current->next;
}
cout << endl;
}
int main()
{
linkedlist li;
li.display();
li.addElementFirst(25); //head->25->NULL
li.addElementFirst(36); //head->36->25->NULL
li.addElementFirst(49); //head->49->36->25->NULL
li.addElementFirst(64); //head->64->49->36->25->NULL
cout << "After adding in the first of linked list" << endl;
li.display();
//64
//49
//36
//25
cout << endl;
cout << "After adding in the end of linked list" << endl;
//head->64->49->36->25->NULL
li.addElementEnd(25); //head->25->NULL
li.addElementEnd(36); //head->25->36->NULL
li.addElementEnd(49); //head->25->36->49->NULL
li.addElementEnd(64); //head->25->36->49->64->NULL
//head->64->49->36->25->25->36->49->64->NULL
li.display();
cout << endl;
//head->64->49->36->25->25->36->49->64->NULL
cout << "linked list after adding 10 after node that has data = 49" << endl;
li.addElementAfter(49, 10);
li.display();
//head->64->49->10->36->25->25->36->49->64->NULL
//head->64->49->10->36->25->25->36->49->64->NULL
cout << "linked list after adding deleting 49" << endl;
li.deleteElement(49);
li.display();
//head->64->10->36->25->25->36->49->64->NULL
//Notice :delete the first 49 ... not permission for duplicates
return 0;
}
| 5,091
|
C++
|
.cpp
| 164
| 25.640244
| 133
| 0.572014
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,151
|
rotate_a_linked_list_by_k_nodes.cpp
|
OpenGenus_cosmos/code/data_structures/src/list/singly_linked_list/operations/rotate_a_linked_list_by_k_nodes/rotate_a_linked_list_by_k_nodes.cpp
|
// C++ program to rotate a linked list counter clock wise by k Nodes
// where k can be greater than length of linked list
#include <iostream>
class Node {
public:
int data;
Node *next;
Node(int d): next(nullptr),data(d) {
}
};
Node *insert() {
// no. of values to insert
std::cout << "Enter no. of Nodes you want to insert in linked list: \n";
int n;
std::cin >> n;
Node *head = nullptr;
Node *temp = head;
std::cout << "Enter " << n << " values of linked list : \n";
for (int i = 0; i < n; ++i) {
int value;
std::cin >> value;
if (i == 0) {
// insert at head
head = new Node(value);
temp = head;
continue;
} else {
temp->next = new Node(value);
temp = temp->next;
}
}
return head;
}
Node *rotate(Node *head, int k) {
// first check whether k is small or greater than length of linked list
// so first find length of linked list
int len = 0;
Node *temp = head;
while (temp != nullptr) {
temp = temp->next;
len++;
}
// length of linked list = len
// update k according to length of linked list
// because k can be greater than length of linked list
k %= len;
if (k == 0) {
// since when k is multiple of len its mod becomes zero
// so we have to correct it
k = len;
}
if (k == len) {
// since if k==len then even after rotating it linked list will remain same
return head;
}
int count = 1;
temp = head;
while (count < k and temp != nullptr) {
temp = temp->next;
count++;
}
Node *newHead = temp->next;
temp->next = nullptr;
temp = newHead;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = head;
return newHead;
}
void printList(Node *head) {
Node *temp = head;
while (temp != nullptr) {
std::cout << temp->data << " --> ";
temp = temp->next;
}
std::cout << "nullptr \n";
return;
}
int main() {
Node *head = insert();
printList(head);
std::cout << "Enter value of k: \n";
int k;
std::cin >> k;
head = rotate(head, k);
std::cout << "After rotation : \n";
printList(head);
return 0;
}
// Input and Output :
/*
Enter no. of Nodes you want to insert in linked list:
9
Enter 9 values of linked list :
1 2 3 4 5 6 7 8 9
1 --> 2 --> 3 --> 4 --> 5 --> 6 --> 7 --> 8 --> 9 --> nullptr
Enter value of k:
3
After rotation :
4 --> 5 --> 6 --> 7 --> 8 --> 9 --> 1 --> 2 --> 3 --> nullptr
*/
| 2,742
|
C++
|
.cpp
| 102
| 20.490196
| 84
| 0.52144
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,152
|
detect_cycle.cpp
|
OpenGenus_cosmos/code/data_structures/src/list/singly_linked_list/operations/detect_cycle/detect_cycle.cpp
|
/*
* Part of Cosmos by OpenGenus Foundation
*/
#include <iostream>
using namespace std;
// Singly-Linked List Defined
struct Node
{
int data;
Node* next;
Node(int val)
{
data = val;
next = NULL;
}
};
//Function to add nodes to the linked list
Node* TakeInput(int n)
{
Node* head = NULL;
//head of the Linked List
Node* tail = NULL;
//Tail of the Linked List
while (n--)
{
int value;
//data value(int) of the node
cin >> value;
//creating new node
Node* newNode = new Node(value);
//if the is no elements/nodes in the linked list so far.
if (head == NULL)
head = tail = newNode; //newNode is the only node in the LL
else // there are some elements/nodes in the linked list
{
tail->next = newNode; // new Node added at the end of the LL
tail = newNode; // last node is tail node
}
}
return head;
}
Node* DetectCycle(Node* head)
{
Node* slow = head;
Node* fast = head;
while (fast->next->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
return fast;
}
return NULL;
}
void RemoveCycle(Node* head, Node* intersect_Node)
{
Node* slow = head;
Node* prev = NULL;
while (slow != intersect_Node)
{
slow = slow->next;
prev = intersect_Node;
intersect_Node = intersect_Node->next;
}
prev->next = NULL; //cycle removed
}
void PrintLL(Node* head)
{
Node* tempPtr = head;
// until it reaches the end
while (tempPtr != NULL)
{
//print the data of the node
cout << tempPtr->data << " ";
tempPtr = tempPtr->next;
}
cout << endl;
}
int main()
{
int n;
//size of the linked list
cin >> n;
Node* head = TakeInput(n);
//creating a cycle in the linked list
// For n=5 and values 1 2 3 4 5
head->next->next->next->next->next = head->next->next; // change this according tp your input
// 1-->2-->3-->4-->5-->3-->4-->5-->3--> ... and so on
// PrintLL(head); Uncomment this to check cycle
RemoveCycle(head, DetectCycle(head));
PrintLL(head);
return 0;
}
| 2,265
|
C++
|
.cpp
| 93
| 19.053763
| 97
| 0.57308
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,153
|
nth_node_linked_list.cpp
|
OpenGenus_cosmos/code/data_structures/src/list/singly_linked_list/operations/nth_node_linked_list/nth_node_linked_list.cpp
|
///
/// Part of Cosmos by OpenGenus Foundation
/// Contributed by: Pranav Gupta (foobar98)
/// Print Nth node of a singly linked list in the reverse manner
///
#include <iostream>
using namespace std;
// Linked list node
struct Node
{
public:
int data;
Node *next;
Node(int data)
{
this->data = data;
next = NULL;
}
};
// Create linked list of n nodes
Node* takeInput(int n)
{
// n is the number of nodes in linked list
Node *head = NULL, *tail = NULL;
int i = n;
cout << "Enter elements: ";
while (i--)
{
int data;
cin >> data;
Node *newNode = new Node(data);
if (head == NULL)
{
head = newNode;
tail = newNode;
}
else
{
tail->next = newNode;
tail = newNode;
}
}
return head;
}
// To find length of linked list
int length(Node *head)
{
int l = 0;
while (head != NULL)
{
head = head->next;
l++;
}
return l;
}
void printNthFromEnd(Node *head, int n)
{
// Get length of linked list
int len = length(head);
// check if n is greater than length
if (n > len)
return;
// nth from end = (len-n+1)th node from beginning
for (int i = 1; i < len - n + 1; i++)
head = head->next;
cout << "Nth node from end: " << head->data << endl;
}
int main()
{
cout << "Enter no. of nodes in linked list: ";
int x;
cin >> x;
Node *head = takeInput(x);
cout << "Enter n (node from the end): ";
int n;
cin >> n;
printNthFromEnd(head, n);
}
| 1,629
|
C++
|
.cpp
| 78
| 15.846154
| 64
| 0.548177
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,154
|
merge_sorted.cpp
|
OpenGenus_cosmos/code/data_structures/src/list/singly_linked_list/operations/merge_sorted/merge_sorted.cpp
|
/*
* Part of Cosmos by OpenGenus Foundation
*/
#include <iostream>
using namespace std;
//Definition for singly-linked list.
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL)
{
}
};
//Merge Function for linkedlist
ListNode* merge(ListNode* head1, ListNode* head2)
{
ListNode* head3 = NULL;
ListNode* temp3 = NULL;
while (head1 && head2)
{
if (head1->val < head2->val)
{
if (head3 == NULL)
head3 = head1;
if (temp3)
temp3->next = head1;
temp3 = head1;
head1 = head1->next;
}
else
{
if (head3 == NULL)
head3 = head2;
if (temp3)
temp3->next = head2;
temp3 = head2;
head2 = head2->next;
}
}
if (head1)
{
if (head3)
temp3->next = head1;
else
return head1;
}
if (head2)
{
if (head3)
temp3->next = head2;
else
return head2;
}
return head3;
}
//Sort function for linkedlist following divide and conquer approach
ListNode* merge_sort(ListNode* A)
{
if (A == NULL || A->next == NULL)
return A;
ListNode* temp = A;
int i = 1;
while (temp->next)
{
i++;
temp = temp->next;
}
int d = i / 2;
int k = 0;
temp = A;
while (temp)
{
k++;
if (k == d)
break;
temp = temp->next;
}
ListNode* head1 = A;
ListNode* head2 = temp->next;
temp->next = NULL;
head1 = merge_sort(head1);
head2 = merge_sort(head2);
ListNode* head3 = merge(head1, head2);
return head3;
}
//function used for calling divide and xonquer algorithm
ListNode* sortList(ListNode* A)
{
ListNode* head = merge_sort(A);
return head;
}
int main()
{
ListNode* head = new ListNode(5);
ListNode* temp = head; // Creating a linkedlist
int i = 4;
while (i > 0) //Adding values to the linkedlist
{
ListNode* t = new ListNode(i);
temp->next = t;
temp = temp->next;
i--;
}
head = sortList(head); //calling merge_sort function
return 0;
}
| 2,323
|
C++
|
.cpp
| 107
| 15.280374
| 72
| 0.516129
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,157
|
skip_list.cpp
|
OpenGenus_cosmos/code/data_structures/src/list/skip_list/skip_list.cpp
|
/**
* skip list C++ implementation
*
* Average Worst-case
* Space O(n) O(n log n)
* Search O(log n) 0(n)
* Insert O(log n) 0(n)
* Delete O(log n) 0(n)
* Part of Cosmos by OpenGenus Foundation
*/
#include <algorithm> // std::less, std::max
#include <cassert> // assert
#include <iostream> // std::cout, std::endl, std::ostream
#include <map> // std::map
#include <stdlib.h> // rand, srand
#include <time.h> // time
template <typename val_t> class skip_list;
template <typename val_t>
std::ostream & operator<<(std::ostream &os, const skip_list<val_t> &jls);
template <typename val_t>
class skip_list
{
private:
/**
* skip_node
*/
struct skip_node
{
val_t data;
skip_node **forward;
int height;
skip_node(int ht)
: forward{new skip_node*[ht]}, height{ht}
{
for (int i = 0; i < ht; ++i)
forward[i] = nullptr;
}
skip_node(const val_t &ele, int ht)
: skip_node(ht)
{
data = ele;
}
~skip_node()
{
if (forward[0])
delete forward[0];
delete[] forward;
}
};
/* member variables */
skip_node *head_;
int size_,
cur_height_;
constexpr const static int MAX_HEIGHT = 10;
constexpr const static float PROB = 0.5f;
/* private functions */
bool coin_flip()
{
return ((float) rand() / RAND_MAX) < PROB;
}
int rand_height()
{
int height = 1;
for (; height < MAX_HEIGHT && coin_flip(); ++height)
{
}
return height;
}
skip_node ** find(const val_t &ele)
{
auto comp = std::less<val_t>();
skip_node **result = new skip_node*[cur_height_],
*cur_node = head_;
for (int lvl = cur_height_ - 1; lvl >= 0; --lvl)
{
while (cur_node->forward[lvl]
&& comp(cur_node->forward[lvl]->data, ele))
cur_node = cur_node->forward[lvl];
result[lvl] = cur_node;
}
return result;
}
void print(std::ostream &os) const
{
int i;
for (skip_node *n = head_; n != nullptr; n = n->forward[0])
{
os << n->data << ": ";
for (i = 0; i < cur_height_; ++i)
{
if (i < n->height)
os << "[ ] ";
else
os << " | ";
}
os << std::endl;
os << " ";
for (i = 0; i < cur_height_; ++i)
os << " | ";
os << std::endl;
}
}
public:
/* Default C'tor */
skip_list()
: head_{new skip_node(MAX_HEIGHT)}, size_{0}, cur_height_{0}
{
srand((unsigned)time(0));
}
/* D'tor */
~skip_list()
{
delete head_;
}
/**
* size
* @return - the number of elements in the list
*/
int size()
{
return size_;
}
/**
* insert
* @param ele - the element to be inserted into the list
*/
void insert(const val_t &ele)
{
int new_ht = rand_height();
skip_node *new_node = new skip_node(ele, new_ht);
cur_height_ = std::max(new_ht, cur_height_);
skip_node **pre = find(ele);
for (int i = 0; i < new_ht; ++i)
{
new_node->forward[i] = pre[i]->forward[i];
pre[i]->forward[i] = new_node;
}
++size_;
delete[] pre;
}
/**
* contains
* @param ele - the element to search for
* @retrun - true if the element is in the list, false otherwise
*/
bool contains(const val_t &ele)
{
skip_node **pre = find(ele);
bool result = pre[0] &&
pre[0]->forward[0] &&
pre[0]->forward[0]->data == ele;
delete[] pre;
return result;
}
/**
* remove
* @param ele - the element to delete if found
*/
void remove(const val_t &ele)
{
if (!contains(ele))
{
std::cout << ele << " not found!" << std::endl;
return;
}
skip_node *tmp, **pre = find(ele), *del = pre[0]->forward[0];
for (int i = 0; i < cur_height_; ++i)
{
tmp = pre[i]->forward[i];
if (tmp != nullptr && tmp->data == ele)
{
pre[i]->forward[i] = tmp->forward[i];
tmp->forward[i] = nullptr;
}
}
--size_;
delete del;
delete[] pre;
}
friend std::ostream & operator<< <val_t>(std::ostream &os,
const skip_list<val_t> &ls);
}; // skip_node
template<typename val_t>
std::ostream & operator<<(std::ostream &os, const skip_list<val_t> &ls)
{
ls.print(os);
return os;
}
int main()
{
auto ints = { 1, 4, 2, 7, 9, 3, 5, 8, 6 };
skip_list<int> isl;
for (auto i : ints)
{
isl.insert(i);
std::cout << isl << std::endl;
}
for (auto i : ints)
{
assert(isl.contains(i));
std::cout << "removing " << i << std::endl;
isl.remove(i);
std::cout << isl << std::endl;
}
return 0;
}
| 5,299
|
C++
|
.cpp
| 206
| 18.320388
| 73
| 0.468849
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,159
|
is_circular_linked_list.cpp
|
OpenGenus_cosmos/code/data_structures/src/list/circular_linked_list/operations/is_circular_linked_list.cpp
|
#include <iostream>
using namespace std;
//node structure
struct node{
int data;
struct node* next;
};
//function to find the circular linked list.
bool isCircular(node *head){
node *temp=head;
while(temp!=NULL)
{ //if temp points to head then it has completed a circle,thus a circular linked list.
if(temp->next==head)
return true;
temp=temp->next;
}
return false;
}
//function for inserting new nodes.
node *newNode(int data){
struct node *temp=new node;
temp->data=data;
temp->next=NULL;
}
int main() {
//first case
struct node* head=newNode(1);
head->next=newNode(2);
head->next->next=newNode(3);
head->next->next->next=newNode(4);
head->next->next->next->next=head;
if(isCircular(head))
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
//second case
struct node* head1=newNode(1);
head1->next=newNode(2);
if(isCircular(head1))
cout<<"yes";
else
cout<<"no";
return 0;
}
| 1,029
|
C++
|
.cpp
| 44
| 18.704545
| 90
| 0.629213
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,160
|
FloydAlgo_circular_ll.cpp
|
OpenGenus_cosmos/code/data_structures/src/list/circular_linked_list/operations/FloydAlgo_circular_ll.cpp
|
#include <iostream>
using namespace std;
struct node{
int data;
struct node* next;
};
bool isCircular(node *head)
{ //fast ptr is ahead of slow pointer
node* slow,*fast;
slow=head;
fast=head->next;
//if linked list is empty it returns true as its entirely null.
if(head==NULL)
return true;
while(true)
{ //fast ptr traverses quickly so If its not circular then it reaches or points to null.
if(fast==NULL||fast->next==NULL)
{
return false;
}
//when circular fast meets or points to slow pointer while traversing
else if(slow==fast||fast->next==slow)
{
return true;
}
//for moving forward through linked list.
else
{
slow=slow->next;
//fast traverses way ahead so it distinguishes loops out of circular list.
fast=fast->next->next;
}
}
}
node *newNode(int data){
struct node *temp=new node;
temp->data=data;
temp->next=NULL;
}
int main() {
struct node* head=newNode(1);
head->next=newNode(2);
head->next->next=newNode(12);
head->next->next->next=newNode(122);
head->next->next->next->next=head;
if(isCircular(head))
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
struct node* head1=newNode(1);
head1->next=newNode(2);
head1->next->next=newNode(3);
head1->next->next->next=newNode(7);
if(isCircular(head1))
cout<<"yes";
else
cout<<"no";
return 0;
}
| 1,550
|
C++
|
.cpp
| 59
| 20.050847
| 92
| 0.597176
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,161
|
bloom_filter.cpp
|
OpenGenus_cosmos/code/data_structures/src/hashs/bloom_filter/bloom_filter.cpp
|
#include <iostream>
using namespace std;
class BloomFilter
{
public:
BloomFilter(int size)
{
size_ = size;
bits_ = new char[size_ / 8 + 1];
}
~BloomFilter()
{
delete [] bits_;
}
void Add(int value)
{
int hash = value % size_;
bits_[hash / 8] |= 1 << (hash % 8);
}
bool Contains(int value)
{
int hash = value % size_;
return (bits_[hash / 8] & (1 << (hash % 8))) != 0;
}
private:
char* bits_;
int size_;
};
int main()
{
BloomFilter bloomFilter(1000);
bloomFilter.Add(1);
bloomFilter.Add(2);
bloomFilter.Add(1001);
bloomFilter.Add(1004);
if (bloomFilter.Contains(1))
cout << "bloomFilter contains 1" << endl;
if (bloomFilter.Contains(2))
cout << "bloomFilter contains 2" << endl;
if (!bloomFilter.Contains(3))
cout << "bloomFilter not contains 3" << endl;
if (bloomFilter.Contains(4))
cout << "bloomFilter not contains 4, but return false positive" << endl;
}
| 1,047
|
C++
|
.cpp
| 44
| 18.5
| 80
| 0.574447
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,162
|
hash_table.cpp
|
OpenGenus_cosmos/code/data_structures/src/hashs/hash_table/hash_table.cpp
|
/*
* Part of Cosmos by OpenGenus Foundation
*
* hash_table synopsis
*
* template<typename _Tp, typename _HashFunc = std::hash<_Tp> >
* class hash_table {
* public:
* typedef _Tp value_type;
* typedef decltype (_HashFunc ().operator()(_Tp())) key_type;
* typedef std::map<key_type, value_type> container_type;
* typedef typename container_type::const_iterator const_iterator;
* typedef typename container_type::size_type size_type;
*
* // Initialize your data structure here.
* hash_table() :_container({}) {}
*
* // Inserts a value to the set. Returns true if the set did not already contain the specified
* element.
* std::pair<const_iterator, bool> insert(const _Tp val);
*
* template<typename _InputIter>
* void insert(_InputIter first, _InputIter last);
*
* void insert(std::initializer_list<_Tp> init_list);
*
* // Removes a value from the set. Returns true if the set contained the specified element.
* const_iterator erase(const _Tp val);
*
* const_iterator erase(const_iterator pos);
*
* // Find a value from the set. Returns true if the set contained the specified element.
*
* const_iterator find(const _Tp val) const;
*
* const_iterator end() const;
*
* bool empty() const;
*
* size_type size() const;
*
* private:
* container_type _container;
*
* key_type hash(const value_type &val) const;
*
* template<typename _InputIter>
* void _insert(_InputIter first, _InputIter last, std::input_iterator_tag);
* };
*/
#include <map>
template<typename _Tp, typename _HashFunc = std::hash<_Tp>>
class hash_table {
public:
typedef _Tp value_type;
typedef decltype (_HashFunc ().operator()(_Tp())) key_type;
typedef std::map<key_type, value_type> container_type;
typedef typename container_type::const_iterator const_iterator;
typedef typename container_type::size_type size_type;
/** Initialize your data structure here. */
hash_table() : _container({})
{
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified
* element. */
std::pair<const_iterator, bool> insert(const _Tp val)
{
key_type key = hash(val);
if (_container.find(key) == _container.end())
{
_container.insert(std::make_pair(key, val));
return make_pair(_container.find(key), true);
}
return make_pair(_container.end(), false);
}
template<typename _InputIter>
void insert(_InputIter first, _InputIter last)
{
_insert(first, last, typename std::iterator_traits<_InputIter>::iterator_category());
}
void insert(std::initializer_list<_Tp> init_list)
{
insert(init_list.begin(), init_list.end());
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
const_iterator erase(const _Tp val)
{
const_iterator it = find(val);
if (it != end())
return erase(it);
return end();
}
const_iterator erase(const_iterator pos)
{
return _container.erase(pos);
}
/** Find a value from the set. Returns true if the set contained the specified element. */
const_iterator find(const _Tp val)
{
key_type key = hash(val);
return _container.find(key);
}
const_iterator find(const _Tp val) const
{
key_type key = hash(val);
return _container.find(key);
}
const_iterator end() const
{
return _container.end();
}
bool empty() const
{
return _container.empty();
}
size_type size() const
{
return _container.size();
}
private:
container_type _container;
key_type hash(const value_type &val) const
{
return _HashFunc()(val);
}
template<typename _InputIter>
void _insert(_InputIter first, _InputIter last, std::input_iterator_tag)
{
_InputIter pos = first;
while (pos != last)
insert(*pos++);
}
};
/*
* // for test
*
* // a user-defined hash function
* template<typename _Tp>
* struct MyHash {
* // hash by C++ boost
* // phi = (1 + sqrt(5)) / 2
* // 2^32 / phi = 0x9e3779b9
* void hash(std::size_t &seed, const _Tp &i) const
* {
* seed ^= std::hash<_Tp>()(i) + 0x87654321 * (seed << 1) + (seed >> 2);
* seed <<= seed % 6789;
* }
*
* std::size_t operator()(const _Tp &d) const
* {
* std::size_t seed = 1234;
* hash(seed, d);
*
* return seed;
* }
* };
*
#include <iostream>
#include <vector>
* using namespace std;
*
* int main() {
* hash_table<int, MyHash<int> > ht;
*
* // test find
* if (ht.find(9) != ht.end())
* cout << __LINE__ << " error\n";
*
* // test insert(1)
* if (!ht.insert(3).second) // return true
* cout << __LINE__ << " error\n";
*
* if (ht.insert(3).second) // return false
* cout << __LINE__ << " error\n";
*
* // test insert(2)
* vector<int> input{10, 11, 12};
* ht.insert(input.begin(), input.end());
* if (ht.find(10) == ht.end())
* cout << __LINE__ << " error\n";
* if (ht.find(11) == ht.end())
* cout << __LINE__ << " error\n";
* if (ht.find(12) == ht.end())
* cout << __LINE__ << " error\n";
*
* // test insert(3)
* ht.insert({13, 14, 15, 16});
*
* // test erase(1)
* ht.erase(13);
*
* // test erase(2)
* auto it = ht.find(14);
* ht.erase(it);
*
* // test empty
* if (ht.empty())
* cout << __LINE__ << " error\n";
*
* // test size
* if (ht.size() != 6)
* cout << __LINE__ << " error\n";
*
* return 0;
* }
*
* // */
| 5,711
|
C++
|
.cpp
| 207
| 23.942029
| 96
| 0.590917
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,163
|
rotate_matrix.cpp
|
OpenGenus_cosmos/code/data_structures/src/2d_array/rotate_matrix.cpp
|
//#rotate square matrix by 90 degrees
#include <bits/stdc++.h>
#define n 5
using namespace std;
void displayimage(
int arr[n][n]);
/* A function to
* rotate a n x n matrix
* by 90 degrees in
* anti-clockwise direction */
void rotateimage(int arr[][n])
{ // Performing Transpose
for (int i = 0; i < n; i++)
{
for (int j = i; j < n; j++)
swap(arr[i][j], arr[j][i]);
}
// Reverse every row
for (int i = 0; i < n; i++)
reverse(arr[i], arr[i] + n);
}
// Function to print the matrix
void displayimage(int arr[n][n])
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
cout << arr[i][j] << " ";
cout << "\n";
}
cout << "\n";
}
int main()
{
int arr[n][n] = {
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20},
{21, 22, 23, 24, 25}};
// displayimage(arr);
rotateimage(arr);
// Print rotated matrix
displayimage(arr);
return 0;
}
/*-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/
/* Test Case 2
* int arr[n][n] = {
* {1, 2, 3, 4},
* {5, 6, 7, 8},
* {9, 10, 11, 12},
* {13, 14, 15, 16}
* };
*/
/* Tese Case 3
*int mat[n][n] = {
* {1, 2},
* {3, 4}
* };*/
/*
Time complexity : O(n*n)
Space complexity: O(1)
*/
| 1,601
|
C++
|
.cpp
| 64
| 21.03125
| 177
| 0.383706
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,164
|
SpiralMatrix.cpp
|
OpenGenus_cosmos/code/data_structures/src/2d_array/SpiralMatrix.cpp
|
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> generateSpiralMatrix(int n) {
vector<vector<int>> matrix(n, vector<int>(n));
int left = 0;
int right = n - 1;
int top = 0;
int bottom = n - 1;
int direction = 0;
int value = 1;
while (left <= right && top <= bottom) {
if (direction == 0) {
for (int i = left; i <= right; i++) {
matrix[top][i] = value++;
}
top++;
} else if (direction == 1) {
for (int j = top; j <= bottom; j++) {
matrix[j][right] = value++;
}
right--;
} else if (direction == 2) {
for (int i = right; i >= left; i--) {
matrix[bottom][i] = value++;
}
bottom--;
} else {
for (int j = bottom; j >= top; j--) {
matrix[j][left] = value++;
}
left++;
}
direction = (direction + 1) % 4;
}
return matrix;
}
int main() {
int n;
cin >> n;
vector<vector<int>> spiralMatrix = generateSpiralMatrix(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << spiralMatrix[i][j] << " ";
}
cout << endl;
}
return 0;
}
| 1,323
|
C++
|
.cpp
| 49
| 18.571429
| 63
| 0.435229
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,165
|
set_matrix_zero.cpp
|
OpenGenus_cosmos/code/data_structures/src/2d_array/set_matrix_zero.cpp
|
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <cmath>
#include <set>
#include <unordered_map>
#include <numeric>
#include <algorithm>
//#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define int int64_t
int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
void setneg(vector<vector<int>> &matrix, int row, int col)
{
for (int i = 0; i < matrix.size(); ++i)
if (matrix[i][col] != 0)
matrix[i][col] = -2147483636;
for (int j = 0; j < matrix[0].size(); ++j)
if (matrix[row][j] != 0)
matrix[row][j] = -2147483636;
}
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t = 1;
cin >> t;
while (t--)
{
// taking input of number of rows & coloums
int n, m;
cin >> n >> m;
// creating a matrix of size n*m and taking input
vector<vector<int>> matrix(n, vector<int>(m));
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> matrix[i][j];
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (!matrix[i][j])
{
setneg(matrix, i, j);
}
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (matrix[i][j]==-2147483636)
{
matrix[i][j]=0;
}
}
}
cout<<endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout<<matrix[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
}
return 0;
}
| 1,888
|
C++
|
.cpp
| 82
| 14.963415
| 58
| 0.4132
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,167
|
bag.cpp
|
OpenGenus_cosmos/code/data_structures/src/bag/bag.cpp
|
//Needed for random and vector
#include <vector>
#include <string>
#include <cstdlib>
using std::string;
using std::vector;
//Bag Class Declaration
class Bag
{
private:
vector<string> items;
int bagSize;
public:
Bag();
void add(string);
bool isEmpty();
int sizeOfBag();
string remove();
};
/******************************************************************************
* Bag::Bag()
* This is the constructor for Bag. It initializes the size variable.
******************************************************************************/
Bag::Bag()
{
bagSize = 0;
}
/******************************************************************************
* Bag::add
* This function adds an item to the bag.
******************************************************************************/
void Bag::add(string item)
{
//Store item in last element of vector
items.push_back(item);
//Increase the size
bagSize++;
}
/******************************************************************************
* Bag::isEmpty
* This function returns true if the bag is empty and returns false if the
* bag is not empty
******************************************************************************/
bool Bag::isEmpty(){
//True
if(bagSize == 0){
return true;
}
//False
else{
return false;
}
}
/******************************************************************************
* Bag::size
* This function returns the current number of items in the bag
******************************************************************************/
int Bag::sizeOfBag(){
return bagSize;
}
/******************************************************************************
* Bag::remove
* This function removes a random item from the bag and returns which item was
* removed from the bag
******************************************************************************/
string Bag::remove(){
//Get random item
int randIndx = rand() % bagSize;
string removed = items.at(randIndx);
//Remove from bag
items.erase(items.begin() + randIndx);
bagSize--;
//Return removed item
return removed;
}
| 2,210
|
C++
|
.cpp
| 75
| 26.533333
| 81
| 0.414657
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,170
|
queue_vector.cpp
|
OpenGenus_cosmos/code/data_structures/src/queue/queue/queue_vector.cpp
|
#include <iostream>
#include <vector>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
class Queue
{
private:
// Vector for storing all of the values
vector<int> _vec;
public:
void enqueue(int & p_put_obj); // Puts object at the end of the queue
void dequeue(int & p_ret_obj); // Returns object at the start of the queue and removes from queue
void peek(int & p_peek_obj); // Returns object at the start of the queue but doesn't remove it
bool is_empty(); // Checks if the queue is full
};
// Purpose: Put a value onto the end of the queue
// Params : p_put_obj - reference to the object you want to enqueue
void Queue::enqueue(int & p_put_obj)
{
// Use the inbuild push_back vector method
_vec.push_back(p_put_obj);
}
// Purpose: Gets the value from the front of the queue
// Params : p_ret_obj - Reference to an empty object to be overwritten by whatever is dequeued
void Queue::dequeue(int & p_ret_obj)
{
// Set the value to what's in the start of the vector
p_ret_obj = _vec[0];
// Delete the first value in the vector
_vec.erase(_vec.begin());
}
// Purpose: Checks if the queue is empty
// Returns: True if the queue is empty
bool Queue::is_empty()
{
return _vec.empty();
}
// Purpose: Returns the value at the front of the queue, without popping it
// Params : p_peek_obj - reference to the object to be overwritten by the data in the front of the queue
void Queue::peek(int &p_peek_obj)
{
p_peek_obj = _vec[0];
}
int main()
{
Queue q;
int i = 0;
int j = 1;
q.enqueue(i);
cout << "Enqueueing " << i << " to the queue" << endl;
q.enqueue(j);
cout << "Enqueueing " << j << " to the queue" << endl;
int k, l, m;
q.peek(m);
cout << "Peeking into the queue, found " << m << endl;
q.dequeue(k);
cout << "Dequeueing, found " << k << endl;
q.dequeue(l);
cout << "Dequeueing, found " << l << endl;
if (q.is_empty())
cout << "The queue is now empty" << endl;
else
cout << "The queue is not empty" << endl;
}
| 2,075
|
C++
|
.cpp
| 64
| 29.1875
| 104
| 0.65
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,171
|
queue.cpp
|
OpenGenus_cosmos/code/data_structures/src/queue/queue/queue.cpp
|
/* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
#include <cassert>
template <typename T>
class Queue {
private:
int m_f;
int m_r;
std::size_t m_size;
T * m_data;
public:
/*! \brief Constructs queue object with size.
* \param sz Size of the queue.
*/
Queue( std::size_t sz = 10) : m_f( -1)
, m_r( -1)
, m_size( sz)
, m_data( new T[sz])
{
/* empty */
}
/*! \brief Destructor
*/
~Queue()
{
delete [] m_data;
}
/*! \brief Insert element at the end of the queue.
* \param value Value to be inserted.
*/
void enqueue( const T& value )
{
int prox_r = (m_r + 1) % m_size;
if (prox_r == 0 or prox_r != m_f)
{
(m_f == -1) ? m_f = 0 : m_f = m_f;
m_data[prox_r] = value;
m_r = prox_r;
}
else
assert(false);
}
/*! \brief Remove element at the end of the queue.
*/
void dequeue()
{
if (m_f != -1)
{
// If there is only 1 element, f = r = -1
if (m_f == m_r)
m_f = m_r = -1;
// If size > 1, f goes forward
else
m_f = (m_f + 1) % m_size;
}
else
assert(false);
}
/*! \brief Get element at the beginning of the queue.
* \return First element at the queue.
*/
T front()
{
if (m_f != -1)
return m_data[m_f];
assert(false);
}
/*! \brief Check if queue is empty.
* \return True if queue is empty, false otherwise.
*/
bool isEmpty()
{
return m_f == -1;
}
/*! \brief Clear content.
*/
void makeEmpty()
{
reserve(m_size);
m_f = m_r = -1;
m_size = 0;
}
/*! \brief Get size of the queue.
* \return Size of the queue.
*/
T size() const
{
if (m_r == m_f)
return 1;
else if (m_r > m_f)
return m_r - m_f + 1;
else
return m_f - m_r + 1;
}
/*! \brief Increase the storage capacity of the array to a value
* that’s is greater or equal to 'new_cap'.
* \param new_cap New capacity.
*/
void reserve( std::size_t new_cap )
{
if (new_cap >= m_size)
{
//<! Allocates new storage area
T *temp = new T[ new_cap ];
//<! Copy content to the new list
for (auto i(0u); i < m_size; i++)
temp[i] = m_data[i];
delete [] m_data; //<! Deallocate old storage area
m_data = temp; //<! Pointer pointing to the new adress
m_size = new_cap; //<! Updates size
}
}
};
int main()
{
Queue<int> queue(3);
queue.enqueue(5);
assert(queue.front() == 5);
assert(queue.size() == 1);
queue.enqueue(4);
queue.enqueue(3);
//remove 2 elements
queue.dequeue();
queue.dequeue();
assert( queue.size() == 1);
//Insert one more
queue.enqueue(2);
assert( queue.size() == 3);
return 0;
}
| 3,076
|
C++
|
.cpp
| 130
| 17.138462
| 73
| 0.486644
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,172
|
queue_using_stack.cpp
|
OpenGenus_cosmos/code/data_structures/src/queue/queue_using_stack/queue_using_stack.cpp
|
#include <iostream>
#include <stack>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
// queue data structure using two stacks
class queue {
private:
stack<int> s1, s2;
public:
void enqueue(int element);
int dequeue();
void displayQueue();
};
// enqueue an element to the queue
void queue :: enqueue(int element)
{
s1.push(element);
}
// dequeue the front element
int queue :: dequeue()
{
// transfer all elements of s1 into s2
if (s1.empty() && s2.empty())
return 0;
while (!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
// pop and store the top element from s2
int ret = s2.top();
s2.pop();
// transfer all elements of s2 back to s1
while (!s2.empty())
{
s1.push(s2.top());
s2.pop();
}
return ret;
}
//display the elements of the queue
void queue :: displayQueue()
{
cout << "\nDisplaying the queue :-\n";
while (!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
while (!s2.empty())
{
cout << s2.top() << " ";
s1.push(s2.top());
s2.pop();
}
}
// main
int main()
{
queue q;
int exit = 0;
int enqueue;
char input;
while (!exit)
{
cout << "Enter e to enqueue,d to dequeue,s to display queue,x to exit: ";
cin >> input;
if (input == 'e')
{
cout << "Enter number to enqueue: ";
cin >> enqueue;
q.enqueue(enqueue);
}
if (input == 'd')
q.dequeue();
if (input == 's')
{
q.displayQueue();
cout << endl;
}
if (input == 'x')
break;
}
return 0;
}
| 1,731
|
C++
|
.cpp
| 85
| 14.835294
| 81
| 0.52474
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,173
|
deque_library_function.cpp
|
OpenGenus_cosmos/code/data_structures/src/queue/double_ended_queue/deque_library_function.cpp
|
#include <iostream>
#include <deque>
using namespace std;
void showdq (deque <int> g)
{
deque <int> :: iterator it; // Iterator to iterate over the deque .
for (it = g.begin(); it != g.end(); ++it)
cout << '\t' << *it;
cout << "\n";
}
int main ()
{
deque <int> que;
int option, x;
do
{
cout << "\n\n DEQUEUE USING STL C++ ";
cout << "\n 1.Insert front";
cout << "\n 2.Insert Back";
cout << "\n 3.Delete front";
cout << "\n 4.Delete Back";
cout << "\n 5.Display ";
cout << "\n Enter your option : ";
cin >> option;
switch (option)
{
case 1: cout << "\n Enter number : ";
cin >> x;
que.push_front(x);
break;
case 2: cout << "\n Enter number : ";
cin >> x;
que.push_back(x);
break;
case 3: que.pop_front();
break;
case 4: que.pop_back();
break;
case 5: showdq(que);
break;
}
} while (option != 6);
return 0;
}
| 1,132
|
C++
|
.cpp
| 44
| 18.068182
| 103
| 0.443721
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,177
|
LazySegmentTree.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/segment_tree/LazySegmentTree.cpp
|
// There are generally three main function for lazy propagation in segment tree
// Lazy propagation is used when we have range update query too, without it only point
// update is possible.
// Build function
// THE SEGMENT TREE WRITTEN HERE IS FOR GETTING SUM , FOR MINIMUM, MAXIMUM, XOR AND DISTINCT ELEMENT COUNT RESPECTIVE SEGMENT TREES
// CAN BE MADE JUST BY REPLACING A FEW LINES
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e5;
int seg[4*N],lazy[4*N];
vector<int> arr;
void build(int node, int st, int en) {
if (st == en) {
// left node ,string the single array element
seg[node] = arr[st];
return;
}
int mid = (st + en) / 2;
// recursively call for left child
build(2 * node, st, mid);
// recursively call for the right child
build(2 * node + 1, mid + 1, en);
// Updating the parent with the values of the left and right child.
seg[node] = seg[2 * node] + seg[2 * node + 1];
}
//Above, every node represents the sum of both subtrees below it. Build function is called once per array, and the time complexity of build() is O(N).
// Update Operation function
void update(int node, int st, int en, int l, int r, int val) {
if (lazy[node] != 0) // if node is lazy then update it
{
seg[node] += (en - st + 1) * lazy[node];
if (st != en) // if its children exist then mark them lazy
{
lazy[2 * node] += lazy[node];
lazy[2 * node + 1] += lazy[node];
}
lazy[node] = 0; // No longer lazy
}
if ((en < l) || (st > r)) // case 1
{
return;
}
if (st >= l && en <= r) // case 2
{
seg[node] += (en - st + 1) * val;
if (st != en) {
lazy[2 * node] += val; // mark its children lazy
lazy[2 * node + 1] += val;
}
return;
}
// case 3
int mid = (st + en) / 2;
// recursively call for updating left child
update(2 * node, st, mid, l, r, val);
// recursively call for updating right child
update(2 * node + 1, mid + 1, en, l, r, val);
// Updating the parent with the values of the left and right child.
seg[node] = (seg[2 * node] + seg[2 * node + 1]);
}
//Here above we take care of three cases for base case:
// Segment lies outside the query range: in this case, we can just simply return back and terminate the call.
// Segment lies fully inside the query range: in this case, we simply update the current node and mark the children lazy.
// If they intersect partially, then we all update for both the child and change the values in them.
// Query function
int query(int node, int st, int en, int l, int r) {
/*If the node is lazy, update it*/
if (lazy[node] != 0) {
seg[node] += (en - st + 1) * lazy[node];
if (st != en) //Check if the child exist
{
// mark both the child lazy
lazy[2 * node] += lazy[node];
lazy[2 * node + 1] += lazy[node];
}
// no longer lazy
lazy[node] = 0;
}
// case 1
if (en < l || st > r) {
return 0;
}
// case 2
if ((l <= st) && (en <= r)) {
return seg[node];
}
int mid = (st + en) / 2;
//query left child
ll q1 = query(2 * node, st, mid, l, r);
// query right child
ll q2 = query(2 * node + 1, mid + 1, en, l, r);
return (q1 + q2);
}
int main(){
int n;
cin >> n;
arr=vector<int>(n+1);
for(int i=1;i<=n;i++)cin >> arr[i];
memset(seg,0,sizeof seg);
memset(lazy,0,sizeof lazy);
build(1,1,n);
return 0;
}
// As compared to non-lazy code only lazy code in base case is added. Also one should remember the kazy implementation only as it can
// help u solve in non-lazy case too.
// Here the insertion, query both take O(logn) time.
| 3,653
|
C++
|
.cpp
| 107
| 30.542056
| 150
| 0.627457
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,178
|
generic_segment_tree.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/segment_tree/generic_segment_tree.cpp
|
/**
* @file generic_segment_tree.cpp
* @author Aryan V S (https://github.com/a-r-r-o-w)
* @brief Implementation of a Generic Segment Tree
*/
namespace arrow {
/**
* @brief Support for two tree memory layouts is provided
*
* Binary:
* - creates the segment tree as a full Binary tree
* - considering the tree is built over `n` elements, the segment tree would allocate
* `4.n` memory for internal usage
*
* EulerTour:
* - more memory efficient than Binary segment tree
* - considering the tree is build over `n` elements, the segment tree would allocate
* `2.n` memory for internal usage
*
* The provided implementation defaults to Binary segment tree if no template parameter is present.
*/
enum class TreeMemoryLayout {
Binary,
EulerTour
};
/**
* @brief Generic Segment Tree
*
* A segment tree allows you to perform operations on an array in an efficient manner
*
* @tparam Type The type of values that the tree holds in its internal nodes
* @tparam impl_type Memory layout type
*/
template <
class Type,
TreeMemoryLayout impl_type = TreeMemoryLayout::Binary
>
class SegmentTree {
private:
// Internal members maintained in the segment tree
std::vector <Type> tree_;
int base_size_;
const std::vector <Type>& base_ref_;
Type (*combine_) (const Type&, const Type&);
public:
/**
* @brief Construct a new segment tree object
*
* @param base_size_ Number of leaf nodes segment tree should have (`n` in the tree_memory_layout documentation)
* @param base Base of the segment tree (leaf node values)
* @param combine_ Function used to combine_ values of children nodes when building parent nodes
*/
SegmentTree (int base_size, const std::vector <Type>& base, Type (*combine) (const Type&, const Type&))
: base_size_ (base_size),
base_ref_ (base),
combine_ (combine) {
if constexpr (impl_type == TreeMemoryLayout::Binary)
tree_.resize(4 * base_size_, Type{});
else
tree_.resize(2 * base_size_, Type{});
_build_impl(0, 0, base_size_ - 1);
}
/**
* @brief Point update in segment tree. Essentially performs `array[position] = value`.
*
* @param position Index to be updated
* @param value Value to be set at `position`
*/
void pointUpdate (int position, const Type& value)
{ _point_update_impl(0, 0, base_size_ - 1, position, value); }
/**
* @brief Point query in segment tree. Essentially returns `array[position]`
*
* @param position Index to be queried
* @return Type `array[position]`
*/
Type pointQuery (int position)
{ return _point_query_impl(0, 0, base_size_ - 1, position); }
/**
* @brief Range query in segment tree. Essentially performs the `combine_` function
* on the range `array[l, r]` (bounds are inclusive).
*
* @param l Left bound of query (inclusive)
* @param r Right bound of query (inclusive)
* @return Type Result of the query based on `combine_`
*/
Type rangeQuery (int l, int r)
{ return _range_query_impl(0, 0, base_size_ - 1, l, r); }
/**
* @brief Custom point update in segment tree.
*
* The implementation for this method can be added by the user if they would like
* to perform updates in a different sense from the norm.
*
* @tparam ParamTypes Types of parameters that will be passed to the update implementation
* @param position Index to be updated
* @param params Parameter list required by custom update implementation
*/
template <typename... ParamTypes>
void customPointUpdate (int position, const ParamTypes&... params)
{ _custom_point_update_impl(0, 0, base_size_ - 1, position, params...); }
/**
* @brief Custom point query in segment tree.
*
* The implementation for this method can be added by the user if they would like
* to perform updates in a different sense from the norm.
*
* @tparam ParamTypes Types of parameters that will be passed to the query implementation
* @param position Index to be queried
* @param params Parameter list required by custom query implementation
*/
template <typename... ParamTypes>
Type customPointQuery (int position, const ParamTypes&... params)
{ _custom_point_query_impl(0, 0, base_size_ - 1, position, params...); }
/**
* @brief Custom query/update in segment tree.
*
* The implementation for this method can be added by the user if they would like
* to perform queries in a different sense from the norm. It is very flexible with
* the requirements of the user.
*
* This function is flexible in the sense that you can copy the body multiple times and rename
* it to achieve different functionality as per liking.
*
* Operations like `lazy propagation` or `beats` or `persistence` have not been implemented, and
* have been left to the user to do as per their liking. It can be done very easily by manipulating
* the body of the _custom_query_impl method (and/or creating copies of this function with different
* names for different purposes).
*
* @tparam ParamTypes Types of parameters that will be passed to the query/update implementation
* @param params Parameter list required by custom query/update implementation
*/
template <typename ReturnType, typename... ParamTypes>
ReturnType customQuery (const ParamTypes&... params)
{ return _custom_query_impl <ReturnType> (0, 0, base_size_ - 1, params...); }
private:
/**
* @brief Returns the index of the left child given the parent index based on
* chosen tree_memory_layout
*
* @param v Index of parent
* @param tl Left bound of parent
* @param tr Right bound of parent
* @return int Index of left child of parent
*/
int _get_leftchild (int v, [[maybe_unused]] int tl, [[maybe_unused]] int tr) {
if constexpr (impl_type == TreeMemoryLayout::Binary)
return 2 * v + 1;
else
return v + 1;
}
/**
* @brief Returns the index of the right child given the parent index based on
* chosen tree_memory_layout
*
* @param v Index of parent
* @param tl Left bound of parent
* @param tr Right bound of parent
* @return int Index of right child of parent
*/
int _get_rightchild (int v, [[maybe_unused]] int tl, [[maybe_unused]] int tr) {
if constexpr (impl_type == TreeMemoryLayout::Binary)
return 2 * v + 2;
else {
int tm = (tl + tr) / 2;
int node_count = tm - tl + 1;
return v + 2 * node_count;
}
}
/**
* @brief Internal function to build the segment tree
*
* @param v Index of node where the segment tree starts to build
* @param tl Left bound of node
* @param tr Right bound of node
*/
void _build_impl (int v, int tl, int tr) {
if (tl == tr) {
tree_[v] = base_ref_[tl];
return;
}
int tm = (tl + tr) / 2;
int lchild = _get_leftchild(v, tl, tr);
int rchild = _get_rightchild(v, tl, tr);
_build_impl(lchild, tl, tm);
_build_impl(rchild, tm + 1, tr);
tree_[v] = combine_(tree_[lchild], tree_[rchild]);
}
/**
* @brief Internal implementation of point_update
*
* @param v Current node index
* @param tl Current node left bound
* @param tr Current node right bound
* @param position Index to be updated
* @param value Value to be set at `position`
*/
void _point_update_impl (int v, int tl, int tr, int position, const Type& value) {
if (tl == tr) {
tree_[v] = value;
return;
}
int tm = (tl + tr) / 2;
int lchild = _get_leftchild(v, tl, tr);
int rchild = _get_rightchild(v, tl, tr);
// Since we need to only update a single index, we choose the correct
// "side" of the segment tree to traverse to at each step
if (position <= tm)
_point_update_impl(lchild, tl, tm, position, value);
else
_point_update_impl(rchild, tm + 1, tr, position, value);
tree_[v] = combine_(tree_[lchild], tree_[rchild]);
}
/**
* @brief Internal implementation of point_query
*
* @param v Current node index
* @param tl Current node left bound
* @param tr Current node right bound
* @param position Index to be updated
* @return Type Value to be set at `position`
*/
Type _point_query_impl (int v, int tl, int tr, int position) {
if (tl == tr)
return tree_[v];
int tm = (tl + tr) / 2;
int lchild = _get_leftchild(v, tl, tr);
int rchild = _get_rightchild(v, tl, tr);
// Since we need to only update a single index, we choose the correct
// "side" of the segment tree to traverse to at each step
if (position <= tm)
return _point_query_impl(lchild, tl, tm, position);
else
return _point_query_impl(rchild, tm + 1, tr, position);
}
/**
* @brief Internal implementation of rangeQuery
*
* @param v Current node index
* @param tl Current node left bound
* @param tr Current node right bound
* @param l Current query left bound
* @param r Current query right bound
* @return Type Result of the query
*/
Type _range_query_impl (int v, int tl, int tr, int l, int r) {
// We are out of bounds in our search
// Return a sentinel value which must be defaulted in the constuctor of Type
if (l > r)
return {};
// We have found the correct range for the query
// Return the value at current node because it's not required to process further
if (tl == l and tr == r)
return tree_[v];
int tm = (tl + tr) / 2;
int lchild = _get_leftchild(v, tl, tr);
int rchild = _get_rightchild(v, tl, tr);
// We have not yet found the correct range for the query
// Get results of left child and right child and combine_
Type lval = _range_query_impl(lchild, tl, tm, l, std::min(r, tm));
Type rval = _range_query_impl(rchild, tm + 1, tr, std::max(l, tm + 1), r);
return combine_(lval, rval);
}
/**
* @brief Internal implementation of customPointUpdate
*
* Note that you need to change the definition of this function if you're passing
* any variadic argument list in customPointUpdate
*
* @param v Current node index
* @param tl Current node left bound
* @param tr Current node right bound
* @param position Index to be updated
*/
void _custom_point_update_impl (int v, int tl, int tr, int position) {
if (tl == tr) {
throw std::runtime_error("undefined implementation");
return;
}
int tm = (tl + tr) / 2;
int lchild = _get_leftchild(v, tl, tr);
int rchild = _get_rightchild(v, tl, tr);
// Since we need to only update a single index, we choose the correct
// "side" of the segment tree to traverse to at each step
if (position <= tm)
_custom_point_update_impl(lchild, tl, tm, position);
else
_custom_point_update_impl(rchild, tm + 1, tr, position);
tree_[v] = combine_(tree_[lchild], tree_[rchild]);
}
/**
* @brief Internal implementation of customPointQuery
*
* Note that you need to change the definition of this function if you're passing
* any variadic argument list in customPointQuery
*
* @param v Current node index
* @param tl Current node left bound
* @param tr Current node right bound
* @param position Index to be queried
* @return Type Result of the query
*/
Type _custom_point_query_impl (int v, int tl, int tr, int position) {
if (tl == tr) {
throw std::runtime_error("undefined implementation");
return {};
}
int tm = (tl + tr) / 2;
int lchild = _get_leftchild(v, tl, tr);
int rchild = _get_rightchild(v, tl, tr);
// Since we need to only update a single index, we choose the correct
// "side" of the segment tree to traverse to at each step
if (position <= tm)
return _custom_point_query_impl(lchild, tl, tm, position);
else
return _custom_point_query_impl(rchild, tm + 1, tr, position);
}
/**
* @brief Internal implementation of customQuery
*
* The user can create multiple copies with different names for this function and make
* calls accordingly. Read the documentation for customQuery above.
*
* @tparam ReturnType Return type of the custom query/update
* @param v Current node index
* @param tl Current node left bound
* @param tr Current node right bound
* @return ReturnType Return value of the custom query/update
*/
template <typename ReturnType>
ReturnType _custom_query_impl (int v, int tl, int tr) {
if (tl == tr) {
throw std::runtime_error("undefined implementation");
return ReturnType{};
}
int tm = (tl + tr) / 2;
int lchild = _get_leftchild(v, tl, tr);
int rchild = _get_rightchild(v, tl, tr);
// Change functionality as per liking
if (true)
return _custom_query_impl <ReturnType> (lchild, tl, tm);
else
return _custom_query_impl <ReturnType> (rchild, tm + 1, tr);
}
};
};
| 15,299
|
C++
|
.cpp
| 346
| 33.083815
| 120
| 0.568173
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,179
|
segment_tree_optimized.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/segment_tree/segment_tree_optimized.cpp
|
// Program to show optimised segment tree operations like construction, sum query and update
#include <iostream>
using namespace std;
/*Parameters for understanding code easily:
N = size of the array for which we are making the segment tree
arr= Given array, it can be of any size
tree=Array for the segment tree representation*/
void createTreeOp(int *arr, int *tree, int size)
{
// First the array elements are fixed in the tree array from N index to 2N-1 index
for (int i = size; i < 2 * size; i++)
{
tree[i] = arr[i - size];
}
// Now tree elements are inserted by taking sum of nodes on children index from index N-1 to 1
for (int i = size - 1; i > 0; i--)
{
tree[i] = tree[2 * i] + tree[2 * i + 1];
}
// This approach only requires atmost 2N elements to make segment tree of N sized array
}
int sumOp(int *tree, int start, int end, int size)
{
start += size;
end += size;
int sum = 0;
/*Range is set [size+start,size+end] in the beginning. At
each step range is moved up and the value do not belonging
to higher range are added.*/
while (start <= end)
{
if (start % 2 == 1)
{
sum += tree[start++];
}
if (end % 2 == 0)
{
sum += tree[end--];
}
start = start / 2;
end = end / 2;
}
return sum;
}
void update(int *tree, int index, int size, int newVal)
{
index = size + index;
int incr = newVal - tree[index];
// First calculate the increase in the value required in the element after the updating
while (index >= 1)
{
tree[index] += incr;
index = index / 2;
}
// Loop to increment the value incr in the path from root to required indexed leaf node
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *tree = new int[20];
/* In this approach we only require 2N sized tree array for storing the segment
tree and all the operations can be achieved in iterative methods.*/
createTreeOp(arr, tree, 10);
cout<<"SEGMENT TREE"<<endl;
for (int i = 1; i < 20; i++)
{
cout << tree[i] << " ";
}
cout << endl<<endl;
cout <<"The sum of the segment from index to 3 to 5 "<<sumOp(tree, 3, 5, 10)<<endl;
update(tree, 0, 10, -1);
cout <<"Updating the value at index 0 with -1"<<endl;
cout<<endl<<"SEGMENT TREE"<<endl;
for (int i = 1; i < 20; i++)
{
cout << tree[i] << " ";
}
}
| 2,487
|
C++
|
.cpp
| 78
| 26.846154
| 98
| 0.601166
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,180
|
union_find_dynamic.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/multiway_tree/union_find/union_find_dynamic.cpp
|
/* Part of Cosmos by OpenGenus Foundation */
// Union-find stores a graph, and allows two operations in amortized constant time:
// * Add a new edge between two vertices.
// * Check if two vertices belong to same component.
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
// dynamic union find (elementary implementation)
template<typename _ValueType, typename _Hash = std::hash<_ValueType>>
class UnionFind
{
public:
using value_type = _ValueType;
UnionFind()
{
}
// Connect vertices `a` and `b`.
void merge(value_type a, value_type b)
{
// 1. to guarantee that the set has both `a` and `b`
auto na = nodes.find(a);
auto nb = nodes.find(b);
if (na == nodes.end())
{
nodes.insert(a);
na = nodes.find(a);
parents.insert({na, na});
}
if (nb == nodes.end())
{
nodes.insert(b);
nb = nodes.find(b);
parents.insert({nb, nb});
}
// 2. update the map
auto pa = parents.find(na);
while (pa != parents.end() && pa->first != pa->second)
pa = parents.find(pa->second);
if (pa != parents.end())
na = pa->second;
parents[na] = nb;
}
value_type find(value_type node)
{
auto root = nodes.find(node);
// new node
if (root == nodes.end())
{
// auto it = nodes.insert(node);
nodes.insert(node);
auto it = nodes.find(node);
parents.insert({it, it});
return node;
}
// existed
else
{
auto pr = parents.find(root);
while (pr != parents.end() && pr->first != pr->second)
pr = parents.find(pr->second);
return *(parents[root] = pr->second);
}
}
bool connected(value_type a, value_type b)
{
return find(a) == find(b);
}
private:
using Set = std::unordered_set<value_type, _Hash>;
using SetIt = typename Set::iterator;
struct SetItHash
{
size_t operator()(const SetIt& it) const
{
return std::hash<const int*>{} (&*it);
}
};
Set nodes;
std::unordered_map<SetIt, SetIt, SetItHash> parents;
};
| 2,324
|
C++
|
.cpp
| 80
| 21.3625
| 83
| 0.541573
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,181
|
union_find.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/multiway_tree/union_find/union_find.cpp
|
#include <iostream>
#include <vector>
/* Part of Cosmos by OpenGenus Foundation */
// Union-find stores a graph, and allows two operations in amortized constant time:
// * Add a new edge between two vertices.
// * Check if two vertices belong to same component.
class UnionFind {
std::vector<size_t> parent;
std::vector<size_t> rank;
size_t root(size_t node)
{
if (parent[node] == node)
return node;
else
return parent[node] = getParent(parent[node]);
}
size_t getParent(size_t node)
{
return parent[node];
}
public:
// Make a graph with `size` vertices and no edges.
UnionFind(size_t size)
{
parent.resize(size);
rank.resize(size);
for (size_t i = 0; i < size; i++)
{
parent[i] = i;
rank[i] = 1;
}
}
// Connect vertices `a` and `b`.
void Union(size_t a, size_t b)
{
a = root(a);
b = root(b);
if (a == b)
return;
if (rank[a] < rank[b])
parent[a] = b;
else if (rank[a] > rank[b])
parent[b] = a;
else
{
parent[a] = b;
rank[b] += 1;
}
}
// Check if vertices `a` and `b` are in the same component.
bool Connected(size_t a, size_t b)
{
return root(a) == root(b);
}
};
int main()
{
UnionFind unionFind(10);
unionFind.Union(3, 4);
unionFind.Union(3, 8);
unionFind.Union(0, 8);
unionFind.Union(1, 3);
unionFind.Union(7, 9);
unionFind.Union(5, 9);
// Now the components are:
// 0 1 3 4 8
// 5 7 9
// 2
// 6
for (size_t i = 0; i < 10; i++)
for (size_t j = i + 1; j < 10; j++)
if (unionFind.Connected(i, j))
std::cout << i << " and " << j << " are in the same component" << std::endl;
return 0;
}
| 1,901
|
C++
|
.cpp
| 75
| 18.813333
| 92
| 0.521212
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,182
|
splay_tree.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/multiway_tree/splay_tree/splay_tree.cpp
|
/*
* Part of Cosmos by OpenGenus Foundation
*
* splay tree synopsis
*
* template<typename _Type, class _Derivative>
* class Node
* {
* protected:
* using SPNodeType = std::shared_ptr<_Derivative>;
* using ValueType = _Type;
*
* public:
* Node(ValueType v, SPNodeType l = nullptr, SPNodeType r = nullptr);
*
* ValueType value();
*
* void value(ValueType v);
*
* SPNodeType left();
*
* void left(SPNodeType l);
*
* SPNodeType right();
*
* void right(SPNodeType r);
*
* protected:
* ValueType value_;
* std::shared_ptr<_Derivative> left_, right_;
* };
*
* template<typename _Type>
* class DerivativeNode :public Node<_Type, DerivativeNode<_Type>>
* {
* private:
* using BaseNode = Node<_Type, DerivativeNode<_Type>>;
* using SPNodeType = typename BaseNode::SPNodeType;
* using WPNodeType = std::weak_ptr<DerivativeNode>;
* using ValueType = typename BaseNode::ValueType;
*
* public:
* DerivativeNode(ValueType v,
* SPNodeType l = nullptr,
* SPNodeType r = nullptr,
* WPNodeType p = WPNodeType());
*
* SPNodeType parent();
*
* void parent(SPNodeType p);
*
* private:
* WPNodeType parent_;
* };
*
* template<typename _Type,
* typename _Compare = std::less<_Type>,
* class NodeType = DerivativeNode<_Type>>
* class SplayTree
* {
* private:
* using SPNodeType = std::shared_ptr<NodeType>;
*
* public:
* using ValueType = _Type;
* using Reference = ValueType &;
* using ConstReference = ValueType const &;
* using SizeType = size_t;
* using DifferenceType = std::ptrdiff_t;
*
* SplayTree() :root_(nullptr), size_(0), compare_(_Compare())
*
* SizeType insert(ConstReference value);
*
* SizeType erase(ConstReference value);
*
* SPNodeType find(ConstReference value);
*
* SPNodeType minimum() const;
*
* SPNodeType maximum() const;
*
* SizeType height() const;
*
* SizeType size() const;
*
* bool empty() const;
*
* void inorderTravel(std::ostream &output) const;
*
* void preorderTravel(std::ostream &output) const;
*
* private:
* SPNodeType root_;
* SizeType size_;
* _Compare compare_;
*
* SPNodeType splay(SPNodeType n);
*
* void leftRotate(SPNodeType n);
*
* void rightRotate(SPNodeType n);
*
* void replace(SPNodeType old, SPNodeType new_);
*
* SPNodeType get(ConstReference value);
*
* SizeType height(SPNodeType n) const;
*
* SPNodeType minimum(SPNodeType n) const;
*
* SPNodeType maximum(SPNodeType n) const;
*
* void inorderTravel(std::ostream &output, SPNodeType n) const;
*
* void preorderTravel(std::ostream &output, SPNodeType n) const;
* };
*/
#include <functional>
#include <algorithm>
#include <memory>
#include <cstddef>
template<typename _Type, class _Derivative>
class Node
{
protected:
using SPNodeType = std::shared_ptr<_Derivative>;
using ValueType = _Type;
public:
Node(ValueType v, SPNodeType l = nullptr, SPNodeType r = nullptr)
: value_(v), left_(l), right_(r)
{
};
ValueType value()
{
return value_;
}
void value(ValueType v)
{
value_ = v;
}
SPNodeType left()
{
return left_;
}
void left(SPNodeType l)
{
left_ = l;
}
SPNodeType right()
{
return right_;
}
void right(SPNodeType r)
{
right_ = r;
}
protected:
ValueType value_;
std::shared_ptr<_Derivative> left_, right_;
};
template<typename _Type>
class DerivativeNode : public Node<_Type, DerivativeNode<_Type>>
{
private:
using BaseNode = Node<_Type, DerivativeNode<_Type>>;
using SPNodeType = typename BaseNode::SPNodeType;
using WPNodeType = std::weak_ptr<DerivativeNode>;
using ValueType = typename BaseNode::ValueType;
public:
DerivativeNode(ValueType v,
SPNodeType l = nullptr,
SPNodeType r = nullptr,
WPNodeType p = WPNodeType())
: BaseNode(v, l, r), parent_(p)
{
};
SPNodeType parent()
{
return parent_.lock();
}
void parent(SPNodeType p)
{
parent_ = p;
}
private:
WPNodeType parent_;
};
template<typename _Type,
typename _Compare = std::less<_Type>,
class NodeType = DerivativeNode<_Type>>
class SplayTree
{
private:
using SPNodeType = std::shared_ptr<NodeType>;
public:
using ValueType = _Type;
using Reference = ValueType &;
using ConstReference = ValueType const &;
using SizeType = size_t;
using DifferenceType = std::ptrdiff_t;
SplayTree() : root_(nullptr), size_(0), compare_(_Compare())
{
;
}
SizeType insert(ConstReference value)
{
SPNodeType n = root_, parent = nullptr;
while (n)
{
parent = n;
if (compare_(n->value(), value))
n = n->right();
else if (compare_(value, n->value()))
n = n->left();
else
{
n->value(value);
return 0;
}
}
n = std::make_shared<NodeType>(value);
n->parent(parent);
if (parent == nullptr)
root_ = n;
else if (compare_(parent->value(), n->value()))
parent->right(n);
else
parent->left(n);
splay(n);
++size_;
return 1;
}
SizeType erase(ConstReference value)
{
SPNodeType n = get(value);
if (n)
{
splay(n);
if (n->left() == nullptr)
replace(n, n->right());
else if (n->right() == nullptr)
replace(n, n->left());
else
{
SPNodeType min = minimum(n->right());
if (min->parent() != n)
{
replace(min, min->right());
min->right(n->right());
min->right()->parent(min);
}
replace(n, min);
min->left(n->left());
min->left()->parent(min);
}
--size_;
return 1;
}
return 0;
}
SPNodeType find(ConstReference value)
{
return get(value);
}
SPNodeType minimum() const
{
return minimum(root_);
}
SPNodeType maximum() const
{
return maximum(root_);
}
SizeType height() const
{
return height(root_);
}
SizeType size() const
{
return size_;
}
bool empty() const
{
return size_ == 0;
}
void inorderTravel(std::ostream &output) const
{
inorderTravel(output, root_);
}
void preorderTravel(std::ostream &output) const
{
preorderTravel(output, root_);
}
private:
SPNodeType root_;
SizeType size_;
_Compare compare_;
SPNodeType splay(SPNodeType n)
{
while (n && n->parent())
{
if (!n->parent()->parent()) // zig step
{
if (n->parent()->left() == n)
rightRotate(n->parent());
else
leftRotate(n->parent());
}
else if (n->parent()->left() == n && n->parent()->parent()->left() == n->parent())
{
rightRotate(n->parent()->parent());
rightRotate(n->parent());
}
else if (n->parent()->right() == n && n->parent()->parent()->right() == n->parent())
{
leftRotate(n->parent()->parent());
leftRotate(n->parent());
}
else if (n->parent()->right() == n && n->parent()->parent()->left() == n->parent())
{
leftRotate(n->parent());
rightRotate(n->parent());
}
else
{
rightRotate(n->parent());
leftRotate(n->parent());
}
}
return n;
}
void leftRotate(SPNodeType n)
{
SPNodeType right = n->right();
if (right)
{
n->right(right->left());
if (right->left())
right->left()->parent(n);
right->parent(n->parent());
}
if (n->parent() == nullptr)
root_ = right;
else if (n == n->parent()->left())
n->parent()->left(right);
else
n->parent()->right(right);
if (right)
right->left(n);
n->parent(right);
}
void rightRotate(SPNodeType n)
{
SPNodeType left = n->left();
if (left)
{
n->left(left->right());
if (left->right())
left->right()->parent(n);
left->parent(n->parent());
}
if (n->parent() == nullptr)
root_ = left;
else if (n == n->parent()->left())
n->parent()->left(left);
else
n->parent()->right(left);
if (left)
left->right(n);
n->parent(left);
}
void replace(SPNodeType old, SPNodeType new_)
{
if (old->parent() == nullptr)
root_ = new_;
else if (old == old->parent()->left())
old->parent()->left(new_);
else
old->parent()->right(new_);
if (new_)
new_->parent(old->parent());
}
SPNodeType get(ConstReference value)
{
SPNodeType n = root_;
while (n)
{
if (compare_(n->value(), value))
n = n->right();
else if (compare_(value, n->value()))
n = n->left();
else
{
splay(n);
return n;
}
}
return nullptr;
}
SizeType height(SPNodeType n) const
{
if (n)
return 1 + std::max(height(n->left()), height(n->right()));
else
return 0;
}
SPNodeType minimum(SPNodeType n) const
{
if (n)
while (n->left())
n = n->left();
return n;
}
SPNodeType maximum(SPNodeType n) const
{
if (n)
while (n->right())
n = n->right();
return n;
}
void inorderTravel(std::ostream &output, SPNodeType n) const
{
if (n)
{
inorderTravel(output, n->left());
output << n->value() << " ";
inorderTravel(output, n->right());
}
}
void preorderTravel(std::ostream &output, SPNodeType n) const
{
if (n)
{
output << n->value() << " ";
preorderTravel(output, n->left());
preorderTravel(output, n->right());
}
}
};
/*
* // for test
#include <iostream>
#include <fstream>
* std::fstream input, ans;
* int main() {
* using namespace std;
*
* std::shared_ptr<SplayTree<int>> st = std::make_shared<SplayTree<int>>();
*
* input.open("/sample.txt");
* ans.open("/output.txt", ios::out | ios::trunc);
*
* int r, ty;
* while (input >> r)
* {
* input >> ty;
*
* // cout << r << " " << ty << endl;
* if (ty == 0)
* {
* st->insert(r);
* }
* else if (ty == 1)
* {
* st->erase(r);
* }
* else
* {
* st->find(r);
* }
*
* st->preorderTravel(ans);
* st->inorderTravel(ans);
* ans << endl;
* }
* ans << st->find(0);
* ans << st->height();
* ans << st->minimum();
* ans << st->maximum();
* ans << st->size();
* ans << st->empty();
*
* return 0;
* }
* // */
| 11,729
|
C++
|
.cpp
| 485
| 17.529897
| 96
| 0.512823
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,183
|
fenwick_tree.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/multiway_tree/fenwick_tree/fenwick_tree.cpp
|
/* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
#include <vector>
using namespace std;
// Fenwick Tree (also known as Binary Indexed Tree or BIT)
class BIT
{
public:
int n;
vector<int> arr;
// constructor: initializes variables
BIT(int n)
{
this->n = n;
arr.resize(n + 1, 0);
}
// returns least significant bit
int lsb(int idx)
{
return idx & -idx;
}
// updates the element at index idx by val
void update(int idx, int val) // log(n) complexity
{
while (idx <= n)
{
arr[idx] += val;
idx += lsb(idx);
}
}
// returns prefix sum from 1 to idx
int prefix(int idx) // log(n) complexity
{
int sum = 0;
while (idx > 0)
{
sum += arr[idx];
idx -= lsb(idx);
}
return sum;
}
// returns sum of elements between indices l and r
int range_query(int l, int r) // log(n) complexity
{
return prefix(r) - prefix(l - 1);
}
};
int main()
{
vector<int> array = {1, 2, 3, 4, 5};
int n = array.size();
BIT tree(n);
for (int i = 0; i < n; i++)
tree.update(i + 1, array[i]);
cout << "Range Sum from 2 to 4: " << tree.range_query(2, 4) << endl;
cout << "Range Sum from 1 to 5: " << tree.range_query(1, 5) << endl;
}
| 1,362
|
C++
|
.cpp
| 57
| 18.421053
| 72
| 0.542504
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,184
|
fenwick_tree_inversion_count.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/multiway_tree/fenwick_tree/fenwick_tree_inversion_count.cpp
|
#include <iostream>
#include <cstring>
using namespace std;
int BIT[101000], A[101000], n;
int query(int i)
{
int ans = 0;
for (; i > 0; i -= i & (-i))
ans += BIT[i];
return ans;
}
void update(int i)
{
for (; i <= n; i += i & (-i))
BIT[i]++;
}
int main()
{
int ans, i;
while (cin >> n and n)
{
memset(BIT, 0, (n + 1) * (sizeof(int)));
for (int i = 0; i < n; i++)
cin >> A[i];
ans = 0;
for (i = n - 1; i >= 0; i--)
{
ans += query(A[i] - 1);
update(A[i]);
}
cout << ans << endl;
}
return 0;
}
| 637
|
C++
|
.cpp
| 34
| 13.441176
| 48
| 0.414309
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,185
|
red_black_tree.test.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/multiway_tree/red_black_tree/red_black_tree.test.cpp
|
#include "red_black_tree.cpp"
void
test()
{
std::shared_ptr<RBTree<int>> rbt;
rbt = make_shared<RBTree<int>>();
rbt->find(3);
assert(rbt->preOrder() == "");
assert(rbt->find(32) == nullptr);
rbt->insert(1);
rbt->insert(4);
rbt->insert(7);
rbt->insert(10);
rbt->insert(2);
rbt->insert(6);
rbt->insert(8);
rbt->insert(3);
rbt->insert(5);
rbt->insert(9);
rbt->insert(100);
assert(rbt->preOrder() == "74213659810100");
rbt->insert(40);
assert(rbt->preOrder() == "7421365984010100");
rbt->insert(30);
assert(rbt->preOrder() == "742136598401030100");
rbt->insert(20);
assert(rbt->preOrder() == "74213659840201030100");
rbt->insert(15);
assert(rbt->preOrder() == "7421365209810154030100");
rbt->insert(50);
assert(rbt->preOrder() == "742136520981015403010050");
rbt->insert(60);
assert(rbt->preOrder() == "74213652098101540306050100");
rbt->insert(70);
assert(rbt->preOrder() == "7421365209810154030605010070");
rbt->insert(80);
assert(rbt->preOrder() == "742136520981015403060508070100");
rbt->insert(63);
assert(rbt->preOrder() == "74213652098101560403050807063100");
rbt->insert(67);
assert(rbt->preOrder() == "7421365209810156040305080676370100");
rbt->insert(65);
rbt->insert(69);
rbt->insert(37);
rbt->insert(33);
rbt->insert(35);
rbt->insert(31);
assert(rbt->inOrder() == "1234567891015203031333537405060636567697080100");
assert(rbt->preOrder() == "2074213659810156040333031373550806763657069100");
assert(rbt->find(31) != nullptr);
assert(rbt->find(32) == nullptr);
rbt->erase(69);
assert(rbt->preOrder() == "20742136598101560403330313735508067636570100");
rbt->erase(65);
assert(rbt->preOrder() == "207421365981015604033303137355080676370100");
rbt->erase(1);
assert(rbt->preOrder() == "20742365981015604033303137355080676370100");
rbt->erase(3);
assert(rbt->preOrder() == "2074265981015604033303137355080676370100");
rbt->erase(2);
assert(rbt->preOrder() == "207546981015604033303137355080676370100");
rbt->erase(60);
assert(rbt->preOrder() == "2075469810155033303137354080676370100");
rbt->erase(35);
assert(rbt->preOrder() == "20754698101550333031374080676370100");
rbt->erase(37);
assert(rbt->preOrder() == "207546981015503330314080676370100");
rbt->erase(40);
assert(rbt->preOrder() == "2075469810155031303380676370100");
rbt->erase(50);
assert(rbt->preOrder() == "20754698101567333130638070100");
rbt->erase(20);
assert(rbt->preOrder() == "157546981067333130638070100");
rbt->erase(15);
assert(rbt->preOrder() == "1075469867333130638070100");
rbt->erase(10);
assert(rbt->preOrder() == "97546867333130638070100");
rbt->erase(9);
assert(rbt->preOrder() == "8547667333130638070100");
rbt->erase(100);
assert(rbt->preOrder() == "8547667333130638070");
rbt->erase(70);
assert(rbt->preOrder() == "85476673331306380");
rbt->erase(80);
assert(rbt->preOrder() == "854763331306763");
}
// test of RBTree methods
struct RBTreeTest
{
typedef RBTree<int> tree_type;
using node_type = tree_type::NodeType;
using p_node_type = tree_type::SPNodeType;
using Color = tree_type::Color;
RBTreeTest()
{
testSibling();
// below test of delete cases need ignore invoke
testDeleteCase2();
testDeleteCase3();
testDeleteCase4();
testDeleteCase5();
testDeleteCase6();
}
void testSibling()
{
tree_type t;
p_node_type n = std::make_shared<node_type>(0), l = std::make_shared<node_type>(0),
r = std::make_shared<node_type>(0);
n->left(l);
n->right(r);
l->parent(n);
r->parent(n);
assert(t.sibling(l) == r);
assert(t.sibling(r) == l);
}
void testDeleteCase2()
{
tree_type t;
p_node_type n = std::make_shared<node_type>(0), p = std::make_shared<node_type>(0),
s = std::make_shared<node_type>(0), sl = std::make_shared<node_type>(0),
sr = std::make_shared<node_type>(0);
// test n is left of parent
p->color(Color::BLACK);
s->color(Color::RED);
sr->right(t.sentinel_);
sr->left(sr->right());
sl->right(sr->left());
sl->left(sl->right());
n->right(sl->left());
n->left(n->right());
p->parent(n->left());
p->left(n);
p->right(s);
s->parent(p);
n->parent(s->parent());
s->left(sl);
s->right(sr);
sr->parent(s);
sl->parent(sr->parent());
t.deleteCase2(n);
assert(p->color() == Color::RED);
assert(s->color() == Color::BLACK);
assert(s->parent() == t.sentinel_);
assert(n->left() == t.sentinel_);
assert(n->right() == t.sentinel_);
assert(sl->left() == t.sentinel_);
assert(sl->right() == t.sentinel_);
assert(sr->left() == t.sentinel_);
assert(sr->right() == t.sentinel_);
assert(s->left() == p);
assert(s->right() == sr);
assert(p->parent() == s);
assert(sr->parent() == s);
assert(p->left() == n);
assert(p->right() == sl);
assert(n->parent() == p);
assert(sl->parent() == p);
// test n is right of parent
p->color(Color::BLACK);
s->color(Color::RED);
sr->right(t.sentinel_);
sr->left(sr->right());
sl->right(sr->left());
sl->left(sl->right());
n->right(sl->left());
n->left(n->right());
p->parent(n->left());
p->left(s);
p->right(n);
s->parent(p);
n->parent(s->parent());
s->left(sl);
s->right(sr);
sr->parent(s);
sl->parent(sr->parent());
t.deleteCase2(n);
assert(p->color() == Color::RED);
assert(s->color() == Color::BLACK);
assert(s->parent() == t.sentinel_);
assert(n->left() == t.sentinel_);
assert(n->right() == t.sentinel_);
assert(sl->left() == t.sentinel_);
assert(sl->right() == t.sentinel_);
assert(sr->left() == t.sentinel_);
assert(sr->right() == t.sentinel_);
assert(s->left() == sl);
assert(s->right() == p);
assert(sl->parent() == s);
assert(p->parent() == s);
assert(p->left() == sr);
assert(p->right() == n);
assert(sr->parent() == p);
assert(n->parent() == p);
}
void testDeleteCase3()
{
tree_type t;
p_node_type n = std::make_shared<node_type>(0), p = std::make_shared<node_type>(0),
s = std::make_shared<node_type>(0), sl = std::make_shared<node_type>(0),
sr = std::make_shared<node_type>(0);
sr->color(Color::BLACK);
sl->color(sr->color());
s->color(sl->color());
p->color(s->color());
n->color(p->color());
sr->right(t.sentinel_);
sr->left(sr->right());
sl->right(sr->left());
sl->left(sl->right());
n->right(sl->left());
n->left(n->right());
p->parent(n->left());
p->left(n);
p->right(s);
s->parent(p);
n->parent(s->parent());
s->left(sl);
s->right(sr);
sr->parent(s);
sl->parent(sr->parent());
t.deleteCase3(n);
assert(s->color() == Color::RED);
assert(p->color() == Color::BLACK);
assert(n->color() == Color::BLACK);
assert(sl->color() == Color::BLACK);
assert(sr->color() == Color::BLACK);
sr->color(Color::BLACK);
sl->color(sr->color());
s->color(sl->color());
p->color(s->color());
n->color(p->color());
sr->right(t.sentinel_);
sr->left(sr->right());
sl->right(sr->left());
sl->left(sl->right());
n->right(sl->left());
n->left(n->right());
p->parent(n->left());
p->left(s);
p->right(n);
s->parent(p);
n->parent(s->parent());
s->left(sl);
s->right(sr);
sr->parent(s);
sl->parent(sr->parent());
t.deleteCase3(n);
assert(s->color() == Color::RED);
assert(p->color() == Color::BLACK);
assert(n->color() == Color::BLACK);
assert(sl->color() == Color::BLACK);
assert(sr->color() == Color::BLACK);
}
void testDeleteCase4()
{
tree_type t;
p_node_type n = std::make_shared<node_type>(0), p = std::make_shared<node_type>(0),
s = std::make_shared<node_type>(0), sl = std::make_shared<node_type>(0),
sr = std::make_shared<node_type>(0);
sr->color(Color::BLACK);
sl->color(sr->color());
s->color(sl->color());
n->color(s->color());
p->color(Color::RED);
sr->right(t.sentinel_);
sr->left(sr->right());
sl->right(sr->left());
sl->left(sl->right());
n->right(sl->left());
n->left(n->right());
p->parent(n->left());
p->left(n);
p->right(s);
s->parent(p);
n->parent(s->parent());
s->left(sl);
s->right(sr);
sr->parent(s);
sl->parent(sr->parent());
t.deleteCase4(n);
assert(s->color() == Color::RED);
assert(p->color() == Color::BLACK);
assert(n->color() == Color::BLACK);
assert(sl->color() == Color::BLACK);
assert(sr->color() == Color::BLACK);
sr->color(Color::BLACK);
sl->color(sr->color());
s->color(sl->color());
n->color(s->color());
p->color(Color::RED);
sr->right(t.sentinel_);
sr->left(sr->right());
sl->right(sr->left());
sl->left(sl->right());
n->right(sl->left());
n->left(n->right());
p->parent(n->left());
p->left(s);
p->right(n);
s->parent(p);
n->parent(s->parent());
s->left(sl);
s->right(sr);
sr->parent(s);
sl->parent(sr->parent());
t.deleteCase4(n);
assert(s->color() == Color::RED);
assert(p->color() == Color::BLACK);
assert(n->color() == Color::BLACK);
assert(sl->color() == Color::BLACK);
assert(sr->color() == Color::BLACK);
}
void testDeleteCase5()
{
tree_type t;
p_node_type n = std::make_shared<node_type>(0), p = std::make_shared<node_type>(0),
s = std::make_shared<node_type>(0), sl = std::make_shared<node_type>(0),
sr = std::make_shared<node_type>(0), s_l = std::make_shared<node_type>(0),
s_r = std::make_shared<node_type>(0);
s_r->color(Color::BLACK);
s_l->color(s_r->color());
sr->color(s_l->color());
s->color(sr->color());
p->color(s->color());
n->color(p->color());
sl->color(Color::RED);
s_r->right(t.sentinel_);
s_r->left(s_r->right());
s_l->right(s_r->left());
s_l->left(s_l->right());
sr->right(s_l->left());
sr->left(sr->right());
n->right(sr->left());
n->left(n->right());
p->parent(n->left());
p->left(n);
p->right(s);
s->parent(p);
n->parent(s->parent());
s->left(sl);
s->right(sr);
sr->parent(s);
sl->parent(sr->parent());
sl->left(s_l);
sl->right(s_r);
s_r->parent(sl);
s_l->parent(s_r->parent());
t.deleteCase5(n);
assert(s->color() == Color::RED);
assert(p->color() == Color::BLACK);
assert(n->color() == Color::BLACK);
assert(sl->color() == Color::BLACK);
assert(sr->color() == Color::BLACK);
assert(s_l->color() == Color::BLACK);
assert(s_r->color() == Color::BLACK);
assert(p->parent() == t.sentinel_);
assert(n->left() == t.sentinel_);
assert(n->right() == t.sentinel_);
assert(sr->left() == t.sentinel_);
assert(sr->right() == t.sentinel_);
assert(s_l->left() == t.sentinel_);
assert(s_l->right() == t.sentinel_);
assert(s_r->left() == t.sentinel_);
assert(s_r->right() == t.sentinel_);
assert(p->left() == n);
assert(p->right() == sl);
assert(n->parent() == p);
assert(sl->parent() == p);
assert(sl->left() == s_l);
assert(sl->right() == s);
assert(s_l->parent() == sl);
assert(s->parent() == sl);
assert(s->left() == s_r);
assert(s->right() == sr);
assert(s_r->parent() == s);
assert(sr->parent() == s);
s_r->color(Color::BLACK);
s_l->color(s_r->color());
sl->color(s_l->color());
s->color(sl->color());
p->color(s->color());
n->color(p->color());
sr->color(Color::RED);
s_r->right(t.sentinel_);
s_r->left(s_r->right());
s_l->right(s_r->left());
s_l->left(s_l->right());
sl->right(s_l->left());
sl->left(sl->right());
n->right(sl->left());
n->left(n->right());
p->parent(n->left());
p->left(s);
p->right(n);
s->parent(p);
n->parent(s->parent());
s->left(sl);
s->right(sr);
sr->parent(s);
sl->parent(sr->parent());
sr->left(s_l);
sr->right(s_r);
s_r->parent(sr);
s_l->parent(s_r->parent());
t.deleteCase5(n);
assert(s->color() == Color::RED);
assert(p->color() == Color::BLACK);
assert(n->color() == Color::BLACK);
assert(sl->color() == Color::BLACK);
assert(sr->color() == Color::BLACK);
assert(s_l->color() == Color::BLACK);
assert(s_r->color() == Color::BLACK);
assert(p->parent() == t.sentinel_);
assert(n->left() == t.sentinel_);
assert(n->right() == t.sentinel_);
assert(sl->left() == t.sentinel_);
assert(sl->right() == t.sentinel_);
assert(s_l->left() == t.sentinel_);
assert(s_l->right() == t.sentinel_);
assert(s_r->left() == t.sentinel_);
assert(s_r->right() == t.sentinel_);
assert(p->left() == sr);
assert(p->right() == n);
assert(n->parent() == p);
assert(sr->parent() == p);
assert(sr->left() == s);
assert(sr->right() == s_r);
assert(s->parent() == sr);
assert(s_r->parent() == sr);
assert(s->left() == sl);
assert(s->right() == s_l);
assert(sl->parent() == s);
assert(s_l->parent() == s);
}
void testDeleteCase6()
{
tree_type t;
p_node_type n = std::make_shared<node_type>(0), p = std::make_shared<node_type>(0),
s = std::make_shared<node_type>(0), sc = std::make_shared<node_type>(0);
s->color(Color::BLACK);
n->color(s->color());
p->color(n->color());
sc->color(Color::RED);
sc->right(t.sentinel_);
sc->left(sc->right());
s->left(sc->left());
n->right(s->left());
n->left(n->right());
p->parent(n->left());
p->left(n);
p->right(s);
n->parent(p);
s->parent(p);
s->right(sc);
sc->parent(s);
t.deleteCase6(n);
assert(p->color() == Color::BLACK);
assert(n->color() == Color::BLACK);
assert(s->color() == Color::BLACK);
assert(sc->color() == Color::BLACK);
assert(s->parent() == t.sentinel_);
assert(n->left() == t.sentinel_);
assert(n->right() == t.sentinel_);
assert(p->right() == t.sentinel_);
assert(sc->left() == t.sentinel_);
assert(sc->right() == t.sentinel_);
assert(s->left() == p);
assert(s->right() == sc);
assert(p->parent() == s);
assert(sc->parent() == s);
assert(p->left() == n);
assert(n->parent() == p);
s->color(Color::BLACK);
n->color(s->color());
p->color(n->color());
sc->color(Color::RED);
sc->right(t.sentinel_);
sc->left(sc->right());
s->right(sc->left());
n->right(s->right());
n->left(n->right());
p->parent(n->left());
p->left(s);
p->right(n);
s->parent(p);
n->parent(p);
s->left(sc);
sc->parent(s);
t.deleteCase6(n);
assert(p->color() == Color::BLACK);
assert(n->color() == Color::BLACK);
assert(s->color() == Color::BLACK);
assert(sc->color() == Color::BLACK);
assert(s->parent() == t.sentinel_);
assert(n->left() == t.sentinel_);
assert(n->right() == t.sentinel_);
assert(p->left() == t.sentinel_);
assert(sc->left() == t.sentinel_);
assert(sc->right() == t.sentinel_);
assert(s->left() == sc);
assert(s->right() == p);
assert(sc->parent() == s);
assert(p->parent() == s);
assert(p->right() == n);
assert(n->parent() == p);
}
};
// Driver Code
int
main()
{
RBTreeTest t;
test();
return 0;
}
| 17,301
|
C++
|
.cpp
| 515
| 25.363107
| 94
| 0.504712
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,186
|
red_black_tree.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/multiway_tree/red_black_tree/red_black_tree.cpp
|
#include <iostream>
#include <memory>
#include <cassert>
#include <string>
#include <stack>
using namespace std;
template<typename _Type, class _Derivative>
class BaseNode
{
protected:
using ValueType = _Type;
using SPNodeType = std::shared_ptr<_Derivative>;
public:
BaseNode(ValueType v, SPNodeType l = nullptr, SPNodeType r = nullptr)
: value_(v), left_(l), right_(r)
{
}
ValueType value()
{
return value_;
}
void value(ValueType v)
{
value_ = v;
}
SPNodeType &left()
{
return left_;
}
void left(SPNodeType l)
{
left_ = l;
}
SPNodeType &right()
{
return right_;
}
void right(SPNodeType r)
{
right_ = r;
}
protected:
ValueType value_;
SPNodeType left_, right_;
};
template<typename _Type>
class RBNode : public BaseNode<_Type, RBNode<_Type>>
{
private:
using ValueType = _Type;
using SPNodeType = std::shared_ptr<RBNode>;
using WPNodeType = std::weak_ptr<RBNode>;
public:
enum class Color
{
RED,
BLACK
};
RBNode(ValueType v, SPNodeType l = nullptr, SPNodeType r = nullptr, SPNodeType p = nullptr)
: BaseNode<_Type, RBNode<_Type>>(v, l, r), parent_(p), color_(Color::RED)
{
}
SPNodeType parent()
{
return parent_.lock();
}
void parent(SPNodeType p)
{
parent_ = p;
}
Color color()
{
return color_;
}
void color(Color c)
{
color_ = c;
}
private:
WPNodeType parent_;
Color color_;
};
struct RBTreeTest;
template<typename _Type, typename _Compare = std::less<_Type>>
class RBTree
{
private:
typedef RBNode<_Type> NodeType;
typedef std::shared_ptr<NodeType> SPNodeType;
typedef typename RBNode<_Type>::Color Color;
public:
RBTree() : root_(nullptr), sentinel_(std::make_shared<NodeType>(0)), compare_(_Compare())
{
sentinel_->left(sentinel_);
sentinel_->right(sentinel_);
sentinel_->parent(sentinel_);
sentinel_->color(Color::BLACK);
root_ = sentinel_;
}
void insert(_Type const &n);
void erase(_Type const &n);
SPNodeType const find(_Type const &);
std::string preOrder() const;
std::string inOrder() const;
private:
SPNodeType root_;
SPNodeType sentinel_;
_Compare compare_;
SPNodeType &insert(SPNodeType &root, SPNodeType &pt);
SPNodeType _find(_Type const &value);
void rotateLeft(SPNodeType const &);
void rotateRight(SPNodeType const &);
void fixViolation(SPNodeType &);
SPNodeType successor(SPNodeType const &);
SPNodeType &sibling(SPNodeType const &);
bool isLeftChild(SPNodeType const &);
bool isRightChild(SPNodeType const &);
void deleteOneNode(SPNodeType &);
void deleteCase1(SPNodeType const &);
void deleteCase2(SPNodeType const &);
void deleteCase3(SPNodeType const &);
void deleteCase4(SPNodeType const &);
void deleteCase5(SPNodeType const &);
void deleteCase6(SPNodeType const &);
// for test
friend RBTreeTest;
};
template<typename _Type, typename _Compare>
void
RBTree<_Type, _Compare>::insert(_Type const &value)
{
SPNodeType pt = std::make_shared<NodeType>(value, sentinel_, sentinel_);
root_ = insert(root_, pt);
fixViolation(pt);
}
template<typename _Type, typename _Compare>
void
RBTree<_Type, _Compare>::erase(_Type const &value)
{
SPNodeType delete_node = _find(value);
if (delete_node != sentinel_)
{
if (delete_node->left() == sentinel_)
deleteOneNode(delete_node);
else
{
SPNodeType smallest = successor(delete_node);
auto temp = delete_node->value();
delete_node->value(smallest->value());
smallest->value(temp);
deleteOneNode(smallest);
}
}
}
template<typename _Type, typename _Compare>
void
RBTree<_Type, _Compare>::deleteOneNode(SPNodeType &pt)
{
auto child = pt->left() != sentinel_ ? pt->left() : pt->right();
if (pt->parent() == sentinel_)
{
root_ = child;
root_->parent(sentinel_);
root_->color(Color::BLACK);
}
else
{
if (isLeftChild(pt))
pt->parent()->left(child);
else
pt->parent()->right(child);
child->parent(pt->parent());
if (pt->color() == Color::BLACK)
{
if (child->color() == Color::RED)
child->color(Color::BLACK);
else
deleteCase1(child);
}
}
}
template<typename _Type, typename _Compare>
auto
RBTree<_Type, _Compare>::find(_Type const &value)->SPNodeType const
{
auto pt = _find(value);
return pt != sentinel_ ? pt : nullptr;
}
template<typename _Type, typename _Compare>
std::string
RBTree<_Type, _Compare>::preOrder() const
{
if (root_ == sentinel_)
{
return {};
}
std::string elem{};
std::stack<SPNodeType> st{};
st.push(root_);
elem.append(std::to_string(st.top()->value()));
while (!st.empty())
{
while (st.top()->left() != sentinel_)
{
elem.append(std::to_string(st.top()->left()->value()));
st.push(st.top()->left());
}
while (!st.empty() && st.top()->right() == sentinel_)
st.pop();
if (!st.empty())
{
elem.append(std::to_string(st.top()->right()->value()));
auto temp = st.top();
st.pop();
st.push(temp->right());
}
}
return elem;
}
template<typename _Type, typename _Compare>
std::string
RBTree<_Type, _Compare>::inOrder() const
{
if (root_ == sentinel_)
{
return {};
}
std::string elem{};
std::stack<SPNodeType> st{};
st.push(root_);
while (!st.empty())
{
while (st.top()->left() != sentinel_)
st.push(st.top()->left());
while (!st.empty() && st.top()->right() == sentinel_)
{
elem.append(std::to_string(st.top()->value()));
st.pop();
}
if (!st.empty())
{
elem.append(std::to_string(st.top()->value()));
auto temp = st.top();
st.pop();
st.push(temp->right());
}
}
return elem;
}
template<typename _Type, typename _Compare>
auto
RBTree<_Type, _Compare>::insert(SPNodeType &root, SPNodeType &pt)->SPNodeType &
{
// If the tree is empty, return a new node
if (root == sentinel_)
{
pt->parent(root->parent());
return pt;
}
// Otherwise, recur down the tree
if (compare_(pt->value(), root->value()))
{
root->left(insert(root->left(), pt));
root->left()->parent(root);
}
else if (compare_(root->value(), pt->value()))
{
root->right(insert(root->right(), pt));
root->right()->parent(root);
}
else
{
pt->parent(root->parent());
pt->left(root->left());
pt->right(root->right());
pt->color(root->color());
}
// return the (unchanged) node pointer
return root;
}
template<typename _Type, typename _Compare>
auto
RBTree<_Type, _Compare>::_find(_Type const &value)->SPNodeType
{
auto pt = std::make_shared<NodeType>(value);
std::stack<SPNodeType> st{};
st.push(root_);
while (!st.empty())
{
if (compare_(st.top()->value(), pt->value()) == compare_(pt->value(), st.top()->value()))
return st.top();
while (st.top()->left() != sentinel_)
{
st.push(st.top()->left());
if (compare_(st.top()->value(),
pt->value()) == compare_(pt->value(), st.top()->value()))
return st.top();
}
while (!st.empty() && st.top()->right() == sentinel_)
st.pop();
if (!st.empty())
{
if (compare_(st.top()->value(),
pt->value()) == compare_(pt->value(), st.top()->value()))
return st.top();
else
{
SPNodeType &temp = st.top();
st.pop();
st.push(temp->right());
}
}
}
return sentinel_;
}
template<typename _Type, typename _Compare>
void
RBTree<_Type, _Compare>::rotateLeft(SPNodeType const &pt)
{
auto pt_right = pt->right();
pt->right() = pt_right->left();
if (pt->right() != sentinel_)
pt->right()->parent(pt);
pt_right->parent(pt->parent());
if (pt->parent() == sentinel_)
root_ = pt_right;
else if (pt == pt->parent()->left())
pt->parent()->left(pt_right);
else
pt->parent()->right(pt_right);
pt_right->left(pt);
pt->parent(pt_right);
}
template<typename _Type, typename _Compare>
void
RBTree<_Type, _Compare>::rotateRight(SPNodeType const &pt)
{
auto pt_left = pt->left();
pt->left(pt_left->right());
if (pt->left() != sentinel_)
pt->left()->parent(pt);
pt_left->parent(pt->parent());
if (pt->parent() == sentinel_)
root_ = pt_left;
else if (pt == pt->parent()->left())
pt->parent()->left(pt_left);
else
pt->parent()->right(pt_left);
pt_left->right(pt);
pt->parent(pt_left);
}
template<typename _Type, typename _Compare>
auto
RBTree<_Type, _Compare>::successor(SPNodeType const &pt)->SPNodeType
{
auto child = sentinel_;
if (pt->left() != sentinel_)
{
child = pt->left();
while (child->right() != sentinel_)
child = child->right();
}
else if (pt->right() != sentinel_)
{
child = pt->right();
while (child->left() != sentinel_)
child = child->left();
}
return child;
}
template<typename _Type, typename _Compare>
void
RBTree<_Type, _Compare>::fixViolation(SPNodeType &pt)
{
auto parent_pt = sentinel_;
auto grand_parent_pt = sentinel_;
while (pt->color() == Color::RED && pt->parent()->color() == Color::RED)
{
parent_pt = pt->parent();
grand_parent_pt = pt->parent()->parent();
/*
* Case : A
* Parent of pt is left child of Grand-parent of pt
*/
if (parent_pt == grand_parent_pt->left())
{
auto uncle_pt = grand_parent_pt->right();
/*
* Case : 1
* The uncle of pt is also red
* Only Recoloring required
*/
if (uncle_pt->color() == Color::RED)
{
grand_parent_pt->color(Color::RED);
parent_pt->color(Color::BLACK);
uncle_pt->color(Color::BLACK);
pt = grand_parent_pt;
}
else
{
/*
* Case : 2
* pt is right child of its parent
* Left-rotation required
*/
if (pt == parent_pt->right())
{
rotateLeft(parent_pt);
pt = parent_pt;
parent_pt = pt->parent();
}
/*
* Case : 3
* pt is left child of its parent
* Right-rotation required
*/
rotateRight(grand_parent_pt);
auto temp = parent_pt->color();
parent_pt->color(grand_parent_pt->color());
grand_parent_pt->color(temp);
pt = parent_pt;
}
}
/*
* Case : B
* Parent of pt is right child of Grand-parent of pt
*/
else
{
auto uncle_pt = grand_parent_pt->left();
/*
* Case : 1
* The uncle of pt is also red
* Only Recoloring required
*/
if (uncle_pt->color() == Color::RED)
{
grand_parent_pt->color(Color::RED);
parent_pt->color(Color::BLACK);
uncle_pt->color(Color::BLACK);
pt = grand_parent_pt;
}
else
{
/*
* Case : 2
* pt is left child of its parent
* Right-rotation required
*/
if (pt == parent_pt->left())
{
rotateRight(parent_pt);
pt = parent_pt;
parent_pt = pt->parent();
}
/*
* Case : 3
* pt is right child of its parent
* Left-rotation required
*/
rotateLeft(grand_parent_pt);
auto temp = parent_pt->color();
parent_pt->color(grand_parent_pt->color());
grand_parent_pt->color(temp);
pt = parent_pt;
}
}
}
root_->color(Color::BLACK);
}
template<typename _Type, typename _Compare>
auto
RBTree<_Type, _Compare>::sibling(SPNodeType const &n)->SPNodeType &
{
return n->parent()->left() != n ? n->parent()->left() : n->parent()->right();
}
template<typename _Type, typename _Compare>
bool
RBTree<_Type, _Compare>::isLeftChild(SPNodeType const &n)
{
return n == n->parent()->left();
}
template<typename _Type, typename _Compare>
bool
RBTree<_Type, _Compare>::isRightChild(SPNodeType const &n)
{
return n == n->parent()->right();
}
template<typename _Type, typename _Compare>
void
RBTree<_Type, _Compare>::deleteCase1(SPNodeType const &n)
{
if (n->parent() != sentinel_)
deleteCase2(n);
}
template<typename _Type, typename _Compare>
void
RBTree<_Type, _Compare>::deleteCase2(SPNodeType const &n)
{
auto s = sibling(n);
if (s->color() == Color::RED)
{
n->parent()->color(Color::RED);
s->color(Color::BLACK);
if (isLeftChild(n))
rotateLeft(n->parent());
else
rotateRight(n->parent());
}
deleteCase3(n);
}
template<typename _Type, typename _Compare>
void
RBTree<_Type, _Compare>::deleteCase3(SPNodeType const &n)
{
auto s = sibling(n);
if (n->parent()->color() == Color::BLACK
&& s->color() == Color::BLACK
&& s->left()->color() == Color::BLACK
&& s->right()->color() == Color::BLACK)
{
s->color(Color::RED);
deleteCase1(n->parent());
}
else
deleteCase4(n);
}
template<typename _Type, typename _Compare>
void
RBTree<_Type, _Compare>::deleteCase4(SPNodeType const &n)
{
auto s = sibling(n);
if (n->parent()->color() == Color::RED
&& s->color() == Color::BLACK
&& s->left()->color() == Color::BLACK
&& s->right()->color() == Color::BLACK)
{
s->color(Color::RED);
n->parent()->color(Color::BLACK);
}
else
deleteCase5(n);
}
template<typename _Type, typename _Compare>
void
RBTree<_Type, _Compare>::deleteCase5(SPNodeType const &n)
{
auto s = sibling(n);
if (s->color() == Color::BLACK)
{
if (isLeftChild(n)
&& s->right()->color() == Color::BLACK
&& s->left()->color() == Color::RED)
{
s->color(Color::RED);
s->left()->color(Color::BLACK);
rotateRight(s);
}
else if (isRightChild(n)
&& s->left()->color() == Color::BLACK
&& s->right()->color() == Color::RED)
{
s->color(Color::RED);
s->right()->color(Color::BLACK);
rotateLeft(s);
}
}
deleteCase6(n);
}
template<typename _Type, typename _Compare>
void
RBTree<_Type, _Compare>::deleteCase6(SPNodeType const &n)
{
auto s = sibling(n);
s->color(n->parent()->color());
n->parent()->color(Color::BLACK);
if (isLeftChild(n))
{
s->right()->color(Color::BLACK);
rotateLeft(n->parent());
}
else
{
s->left()->color(Color::BLACK);
rotateRight(n->parent());
}
}
| 16,092
|
C++
|
.cpp
| 588
| 20.003401
| 97
| 0.533545
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,187
|
van_emde_boas.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/multiway_tree/van_emde_boas_tree/van_emde_boas.cpp
|
#include <iostream>
#include <math.h>
using namespace std;
typedef struct VEB
{
int u;
int min, max;
int count;
struct VEB *summary, **cluster;
} VEB;
int high(int x, int u)
{
return (int)(x / (int) sqrt(u));
}
int low(int x, int u)
{
return x % (int) sqrt(u);
}
int VEBmin(VEB*V)
{
return V->min;
}
int VEBmax(VEB*V)
{
return V->max;
}
VEB* insert(VEB*V, int x, int u)
{
if (!V)
{
V = (VEB*) malloc(sizeof(VEB));
V->min = V->max = x;
V->u = u;
V->count = 1;
if (u > 2)
{
V->summary = NULL;
V->cluster = (VEB**) calloc(sqrt(u), sizeof(VEB*));
}
else
{
V->summary = NULL;
V->cluster = NULL;
}
}
else if (V->min == x || V->max == x)
V->count = 1;
else
{
if (x < V->min)
{
if (V->min == V->max)
{
V->min = x;
V->count = 1;
return V;
}
}
else if (x > V->max)
{
int aux = V->max;
V->max = x;
x = aux;
V->count = 1;
if (V->min == x)
return V;
}
if (V->u > 2)
{
if (V->cluster[high(x, V->u)] == NULL)
V->summary = insert(V->summary, high(x, V->u), sqrt(V->u));
V->cluster[high(x, V->u)] =
insert(V->cluster[high(x, V->u)], low(x, V->u), sqrt(V->u));
}
}
return V;
}
VEB* deleteVEB(VEB*V, int x)
{
if (V->min == V->max)
{
free(V);
return NULL;
}
else if (x == V->min || x == V->max)
{
if (!--V->count)
{
if (V->summary)
{
int cluster = VEBmin(V->summary);
int new_min = VEBmin(V->cluster[cluster]);
V->min = cluster * (int) sqrt(V->u) + new_min;
V->count = V->cluster[cluster]->count;
(V->cluster[cluster])->count = 1;
if ((V->cluster[cluster])->min == (V->cluster[cluster])->max)
(V->cluster[cluster])->count = 1;
V->cluster[cluster] = deleteVEB(V->cluster[cluster], new_min);
if (V->cluster[cluster] == NULL)
V->summary = deleteVEB(V->summary, cluster);
}
else
{
V->min = V->max;
V->count = 1;
}
}
}
else
{
V->cluster[high(x, V->u)] = deleteVEB(V->cluster[high(x, V->u)], low(x, V->u));
if (V->cluster[high(x, V->u)] == NULL)
V->summary = deleteVEB(V->summary, high(x, V->u));
}
return V;
}
int elements(VEB*V, int x)
{
if (!V)
return 0;
else if (V->min == x || V->max == x)
return V->count;
else
{
if (V->cluster)
return elements(V->cluster[high(x, V->u)], low(x, V->u));
else
return 0;
}
}
void printVEB(VEB*V, int u)
{
for (int i = 0; i < u; ++i)
printf("VEB[%d] = %d\n", i, elements(V, i));
}
int main()
{
int u = 4;
int sqrt_u = sqrt(u);
VEB* V = NULL;
if (sqrt_u * sqrt_u != u)
{
printf("Invalid 'u' : Must be a perfect square\n");
return 0;
}
V = insert(V, 0, u);
V = insert(V, 1, u);
V = insert(V, 2, u);
printVEB(V, u);
printf("\n\n");
V = deleteVEB(V, 0);
V = deleteVEB(V, 1);
printVEB(V, u);
return 0;
}
| 3,557
|
C++
|
.cpp
| 155
| 15.187097
| 87
| 0.419669
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,188
|
treap.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/binary_tree/treap/treap.cpp
|
#include <iostream>
#define ll long long
#define MOD 1000000007
using namespace std;
// Part of Cosmos by OpenGenus Foundation
// structure representing a treap node
struct node
{
ll key;
ll priority;
node* left;
node* right;
node* parent;
node(ll data)
{
key = data;
priority = (1LL * rand()) % MOD;
left = right = parent = NULL;
}
};
// function to left-rotate the subtree rooted at x
void left_rotate(node* &root, node* x)
{
node* y = x->right;
x->right = y->left;
if (y->left != NULL)
y->left->parent = x;
y->parent = x->parent;
if (x->parent == NULL)
root = y;
else if (x->key > x->parent->key)
x->parent->right = y;
else
x->parent->left = y;
y->left = x;
x->parent = y;
}
// function to right-rotate the subtree rooted at x
void right_rotate(node* &root, node* x)
{
node* y = x->left;
x->left = y->right;
if (y->right != NULL)
y->right->parent = x;
y->parent = x->parent;
if (x->parent == NULL)
root = y;
else if (x->key > x->parent->key)
x->parent->right = y;
else
x->parent->left = y;
y->right = x;
x->parent = y;
}
// function to restore min-heap property by rotations
void treap_insert_fixup(node* &root, node* z)
{
while (z->parent != NULL && z->parent->priority > z->priority)
{
// if z is a right child
if (z->key > z->parent->key)
left_rotate(root, z->parent);
// if z is a left child
else
right_rotate(root, z->parent);
}
}
// function to insert a node into the treap
// performs simple BST insert and calls treap_insert_fixup
void insert(node* &root, ll data)
{
node *x = root, *y = NULL;
while (x != NULL)
{
y = x;
if (data < x->key)
x = x->left;
else
x = x->right;
}
node* z = new node(data);
z->parent = y;
if (y == NULL)
root = z;
else if (z->key > y->key)
y->right = z;
else
y->left = z;
treap_insert_fixup(root, z);
}
void preorder(node* root)
{
if (root)
{
cout << root->key << " ";
preorder(root->left);
preorder(root->right);
}
}
// free the allocated memory
void delete_treap(node* root)
{
if (root)
{
delete_treap(root->left);
delete_treap(root->right);
delete root;
}
}
int main()
{
node* root = NULL;
int choice;
ll key;
while (true)
{
cout << "1. Insert 2. Preorder 3. Quit\n";
cin >> choice;
if (choice == 1)
{
cout << "Enter key : ";
cin >> key;
insert(root, key);
}
else if (choice == 2)
{
preorder(root);
cout << endl;
}
else
break;
}
delete_treap(root);
return 0;
}
| 2,935
|
C++
|
.cpp
| 135
| 16.044444
| 66
| 0.52369
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,189
|
is_same.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/binary_tree/binary_tree/is_same/is_same.cpp
|
/*
* Part of Cosmos by OpenGenus Foundation
*
* tree comparer synopsis
*
* template<typename _Tp, typename _Comp = std::equal_to<_Tp> >
* class TreeComparer
* {
* public:
* using NodeType = TreeNode<_Tp>;
* using PNodeType = std::shared_ptr<NodeType>;
*
* bool isSameTree(PNodeType p, PNodeType q) const;
*
* private:
* _Comp comp_;
* };
*/
#include <stack>
#include <functional>
#include <memory>
#include "../node/node.cpp"
#ifndef TREE_COMPARER
#define TREE_COMPARER
template<typename _Tp, typename _Comp = std::equal_to<_Tp>>
class TreeComparer
{
public:
using NodeType = TreeNode<_Tp>;
using PNodeType = std::shared_ptr<NodeType>;
bool isSameTree(PNodeType const &f, PNodeType const &s) const
{
std::stack<PNodeType> first, second;
first.push(f);
second.push(s);
// DFS
while (!first.empty() || !second.empty())
{
// mining left
while (first.top() != nullptr
|| second.top() != nullptr)
{
// check not same node and not same value
if (first.top() == nullptr
|| second.top() == nullptr
|| !comp_(first.top()->value(), second.top()->value()))
return false;
first.push(first.top()->left());
second.push(second.top()->left());
}
// escape if top is empty or right is empty
while (!first.empty()
&& ((first.top() == nullptr && second.top() == nullptr)
|| (first.top()->right() == nullptr && second.top()->right() == nullptr)))
{
first.pop();
second.pop();
}
if (!first.empty())
{
auto first_right = first.top()->right(),
second_right = second.top()->right();
first.pop();
second.pop();
first.push(first_right);
second.push(second_right);
}
}
return true;
}
private:
_Comp comp_;
};
#endif // TREE_COMPARER
| 2,176
|
C++
|
.cpp
| 74
| 20.756757
| 97
| 0.511239
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,190
|
path_sum.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/binary_tree/binary_tree/path_sum/path_sum.cpp
|
/*
* Part of Cosmos by OpenGenus Foundation
*/
#ifndef path_sum_cpp
#define path_sum_cpp
#include "path_sum.hpp"
#include <queue>
#include <stack>
#include <set>
#include <vector>
#include <memory>
#include <algorithm>
#include <utility>
#include <functional>
// public
template<typename _Ty, typename _Compare, class _TreeNode>
auto
PathSum<_Ty, _Compare, _TreeNode>::countPathsOfSum(PNode<_Ty> root, _Ty sum)->size_type
{
if (path_type_ == PathType::Whole)
return getPathsOfSum(root, sum).size();
else // path_type_ == PathType::Part
{
if (root == nullptr)
{
return {};
}
return getPathsOfSum(root, sum).size()
+ countPathsOfSum(root->left(), sum)
+ countPathsOfSum(root->right(), sum);
}
}
template<typename _Ty, typename _Compare, class _TreeNode>
std::vector<std::vector<_Ty>>
PathSum<_Ty, _Compare, _TreeNode>::getPathsOfSum(PNode<_Ty> root, _Ty sum)
{
std::vector<std::vector<_Ty>> res{};
getPathsOfSumUp(root, {}, {}, sum, res);
return res;
}
// public end
// private
template<typename _Ty, typename _Compare, class _TreeNode>
void
PathSum<_Ty, _Compare, _TreeNode>::getPathsOfSumUp(PNode<_Ty> root,
std::vector<_Ty> prev,
_Ty prev_sum,
_Ty const &sum,
std::vector<std::vector<_Ty>> &res)
{
if (root != nullptr)
{
auto &curr = prev;
curr.push_back(root->value());
auto &curr_sum = prev_sum;
curr_sum += root->value();
if (path_type_ == PathType::Whole)
{
if (root->left() == nullptr
&& root->right() == nullptr
&& compare_(curr_sum, sum))
res.push_back(curr);
}
else // path_type_ == PathType::Part
if (compare_(curr_sum, sum))
res.push_back(curr);
getPathsOfSumUp(root->left(), curr, curr_sum, sum, res);
getPathsOfSumUp(root->right(), curr, curr_sum, sum, res);
}
}
// private end
#endif /* path_sum_cpp */
| 2,234
|
C++
|
.cpp
| 72
| 23.041667
| 87
| 0.544015
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,192
|
maximum_height2.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/binary_tree/binary_tree/maximum_height/maximum_height2.cpp
|
#include <iostream>
using namespace std;
class node {
private:
int value;
node* left, *right;
public:
node()
{
};
~node()
{
};
node* create_node(int& val);
void create_tree(int& val);
int height_tree(node* tmp);
void cleanup_tree(node* tmp);
inline int maximum(int left_ht, int right_ht)
{
return left_ht > right_ht ? left_ht : right_ht;
}
};
static node* root = NULL;
node* node::create_node(int& val)
{
node* tmp = new node;
tmp->value = val;
tmp->left = tmp->right = NULL;
return tmp;
}
void node::create_tree(int& val)
{
node* tmp = root;
if (!root)
root = create_node(val);
else
while (1)
{
if (val > tmp->value)
{
if (!tmp->right)
{
tmp->right = create_node(val);
break;
}
else
tmp = tmp->right;
}
else
{
if (!tmp->left)
{
tmp->left = create_node(val);
break;
}
else
tmp = tmp->left;
}
}
}
int node::height_tree(node* tmp)
{
if (!tmp)
return 0;
int left_ht = height_tree(tmp->left);
int right_ht = height_tree(tmp->right);
return 1 + max(left_ht, right_ht);
}
void node::cleanup_tree(node* tmp)
{
if (tmp)
{
cleanup_tree(tmp->left);
cleanup_tree(tmp->right);
if (tmp->left)
delete tmp->left;
if (tmp->right)
delete tmp->right;
}
if (tmp == root)
delete root;
}
int main()
{
int val, num;
node tmp;
cout << "Enter number of nodes" << endl;
cin >> num;
for (int ctr = 0; ctr < num; ctr++)
{
cout << "Enter values" << endl;
cin >> val;
tmp.create_tree(val);
}
int tree_ht = tmp.height_tree(root);
cout << "Height of tree is " << tree_ht << endl;
tmp.cleanup_tree(root);
return 0;
}
| 2,113
|
C++
|
.cpp
| 99
| 14
| 55
| 0.474078
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,193
|
right_threaded.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/binary_tree/binary_tree/traversal/inorder/right_threaded/right_threaded.cpp
|
/* Part of Cosmos by OpenGenus Foundation */
/*
* Right-Threaded Binary Tree implementation in C++
*/
//Author: Arpan Konar
#include <iostream>
using namespace std;
typedef long long ll;
#define REP(i, n) for (long long i = 0; i < (n); i++)
#define FOR(i, a, b) for (long long i = (a); i <= (b); i++)
#define FORD(i, a, b) for (int i = (a); i >= (b); i--)
//Structure of a node
struct node
{
int data;
node * left;
node * right;
bool isThreaded;
};
//Function to create a new node with value d
node * newnode(int d)
{
node *temp = new node();
temp->data = d;
temp->left = NULL;
temp->right = NULL;
temp->isThreaded = false;
return temp; // the node will not be deleted
}
//Function to find the leftmost node of a subtree
node * leftmost(node * root)
{
node * temp = root;
while (temp != NULL && temp->left != NULL)
temp = temp->left;
return temp;
}
//Function to find a node with value b
node * findNode(int b, node * root)
{
if (root->data == b)
return root;
root = leftmost(root);
while (1)
{
if (root->data == b)
return root;
while (root->isThreaded)
{
root = root->right;
if (root->data == b)
return root;
}
if (root->right != NULL)
root = leftmost(root->right);
else
break;
}
return NULL;
}
//Function to set the new node at left of node x
node * setLeftNode(node * x, int a)
{
if (x->left != NULL)
{
cout << a << " is ignored" << endl;
return x;
}
node * temp = newnode(a);
temp->right = x;
x->left = temp;
temp->isThreaded = true;
return x;
}
//Function to set the new node at right of node x
node * setRightNode(node * x, int a)
{
if (x->right != NULL && !x->isThreaded)
{
cout << a << " is ignored" << endl;
return x;
}
node * temp = newnode(a);
if (x->isThreaded)
{
node *q = x->right;
x->isThreaded = false;
x->right = temp;
temp->right = q;
temp->isThreaded = true;
}
else
x->right = temp;
return x;
}
//Function to take input and create threaded tree
/*Input is of the form number L/R number
* where a is entered at the left or right position of b
* if b is found
* Input ends when a is -1
*/
node * createTree()
{
node * root = NULL;
while (1)
{
int a, b;
char c;
cin >> a;
if (a == -1)
break;
cin >> c >> b;
if (root == NULL)
root = newnode(a);
else
{
node * x = findNode(b, root);
if (x == NULL)
cout << "Node not found" << endl;
else
{
if (c == 'L')
x = setLeftNode(x, a);
else if (c == 'R')
x = setRightNode(x, a);
}
}
}
return root;
}
//Function for inorder traversal of threaded binary tree
void inOrder(node * root)
{
root = leftmost(root);
while (1)
{
cout << root->data << " ";
while (root->isThreaded)
{
root = root->right;
cout << root->data << " ";
}
if (root->right != NULL)
root = leftmost(root->right);
else
break;
}
}
//Driver function to implement the above functions
int main()
{
node * root = createTree();
cout << "Inorder:";
inOrder(root);
cout << endl;
return 0;
}
| 3,576
|
C++
|
.cpp
| 157
| 16.88535
| 59
| 0.518876
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,195
|
zigzag.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/binary_tree/binary_tree/traversal/zigzag/zigzag.cpp
|
#include <iostream>
#include <stack>
class Node
{
public:
int info;
Node* left_child;
Node* right_child;
Node (int info) : info{info}, left_child{nullptr}, right_child{nullptr}
{
}
};
class BinaryTree
{
public:
Node* root;
BinaryTree() : root{nullptr}
{
}
void zigzag_traversal();
};
void BinaryTree :: zigzag_traversal()
{
std::stack<Node*> st1, st2;
st2.push (root);
while (!st1.empty() || !st2.empty())
{
while (!st1.empty())
{
Node* curr = st1.top();
st1.pop();
if (curr->right_child)
st2.push (curr->right_child);
if (curr->left_child)
st2.push (curr->left_child);
std::cout << curr->info << " ";
}
while (!st2.empty())
{
Node* curr = st2.top();
st2.pop();
if (curr->left_child)
st1.push (curr->left_child);
if (curr->right_child)
st1.push (curr->right_child);
std::cout << curr->info << " ";
}
}
}
int main()
{
BinaryTree binary_tree;
binary_tree.root = new Node (1);
binary_tree.root->left_child = new Node (2);
binary_tree.root->right_child = new Node (3);
binary_tree.root->left_child->left_child = new Node (4);
binary_tree.root->left_child->right_child = new Node (5);
binary_tree.root->right_child->left_child = new Node (6);
binary_tree.root->right_child->right_child = new Node (7);
binary_tree.zigzag_traversal();
return 0;
}
| 1,581
|
C++
|
.cpp
| 62
| 19.016129
| 75
| 0.543894
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,196
|
convert_to_doubly_linked_list.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/binary_tree/binary_tree/convert_to_doubly_linked_list/convert_to_doubly_linked_list.cpp
|
/* Structure for tree and linked list
*
* struct Node
* {
* int data;
* Node *left, *right;
* };
*
*/
// root --> Root of Binary Tree
// head_ref --> Pointer to head node of created doubly linked list
template<typename Node>
void BToDLL(Node *root, Node **head_ref)
{
if (!root)
return;
BToDLL(root->right, head_ref);
root->right = *head_ref;
if (*head_ref)
(*head_ref)->left = root;
*head_ref = root;
BToDLL(root->left, head_ref);
}
| 489
|
C++
|
.cpp
| 23
| 17.956522
| 66
| 0.613883
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,197
|
minimum_height.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/binary_tree/binary_tree/minimum_height/minimum_height.cpp
|
#include <iostream>
using namespace std;
typedef struct tree_node
{
int value;
struct tree_node *left, *right;
}node;
// create a new node
node *getNewNode(int value)
{
node *new_node = new node;
new_node->value = value;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
// create the tree
node *createTree()
{
node *root = getNewNode(31);
root->left = getNewNode(16);
root->right = getNewNode(45);
root->left->left = getNewNode(7);
root->left->right = getNewNode(24);
root->left->right->left = getNewNode(19);
root->left->right->right = getNewNode(29);
return root;
}
int minDepth(node* A)
{
if (A == NULL)
return 0;
int l = minDepth(A->left);
int r = minDepth(A->right);
if (l && r)
return min(l, r) + 1;
if (l)
return l + 1;
return r + 1;
}
// main
int main()
{
node *root = createTree();
cout << minDepth(root);
cout << endl;
return 0;
}
| 992
|
C++
|
.cpp
| 48
| 16.875
| 46
| 0.608137
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,198
|
subtreesum_recursive.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/binary_tree/binary_tree/Subtree_sum/subtreesum_recursive.cpp
|
#include<iostream>
using namespace std;
//Binary tree structure
struct node
{
int data;
struct node* left;
struct node* right;
};
//for inserting a new node
node *newNode(int data){
node *temp=new node;
temp->data=data;
temp->right=NULL;
temp->left=NULL;
return (temp);
}
//helper function
//Function to return sum of subtrees and count subtrees with sum=x
int countSubtreesWithSumX(node* root, int x ,int& count)
{ if(root==NULL)
return 0;
int ls= countSubtreesWithSumX(root->left,x,count);
int rs= countSubtreesWithSumX(root->right,x,count);
int sum=ls+rs+root->data;
if(sum==x)
count++;
return sum;
}
//main function
//Function to return the count of subtrees whose sum=x
int countSubtreescheckroot(node* root, int x)
{
if(root==NULL)
return 0;
int count=0;
//return sum of left and right subtrees respectively
int ls= countSubtreesWithSumX(root->left,x,count);
int rs= countSubtreesWithSumX(root->right,x,count);
//checks if the root value added to sums of left and right subtrees equals x
if(x==ls+rs+root->data)
count++;
//returns the count of subtrees with their sum=x
return count;
}
int main() {
// input of sum to check for
int x;
cout<<"Enter the sum to check for"<<endl;
cin>>x;
//sample input of the binary tree
struct node* root=newNode(7);
root->left=newNode(3);
root->right=newNode(2);
root->left->right=newNode(6);
root->left->left=newNode(2);
root->right->right=newNode(11);
cout<<"Number of subtrees with specific sum :"<<" "<<countSubtreescheckroot(root, x)<<endl;
return 0;
}
| 1,575
|
C++
|
.cpp
| 60
| 23.95
| 92
| 0.72505
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,199
|
diameter2.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/binary_tree/binary_tree/diameter/diameter2.cpp
|
/*
* Data Structures : Finding Diameter of a binary tree
*
* Description : Diameter of tree is defined as the longest path or route between any two nodes in a tree.
* This path may or may not be through the root. The below algorithm computes the height of
* the tree and uses it recursivley in the calculation of diameter of the specified tree.
*
* A massive collaborative effort by OpenGenus Foundation
*/
#include <iostream>
using namespace std;
// get the max of two no.s
int max(int a, int b)
{
return (a > b) ? a : b;
}
typedef struct node
{
int value;
struct node *left, *right;
} node;
// create a new node
node *getNewNode(int value)
{
node *new_node = new node;
new_node->value = value;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
// compute height of the tree
int getHeight(node *root)
{
if (root == NULL)
return 0;
// find the height of each subtree
int lh = getHeight(root->left);
int rh = getHeight(root->right);
return 1 + max(lh, rh);
}
// compute tree diameter recursively
int getDiameter(node *root)
{
if (root == NULL)
return 0;
// get height of each subtree
int lh = getHeight(root->left);
int rh = getHeight(root->right);
// compute diameters of each subtree
int ld = getDiameter(root->left);
int rd = getDiameter(root->right);
return max(lh + rh + 1, max(ld, rd));
}
// create the tree
node *createTree()
{
node *root = getNewNode(31);
root->left = getNewNode(16);
root->right = getNewNode(52);
root->left->left = getNewNode(7);
root->left->right = getNewNode(24);
root->left->right->left = getNewNode(19);
root->left->right->right = getNewNode(29);
return root;
}
// main
int main()
{
node *root = createTree();
cout << "\nDiameter of the tree is " << getDiameter(root);
cout << endl;
return 0;
}
| 1,932
|
C++
|
.cpp
| 73
| 23.150685
| 106
| 0.659263
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,200
|
diameter.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/binary_tree/binary_tree/diameter/diameter.cpp
|
/*
* Part of Cosmos by OpenGenus Foundation
*
* diameter of tree synopsis
*
* template<typename _TreeNode>
* size_t
* diameter(_TreeNode node);
*
* template<typename _TreeNode>
* void
* diameterIterative(_TreeNode const &node, size_t &maximum);
*
* template<typename _TreeNode>
* size_t
* getDiameter(_TreeNode const &node);
*
* template<typename _TreeNode>
* size_t
* getDeep(_TreeNode const &node);
*
* template<typename _TreeNode>
* size_t
* diameterRecursive(_TreeNode node, size_t &maximum);
*/
#include <algorithm>
#include <memory>
#include <stack>
#include "../node/node.cpp"
template<typename _TreeNode>
size_t
diameter(_TreeNode node)
{
size_t res{};
diameterIterative(node, res);
return res;
}
template<typename _TreeNode>
void
diameterIterative(_TreeNode const &node, size_t &maximum)
{
maximum = 0;
if (node != nullptr)
{
std::stack<_TreeNode> diameters;
diameters.push(node);
// DFS
while (!diameters.empty())
{
while (diameters.top()->left() != nullptr)
diameters.push(diameters.top()->left());
while (!diameters.empty()
&& (diameters.top() == nullptr
|| diameters.top()->right() == nullptr))
{
if (diameters.top() == nullptr) // if back from right hand
diameters.pop();
auto top = diameters.top();
maximum = std::max(maximum, static_cast<size_t>(getDiameter(top)));
top->value(static_cast<int>(getDeep(top)));
diameters.pop();
}
if (!diameters.empty())
{
auto right = diameters.top()->right();
diameters.push(nullptr); // prevent visit two times when return to parent
diameters.push(right);
}
}
}
}
template<typename _TreeNode>
size_t
getDiameter(_TreeNode const &node)
{
size_t res = 1;
res += node->left() ? node->left()->value() : 0;
res += node->right() ? node->right()->value() : 0;
return res;
}
template<typename _TreeNode>
size_t
getDeep(_TreeNode const &node)
{
size_t res = 1;
res += std::max(node->left() ? node->left()->value() : 0,
node->right() ? node->right()->value() : 0);
return res;
}
template<typename _TreeNode>
size_t
diameterRecursive(_TreeNode node, size_t &maximum)
{
if (node != nullptr)
{
size_t leftMax{}, rightMax{};
// DFS
size_t leftHeight = diameterRecursive(node->left(), leftMax);
size_t rightHeight = diameterRecursive(node->right(), rightMax);
maximum = leftHeight + rightHeight + 1;
maximum = std::max(maximum, leftMax);
maximum = std::max(maximum, rightMax);
return std::max(leftHeight, rightHeight) + 1;
}
return 0;
}
| 2,910
|
C++
|
.cpp
| 106
| 21.433962
| 92
| 0.590323
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,202
|
node.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/binary_tree/binary_tree/node/node.cpp
|
/*
* Part of Cosmos by OpenGenus Foundation
*
* tree node synopsis
*
* // for normal binary tree
* template<typename _Type>
* class TreeNode
* {
* protected:
* using SPNodeType = std::shared_ptr<TreeNode>;
* using ValueType = _Type;
*
* public:
* TreeNode(ValueType v, SPNodeType l = nullptr, SPNodeType r = nullptr)
* :value_(v), left_(l), right_(r) {}
*
* ValueType value() {
* return value_;
* }
*
* void value(ValueType v) {
* value_ = v;
* }
*
* SPNodeType left() {
* return left_;
* }
*
* void left(SPNodeType l) {
* left_ = l;
* }
*
* SPNodeType right() {
* return right_;
* }
*
* void right(SPNodeType r) {
* right_ = r;
* }
*
* private:
* ValueType value_;
* SPNodeType left_;
* SPNodeType right_;
* };
*
* // for derivative binary tree (e.g., avl tree, splay tree)
* template<typename _Type, class _Derivative>
* class __BaseTreeNode
* {
* protected:
* using SPNodeType = std::shared_ptr<_Derivative>;
* using ValueType = _Type;
*
* public:
* __BaseTreeNode(ValueType v, SPNodeType l = nullptr, SPNodeType r = nullptr)
* :value_(v), left_(l), right_(r) {}
*
* ValueType value() {
* return value_;
* }
*
* void value(ValueType v) {
* value_ = v;
* }
*
* SPNodeType left() {
* return left_;
* }
*
* void left(SPNodeType l) {
* left_ = l;
* }
*
* SPNodeType right() {
* return right_;
* }
*
* void right(SPNodeType r) {
* right_ = r;
* }
*
* private:
* ValueType value_;
* SPNodeType left_;
* SPNodeType right_;
* };
*
* template<typename _Type>
* class DerivativeTreeNode :public __BaseTreeNode<_Type, DerivativeTreeNode<_Type>>
* {
* private:
* using BaseNode = __BaseTreeNode<_Type, DerivativeTreeNode<_Type>>;
* using SPNodeType = typename BaseNode::SPNodeType;
* using ValueType = typename BaseNode::ValueType;
*
* public:
* DerivativeTreeNode(_Type v, SPNodeType l = nullptr, SPNodeType r = nullptr)
* :__BaseTreeNode<_Type, DerivativeTreeNode<_Type>>(v, l, r) {}
* };
*/
#include <memory>
#ifndef TREE_NODE_POLICY
#define TREE_NODE_POLICY
template<typename _Type>
class TreeNode
{
protected:
using SPNodeType = std::shared_ptr<TreeNode>;
using ValueType = _Type;
public:
TreeNode(ValueType v, SPNodeType l = nullptr, SPNodeType r = nullptr)
: value_(v), left_(l), right_(r)
{
}
ValueType value()
{
return value_;
}
void value(ValueType v)
{
value_ = v;
}
SPNodeType left()
{
return left_;
}
void left(SPNodeType l)
{
left_ = l;
}
SPNodeType right()
{
return right_;
}
void right(SPNodeType r)
{
right_ = r;
}
private:
ValueType value_;
SPNodeType left_;
SPNodeType right_;
};
template<typename _Type, class _Derivative>
class __BaseTreeNode
{
protected:
using SPNodeType = std::shared_ptr<_Derivative>;
using ValueType = _Type;
public:
__BaseTreeNode(ValueType v, SPNodeType l = nullptr, SPNodeType r = nullptr)
: value_(v), left_(l), right_(r)
{
}
ValueType value()
{
return value_;
}
void value(ValueType v)
{
value_ = v;
}
SPNodeType left()
{
return left_;
}
void left(SPNodeType l)
{
left_ = l;
}
SPNodeType right()
{
return right_;
}
void right(SPNodeType r)
{
right_ = r;
}
private:
ValueType value_;
SPNodeType left_;
SPNodeType right_;
};
template<typename _Type>
class DerivativeTreeNode : public __BaseTreeNode<_Type, DerivativeTreeNode<_Type>>
{
private:
using BaseNode = __BaseTreeNode<_Type, DerivativeTreeNode<_Type>>;
using SPNodeType = typename BaseNode::SPNodeType;
using ValueType = typename BaseNode::ValueType;
public:
DerivativeTreeNode(_Type v, SPNodeType l = nullptr, SPNodeType r = nullptr)
: __BaseTreeNode<_Type, DerivativeTreeNode<_Type>>(v, l, r)
{
}
};
#endif // TREE_NODE_POLICY
| 4,114
|
C++
|
.cpp
| 199
| 17.281407
| 84
| 0.611768
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,203
|
serializer.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/binary_tree/binary_tree/serializer/serializer.cpp
|
/*
* Part of Cosmos by OpenGenus Foundation
*
* tree serializer synopsis
*
* class TreeSerializer
* {
* public:
* using NodeType = TreeNode<int>;
* using PNodeType = std::shared_ptr<NodeType>;
*
* // Encodes a tree to a single string.
* std::string serialize(PNodeType root);
*
* // Decodes your encoded data to tree.
* PNodeType deserialize(std::string data);
*
* private:
* std::vector<std::string> splitToVector(std::string s);
* };
*/
#ifndef TREE_SERIALIZER
#define TREE_SERIALIZER
#include <vector>
#include <stack>
#include <queue>
#include <iterator>
#include <memory>
#include <string>
#include <sstream>
#include "../node/node.cpp"
class TreeSerializer
{
public:
using NodeType = TreeNode<int>;
using PNodeType = std::shared_ptr<NodeType>;
// Encodes a tree to a single string.
std::string serialize(PNodeType root)
{
if (root)
{
std::string ret {};
std::stack<PNodeType> st {};
PNodeType old {};
st.push(root);
ret.append(std::to_string(root->value()) + " ");
while (!st.empty())
{
while (st.top() && st.top()->left())
{
st.push(st.top()->left());
ret.append(std::to_string(st.top()->value()) + " ");
}
if (!st.top()->left())
ret.append("# ");
while (!st.empty())
{
old = st.top();
st.pop();
if (old->right())
{
st.push(old->right());
if (st.top())
ret.append(std::to_string(st.top()->value()) + " ");
break;
}
else
ret.append("# ");
}
}
return ret;
}
else
return "# ";
}
// Decodes your encoded data to tree.
PNodeType deserialize(std::string data)
{
if (data.at(0) == '#')
return nullptr;
auto nodes = splitToVector(data);
std::stack<PNodeType> st{};
PNodeType ret = std::make_shared<NodeType>(stoi(nodes.at(0))), old{};
st.push(ret);
size_t i{}, sz {nodes.size()};
i++;
bool check_l{true};
while (!st.empty())
{
while (i < sz && nodes.at(i) != "#" && check_l)
{
st.top()->left(std::make_shared<NodeType>(stoi(nodes.at(i++))));
st.push(st.top()->left());
}
st.top()->left(nullptr);
i++;
check_l = false;
while (!st.empty())
{
old = st.top();
st.pop();
check_l = true;
if (nodes.at(i) != "#")
{
old->right(std::make_shared<NodeType>(stoi(nodes.at(i++))));
st.push(old->right());
break;
}
else
{
old->right(nullptr);
i++;
}
}
}
return ret;
}
private:
std::vector<std::string> splitToVector(std::string s)
{
std::stringstream ss(s);
std::istream_iterator<std::string> begin(ss);
std::istream_iterator<std::string> end;
std::vector<std::string> vstrings(begin, end);
return vstrings;
}
};
#endif // TREE_SERIALIZER
| 3,608
|
C++
|
.cpp
| 128
| 17.992188
| 80
| 0.452841
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,205
|
make_tree_from_inorder_and_preorder.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/binary_tree/binary_tree/make_binary_tree/from_inorder_and_preorder/make_tree_from_inorder_and_preorder.cpp
|
#include <iostream>
#include <cmath>
#include <queue>
#include <cmath>
using namespace std;
template<typename T>
class Binarytreenode {
public:
T data;
Binarytreenode<T> * left;
Binarytreenode<T> * right;
Binarytreenode(T data)
{
this->data = data;
left = NULL;
right = NULL;
}
};
void postorder(Binarytreenode<int>* root)
{
if (root == NULL)
return;
postorder(root->left);
postorder(root->right);
cout << root->data << " ";
return;
}
Binarytreenode<int> * create(int *preorder, int*inorder, int ps, int pe, int is, int ie)
{
if (ps > pe || is > ie)
return NULL;
int rootdata = preorder[ps];
Binarytreenode<int> * root = new Binarytreenode<int>(rootdata);
int k;
for (int i = is; i <= ie; i++)
if (inorder[i] == rootdata)
{
k = i;
break;
}
root->left = create(preorder, inorder, ps + 1, ps + k - is, is, k - 1);
root->right = create(preorder, inorder, ps + k - is + 1, pe, k + 1, ie);
return root;
}
int main()
{
int preorder[100], inorder[100];
int size;
cin >> size;
for (int i = 0; i < size; i++)
cin >> preorder[i];
for (int i = 0; i < size; i++)
cin >> inorder[i];
Binarytreenode<int> * root = create(preorder, inorder, 0, size - 1, 0, size - 1);
postorder(root);
}
| 1,397
|
C++
|
.cpp
| 56
| 19.910714
| 88
| 0.572184
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,206
|
is_binary_tree.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/binary_tree/binary_tree/is_binary_tree/is_binary_tree.cpp
|
/* A binary tree node has data, pointer to left child
* and a pointer to right child
*
* struct Node {
* int data;
* Node* left, * right;
* };
*
*/
/* Should return true if tree represented by root is BST.
* For example, return value should be 1 for following tree.
* 20
* / \
* 10 30
* and return value should be 0 for following tree.
* 10
* / \
* 20 30 */
template<typename Node>
Node *findmax(Node *root)
{
if (!root)
return nullptr;
while (root->right)
root = root->right;
return root;
}
template<typename Node>
Node *findmin(Node *root)
{
if (!root)
return nullptr;
while (root->left)
root = root->left;
return root;
}
template<typename Node>
bool isBST(Node* root)
{
if (!root)
return 1;
if (root->left && findmax(root->left)->data > (root->data))
return 0;
if (root->right && findmin(root->right)->data < (root->data))
return 0;
if (!isBST(root->left) || !isBST(root->right))
return 0;
return 1;
}
// Another variation
// Utility function
//another function for the same but need to provide the min and max in the the tree beforehand
template<typename Node>
int isBSTUtil(Node *root, int min, int max)
{
if (!root)
return 1;
if (root->data < min || root->data > max)
return 0;
return isBSTUtil(root->left, min, root->data - 1) &&
isBSTUtil(root->right, root->data + 1, max);
}
| 1,508
|
C++
|
.cpp
| 62
| 20.370968
| 94
| 0.611501
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,207
|
balance_bst_dsw.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/binary_tree/binary_tree/balance_binary_tree/balance_bst_dsw.cpp
|
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
struct node
{
int key;
struct node *left, *right;
};
struct node *newNode(int value)
{
struct node *temp = new node;
temp->key = value;
temp->left = temp->right = NULL;
return temp;
}
struct node* insert(struct node* node, int key)
{
if (node == NULL)
return newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
return node;
}
//Inorder traversal
void inorder(struct node *root)
{
if (root)
{
inorder(root->left);
cout << root->key << " ";
inorder(root->right);
}
}
//Preorder traversal
void preorder(struct node *root)
{
if (root)
{
cout << root->key << " ";
preorder(root->left);
preorder(root->right);
}
}
struct node* leftRotate(struct node * root)
{
struct node *right, *right_left;
if ( (root == NULL) || (root->right ==NULL) )
return root;
right = root->right;
right_left = right->left;
right->left = root;
root->right = right_left;
return right;
}
struct node* rightRotate(struct node * root){
struct node *left, *left_right;
if ( (root == NULL) || (root->left == NULL) )
return root;
left = root->left;
left_right = left->right;
left->right = root;
root->left = left_right;
return left;
}
/*
Make a vine structure rooted at a dummy root and
branching only towards right
*/
struct node* createBackbone(struct node* root)
{
struct node *parent, *r;
r = newNode(-1);
parent = r;
r->right = root;
// making tree skewed towards right;
while (parent->right)
{
if (parent->right->left == NULL)
parent = parent->right;
else
parent->right = rightRotate(parent->right);
}
return r;
};
/*
Compress the tree using series of left rotations on
alternate nodes provided by the count.
*/
struct node* compress(struct node* root, int cnt)
{
struct node *temp;
temp = root;
while (cnt && temp)
{
temp->right = leftRotate(temp->right);
temp = temp->right;
cnt -= 1;
}
return root;
}
// To calculate height of the tree
int height(struct node* root)
{
int left, right;
if (root == NULL)
return -1;
left = height(root->left);
right = height(root->right);
left = left >= right ? left : right;
return 1 + left;
}
struct node* balanceTree(struct node* root)
{
root = createBackbone(root);
/*
Now a dummy root is added so we get original
root from root->right;
*/
cout << "Backbone Tree structure" << endl;
cout << "Inorder traversal: ";
inorder(root->right);
cout << "\nPreorder traversal: ";
preorder(root->right);
cout << endl;
// h = total number of nodes
int h = height(root);
int left_count, temp, l = 0;
temp = h + 1;
// l = log(n+1) (base 2)
while (temp > 1)
{
temp /= 2;
l += 1;
}
/*
make n-m rotations starting from the top of backbone
where m = 2^( floor(lg(n+1)))-1
*/
left_count = h + 1 - (1 << l);
if (left_count == 0)
{
left_count = (1 << (l - 1));
}
root = compress(root, left_count);
h -= left_count ;
while (h > 1)
{
h /= 2;
root = compress(root, h);
}
return root;
};
int main()
{
/* Let us create following BST
* 50
* \
* 70
* /
* 60 */
struct node *root = NULL;
root = insert(root, 50);
insert(root, 70);
insert(root, 60);
// insert(root, 80);
root = balanceTree(root);
root = root->right;
/* Back-bone structure of above BST
* 50
* \
* 60
* \
* 70 */
/* Balanced BST
* 60
* / \
* 50 70 */
cout << endl;
cout << "Balanced Tree Structure " << endl;
cout << "Inorder traversal: ";
inorder(root);
cout << "\nPreorder traversal: ";
preorder(root);
return 0;
}
| 4,218
|
C++
|
.cpp
| 188
| 17.776596
| 63
| 0.560994
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,211
|
avl_tree.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/binary_tree/avl_tree/avl_tree.cpp
|
/*
* Part of Cosmos by OpenGenus Foundation
* avl tree synopsis
*
* template<typename _Tp, typename _Comp = std::less<_Tp> >
* class avl_tree {
* private:
* struct AVLNode {
* _Tp data;
* std::shared_ptr<AVLNode> left;
* std::shared_ptr<AVLNode> right;
* int height;
* };
*
* typedef _Tp value_type;
* typedef AVLNode node_type;
* typedef std::shared_ptr<AVLNode> p_node_type;
*
* public:
* avl_tree() :root_(nullptr);
*
* // function to insert a node into the AVL tree
* void insert(int data);
*
* // function to delete a node from the AVL tree
* void erase(int data);
*
* // helper function to return height of a node
* int getHeight(p_node_type node);
*
* // function to find the minimum element in the tree (lefftmost node)
* p_node_type findMin(p_node_type root_);
*
* // function to find the maximum element in the tree (rightmost node)
* p_node_type findMax(p_node_type root_);
*
* // preorder traversal of the AVL tree
* void preOrder(std::ostream &out) const;
*
* // inorder traversal of the AVL tree
* void inOrder(std::ostream &out) const;
*
* // postorder traversal of the AVL tree
* void postOrder(std::ostream &out) const;
*
* private:
* p_node_type root_;
* _Comp comp_;
*
* // LL rotation root_ed at X
* p_node_type rotateLL(p_node_type &X);
*
* // RR rotation root_ed at X
* p_node_type rotateRR(p_node_type &X);
*
* // LR rotation root_ed at X
* p_node_type rotateLR(p_node_type &X);
*
* // RL rotation root_ed at X
* p_node_type rotateRL(p_node_type &X);
*
* // function to insert a node into the AVL tree
* p_node_type insert(p_node_type root_, int data);
*
* // function to delete a node from the AVL tree
* p_node_type erase(p_node_type root_, int data);
*
* // preorder traversal of the AVL tree
* void preOrder(p_node_type root_, std::ostream &out) const;
*
* // inorder traversal of the AVL tree
* void inOrder(p_node_type root_, std::ostream &out) const;
*
* // postorder traversal of the AVL tree
* void postOrder(p_node_type root_, std::ostream &out) const;
* };
*/
#include <algorithm>
#include <memory>
#include <ostream>
template<typename _Tp, typename _Comp = std::less<_Tp>>
class avl_tree {
private:
struct AVLNode
{
_Tp data;
std::shared_ptr<AVLNode> left;
std::shared_ptr<AVLNode> right;
int height;
};
typedef _Tp value_type;
typedef AVLNode node_type;
typedef std::shared_ptr<AVLNode> p_node_type;
public:
avl_tree() : root_(nullptr)
{
;
}
// function to insert a node into the AVL tree
void insert(int data)
{
root_ = insert(root_, data);
}
// function to delete a node from the AVL tree
void erase(int data)
{
root_ = erase(root_, data);
}
// helper function to return height of a node
int getHeight(p_node_type node)
{
if (node)
return node->height;
return -1;
}
// function to find the minimum element in the tree (lefftmost node)
p_node_type findMin(p_node_type root_)
{
if (root_ != nullptr)
while (root_->left != nullptr)
root_ = root_->left;
return root_;
}
// function to find the maximum element in the tree (rightmost node)
p_node_type findMax(p_node_type root_)
{
if (root_ != nullptr)
while (root_->right != nullptr)
root_ = root_->right;
return root_;
}
// preorder traversal of the AVL tree
void preOrder(std::ostream &out) const
{
preOrder(root_, out);
}
// inorder traversal of the AVL tree
void inOrder(std::ostream &out) const
{
inOrder(root_, out);
}
// postorder traversal of the AVL tree
void postOrder(std::ostream &out) const
{
postOrder(root_, out);
}
private:
p_node_type root_;
_Comp comp_;
// LL rotation root_ed at X
p_node_type rotateLL(p_node_type &X)
{
p_node_type W = X->left;
X->left = W->right;
W->right = X;
X->height = std::max(getHeight(X->left), getHeight(X->right)) + 1;
W->height = std::max(getHeight(W->left), getHeight(X)) + 1;
return W; // new root_
}
// RR rotation root_ed at X
p_node_type rotateRR(p_node_type &X)
{
p_node_type W = X->right;
X->right = W->left;
W->left = X;
X->height = std::max(getHeight(X->left), getHeight(X->right)) + 1;
W->height = std::max(getHeight(X), getHeight(W->right));
return W; // new root_
}
// LR rotation root_ed at X
p_node_type rotateLR(p_node_type &X)
{
X->left = rotateRR(X->left);
return rotateLL(X);
}
// RL rotation root_ed at X
p_node_type rotateRL(p_node_type &X)
{
X->right = rotateLL(X->right);
return rotateRR(X);
}
// function to insert a node into the AVL tree
p_node_type insert(p_node_type root_, int data)
{
if (root_ == nullptr)
{
p_node_type newNode = std::make_shared<node_type>();
newNode->data = data;
newNode->height = 0;
newNode->left = newNode->right = nullptr;
root_ = newNode;
}
else if (comp_(data, root_->data))
{
root_->left = insert(root_->left, data);
if (getHeight(root_->left) - getHeight(root_->right) == 2)
{
if (comp_(data, root_->left->data))
root_ = rotateLL(root_);
else
root_ = rotateLR(root_);
}
}
else if (comp_(root_->data, data))
{
root_->right = insert(root_->right, data);
if (getHeight(root_->right) - getHeight(root_->left) == 2)
{
if (comp_(root_->right->data, data))
root_ = rotateRR(root_);
else
root_ = rotateRL(root_);
}
}
root_->height = std::max(getHeight(root_->left), getHeight(root_->right)) + 1;
return root_;
}
// function to delete a node from the AVL tree
p_node_type erase(p_node_type root_, int data)
{
if (root_ == nullptr)
return nullptr;
else if (comp_(data, root_->data))
{
root_->left = erase(root_->left, data);
if (getHeight(root_->right) - getHeight(root_->left) == 2)
{
if (getHeight(root_->right->right) > getHeight(root_->right->left))
root_ = rotateRR(root_);
else
root_ = rotateRL(root_);
}
}
else if (comp_(root_->data, data))
{
root_->right = erase(root_->right, data);
if (getHeight(root_->left) - getHeight(root_->right) == 2)
{
if (getHeight(root_->left->left) > getHeight(root_->left->right))
root_ = rotateLL(root_);
else
root_ = rotateLR(root_);
}
}
else
{
p_node_type temp = nullptr;
if (root_->left && root_->right)
{
temp = findMin(root_->right);
root_->data = temp->data;
root_->right = erase(root_->right, root_->data);
if (getHeight(root_->left) - getHeight(root_->right) == 2)
{
if (getHeight(root_->left->left) > getHeight(root_->left->right))
root_ = rotateLL(root_);
else
root_ = rotateLR(root_);
}
}
else if (root_->left)
{
temp = root_;
root_ = root_->left;
}
else if (root_->right)
{
temp = root_;
root_ = root_->right;
}
else
return nullptr;
}
return root_;
}
// preorder traversal of the AVL tree
void preOrder(p_node_type root_, std::ostream &out) const
{
if (root_ != nullptr)
{
out << (root_)->data << " ";
preOrder((root_)->left, out);
preOrder((root_)->right, out);
}
}
// inorder traversal of the AVL tree
void inOrder(p_node_type root_, std::ostream &out) const
{
if (root_ != nullptr)
{
inOrder((root_)->left, out);
out << (root_)->data << " ";
inOrder((root_)->right, out);
}
}
// postorder traversal of the AVL tree
void postOrder(p_node_type root_, std::ostream &out) const
{
if (root_ != nullptr)
{
postOrder((root_)->left, out);
postOrder((root_)->right, out);
out << (root_)->data << " ";
}
}
};
/*
* // for test
#include <iostream>
* using namespace std;
* int main() {
* int ch, data;
* shared_ptr<avl_tree<int> > avlt = make_shared<avl_tree<int> >();
* while (1)
* {
* cout << "1. Insert 2. Delete 3. Preorder 4. Inorder 5. Postorder 6. Exit\n";
* cin >> ch;
* switch (ch) {
* case 1: cout << "Enter data\n";
* cin >> data;
* avlt->insert(data);
* break;
* case 2: cout << "Enter data\n";
* cin >> data;
* avlt->erase(data);
* break;
* case 3: avlt->preOrder(cout);
* cout << endl;
* break;
* case 4: avlt->inOrder(cout);
* cout << endl;
* break;
* case 5: avlt->postOrder(cout);
* cout << endl;
* break;
* }
* if (ch == 6)
* break;
* }
*
* return 0;
* }
*
* // */
| 9,900
|
C++
|
.cpp
| 344
| 21.90407
| 86
| 0.52163
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,212
|
BST_Operations.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/binary_tree/binary_search_tree/BST_Operations.cpp
|
#include<iostream>
#include<algorithm>
using namespace std;
class BST{
private:
int data;
BST *left,*right;
public:
//Constructors:
BST(){
data=0;
left=right=NULL;
}
BST(int val){
data=val;
left=right=NULL;
}
//Inserting a Node into BST:
BST* InsertNode(BST*,int);
//Delete a Node from BST:
BST* DeletNode(BST*,int);
//Traversals:
void InOrder(BST*);
void PreOrder(BST*);
void PostOrder(BST*);
//Searching
BST* SearchNode(BST*,int);
};
BST* BST::InsertNode(BST *root,int key){
if(root==NULL){
root=new BST(key);
return root;
}
else if(key<=root->data){
if(root->left==NULL){
root->left=new BST(key);
return root;
}
else{
root->left=InsertNode(root->left,key);
return root;
}
}
else{
if(root->right==NULL){
root->right=new BST(key);
return root;
}
else {
root->right=InsertNode(root->right,key);
return root;
}
}
}
BST* BST::DeletNode(BST *root,int key){
// Base case
if (root == NULL)
return root;
//If root->data is greater than k then we delete the root's subtree
if(root->data > key){
root->left = DeletNode(root->left, key);
return root;
}
else if(root->data < key){
root->right = DeletNode(root->right, key);
return root;
}
// If one of the children is empty
if (root->left == NULL) {
BST* temp = root->right;
delete root;
return temp;
}
else if (root->right == NULL) {
BST* temp = root->left;
delete root;
return temp;
}
else {
BST* Parent = root;
// Find successor of the Node
BST *succ = root->right;
while (succ->left != NULL) {
Parent = succ;
succ = succ->left;
}
if (Parent != root)
Parent->left = succ->right;
else
Parent->right = succ->right;
// Copy Successor Data
root->data = succ->data;
// Delete Successor and return root
delete succ;
return root;
}
}
BST* BST::SearchNode(BST *root,int key){
//Base Case
if(root==NULL||root->data==key)
return root;
if(root->data>key){
return SearchNode(root->left,key);
}
return SearchNode(root->right,key);
}
void BST::InOrder(BST *root){
//InOrder traversal of a Binary Search Tree gives sorted order.
if(root==NULL)return;
InOrder(root->left);
cout<<root->data<<" ";
InOrder(root->right);
}
void BST::PreOrder(BST *root){
if(root==NULL)return;
cout<<root->data<<" ";
PreOrder(root->left);
PreOrder(root->right);
}
void BST::PostOrder(BST *root){
if(root==NULL)return;
PostOrder(root->left);
PostOrder(root->right);
cout<<root->data<<" ";
}
int main(){
int choice,element;
BST B,*root=NULL;
while(true){
cout << "------------------\n";
cout << "Operations on Binary Search Tree\n";
cout << "------------------\n";
cout << "1.Insert Element\n";
cout << "2.Delete Element\n";
cout << "3.Search Element\n";
cout << "4.Traversals\n";
cout << "5.Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch(choice){
case 1:
cout << "Enter the element to be inserted: ";
cin >> element;
root=B.InsertNode(root,element);
break;
case 2:
cout << "Enter the element to be deleted: ";
cin >> element;
root=B.DeletNode(root,element);
break;
case 3:
cout << "Search Element: ";
cout << "Enter the element to be Searched: ";
cin >> element;
if (B.SearchNode(root,element)){
cout << "Element Found \n" ;
}
else
cout << "Element Not Found\n";
break;
case 4:
cout << "Displaying elements of BST: ";
cout <<"\nInORder: ";
B.InOrder(root);
cout <<"\nPreORder: ";
B.PreOrder(root);
cout <<"\nPostORder: ";
B.PostOrder(root);
cout<<endl;
break;
case 5:
return 1;
default:
cout << "Enter Correct Choice \n";
}
}
}
| 4,554
|
C++
|
.cpp
| 177
| 17.920904
| 71
| 0.510979
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,213
|
aa_tree.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/binary_tree/aa_tree/aa_tree.cpp
|
/*
* Part of Cosmos by OpenGenus Foundation
* arne andersson tree synopsis
*
* template<typename _Derive, typename _Tp, typename _Comp = std::less<_Tp> >
* struct BinaryTreeNode {
* _Tp value;
* std::shared_ptr<_Derive> left, right;
* BinaryTreeNode(_Tp v,
* std::shared_ptr<_Derive> l = nullptr,
* std::shared_ptr<_Derive> r = nullptr);
* };
*
* template<typename _Tp, typename _Comp = std::less<_Tp> >
* struct AABinaryTreeNode :public BinaryTreeNode<AABinaryTreeNode<_Tp, _Comp>, _Tp, _Comp> {
* size_t level;
* AABinaryTreeNode(_Tp v,
* std::shared_ptr<AABinaryTreeNode> l = nullptr,
* std::shared_ptr<AABinaryTreeNode> r = nullptr);
* };
*
* template<typename _Tp,
* typename _Comp = std::less<_Tp>,
* typename _NodeType = BinaryTreeNode<_Tp, _Comp> >
* class BinaryTree {
* public:
* typedef _Tp value_type;
* typedef value_type & reference;
* typedef value_type const &const_reference;
* typedef std::ptrdiff_t difference_type;
* typedef size_t size_type;
*
* protected:
* typedef BinaryTree<_Tp, _Comp, _NodeType> self;
* typedef _NodeType node_type;
* typedef std::shared_ptr<node_type> p_node_type;
*
* public:
* BinaryTree(p_node_type r = nullptr) :root_(r), sz_(0), comp_(_Comp()), release_(true);
*
* p_node_type const maximum() const;
*
* p_node_type const minimum() const;
*
* size_type size() const;
*
* bool empty() const;
*
* void inOrder(std::ostream &output) const;
*
* void preOrder(std::ostream &output) const;
*
* void postOrder(std::ostream &output) const;
*
* protected:
* p_node_type root_;
* size_type sz_;
* _Comp comp_;
* bool release_;
* p_node_type nil_;
*
* p_node_type get(const_reference value);
*
* p_node_type const maximum(p_node_type n) const;
*
* p_node_type const minimum(p_node_type n) const;
*
* void inOrder(std::ostream &output, p_node_type const n) const;
*
* void preOrder(std::ostream &output, p_node_type const n) const;
*
* void postOrder(std::ostream &output, p_node_type const n) const;
* };
*
* template<typename _Tp, typename _Comp = std::less<_Tp> >
* class AATree :public BinaryTree<_Tp, _Comp, AABinaryTreeNode<_Tp, _Comp> > {
* private:
* typedef BinaryTree<_Tp, _Comp, AABinaryTreeNode<_Tp, _Comp> > base;
* typedef AATree<_Tp, _Comp> self;
*
* public:
* using typename base::size_type;
* using typename base::value_type;
* using typename base::reference;
* using typename base::const_reference;
* using typename base::difference_type;
*
* protected:
* using typename base::p_node_type;
* using typename base::node_type;
* using base::root_;
* using base::comp_;
* using base::nil_;
* using base::sz_;
*
* public:
* AATree() :base();
*
* void insert(const_reference value);
*
* void erase(const_reference value);
*
* p_node_type const find(const_reference value);
*
* private:
* // implement by recursive
* void insert(p_node_type &n, const_reference value);
*
* void erase(p_node_type &n, const_reference value);
*
* // input: T, a node representing an AA tree that needs to be rebalanced.
* // output: Another node representing the rebalanced AA tree.
* p_node_type skew(p_node_type n);
*
* // input: T, a node representing an AA tree that needs to be rebalanced.
* // output: Another node representing the rebalanced AA tree
* p_node_type split(p_node_type n);
*
* void makeNode(p_node_type &n, value_type value);
* };
*/
#include <algorithm>
#include <functional>
#include <memory>
#include <stack>
#include <cstddef>
template<typename _Derive, typename _Tp, typename _Comp = std::less<_Tp>>
struct BinaryTreeNode
{
_Tp value;
std::shared_ptr<_Derive> left, right;
BinaryTreeNode(_Tp v,
std::shared_ptr<_Derive> l = nullptr,
std::shared_ptr<_Derive> r = nullptr)
: value(v), left(l), right(r)
{
};
};
template<typename _Tp, typename _Comp = std::less<_Tp>>
struct AABinaryTreeNode : public BinaryTreeNode<AABinaryTreeNode<_Tp, _Comp>, _Tp, _Comp>
{
size_t level;
AABinaryTreeNode(_Tp v,
std::shared_ptr<AABinaryTreeNode> l = nullptr,
std::shared_ptr<AABinaryTreeNode> r = nullptr)
: BinaryTreeNode<AABinaryTreeNode<_Tp, _Comp>, _Tp, _Comp>(v, l, r), level(1)
{
};
};
template<typename _Tp,
typename _Comp = std::less<_Tp>,
typename _NodeType = BinaryTreeNode<_Tp, _Comp>>
class BinaryTree {
public:
typedef _Tp value_type;
typedef value_type & reference;
typedef value_type const &const_reference;
typedef std::ptrdiff_t difference_type;
typedef size_t size_type;
protected:
typedef BinaryTree<_Tp, _Comp, _NodeType> self;
typedef _NodeType node_type;
typedef std::shared_ptr<node_type> p_node_type;
public:
BinaryTree(p_node_type r = nullptr) : root_(r), sz_(0), comp_(_Comp()), release_(true)
{
};
p_node_type const maximum() const
{
auto f = maximum(root_);
if (f == nil_)
return nullptr;
return f;
}
p_node_type const minimum() const
{
auto f = minimum(root_);
if (f == nil_)
return nullptr;
return f;
}
size_type size() const
{
return sz_;
}
bool empty() const
{
return sz_ == 0;
}
void inOrder(std::ostream &output) const
{
inOrder(output, root_);
}
void preOrder(std::ostream &output) const
{
preOrder(output, root_);
}
void postOrder(std::ostream &output) const
{
postOrder(output, root_);
}
protected:
p_node_type root_;
size_type sz_;
_Comp comp_;
bool release_;
p_node_type nil_;
p_node_type get(const_reference value)
{
p_node_type n = root_;
while (n != nil_)
{
if (comp_(value, n->value))
n = n->left;
else if (comp_(n->value, value))
n = n->right;
else
break;
}
return n;
}
p_node_type const maximum(p_node_type n) const
{
if (n != nil_)
while (n->right != nil_)
n = n->right;
return n;
}
p_node_type const minimum(p_node_type n) const
{
if (n != nil_)
while (n->left != nil_)
n = n->left;
return n;
}
void inOrder(std::ostream &output, p_node_type const n) const
{
if (n != nil_)
{
inOrder(output, n->left);
output << n->value << " ";
inOrder(output, n->right);
}
}
void preOrder(std::ostream &output, p_node_type const n) const
{
if (n != nil_)
{
output << n->value << " ";
preOrder(output, n->left);
preOrder(output, n->right);
}
}
void postOrder(std::ostream &output, p_node_type const n) const
{
if (n != nil_)
{
postOrder(output, n->left);
output << n->value << " ";
postOrder(output, n->right);
}
}
};
template<typename _Tp, typename _Comp = std::less<_Tp>>
class AATree : public BinaryTree<_Tp, _Comp, AABinaryTreeNode<_Tp, _Comp>> {
private:
typedef BinaryTree<_Tp, _Comp, AABinaryTreeNode<_Tp, _Comp>> base;
typedef AATree<_Tp, _Comp> self;
public:
using typename base::size_type;
using typename base::value_type;
using typename base::reference;
using typename base::const_reference;
using typename base::difference_type;
protected:
using typename base::p_node_type;
using typename base::node_type;
using base::root_;
using base::comp_;
using base::nil_;
using base::sz_;
public:
AATree() : base()
{
nil_ = std::make_shared<node_type>(0);
nil_->left = nil_;
nil_->right = nil_;
nil_->level = 0;
root_ = nil_;
}
void insert(const_reference value)
{
insert(root_, value);
}
void erase(const_reference value)
{
erase(root_, value);
}
p_node_type const find(const_reference value)
{
auto f = base::get(value);
if (f == nil_)
return nullptr;
return f;
}
private:
// implement by recursive
void insert(p_node_type &n, const_reference value)
{
if (n == nil_)
{
makeNode(n, value);
++sz_;
}
else
{
if (comp_(value, n->value))
insert(n->left, value);
else if (comp_(n->value, value))
insert(n->right, value);
else // depend on implement
n->value = value;
}
n = skew(n);
n = split(n);
}
void erase(p_node_type &n, const_reference value)
{
if (n != nil_)
{
if (comp_(value, n->value))
erase(n->left, value);
else if (comp_(n->value, value))
erase(n->right, value);
else
{
if (n->left != nil_ && n->right != nil_)
{
p_node_type leftMax = n->left;
while (leftMax->right != nil_)
leftMax = leftMax->right;
n->value = leftMax->value;
erase(n->left, n->value);
}
else // 3 way, n is leaf then nullptr, otherwise n successor
{
p_node_type successor = n->left == nil_ ? n->right : n->left;
n = successor;
--sz_;
}
}
}
if (n != nil_
&& (n->left->level < n->level - 1 || n->right->level < n->level - 1))
{
--n->level;
if (n->right->level > n->level)
n->right->level = n->level;
n = skew(n);
if (n->right != nil_)
n->right = skew(n->right);
if (n->right != nil_ && n->right != nil_)
n->right->right = skew(n->right->right);
n = split(n);
if (n->right != nil_)
n->right = split(n->right);
}
}
// input: T, a node representing an AA tree that needs to be rebalanced.
// output: Another node representing the rebalanced AA tree.
p_node_type skew(p_node_type n)
{
if (n != nil_
&& n->left != nil_
&& n->left->level == n->level)
{
p_node_type left = n->left;
n->left = left->right;
left->right = n;
n = left;
}
return n;
}
// input: T, a node representing an AA tree that needs to be rebalanced.
// output: Another node representing the rebalanced AA tree
p_node_type split(p_node_type n)
{
if (n != nil_
&& n->right != nil_
&& n->right->right != nil_
&& n->level == n->right->right->level)
{
p_node_type right = n->right;
n->right = right->left;
right->left = n;
n = right;
++n->level;
}
return n;
}
void makeNode(p_node_type &n, value_type value)
{
n = std::make_shared<node_type>(value, nil_, nil_);
}
};
/*
* // for test
* // test insert/erase/size function
#include <iostream>
* using namespace std;
*
* int main() {
* std::shared_ptr<AATree<int> > aat = make_shared<AATree<int> >();
*
* if (!aat->empty())
* cout << "error";
*
* auto f = aat->find(3);
* if (f != nullptr)
* cout << "error";
*
* f = aat->maximum();
* if (f != nullptr)
* cout << "error";
*
* f = aat->minimum();
* if (f != nullptr)
* cout << "error";
*
* aat->insert(0);
* f = aat->find(0);
* if (f == nullptr)
* cout << "error";
*
* aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n";
* cout << aat->size() << "\n\n";
* aat->insert(1);
* aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n";
* cout << aat->size() << "\n\n";
* aat->insert(2);
* aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n";
* cout << aat->size() << "\n\n";
* aat->insert(3);
* aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n";
* cout << aat->size() << "\n\n";
* aat->insert(4);
* aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n";
* cout << aat->size() << "\n\n";
* aat->insert(5);
* aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n";
* cout << aat->size() << "\n\n";
* aat->insert(6);
* aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n";
* cout << aat->size() << "\n\n";
* aat->erase(0);
* aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n";
* cout << aat->size() << "\n\n";
* aat->erase(3);
* aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n";
* cout << aat->size() << "\n\n";
* aat->erase(1);
* aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n";
* cout << aat->size() << "\n\n";
* aat->insert(7);
* aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n";
* cout << aat->size() << "\n\n";
* aat->insert(3);
* aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n";
* cout << aat->size() << "\n\n";
* aat->erase(7);
* aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n";
* cout << aat->size() << "\n\n";
* aat->erase(3);
* aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n";
* cout << aat->size() << "\n\n";
* aat->insert(3);
* aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n";
* cout << aat->size() << "\n\n";
* aat->insert(1);
* aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n";
* cout << aat->size() << "\n\n";
* aat->erase(7);
* aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n";
* cout << aat->size() << "\n\n";
* aat->erase(8);
* aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n";
* cout << aat->size() << "\n\n";
*
* f = aat->maximum();
* if (f == nullptr || f->value != 6)
* cout << "error";
*
* f = aat->minimum();
* if (f == nullptr || f->value != 1)
* cout << "error";
*
* if (aat->empty())
* cout << "error";
*
* return 0;
* }
*
*
* expected:
* 0
* 0
* 1
*
* 0 1
* 0 1
* 2
*
* 0 1 2
* 1 0 2
* 3
*
* 0 1 2 3
* 1 0 2 3
* 4
*
* 0 1 2 3 4
* 1 0 3 2 4
* 5
*
* 0 1 2 3 4 5
* 1 0 3 2 4 5
* 6
*
* 0 1 2 3 4 5 6
* 3 1 0 2 5 4 6
* 7
*
* 1 2 3 4 5 6
* 3 1 2 5 4 6
* 6
*
* 1 2 4 5 6
* 2 1 5 4 6
* 5
*
* 2 4 5 6
* 4 2 5 6
* 4
*
* 2 4 5 6 7
* 4 2 6 5 7
* 5
*
* 2 3 4 5 6 7
* 4 2 3 6 5 7
* 6
*
* 2 3 4 5 6
* 4 2 3 5 6
* 5
*
* 2 4 5 6
* 4 2 5 6
* 4
*
* 2 3 4 5 6
* 4 2 3 5 6
* 5
*
* 1 2 3 4 5 6
* 2 1 4 3 5 6
* 6
*
* 1 2 3 4 5 6
* 2 1 4 3 5 6
* 6
*
* 1 2 3 4 5 6
* 2 1 4 3 5 6
* 6
*
*/
| 15,340
|
C++
|
.cpp
| 577
| 21.372617
| 93
| 0.524625
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,214
|
segment_tree_rmq_with_update.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree_rmq_with_update.cpp
|
/* Part of Cosmos by OpenGenus Foundation */
/*
* Processes range minimum query.
* Query function returns index of minimum element in given interval.
* Code assumes that length of array can be contained into integer.
*/
#include <iostream>
#include <utility>
#include <vector>
struct Node
{
// store the data in variable value
int index;
// store the interval in a pair of integers
std::pair<int, int> interval;
Node *left;
Node *right;
};
// update adds new value to array[x] rather than replace it
class SegmentTree {
private:
Node *root;
int build(std::vector<int> &array, Node *node, int L, int R)
{
node->interval = std::make_pair(L, R);
if (L == R)
{
node->index = L;
return node->index;
}
node->left = new Node;
node->right = new Node;
int leftIndex = build(array, node->left, L, (L + R) / 2);
int rightIndex = build(array, node->right, (L + R) / 2 + 1, R);
node->index = (array[leftIndex] < array[rightIndex]) ? leftIndex : rightIndex;
return node->index;
}
// returns the index of smallest element in the range [start, end]
int query(Node *node, int start, int end)
{
if (start > end)
return -1;
int L = node->interval.first;
int R = node->interval.second;
if (R < start || L > end)
return -1;
if (start <= L && end >= R)
return node->index;
int leftIndex = query(node->left, start, end);
int rightIndex = query(node->right, start, end);
if (leftIndex == -1)
return rightIndex;
if (rightIndex == -1)
return leftIndex;
return (array[leftIndex] < array[rightIndex]) ? leftIndex : rightIndex;
}
void update(Node *node, int x, int value)
{
int L = node->interval.first;
int R = node->interval.second;
if (L == R)
{
array[L] += value;
return;
}
if (L <= x && (L + R) / 2 >= x)
// x is in left subtree
update(node->left, x, value);
else
// x is in right subtree
update(node->right, x, value);
int leftIndex = node->left->index;
int rightIndex = node->right->index;
//update current node
node->index = (array[leftIndex] < array[rightIndex]) ? leftIndex : rightIndex;
}
// To clear allocated memory at end of program
void clearMem(Node *node)
{
int L = node->interval.first;
int R = node->interval.second;
if (L != R)
{
clearMem(node->left);
clearMem(node->right);
}
delete node;
}
public:
std::vector<int> array;
SegmentTree(std::vector<int> &ar)
{
array = ar;
root = new Node;
build(ar, root, 0, ar.size() - 1);
}
int query(int L, int R)
{
return query(root, L, R);
}
void update(int pos, int value)
{
return update(root, pos, value);
}
~SegmentTree()
{
clearMem(root);
}
};
int main()
{
// define n and array
int n = 8;
std::vector<int> array = {5, 4, 3, 2, 1, 0, 7, 0};
SegmentTree st(array);
std::cout << "Array:\n";
for (int i = 0; i < n; ++i)
std::cout << st.array[i] << ' ';
std::cout << '\n';
// sample query
std::cout << "The smallest element in the interval [1, 6] is "
<< array[st.query(0, 5)] << '\n'; // since array is 0 indexed.
// change 0 at index 5 to 8
st.update(5, 8);
array[5] += 8;
std::cout << "After update, array:\n";
for (int i = 0; i < n; ++i)
std::cout << st.array[i] << ' ';
std::cout << '\n';
std::cout << "The smallest element in the interval [1, 6] after update is "
<< array[st.query(0, 5)] << '\n';
return 0;
}
| 3,957
|
C++
|
.cpp
| 133
| 22.654135
| 86
| 0.540776
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,216
|
persistent_segment_tree_sum.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/space_partitioning_tree/segment_tree/persistent_segment_tree_sum.cpp
|
// Fully persistent Segment tree with spaces. Allows to find sum in O(log size) time in any version. Uses O(n log size) memory.
#include <iostream>
#include <string>
const int size = 1000000000;
const int versionCount = 100000;
struct node
{
int leftBound, rightBound;
node *leftChild, *rightChild;
int value;
node (int LeftBound, int RightBound)
{
leftBound = LeftBound;
rightBound = RightBound;
value = 0;
leftChild = rightChild = 0;
}
node (node *vertexToClone)
{
leftBound = vertexToClone->leftBound;
rightBound = vertexToClone->rightBound;
value = vertexToClone->value;
leftChild = vertexToClone->leftChild;
rightChild = vertexToClone->rightChild;
}
} *root[versionCount];
void add (node *vertex, int destination, int value)
{
if (vertex->leftBound == destination && vertex->rightBound == destination + 1)
{
vertex->value += value;
return;
}
vertex->value += value;
int middle = (vertex->leftBound + vertex->rightBound) / 2;
if (destination < middle)
{
if (vertex->leftChild == 0)
vertex->leftChild = new node (vertex->leftBound, middle);
else
vertex->leftChild = new node (vertex->leftChild);
add (vertex->leftChild, destination, value);
}
else
{
if (vertex->rightChild == 0)
vertex->rightChild = new node (middle, vertex->rightBound);
else
vertex->rightChild = new node (vertex->rightChild);
add (vertex->rightChild, destination, value);
}
}
int ask (node *vertex, int leftBound, int rightBound)
{
if (vertex == 0)
return 0;
if (vertex->leftBound >= leftBound && vertex->rightBound <= rightBound)
return vertex->value;
if (vertex->leftBound >= rightBound && vertex->rightBound <= leftBound)
return 0;
return ask (vertex->leftChild, leftBound, rightBound) + ask (vertex->rightChild, leftBound,
rightBound);
}
int main ()
{
root[0] = new node (-size, size); // Actually allows negative numbers
std::cout << "Print number of queries!\n";
int q;
std::cin >> q;
int currentVersion = 1;
for (int _ = 0; _ < q; _++)
{
std::string type;
std::cin >> type;
if (type == "add")
{
int version, destination, value;
std::cin >> version >> destination >> value;
root[currentVersion] = new node (root[version]);
add (root[currentVersion], destination, value);
std::cout << "Version " << currentVersion << " created succesfully!\n";
++currentVersion;
}
else if (type == "ask")
{
int version, leftBound, rightBound;
std::cin >> version >> leftBound >> rightBound;
std::cout << ask (root[version], leftBound, rightBound) << "\n";
}
else
std::cout << "Unknown Type! Only add and ask allowed\n";
}
}
| 3,100
|
C++
|
.cpp
| 93
| 25.72043
| 127
| 0.58861
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,217
|
segment_tree_kth_statistics_on_segment.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree_kth_statistics_on_segment.cpp
|
#include <cassert>
#include <iostream>
#include <vector>
using namespace std;
const int lb = -1e9, rb = 1e9;
struct node
{
int val;
node *l, *r;
node()
{
val = 0;
l = r = nullptr;
}
node(int x)
{
val = x;
l = r = nullptr;
}
node(node* vl, node* vr)
{
l = vl;
r = vr;
if (l)
val += l->val;
if (r)
val += r->val;
}
};
vector<node*> tr;
int cnt(node* v)
{
return v ? v->val : 0;
}
node* add_impl(node* v, int tl, int tr, int x)
{
if (tl == tr)
return new node(cnt(v) + 1);
else
{
int tm = (tl + tr) / 2;
if (x <= tm)
return new node(add_impl(v ? v->l : v, tl, tm, x), v ? v->r : v);
else
return new node(v ? v->l : v,
add_impl(v ? v->r : v, tm + 1, tr, x));
}
}
void add(int x)
{
node* v = tr.back();
tr.push_back(add_impl(v, lb, rb, x));
}
int order_of_key_impl(node* v, int tl, int tr, int l, int r)
{
if (!v)
return 0;
if (l == tl && r == tr)
return v->val;
int tm = (tl + tr) / 2;
if (r <= tm)
return order_of_key_impl(v->l, tl, tm, l, r);
else
return order_of_key_impl(v->l, tl, tm, l, tm) +
order_of_key_impl(v->r, tm + 1, tr, tm + 1, r);
}
int order_of_key(int l, int r, int x)
{
int ans = order_of_key_impl(tr[r], lb, rb, lb, x - 1) -
order_of_key_impl(tr[l - 1], lb, rb, lb, x - 1) + 1;
return ans;
}
int find_by_order_impl(node* l, node* r, int tl, int tr, int x)
{
if (tl == tr)
return tl;
int tm = (tl + tr) / 2;
if (cnt(r ? r->l : r) - cnt(l ? l->l : l) >= x)
return find_by_order_impl(l ? l->l : l, r ? r->l : r, tl, tm, x);
else
return find_by_order_impl(l ? l->r : l, r ? r->r : r, tm + 1, tr,
x - (cnt(r ? r->l : r) - cnt(l ? l->l : l)));
}
int find_by_order(int l, int r, int x)
{
assert(r - l + 1 >= x && x > 0);
return find_by_order_impl(tr[l - 1], tr[r], lb, rb, x);
}
int main()
{
tr.push_back(nullptr);
vector<int> a;
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
int x;
cin >> x;
a.push_back(x);
add(x);
}
int q;
cin >> q;
for (int i = 0; i < q; i++)
{
int t; // type of question: 1 - order of key, 2 - find by order
cin >> t;
int l, r, x; // 1 <= l <= r <= n
cin >> l >> r >> x;
if (t == 1)
cout << order_of_key(l, r, x) << endl;
else
cout << find_by_order(l, r, x) << endl;
}
}
| 2,687
|
C++
|
.cpp
| 115
| 17.434783
| 80
| 0.43196
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,218
|
segment_tree_rmq.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree_rmq.cpp
|
/* Name: Mohit Khare
* B.Tech 2nd Year
* Computer Science and Engineering
* MNNIT Allahabad
*/
#include <cstdio>
#include <climits>
#define min(a, b) ((a) < (b) ? (a) : (b))
using namespace std;
typedef long long int ll;
#define mod 1000000007
const int maxn = 1e5 + 1;
void build(ll segtree[], ll arr[], int low, int high, int pos)
{
if (low == high)
{
segtree[pos] = arr[low];
return;
}
int mid = (low + high) / 2;
build(segtree, arr, low, mid, 2 * pos + 1);
build(segtree, arr, mid + 1, high, 2 * pos + 2);
segtree[pos] = min(segtree[2 * pos + 2], segtree[2 * pos + 1]);
}
ll query(ll segtree[], ll arr[], int low, int high, int qs, int qe, int pos)
{
if (qe < low || qs > high)
return LLONG_MAX;
if (qs <= low && high <= qe)
return segtree[pos];
int mid = (low + high) / 2;
ll left = query(segtree, arr, low, mid, qs, qe, 2 * pos + 1);
ll right = query(segtree, arr, mid + 1, high, qs, qe, 2 * pos + 2);
return min(right, left);
}
int main()
{
int n, m;
printf("Input no of input elements and no. of queries\n");
scanf("%d %d", &n, &m);
ll segtree[4 * n], arr[n];
printf("Input Array elements\n");
for (int i = 0; i < n; i++)
scanf("%lld", &arr[i]);
build(segtree, arr, 0, n - 1, 0);
for (int i = 0; i < m; i++)
{
int l, r;
printf("Enter range - l and r\n");
scanf("%d %d", &l, &r);
l--; r--;
printf("Result is :%lld\n", query(segtree, arr, 0, n - 1, l, r, 0));
}
return 0;
}
/* Test Case
*
* 5 2
* Input Array elements
* 3 4 2 1 5
* 1 2
* Result is :3
* 2 5
* Result is :1
*
*/
| 1,678
|
C++
|
.cpp
| 66
| 21.469697
| 76
| 0.541381
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,219
|
segment_tree_sum.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree_sum.cpp
|
// Segment tree with spaces. Allows to find sum in O(log size) time. Uses O(n log size) memory.
#include <iostream>
#include <string>
const int size = 1000000000;
struct node
{
int leftBound, rightBound;
node *leftChild, *rightChild;
int value;
node (int LeftBound, int RightBound)
{
leftBound = LeftBound;
rightBound = RightBound;
value = 0;
leftChild = rightChild = 0;
}
} *root;
void add (node *vertex, int destination, int value)
{
if (vertex->leftBound == destination && vertex->rightBound == destination + 1)
{
vertex->value += value;
return;
}
vertex->value += value;
int middle = (vertex->leftBound + vertex->rightBound) / 2;
if (destination < middle)
{
if (vertex->leftChild == 0)
vertex->leftChild = new node (vertex->leftBound, middle);
add (vertex->leftChild, destination, value);
}
else
{
if (vertex->rightChild == 0)
vertex->rightChild = new node (middle, vertex->rightBound);
add (vertex->rightChild, destination, value);
}
}
int ask (node *vertex, int leftBound, int rightBound)
{
if (vertex == 0)
return 0;
if (vertex->leftBound >= leftBound && vertex->rightBound <= rightBound)
return vertex->value;
if (vertex->leftBound >= rightBound && vertex->rightBound <= leftBound)
return 0;
return ask (vertex->leftChild, leftBound, rightBound) + ask (vertex->rightChild, leftBound,
rightBound);
}
int main ()
{
root = new node (-size, size); // Actually allows negative numbers
std::cout << "Print number of queries!\n";
int q;
std::cin >> q;
for (int _ = 0; _ < q; _++)
{
std::string type;
std::cin >> type;
if (type == "add")
{
int destination, value;
std::cin >> destination >> value;
add (root, destination, value);
std::cout << "Added succesfully!\n";
}
else if (type == "ask")
{
int leftBound, rightBound;
std::cin >> leftBound >> rightBound;
std::cout << ask (root, leftBound, rightBound) << "\n";
}
else
std::cout << "Unknown Type! Only add and ask allowed\n";
}
}
| 2,376
|
C++
|
.cpp
| 77
| 23.454545
| 95
| 0.568232
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,223
|
min_heap.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/heap/min_heap/min_heap.cpp
|
/* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
#include <vector>
using namespace std;
class minHeap {
vector<int> v;
void heapify(size_t i)
{
size_t l = 2 * i;
size_t r = 2 * i + 1;
size_t min = i;
if (l < v.size() && v[l] < v[min])
min = l;
if (r < v.size() && v[r] < v[min])
min = r;
if (min != i)
{
swap(v[i], v[min]);
heapify(min);
}
}
public:
minHeap()
{
v.push_back(-1);
}
void insert(int data)
{
v.push_back(data);
int i = v.size() - 1;
int parent = i / 2;
while (v[i] < v[parent] && i > 1)
{
swap(v[i], v[parent]);
i = parent;
parent = parent / 2;
}
}
int top()
{
return v[1];
}
void pop()
{
int last = v.size() - 1;
swap(v[1], v[last]);
v.pop_back();
heapify(1);
}
bool isEmpty()
{
return v.size() == 1;
}
};
int main()
{
int data;
cout << "\nEnter data : ";
cin >> data;
minHeap h;
while (data != -1)
{
h.insert(data);
cout << "\nEnter data(-1 to exit) : ";
cin >> data;
}
while (!h.isEmpty())
{
cout << h.top() << " ";
h.pop();
}
return 0;
}
| 1,396
|
C++
|
.cpp
| 73
| 12.30137
| 46
| 0.40916
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,224
|
soft_heap.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/heap/soft_heap/soft_heap.cpp
|
/**
* Soft Heap
* Author: JonNRb
*
* Original paper: https://www.cs.princeton.edu/~chazelle/pubs/sheap.pdf
* Binary heap version by Kaplan and Zwick
*/
#include <functional>
#include <iterator>
#include <limits>
#include <list>
#include <memory>
#include <stdexcept>
using namespace std;
#if __cplusplus <= 201103L
namespace {
template <typename T, typename ... Args>
unique_ptr<T> make_unique(Args&& ... args)
{
return unique_ptr<T>(new T(forward<Args>(args) ...));
}
} // namespace
#endif
// `T` is a comparable type and higher values of `corruption` increase the
// orderedness of the soft heap
template <typename T>
class SoftHeap {
private:
// `node`s make up elements in the soft queue, which is a binary heap with
// "corrupted" entries
struct node
{
typename list<T>::iterator super_key;
unsigned rank;
// `target_size` is a target for the number of corrupted nodes. the number
// increases going up the heap and should be between 1 and 2 times the
// `target_size` of its children -- unless it is `corruption` steps from the
// bottom, in which case it is 1.
unsigned target_size;
// `link[0]` is the left node and `link[1]` is the right node
unique_ptr<node> link[2];
// if `l` contains more than 1 entry, the node is "corrupted"
list<T> l;
};
struct head
{
// the root of a "soft queue": a binary heap of nodes
unique_ptr<node> q;
// iterator to the tree following this one with the minimum `super_key` at
// the root. may be the current `head`.
typename list<head>::iterator suffix_min;
};
// doubly-linked list of all binary heaps (soft queues) in the soft heap
list<head> l;
unsigned corruption;
public:
SoftHeap(unsigned corruption) : corruption(corruption)
{
}
bool empty()
{
return l.empty();
}
void push(T item)
{
auto item_node = make_unique<node>();
item_node->rank = 0;
item_node->target_size = 1;
item_node->link[0] = nullptr;
item_node->link[1] = nullptr;
item_node->l.push_front(move(item));
item_node->super_key = item_node->l.begin();
l.emplace_front();
auto h = l.begin();
h->q = move(item_node);
h->suffix_min = next(h) != l.end() ? next(h)->suffix_min : h;
repeated_combine(1);
}
T pop()
{
if (l.empty())
throw invalid_argument("empty soft heap");
auto it = l.begin()->suffix_min;
node* n = it->q.get();
T ret = move(*n->l.begin());
n->l.pop_front();
if (n->l.size() < n->target_size)
{
if (n->link[0] || n->link[1])
{
sift(n);
update_suffix_min(it);
}
else if (n->l.empty())
{
if (it == l.begin())
l.erase(it);
else
{
auto p = prev(it);
l.erase(it);
update_suffix_min(p);
}
}
}
return ret;
}
private:
void update_suffix_min(typename list<head>::iterator it) const
{
if (it == l.end())
return;
while (true)
{
if (next(it) == l.end())
it->suffix_min = it;
else if (*it->q->super_key <= *next(it)->suffix_min->q->super_key)
it->suffix_min = it;
else
it->suffix_min = next(it)->suffix_min;
if (it == l.begin())
return;
--it;
}
}
unique_ptr<node> combine(unique_ptr<node> a, unique_ptr<node> b) const
{
auto n = make_unique<node>();
n->rank = a->rank + 1;
n->target_size = n->rank <= corruption ? 1 : (3 * a->target_size + 1) / 2;
n->link[0] = move(a);
n->link[1] = move(b);
sift(n.get());
return n;
}
void repeated_combine(unsigned max_rank)
{
auto it = l.begin();
for (auto next_it = next(l.begin()); next_it != l.end();
it = next_it, ++next_it)
{
if (it->q->rank == next_it->q->rank)
{
if (next(next_it) == l.end() || next(next_it)->q->rank != it->q->rank)
{
it->q = combine(move(it->q), move(next_it->q));
next_it = l.erase(next_it);
if (next_it == l.end())
break;
}
}
else if (it->q->rank > max_rank)
break;
}
update_suffix_min(it);
}
static void sift(node* n)
{
while (n->l.size() < n->target_size)
{
if (n->link[1])
{
if (!n->link[0] || *n->link[0]->super_key > *n->link[1]->super_key)
swap(n->link[0], n->link[1]);
}
else if (!n->link[0])
return;
n->super_key = n->link[0]->super_key;
n->l.splice(n->l.end(), n->link[0]->l);
if (!n->link[0]->link[0] && !n->link[0]->link[1])
n->link[0] = nullptr;
else
sift(n->link[0].get());
}
}
};
#include <chrono>
#include <iostream>
#include <random>
#include <vector>
int run_test_with_corruption(unsigned corruption, unsigned k_num_elems)
{
using namespace std::chrono;
cout << "making soft heap with corruption " << corruption << " and "
<< k_num_elems << " elements..." << endl;
SoftHeap<unsigned> sh(corruption);
// create a random ordering of the numbers [0, k_num_elems)
vector<bool> popped_nums(k_num_elems);
vector<unsigned> nums(k_num_elems);
random_device rd;
mt19937 gen(rd());
for (unsigned i = 0; i < k_num_elems; ++i)
nums[i] = i;
for (unsigned i = 0; i < k_num_elems; ++i)
{
uniform_int_distribution<unsigned> dis(i, k_num_elems - 1);
swap(nums[i], nums[dis(gen)]);
}
auto start = steady_clock::now();
for (unsigned i = 0; i < k_num_elems; ++i)
sh.push(nums[i]);
// this notion of `num_errs` is not rigorous in any way
unsigned num_errs = 0;
unsigned last = 0;
while (!sh.empty())
{
unsigned i = sh.pop();
if (popped_nums[i])
{
cerr << " popped number " << i << " already" << endl;
return -1;
}
popped_nums[i] = true;
if (i < last)
++num_errs;
last = i;
// cout << i << endl;
}
auto end = steady_clock::now();
cout << " error rate: " << ((double)num_errs / k_num_elems) << endl;
cout << " took " << duration_cast<milliseconds>(end - start).count() << " ms"
<< endl;
return 0;
}
int main()
{
for (unsigned i = 0; i < 20; ++i)
if (run_test_with_corruption(i, 1 << 18))
return -1;
return 0;
}
| 7,073
|
C++
|
.cpp
| 231
| 22.294372
| 86
| 0.508011
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,225
|
binomial_heap.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/heap/binomial_heap/binomial_heap.cpp
|
#include <iostream>
#include <queue>
#include <vector>
/* Part of Cosmos by OpenGenus Foundation */
using namespace std;
class Node {
public:
int value;
int degree;
Node* parent;
Node* child;
Node* sibling;
Node() : value(0), degree(0), parent(0), child(0), sibling(0)
{
};
~Node()
{
};
};
class BinomialHeap {
public:
BinomialHeap() : head(NULL)
{
}
Node* getHead()
{
return head;
}
void insert(int value)
{
BinomialHeap tempHeap;
Node* tempNode = new Node();
tempNode->value = value;
tempHeap.setHead(&tempNode);
bHeapUnion(tempHeap);
}
void deleteMin()
{
int min = head->value;
Node* tmp = head;
Node* minPre = NULL;
Node* minCurr = head;
//find the root x with the minimum key in the root list of H
// remove x from the root list of H
while (tmp->sibling)
{
if (tmp->sibling->value < min)
{
min = tmp->sibling->value;
minPre = tmp;
minCurr = tmp->sibling;
}
tmp = tmp->sibling;
}
if (!minPre && minCurr)
head = minCurr->sibling;
else if (minPre && minCurr)
minPre->sibling = minCurr->sibling;
//H' Make-BINOMIAL-HEAP()
BinomialHeap bh;
Node *pre, *curr;
//reverse the order of the linked list of x's children
pre = tmp = NULL;
curr = minCurr->child;
while (curr)
{
tmp = curr->sibling;
curr->sibling = pre;
curr->parent = NULL;
pre = curr;
curr = tmp;
}
//set head[H'] to point to the head of the resulting list
bh.setHead(&pre);
//H <- BINOMIAL-HEAP-UNION
bHeapUnion(bh);
}
int getMin()
{
int min = 2 << 20;
Node* tmp = head;
while (tmp)
{
if (tmp->value < min)
min = tmp->value;
tmp = tmp->sibling;
}
return min;
}
void preorder()
{
puts("");
Node* tmp = head;
while (tmp)
{
_preorder(tmp);
tmp = tmp->sibling;
}
puts("");
}
void BFS()
{
puts("");
queue<Node*> nodeQueue;
Node *tmp = head;
while (tmp)
{
nodeQueue.push(tmp);
tmp = tmp->sibling;
}
while (!nodeQueue.empty())
{
Node *node = nodeQueue.front();
nodeQueue.pop();
if (node)
printf("%d ", node->value);
node = node->child;
while (node)
{
nodeQueue.push(node);
node = node->sibling;
}
}
puts("");
}
void bHeapUnion(BinomialHeap &bh)
{
_mergeHeap(bh);
Node* prev = NULL;
Node* x = head;
Node* next = x->sibling;
while (next)
{
if (x->degree != next->degree)
{
prev = x; //Case 1 and 2
x = next; //Case 1 and 2
}
else if (next->sibling && next->sibling->degree == x->degree) //three BT has the same degree
{
if (next->value < x->value && next->value < next->sibling->value) //312, need to trans to 132
{
x->sibling = next->sibling;
next->sibling = x;
if (prev)
prev->sibling = next;
else
head = next;
prev = x;
x = next;
}
else if (next->sibling->value < x->value && next->sibling->value < next->value) //321, need to trans to 123
{
x->sibling = next->sibling->sibling;
next->sibling->sibling = next;
if (prev)
prev->sibling = next->sibling;
else
head = next->sibling;
prev = next->sibling;
next->sibling = x;
x = next;
}
else
{
prev = x; //Case 1 and 2
x = next; //Case 1 and 2
}
}
else if (x->value <= next->value)
{
x->sibling = next->sibling; //Case 3
_mergeTree(next, x); //Case 3
next = x;
}
else
{
if (!prev) //Case 4
head = next; //Case 4
else
prev->sibling = next; //Case 4
_mergeTree(x, next); //Case 4
x = next; //Case 4
}
next = next->sibling; //Case 4
}
}
int size()
{
return _size(head);
}
void setHead(Node** node)
{
head = *node;
}
private:
int _size(Node* node)
{
if (!node)
return 0;
return 1 + _size(node->child) + _size(node->sibling);
}
void _preorder(Node* node)
{
if (!node)
return;
printf("%d ", node->value);
_preorder(node->child);
if (node->parent)
_preorder(node->sibling);
//printf("%d(%d) ",node->value,node->degree);
}
void _mergeTree(Node* tree1, Node* tree2)
{
tree1->parent = tree2;
tree1->sibling = tree2->child;
tree2->child = tree1;
tree2->degree++;
}
void _mergeHeap(BinomialHeap &bh)
{
Node* head2 = bh.getHead();
Node* head1 = head;
//for new pointer
Node *newHead, *newCurr;
if (!head1)
{
head = head2;
return;
}
if (head1->degree > head2->degree)
{
newHead = newCurr = head2;
head2 = head2->sibling;
}
else
{
newHead = newCurr = head1;
head1 = head1->sibling;
}
//Sorted by degree into monotonically increasing order
while (head1 && head2)
{
if (head1->degree < head2->degree)
{
newCurr->sibling = head1;
newCurr = head1;
head1 = head1->sibling;
}
else
{
newCurr->sibling = head2;
newCurr = head2;
head2 = head2->sibling;
}
}
while (head1)
{
newCurr->sibling = head1;
newCurr = head1;
head1 = head1->sibling;
}
while (head2)
{
newCurr->sibling = head2;
newCurr = head2;
head2 = head2->sibling;
}
head = newHead;
}
Node* head;
};
int main()
{
vector<int> heap1{5, 4, 3, 2, 1};
vector<int> heap2{4, 3, 2, 1, 8};
BinomialHeap bh1, bh2;
for (auto v: heap1)
bh1.insert(v);
for (auto v: heap2)
bh2.insert(v);
printf("preorder traversal of first binomialheap: ");
bh1.preorder();
printf("BFS of first binomialheap: ");
bh1.BFS();
printf("\n");
printf("preorder traversal of second binomialheap: ");
bh2.preorder();
printf("BFS of second binomialheap: ");
bh2.BFS();
printf("-----------Union------------------\n");;
bh1.bHeapUnion(bh2);
printf("preorder traversal of union: ");
bh1.preorder();
printf("BFS of union: ");
bh1.BFS();
printf("-----------Delete min = 1 --------\n");
bh1.deleteMin();
printf("preorder traversal of delete min: ");
bh1.preorder();
printf("BFS of union: ");
bh1.BFS();
printf("-----------Delete min = 2 --------\n");
bh1.deleteMin();
printf("preorder traversal of delete min: ");
bh1.preorder();
printf("BFS of union: ");
bh1.BFS();
printf("binomialheap min:%d\n", bh1.getMin());
printf("binomailheap size %d\n", bh1.size());
}
| 8,789
|
C++
|
.cpp
| 311
| 18.29582
| 149
| 0.418145
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,226
|
leftist_priority_queue.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/heap/priority_queue/leftist_tree/leftist_priority_queue.cpp
|
#include <iostream>
#include <algorithm>
struct Leftist
{
Leftist *left, *right;
// dis is the distance to the right-bottom side of the tree
int dis, value, size;
Leftist(int val = 0)
{
left = NULL, right = NULL;
dis = 0, value = val, size = 1;
}
~Leftist()
{
delete left;
delete right;
}
};
Leftist* merge(Leftist *x, Leftist *y)
{
// if x or y is NULL, return the other tree to be the answer
if (x == NULL)
return y;
if (y == NULL)
return x;
if (y->value < x->value)
std::swap(x, y);
// We take x as new root, so add the size of y to x
x->size += y->size;
// merge the origin right sub-tree of x with y to construct the new right sub-tree of x
x->right = merge(x->right, y);
if (x->left == NULL && x->right != NULL)
// if x->left is NULL pointer, swap the sub-trees to make it leftist
std::swap(x->left, x->right);
else if (x->right != NULL && x->left->dis < x->right->dis)
// if the distance of left sub-tree is smaller, swap the sub-trees to make it leftist
std::swap(x->left, x->right);
// calculate the new distance
if (x->right == NULL)
x->dis = 0;
else
x->dis = x->right->dis + 1;
return x;
}
Leftist* delete_root(Leftist *T)
{
//deleting root equals to make a new tree containing only left sub-tree and right sub-tree
Leftist *my_left = T->left;
Leftist *my_right = T->right;
T->left = T->right = NULL;
delete T;
return merge(my_left, my_right);
}
int main()
{
Leftist *my_tree = new Leftist(10); // create a tree with root = 10
// adding a node to a tree is the same as creating a new tree and merge them together
my_tree = merge(my_tree, new Leftist(100)); // push 100
my_tree = merge(my_tree, new Leftist(10000)); // push 10000
my_tree = merge(my_tree, new Leftist(1)); // push 1
my_tree = merge(my_tree, new Leftist(1266)); // push 1266
while (my_tree != NULL)
{
std::cout << my_tree->value << std::endl;
my_tree = delete_root(my_tree);
}
return 0;
}
/* the output should be
* 1
* 10
* 100
* 1266
* 10000
*/
| 2,217
|
C++
|
.cpp
| 75
| 24.64
| 94
| 0.594366
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
10,227
|
van_emde_boas_tree.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/van_emde_boas_tree/van_emde_boas_tree.cpp
|
#include <bits/stdc++.h>
using namespace std;
class veb
{
int u;
int *min;
int *max;
veb *summary;
veb **cluster;
public:
veb(int u);
void insert(int x);
void remove(int x);
int* pred(int x);
int minimum();
int maximum();
};
veb :: veb(int u)
{
this->u = u;
this->min = NULL;
this->max = NULL;
if (u == 2)
{
this->summary = NULL;
this->cluster = NULL;
}
else
{
int sub_size = sqrt(u);
this->summary = new veb(sub_size);
this->cluster = new veb*[sub_size];
}
}
void veb::insert(int x)
{
if (u == 2)
{
if (x == 0)
{
if (max == NULL)
{
max = new int;
min = new int;
*max = x;
*min = x;
}
else
*min = x;
}
else if (x == 1)
{
if (min == NULL)
{
max = new int;
min = new int;
*max = x;
*min = x;
}
else
*max = x;
}
}
else
{
if (min == NULL)
{
min = new int;
max = new int;
*max = x;
*min = x;
this->insert(x);
}
else
{
if ((*min) > x)
{
*min = x;
this->insert(x);
}
else
{
int subsize = sqrt(u);
int high = x / subsize, low = x % subsize;
if (cluster[high] == NULL)
{
cluster[high] = new veb(subsize);
cluster[high]->insert(low);
summary->insert(high);
}
else
cluster[high]->insert(low);
if ((*max) < x)
*max = x;
}
}
}
}
void veb::remove(int x)
{
if (u == 2)
{
if (x == 0)
{
if (min != NULL)
{
if (*max == 0)
{
min = NULL;
max = NULL;
}
else
*min = 1;
}
}
else if (max != NULL)
{
if (*min == 1)
{
min = NULL;
max = NULL;
}
else
*max = 0;
}
}
else
{
int subsize = sqrt(u);
int high = x / subsize, low = x % subsize;
if (min == NULL || cluster[high] == NULL)
return;
if (x == *min)
{
if (x == *max)
{
min = NULL;
max = NULL;
cluster[high]->remove(low);
return;
}
cluster[high]->remove(low);
if (cluster[high]->min == NULL)
{
delete cluster[high];
cluster[high] = NULL;
summary->remove(high);
}
int newminhigh = summary->minimum();
int newminlow = cluster[newminhigh]->minimum();
*min = newminhigh * subsize + newminlow;
}
else
{
cluster[high]->remove(low);
if (cluster[high]->min == NULL)
{
delete cluster[high];
cluster[high] = NULL;
summary->remove(high);
}
if (x == *max)
{
int newmaxhigh = summary->maximum();
int newmaxlow = cluster[newmaxhigh]->maximum();
*max = newmaxhigh * subsize + newmaxlow;
}
}
}
}
int* veb::pred(int x)
{
if (u == 2)
{
if (x == 0)
return NULL;
else if (x == 1)
{
if (min == NULL)
return NULL;
else if ((*min) == 1)
return NULL;
else
return min;
}
else
return NULL;
}
else
{
if (min == NULL)
return NULL;
if ((*min) >= x)
return NULL;
if (x > (*max))
return max;
int subsize = sqrt(u);
int high = x / subsize;
int low = x % subsize;
if (cluster[high] == NULL)
{
int *pred = summary->pred(high);
int *ans = new int;
*ans = (*pred) * subsize + *(cluster[*pred]->max);
return ans;
}
else
{
int *ans_high = new int;
int *ans_low = new int;
if (low > *(cluster[high]->min))
{
*ans_high = high;
ans_low = cluster[high]->pred(low);
}
else
{
ans_high = summary->pred(high);
ans_low = cluster[(*ans_high)]->max;
}
int *ans = new int;
*ans = (*ans_high) * subsize + (*ans_low);
return ans;
}
}
}
int veb::minimum()
{
return *min;
}
int veb::maximum()
{
return *max;
}
void findpred(veb *x, int y)
{
int *temp = x->pred(y);
if (temp == NULL)
cout << "no predecesor" << endl;
else
cout << "predecesor of " << y << " is " << *temp << endl;
}
int main()
{
veb *x = new veb(16);
x->insert(2);
x->insert(3);
x->insert(4);
x->insert(5);
x->insert(7);
x->insert(14);
x->insert(15);
cout << x->minimum() << endl << x->maximum() << endl;
findpred(x, 0);
findpred(x, 1);
findpred(x, 2);
findpred(x, 3);
findpred(x, 4);
findpred(x, 5);
findpred(x, 6);
findpred(x, 7);
findpred(x, 8);
findpred(x, 9);
findpred(x, 10);
findpred(x, 11);
findpred(x, 12);
findpred(x, 13);
findpred(x, 14);
findpred(x, 15);
findpred(x, 16);
findpred(x, 7);
x->remove(15);
x->remove(5);
findpred(x, 0);
findpred(x, 1);
findpred(x, 2);
findpred(x, 3);
findpred(x, 4);
findpred(x, 5);
findpred(x, 6);
findpred(x, 7);
findpred(x, 8);
findpred(x, 9);
findpred(x, 10);
findpred(x, 11);
findpred(x, 12);
findpred(x, 13);
findpred(x, 14);
findpred(x, 15);
findpred(x, 16);
findpred(x, 7);
}
| 6,472
|
C++
|
.cpp
| 292
| 12.582192
| 65
| 0.382449
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,229
|
suffix_array.cpp
|
OpenGenus_cosmos/code/data_structures/src/tree/tree/suffix_array/suffix_array.cpp
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#define ll size_t
using namespace std;
struct ranking
{
ll index;
ll first;
ll second;
};
bool comp(ranking a, ranking b)
{
if (a.first == b.first)
return a.second < b.second;
return a.first < b.first;
}
vector<ll> build_suffix_array(string s)
{
const ll n = s.length();
const ll lgn = ceil(log2(n));
// vector to hold final suffix array result
vector<ll> sa(n);
// P[i][j] holds the ranking of the j-th suffix
// after comparing the first 2^i characters
// of that suffix
ll P[lgn][n];
// vector to store ranking tuples of suffixes
vector<ranking> ranks(n);
ll i, j, step = 1;
for (j = 0; j < n; j++)
P[0][j] = s[j] - 'a';
for (i = 1; i <= lgn; i++, step++)
{
for (j = 0; j < n; j++)
{
ranks[j].index = j;
ranks[j].first = P[i - 1][j];
ranks[j].second = (j + std::pow(2, i - 1) < n) ? P[i - 1][j + (ll)(pow(2, i - 1))] : -1;
}
std::sort(ranks.begin(), ranks.end(), comp);
for (j = 0; j < n; j++)
P[i][ranks[j].index] =
(j > 0 && ranks[j].first == ranks[j - 1].first &&
ranks[j].second == ranks[j - 1].second) ? P[i][ranks[j - 1].index] : j;
}
step -= 1;
for (i = 0; i < n; i++)
sa[P[step][i]] = i;
return sa;
}
int main()
{
string s;
cin >> s;
vector<ll> sa = build_suffix_array(s);
for (ll i = 0; i < s.length(); i++)
cout << i << " : " << sa[i] << endl;
return 0;
}
| 1,625
|
C++
|
.cpp
| 61
| 21.04918
| 100
| 0.503551
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
10,231
|
KadaneAlgorithm.cpp
|
OpenGenus_cosmos/code/data_structures/src/maxSubArray(KadaneAlgorithm)/KadaneAlgorithm.cpp
|
#include <iostream>
#include <vector>
using namespace std;
int Kadane(vector<int>& arr) {
int max_so_far = INT_MIN;
int max_ending_here = 0;
for (int i = 0; i < arr.size(); i++) {
max_ending_here = max_ending_here + arr[i];
if (max_ending_here < 0) {
max_ending_here = 0;
}
if (max_so_far < max_ending_here) {
max_so_far = max_ending_here;
}
}
return max_so_far;
}
int main(){
vector<int> a = {-2, -3, 4, -1, -2, 1, 5, -3};
cout << Kadane(a) << endl;
return 0;
}
// Time Complexity: O(n)
// Space Complexity: O(1)
// Kadane algorithm is a simple algorithm for finding the maximum subarray sum in a given array.
| 712
|
C++
|
.cpp
| 25
| 23.44
| 96
| 0.57478
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,232
|
Add_one_to_LL.cpp
|
OpenGenus_cosmos/code/data_structures/src/Linked_List/Add_one_to_LL.cpp
|
class Solution
{
public:
Node* reverse( Node *head)
{
// code here
// return head of reversed list
Node *prevNode=NULL,*currNode=head,*nextNode=head;
while(currNode!=NULL){
nextNode=currNode->next;
currNode->next=prevNode;
prevNode=currNode;
currNode=nextNode;
}
return prevNode;
}
Node* addOne(Node *head)
{
// Your Code here
// return head of list after adding one
if(head==NULL)
return NULL;
head=reverse(head);
Node* node=head;int carry=1;
while(node!=NULL){
int sum=carry+node->data;
node->data=(sum%10);
carry=sum/10;
if(node->next==NULL) break;
node=node->next;
}
if(carry) node->next=new Node(carry);
return reverse(head);
}
};
| 963
|
C++
|
.cpp
| 35
| 17.171429
| 58
| 0.530023
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,234
|
Intersection_of_two_sorted_lists.cpp
|
OpenGenus_cosmos/code/data_structures/src/Linked_List/Intersection_of_two_sorted_lists.cpp
|
Node* findIntersection(Node* head1, Node* head2)
{
if(head1==NULL or head2==NULL) return NULL;
if(head1->data==head2->data)
{
head1->next=findIntersection(head1->next,head2->next);
return head1;
}
else if(head1->data>head2->data)
return findIntersection(head1,head2->next);
else return findIntersection(head1->next,head2);
}
| 391
|
C++
|
.cpp
| 12
| 26.083333
| 62
| 0.679666
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.