id
int64 0
755k
| 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
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9,941
|
n_queen_bitimp.cpp
|
OpenGenus_cosmos/code/backtracking/src/n_queen/n_queen_bitimp.cpp
|
#include <iostream>
// Part of Cosmos by OpenGenus Foundation
using namespace std;
int limit;
int N;
int counter;
void Backtracking(int position, int left, int right, int depth)
{
if (depth == N)
{
counter++;
return;
}
int currentPos = position | left | right;
int newPos;
while (currentPos < limit)
{
newPos = (currentPos + 1) & ~currentPos;
Backtracking( position | newPos, limit & ((left | newPos) << 1),
limit & ((right | newPos) >> 1), depth + 1);
currentPos = currentPos | newPos;
}
}
int main()
{
cout << "Please Enter the size of board" << endl;
cin >> N;
counter = 0;
limit = (1 << (N)) - 1;
Backtracking(0, 0, 0, 0);
cout << "There are " << counter << " ways" << endl;
}
| 800
|
C++
|
.cpp
| 32
| 20.28125
| 72
| 0.571056
|
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
|
9,942
|
n_queen_backtracking.cpp
|
OpenGenus_cosmos/code/backtracking/src/n_queen/n_queen_backtracking.cpp
|
#include <iostream>
// Part of Cosmos by OpenGenus Foundation
using namespace std;
bool isSafe(char board[][100], int row, int column, int n)
{
//check that whole row should not have a queen
for (int i = 0; i < n; i++)
if (board[row][i] == 'Q')
return false;
//check that whole column should not have a queen
for (int i = 0; i < n; i++)
if (board[i][column] == 'Q')
return false;
//check that left diagonal to the current cell should not have queen
int p = row, q = column;
while (p >= 0 && q >= 0)
{
if (board[p][q] == 'Q')
return false;
p--; q--;
}
//check that right diagonal to the current cell should not have queen
p = row; q = column;
while (p >= 0 && q <= n - 1)
{
if (board[p][q] == 'Q')
return false;
p--; q++;
}
return true;
}
bool nqueen(char board[][100], int n, int i = 0)
{
if (i == n)
{
//board is filled with the n-queens, just print the board
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
cout << board[i][j] << " ";
cout << endl;
}
return true; //hack :: if to print all possible combination just make it false
}
for (int j = 0; j < n; j++)
if (isSafe(board, i, j, n)) //check that cell is safe or not
{
board[i][j] = 'Q'; //if it's safe, then place a queen at that cell
if (nqueen(board, n, i + 1)) //now searching place for queen in next row
return true;
board[i][j] = '.'; //since, not safe, so again mark that cell with '.'
}
return false;
}
int main()
{
int n;
cin >> n;
char board[100][100];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
board[i][j] = '.';
if (!nqueen(board, n))
cout << "No state possible!";
return 0;
}
| 2,014
|
C++
|
.cpp
| 66
| 23.515152
| 94
| 0.489669
|
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
|
9,943
|
n_queen_bitset.cpp
|
OpenGenus_cosmos/code/backtracking/src/n_queen/n_queen_bitset.cpp
|
///GIVES TOTAL NUMBER OF POSSIBLE WAYS TO SOLVE N QUEEN PROBLEM USING BITSET
// Part of Cosmos by OpenGenus Foundation
#include <iostream>
#include <bitset>
using namespace std;
bitset<30> column, diag1, diag2;
void solveNQueen(int r, int n, int &ans)
{
if (r == n)
{
ans++;
return;
}
for (int c = 0; c < n; c++)
if (!column[c] && !diag1[r - c + n - 1] && !diag2[r + c])
{
column[c] = diag1[r - c + n - 1] = diag2[r + c] = 1;
solveNQueen(r + 1, n, ans);
//backtrack
column[c] = diag1[r - c + n - 1] = diag2[r + c] = 0;
}
}
int main()
{
int n;
cout << "Enter N: ";
cin >> n;
int ans = 0;
solveNQueen(0, n, ans);
cout << endl << ans << endl;
return 0;
}
| 789
|
C++
|
.cpp
| 32
| 19.375
| 76
| 0.511968
|
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
|
9,944
|
sudoku_solve.cpp
|
OpenGenus_cosmos/code/backtracking/src/sudoku_solve/sudoku_solve.cpp
|
#include <iostream>
using namespace std;
/*
* Part of Cosmos by OpenGenus Foundation
*/
int n = 9;
bool isPossible(int mat[][9], int i, int j, int no)
{
///Row or col should not have no
for (int x = 0; x < n; x++)
if (mat[x][j] == no || mat[i][x] == no)
return false;
/// Subgrid should not have no
int sx = (i / 3) * 3;
int sy = (j / 3) * 3;
for (int x = sx; x < sx + 3; x++)
for (int y = sy; y < sy + 3; y++)
if (mat[x][y] == no)
return false;
return true;
}
void printMat(int mat[][9])
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << mat[i][j] << " ";
if ((j + 1) % 3 == 0)
cout << '\t';
}
if ((i + 1) % 3 == 0)
cout << endl;
cout << endl;
}
}
bool solveSudoku(int mat[][9], int i, int j)
{
///Base Case
if (i == 9)
{
printMat(mat);
return true;
}
///Crossed the last Cell in the row
if (j == 9)
return solveSudoku(mat, i + 1, 0);
///Skip if filled cell
if (mat[i][j] != 0)
return solveSudoku(mat, i, j + 1);
///White Cell
///Try to place every possible no
for (int no = 1; no <= 9; no++)
if (isPossible(mat, i, j, no))
{
///Place the no - assuming solution is possible with this
mat[i][j] = no;
bool isSolve = solveSudoku(mat, i, j + 1);
if (isSolve)
return true;
///loop will place the next no.
}
///Backtracking
mat[i][j] = 0;
return false;
}
int main()
{
int mat[9][9] =
{{5, 3, 0, 0, 7, 0, 0, 0, 0},
{6, 0, 0, 1, 9, 5, 0, 0, 0},
{0, 9, 8, 0, 0, 0, 0, 6, 0},
{8, 0, 0, 0, 6, 0, 0, 0, 3},
{4, 0, 0, 8, 0, 3, 0, 0, 1},
{7, 0, 0, 0, 2, 0, 0, 0, 6},
{0, 6, 0, 0, 0, 0, 2, 8, 0},
{0, 0, 0, 4, 1, 9, 0, 0, 5},
{0, 0, 0, 0, 8, 0, 0, 7, 9}};
printMat(mat);
cout << "Solution " << endl;
solveSudoku(mat, 0, 0);
return 0;
}
| 2,099
|
C++
|
.cpp
| 83
| 18.807229
| 69
| 0.433849
|
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
|
9,947
|
subset_sum.cpp
|
OpenGenus_cosmos/code/backtracking/src/subset_sum/subset_sum.cpp
|
/* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
#include <vector>
using namespace std;
/*
* Generate all possible subset sums
* of array v that sum up to targetSum
*/
vector< vector<int>> generateSubsetSums(int v[], size_t size, int targetSum)
{
vector< vector<int>> solutions;
for (int i = 0; i < (1 << size); ++i)
{
int currentSum = 0;
for (size_t j = 0; j < size; ++j)
if (i & (1 << j))
currentSum += v[j];
if (currentSum == targetSum)
{
vector<int> subsetSum;
for (size_t j = 0; j < size; ++j)
if (i & (1 << j))
subsetSum.push_back(v[j]);
solutions.push_back(subsetSum);
}
}
return solutions;
}
int main()
{
int v[] = {5, 12, -3, 10, -2, 7, -1, 8, 11};
int targetSum = 7;
vector< vector<int>> subsetSums = generateSubsetSums(v, sizeof(v) / sizeof(v[0]), targetSum);
cout << "Subset sums:\n";
for (size_t i = 0; i < subsetSums.size(); ++i)
{
cout << subsetSums[i][0];
for (size_t j = 1; j < subsetSums[i].size(); ++j)
cout << ", " << subsetSums[i][j];
cout << '\n';
}
return 0;
}
| 1,247
|
C++
|
.cpp
| 43
| 22.302326
| 97
| 0.516807
|
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
|
9,951
|
generate_parentheses.cpp
|
OpenGenus_cosmos/code/backtracking/src/generate_parentheses/generate_parentheses.cpp
|
/*
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Approach:
only add open paraenthesis if open < n
only add close parenthesis if close < open
stop- valid parenthesis if close == open == n
TC/SC - O(4^n)
*/
#include<bits/stdc++.h>
using namespace std;
vector<string> res;
void backtrack(int open, int close, string s,int n)
{
if(open == n and close == n)
{
res.push_back(s);
return;
}
if(open < n)
{
backtrack(open+1, close, s+'(', n);
}
if(close < open)
{
backtrack(open, close+1, s +')', n);
}
}
vector<string> generateParenthesis(int n)
{
backtrack(0, 0, "", n);
return res;
}
int main()
{
vector<string> res;
int n = 3;
res = generateParenthesis(n);
for(auto x : res)
cout << x << " ";
return 0;
}
| 985
|
C++
|
.cpp
| 42
| 16.190476
| 56
| 0.48062
|
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
|
9,952
|
partitions_of_number.cpp
|
OpenGenus_cosmos/code/backtracking/src/partitions_of_number/partitions_of_number.cpp
|
/// Part of Cosmos by OpenGenus Foundation
#include <stdio.h>
#include <vector>
void backtrack(int level);
void print_sol(int length);
std::vector<int> solution;
int N, S = 0;
int solsFound = 0;
int main()
{
scanf("%d", &N);
solution.reserve(N + 1);
solution[0] = 1;
backtrack(1);
return 0;
}
void backtrack(int level)
{
if (S == N)
print_sol(level - 1);
else
for (int i = solution[level - 1]; i <= N - S; i++)
{
solution[level] = i;
S += i;
backtrack(level + 1);
S -= i;
}
}
void print_sol(int length)
{
printf("SOLUTION %d\n", ++solsFound);
printf("%d=", N);
for (int i = 1; i <= length - 1; i++)
printf("%d+", solution[i]);
printf("%d\n", solution[length]);
}
| 795
|
C++
|
.cpp
| 37
| 16.918919
| 58
| 0.538259
|
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
|
9,954
|
test_palindrome_check.cpp
|
OpenGenus_cosmos/code/unclassified/test/palindrome/palindrome_check/test_palindrome_check.cpp
|
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <cassert>
#include "../../../src/palindrome/palindrome_check/palindrome_check.cpp"
using namespace std;
using namespace palindrome_check;
// for test
struct MapValueEqual
{
bool operator()(std::pair<int, int> const &a, std::pair<int, int> const &b) const
{
return a.second != b.second;
}
};
template<typename _Type>
struct GreaterEqual
{
bool operator()(typename _Type::iterator a, typename _Type::iterator b) const
{
return (*a).first < (*b).first;
}
};
void
testTrueRecursive()
{
string sz = "";
assert(isPalindromeRecursive(sz.begin(), sz.end()));
string s = "1221";
assert(isPalindromeRecursive(s.begin(), s.end()));
string s2 = "12321";
assert(isPalindromeRecursive(s2.begin(), s2.end()));
vector<int> v = {1, 2, 2, 1};
assert(isPalindromeRecursive(v.begin(), v.end()));
vector<int> v2 = {1, 2, 3, 2, 1};
assert(isPalindromeRecursive(v2.begin(), v2.end()));
int *ivz = nullptr;
assert(isPalindromeRecursive(ivz, ivz));
int *iv = new int(4);
*iv = 1;
*(iv + 1) = 2;
*(iv + 2) = 2;
*(iv + 3) = 1;
assert(isPalindromeRecursive(iv, iv + 4));
int *iv2 = new int(5);
*iv2 = 1;
*(iv2 + 1) = 2;
*(iv2 + 2) = 3;
*(iv2 + 3) = 2;
*(iv2 + 4) = 1;
assert(isPalindromeRecursive(iv2, iv2 + 5));
int ivaz[0];
assert(isPalindromeRecursive(ivaz, ivaz));
int iva[4] = {1, 2, 2, 1};
assert(isPalindromeRecursive(iva, iva + 4));
int iva2[5] = {1, 2, 3, 2, 1};
assert(isPalindromeRecursive(iva2, iva2 + 5));
map<int, int> se;
se[1] = 1; se[2] = 2; se[4] = 2; se[5] = 1;
assert((isPalindromeRecursive<map<int, int>::iterator,
MapValueEqual,
GreaterEqual<map<int, int>>>(se.begin(), se.end())));
se[3] = 3;
assert((isPalindromeRecursive<map<int, int>::iterator,
MapValueEqual,
GreaterEqual<map<int, int>>>(se.begin(), se.end())));
}
void
testFalseRecursive()
{
string s = "1231";
assert(!isPalindromeRecursive(s.begin(), s.end()));
string s2 = "12331";
assert(!isPalindromeRecursive(s2.begin(), s2.end()));
vector<int> v = {1, 2, 3, 1};
assert(!isPalindromeRecursive(v.begin(), v.end()));
vector<int> v2 = {1, 2, 3, 3, 1};
assert(!isPalindromeRecursive(v2.begin(), v2.end()));
int *iv = new int(4);
*iv = 1;
*(iv + 1) = 2;
*(iv + 2) = 3;
*(iv + 3) = 1;
assert(!isPalindromeRecursive(iv, iv + 4));
int *iv2 = new int(5);
*iv2 = 1;
*(iv2 + 1) = 2;
*(iv2 + 2) = 3;
*(iv2 + 3) = 3;
*(iv2 + 4) = 1;
assert(!isPalindromeRecursive(iv2, iv2 + 5));
int iva[4] = {1, 2, 3, 1};
assert(!isPalindromeRecursive(iva, iva + 4));
int iva2[5] = {1, 2, 3, 3, 1};
assert(!isPalindromeRecursive(iva2, iva2 + 5));
map<int, int> se;
se[1] = 1; se[2] = 2; se[4] = 3; se[5] = 1;
assert(!(isPalindromeRecursive<map<int, int>::iterator,
MapValueEqual,
GreaterEqual<map<int, int>>>(se.begin(), se.end())));
se[3] = 3;
assert(!(isPalindromeRecursive<map<int, int>::iterator,
MapValueEqual,
GreaterEqual<map<int, int>>>(se.begin(), se.end())));
}
void
testTrueIterative()
{
string sz = "";
assert(isPalindrome(sz.begin(), sz.end()));
string s = "1221";
assert(isPalindrome(s.begin(), s.end()));
string s2 = "12321";
assert(isPalindrome(s2.begin(), s2.end()));
vector<int> v = {1, 2, 2, 1};
assert(isPalindrome(v.begin(), v.end()));
vector<int> v2 = {1, 2, 3, 2, 1};
assert(isPalindrome(v2.begin(), v2.end()));
int *ivz = nullptr;
assert(isPalindrome(ivz, ivz));
int *iv = new int(4);
*iv = 1;
*(iv + 1) = 2;
*(iv + 2) = 2;
*(iv + 3) = 1;
assert(isPalindrome(iv, iv + 4));
int *iv2 = new int(5);
*iv2 = 1;
*(iv2 + 1) = 2;
*(iv2 + 2) = 3;
*(iv2 + 3) = 2;
*(iv2 + 4) = 1;
assert(isPalindrome(iv2, iv2 + 5));
int ivaz[0];
assert(isPalindrome(ivaz, ivaz));
int iva[4] = {1, 2, 2, 1};
assert(isPalindrome(iva, iva + 4));
int iva2[5] = {1, 2, 3, 2, 1};
assert(isPalindrome(iva2, iva2 + 5));
map<int, int> se;
se[1] = 1; se[2] = 2; se[4] = 2; se[5] = 1;
assert((isPalindrome<map<int, int>::iterator,
MapValueEqual,
GreaterEqual<map<int, int>>>(se.begin(), se.end())));
se[3] = 3;
assert((isPalindrome<map<int, int>::iterator,
MapValueEqual,
GreaterEqual<map<int, int>>>(se.begin(), se.end())));
}
void
testFalseIterative()
{
string s = "1231";
assert(!isPalindrome(s.begin(), s.end()));
string s2 = "12331";
assert(!isPalindrome(s2.begin(), s2.end()));
vector<int> v = {1, 2, 3, 1};
assert(!isPalindrome(v.begin(), v.end()));
vector<int> v2 = {1, 2, 3, 3, 1};
assert(!isPalindrome(v2.begin(), v2.end()));
int *iv = new int(4);
*iv = 1;
*(iv + 1) = 2;
*(iv + 2) = 3;
*(iv + 3) = 1;
assert(!isPalindrome(iv, iv + 4));
int *iv2 = new int(5);
*iv2 = 1;
*(iv2 + 1) = 2;
*(iv2 + 2) = 3;
*(iv2 + 3) = 3;
*(iv2 + 4) = 1;
assert(!isPalindrome(iv2, iv2 + 5));
int iva[4] = {1, 2, 3, 1};
assert(!isPalindrome(iva, iva + 4));
int iva2[5] = {1, 2, 3, 3, 1};
assert(!isPalindrome(iva2, iva2 + 5));
map<int, int> se;
se[1] = 1; se[2] = 2; se[4] = 3; se[5] = 1;
assert(!(isPalindrome<map<int, int>::iterator,
MapValueEqual,
GreaterEqual<map<int, int>>>(se.begin(), se.end())));
se[3] = 3;
assert(!(isPalindrome<map<int, int>::iterator,
MapValueEqual,
GreaterEqual<map<int, int>>>(se.begin(), se.end())));
}
int
main()
{
testTrueRecursive();
testFalseRecursive();
testTrueIterative();
testFalseIterative();
return 0;
}
// */
| 6,229
|
C++
|
.cpp
| 198
| 24.914141
| 88
| 0.529745
|
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
|
9,955
|
test_spiral_print.cpp
|
OpenGenus_cosmos/code/unclassified/test/spiral_printing/test_spiral_print.cpp
|
#include "../../src/spiral_print/spiral_print.cpp"
#include <cassert>
int main()
{
using namespace std;
vector<vector<int>> vec;
// empty test
assert("" == spiralPrint(vec, 0, 0));
/* row test (even col)
* 1 2 3 4 5 6
* 7 8 9 10 11 12
* 13 14 15 16 17 18
* 19 20 21 22 23 24
*/
vec.push_back({1, 2, 3, 4, 5, 6});
assert(spiralPrint(vec, vec.size(), vec[0].size()) == "1 2 3 4 5 6");
vec.push_back({7, 8, 9, 10, 11, 12});
assert(spiralPrint(vec, vec.size(), vec[0].size()) == "1 2 3 4 5 6 12 11 10 9 8 7");
vec.push_back({13, 14, 15, 16, 17, 18});
assert(spiralPrint(vec, vec.size(),
vec[0].size()) == "1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11");
vec.push_back({19, 20, 21, 22, 23, 24});
assert(spiralPrint(vec, vec.size(),
vec[0].size()) ==
"1 2 3 4 5 6 12 18 24 23 22 21 20 19 13 7 8 9 10 11 17 16 15 14");
/* row test (odd col)
* 1 2 3
* 4 5 6
* 7 8 9
*/
vec.clear();
vec.push_back({1, 2, 3});
assert(spiralPrint(vec, vec.size(), vec[0].size()) == "1 2 3");
vec.push_back({4, 5, 6});
assert(spiralPrint(vec, vec.size(), vec[0].size()) == "1 2 3 6 5 4");
vec.push_back({7, 8, 9});
assert(spiralPrint(vec, vec.size(), vec[0].size()) == "1 2 3 6 9 8 7 4 5");
/* col test
* 1
* 2
* 3
*/
vec.clear();
vec.push_back({1});
assert(spiralPrint(vec, vec.size(), vec[0].size()) == "1");
vec.push_back({2});
assert(spiralPrint(vec, vec.size(), vec[0].size()) == "1 2");
vec.push_back({3});
assert(spiralPrint(vec, vec.size(), vec[0].size()) == "1 2 3");
return 0;
}
| 1,721
|
C++
|
.cpp
| 51
| 27.882353
| 89
| 0.512019
|
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
|
9,957
|
majority_element_randomized.cpp
|
OpenGenus_cosmos/code/unclassified/src/majority_element/majority_element_randomized.cpp
|
#include <iostream>
#include <vector>
using namespace std;
int n;
vector<int> v;
// Randomized algorithm with expected runtime: O(n), and Space: O(1)
int majorityElement(vector<int>& nums) {
int pos = 0, n = nums.size(), freq;
while(1) {
freq = 0;
for(int x : nums)if(x == nums[pos])++freq;
if(freq > n / 2)
return nums[pos];
pos = rand() % n;
}
}
int main()
{
cin >> n;
for (int i = 0; i < n; i++){
int tmp;
cin >> tmp;
v.push_back(tmp);
}
cout << "The majority element is: " << majorityElement(v);
return 0;
}
| 623
|
C++
|
.cpp
| 27
| 17.962963
| 68
| 0.536256
|
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
|
9,958
|
majority_element.cpp
|
OpenGenus_cosmos/code/unclassified/src/majority_element/majority_element.cpp
|
#include <iostream>
#include <vector>
using namespace std;
int n;
vector<int> v;
int main()
{
cin >> n;
for (int i = 0; i < n; i++)
{
int tmp;
cin >> tmp;
v.push_back(tmp);
}
int m, i = 0;
for (int k = 0; k < n; k++)
{
int x = v[k];
if (!i)
{
m = x;
i = 1;
}
else if (m == x)
i++;
else
i--;
}
cout << "The majority element is: " << m;
return 0;
}
| 515
|
C++
|
.cpp
| 31
| 10.193548
| 45
| 0.380252
|
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
|
9,960
|
maximum_subarray_sum.cpp
|
OpenGenus_cosmos/code/unclassified/src/maximum_subarray_sum/maximum_subarray_sum.cpp
|
// Part of Cosmos by OpenGenus Foundation
// C++ implementation of simple algorithm to find
// Maximum Subarray Sum in a given array
// this implementation is done using Kadane's Algorithm which has a time complexity of O(n)
#include <iostream>
#include <vector>
#include <climits>
int maxSubarraySum(const std::vector<int>& arr)
{
int maxSumSoFar = INT_MIN;
int currMax = 0;
for (int element : arr)
{
currMax += element;
if (maxSumSoFar < currMax)
maxSumSoFar = currMax;
if (currMax < 0) // if the current maximum sum becomes less than 0 then we make it 0 to represent an empty subarray
currMax = 0;
}
return maxSumSoFar;
}
int main()
{
int n;
std::cin >> n;
std::vector<int> v(n);
for (int i = 0; i < n; ++i)
{
int x;
std::cin >> x;
v[i] = x;
}
int answer = maxSubarraySum(v);
std::cout << "Maximum subarray sum is " << answer << '\n';
return 0;
}
| 987
|
C++
|
.cpp
| 36
| 22.611111
| 123
| 0.61945
|
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
|
9,961
|
biggest_of_n_numbers2.cpp
|
OpenGenus_cosmos/code/unclassified/src/biggest_of_n_numbers/biggest_of_n_numbers2.cpp
|
#include <iostream>
using namespace std;
int main()
{
int n, max, tmp;
cout << "Enter numbers of elements : ";
cin >> n;
cout << "Enter numbers\n";
cin >> tmp;
max = tmp;
for (int i = 0; i < n - 1; i++)
{
cin >> tmp;
if (max < tmp)
max = tmp;
}
cout << "Maximum is " << max << "\n";
return 0;
}
| 368
|
C++
|
.cpp
| 19
| 14.526316
| 43
| 0.471264
|
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
|
9,962
|
biggest_of_n_numbers.cpp
|
OpenGenus_cosmos/code/unclassified/src/biggest_of_n_numbers/biggest_of_n_numbers.cpp
|
// Part of cosmos from opengenus foundation
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> arr;
std::cout << "Keep entering numbers (EOF to stop): ";
for (int num; std::cin >> num;)
arr.push_back(num);
sort(arr.begin(), arr.end());
std::cout << "biggest number : " << arr.back();
}
| 356
|
C++
|
.cpp
| 13
| 23.923077
| 57
| 0.628319
|
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
|
9,963
|
medianOfTwoSortedArrayOfDifferentLength.cpp
|
OpenGenus_cosmos/code/unclassified/src/median_two_sortedArrayOfDifferentLength/medianOfTwoSortedArrayOfDifferentLength.cpp
|
#include <bits/stdc++.h>
using namespace std;
double findMedian(int arr1[], int n1, int arr2[], int n2)
{
int lo = 0, hi = n1;
while (lo <= hi)
{
int cut1 = lo + (hi - lo) / 2;
int cut2 = (n1 + n2) / 2;
double l1 = cut1 == 0 ? INT_MIN : arr1[cut1 - 1];
double l2 = cut2 == 0 ? INT_MIN : arr2[cut2 - 1];
double r1 = cut1 == 0 ? INT_MAX : arr1[cut1];
double r2 = cut2 == 0 ? INT_MAX : arr2[cut2];
if (l1 > r2)
{
hi = cut1 - 1;
}
else if (l2 > r1)
{
lo = cut1 + 1;
}
else
{
if ((n1 + n2) % 2 == 0)
{
return ((max(l1, l2)) + (min(r1, r2))) / 2;
}
else
{
return min(r1, r2);
}
}
return -1;
}
}
int main()
{
int n1, n2;
cin >> n1 >> n2;
int arr1[n1], arr2[n2];
for (int i = 0; i < n1; i++)
{
cin >> arr1[i];
}
for (int i = 0; i < n2; i++)
{
cin >> arr2[i];
}
if (n2 > n1)
cout << findMedian(arr1, n1, arr2, n2);
else
cout << findMedian(arr2, n2, arr1, n1);
}
| 1,205
|
C++
|
.cpp
| 53
| 15.09434
| 59
| 0.394599
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
9,967
|
palindrome_check.cpp
|
OpenGenus_cosmos/code/unclassified/src/palindrome/palindrome_check/palindrome_check.cpp
|
#include <iterator>
#include <type_traits>
#include <functional>
namespace palindrome_check {
template<typename _InputIter,
typename _ValueNotEqualTo
= std::not_equal_to<typename std::iterator_traits<_InputIter>::value_type>,
typename _IterLess = std::less<_InputIter>>
bool
isPalindromeRecursive(_InputIter begin, _InputIter end)
{
if (begin != end)
{
--end;
if (_IterLess()(begin, end))
{
if (_ValueNotEqualTo()(*begin, *end))
return false;
return isPalindromeRecursive<_InputIter, _ValueNotEqualTo, _IterLess>(++begin, end);
}
}
return true;
}
template<typename _InputIter,
typename _ValueNotEqualTo
= std::not_equal_to<typename std::iterator_traits<_InputIter>::value_type>,
typename _IterLess = std::less<_InputIter>>
bool
isPalindromeIterative(_InputIter begin, _InputIter end)
{
if (begin != end)
{
--end;
while (_IterLess()(begin, end))
if (_ValueNotEqualTo()(*begin++, *end--))
return false;
}
return true;
}
template<typename _InputIter,
typename _ValueNotEqualTo
= std::not_equal_to<typename std::iterator_traits<_InputIter>::value_type>,
typename _IterLess = std::less<_InputIter>>
inline bool
isPalindrome(_InputIter begin, _InputIter end)
{
// default is iterative
return isPalindromeIterative<_InputIter, _ValueNotEqualTo, _IterLess>(begin, end);
}
} // palindrome_check
| 1,541
|
C++
|
.cpp
| 50
| 24.72
| 96
| 0.643098
|
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
|
9,968
|
average.cpp
|
OpenGenus_cosmos/code/unclassified/src/average/average.cpp
|
/// Part of Cosmos by OpenGenus Foundation
/// Find of average of numbers in an array
/// Contributed by: Pranav Gupta (foobar98)
/// Modified by: Arnav Borborah (arnavb)
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
vector<int> elements;
cout << "Enter the numbers you want to find the average of: ";
int sum = 0;
string input;
getline(cin, input);
istringstream is(input);
for (int element; is >> element;) // Read numbers until the user enters a newline
{
elements.push_back(element);
sum += element;
}
double avg = static_cast<double>(sum) / elements.size();
cout << "Average of numbers: " << avg << endl;
}
| 742
|
C++
|
.cpp
| 25
| 26.16
| 89
| 0.668067
|
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
|
9,969
|
arraytoset_iterator.cpp
|
OpenGenus_cosmos/code/unclassified/src/array_to_set/arraytoset_iterator.cpp
|
#include <iostream>
#include <set>
// This program converts an array to a set in C++ using iterators
// See the corresponding article here: https://iq.opengenus.org/convert-array-to-set-cpp/
int main()
{
int a[] = {4, 11, 5, 3, 1, 6};
std::set<int> s(std::begin(a), std::end(a));
for (int i : s) {
std::cout << i << " ";
}
std::cout << "\n";
return 0;
}
| 388
|
C++
|
.cpp
| 14
| 24.285714
| 89
| 0.586022
|
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
|
9,973
|
paint_fill.cpp
|
OpenGenus_cosmos/code/unclassified/src/paint_fill/paint_fill.cpp
|
#include <iostream>
// Part of Cosmos by OpenGenus Foundation
using namespace std;
void print_matrix(char matrix[][100], int n, int m)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
cout << matrix[i][j];
cout << endl;
}
}
void paint_fill(int i, int j, char dot, char colour, char matrix[][100], int n, int m)
{
if (matrix[i][j] != dot || i<0 || j<0 || i>n - 1 || j>m - 1)
return;
matrix[i][j] = colour;
paint_fill(i + 1, j, dot, colour, matrix, n, m);
paint_fill(i - 1, j, dot, colour, matrix, n, m);
paint_fill(i, j + 1, dot, colour, matrix, n, m);
paint_fill(i, j - 1, dot, colour, matrix, n, m);
}
int main()
{
int n, m;
char matrix[100][100];
cout << "Enter N and M: ";
cin >> n >> m;
//enter matrix i.e. the image
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> matrix[i][j];
print_matrix(matrix, n, m);
paint_fill(8, 13, '.', 'R', matrix, n, m);
print_matrix(matrix, n, m);
return 0;
}
| 1,063
|
C++
|
.cpp
| 37
| 23.864865
| 86
| 0.520197
|
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
|
9,975
|
autobiographical_numbers.cpp
|
OpenGenus_cosmos/code/unclassified/src/autobiographical_numbers/autobiographical_numbers.cpp
|
// Part of OpenGenus Cosmos
#include <iostream>
#include <string>
#include <unordered_map>
int main()
{
std::string s2 = "22535320"; // Input string
// string s2 = "72100001000"; // Uncomment this for a "TRUE" answer example.
std::unordered_map<int, int> indexCounter;
std::unordered_map<int, int> eleCounter;
int index = 0;
for (char c : s2)
{
indexCounter[index] = (c - '0'); // c - '0' converts the char to a proper integer.
index++;
}
for (char c : s2)
eleCounter[(c - '0')]++; // c - '0' converts the char to a proper integer.
for (auto &par : indexCounter)
{
if (eleCounter[par.first] != par.second)
{
std::cout << "false" << std::endl;
return 0;
// return false;
}
}
// return true;
std::cout << "true" << std::endl;
}
| 902
|
C++
|
.cpp
| 30
| 23.833333
| 94
| 0.545984
|
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
|
9,976
|
segregate_positive_negative.cpp
|
OpenGenus_cosmos/code/unclassified/src/segregate_positive_negative/segregate_positive_negative.cpp
|
// Segregate positive and negative numbers in an array
// Here, we try to place all negative numbers to the left
// and all positive elements to the right in O(n) time.
// We can achieve this using Sorting also. But that takes O(nlogn) time.
#include <iostream>
#include <cstdlib>
// Similar to the partition function in Quicksort
// with pivot as 0
void segregate_pos_neg(int a[], int n) {
int left = 0;
int right = n - 1;
while (1) {
while (a[left] < 0 && left < right)
left++;
while (a[right] > 0 && left < right)
right--;
if (left < right) {
int temp = a[left];
a[left] = a[right];
a[right] = temp;
} else
break;
}
}
int main() {
int n;
std::cout << "Enter the size of the array : ";
std::cin >> n;
// allocating heap memory for array
int *a = new int[n];
std::cout << "Enter the values of the array : \n";
for (int i = 0; i < n; i++) {
std::cin >> a[i];
}
segregate_pos_neg(a, n);
std::cout << "Array after partition function\n";
for (int i = 0; i < n; i++) {
std::cout << a[i] << "\t";
}
}
/*
Enter the size of the array : 8
Enter the values of the array :
-1 4 5 9 -12 -15 7 21
Array after partition function
-1 -15 -12 9 5 4 7 21
*/
| 1,333
|
C++
|
.cpp
| 47
| 23.361702
| 72
| 0.563183
|
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
|
9,977
|
optimized_fibonacci.cpp
|
OpenGenus_cosmos/code/unclassified/src/optimized_fibonacci/optimized_fibonacci.cpp
|
/* Fibonacci Series implemented using Memoization */
#include <iostream>
long long fibonacci (int n)
{
static long long fib[100] = {}; // initialises the array with all elements as 0
fib[1] = 0;
fib[2] = 1;
if (n == 1 || n == 2)
return fib[n];
else if (fib[n] != 0)
return fib[n];
else
{
fib[n] = fibonacci (n - 1) + fibonacci (n - 2);
return fib[n];
}
}
int main ()
{
int n;
std::cout << "Enter number of terms: ";
std::cin >> n;
for (int i = 1; i <= n; i++)
std::cout << fibonacci (i) << std::endl;
}
| 594
|
C++
|
.cpp
| 25
| 19.12
| 83
| 0.530035
|
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
|
9,981
|
lapindrome_checker.cpp
|
OpenGenus_cosmos/code/unclassified/src/lapindrom_checker/lapindrome_checker.cpp
|
// part of cosmos by opengenus foundation
#include <iostream>
#include <algorithm> // used for sort()
using namespace std;
bool isLapindrome(string str)
{
int mid = str.length() / 2;
int delim = (str.length() % 2) == 0 ? mid : mid + 1;
string first_half = str.substr(0, mid);
string second_half = str.substr(delim);
sort(first_half.begin(), first_half.end());
sort(second_half.begin(), second_half.end());
return first_half == second_half;
}
int main()
{
string test_case;
cout << "Input the string to be checked" << endl;
cin >> test_case;
if (isLapindrome(test_case))
cout << test_case << "is a lapindrome.\n";
else
cout << test_case << "is not a lapindrome.\n";
return 0;
}
| 755
|
C++
|
.cpp
| 25
| 26.16
| 56
| 0.632964
|
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
|
9,982
|
minsubarraysizewithdegree.cpp
|
OpenGenus_cosmos/code/unclassified/src/minimum_subarray_size_with_degree/minsubarraysizewithdegree.cpp
|
#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
/* Part of Cosmos by OpenGenus Foundation */
using namespace std;
int minSubArraySizeWithDegree(const vector<int> nums)
{
unordered_map <int, int> m;
priority_queue<int> pq;
int best_degree = 1,
curr_best_degree = nums[0],
i,
j,
s = nums.size();
for (int x = 0; x < s; x++)
{
m[nums[x]]++;
if (m[nums[x]] > best_degree)
best_degree = m[nums[x]];
}
m.clear();
i = 0; j = 0;
int n;
m[nums[0]]++;
while (i < s && j < s)
{
n = nums[j];
if (m[n] >= m[curr_best_degree])
curr_best_degree = n;
if (m[curr_best_degree] < best_degree)
{
j++;
m[nums[j]]++;
}
else
{
pq.push(-(j - i + 1));
m[nums[i]]--;
i++;
}
}
return -pq.top();
}
#define pb push_back
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
srand(time(NULL));
vector<int> v;
for (int i = 0; i < 20; i++)
{
v.pb(rand() % 10);
cout << v[i] << " ";
}
cout << endl;
cout << minSubArraySizeWithDegree(v) << endl;
return 0;
}
| 1,277
|
C++
|
.cpp
| 60
| 14.866667
| 53
| 0.4725
|
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
|
9,984
|
line_determinant_method.cpp
|
OpenGenus_cosmos/code/computational_geometry/src/2d_line_intersection/line_determinant_method.cpp
|
#include <iostream>
class TwoDimensionalLineIntersection
{
public:
bool determinantMethod();
void setCoordinatesOfLines(double x1_, double y1_, double x2_, double y2_, double x3_, double y3_, double x4_, double y4_);
void printIntersectionPoints();
private:
double x1_, y1_, x2_, y2_, x3_, y3_, x4_, y4_, xin_, yin_;
};
void TwoDimensionalLineIntersection :: setCoordinatesOfLines(double x1_, double y1_, double x2_, double y2_, double x3_,
double y3_, double x4_, double y4_)
{
this->x1_ = x1_;
this->x2_ = x2_;
this->x3_ = x3_;
this->x4_ = x4_;
this->y1_ = y1_;
this->y2_ = y2_;
this->y3_ = y3_;
this->y4_ = y4_;
}
bool TwoDimensionalLineIntersection :: determinantMethod()
{
double slopeOfLine1;
double slopeOfLine2;
if(x2_ - x1_ != 0)
slopeOfLine1 = (y2_ - y1_)/(x2_ - x1_);
else
slopeOfLine1 = 0;
if(x4_ - x3_ != 0)
slopeOfLine2 = (y4_ - y3_)/(x4_ - x3_);
else
slopeOfLine1 = 0;
if(slopeOfLine1 != slopeOfLine2)
{
xin_ = ((x1_*y2_ - y1_*x2_)*(x3_ - x4_) - (x3_*y4_ - y3_*x4_)*(x1_ - x2_) )/( ((x1_ - x2_)*(y3_ - y4_))- ((y1_ - y2_)*(x3_ - x4_)));
yin_ = ((x1_*y2_ - y1_*x2_)*(y3_ - y4_) - (x3_*y4_ - y3_*x4_)*(y1_ - y2_) )/( ((x1_ - x2_)*(y3_ - y4_))- ((y1_ - y2_)*(x3_ - x4_)));
return true;
} else
return false;
}
void TwoDimensionalLineIntersection ::printIntersectionPoints()
{
if(determinantMethod())
{
std::cout << "\nIntersection Coordinate : ";
std::cout << "\nX-coordinate : " << xin_;
std::cout << "\nY-coordinate : " << yin_;
} else
std::cout << "\nLines are Parallel.";
}
int main()
{
TwoDimensionalLineIntersection t;
double x1, y1, x2, y2, x3, y3, x4, y4;
std::cout << "\nEnter the Coordinates for Line-1 : ";
std::cout << "\nLine-1 | x1-coordinate : ";
std::cin >> x1;
std::cout << "\nLine-1 | y1-coordinate : ";
std::cin >> y1;
std::cout << "\nLine-1 | x2-coordinate : ";
std::cin >> x2;
std::cout << "\nLine-1 | y2-coordinate : ";
std::cin >> y2;
std::cout << "\nEnter the Coordinates for Line-2 : ";
std::cout << "\nLine-2 | x3-coordinate : ";
std::cin >> x3;
std::cout << "\nLine-2 | y3-coordinate : ";
std::cin >> y3;
std::cout << "\nLine-2 | x4-coordinate : ";
std::cin >> x4;
std::cout << "\nLine-2 | y4-coordinate : ";
std::cin >> y4;
t.setCoordinatesOfLines(x1, y1, x2, y2, x3, y3, x4, y4);
t.printIntersectionPoints();
}
| 2,598
|
C++
|
.cpp
| 77
| 28.233766
| 140
| 0.539563
|
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
|
9,985
|
line_elemination_method.cpp
|
OpenGenus_cosmos/code/computational_geometry/src/2d_line_intersection/line_elemination_method.cpp
|
#include <iostream>
#include <vector>
class EliminationMethd2DLineIntersection
{
public:
void acceptTheCoordinates(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4);
void intersection1(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4);
private:
std::vector<double> a, b, c, d; //four coordinates constituting 2 Dimensional Lines.
};
void EliminationMethd2DLineIntersection::acceptTheCoordinates(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4)
{
a.push_back(x1);
a.push_back(y1);
b.push_back(x1);
b.push_back(y1);
c.push_back(x1);
c.push_back(y1);
d.push_back(x1);
d.push_back(y1);
intersection1(a[0], a[1], b[0], b[1], c[0], c[1], d[0], d[1]);
}
void EliminationMethd2DLineIntersection::intersection1(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4)
{
double x12 = x1 - x2;
double x34 = x3 - x4;
double y12 = y1 - y2;
double y34 = y3 - y4;
double c = x12 * y34 - y12 * x34;
double a = x1 * y2 - y1 * x2;
double b = x3 * y4 - y3 * x4;
if(c != 0)
{
double x = (a * x34 - b * x12) / c;
double y = (a * y34 - b * y12) / c;
std::cout << "Intersection point coordinates : \n";
std::cout << "Xin : " << x << std::endl;
std::cout << "Yin : " << y << std::endl;
}
else
{
std::cout << "Lines are parallel";
}
}
int main()
{
EliminationMethd2DLineIntersection obj;
int value;
double x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, x6, y6, x7, y7, x8, y8;
std::cout << "\nEnter the Coordinates for Line-1";
std::cout << "\nEnter the X-coordinate for Point-1: ";
std::cin >> x1;
std::cout << "\nEnter the Y-coordinate for Point-1: ";
std::cin >> y1;
std::cout << "\nEnter the X-coordinate for Point-2: ";
std::cin >> x2;
std::cout << "\nEnter the Y-coordinate for Point-2: ";
std::cin >> y2;
std::cout << "\nEnter the Coordinates for Line-2";
std::cout << "\nEnter the X-coordinate for Point-1: ";
std::cin >> x3;
std::cout << "\nEnter the Y-coordinate for Point-1: ";
std::cin >> y3;
std::cout << "\nEnter the X-coordinate for Point-2: ";
std::cin >> x4;
std::cout << "\nEnter the Y-coordinate for Point-2: ";
std::cin >> y4;
obj.acceptTheCoordinates(x1,y1, x2, y2, x3, y3, x4, y4);
return 0;
}
| 2,475
|
C++
|
.cpp
| 70
| 30.9
| 149
| 0.607321
|
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
|
9,986
|
2d_line_intersection.cpp
|
OpenGenus_cosmos/code/computational_geometry/src/2d_line_intersection/2d_line_intersection.cpp
|
// computational geometry | 2D line intersecton | C++
// main.cpp
// forfun
//
// Created by Ivan Reinaldo Liyanto on 10/5/17.
// Copyright © 2017 Ivan Reinaldo Liyanto. All rights reserved.
// Path of Cosmos by OpenGenus Foundation
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
struct vec2
{
double x;
double y;
vec2(double x, double y) : x(x), y(y)
{
}
};
/* return point of intersection, in parent's coordinate space of its parameters */
vec2 intersection(double x1, double y1, double x2, double y2, double x3, double y3, double x4,
double y4)
{
double x12 = x1 - x2;
double x34 = x3 - x4;
double y12 = y1 - y2;
double y34 = y3 - y4;
double c = x12 * y34 - y12 * x34;
double a = x1 * y2 - y1 * x2;
double b = x3 * y4 - y3 * x4;
double x = (a * x34 - b * x12) / c;
double y = (a * y34 - b * y12) / c;
return vec2(x, y);
}
/* line segments defined by 2 points a-b, and c-d */
vec2 intersection(vec2 a, vec2 b, vec2 c, vec2 d)
{
return intersection(a.x, a.y, b.x, b.y, c.x, c.y, d.x, d.y);
}
int main()
{
//example set 1
vec2 a(10, 3);
vec2 b(20, 10);
vec2 c(10, 10);
vec2 d(20, 3);
//example set 2
// vec2 a(10, 3);
// vec2 b(20, 3);
// vec2 c(10, 5);
// vec2 d(20, 5);
vec2 intersectionpoint = intersection(a, b, c, d);
if (intersectionpoint.x >= min(a.x, b.x) && intersectionpoint.x <= max(a.x, b.x) &&
intersectionpoint.y >= min(a.y, b.y) && intersectionpoint.y <= max(a.y, b.y))
cout << "intersection: " << intersectionpoint.x << " " << intersectionpoint.y;
else
cout << "no intersection";
return 0;
}
| 1,713
|
C++
|
.cpp
| 59
| 25.372881
| 94
| 0.597687
|
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
|
9,987
|
distance_between_points.cpp
|
OpenGenus_cosmos/code/computational_geometry/src/distance_between_points/distance_between_points.cpp
|
#include <iostream>
#include <cmath>
typedef std::pair<double, double> point;
#define x first
#define y second
double calcDistance (point a, point b)
{
return sqrt(pow(a.x - b.x, 2) + pow(a.y - b.y, 2));
}
int main ()
{
point a, b, c;
std::cin >> a.x >> a.y >> b.x >> b.y;
std::cout << calcDistance(a, b);
}
| 328
|
C++
|
.cpp
| 15
| 19.533333
| 55
| 0.61165
|
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
|
9,989
|
2d_separating_axis_test.cpp
|
OpenGenus_cosmos/code/computational_geometry/src/2d_separating_axis_test/2d_separating_axis_test.cpp
|
// computational geometry | Two convex polygon intersection 2d seperating axis test | C++
//Ivan Reinaldo Liyanto
// open genus - cosmos
#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
struct vec2
{
double x, y;
vec2(double x, double y) : x(x), y(y)
{
}
friend vec2 operator+(vec2 lhs, const vec2& vec)
{
return vec2(lhs.x + vec.x, lhs.y + vec.y);
}
friend vec2 operator-(vec2 lhs, const vec2& vec)
{
return vec2(lhs.x - vec.x, lhs.y - vec.y);
}
};
double dot(vec2 a, vec2 b)
{
return a.x * b.x + a.y * b.y;
}
vector<vec2> inputPolygon1;
vector<vec2> inputPolygon2;
bool sat()
{
//project every points onto every axis
for (size_t i = 1; i < inputPolygon1.size(); i++)
{
vec2 axis = inputPolygon1[i] - inputPolygon1[i - 1];
double leftMostPolygonA = __FLT_MAX__;
double rightMostPolygonA = __FLT_MIN__;
for (size_t j = 0; j < inputPolygon1.size(); j++)
{
double d = dot(inputPolygon1[j], axis);
if (d > rightMostPolygonA)
rightMostPolygonA = d;
if (d < leftMostPolygonA)
leftMostPolygonA = d;
}
double leftMostPolygonB = __FLT_MAX__;
double rightMostPolygonB = __FLT_MIN__;
for (size_t j = 0; j < inputPolygon2.size(); j++)
{
double d = dot(inputPolygon2[j], axis);
if (d > rightMostPolygonB)
rightMostPolygonB = d;
if (d < leftMostPolygonB)
leftMostPolygonB = d;
}
if ((leftMostPolygonB < rightMostPolygonA && rightMostPolygonB > rightMostPolygonA) ||
(leftMostPolygonA < rightMostPolygonB && rightMostPolygonA > rightMostPolygonB) )
return true;
}
//false = no intersection
return false;
}
int main()
{
//given 2 convex polygons defined by set of points, determine if the two polygon intersects using Separating Axis Test
//example set 1
inputPolygon1.push_back(vec2(5, 5));
inputPolygon1.push_back(vec2(7, 10));
inputPolygon1.push_back(vec2(15, 10));
inputPolygon1.push_back(vec2(4, 4));
inputPolygon2.push_back(vec2(6, 6));
inputPolygon2.push_back(vec2(0, 0));
inputPolygon2.push_back(vec2(7, 0));
cout << "The two polygons " << (sat() ? "" : "do not ") << "intersect\n";
return 0;
}
| 2,412
|
C++
|
.cpp
| 75
| 25.866667
| 122
| 0.607573
|
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
|
9,990
|
sutherland_hodgeman_clipping.cpp
|
OpenGenus_cosmos/code/computational_geometry/src/sutherland_hodgeman_clipping/sutherland_hodgeman_clipping.cpp
|
//
// main.cpp
// forfun
//
// Created by Ivan Reinaldo Liyanto on 10/5/17.
// Copyright © 2017 Ivan Reinaldo Liyanto. All rights reserved.
// Path of Cosmos by OpenGenus Foundation
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
struct coor2d
{
float x, y;
coor2d(float a, float b) : x(a), y(b)
{
}
coor2d()
{
}
};
struct edge
{
float x1, y1, x2, y2;
float xnormal, ynormal;
edge(float x1, float y1, float x2, float y2) : x1(x1), y1(y1), x2(x2), y2(y2)
{
float dx = x2 - x1;
float dy = y2 - y1;
xnormal = -dy;
ynormal = dx;
}
};
struct polygon
{
vector<coor2d> points;
polygon(const vector<coor2d> &p)
{
for (size_t i = 0; i < p.size(); i++)
points.push_back(p[i]);
}
};
bool inside(coor2d input, edge clipedge);
coor2d ComputeIntersection(coor2d a, coor2d b, edge c);
/*
* 100
*
* y
*
* 0 x 100
*/
int main()
{
//since there's normal computing involved, polygon points must be defined in clockwise manner
vector<coor2d> clipperCoords;
//example set 1
clipperCoords.push_back(coor2d(2, 5));
clipperCoords.push_back(coor2d(5, 5));
clipperCoords.push_back(coor2d(5, 1));
clipperCoords.push_back(coor2d(2, 1));
// example set 2
// clipperCoords.push_back(coor2d(5,10));
// clipperCoords.push_back(coor2d(10,1));
// clipperCoords.push_back(coor2d(0,1));
vector<coor2d> clippedCoords;
// example set 1
clippedCoords.push_back(coor2d(2, 7));
clippedCoords.push_back(coor2d(3, 7));
clippedCoords.push_back(coor2d(3, 3));
clippedCoords.push_back(coor2d(2, 3));
// example set 2
// clippedCoords.push_back(coor2d(5,5));
// clippedCoords.push_back(coor2d(15,7));
// clippedCoords.push_back(coor2d(13,1));
polygon clipper = polygon(clipperCoords);
polygon clipped = polygon(clippedCoords);
vector<coor2d> outputCoords;
vector<coor2d> inputList;
outputCoords = clipped.points;
for (size_t i = 0; i < clipper.points.size() - 1; i++)
{
inputList = outputCoords;
outputCoords.clear();
coor2d a = clipper.points[i];
coor2d b = clipper.points[i + 1];
edge clipedge = edge(a.x, a.y, b.x, b.y);
coor2d s = inputList[inputList.size() - 1];
for (size_t j = 0; j < inputList.size(); j++)
{
if (inside(inputList[j], clipedge))
{
if (!inside(s, clipedge))
outputCoords.push_back(ComputeIntersection(inputList[j], s, clipedge));
outputCoords.push_back(inputList[j]);
}
else if (inside(s, clipedge))
outputCoords.push_back(ComputeIntersection(inputList[j], s, clipedge));
s = inputList[j];
}
}
cout << "Clipped area: " << endl;
for (size_t i = 0; i < outputCoords.size(); i++)
cout << "X: " << outputCoords[i].x << " Y: " << outputCoords[i].y << endl;
return 0;
}
bool inside(coor2d input, edge clipedge)
{
coor2d a = coor2d(input.x - clipedge.x1, input.y - clipedge.y1);
float dot = a.x * clipedge.xnormal + a.y * clipedge.ynormal;
if (dot <= 0)
return true;
return false;
}
coor2d ComputeIntersection(coor2d ca, coor2d cb, edge edg)
{
float x1 = ca.x;
float x2 = cb.x;
float x3 = edg.x1;
float x4 = edg.x2;
float y1 = ca.y;
float y2 = cb.y;
float y3 = edg.y1;
float y4 = edg.y2;
float x12 = x1 - x2;
float x34 = x3 - x4;
float y12 = y1 - y2;
float y34 = y3 - y4;
float c = x12 * y34 - y12 * x34;
float a = x1 * y2 - y1 * x2;
float b = x3 * y4 - y3 * x4;
float x = (a * x34 - b * x12) / c;
float y = (a * y34 - b * y12) / c;
return coor2d(x, y);
}
| 3,839
|
C++
|
.cpp
| 134
| 23.552239
| 97
| 0.595432
|
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
|
9,991
|
halfplane_intersection.cpp
|
OpenGenus_cosmos/code/computational_geometry/src/halfplane_intersection/halfplane_intersection.cpp
|
#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
const double INF = 1e9;
const double EPS = 1e-8;
class Point {
public:
double x, y;
Point()
{
}
Point(double x, double y) : x(x), y(y)
{
}
bool operator==(const Point &other) const
{
return abs(x - other.x) < EPS && abs(y - other.y) < EPS;
}
Point operator-(const Point &a) const
{
return Point(x - a.x, y - a.y);
}
double operator^(const Point &a) const
{
return x * a.y - a.x * y;
}
void scan()
{
cin >> x >> y;
}
void print() const
{
cout << x << " " << y << "\n";
}
};
class Line {
public:
double a, b, c;
Line()
{
}
Line(double a, double b, double c) : a(a), b(b), c(c)
{
}
Line(const Point &A, const Point &B) : a(A.y - B.y), b(B.x - A.x),
c(A.x * (B.y - A.y) + A.y * (A.x - B.x))
{
}
bool operator==(const Line &other) const
{
return a == other.a && b == other.b && c == other.c;
}
bool contains_point(const Point &A) const
{
return a * A.x + b * A.y + c == 0;
}
bool intersects(const Line &l) const
{
return !(a * l.b == b * l.a);
}
Point intersect(const Line &l) const
{
return Point(-(c * l.b - l.c * b) / (a * l.b - l.a * b),
-(a * l.c - l.a * c) / (a * l.b - l.a * b));
}
};
class Segment {
private:
Point A, B;
public:
Segment()
{
}
Segment(Point A, Point B) : A(A), B(B)
{
}
bool intersects(const Line &l) const
{
return l.intersects(Line(A, B)) &&
l.intersect(Line(A, B)).x <= max(A.x, B.x) + EPS &&
l.intersect(Line(A, B)).x >= min(A.x, B.x) - EPS &&
l.intersect(Line(A, B)).y <= max(A.y, B.y) + EPS &&
l.intersect(Line(A, B)).y >= min(A.y, B.y) - EPS;
}
double length2() const
{
return (A - B).x * (A - B).x + (A - B).y * (A - B).y;
}
double length() const
{
return sqrt(length2());
}
};
class HalfPlane {
private:
double a, b, c;
public:
HalfPlane()
{
}
HalfPlane(Line l, Point A)
{
if (l.a * A.x + l.b * A.y + l.c < 0)
{
a = -l.a;
b = -l.b;
c = -l.c;
}
else
{
a = l.a;
b = l.b;
c = l.c;
}
}
bool contains_point(const Point &p) const
{
return a * p.x + b * p.y + c >= 0;
}
Line line() const
{
return Line(a, b, c);
}
};
class HalfPlaneIntersector {
private:
vector <Point> points;
public:
HalfPlaneIntersector()
{
points.push_back(Point(-INF, INF));
points.push_back(Point(INF, INF));
points.push_back(Point(INF, -INF));
points.push_back(Point(-INF, -INF));
}
void intersect(const HalfPlane &h)
{
vector <Point> result;
for (unsigned int i = 0; i < points.size(); i++)
{
Line a = Line(points[i], points[(i + 1) % points.size()]);
Segment a_seg = Segment(points[i], points[(i + 1) % points.size()]);
if (h.contains_point(points[i]))
result.push_back(points[i]);
if (a_seg.intersects(h.line()))
result.push_back(a.intersect(h.line()));
}
points = result;
}
double perimeter() const
{
double res = 0;
for (unsigned int i = 0; i < points.size(); i++)
res += Segment(points[i], points[(i + 1) % points.size()]).length();
return res;
}
};
// Calculate perimeter of 2 triangle intersection for examle.
int main()
{
HalfPlaneIntersector hpi;
for (int i = 0; i < 2; i++)
{
Point p1, p2, p3;
p1.scan();
p2.scan();
p3.scan();
hpi.intersect(HalfPlane(Line(p1, p2), p3));
hpi.intersect(HalfPlane(Line(p1, p3), p2));
hpi.intersect(HalfPlane(Line(p2, p3), p1));
}
cout << hpi.perimeter();
}
| 4,099
|
C++
|
.cpp
| 174
| 17.218391
| 80
| 0.48045
|
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
|
9,992
|
quick_hull.cpp
|
OpenGenus_cosmos/code/computational_geometry/src/quick_hull/quick_hull.cpp
|
#include <vector>
#include <iostream>
#include <cmath>
using namespace std;
struct vec2
{
float x, y;
vec2(float x, float y) : x(x), y(y)
{
}
vec2()
{
}
};
vector<vec2> input;
vector<vec2> output;
float lineToPointSupport(vec2 l1, vec2 l2, vec2 p)
{
return abs ((p.y - l1.y) * (l2.x - l1.x) -
(l2.y - l2.y) * (p.x - l1.x));
}
float dot(vec2 A, vec2 B)
{
return A.x * B.x + A.y * B.y;
}
void findHull(int a, int b)
{
float dy = input[b].y - input[a].y;
float dx = input[b].x - input[a].x;
vec2 normal(-dy, dx);
float biggestLinePointDistance = -1;
int c = 0;
for (size_t i = 0; i < input.size(); i++)
{
vec2 aToPoint(input[i].x - input[a].x, input[i].y - input[a].y);
if (dot(aToPoint, normal) < 0 || static_cast<int>(i) == a || static_cast<int>(i) == b)
continue;
float lineToPoint = lineToPointSupport(input[a], input[b], input[i]);
if (lineToPoint > biggestLinePointDistance)
{
c = i;
biggestLinePointDistance = lineToPoint;
}
}
if (biggestLinePointDistance == -1)
return;
output.push_back(input[c]);
findHull(a, c);
findHull(c, b);
}
void quickhull()
{
if (input.size() < 3)
return;
float mini = 0;
float maxi = 0;
for (size_t i = 0; i < input.size(); i++)
{
if (input[i].x < input[mini].x)
mini = i;
if (input[i].x > input[maxi].x)
maxi = i;
}
output.push_back(input[mini]);
output.push_back(input[maxi]);
findHull(mini, maxi);
findHull(maxi, mini);
}
int main()
{
//example set 1
input.push_back(vec2(5, 10));
input.push_back(vec2(10, 10));
input.push_back(vec2(7, 15));
input.push_back(vec2(7, 13));
//example set 2
// input.push_back(vec2(0, 15));
// input.push_back(vec2(10, 15));
// input.push_back(vec2(10, 20));
// input.push_back(vec2(0, 20));
// input.push_back(vec2(5, 17));
quickhull();
for (size_t i = 0; i < output.size(); i++)
cout << "x: " << output[i].x << "y: " << output[i].y << endl;
return 0;
}
| 2,173
|
C++
|
.cpp
| 86
| 20.325581
| 94
| 0.54778
|
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
|
9,995
|
jarvis_march.cpp
|
OpenGenus_cosmos/code/computational_geometry/src/jarvis_march/jarvis_march.cpp
|
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
struct Point
{
int x;
int y;
int pos;
Point(int x, int y, int p)
{
this->x = x;
this->y = y;
this->pos = p;
}
};
int orientation(Point p, Point q, Point r)
{
int cross = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
if (cross == 0)
return 0;
return (cross > 0) ? 1 : -1;
}
vector<Point> getConvexHull(vector<Point> points)
{
if (points.size() < 3)
return points;
int left = 0;
for (size_t i = 1; i < points.size(); i++)
if (points[i].x < points[left].x)
left = i;
// Starting from left move counter-clockwise
vector<Point> hull;
int tail = left, middle;
do {
middle = (tail + 1) % points.size();
for (size_t i = 0; i < points.size(); i++)
if (orientation(points[tail], points[i], points[middle]) == -1)
middle = i;
hull.push_back(points[middle]);
tail = middle;
} while (tail != left);
return hull;
}
double dist(Point p1, Point p2)
{
return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}
int main()
{
int N;
cin >> N;
vector<Point> points;
for (int i = 0; i < N; i++)
{
int x, y;
cin >> x >> y;
points.push_back(Point(x, y, i + 1));
}
vector<Point> result = getConvexHull(points);
result.push_back(result[0]);
double ans = 0;
for (size_t i = 1; i < result.size(); i++)
ans += dist(result[i], result[i - 1]);
cout << ans << '\n';
cout << "Points lying on hull\n";
for (size_t i = 0; i < result.size(); i++)
cout << result[i].pos << ' ';
}
| 1,748
|
C++
|
.cpp
| 69
| 19.985507
| 79
| 0.514097
|
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
|
9,999
|
axis_aligned_bounding_box_collision.cpp
|
OpenGenus_cosmos/code/computational_geometry/src/axis_aligned_bounding_box_collision/axis_aligned_bounding_box_collision.cpp
|
#include <iostream>
// Part of Cosmos by OpenGenus Foundation
struct Vector
{
int x;
int y;
};
struct Shape
{
Vector center;
int width;
int height;
};
bool checkAABBCollision(Shape &a, Shape &b)
{
// change '<' to '<=' if you want to include edge touching as a collision
return (abs(a.center.x - b.center.x) * 2 < (a.width + b.width)) &&
(abs(a.center.y - b.center.y) * 2 < (a.height + b.height));
}
int main()
{
Shape a = { Vector {3, 3}, 4, 5 };
Shape b = { Vector {9, 3}, 6, 4 };
// 0 - no collision
std::cout << checkAABBCollision(a, b) << std::endl;
a = { Vector {3, 3}, 4, 5 };
b = { Vector {7, 3}, 6, 4 };
// 1 - collision
std::cout << checkAABBCollision(a, b) << std::endl;
a = { Vector {3, 10}, 4, 6 };
b = { Vector {3, 5}, 6, 6 };
// 1 - collision
std::cout << checkAABBCollision(a, b) << std::endl;
}
| 907
|
C++
|
.cpp
| 34
| 22.882353
| 77
| 0.557225
|
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,000
|
dda_line.cpp
|
OpenGenus_cosmos/code/computational_geometry/src/dda_line/dda_line.cpp
|
#include <iostream>
class DDALineDrawingAlgorithm
{
public:
void ddaLineDrawing();
void getCoordinates();
private:
int x1_, x2_, y1_, y2_;
};
void DDALineDrawingAlgorithm::ddaLineDrawing()
{
//calculating range for line between start and end point
int dx = x2_ - x1_;
int dy = y2_ - y1_;
// calculate steps required for creating pixels
int step = abs(abs(dx) > abs(dy) ? dx : dy);
// calculate increment in x & y for each steps
float xIncrement = (dx) / (float)step;
float yIncrement = (dy) / (float)step;
// drawing pixel for each step
float x = x1_;
float y = y1_;
putpixel((x), (y),GREEN); //this putpixel is for very first pixel of the line
for(int i = 1; i <= step; ++i)
{
x = x + xIncrement; // increment in x at each step
y = y + yIncrement; // increment in y at each step
putpixel(round(x), round(y),GREEN); // display pixel at coordinate (x, y)
delay(200); //delay introduced for visualization at each step
}
delay(500);
}
void DDALineDrawingAlgorithm::getCoordinates()
{
std::cout << "\nEnter the First Coordinate ";
std::cout << "\nEnter X1 : ";
std::cin >> x1_;
std::cout << "\nEnter Y1 : ";
std::cin >> y1_;
std::cout << "\nEnter the Second Coordinate ";
std::cout << "\nEnter X2 : ";
std::cin >> x2_;
std::cout << "\nEnter Y2 : ";
std::cin >> y2_;
}
int main()
{
DDALineDrawingAlgorithm d;
d.getCoordinates();
int gd=DETECT,gm;
initgraph(&gd,&gm,NULL);
d.ddaLineDrawing();
}
| 1,630
|
C++
|
.cpp
| 53
| 25.320755
| 84
| 0.59373
|
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,001
|
cohen_sutherland_lineclip.cpp
|
OpenGenus_cosmos/code/computational_geometry/src/cohen_sutherland_lineclip/cohen_sutherland_lineclip.cpp
|
#include <iostream>
class CohenSutherLandAlgo
{
public:
CohenSutherLandAlgo() : x1_(0.0), x2_(0.0), y1_(0.0), y2_(0.0) { }
void setCoordinates(double x1, double y1, double x2, double y2);
void setClippingRectangle(double x_max, double y_max, double x_min, double y_min);
int generateCode(double x, double y);
void cohenSutherland();
private:
double x1_, y1_, x2_, y2_;
double xMax_, yMax_, xMin_, yMin_;
const int Inside = 0; // 0000
const int Left = 1; // 0001
const int Right = 2; // 0010
const int Bottom = 4; // 0100
const int Top = 8; // 1000
};
void CohenSutherLandAlgo::setCoordinates(double x1, double y1, double x2, double y2)
{
this->x1_ = x1;
this->y1_ = y1;
this->x2_ = x2;
this->y2_ = y2;
}
void CohenSutherLandAlgo::setClippingRectangle(double x_max, double y_max, double x_min, double y_min)
{
this->xMax_ = x_max;
this->yMax_ = y_max;
this->xMin_ = x_min;
this->yMin_ = y_min;
}
int CohenSutherLandAlgo::generateCode(double x, double y)
{
int code = Inside; // intially initializing as being inside
if (x < xMin_) // lies to the left of rectangle
code |= Left;
else if (x > xMax_) // lies to the right of rectangle
code |= Right;
if (y < yMin_) // lies below the rectangle
code |= Bottom;
else if (y > yMax_) // lies above the rectangle
code |= Top;
return code;
}
void CohenSutherLandAlgo::cohenSutherland()
{
int code1 = generateCode(x1_, y1_); // Compute region codes for P1.
int code2 = generateCode(x2_, y2_); // Compute region codes for P2.
bool accept = false; // Initialize line as outside the rectangular window.
while (true)
{
if ((code1 == 0) && (code2 == 0))
{
// If both endpoints lie within rectangle.
accept = true;
break;
}
else if (code1 & code2)
{
break; // If both endpoints are outside rectangle,in same region.
}
else
{
// Some segment of line lies within the rectangle.
int codeOut;
double x, y;
// At least one endpoint lies outside the rectangle, pick it.
if (code1 != 0)
codeOut = code1;
else
codeOut = code2;
/*
* Find intersection point by using formulae :
y = y1 + slope * (x - x1)
x = x1 + (1 / slope) * (y - y1)
*/
if (codeOut & Top)
{
// point is above the clip rectangle
x = x1_ + (x2_ - x1_) * (yMax_ - y1_) / (y2_ - y1_);
y = yMax_;
}
else if (codeOut & Bottom)
{
// point is below the rectangle
x = x1_ + (x2_ - x1_) * (yMin_ - y1_) / (y2_ - y1_);
y = yMin_;
}
else if (codeOut & Right)
{
// point is to the right of rectangle
y = y1_ + (y2_ - y1_) * (xMax_ - x1_) / (x2_ - x1_);
x = xMax_;
}
else if (codeOut & Left)
{
// point is to the left of rectangle
y = y1_ + (y2_ - y1_) * (xMin_ - x1_) / (x2_ - x1_);
x = xMin_;
}
/*
* Intersection point x,y is found.
Replace point outside rectangle by intersection point.
*/
if (codeOut == code1)
{
x1_ = x;
y1_ = y;
code1 = generateCode(x1_, y1_);
}
else
{
x2_ = x;
y2_ = y;
code2 = generateCode(x2_, y2_);
}
}
}
if (accept)
{
std::cout <<"Line accepted from " <<"("<< x1_ << ", "
<< y1_ << ")" << " to "<< "(" << x2_ << ", " << y2_ << ")" << std::endl;
}
else
std::cout << "Line rejected" << std::endl;
}
int main() {
CohenSutherLandAlgo c;
double x1, y1, x2, y2, x_max, y_max, x_min, y_min;
std::cout << "\nEnter Co-ordinates of P1(X1,Y1) of Line Segment : ";
std::cout << "\nEnter X1 Co-ordinate : ";
std::cin >> x1;
std::cout << "\nEnter Y1 Co-ordinate : ";
std::cin >> y1;
std::cout << "\nEnter Co-ordinates of P2(X2,Y2) of Line Segment : ";
std::cout << "\nEnter X2 Co-ordinate : ";
std::cin >> x2;
std::cout << "\nEnter Y2 Co-ordinate : ";
std::cin >> y2;
c.setCoordinates(x1, y1, x2, y2);
std::cout << "\nEnter the Co-ordinates of Interested Rectangle.";
std::cout << "\nEnter the X_MAX : ";
std::cin >> x_max;
std::cout << "\nEnter the Y_MAX : ";
std::cin >> y_max;
std::cout << "\nEnter the X_MIN : ";
std::cin >> x_min;
std::cout << "\nEnter the Y_MIN : ";
std::cin >> y_min;
c.setClippingRectangle(x_max, y_max, x_min, y_min);
c.cohenSutherland();
}
| 5,045
|
C++
|
.cpp
| 153
| 24.320261
| 102
| 0.49456
|
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,004
|
area_of_triangle_herons_formula.cpp
|
OpenGenus_cosmos/code/computational_geometry/src/area_of_triangle/area_of_triangle_herons_formula.cpp
|
#include <iostream>
#include <cmath>
class AreaOfTriangle
{
public:
AreaOfTriangle(double a, double b, double c) : a_(a), b_(b), c_(c) {}
double calculateArea();
private:
double a_, b_, c_;
};
double AreaOfTriangle::calculateArea()
{
/*
* As magnitude of length of sides must be positive.
* Given length of sides of triangle must follow the following result :
* "Sum of any two sides of triangle must be smaller than the third side of triangle".
*/
if (a_ < 0 || b_ < 0 || c_ < 0 || a_+ b_ <= c_ || a_+ c_ <= b_ || b_+ c_ <= a_)
return 0.0;
double s = (a_ + b_ + c_) / 2; //semi-perimeter of triangle
return sqrt(s * (s - a_) * (s - b_) * (s - c_)); //Heron's Formula
}
int main()
{
double ta, tb, tc;
std::cout << "\nEnter the length of side-1 : ";
std::cin >> ta;
std::cout << "\nEnter the length of side-2 : ";
std::cin >> tb;
std::cout << "\nEnter the length of side-3 : ";
std::cin >> tc;
AreaOfTriangle a(ta, tb, tc);
if (a.calculateArea() == 0.0)
std::cout << "\nInvalid Triangle";
else
std::cout << "\nArea of Triangle : " << a.calculateArea() << " square units.";
}
| 1,198
|
C++
|
.cpp
| 37
| 28.162162
| 90
| 0.566724
|
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,005
|
area_of_polygon.cpp
|
OpenGenus_cosmos/code/computational_geometry/src/area_of_polygon/area_of_polygon.cpp
|
#include <iostream>
typedef std::pair<double, double> point;
const int size = 100000;
point points[size];
#define x first
#define y second
double calcArea(point a, point b, point c)
{
return abs( (a.first - b.first) * (c.second - b.second) - (a.second - b.second) *
(c.first - b.first) ) / 2;
}
int main ()
{
double answer = 0;
int n;
std::cin >> n;
for (int i = 0; i < n; i++)
std::cin >> points[i].x >> points[i].y;
for (int i = 2; i < n; i++)
answer += calcArea(points[0], points[i - 1], points[i]);
std::cout << answer;
}
| 595
|
C++
|
.cpp
| 22
| 22.909091
| 85
| 0.570922
|
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,006
|
bresenham_circle.cpp
|
OpenGenus_cosmos/code/computational_geometry/src/bresenham_circle/bresenham_circle.cpp
|
#include <iostream>
#include "graphics.h"
class BresenhamCircle
{
public:
BresenhamCircle(int radius_) : radius_(radius_) { }
void getRadiusCenter();
void drawBresenhamCircle();
void displayBresenhmCircle(int xc_, int yc_, int x, int y);
private:
int radius_;
int xc_;
int yc_;
};
void BresenhamCircle::drawBresenhamCircle()
{
int x = 0, y = radius_;
int decesionParameter = 3 - 2 * radius_;
displayBresenhmCircle(xc_, yc_, x, y);
while (y >= x)
{
x++;
if (decesionParameter > 0)
{
y--;
decesionParameter = decesionParameter + 4 * (x - y) + 10;
}
else
decesionParameter = decesionParameter + 4 * x + 6;
displayBresenhmCircle(xc_, yc_, x, y); //displaying all the Eight Pixels of (x,y)
delay(30);
}
}
void BresenhamCircle::getRadiusCenter()
{
std::cout << "\nEnter Radius of the Circle : ";
std::cin >> radius_;
std::cout << "\nEnter X-Coordinate of Center of Circle : ";
std::cin >> xc_;
std::cout << "\nEnter Y-Coordinate of Center of Circle : ";
std::cin >> yc_;
}
void BresenhamCircle::displayBresenhmCircle(int xc_,int yc_, int x, int y)
{
//displaying all 8 coordinates of(x,y) residing in 8-octants
putpixel(xc_+x, yc_+y, WHITE);
putpixel(xc_-x, yc_+y, WHITE);
putpixel(xc_+x, yc_-y, WHITE);
putpixel(xc_-x, yc_-y, WHITE);
putpixel(xc_+y, yc_+x, WHITE);
putpixel(xc_-y, yc_+x, WHITE);
putpixel(xc_+y, yc_-x, WHITE);
putpixel(xc_-y, yc_-x, WHITE);
}
int main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, NULL);
BresenhamCircle b(0);
//accepting the radius and the centre coordinates of the circle
b.getRadiusCenter();
/*
* selecting the nearest pixel and displaying all the corresponding
* points of the nearest pixel point lying in 8-octants.
*
*/
b.drawBresenhamCircle();
delay(200);
closegraph();
}
| 2,061
|
C++
|
.cpp
| 70
| 23.385714
| 90
| 0.595323
|
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,008
|
quickselect.cpp
|
OpenGenus_cosmos/code/selection_algorithms/src/quickselect.cpp
|
// This algorithm is similar to quicksort because it
// chooses an element as a pivot and partitions the
// data into two based on the pivot. However, unlike
// quicksort, quickselect only recurses into one side
// - the side with the element it is searching for.
#include <iostream>
#include <vector>
#include <cmath>
#include <cstdlib>
// Part of Cosmos by OpenGenus Foundation
using namespace std;
// Swaps values in vector with given indices
void vSwap(vector<int> &v, int pos1, int pos2)
{
int temp = v[pos1];
v[pos1] = v[pos2];
v[pos2] = temp;
}
int partition(vector<int> &v, int left, int right, int pivotIndex)
{
int pivotValue = v[pivotIndex];
vSwap(v, pivotIndex, right);
int storeIndex = left;
for (int i = left; i < right; i++)
if (v[i] < pivotValue)
{
vSwap(v, storeIndex, i);
storeIndex++;
}
vSwap(v, right, storeIndex);
return storeIndex;
}
// Returns the k-th smallest element of list in left <= k <= right
int select(vector<int> &v, int left, int right, int k)
{
if (left == right)
return v[k];
// Select a random pivot within left and right
int pivotIndex = left + floor(rand() % (right - left + 1));
pivotIndex = partition(v, left, right, pivotIndex);
if (k == pivotIndex)
return v[k];
else if (k < pivotIndex)
return select(v, left, pivotIndex - 1, k);
else
return select(v, pivotIndex + 1, right, k);
}
int main()
{
vector<int> v = {70, 45, 98, 66, 34, 18, 23, 6, 8, 99, 69, 24, 10, 97, 88, 42, 74, 4, 5, 100};
cout << select(v, 0, v.size() - 1, 0) << endl;
return 0;
}
| 1,652
|
C++
|
.cpp
| 53
| 27.132075
| 98
| 0.634253
|
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,010
|
ceil_of_element_in_sorted_array.cpp
|
OpenGenus_cosmos/code/algorithm_applications/src/binary_search/ceil_of_element/ceil_of_element_in_sorted_array.cpp
|
#include<bits/stdc++.h>
using namespace std;
int solve(int arr[],int n, int ele){
int ans=-1;
int low=0;
int high=n-1;
while(low<=high){
int mid=low+(high-low)/2;
if(ele==arr[mid]){
return ele;
}
else if(ele>arr[mid]){
ans=mid;
high=mid-1;
}
else{
low=mid+1;
}
}
return arr[ans];
}
int main(){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
int ele;
cin>>ele;
int ans=solve(arr,n,ele);
cout<<"Ceil of "<<ele<<" is "<<ans<<endl;
return 0;
}
| 566
|
C++
|
.cpp
| 34
| 12.441176
| 44
| 0.526316
|
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,012
|
firstAndLastPosInSortedArray.cpp
|
OpenGenus_cosmos/code/algorithm_applications/src/binary_search/first_and_last_position_in_sorted_array/firstAndLastPosInSortedArray.cpp
|
#include <bits/stdc++.h>
using namespace std;
int first(int arr[], int x, int n)
{
int low = 0, high = n - 1, res = -1;
while (low <= high)
{
int mid = (low + high) / 2;
if (arr[mid] > x)
high = mid - 1;
else if (arr[mid] < x)
low = mid + 1;
else
{
res = mid;
high = mid - 1;
}
}
return res;
}
int last(int arr[], int x, int n)
{
int low = 0, high = n - 1, res = -1;
while (low <= high)
{
int mid = (low + high) / 2;
if (arr[mid] > x)
high = mid - 1;
else if (arr[mid] < x)
low = mid + 1;
else
{
res = mid;
low = mid + 1;
}
}
return res;
}
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int q;
cin >> q;
while (q--)
{
int a;
cin >> a;
cout << first(arr, a, n) << " " << last(arr, a, n) << endl;
}
}
| 1,053
|
C++
|
.cpp
| 56
| 12.232143
| 67
| 0.380665
|
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,014
|
test_naive_pattern_search.cpp
|
OpenGenus_cosmos/code/string_algorithms/test/test_naive_pattern_search.cpp
|
/**
* @file test_naive_pattern_search.cpp
* @author zafar hussain (zafar_hussain2000@hotmail.com)
* @brief test naive_pattern_search.cpp
* @version 0.1
* @date 2022-10-16
*
* @copyright Copyright (c) 2022
*
*/
#include <assert.h>
#include "./../src/naive_pattern_search/naive_pattern_search.cpp"
int main() {
assert(search("z", "const char *txt") == false);
assert(search("", "const char *txt") == false);
assert(search("xt", "") == false);
assert(search("xt", "const char *txt") == 13);
assert(search("*", "const char *txt") == 11);
assert(search("c", "const char *txt") == 0);
assert(search(" c", "const char *txt") == 5);
assert(search("t ", "const char *txt") == 4);
return 0;
}
| 715
|
C++
|
.cpp
| 23
| 28.695652
| 65
| 0.631732
|
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,015
|
kasai_algorithm.cpp
|
OpenGenus_cosmos/code/string_algorithms/src/kasai_algorithm/kasai_algorithm.cpp
|
/*
*
* Kasai Algorithm
* https://www.geeksforgeeks.org/%C2%AD%C2%ADkasais-algorithm-for-construction-of-lcp-array-from-suffix-array/
*
*/
#include <iostream>
#include <vector>
#include <string>
std::vector<int> kasaiAlgorithm(std::string s, std::vector<int> suffix_array)
{
size_t m = 0;
std::vector<int> LCP(s.size(), 0);
std::vector<size_t> rank(s.size(), 0);
for (size_t i = 0; i < s.size(); i++)
rank[suffix_array[i]] = i;
for (size_t i = 0; i < s.size(); i++, m ? m-- : 0)
{
if (rank[i] == s.size() - 1)
{
m = 0;
continue;
}
int j = suffix_array[rank[i] + 1];
while (i + m < s.size() && j + m < s.size() && s[i + m] == s[j + m])
m++;
LCP[rank[i]] = m;
}
return LCP;
}
int main()
{
std::string input = "banana";
int indexes[] = {5, 3, 1, 0, 4, 2};
std::vector<int> suffixArray(indexes, indexes + 62);
std::vector<int> lcpArray = kasaiAlgorithm(input, suffixArray);
for (int i = 0; i < lcpArray.size(); i++) // => 1 3 0 0 2 0
std::cout << lcpArray[i] << " ";
return 0;
}
| 1,141
|
C++
|
.cpp
| 40
| 23.35
| 110
| 0.527854
|
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,019
|
morsecode.cpp
|
OpenGenus_cosmos/code/string_algorithms/src/morse_code/morsecode.cpp
|
#include <iostream>
#include <string>
#include <vector>
std::pair<char, std::string> pairing(char alpha, std::string morse_code);
std::string finder(const std::vector<std::pair<char, std::string>> &mp, std::string value);
std::string wordToMorse(const std::vector<std::pair<char, std::string>> &mp, std::string input);
std::string morseToWord(const std::vector<std::pair<char, std::string>> &mp, std::string input);
int main()
{
std::vector<std::pair<char, std::string>> key;
key.push_back(pairing('A', ".-"));
key.push_back(pairing('B', "-..."));
key.push_back(pairing('C', "-.-."));
key.push_back(pairing('D', "-.."));
key.push_back(pairing('E', "."));
key.push_back(pairing('F', "..-."));
key.push_back(pairing('G', "--."));
key.push_back(pairing('H', "...."));
key.push_back(pairing('I', ".."));
key.push_back(pairing('J', ".---"));
key.push_back(pairing('K', "-.-"));
key.push_back(pairing('L', ".-.."));
key.push_back(pairing('M', "--"));
key.push_back(pairing('N', "-."));
key.push_back(pairing('O', "---"));
key.push_back(pairing('P', ".--."));
key.push_back(pairing('Q', "--.-"));
key.push_back(pairing('R', ".-."));
key.push_back(pairing('S', "..."));
key.push_back(pairing('T', "-"));
key.push_back(pairing('U', "..-"));
key.push_back(pairing('V', "...-"));
key.push_back(pairing('W', ".--"));
key.push_back(pairing('X', "-..-"));
key.push_back(pairing('Y', "-.--"));
key.push_back(pairing('Z', "--.."));
key.push_back(pairing('1', ".----"));
key.push_back(pairing('2', "..---"));
key.push_back(pairing('3', "...--"));
key.push_back(pairing('4', "....-"));
key.push_back(pairing('5', "....."));
key.push_back(pairing('6', "-...."));
key.push_back(pairing('7', "--..."));
key.push_back(pairing('8', "---.."));
key.push_back(pairing('9', "---."));
key.push_back(pairing('0', "-----"));
std::cout << wordToMorse(key, "shobhit is a programmer") << std::endl;
std::cout << morseToWord(key, "--- .--. . -. --. . -. ..- ...") << std::endl; // prints OPENGENUS
return 0;
}
std::pair<char, std::string> pairing(char alpha, std::string morse_code)
{
return std::make_pair(alpha, morse_code);
}
// returns the corresponding code for both alphabet and numbers & vice versa
std::string finder(const std::vector<std::pair<char, std::string>> &mp, std::string value)
{
// to know where to search on (first index or second index)
if (value[0] == '.' || value[0] == '-')
{
std::string val = "";
for (const auto &it : mp)
if (it.second == value)
{
val += it.first;
return val;
}
}
else
{
// it is used because length of any alphabet is 1
char val = value[0];
for (const auto &it : mp)
if (it.first == val)
return it.second;
}
return std::string{};
}
std::string wordToMorse(const std::vector<std::pair<char, std::string>> &mp, std::string input)
{
std::string tempr, encoded = "";
for (const auto& elem : input)
{
if (elem == ' ')
encoded += '/';
else
{
tempr = std::toupper(elem);
tempr = finder(mp, tempr);
encoded += tempr + " ";
}
}
return encoded;
}
std::string morseToWord(const std::vector<std::pair<char, std::string>> &mp, std::string input)
{
std::string new_input = input + " ", decoded = "", pseudo_morse = "";
for (const auto& elem : input)
{
if (elem != ' ' && elem != '/')
pseudo_morse += elem;
else if (elem == ' ')
{
decoded += finder(mp, pseudo_morse);
pseudo_morse.clear();
}
else
{
decoded += ' ';
decoded += finder(mp, pseudo_morse);
pseudo_morse.clear();
}
}
return decoded;
}
| 3,979
|
C++
|
.cpp
| 115
| 28.495652
| 101
| 0.525797
|
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,020
|
string_addition.cpp
|
OpenGenus_cosmos/code/string_algorithms/src/arithmetic_on_large_numbers/string_addition.cpp
|
#include <string>
#include <iostream>
#include <cassert>
std::string strAdd(std::string s, std::string r)
{
int re = 0;
std::string sum;
// precondition for empty strings
assert(s.length() > 0 && r.length() > 0);
if (r.length() < s.length())
r.insert(r.begin(), s.length() - r.length(), '0');
else if (r.length() > s.length())
s.insert(s.begin(), r.length() - s.length(), '0');
for (int i = s.length() - 1; i >= 0; --i)
{
int a = (int(s[i] + r[i]) + re - 96);
sum.insert(sum.begin(), char(a % 10 + 48));
re = a / 10;
}
if (re != 0)
sum.insert(sum.begin(), char(re + 48));
return sum;
}
int main()
{
std::string s;
std::string c;
std::cout << "Enter Number One" << "\n";
std::cin >> s;
std::cout << "Enter Number Two" << "\n";
std::cin >> c;
std::cout << "Addition Result: " << strAdd(s, c) << "\n";
return 0;
}
| 939
|
C++
|
.cpp
| 34
| 22.852941
| 61
| 0.511654
|
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,025
|
trie_pattern_search.cpp
|
OpenGenus_cosmos/code/string_algorithms/src/trie_pattern_search/trie_pattern_search.cpp
|
#include <iostream>
#include <string>
#include <stdlib.h>
#include <vector>
#define alphas 26
using namespace std;
typedef struct Node
{
Node *child[alphas];
int leaf;
}trieNode;
trieNode* getNode()
{
trieNode *t = new trieNode;
if (t)
{
for (int i = 0; i < alphas; i++)
t->child[i] = NULL;
t->leaf = 0;
}
return t;
}
void insert(trieNode *root, string s)
{
trieNode *head = root;
int len = s.length();
for (int i = 0; i < len; i++)
{
if (head->child[s[i] - 'a'] == NULL)
head->child[s[i] - 'a'] = getNode();
head = head->child[s[i] - 'a'];
}
head->leaf = 1;
}
void walk(trieNode *root)
{
trieNode *head = root;
for (int i = 0; i < alphas; i++)
if (head->child[i] != NULL)
{
cout << char(i + 'a') << " ";
walk(head->child[i]);
}
}
bool noChildren(trieNode *root)
{
trieNode *head = root;
for (int i = 0; i < 26; i++)
if (head->child[i])
return false;
return true;
}
bool notLeaf(trieNode *root)
{
if (root->leaf == 1)
return false;
return true;
}
bool deletes(trieNode *root, string s, int l, int len)
{
if (root)
{
if (l == len)
{
root->leaf = 0;
if (noChildren(root))
return true;
return false;
}
else
{
int index = s[l] - 'a';
if (deletes(root->child[index], s, l + 1, len))
{
free(root->child[index]);
root->child[index] = NULL;
return notLeaf(root) && noChildren(root);
}
}
}
return false;
}
int main()
{
int n;
cin >> n;
vector<string> str;
string s;
for (int i = 0; i < n; i++)
{
cin >> s;
str.push_back(s);
}
trieNode *root = getNode();
for (int i = 0; i < n; i++)
insert(root, str[i]);
walk(root);
cout << endl;
cin >> s;
deletes(root, s, 0, n);
walk(root);
return 0;
}
| 2,098
|
C++
|
.cpp
| 103
| 14.330097
| 59
| 0.481351
|
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,027
|
pw_checker.cpp
|
OpenGenus_cosmos/code/string_algorithms/src/password_strength_checker/pw_checker.cpp
|
// C++ program for check password strength
//
// main.cpp
// pw_checker
//
#include <iostream>
#include <string>
using namespace std;
int main()
{
// criteria
bool has_upper_letter = false;
bool has_lower_letter = false;
bool has_digits_letter = false;
bool has_approved_length = false;
bool storng_password = false;
// password input
string input_password = "XmkA78Ji";
// check password
has_approved_length = input_password.length() >= 8 ? true : false;
if (has_approved_length)
{
for (size_t i = 0; i < input_password.length(); i++)
{
if (isupper(input_password[i]) && has_upper_letter == false)
has_upper_letter = true;
else if (islower(input_password[i]) && has_lower_letter == false)
has_lower_letter = true;
else if (isdigit(input_password[i]) && has_digits_letter == false)
has_digits_letter = true;
// handle all valid
if (has_upper_letter && has_lower_letter && has_digits_letter && has_approved_length)
{
storng_password = true;
break;
}
}
// displaying error
if (storng_password)
cout << "Password is strong\n";
else
{
cout << "Password is week\n";
if (!has_upper_letter)
cout << "You must have one upper case letter\n";
if (!has_lower_letter)
cout << "You must have one lower case letter\n";
if (!has_digits_letter)
cout << "You must have one digits case letter\n";
}
}
else
cout << "You must have 8 digits lenght\n";
return 0;
}
| 1,767
|
C++
|
.cpp
| 55
| 23.472727
| 97
| 0.549853
|
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,030
|
z_algorithm.cpp
|
OpenGenus_cosmos/code/string_algorithms/src/z_algorithm/z_algorithm.cpp
|
#include <string>
#include <iostream>
void Zalgo(std::string s, std::string pattern)
{
using namespace std;
string k = pattern + "&" + s;
size_t Z[k.length()]; //Z-array for storing the length of the longest substring
//starting from s[i] which is also a prefix of s[0..n-1]
size_t l = 0, r = 0;
for (size_t i = 1; i < k.length(); i++)
{
if (i > r)
{
l = i; r = i;
while (r < k.length() && k[r] == k[r - l])
r++;
Z[i] = r - l;
r--;
}
else
{
int p = i - l;
if (Z[p] < r - i + 1)
Z[i] = Z[p];
else
{
l = i;
while (r < k.length() && k[r] == k[r - l])
r++;
Z[i] = r - l;
r--;
}
}
}
for (size_t i = 1; i < k.length(); i++)
if (Z[i] == pattern.length())
cout << "Found Pattern at " << i - pattern.length() - 1 << endl;
}
int main()
{
using namespace std;
string s = "atababatggagabagt"; //original string
string pattern = "aba"; //pattern to be searched in string
Zalgo(s, pattern);
return 0;
}
/*Output:
* Found Pattern at 2
* Found Pattern at 4
* Found Pattern at 12
*/
| 1,345
|
C++
|
.cpp
| 51
| 17.980392
| 83
| 0.42835
|
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,033
|
pangram.cpp
|
OpenGenus_cosmos/code/string_algorithms/src/pangram_checker/pangram.cpp
|
/*
* pangram.cpp
* by Charles (@c650)
*
* Part of Cosmos by OpenGenus Foundation
*/
#include <iostream>
#include <string>
#include <vector>
#include <cctype>
/*
* Return whether or not str is a pangram, in O(n) time.
*/
static bool is_pangram(const std::string& str);
static void test_pangram(const std::string& test_string, const bool should_be_pangram);
int main(void)
{
/* test for correct ones */
test_pangram("We promptly judged antique ivory buckles for the next prize.", true);
test_pangram("How razorback jumping frogs can level six piqued gymnasts.", true);
test_pangram("Sixty zippers were quickly picked from the woven jute bag.", true);
test_pangram("The quick brown fox jumps over a lazy dog.", true);
test_pangram("Waltz, nymph, for quick jigs vex bud.", true);
/* test to make sure it doesn't false flag */
test_pangram("", false);
test_pangram("I love C++", false);
test_pangram("The alphabet", false);
test_pangram("131;1)_()[]", false);
return 0;
}
static bool is_pangram(const std::string& str)
{
const int ALPHA_LEN = 'z' - 'a' + 1;
const char ALPHA_BASE = 'a';
std::vector<bool> alphabet(ALPHA_LEN, false); /* we'll flag each character. */
int count = 0;
for (const auto& c : str)
{
/* if the character c isn't alphabetical, or if we've already seen that character, skip it. */
if (!std::isalpha(c) || alphabet[std::tolower(c) - ALPHA_BASE])
continue;
/* denote that we saw this character. */
alphabet[std::tolower(c) - ALPHA_BASE] = true;
/* increment count. */
++count;
}
return count == ALPHA_LEN;
}
static void test_pangram(const std::string& test_string, const bool should_be_pangram)
{
std::cout << "Testing if \"" << test_string << "\" is a pangram.\n\t";
if (is_pangram(test_string) == should_be_pangram)
std::cout << "Success!";
else
std::cout << "WRONG!";
std::cout << "\n";
}
| 2,027
|
C++
|
.cpp
| 57
| 31.140351
| 102
| 0.634596
|
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,035
|
naive_pattern_search.cpp
|
OpenGenus_cosmos/code/string_algorithms/src/naive_pattern_search/naive_pattern_search.cpp
|
// # Part of Cosmos by OpenGenus Foundation
#include <cstddef>
#include <cstring>
int search(const char *pattern, const char *text) {
/**
* @brief Searches for the given pattern in the provided text,
*
*
* @param pat Pattern to search for
* @param txt Text to search in
*
* @returns [int] position if pattern exists, else [bool] false
*/
const size_t M = strlen(pattern); // length of pattern
const size_t N = strlen(text); // length of txt
if (M == 0 || N == 0)
return false; // empty pattern or text provided
for (size_t i = 0; i < (N - M + 1); i++) { // loop along the text
for (size_t j = 0; j < M; j++) { // loop through the pattern
if (text[i + j] != pattern[j]) { // compare elements of pattern and text
break; // break out of loop, if mismatch
}
if (j == M - 1) { // loop through the pattern passes, here we have a match
return i; // return matched text index
}
}
}
return false; // return false, as match not found
}
// int main(int argc, const char **argv) {
// search("xt", "const char *txt");
// return 0;
// }
| 1,161
|
C++
|
.cpp
| 33
| 31.151515
| 80
| 0.593918
|
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,036
|
remove_dups.cpp
|
OpenGenus_cosmos/code/string_algorithms/src/remove_dups/remove_dups.cpp
|
#include <iostream>
//Part of Cosmos by OpenGenus Foundation
void removeDups(std::string &str)
{
std::string resStr;
resStr.push_back(str.front());
for (std::string::iterator it = str.begin() + 1; it != str.end(); ++it)
if (*it != resStr.back())
resStr.push_back(*it);
std::swap(str, resStr);
}
int main()
{
std::string str;
std::cout << "Enter string: " << std::endl;
std::getline(std::cin, str);
removeDups(str);
std::cout << "Resultant string: " << str << std::endl;
return 0;
}
| 545
|
C++
|
.cpp
| 20
| 23.1
| 75
| 0.599617
|
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,037
|
aho_corasick_algorithm2.cpp
|
OpenGenus_cosmos/code/string_algorithms/src/aho_corasick_algorithm/aho_corasick_algorithm2.cpp
|
#include <vector>
#include <fstream>
#include <queue>
using namespace std;
const int MAXN = 1000005;
char word[MAXN];
int n;
struct trie_node
{
int nr;
trie_node *children[26];
trie_node *fail;
vector<trie_node* >out;
trie_node()
{
nr = 0;
for (int i = 0; i < 26; i++)
children[i] = 0;
fail = 0;
out.clear();
}
}*root = new trie_node;
trie_node *fr[MAXN];
queue<trie_node* >coada;
trie_node* trie_insert(trie_node *&node, char *p)
{
if (!*p)
return node;
if (!node->children[*p - 'a'])
node->children[*p - 'a'] = new trie_node;
return trie_insert(node->children[*p - 'a'], p + 1);
}
void traversal(trie_node *t)
{
for (size_t i = 0; i < t->out.size(); i++)
{
traversal(t->out[i]);
t->nr += t->out[i]->nr;
}
}
int main()
{
ifstream in("ahocorasick.in");
ofstream out("ahocorasick.out");
in >> word >> n;
for (int i = 1; i <= n; i++)
{
char s[100000];
in >> s;
fr[i] = trie_insert(root, s);
}
coada.push(root);
while (!coada.empty())
{
trie_node *nod = coada.front();
coada.pop();
for (int i = 0; i < 26; i++)
{
if (!nod->children[i])
continue;
trie_node *f = nod->fail;
while (f && !f->children[i])
f = f->fail;
if (!f)
{
nod->children[i]->fail = root;
root->out.push_back(nod->children[i]);
}
else
{
nod->children[i]->fail = f->children[i];
f->children[i]->out.push_back(nod->children[i]);
}
coada.push(nod->children[i]);
}
}
trie_node *t = root;
for (char *p = word; *p; p++)
{
int ch = *p - 'a';
while (t && !t->children[ch])
t = t->fail;
if (!t)
t = root;
else
t = t->children[ch];
t->nr++;
}
traversal(root);
for (int i = 1; i <= n; i++)
out << fr[i]->nr << '\n';
return 0;
}
| 2,166
|
C++
|
.cpp
| 93
| 15.989247
| 64
| 0.453835
|
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,040
|
randomized_quicksort.cpp
|
OpenGenus_cosmos/code/randomized_algorithms/src/randomized_quick_sort/randomized_quicksort.cpp
|
// implementation of quicksort using randomization
// by shobhit(dragon540)
#include <algorithm>
#include <ctime>
#include <iostream>
#include <vector>
void quicksort(std::vector<int> &vect, int low, int high);
int part(std::vector<int> &vect, int low, int high);
int main()
{
srand(time(NULL));
std::vector<int> val = {-25, 119, 32, 54, 623, 20, -2, -4, 8, 11};
// sorts the array in increasing order
quicksort(val, 0, 10);
for (int i = 0; i < 10; i++)
std::cout << val[i] << " ";
std::cout << '\n';
return 0;
}
void quicksort(std::vector<int> &vect, int low, int high)
{
if (low < high)
{
int pi = part(vect, low, high);
quicksort(vect, low, pi - 1);
quicksort(vect, pi + 1, high);
}
}
// sort a sub array partially in increasing order
int part(std::vector<int> &vect, int low, int high)
{
int pivotIndex = low + (rand() % (high - low + 1));
int pivot = vect[pivotIndex];
int l = low - 1;
std::swap(vect[pivotIndex], vect[high]);
for (int i = low; i < high; ++i)
if (vect[i] < pivot)
{
++l;
std::swap(vect[l], vect[i]);
}
std::swap(vect[l + 1], vect[high]);
return l + 1;
}
| 1,234
|
C++
|
.cpp
| 44
| 23.454545
| 70
| 0.575424
|
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,041
|
random_number_selection_from_a_stream.cpp
|
OpenGenus_cosmos/code/randomized_algorithms/src/random_from_stream/random_number_selection_from_a_stream.cpp
|
// Randomly select a number from stream of numbers.
// A function to randomly select a item from stream[0], stream[1], .. stream[i-1]
#include <random>
#include <iostream>
using namespace std;
int selectRandom(int x)
{
static int res; // The resultant random number
static int count = 0; //Count of numbers visited so far in stream
count++; // increment count of numbers seen so far
// If this is the first element from stream, return it
if (count == 1)
res = x;
else
{
// Generate a random number from 0 to count - 1
int i = rand() % count;
// Replace the prev random number with new number with 1/count probability
if (i == count - 1)
res = x;
}
return res;
}
int main()
{
int n;
cin >> n;
int stream[n];
for (int i = 0; i < n; i++)
cin >> stream[i];
// Use a different seed value for every run.
srand(time(NULL));
for (int i = 0; i < n; ++i)
printf("Random number from first %d numbers is %d \n",
i + 1, selectRandom(stream[i]));
return 0;
}
| 1,106
|
C++
|
.cpp
| 37
| 24.675676
| 82
| 0.599624
|
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,042
|
shuffle_an_array.cpp
|
OpenGenus_cosmos/code/randomized_algorithms/src/shuffle_an_array/shuffle_an_array.cpp
|
#include <array>
#include <iostream>
#include <iterator>
#include <random>
// Part of Cosmos by OpenGenus Foundation
template<class It, class RNG>
void shuffle_an_array(It first, It last, RNG &&rng)
{
std::uniform_int_distribution<> dist;
using ptype = std::uniform_int_distribution<>::param_type;
using std::swap;
for (; first != last; ++first)
swap(*first, *(first + dist(rng, ptype(0, last - first - 1))));
}
int main()
{
std::array<int, 10> values{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
std::minstd_rand rng(std::random_device{} ());
shuffle_an_array(values.begin(), values.end(), rng);
for (size_t i = 0; i < values.size(); ++i)
std::cout << (i > 0 ? ", " : "") << values[i];
std::cout << std::endl;
}
| 755
|
C++
|
.cpp
| 23
| 29.391304
| 71
| 0.608516
|
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,043
|
kth_smallest_element_algorithm.cpp
|
OpenGenus_cosmos/code/randomized_algorithms/src/kth_smallest_element_algorithm/kth_smallest_element_algorithm.cpp
|
#include <iostream>
#include <climits>
#include <cstdlib>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
int randomPartition(int arr[], int l, int r);
// QuickSort based method. ASSUMPTION: ELEMENTS IN ARR[] ARE DISTINCT
int kthSmallest(int arr[], int l, int r, int k)
{
// If k is smaller than number of elements in array
if (k > 0 && k <= r - l + 1)
{
// Partition the array around a random element and
// get position of pivot element in sorted array
int pos = randomPartition(arr, l, r);
// If position is same as k
if (pos - l == k - 1)
return arr[pos];
if (pos - l > k - 1) // If position is more, recur for left subarray
return kthSmallest(arr, l, pos - 1, k);
// Else recur for right subarray
return kthSmallest(arr, pos + 1, r, k - pos + l - 1);
}
return INT_MAX;
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
// Standard partition process of QuickSort(). It considers the last
// element as pivot and moves all smaller element to left of it and
// greater elements to right. This function is used by randomPartition()
int partition(int arr[], int l, int r)
{
int x = arr[r], i = l;
for (int j = l; j <= r - 1; j++)
if (arr[j] <= x)
{
swap(&arr[i], &arr[j]);
i++;
}
swap(&arr[i], &arr[r]);
return i;
}
// Picks a random pivot element between l and r and partitions
// arr[l..r] arount the randomly picked element using partition()
int randomPartition(int arr[], int l, int r)
{
int n = r - l + 1;
int pivot = rand() % n;
swap(&arr[l + pivot], &arr[r]);
return partition(arr, l, r);
}
int main()
{
int n;
int k;
int arr[1000000];
cout << "Enter the no. of elements in array" << endl;
cin >> n;
cout << "Enter the elements of the array seprated by single space" << endl;
for (int x = 0; x < n; x++)
cin >> arr[x];
cout << "Enter k (nth smallest element to be find)" << endl;
cin >> k;
cout << endl;
cout << "kth smallest element is " << kthSmallest(arr, 0, n - 1, k);
cout << endl;
return 0;
}
| 2,211
|
C++
|
.cpp
| 72
| 25.944444
| 79
| 0.589756
|
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,045
|
reservoir_sampling.cpp
|
OpenGenus_cosmos/code/randomized_algorithms/src/reservoir_sampling/reservoir_sampling.cpp
|
// An efficient program to randomly select k items from a stream of n items
// Part of Cosmos by OpenGenus Foundation
#include <iostream>
using namespace std;
void printArray(int stream[], int n)
{
for (int i = 0; i < n; i++)
printf("%d ", stream[i]);
printf("\n");
}
// A function to randomly select k items from stream[0..n-1].
void selectKItems(int stream[], int n, int k)
{
int i; // index for elements in stream[]
// reservoir[] is the output array. Initialize it with
// first k elements from stream[]
int reservoir[k];
for (i = 0; i < k; i++)
reservoir[i] = stream[i];
// Use a different seed value so that we don't get
// same result each time we run this program
srand(time(NULL));
// Iterate from the (k+1)th element to nth element
for (; i < n; i++)
{
// Pick a random index from 0 to i.
int j = rand() % (i + 1);
// If the randomly picked index is smaller than k, then replace
// the element present at the index with new element from stream
if (j < k)
reservoir[j] = stream[i];
}
printf("Following are k randomly selected items \n");
printArray(reservoir, k);
}
// Driver program to test above function.
int main()
{
int n;
cin >> n;
int stream[n];
for (int i = 0; i < n; i++)
cin >> stream[i];
int k;
cin >> k;
selectKItems(stream, n, k);
return 0;
}
| 1,447
|
C++
|
.cpp
| 48
| 25.395833
| 75
| 0.608914
|
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,046
|
the_maximum_subarray.cpp
|
OpenGenus_cosmos/code/online_challenges/src/hackerrank/the_maximum_subarray/the_maximum_subarray.cpp
|
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
int t; //t is the number of test case
std::cin >> t;
while (t--) {
int n; //n is the size of input array
int sum, ans, ans1;
sum = ans = ans1 = 0;
int flag = 0;
std::cin >> n;
std::vector<int> arr(n);
for (int i = 0; i < n; ++i) {
std::cin >> arr[i];
if (arr[i] >= 0)
++flag;
}
if (flag == 0) {
std::sort(arr.begin(), arr.end());
std::cout << arr[n - 1] << " " << arr[n - 1] << "\n";
continue;
}
sum = ans = ans1 = 0;
for (int i = 0; i < n; ++i) {
if ((sum + arr[i]) > 0)
sum += arr[i];
else
sum = 0;
if (arr[i] >= 0)
ans1 += arr[i];
ans = std::max(ans, sum);
}
std::cout << ans << " " << ans1 << "\n";
}
return 0;
}
| 1,009
|
C++
|
.cpp
| 38
| 17.342105
| 65
| 0.369678
|
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,047
|
3D_surface_area.cpp
|
OpenGenus_cosmos/code/online_challenges/src/hackerrank/3D_aurface_area/3D_surface_area.cpp
|
#include <iostream>
int main()
{
int h, w;
int a[110][110];
std::cin >> h >> w;
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j)
std::cin >> a[i][j];
}
int sum = 0;
for (int i = 0; i < h; ++i) {
if (i == 0) {
for (int j = 0; j < w; ++j) {
int temp = 0;
if (j == 0) {
temp = (a[i][j] - 1) * 4 + 6;
sum += temp;
}
else {
temp = (a[i][j] - 1) * 4 + 6;
int d = std::min(a[i][j - 1], a[i][j]);
temp -= (d * 2);
sum += temp;
}
}
}
else {
for (int j = 0; j < w; ++j) {
int temp = 0;
if (j == 0) {
temp = (a[i][j] - 1) * 4 + 6;
int d = std::min(a[i][j], a[i - 1][j]);
temp -= (d * 2);
sum += temp;
}
else {
temp = (a[i][j] - 1) * 4 + 6;
int d = std::min(a[i][j - 1], a[i][j]);
temp -= (d * 2);
d = std::min(a[i][j], a[i - 1][j]);
temp -= (d * 2);
sum += temp;
}
}
}
}
std::cout << sum << "\n";
return 0;
}
| 1,430
|
C++
|
.cpp
| 50
| 15.16
| 59
| 0.240203
|
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,048
|
encryption.cpp
|
OpenGenus_cosmos/code/online_challenges/src/hackerrank/encryption/encryption.cpp
|
#include <cmath>
#include <iostream>
int main()
{
std::string s;
std::cin >> s;
int r, c;
int l = s.size();
r = floor(sqrt(l));
c = ceil(sqrt(l));
for (int i = 0; i < c; ++i) {
for (int j = i; j < l; j = j + c)
std::cout << s[j];
std::cout << "\n";
}
}
| 317
|
C++
|
.cpp
| 16
| 14.8125
| 41
| 0.427609
|
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,049
|
array_manipulation.cpp
|
OpenGenus_cosmos/code/online_challenges/src/hackerrank/array_manipulation/array_manipulation.cpp
|
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
int n;
int m;
int a;
int b;
int k;
std::cin >> n >> m;
std::vector<std::pair<int, int> > v;
for (int i = 0; i < m; ++i) {
std::cin >> a >> b >> k;
v.push_back(std::make_pair(a, k));
v.push_back(std::make_pair(b + 1, -1 * k));
}
long mx = 0, sum = 0;
std::sort(v.begin(), v.end());
for (int i = 0; i < 2 * m; ++i) {
sum += v[i].second;
mx = std::max(mx, sum);
}
std::cout << mx << "\n";
return 0;
}
| 576
|
C++
|
.cpp
| 26
| 17.076923
| 51
| 0.457721
|
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,054
|
almost_sorted.cpp
|
OpenGenus_cosmos/code/online_challenges/src/hackerrank/almost_sorted/almost_sorted.cpp
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
int main()
{
int n = 0;
int p = 0;
int s, l;
s = l = 0;
int t = 0;
std::cin >> n;
std::vector<int> a(n);
std::vector<int> b(n);
for (int i; i < n; ++i) {
std::cin >> a[i];
b[i] = a[i];
}
std::sort(b.begin(), b.end());
for (int i = 0; i < n; ++i) {
if (b[i] != a[i]) {
++p;
if (t == 0) {
s = i;
++t;
}
else
l = i;
}
}
if (p == 0) {
std::cout << "yes\n";
return 0;
}
else if (p == 2) {
std::cout << "yes"
<< "\n";
std::cout << "swap " << s + 1 << " " << l + 1;
return 0;
}
for (int i = l; i > s;--i) {
if (a[i] > a[i - 1]) {
std::cout << "no\n";
return 0;
}
}
std::cout << "yes \n";
std::cout << "reverse " << s + 1 << " " << l + 1;
return 0;
}
| 1,100
|
C++
|
.cpp
| 51
| 13.45098
| 57
| 0.325
|
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,055
|
CHDIGER.cpp
|
OpenGenus_cosmos/code/online_challenges/src/codechef/CHDIGER/CHDIGER.cpp
|
#include <iostream>
#include <algorithm>
#include <list>
#include <stack>
#include <string>
int main ()
{
int t;
std::cin >> t;
while (t--)
{
std::string n;
int d;
std::cin >> n >> d;
std::list<char>ans;
std::stack<char>st;
for (int i = 0; i < n.size(); ++i)
{
if (n[i] - '0' < d)
{
while (!st.empty() && st.top() > n[i])
st.pop();
st.push(n[i]);
}
}
while (!st.empty())
{
ans.push_front(st.top());
st.pop();
}
int sz = n.size() - ans.size();
for (int i = 0; i < sz; ++i)
{
ans.push_back(char(d + '0'));
}
for (auto i : ans)
{
std::cout << i;
}
std::cout << "\n";
}
return 0;
}
| 899
|
C++
|
.cpp
| 43
| 12.44186
| 54
| 0.363636
|
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,056
|
LAZERTST.cpp
|
OpenGenus_cosmos/code/online_challenges/src/codechef/LAZERTST/LAZERTST.cpp
|
#include<iostream>
using namespace std;
typedef long long ll;
void solve()
{
ll n,m,k,q;
cin>>n>>m>>k>>q;
vector<pair<int,int>> qs(q);
vector<ll> ans(q,0);
for (int i = 0; i < q; i++)
{
cin>>qs[i].first>>qs[i].second;
}
if(k==3)
{
cout<<2<<' ';
for (int i = 0; i < q; i++)
{
cout<<m-1<<' ';
}
cout<<endl;
int h;
cin>>h;
if(h==-1)
{
exit(1);
}
}
else if(k==100)
{
ll gm = 0;
for (int i = 0; i < q; i++)
{
cout<<1<<' '<<qs[i].first<<' '<<qs[i].second<<' '<<(m*i)/10<<endl;
ll h;
cin>>h;
if(h==-1)
{
exit(1);
}
gm = max(gm,h);
}
cout<<2<<' ';
for (int i = 0; i < q; i++)
{
cout<<gm<<' ';
}
cout<<endl;
int h;
cin>>h;
if(h==-1)
{
exit(1);
}
}
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin>>t;
while(t--)
solve();
return 0;
}
| 1,180
|
C++
|
.cpp
| 66
| 10.257576
| 78
| 0.336036
|
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,057
|
hard_cash.cpp
|
OpenGenus_cosmos/code/online_challenges/src/codechef/CASH/hard_cash.cpp
|
#include <iostream>
int main() {
int t;
std::cin >> t;
while (t--) {
int n, k, x, sum = 0;
std::cin >> n >> k;
for (int i = 0; i < n; ++i) {
std::cin >> x;
sum += x;
}
sum %= k;
std::cout << sum << "\n";
}
}
| 297
|
C++
|
.cpp
| 15
| 12.866667
| 37
| 0.33452
|
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,058
|
JOHNY.cpp
|
OpenGenus_cosmos/code/online_challenges/src/codechef/JOHNY/JOHNY.cpp
|
#include <iostream>
int main() {
int t;
std::cin >> t;
while (t--) {
int n;
std::cin >> n;
int a[100];
for (int i = 0; i < n; ++i) {
std::cin >> a[i];
}
int k;
std::cin >> k;
int ans = 0;
for (int i = 0; i < n; ++i) {
ans += (a[k - 1] > a[i]);
}
std::cout << ans + 1 << '\n';
}
return 0;
}
| 451
|
C++
|
.cpp
| 21
| 12.809524
| 37
| 0.329177
|
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,059
|
JAIN.cpp
|
OpenGenus_cosmos/code/online_challenges/src/codechef/JAIN/JAIN.cpp
|
#include <iostream>
#include <algorithm>
#include <list>
#include <stack>
#include <string>
#include <map>
#include <vector>
#include <set>
#include <utility>
std::map<char,int>g_mp;
void build ()
{
g_mp.insert(std::make_pair('a',16));
g_mp.insert(std::make_pair('e',8));
g_mp.insert(std::make_pair('i',4));
g_mp.insert(std::make_pair('o',2));
g_mp.insert(std::make_pair('u',1));
}
int main()
{
build();
int t;
std::cin >> t;
while (t--)
{
int n;
std::cin >> n;
std::string a[n];
for (int i = 0; i < n; ++i)
std::cin >> a[i];
std::vector<short>value;
std::set<short>s;
std::vector<long long>count(33,0);
for (int i = 0; i < n; i++)
{
int x = 0;
for(int j = 0; j < a[i].size(); ++j)
{
x = x | g_mp[a[i][j]];
}
if (s.find(x) == s.end())
{
value.push_back(x);
count[x] = 1;
s.insert(x);
}
else
{
count[x]++;
}
}
long long ans = 0;
for (int i = 0; i < value.size(); ++i)
{
for (int j = i + 1; j < value.size(); ++j)
if ((value[i] | value[j]) == 31)
ans = ans + (count[value[i]] * count[value[j]]);
}
ans = ans + ((count[31] * (count[31] - 1)) / 2);
std::cout << ans << "\n";
}
return 0;
}
| 1,536
|
C++
|
.cpp
| 63
| 16.222222
| 68
| 0.412047
|
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,060
|
CHNUM.cpp
|
OpenGenus_cosmos/code/online_challenges/src/codechef/CHNUM/CHNUM.cpp
|
#include <iostream>
#include <algorithm>
#include <list>
#include <stack>
#include <string>
int main ()
{
int t;
std::cin >> t;
while (t--)
{
int n;
std::cin >> n;
int a;
int cnt_ps = 0, cnt_nt = 0;
for (int i = 0; i < n; ++i)
{
std::cin >> a;
if (a < 0)
cnt_nt++;
else cnt_ps++;
}
if (cnt_nt == 0)
cnt_nt = cnt_ps;
else if (cnt_ps == 10)
cnt_ps = cnt_nt;
std::cout << std::max(cnt_ps, cnt_nt) << " " << std::min(cnt_ps, cnt_nt) << "\n";
}
return 0;
}
| 638
|
C++
|
.cpp
| 30
| 14.066667
| 89
| 0.406977
|
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,061
|
coins.cpp
|
OpenGenus_cosmos/code/online_challenges/src/codechef/COINS/coins.cpp
|
#include <iostream>
#include <unordered_map>
#define lli long long int
std::unordered_map<lli, lli> mpp;
lli check(lli n)
{
if (n == 0) {
mpp[0] = 0;
return 0;
}
if (mpp[n] != 0)
return mpp[n];
else {
mpp[n] = check(n / 2) + check(n / 3) + check(n / 4);
mpp[n] = std::max(n, mpp[n]);
return mpp[n];
}
}
int main()
{
for (lli n; std::cin >> n;) {
lli d = check(n);
std::cout<< std::max(n, d) << "\n";
}
return 0;
}
| 514
|
C++
|
.cpp
| 26
| 14.923077
| 60
| 0.477273
|
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,062
|
CHFING.cpp
|
OpenGenus_cosmos/code/online_challenges/src/codechef/CHFING/CHFING.cpp
|
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define FLASH ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define mod 1000000007
int main()
{
int t;
long long k,n,ans,x,y,z,a;
cin >> t;
while(t--)
{
ans = x = y = z = a = 0;
cin >> n >> k;
k = k-1;
x = (k/(n-1));
y = (n%mod - 1%mod)%mod;
if(x%2 == 0)
{
a = x/2;
z = ((a%mod)*((x+1)%mod))%mod;
}
else
{
a = (x+1)/2;
z = ((a%mod)*(x%mod))%mod;
}
ans = ((y%mod)*(z%mod))%mod;
if(k % (n-1) != 0)
{
ans = ans + (k%(n-1))*(x+1);
}
cout << ans%mod << "\n";
}
return 0;
}
| 772
|
C++
|
.cpp
| 36
| 14.222222
| 69
| 0.401138
|
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,063
|
snug_fit.cpp
|
OpenGenus_cosmos/code/online_challenges/src/codechef/SNUG_FIT/snug_fit.cpp
|
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
int t;
std::cin >> t;
while (t--) {
int n, i, sum = 0;
std::cin >> n;
std::vector<int> a(n), b(n);
for (i = 0; i < n; ++i) {
std::cin >> a[i];
}
for (i = 0; i < n; ++i) {
std::cin >> b[i];
}
std::sort(a.begin(), a.end());
std::sort(b.begin(), b.end());
for (i = 0; i < n; ++i) {
sum += std::min(a[i], b[i]);
}
std::cout << sum << "\n";
}
}
| 561
|
C++
|
.cpp
| 24
| 16.166667
| 40
| 0.369403
|
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,064
|
SLAB.cpp
|
OpenGenus_cosmos/code/online_challenges/src/codechef/SLAB/SLAB.cpp
|
// Part of Cosmos by OpenGenus
#include <iostream>
using namespace std;
int main ()
{
int t;
cin >> t;
while (t --)
{
long long int total, net, tax;
cin >> total;
if (total <= 250000)
{
net = total;
}
else if ((250000 < total) && (total <= 500000))
{
tax = 0.05 * (total - 250000);
net = total - tax;
}
else if ((500000 < total) && (total <= 750000))
{
tax = 0.05 * ( 500000- 250000) + 0.10 * (total - 500000);
net = total - tax;
}
else if ((750000 < total) && (total <= 1000000))
{
tax = 0.05 * (500000 - 250000) + 0.10 * (750000 - 500000) + 0.15 * (total - 750000);
net = total - tax;
}
else if ((1000000 < total) && (total <= 1250000))
{
tax = 0.05 * (500000 - 250000) + 0.10 * (750000 - 500000) + 0.15 * (1000000 - 750000) + 0.20 * (total - 1000000);
net = total - tax;
}
else if ((1250000 < total) && (total <= 1500000))
{
tax = 0.05 *(500000 - 250000) + 0.10 * (750000 - 500000) + 0.15 * (1000000 - 750000) + 0.20 * (1250000 - 1000000) + 0.25 * (total - 1250000);
net = total - tax;
}
else if (total > 1500000)
{
tax = 0.05 * (500000 - 250000) + 0.10 * (750000 - 500000) + 0.15 * (1000000 - 750000) + 0.20 * (1250000 - 1000000) + 0.25 * (1500000 - 1250000) + 0.30 * (total - 1500000);
net = total - tax;
}
cout << net << endl;
}
return 0;
}
| 1,671
|
C++
|
.cpp
| 49
| 24.44898
| 183
| 0.462387
|
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,065
|
eid2.cpp
|
OpenGenus_cosmos/code/online_challenges/src/codechef/EID2/eid2.cpp
|
#include <algorithm>
#include <iostream>
#include <vector>
bool istrue(std::vector<int> a, std::vector<int> c) {
std::pair<int, int> pairt[3];
bool x = true;
int i;
for (i = 0; i < 3; ++i) {
pairt[i].first = a[i];
pairt[i].second = c[i];
}
std::sort(pairt, pairt + 3);
for (i = 0; i < 2; ++i) {
if (pairt[i].first == pairt[i + 1].first) {
if (pairt[i].second != pairt[i + 1].second) {
x = false;
break;
}
}
if (pairt[i].second > pairt[i + 1].second) {
x = false;
break;
}
if (pairt[i].second == pairt[i + 1].second) {
if (pairt[i].first != pairt[i + 1].first) {
x = false;
break;
}
}
}
return x;
}
int main() {
int t;
std::cin >> t;
while (t--) {
std::vector<int> a(3), c(3);
int i;
for (i = 0; i < 3; ++i) {
std::cin >> a[i];
}
for (i = 0; i < 3; ++i) {
std::cin >> c[i];
}
bool x = istrue(a, c);
if (x) {
std::cout << "FAIR" << std::endl;
} else {
std::cout << "NOT FAIR" << std::endl;
}
}
}
| 1,275
|
C++
|
.cpp
| 52
| 16.192308
| 57
| 0.39198
|
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,066
|
NBONACCI.cpp
|
OpenGenus_cosmos/code/online_challenges/src/codechef/NBONACCI/NBONACCI.cpp
|
#include <iostream>
#include <algorithm>
int main ()
{
int n,q;
std::cin >> n >> q;
int a[n];
for (int i = 0; i < n; ++i)
{
std::cin>>a[i];
}
int x = 0;
int xors[n] = {0};
for (int i = 0; i < n; ++i)
{
x = x ^ a[i];
xors[i] = x;
}
while (q--)
{
int k;
std::cin >> k;
int idx = k % (n + 1);
if (idx > 0)
std::cout << xors[idx - 1] << "\n";
else std::cout << "0\n";
}
return 0;
}
| 521
|
C++
|
.cpp
| 29
| 12.034483
| 47
| 0.36701
|
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,067
|
HILLJUMP.cpp
|
OpenGenus_cosmos/code/online_challenges/src/codechef/HILLJUMP/HILLJUMP.cpp
|
#include<iostream>
using namespace std;
void jump(int[], int);
void inc(int[], int);
int main()
{
std::ios::sync_with_stdio(false);
//int j;for(j=0;j<100;j++)printf("1 ");
int n, q; cin>>n>>q;
int arr[n]; arr[0]=0;
int i; for(i=0;i<n;i++)
{
int temp; cin>>temp; arr[i]+=temp; arr[i+1]=-temp;
}
while(q--)
{
int a;
cin>>a;
if(a==1) jump(arr, n);
else inc(arr, n);
}
return 0;
}
void jump(int arr[], int n)
{
int start, num, curr;
cin>>start>>num;
curr = start-1;
int i; int sum=0;
int f=1;
while(num-- && f==1)
{
int i; f=0; int sum=0;
for(i = curr+1; i<(n<curr+101?n:curr+101); i++)
{
sum+=arr[i];
if(sum>0){curr = i;f=1;break;}
}
}
cout<<curr+1<<endl;
}
void inc(int arr[], int n)
{
int start, end, lol;
cin>>start>>end>>lol;
arr[start-1]+=lol; if(end<n)arr[end]-=lol;
}
| 812
|
C++
|
.cpp
| 47
| 15.425532
| 52
| 0.596026
|
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,068
|
MEETUP.cpp
|
OpenGenus_cosmos/code/online_challenges/src/codechef/MEETUP/MEETUP.cpp
|
#include <iostream>
#include <fstream>
#include <set>
#include <map>
#include <string>
#include <vector>
#include <bitset>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <cassert>
#include <queue>
#define mp make_pair
#define pb push_back
typedef long long ll;
typedef long double ld;
using namespace std;
#ifndef LOCAL
#define cerr _cer
struct _cert
{
template <typename T> _cert& operator << (T)
{
return *this;
}
};
_cert _cer;
#endif
template <typename T> void dprint(T begin, T end)
{
for (auto i = begin; i != end; i++)
{
cerr << (*i) << " ";
}
cerr << "\n";
}
char buf[100];
int ka, kb;
map<string, int > mm1;
map<string, int > mm2;
int cc1, cc2;
set<int> eds1[1200];
set<int> eds2[1200];
string s1[1200];
string s2[1200];
int rd1()
{
scanf(" %s", buf);
if (mm1.count(buf))
return mm1[buf];
else
{
s1[cc1] = buf;
return mm1[buf] = cc1++;
}
}
int rd2()
{
scanf(" %s", buf);
if (mm2.count(buf))
return mm2[buf];
else
{
s2[cc2] = buf;
return mm2[buf] = cc2++;
}
}
void del1(int v)
{
for (int i: eds1[v])
{
eds1[i].erase(v);
}
eds1[v].clear();
}
void del2(int v)
{
for (int i: eds2[v])
{
eds2[i].erase(v);
}
eds2[v].clear();
}
int ask1(int v)
{
cout << "A " << s1[v] << "\n";
cout.flush();
return rd2();
}
int ask2(int v)
{
cout << "B " << s2[v] << "\n";
cout.flush();
return rd1();
}
void solve(vector<int> av1, vector<int> av2)
{
set<int> ss;
for (int i: av1)
if (i < ka)
ss.insert(eds1[i].size());
int bst = -1;
for (int i: av2)
{
if (i < kb)
{
if (ss.count(eds2[i].size()))
{
bst = eds2[i].size();
break;
}
}
}
if (bst == -1)
{
cout << "C No\n";
cout.flush();
exit(0);
}
int n = av1.size();
int c1 = bst;
int c2 = n - 1 - bst;
if (c1 < c2)
{
int a = -1;
for (int i: av1)
{
if (eds1[i].size() == bst && i < ka)
{
a = i;
break;
}
}
int b = ask1(a);
if (b < kb) {
cout << "C Yes\n";
cout.flush();
exit(0);
}
vector<int> avi;
vector<int> avii;
for (int i: av1)
if (i != a && eds1[a].count(i) == 1)
{
avi.push_back(i);
}
else if (i != a)
{
del1(i);
}
del1(a);
for (int i: av2)
if (i != b && eds2[b].count(i) == 1)
{
avii.push_back(i);
}
else if (i != b)
{
del2(i);
}
del2(b);
solve(avi, avii);
}
else
{
int b = -1;
for (int i: av2)
{
if (eds2[i].size() == bst && i < kb)
{
b = i;
break;
}
}
int a = ask2(b);
if (a < ka) {
cout << "C Yes\n";
cout.flush();
exit(0);
}
vector<int> avi;
vector<int> avii;
for (int i: av1)
if (i != a && eds1[a].count(i) == 0)
{
avi.push_back(i);
}
else if (i != a)
{
del1(i);
}
del1(a);
for (int i: av2)
if (i != b && eds2[b].count(i) == 0)
{
avii.push_back(i);
}
else if (i != b)
{
del2(i);
}
del2(b);
solve(avi, avii);
}
}
int n, m;
int main()
{
scanf("%d%d%d%d", &n, &m, &ka, &kb);
for (int i = 0; i < n; ++i)
assert(rd1() == i);
for (int j = 0; j < m; ++j)
{
int a = rd1();
int b = rd1();
eds1[a].insert(b);
eds1[b].insert(a);
}
for (int i = 0; i < n; ++i)
assert(rd2() == i);
for (int j = 0; j < m; ++j)
{
int a = rd2();
int b = rd2();
eds2[a].insert(b);
eds2[b].insert(a);
}
vector<int> av1;
for (int i = 0; i < n; ++i)
av1.push_back(i);
vector<int> av2;
for (int i = 0; i < n; ++i)
av2.push_back(i);
solve(av1, av2);
return 0;
}
| 3,502
|
C++
|
.cpp
| 237
| 12.101266
| 49
| 0.528941
|
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,069
|
CHEFING.cpp
|
OpenGenus_cosmos/code/online_challenges/src/codechef/CHEFING/CHEFING.cpp
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t,n,cnt,i,j;
string s;
cin >> t;
while(t--)
{
cnt = 0;
cin >> n;
int hash[n][26] = {0};
for(i = 0 ; i < n ; i++)
{
cin >> s;
for(j = 0 ; j < s.length() ; j++)
{
hash[i][s[j]-97]++;
}
}
for(i = 0 ; i < 26 ; i++)
{
for(j = 0 ; j < n ; j++)
{
if(hash[j][i] == 0)
{
cnt++;
break;
}
}
}
cout << 26 - cnt << "\n";
}
return 0;
}
| 624
|
C++
|
.cpp
| 35
| 9.971429
| 42
| 0.309353
|
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,070
|
STRWN.cpp
|
OpenGenus_cosmos/code/online_challenges/src/codechef/STRWN/STRWN.cpp
|
#include <iostream>
#define ll long long
#define ld long double
#define pb push_back
#define pp pop_back
#define mp make_pair
#define ff first
#define ss second
#define maxn 1000000007
#define PI 3.14159265358979323846
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
//cout<<fixed<<setprecision(20);
ll a,b,c;
cin>>a>>b>>c;
if(a==0 && b==0 && c==0)
{
cout<<0<<endl;
return 0;
}
if(a==0 && b==0 && c>0)
{
cout<<c<<endl;
return 0;
}
if(a==0 && c==0 && b>0)
{
cout<<b<<endl;
return 0;
}
if(c==0 && b==0 && a>0)
{
cout<<a<<endl;
return 0;
}
if(a==0 && b>0 && c>0)
{
cout<<b<<endl;
return 0;
}
if(b==0 && a>0 && c>0)
{
cout<<c<<endl;
return 0;
}
if(c==0 && a>0 && b>0)
{
cout<<a<<endl;
return 0;
}
cout<<1<<endl;
return 0;
}
| 983
|
C++
|
.cpp
| 56
| 12.482143
| 37
| 0.485931
|
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,071
|
BACREP.cpp
|
OpenGenus_cosmos/code/online_challenges/src/codechef/BACREP/BACREP.cpp
|
#include <iostream>
using namespace std;
#define ll long long
#define dd double
#define endl "\n"
#define pb push_back
#define all(v) v.begin(),v.end()
#define mp make_pair
#define fi first
#define se second
#define fo(i,n) for(int i=0;i<n;i++)
#define fo1(i,n) for(int i=1;i<=n;i++)
ll mod=1000000007;
const ll N=500050;
bool vis[N];
vector <int> adj[N];
ll depth[N]={0};
vector <int> atd[N];
ll maxdepth=1;
ll par[N]={0};
ll po(ll k ,ll n,ll ans,ll temp,ll ans1)
{
if(n==0)return ans;
while(temp<=n)
{
ans*=ans1;ans%=mod;ans1=ans1*ans1;ans1%=mod;n=n-temp;temp*=2;
}
return po(k,n,ans,1,k)%mod;
//eg. po(2,78,1,1,2);
}
void bfs(int root)
{
vis[root]=1;
depth[root]=1;
atd[1].pb(root);
queue <int> q;
q.push(root);
while(!q.empty())
{
ll a=q.front();
// vis[a]=1;
q.pop();
for(int i:adj[a])
{
if(vis[i])
continue;
vis[i]=1;
depth[i]=depth[a]+1;
atd[depth[i]].pb(i);
par[i]=a;
maxdepth=depth[i];
q.push(i);
}
}
}
ll min(ll a,ll b)
{
if(a>b)return b;else return a;
}
ll max(ll a,ll b)
{
if(a>b)return a;else return b;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
ll t;
//cin>>t;
t=1;
while(t--)
{
ll n,q;
cin>>n>>q;
fo(i,n-1)
{
ll a,b;
cin>>a>>b;
adj[a].pb(b);
adj[b].pb(a);
}
bfs(1);
ll store[n+1]={0};
for(int i=1;i<=n;i++)
{
ll c;
cin>>c;
store[i]=c;
}
while(q--)
{
for(int i=maxdepth;i>=2;i--)
{
for(int j:atd[i])
{
if(adj[j].size()!=1)
store[j]=0;
store[j]+=store[par[j]];
}
}
store[1]=0;
char ch;
cin>>ch;
if(ch=='?')
{
ll a;
cin>>a;
cout<<store[a]<<'\n';
}
else
{
ll a,b;
cin>>a>>b;
store[a]+=b;
}
}
}
return 0;
}
| 2,195
|
C++
|
.cpp
| 119
| 11.983193
| 69
| 0.442177
|
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,072
|
PBATTLE.cpp
|
OpenGenus_cosmos/code/online_challenges/src/codechef/P-BATTLE/PBATTLE.cpp
|
// Question link : https://www.codechef.com/submit/PBATTLE
//Author - Vishwas Kapoor
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
void solve(){
int n;
cin>>n;
vector<pair<int,int>> pg; // pokemon ground
fl(n){
int x;
cin>>x;
pg.push_back({x,i});
}
vector<int>pw; // pokemon water
fl(n){
int x;
cin>>x;
pw.push_back(x);
}
sort(pg.begin(), pg.end() );
priority_queue<int>pq;
pq.push(pw[pg[n-1].second]);
int count = 1;
for(int i = n-2; i >= 0; i--){
pq.push(pw[pg[i].second]);
if(pq.top() == pw[pg[i].second])
count++;
}
cout<<count<<endl;
}
signed main(){
IOS
int t;
cin>>t;
while(t--)
goddamn();
return 0;
}
| 760
|
C++
|
.cpp
| 40
| 16.525
| 68
| 0.628205
|
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,073
|
NEWSCH.cpp
|
OpenGenus_cosmos/code/online_challenges/src/codechef/NEWSCH/NEWSCH.cpp
|
#include <iostream>
#include <cstring>
using namespace std;
#define MOD 1000000007
uint64_t modmul(const uint64_t x, const uint64_t y)
{
if (x > (1 << 30) && y > (1 << 30))
return ((x >> 30)*((y << 30) % MOD) + y*(x & ((1 << 30) - 1))) % MOD;
uint64_t z = x*y;
if (z >= MOD)
z %= MOD;
return z;
}
uint64_t modpow(uint64_t base, int exp)
{
uint64_t result = 1;
for (;;)
{
if (exp & 1)
result = modmul(result, base);
exp >>= 1;
if (!exp)
break;
base = modmul(base, base);
}
return result;
}
int main()
{
int t;
cin >> t;
while (t-- > 0)
{
int n;
cin >> n;
uint64_t ans = modpow(3, n);
if (n % 2 == 0)
ans = (ans + 3) % MOD;
else
ans = (ans + MOD - 3) % MOD;
cout << ans << endl;
}
return 0;
}
| 750
|
C++
|
.cpp
| 44
| 14.704545
| 71
| 0.547278
|
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,074
|
Mathces.cpp
|
OpenGenus_cosmos/code/online_challenges/src/codechef/MATCHES/Mathces.cpp
|
#include <iostream>
#include <vector>
int main() {
std::vector<int> m = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6};
int t;
std::cin >> t;
while (t--) {
long long int a, b, sum = 0;
std::cin >> a >> b;
a += b;
while (a > 0) {
sum += m[a % 10];
a /= 10;
}
std::cout << sum << "\n";
}
}
| 365
|
C++
|
.cpp
| 17
| 15
| 56
| 0.37464
|
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,075
|
EGGFREE.cpp
|
OpenGenus_cosmos/code/online_challenges/src/codechef/EGGFREE/EGGFREE.cpp
|
#include <iostream>
using namespace std;
int tt,n,m,old,it,i,j,k,x[222],y[222],u[222];
bool g[222][222],q;
char r[222];
int main()
{
scanf("%d",&tt);
while (tt--)
{
scanf("%d%d",&n,&m);
memset(u,0,sizeof(u));
memset(g,0,sizeof(g));
memset(r,0,sizeof(r));
for (i=0; i<m; i++)
{
scanf("%d%d",&x[i],&y[i]);
g[x[i]][y[i]]=true;
g[y[i]][x[i]]=true;
}
for (it=1; it<=n; )
{
old=it;
for (i=1; i<=n; i++) if (u[i]==0)
{
q=true;
for (j=1; j<=n && q; j++) if (g[i][j]) for (k=1; k<j; k++) if (g[i][k])
{
if (!g[j][k]) { q=false; break;
}
}
if (q)
{
u[i]=it++;
for (j=1; j<=n; j++) if (g[i][j]) g[i][j]=g[j][i]=0;
break;
}
}
if (old==it) break;
}
if (it<=n) { puts("No solution"); continue;
}
for (i=0; i<m; i++) r[i]=(u[x[i]]<u[y[i]])?'^':'v';
puts(r);
}
return 0;
}
| 981
|
C++
|
.cpp
| 47
| 15.106383
| 80
| 0.3942
|
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,076
|
COVID19.cpp
|
OpenGenus_cosmos/code/online_challenges/src/codechef/COVID19/COVID19.cpp
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int T;
cin>>T;
while(T--)
{
int n;
cin>>n;
std::vector<int> x(n);
for(int &i:x)
cin>>i;
int smallest=10,largest=0,infected=1;
for(int i=1;i<n;i++)
{
if(x[i]-x[i-1]<=2)
infected++;
else
{
largest=max(largest,infected);
smallest=min(smallest,infected);
infected=1;
}
}
if(infected!=0)
{
largest=max(largest,infected);
smallest=min(smallest,infected);
}
smallest=min(smallest,largest);
cout<<smallest<<" "<<largest<<"\n";
}
return 0;
}
| 565
|
C++
|
.cpp
| 35
| 13.028571
| 39
| 0.620952
|
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,078
|
median_of_two_sorted_arrays.cpp
|
OpenGenus_cosmos/code/online_challenges/src/leetcode/median_of_two_sorted_arrays/median_of_two_sorted_arrays.cpp
|
class Solution
{
public:
double findMedianSortedArrays(vector<int> &nums1, vector<int> &nums2)
{
int i = 0, j = 0;
double m;
vector<int> v;
while (i < nums1.size() && j < nums2.size())
{
if (nums1[i] < nums2[j])
{
v.push_back(nums1[i++]);
}
else if (nums1[i] > nums2[j])
{
v.push_back(nums2[j++]);
}
else
{
v.push_back(nums1[i++]);
}
}
while (i < nums1.size())
{
v.push_back(nums1[i++]);
}
while (j < nums2.size())
{
v.push_back(nums2[j++]);
}
for (int i = 0; i < v.size(); ++i)
{
cout << v[i] << " ";
}
int n = v.size();
double r = n % 2 == 0 ? (double)(v[n / 2] + v[n / 2 - 1]) / 2 : v[n / 2];
return r;
}
};
| 959
|
C++
|
.cpp
| 40
| 14.275
| 81
| 0.357998
|
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,079
|
arranging_coins.cpp
|
OpenGenus_cosmos/code/online_challenges/src/leetcode/Arranging_coins/arranging_coins.cpp
|
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
bool possibol(int n, long long row){
long sum = (row*(row+1))/2;
return n>=sum;
}
int arrangeCoins(int n) {
int start=0,end=n,answer=0;
while(start<=end){
int mid=start+(end-start)/2;
if(possibol(n,mid)){
start=mid+1;
answer=mid;
}else{
end=mid-1;
}
}
return answer;
}
};
int main(){
cout<< Solution().arrangeCoins(5) << "\n";
return 0;
}
| 583
|
C++
|
.cpp
| 26
| 14.730769
| 46
| 0.491833
|
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,080
|
maximumsubarray.cpp
|
OpenGenus_cosmos/code/online_challenges/src/leetcode/maximum_subarray/maximumsubarray.cpp
|
//In this corrected code, we compare max_ending + nums[i] with nums[i] to determine if it's beneficial to extend the current subarray or start a new one. This way, the code correctly calculates the maximum subarray sum.
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int len = nums.size();
int max_overall = INT_MIN;
int max_ending = 0;
for (int i = 0; i < len; i++) {
if (max_ending + nums[i] >= nums[i]) {
max_ending += nums[i];
} else {
max_ending = nums[i];
}
if (max_ending > max_overall) {
max_overall = max_ending;
}
}
return max_overall;
}
};
| 762
|
C++
|
.cpp
| 20
| 27.3
| 219
| 0.542254
|
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,081
|
remove_duplicates_from_sorted_list_ii.cpp
|
OpenGenus_cosmos/code/online_challenges/src/leetcode/remove_duplicates_from_sorted_list_ii/remove_duplicates_from_sorted_list_ii.cpp
|
/*
link to problem:https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
difficulty level: Medium
approach:
maintained a previous,current and next pointer in the linked list
if next pointer and curr pointer is having same value then we increment the next pointer till they are unequal or nex becomes NULL
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
ListNode *deleteDuplicates(ListNode *head)
{
if (head == NULL)
return head;
ListNode *curr = head;
ListNode *nex;
ListNode *prev = NULL;
while (curr != NULL)
{
nex = curr->next;
cout << curr->val;
if (nex != NULL and curr->val == nex->val)
{
while (nex != NULL && nex->val == curr->val)
{
nex = nex->next;
}
if (nex != NULL)
{
curr->next = nex->next;
swap(curr->val, nex->val);
// curr=curr->next;
}
else
{
if (head == curr)
head = NULL;
if (prev != NULL)
{
prev->next = NULL;
}
curr = NULL;
}
}
else
{
prev = curr;
curr = curr->next;
}
}
return head;
}
};
| 1,788
|
C++
|
.cpp
| 63
| 17.507937
| 134
| 0.441279
|
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,082
|
longest_substring_without_repetition.cpp
|
OpenGenus_cosmos/code/online_challenges/src/leetcode/longest_substring_without_repetition/longest_substring_without_repetition.cpp
|
/*
*
* Problem: https://leetcode.com/problems/longest-substring-without-repeating-characters/
*
* Solution Description:
* "Sliding Window Approach"
*
* 1. We take two pointers i (left pointer) and j (right pointer).
* 2. We widen our window on the right side at each step (by incrementing j).
* 3. Whenever s[j] has been previously visited, we move the left pointer over
* to the just right of the last visited index of (s[j]). This makes all
* characters in the window from i to j unique again.
* 4. We do a comparison between the current best and the length of the
* window (i - j + 1), and update our solution accordingly.
* 5. When j crosses the size of the string, we stop and we will end up with
* the length of the longset substring without repetition of characters
* as our solution.
*
* Time Complexity: O(N)
*
*/
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
static int lengthOfLongestSubstring(string s) {
int n = s.length();
// Map each character to its last visited index in s
unordered_map<char, int> char_to_index;
int best_len = 0;
for (int i = 0, j = 0; j < n; j++)
{
// Update i if s[j] has been seen before
if (char_to_index.find(s[j]) != char_to_index.end())
i = max(i, char_to_index[s[j]] + 1);
// Length of window = j - i + 1
best_len = max(j - i + 1, best_len);
char_to_index[s[j]] = j;
}
return best_len;
}
};
int main()
{
int T = 3;
string testCases[] = {"abcabcbb", "bbbbb", "pwwkew"};
for (int i = 0; i < T; i++)
{
int sol = Solution::lengthOfLongestSubstring(testCases[i]);
cout << "String: " << testCases[i] << " | Solution: " << sol << endl;
}
return 0;
}
| 1,820
|
C++
|
.cpp
| 53
| 29.886792
| 89
| 0.618966
|
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,083
|
Sqrt(x).cpp
|
OpenGenus_cosmos/code/online_challenges/src/leetcode/Sqrt(x)/Sqrt(x).cpp
|
#include<bits/stdc++.h>
using namespace std;
// O(logn)
class Solution {
public:
int mySqrt(int x) {
double start=0,end=x;
for(int i=0;i<100;++i){
double mid = start + (end - start) / 2;
if(mid*mid<=x){
start = mid;
}else{
end = mid;
}
}
return start;
}
};
int main(){
cout<< Solution().mySqrt(8) << "\n";
return 0;
}
| 445
|
C++
|
.cpp
| 22
| 13.454545
| 50
| 0.463007
|
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,084
|
minimum_number_of_days_to_make_m_bouquets.cpp
|
OpenGenus_cosmos/code/online_challenges/src/leetcode/minimum_number_of_days_to_make_m_bouquets/minimum_number_of_days_to_make_m_bouquets.cpp
|
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
int minDays(vector<int>& bloomDay, int m, int k) {
if(m > (int)bloomDay.size() / k){
return -1;
}
int start=1,end=*max_element(bloomDay.begin(), bloomDay.end()),res=-1;
while(start<=end){
int mid=start+(end-start)/2;
if(possible(bloomDay,m,k,mid)){
end=mid-1;
res=mid;
}else{
start=mid+1;
}
}
return res;
}
bool possible(vector<int>& bloomDay, int m, int k, int waiting_days){
int adj_flowers=0, bouquets=0;
for(int i=0;i<(int)bloomDay.size();++i){
if(bloomDay[i]<=waiting_days){
++adj_flowers;
if(adj_flowers >= k){
adj_flowers=0;
++bouquets;
}
if(bouquets==m){
return true;
}
}else{
adj_flowers=0;
}
}
return false;
}
};
int main(){
vector<int>bloomDay {1,10,3,10,2};
int m=3;
int k=1;
cout<< Solution().minDays(bloomDay, m ,k) << "\n";
return 0;
}
| 1,247
|
C++
|
.cpp
| 46
| 16.847826
| 78
| 0.45508
|
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,085
|
two_sum.cpp
|
OpenGenus_cosmos/code/online_challenges/src/leetcode/two_sum/two_sum.cpp
|
#include<bits/stdc++.h>
using namespace std;
//O(n^2)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target){
vector<int>res;
for(int i=0;i<(int)nums.size();++i){
for(int j=i+1;j<(int)nums.size();++j){
if(nums[i]+nums[j]==target){
res.push_back(i);
res.push_back(j);
return res;
}
}
}
return res;
}
};
int main(){
vector<int>numbers {2,7,11,15};
vector<int>result;
result = Solution().twoSum(numbers, 9);
for(int i=0;i<(int)result.size();++i){
cout<<result[i]<< " ";
}
return 0;
}
| 695
|
C++
|
.cpp
| 28
| 16.892857
| 54
| 0.484115
|
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,086
|
problem_023.cpp
|
OpenGenus_cosmos/code/online_challenges/src/project_euler/problem_023/problem_023.cpp
|
#include <bits/stdc++.h>
using namespace std;
int isAbundant(int x)
{
int sum = 0;
for(int i = 1; i * i <= x; i++)
{
if(x % i == 0)
{
if((x / i) == i)
{
sum += i;
}
else
{
sum += i + (x / i);
}
}
}
sum -= x;
if(sum > x)
{
return true;
}
return false;
}
int main()
{
int max = 28123;
vector<int> abundant;
for(int i = 1; i <= max; i++)
{
if(isAbundant(i))
{
abundant.push_back(i);
}
}
int isSumAbundant[max + 1] = {};
for(int i = 0; i < abundant.size(); i++)
{
for(int j = i; j < abundant.size(); j++)
{
if(abundant[i] + abundant[j] <= max)
{
isSumAbundant[abundant[i] + abundant[j]] = 1;
}
}
}
int ans = 0;
for(int i = 1; i <= max; i++)
{
if(isSumAbundant[i] == 0)
{
ans += i;
}
}
cout << ans;
}
| 1,080
|
C++
|
.cpp
| 58
| 11
| 61
| 0.362475
|
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,087
|
problem_011.cpp
|
OpenGenus_cosmos/code/online_challenges/src/project_euler/problem_011/problem_011.cpp
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n = 20;
int a[n][n];
// Passing the 20 * 20 array as input
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
cin >> a[i][j];
}
}
int dr[8] = {1, 1, 0, -1, -1, -1, 0, 1};
int dc[8] = {0, 1, 1, 1, 0, -1, -1, -1};
int ans = 0;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
for(int k = 0; k < 8; k++)
{
int prod = 1, flag = 0;
for(int steps = 0; steps < 4; steps++)
{
int u = i + steps * dr[k], v = j + steps * dc[k];
if(u >= 0 && u < n && v >= 0 && v < n)
{
prod *= a[u][v];
}
else
{
flag = 1;
}
}
if(flag == 0)
{
ans = max(ans, prod);
}
}
}
}
cout << ans;
}
| 1,110
|
C++
|
.cpp
| 45
| 13.2
| 69
| 0.268797
|
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,088
|
problem_007.cpp
|
OpenGenus_cosmos/code/online_challenges/src/project_euler/problem_007/problem_007.cpp
|
#include <cmath>
#include <iostream>
#include <vector>
std::vector<long long int> primesUpto(size_t limit) // Function that implements the Sieve of Eratosthenes
{
std::vector<bool> primesBoolArray(limit, true);
std::vector<long long int> primesUptoLimit;
primesBoolArray[0] = primesBoolArray[1] = false;
size_t sqrtLimit = std::sqrt(limit) + 1;
for (size_t i = 0; i < sqrtLimit; ++i)
if (primesBoolArray[i])
for (size_t j = (2 * i); j < limit; j += i)
primesBoolArray[j] = false;
for (size_t i = 0; i < primesBoolArray.size(); ++i)
if (primesBoolArray[i])
primesUptoLimit.push_back(i);
return primesUptoLimit;
}
int main()
{
std::vector<long long int> primes = primesUpto(1000000); // Arbitrary limit
std::cout << primes[10000] << "\n";
}
| 835
|
C++
|
.cpp
| 23
| 31.130435
| 105
| 0.638614
|
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,089
|
problem_006.cpp
|
OpenGenus_cosmos/code/online_challenges/src/project_euler/problem_006/problem_006.cpp
|
#include <iostream>
int main()
{
long long int sumOfSquares = 0LL;
long int squareOfSum = 0LL;
for (int n = 1; n <= 100; ++n)
{
sumOfSquares += (n * n);
squareOfSum += n;
}
squareOfSum *= squareOfSum;
std::cout << (squareOfSum - sumOfSquares) << "\n";
}
| 301
|
C++
|
.cpp
| 13
| 18.538462
| 54
| 0.564912
|
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,090
|
problem_102.cpp
|
OpenGenus_cosmos/code/online_challenges/src/project_euler/problem_102/problem_102.cpp
|
#include <cmath>
#include <iostream>
#include <fstream>
struct Coord
{
int x;
int y;
};
int doubleTriangleArea(Coord a, Coord b, Coord c) // Area doesn't actually need to be calculated either,
// just compared for equality
{
/*
* Coordinate area method for Triangle:
*
* A = | (x1(y2 - y3) + x2(y3 - y1) + x3(y1 - y2))/2 |
*
*/
return std::abs((a.x * (b.y - c.y)) + (b.x * (c.y - a.y)) + (c.x * (a.y - b.y)));
}
bool containsOrigin(Coord a, Coord b, Coord c)
{
// A triangle contains a point if the area of it as a whole is
// equivalent to the sum of the areas of the three triangles
// formed with two of the main triangle's points and the point
static Coord origin {0, 0};
return doubleTriangleArea(a, b, c) ==
(
doubleTriangleArea(origin, a, b) +
doubleTriangleArea(origin, b, c) +
doubleTriangleArea(origin, a, c)
);
}
int main()
{
std::ifstream trianglesFile("triangles.txt");
int numOriginTriangles = 0;
if (trianglesFile.is_open())
{
Coord a, b, c;
char comma; // Since each part of a coordinate is comma separated
while (trianglesFile >> a.x >> comma >> a.y >> comma >> b.x >> comma >> b.y >> comma >>
c.x >> comma >> c.y)
if (containsOrigin(a, b, c))
++numOriginTriangles;
trianglesFile.close();
}
else
std::cout <<
"Unable to open the file triangles.txt! Please check if the file exists in the appropriate location!\n";
std::cout << numOriginTriangles << "\n";
}
| 1,659
|
C++
|
.cpp
| 51
| 25.941176
| 116
| 0.573924
|
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,093
|
problem_009.cpp
|
OpenGenus_cosmos/code/online_challenges/src/project_euler/problem_009/problem_009.cpp
|
#include <iostream>
int main()
{
for (int i = 1; i < 1000; ++i)
for (int j = 1; j < 1000; ++j)
{
for (int k = 1; k < 1000; ++k)
if (((i * i) + (j * j) == (k * k)) && ((i + j + k) == 1000))
{
std::cout << i * j * k << "\n";
goto OutsideLoop;
}
}
OutsideLoop: // Need this for breaking outside all three loops
return 0;
}
| 457
|
C++
|
.cpp
| 16
| 19.25
| 76
| 0.368182
|
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,094
|
problem_021.cpp
|
OpenGenus_cosmos/code/online_challenges/src/project_euler/problem_021/problem_021.cpp
|
#include <iostream>
int sumProperDivisors(int n)
{
int sum = 0;
for (int i = 1; i * i <= n; ++i)
if (n % i == 0)
{
sum += i;
if (n / i != i)
sum += n / i;
}
return sum - n;
}
bool isAmicableNumber(int n)
{
int m = sumProperDivisors(n);
return m != n && sumProperDivisors(m) == n;
}
int main()
{
int result = 0;
for (int i = 1; i < 10000; ++i)
if (isAmicableNumber(i))
result += i;
std::cout << result << std::endl;
return 0;
}
| 551
|
C++
|
.cpp
| 27
| 14.814815
| 47
| 0.471154
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.