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

Added Some Algorithms.!! #3355 #3546

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
26 changes: 26 additions & 0 deletions One-time pad cipher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import random

def generate_key(length):
"""Generates a random key of the specified length."""
return bytes([random.randint(0, 255) for _ in range(length)])

def encrypt(plaintext, key):
"""Encrypts the plaintext using the provided key."""
ciphertext = bytes([plaintext[i] ^ key[i] for i in range(len(plaintext))])
return ciphertext

def decrypt(ciphertext, key):
"""Decrypts the ciphertext using the provided key."""
plaintext = bytes([ciphertext[i] ^ key[i] for i in range(len(ciphertext))])
return plaintext

# Example usage
plaintext = b"SECRET MESSAGE"
key = generate_key(len(plaintext))
ciphertext = encrypt(plaintext, key)
decrypted_text = decrypt(ciphertext, key)

print("Plaintext:", plaintext)
print("Key:", key)
print("Ciphertext:", ciphertext)
print("Decrypted text:", decrypted_text)
32 changes: 32 additions & 0 deletions Q-learning/Q-learning.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import numpy as np

# Q-learning function
def q_learning(env, learning_rate=0.1, discount_factor=0.9, epsilon=0.1, num_episodes=1000):
# Initialize Q-table with zeros
Q = np.zeros((env.observation_space.n, env.action_space.n))

# Iterate over episodes
for episode in range(num_episodes):
# Reset the environment for each episode
state = env.reset()
done = False

# Iterate over timesteps
while not done:
# Choose action using epsilon-greedy strategy
if np.random.uniform(0, 1) < epsilon:
action = env.action_space.sample() # Exploration
else:
action = np.argmax(Q[state, :]) # Exploitation

# Take the chosen action and observe the reward and new state
next_state, reward, done, info = env.step(action)

# Update Q-value of the current state-action pair
Q[state, action] = Q[state, action] + learning_rate * \
(reward + discount_factor * np.max(Q[next_state, :]) - Q[state, action])

# Set the current state to the new state
state = next_state

return Q
19 changes: 19 additions & 0 deletions mind_games.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import random

number = random.randint(1, 100)
print("I'm thinking of a number between 1 and 100. Guess what it is!")

guess = None
while guess != number:
try:
guess = int(input())
except ValueError:
print("Please enter a valid integer!")
continue

if guess < number:
print("Too low! Guess again.")
elif guess > number:
print("Too high! Guess again.")
else:
print("Correct! You win!")
44 changes: 44 additions & 0 deletions set.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
class HashSet:
def __init__(self):
self.buckets = [[] for _ in range(16)]
self.size = 0

def __contains__(self, item):
hash_code = hash(item)
bucket = self.buckets[hash_code % len(self.buckets)]
for element in bucket:
if element == item:
return True
return False

def add(self, item):
if item not in self:
hash_code = hash(item)
bucket = self.buckets[hash_code % len(self.buckets)]
bucket.append(item)
self.size += 1

if self.size >= len(self.buckets):
self._resize()

def remove(self, item):
hash_code = hash(item)
bucket = self.buckets[hash_code % len(self.buckets)]
for i, element in enumerate(bucket):
if element == item:
bucket.pop(i)
self.size -= 1
return True
return False

def _resize(self):
new_buckets = [[] for _ in range(len(self.buckets) * 2)]
for bucket in self.buckets:
for element in bucket:
hash_code = hash(element)
new_bucket = new_buckets[hash_code % len(new_buckets)]
new_bucket.append(element)
self.buckets = new_buckets

def __len__(self):
return self.size
71 changes: 71 additions & 0 deletions sort/Dutch_National_Flag_Problem.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// C++ program to sort an array
// with 0, 1 and 2 in a single pass

#include <bits/stdc++.h>
using namespace std;

// Function to sort the input array,
// the array is assumed
// to have values in {0, 1, 2}
void sort012(int a[], int arr_size)
{
int lo = 0;
int hi = arr_size - 1;
int mid = 0;

// Iterate till all the elements
// are sorted
while (mid <= hi) {
switch (a[mid]) {

// If the element is 0
case 0:
swap(a[lo++], a[mid++]);
break;

// If the element is 1 .
case 1:
mid++;
break;

// If the element is 2
case 2:
swap(a[mid], a[hi--]);
break;
}
}
}

// Function to print array arr[]
void printArray(int arr[], int arr_size)
{
// Iterate and print every element
for (int i = 0; i < arr_size; i++)
cout << arr[i] << " ";
}

int main()
{
int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 };
int n = sizeof(arr) / sizeof(arr[0]);

sort012(arr, n);

printArray(arr, n);

return 0;
}

/*
Time Complexity: O(n), Only one traversal of the array is needed.
Space Complexity: O(1), No extra space is required.
*/

/*
Disclaimer:
* RoyCoding8 (Me) isn't the original author of this code. The original author is shivesh41kr.
* I have just updated the decription to account for the simplification of the file name.

Description: The problem sorts an array containing 0,1 and 2 in a single iteration. (The Dutch national flag problem).

*/