Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trash talk - adding algorithms #14

Merged
merged 3 commits into from
Aug 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 46 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,51 @@
"summy_ave.h": "c",
"sortme.h": "c",
"*.php": "php",
"random": "cpp"
"random": "cpp",
"array": "cpp",
"atomic": "cpp",
"bit": "cpp",
"*.tcc": "cpp",
"cctype": "cpp",
"clocale": "cpp",
"cmath": "cpp",
"compare": "cpp",
"concepts": "cpp",
"cstdarg": "cpp",
"cstddef": "cpp",
"cstdint": "cpp",
"cstdio": "cpp",
"cstdlib": "cpp",
"cwchar": "cpp",
"cwctype": "cpp",
"deque": "cpp",
"map": "cpp",
"unordered_map": "cpp",
"vector": "cpp",
"exception": "cpp",
"algorithm": "cpp",
"functional": "cpp",
"iterator": "cpp",
"memory": "cpp",
"memory_resource": "cpp",
"numeric": "cpp",
"optional": "cpp",
"string": "cpp",
"string_view": "cpp",
"system_error": "cpp",
"tuple": "cpp",
"type_traits": "cpp",
"utility": "cpp",
"initializer_list": "cpp",
"iosfwd": "cpp",
"iostream": "cpp",
"istream": "cpp",
"limits": "cpp",
"new": "cpp",
"ostream": "cpp",
"ranges": "cpp",
"stdexcept": "cpp",
"streambuf": "cpp",
"typeinfo": "cpp"
}
}
40 changes: 40 additions & 0 deletions cc_files/algos/a1.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#include <iostream>
#include <vector>
#include <sstream>
#include <algorithm>

double median(std::vector<int>& nums) {
// Sort the array in ascending order
std::sort(nums.begin(), nums.end());
size_t length = nums.size();
size_t midIndex = length / 2;

// Check if the array has odd or even length
if (length % 2 == 0) {
// For even length, take the average of the middle two elements
return static_cast<double>(nums[midIndex] + nums[midIndex - 1]) / 2;
} else {
// For odd length, return the middle element
return static_cast<double>(nums[midIndex]);
}
}

int main() {
// Read input from the user
std::cout << "Enter the numbers separated by spaces: ";
std::string inputLine;
std::getline(std::cin, inputLine);

std::vector<int> nums;
std::istringstream iss(inputLine);
int num;
while (iss >> num) {
nums.push_back(num);
}

// Calculate and display the median
double result = median(nums);
std::cout << "Median: " << result << std::endl;

return 0;
}
76 changes: 76 additions & 0 deletions cc_files/bank_me/bank1.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
#include <iostream>
#include <string>
#include <map>

class BankAccount {
private:
int accountNumber;
std::string accountHolderName;
double balance;

public:
BankAccount(int accNum, const std::string& name, double initialBalance)
: accountNumber(accNum), accountHolderName(name), balance(initialBalance) {}

int getAccountNumber() const { return accountNumber; }
const std::string& getAccountHolderName() const { return accountHolderName; }
double getBalance() const { return balance; }

void deposit(double amount) { balance += amount; }
bool withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
return true;
}
return false;
}
};

class BankingSystem {
private:
std::map<int, BankAccount> accounts;
int nextAccountNumber;

public:
BankingSystem() : nextAccountNumber(1000) {}

int createAccount(const std::string& name, double initialBalance) {
int newAccountNumber = nextAccountNumber++;
BankAccount newAccount(newAccountNumber, name, initialBalance);
accounts.insert({ newAccountNumber, newAccount });
return newAccountNumber;
}

BankAccount* findAccount(int accountNumber) {
auto it = accounts.find(accountNumber);
return (it != accounts.end()) ? &it->second : nullptr;
}
};

int main() {
BankingSystem bankingSystem;

int accountNumber = bankingSystem.createAccount("John Doe", 1000.0);
std::cout << "Account created with number: " << accountNumber << std::endl;

BankAccount* account = bankingSystem.findAccount(accountNumber);
if (account) {
std::cout << "Account holder: " << account->getAccountHolderName() << std::endl;
std::cout << "Balance: " << account->getBalance() << std::endl;

account->deposit(500.0);
std::cout << "Deposited 500.0" << std::endl;
std::cout << "Balance: " << account->getBalance() << std::endl;

if (account->withdraw(200.0)) {
std::cout << "Withdrawn 200.0" << std::endl;
std::cout << "Balance: " << account->getBalance() << std::endl;
} else {
std::cout << "Insufficient balance for withdrawal." << std::endl;
}
} else {
std::cout << "Account not found." << std::endl;
}

return 0;
}
74 changes: 74 additions & 0 deletions cc_files/ctmp6.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
#include <iostream>
#include <vector>
#include <string>

bool isSafe(
int row,
int col,
const std::vector<int>& left_diagonal,
const std::vector<int>& right_diagonal,
const std::vector<int>& vertical
) {
return (left_diagonal[row + col] == 0 &&
right_diagonal[row - col + right_diagonal.size() - 1] == 0 &&
vertical[col] == 0);
}

void depthFirstSearch(
std::vector<std::vector<std::string>>& boards,
std::vector<std::string>& board,
const std::vector<int>& left_diagonal,
const std::vector<int>& right_diagonal,
const std::vector<int>& vertical,
int row,
int n
) {
if (row == n) {
boards.push_back(board);
return;
}

for (int col = 0; col < n; col++) {
if (isSafe(row, col, left_diagonal, right_diagonal, vertical)) {
std::vector<int> new_left_diagonal = left_diagonal;
std::vector<int> new_right_diagonal = right_diagonal;
std::vector<int> new_vertical = vertical;

new_left_diagonal[row + col] = 1;
new_right_diagonal[row - col + right_diagonal.size() - 1] = 1;
new_vertical[col] = 1;
board[row][col] = 'Q';

depthFirstSearch(boards, board, new_left_diagonal, new_right_diagonal, new_vertical, row + 1, n);

board[row][col] = '.';
}
}
}

void nQueensSolution(int n) {
std::vector<std::vector<std::string>> boards;
std::vector<std::string> board(n, std::string(n, '.'));

// Vectors to keep track of occupied diagonals and vertical positions
std::vector<int> left_diagonal(2 * n - 1, 0);
std::vector<int> right_diagonal(2 * n - 1, 0);
std::vector<int> vertical(n, 0);

depthFirstSearch(boards, board, left_diagonal, right_diagonal, vertical, 0, n);

// Print all the boards
for (const auto& board : boards) {
for (const auto& row : board) {
std::cout << row << std::endl;
}
std::cout << std::endl;
}

std::cout << boards.size() << " solutions were found." << std::endl;
}

int main() {
nQueensSolution(4);
return 0;
}
39 changes: 39 additions & 0 deletions js/algos/a1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
function median(nums) {
// Sort the array in ascending order
const sortedList = nums.slice().sort((a, b) => a - b);
const length = sortedList.length;
const midIndex = Math.floor(length / 2);

// Check if the array has odd or even length
if (length % 2 === 0) {
// For even length, take the average of the middle two elements
return (sortedList[midIndex] + sortedList[midIndex - 1]) / 2;
} else {
// For odd length, return the middle element
return sortedList[midIndex];
}
}

function main() {
// Check if the user provided arguments
if (process.argv.length <= 2) {
console.log("Usage: node median.js <num1> <num2> <num3> ...");
return;
}

// Parse command-line arguments to integers
const nums = process.argv.slice(2).map(Number);

// Check if all arguments are valid numbers
if (nums.some(isNaN)) {
console.log("Invalid input. Please provide only numeric values.");
return;
}

const result = median(nums);
console.log(`Median: ${result}`);
}

if (require.main === module) {
main();
}
42 changes: 42 additions & 0 deletions py/algos/a1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import sys

def median(nums: list[int]) -> int | float:
"""
Find median of a list of numbers.
Wiki: https://en.wikipedia.org/wiki/Median

Args:
nums: List of numbers

Returns:
Median.
"""
sorted_list = sorted(nums)
length = len(sorted_list)
mid_index = length // 2
return (
(sorted_list[mid_index] + sorted_list[mid_index - 1]) / 2
if length % 2 == 0
else sorted_list[mid_index]
)


def main():
# Check if the user provided arguments
if len(sys.argv) <= 1:
print("Usage: python median.py <num1> <num2> <num3> ...")
return

# Parse command-line arguments to integers
try:
nums = [int(arg) for arg in sys.argv[1:]]
except ValueError:
print("Invalid input. Please provide only integer values.")
return

result = median(nums)
print(f"Median: {result}")


if __name__ == "__main__":
main()
22 changes: 22 additions & 0 deletions py/algos/a2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import cmath

def riemann_zeta(s, terms=100):
"""
Calculate the Riemann zeta function for a given complex number s.

Args:
s (complex): The complex number for which to calculate the Riemann zeta function.
terms (int, optional): The number of terms to use in the series approximation. Default is 100.

Returns:
complex: The value of the Riemann zeta function for the given complex number.
"""
result = 0
for n in range(1, terms+1):
result += 1 / (n**s)
return result

# Example usage
s = 1 + 2j
result = riemann_zeta(s)
print(f"zeta({s}) =", result)