From 10036e99d3cbc6aac2d668df79e3f4f1d1092857 Mon Sep 17 00:00:00 2001 From: vivekvernekar02 Date: Tue, 7 Oct 2025 00:00:05 +0530 Subject: [PATCH 1/2] Add Snake Water Gun game implementation - Implements Snake Water Gun game (similar to Rock Paper Scissors) - Game rules: Snake drinks Water, Water rusts Gun, Gun shoots Snake - Features single game and multiple rounds modes - Includes input validation and user-friendly interface - Added comprehensive doctests for core functions - Follows Python type hints and coding standards Fixes #12987 --- other/snake_water_gun.py | 239 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 239 insertions(+) create mode 100644 other/snake_water_gun.py diff --git a/other/snake_water_gun.py b/other/snake_water_gun.py new file mode 100644 index 000000000000..f8bcd7ec3fc9 --- /dev/null +++ b/other/snake_water_gun.py @@ -0,0 +1,239 @@ +""" +Snake Water Gun Game + +This is a simple implementation of the Snake Water Gun game (similar to Rock Paper Scissors). +The rules are: +- Snake drinks Water (Snake wins) +- Water rusts Gun (Water wins) +- Gun shoots Snake (Gun wins) + +Author: TheAlgorithms/Python +""" + +import random + + +def get_computer_choice() -> str: + """ + Generate a random choice for the computer. + + Returns: + str: Computer's choice ('s' for snake, 'w' for water, 'g' for gun) + + Examples: + >>> choice = get_computer_choice() + >>> choice in ['s', 'w', 'g'] + True + """ + choices = ['s', 'w', 'g'] + return random.choice(choices) + + +def get_choice_name(choice: str) -> str: + """ + Convert choice letter to full name. + + Args: + choice (str): Choice letter ('s', 'w', or 'g') + + Returns: + str: Full name of the choice + + Examples: + >>> get_choice_name('s') + 'snake' + >>> get_choice_name('w') + 'water' + >>> get_choice_name('g') + 'gun' + >>> get_choice_name('x') + 'unknown' + """ + choice_names = { + 's': 'snake', + 'w': 'water', + 'g': 'gun' + } + return choice_names.get(choice, 'unknown') + + +def determine_winner(player_choice: str, computer_choice: str) -> str: + """ + Determine the winner based on game rules. + Rules: Snake drinks Water, Water rusts Gun, Gun shoots Snake + + Args: + player_choice (str): Player's choice ('s', 'w', or 'g') + computer_choice (str): Computer's choice ('s', 'w', or 'g') + + Returns: + str: Result of the game ('win', 'lose', or 'draw') + + Examples: + >>> determine_winner('s', 's') + 'draw' + >>> determine_winner('s', 'w') # Snake drinks Water + 'win' + >>> determine_winner('w', 'g') # Water rusts Gun + 'win' + >>> determine_winner('g', 's') # Gun shoots Snake + 'win' + >>> determine_winner('w', 's') # Snake drinks Water + 'lose' + >>> determine_winner('g', 'w') # Water rusts Gun + 'lose' + >>> determine_winner('s', 'g') # Gun shoots Snake + 'lose' + """ + if player_choice == computer_choice: + return 'draw' + + # Define winning conditions for player + winning_conditions = { + 's': 'w', # Snake drinks Water + 'w': 'g', # Water rusts Gun + 'g': 's' # Gun shoots Snake + } + + if winning_conditions[player_choice] == computer_choice: + return 'win' + else: + return 'lose' + + +def play_single_game() -> None: + """ + Play a single round of Snake Water Gun game. + """ + print("\n=== Snake Water Gun Game ===") + print("Rules:") + print("- Snake drinks Water (Snake wins)") + print("- Water rusts Gun (Water wins)") + print("- Gun shoots Snake (Gun wins)") + print() + + # Get player input + while True: + player_choice = input("Enter your choice: s for snake, w for water, g for gun: ").lower().strip() + if player_choice in ['s', 'w', 'g']: + break + print("Invalid choice! Please enter 's', 'w', or 'g'.") + + # Get computer choice + computer_choice = get_computer_choice() + + # Display choices + print(f"You chose {get_choice_name(player_choice)}") + print(f"Computer chose {get_choice_name(computer_choice)}") + + # Determine and display result + result = determine_winner(player_choice, computer_choice) + + if result == 'draw': + print("It's a draw!") + elif result == 'win': + print("You win!") + else: + print("You lose!") + + +def play_multiple_games() -> None: + """ + Play multiple rounds and keep score. + """ + player_score = 0 + computer_score = 0 + draws = 0 + + print("\n=== Snake Water Gun - Multiple Rounds ===") + + while True: + try: + rounds = int(input("How many rounds would you like to play? ")) + if rounds > 0: + break + print("Please enter a positive number.") + except ValueError: + print("Please enter a valid number.") + + for round_num in range(1, rounds + 1): + print(f"\n--- Round {round_num} ---") + + # Get player input + while True: + player_choice = input("Enter your choice: s for snake, w for water, g for gun: ").lower().strip() + if player_choice in ['s', 'w', 'g']: + break + print("Invalid choice! Please enter 's', 'w', or 'g'.") + + # Get computer choice + computer_choice = get_computer_choice() + + # Display choices + print(f"You chose {get_choice_name(player_choice)}") + print(f"Computer chose {get_choice_name(computer_choice)}") + + # Determine result + result = determine_winner(player_choice, computer_choice) + + if result == 'draw': + print("It's a draw!") + draws += 1 + elif result == 'win': + print("You win this round!") + player_score += 1 + else: + print("Computer wins this round!") + computer_score += 1 + + # Display current score + print(f"Score - You: {player_score}, Computer: {computer_score}, Draws: {draws}") + + # Final results + print(f"\n=== Final Results ===") + print(f"Your score: {player_score}") + print(f"Computer score: {computer_score}") + print(f"Draws: {draws}") + + if player_score > computer_score: + print("๐ŸŽ‰ Congratulations! You won overall!") + elif computer_score > player_score: + print("๐Ÿ’ป Computer wins overall! Better luck next time!") + else: + print("๐Ÿค It's a tie overall! Great game!") + + +def main() -> None: + """ + Main function to run the Snake Water Gun game. + """ + print("Welcome to Snake Water Gun Game!") + + while True: + print("\nChoose game mode:") + print("1. Single game") + print("2. Multiple rounds") + print("3. Exit") + + choice = input("Enter your choice (1/2/3): ").strip() + + if choice == '1': + play_single_game() + elif choice == '2': + play_multiple_games() + elif choice == '3': + print("Thanks for playing! Goodbye!") + break + else: + print("Invalid choice! Please enter 1, 2, or 3.") + + # Ask if player wants to continue + if choice in ['1', '2']: + play_again = input("\nWould you like to play again? (y/n): ").lower().strip() + if play_again != 'y': + print("Thanks for playing! Goodbye!") + break + + +if __name__ == "__main__": + main() From 3d1ef778171ed5963228de23c0749fad84e140ae Mon Sep 17 00:00:00 2001 From: vivekvernekar02 Date: Tue, 7 Oct 2025 00:20:17 +0530 Subject: [PATCH 2/2] Add comprehensive README for other/ directory - Created detailed documentation for all 27 algorithms in other/ directory - Enhanced visual design with modern markdown formatting - Added categorized sections: Games, Search, Math, Security, Caching, etc. - Included complexity analysis and feature highlights - Added professional badges and community links - Highlighted Snake Water Gun game implementation - Provided contribution guidelines and educational notes --- other/README.md | 434 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 434 insertions(+) create mode 100644 other/README.md diff --git a/other/README.md b/other/README.md new file mode 100644 index 000000000000..545939c8fc26 --- /dev/null +++ b/other/README.md @@ -0,0 +1,434 @@ +
+ +# ๐Ÿ”ง Other Algorithms + +Algorithm Count +Python Version +Category + +*A collection of diverse algorithms and implementations for educational purposes* + +--- + +
+ +This directory contains **27 unique algorithms** and implementations that don't fit into specific categories but are valuable for learning computer science concepts, problem-solving techniques, and algorithmic thinking. + +## ๐ŸŽฎ Games & Interactive Algorithms + + + + + + +
+ +### ๐Ÿ Snake Water Gun Game +**File**: [`snake_water_gun.py`](snake_water_gun.py) + +A Python implementation of the classic Snake Water Gun game (similar to Rock Paper Scissors). + +**๐ŸŽฏ Game Rules:** +- ๐Ÿ Snake drinks ๐Ÿ’ง Water (Snake wins) +- ๐Ÿ’ง Water rusts ๐Ÿ”ซ Gun (Water wins) +- ๐Ÿ”ซ Gun shoots ๐Ÿ Snake (Gun wins) + + + +**โœจ Features:** +- ๐ŸŽฎ Interactive command-line interface +- ๐ŸŽฏ Single game and multiple rounds modes +- ๐Ÿ“Š Score tracking for multiple rounds +- โœ… Input validation and error handling +- ๐Ÿงช Comprehensive doctests + +**๐Ÿš€ Usage:** +```bash +python3 snake_water_gun.py +``` + +
+ +## ๐Ÿ” Search & Selection Algorithms + +
+ +| Algorithm | File | Description | Complexity | +|-----------|------|-------------|------------| +| ๐ŸŽฏ **Activity Selection** | [`activity_selection.py`](activity_selection.py) | Greedy approach to select maximum non-overlapping activities | O(n log n) | +| ๐ŸŽฒ **Guess The Number** | [`guess_the_number_search.py`](guess_the_number_search.py) | Binary search implementation for number guessing | O(log n) | + +
+ +## ๐Ÿงฎ Mathematical Algorithms + + + + + + + +
+ +### ๐Ÿ“… Doomsday Algorithm +**File**: [`doomsday.py`](doomsday.py) + +๐Ÿ—“๏ธ Calculates the day of the week for any given date using John Conway's Doomsday algorithm. + +**Features:** +- โšก Fast date calculation +- ๐ŸŽฏ High accuracy +- ๐Ÿ“š Educational value + + + +### ๐Ÿฐ Gauss Easter +**File**: [`gauss_easter.py`](gauss_easter.py) + +๐ŸŒธ Calculates the date of Easter for any given year using Gauss's algorithm. + +**Features:** +- ๐Ÿ“Š Mathematical precision +- ๐Ÿ”ข Works for any year +- โ›ช Religious calendar + + + +### ๐Ÿ“ˆ H-Index Calculator +**File**: [`h_index.py`](h_index.py) + +๐ŸŽ“ Calculates the H-index of a researcher based on their publication citations. + +**Features:** +- ๐Ÿ“Š Research metrics +- ๐Ÿ“š Academic analysis +- ๐Ÿ† Impact measurement + +
+ +## ๐Ÿ” Security & Cryptography + +
+ +| ๐Ÿ›ก๏ธ Algorithm | File | Description | Security Level | +|--------------|------|-------------|----------------| +| ๐Ÿ”‘ **Password Generator** | [`password.py`](password.py) | Generates secure passwords with customizable options | ๐Ÿ”’ High | +| ๐Ÿ” **SDES Encryption** | [`sdes.py`](sdes.py) | Simplified Data Encryption Standard implementation | ๐Ÿ”’ Educational | + +
+ +## ๐Ÿ—ƒ๏ธ Caching Algorithms + + + + + + + +
+ +### ๐Ÿ”„ LRU Cache +**File**: [`lru_cache.py`](lru_cache.py) + +โšก **O(1)** operations + +๐ŸŽฏ Least Recently Used eviction policy + +๐Ÿ“Š Optimal for temporal locality + + + +### ๐Ÿ“ˆ LFU Cache +**File**: [`lfu_cache.py`](lfu_cache.py) + +๐Ÿ”ข **Frequency-based** eviction + +๐Ÿ“Š Tracks access patterns + +๐ŸŽฏ Best for skewed access + + + +### ๐Ÿ”„ LRU Alternative +**File**: [`least_recently_used.py`](least_recently_used.py) + +๐Ÿ”ง **Alternative** implementation + +๐Ÿ“š Educational comparison + +โš™๏ธ Different approach + +
+ +## ๐Ÿ”ข Data Structure Algorithms + +
+ +| ๐Ÿ“Š Algorithm | File | Description | Use Case | +|-------------|------|-------------|----------| +| ๐Ÿ”„ **Alternative List Arrange** | [`alternative_list_arrange.py`](alternative_list_arrange.py) | Alternating pattern arrangement | Data visualization | +| ๐Ÿ“ˆ **Maximum Subsequence** | [`maximum_subsequence.py`](maximum_subsequence.py) | Kadane's algorithm implementation | Dynamic programming | +| ๐Ÿ”— **Nested Brackets** | [`nested_brackets.py`](nested_brackets.py) | Bracket validation and processing | Parsing & validation | +| ๐Ÿ“ฆ **Number Container** | [`number_container_system.py`](number_container_system.py) | Efficient number storage system | Data management | + +
+ +## ๐ŸŽฒ Random Number Generation + + + + + + +
+ +### ๐Ÿ”€ Fischer-Yates Shuffle +**File**: [`fischer_yates_shuffle.py`](fischer_yates_shuffle.py) + +๐ŸŽฏ **Perfect randomization** algorithm for array permutation + +**Features:** +- โšก O(n) time complexity +- ๐ŸŽฒ Unbiased shuffling +- ๐Ÿ“Š Uniform distribution + + + +### ๐Ÿ”ข Linear Congruential Generator +**File**: [`linear_congruential_generator.py`](linear_congruential_generator.py) + +๐ŸŽฒ **Pseudorandom number** generation algorithm + +**Features:** +- โšก Fast generation +- ๐Ÿ”„ Deterministic sequence +- ๐Ÿ“š Educational PRNG + +
+ +## ๐Ÿงฉ Pattern & Logic Algorithms + + + + + + + +
+ +### ๐Ÿง  DPLL Algorithm +**File**: [`davis_putnam_logemann_loveland.py`](davis_putnam_logemann_loveland.py) + +๐Ÿ” **Boolean satisfiability** solver + +๐ŸŽฏ SAT problem resolution + +๐Ÿงฎ Logic programming + + + +### ๐Ÿ’Ž Magic Diamond +**File**: [`magicdiamondpattern.py`](magicdiamondpattern.py) + +โœจ **Pattern generation** algorithm + +๐ŸŽจ Visual mathematics + +๐Ÿ”ข Number arrangements + + + +### ๐Ÿ”„ Quine Program +**File**: [`quine.py`](quine.py) + +๐Ÿชž **Self-replicating** code + +๐Ÿค– Meta-programming + +๐Ÿงฌ Code genetics + +
+ +## ๐Ÿ›๏ธ System Algorithms + + + + + + +
+ +### ๐Ÿฆ Banker's Algorithm +**File**: [`bankers_algorithm.py`](bankers_algorithm.py) + +๐Ÿ›ก๏ธ **Deadlock avoidance** in operating systems + +**Key Features:** +- ๐Ÿ”’ Resource allocation safety +- ๐ŸŽฏ Deadlock prevention +- ๐Ÿ’ป OS fundamentals +- ๐Ÿ“Š State analysis + + + +### ๐Ÿ—ผ Tower of Hanoi +**File**: [`tower_of_hanoi.py`](tower_of_hanoi.py) + +๐Ÿงฉ **Classic recursive** puzzle solution + +**Key Features:** +- ๐Ÿ”„ Recursive thinking +- ๐ŸŽฏ Problem decomposition +- ๐Ÿ“ˆ Exponential complexity +- ๐Ÿง  Mathematical beauty + +
+ +## ๐Ÿ” Advanced Search Algorithms + +
+ +| ๐ŸŽฏ Algorithm | File | Description | Technique | Complexity | +|-------------|------|-------------|-----------|------------| +| ๐Ÿ“ **Graham Scan** | [`graham_scan.py`](graham_scan.py) | Convex hull computation | Geometric | O(n log n) | +| ๐Ÿ”ค **Word Search** | [`word_search.py`](word_search.py) | 2D grid word finding | Backtracking | O(4^L) | + +
+ +## ๐Ÿ“Š Scoring & Voting Algorithms + + + + + + +
+ +### ๐Ÿ—ณ๏ธ Majority Vote Algorithm +**File**: [`majority_vote_algorithm.py`](majority_vote_algorithm.py) + +๐ŸŽฏ **Boyer-Moore** majority element finder + +**Advantages:** +- โšก O(n) time complexity +- ๐Ÿ’พ O(1) space complexity +- ๐ŸŽฏ Single pass algorithm + + + +### ๐Ÿ“ˆ Scoring Algorithm +**File**: [`scoring_algorithm.py`](scoring_algorithm.py) + +๐Ÿ“Š **Generic scoring** system implementation + +**Applications:** +- ๐Ÿ† Competition ranking +- ๐Ÿ“Š Performance metrics +- ๐ŸŽฏ Decision making + +
+ +## ๐ŸŽฏ Greedy Algorithms + +
+ +### ๐Ÿƒโ€โ™‚๏ธ Greedy Algorithm Collection +**File**: [`greedy.py`](greedy.py) + +๐ŸŽฏ **Optimization problems** solved with greedy approach + +| Feature | Description | +|---------|-------------| +| โšก **Speed** | Fast local optimal choices | +| ๐ŸŽฏ **Simplicity** | Easy to understand and implement | +| ๐Ÿ“Š **Applications** | Scheduling, graph problems, optimization | +| ๐Ÿง  **Strategy** | Make locally optimal choice at each step | + +
+ +--- + +
+ +## ๐Ÿš€ Getting Started + + + + + + + + +
+ +### ๐Ÿ“š Documentation +**Comprehensive** + +Every algorithm includes detailed docstrings and examples + + + +### ๐Ÿงช Testing +**Verified** + +Doctests and test cases ensure correctness + + + +### โšก Complexity +**Analyzed** + +Time and space complexity documented + + + +### ๐ŸŽฏ Examples +**Practical** + +Real-world usage examples provided + +
+ +--- + +## ๐Ÿ“ Contributing Guidelines + +
+ +### โœ… Code Standards +- ๐Ÿ Follow Python PEP 8 style guidelines +- ๐Ÿ“– Include comprehensive docstrings with examples +- ๐Ÿงช Add doctests for verification +- ๐Ÿท๏ธ Use descriptive variable and function names +- โฑ๏ธ Document time/space complexity + +### ๐ŸŽฏ Quality Checklist +- [ ] Code compiles without errors +- [ ] All doctests pass +- [ ] Proper type hints included +- [ ] Clear documentation provided +- [ ] Educational value demonstrated + +
+ +--- + +
+ +## ๐Ÿ“š Educational Purpose + +> *These implementations are designed for **educational purposes** to help understand algorithmic concepts and problem-solving techniques.* + +**โš ๏ธ Note**: Implementations may not be optimized for production use. They prioritize clarity and learning over performance. + +--- + +### ๐Ÿค Community + +[![Discord](https://img.shields.io/badge/Discord-Join%20Us-7289da?style=for-the-badge&logo=discord)](https://the-algorithms.com/discord) +[![Gitter](https://img.shields.io/badge/Gitter-Chat-ff69b4?style=for-the-badge&logo=gitter)](https://gitter.im/TheAlgorithms/community) +[![GitHub](https://img.shields.io/badge/GitHub-Contribute-181717?style=for-the-badge&logo=github)](https://github.com/TheAlgorithms/Python) + +**Happy Learning! ๐ŸŽ‰** + +