diff --git a/AI_Chatbot/README.md b/AI_Chatbot/README.md new file mode 100644 index 00000000..15cf38f6 --- /dev/null +++ b/AI_Chatbot/README.md @@ -0,0 +1,82 @@ +# AI Chatbot - Intelligent Conversational Assistant + +A powerful and interactive AI chatbot built with Python that can engage in meaningful conversations and provide various helpful services. + +## Features + +- šŸ¤– **Intelligent Conversations**: Natural language processing for engaging dialogue +- šŸŒ¤ļø **Weather Information**: Get current weather for any city +- 🧮 **Mathematical Calculations**: Safe evaluation of mathematical expressions +- šŸ˜„ **Entertainment**: Tell jokes and stories +- šŸ’» **Programming Help**: Get tips and advice for coding +- ā° **Time & Date**: Current time and date information +- šŸ’¾ **Conversation History**: Save and recall previous conversations +- šŸŽÆ **Context Awareness**: Remembers user name and conversation flow + +## Installation + +```bash +# Clone the repository +git clone +cd AI_Chatbot + +# Install required dependencies +pip install requests datetime random json re math +``` + +## Usage + +```bash +python chatbot.py +``` + +## Example Conversations + +``` +You: Hello! +AI Assistant: Nice to meet you, John! Hello! I'm your AI assistant. How can I help you today? + +You: What's the weather in Jakarta? +AI Assistant: The weather in Jakarta is: Sunny, 32°C + +You: Calculate 15 * 8 + 32 +AI Assistant: The result is: 152 + +You: Tell me a joke +AI Assistant: Why don't scientists trust atoms? Because they make up everything! + +You: What time is it? +AI Assistant: Current time: 14:30:25, Date: 2024-01-15 +``` + +## Commands + +- **Greetings**: "hello", "hi", "hey", "good morning" +- **Weather**: "weather in [city]", "what's the weather" +- **Math**: "calculate [expression]", "what is 5 + 3" +- **Jokes**: "tell me a joke", "make me laugh" +- **Stories**: "tell me a story", "narrative" +- **Programming**: "programming help", "coding tips" +- **Time**: "what time is it", "current date" +- **Exit**: "quit", "exit", "bye" + +## Technical Details + +- **Language**: Python 3 +- **Architecture**: Object-oriented design with modular components +- **Safety**: Secure mathematical expression evaluation +- **Extensibility**: Easy to add new features and responses +- **Error Handling**: Robust error handling and graceful degradation + +## Contributing + +Feel free to contribute by: +- Adding new conversation topics +- Improving natural language processing +- Adding new features +- Fixing bugs +- Improving documentation + +## License + +This project is open source and available under the MIT License. diff --git a/AI_Chatbot/chatbot.py b/AI_Chatbot/chatbot.py new file mode 100644 index 00000000..70a8106d --- /dev/null +++ b/AI_Chatbot/chatbot.py @@ -0,0 +1,232 @@ +#!/usr/bin/env python3 +""" +AI Chatbot - Intelligent Conversational Assistant +================================================= + +A simple yet powerful AI chatbot that can: +- Answer questions intelligently +- Provide weather information +- Calculate mathematical expressions +- Tell jokes and stories +- Help with programming concepts +- Remember conversation context + +Author: AI Assistant +Language: Python 3 +Dependencies: requests, datetime, random, json +""" + +import json +import random +import datetime +import requests +import re +import math + +class AIChatbot: + def __init__(self): + self.name = "AI Assistant" + self.conversation_history = [] + self.user_name = "" + + # Knowledge base + self.responses = { + "greeting": [ + "Hello! I'm your AI assistant. How can I help you today?", + "Hi there! What would you like to know?", + "Greetings! I'm here to assist you with anything you need.", + "Hello! Ready to chat and help you out!" + ], + "farewell": [ + "Goodbye! It was nice talking to you!", + "See you later! Feel free to come back anytime.", + "Take care! Have a great day!", + "Farewell! Remember, I'm always here to help." + ], + "jokes": [ + "Why don't scientists trust atoms? Because they make up everything!", + "Why did the scarecrow win an award? He was outstanding in his field!", + "What do you call a fake noodle? An impasta!", + "Why don't eggs tell jokes? They'd crack each other up!", + "What do you call a bear with no teeth? A gummy bear!" + ], + "programming_tips": [ + "Always write clean, readable code with meaningful variable names.", + "Comment your code - your future self will thank you!", + "Test your code thoroughly before deploying.", + "Use version control (Git) for all your projects.", + "Learn one programming language deeply before moving to others." + ] + } + + def get_weather(self, city="Jakarta"): + """Get weather information for a city""" + try: + # Using a free weather API (OpenWeatherMap) + api_key = "demo_key" # Replace with actual API key + url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric" + + # For demo purposes, return mock data + mock_weather = { + "Jakarta": "Sunny, 32°C", + "Bandung": "Cloudy, 28°C", + "Surabaya": "Rainy, 26°C", + "Yogyakarta": "Partly cloudy, 30°C" + } + + return f"The weather in {city} is: {mock_weather.get(city, 'Weather data not available')}" + except: + return "Sorry, I couldn't fetch weather data right now." + + def calculate_math(self, expression): + """Safely evaluate mathematical expressions""" + try: + # Remove dangerous functions and only allow safe math operations + safe_dict = { + "__builtins__": {}, + "abs": abs, "round": round, "min": min, "max": max, + "sum": sum, "pow": pow, "sqrt": math.sqrt, + "sin": math.sin, "cos": math.cos, "tan": math.tan, + "log": math.log, "pi": math.pi, "e": math.e + } + + # Clean the expression + expression = re.sub(r'[^0-9+\-*/().\s]', '', expression) + result = eval(expression, safe_dict) + return f"The result is: {result}" + except: + return "Sorry, I couldn't calculate that. Please check your math expression." + + def tell_story(self): + """Tell a random short story""" + stories = [ + "Once upon a time, there was a little robot who dreamed of becoming a painter. Every day, it would collect colorful data and create beautiful digital art. The robot's art became so popular that it inspired humans to see the world in new ways.", + "In a distant galaxy, there lived a wise alien who could speak every programming language in the universe. One day, it met a curious human programmer, and together they created the most efficient algorithm ever known.", + "There was a magical computer that could solve any problem, but it had one condition: you had to ask the right question. Many tried, but only those who understood the problem deeply could unlock its power." + ] + return random.choice(stories) + + def process_message(self, user_input): + """Process user input and generate appropriate response""" + user_input = user_input.lower().strip() + + # Store conversation + self.conversation_history.append(f"User: {user_input}") + + # Greeting detection + if any(word in user_input for word in ["hello", "hi", "hey", "good morning", "good afternoon"]): + if not self.user_name: + self.user_name = input("What's your name? ") + return f"Nice to meet you, {self.user_name}! " + random.choice(self.responses["greeting"]) + return random.choice(self.responses["greeting"]) + + # Farewell detection + if any(word in user_input for word in ["bye", "goodbye", "see you", "farewell"]): + return random.choice(self.responses["farewell"]) + + # Weather request + if "weather" in user_input: + city = "Jakarta" # Default city + words = user_input.split() + for i, word in enumerate(words): + if word == "in" and i + 1 < len(words): + city = words[i + 1].capitalize() + return self.get_weather(city) + + # Math calculation + if any(op in user_input for op in ["+", "-", "*", "/", "calculate", "math", "="]): + # Extract mathematical expression + math_pattern = r'[\d+\-*/().\s]+' + match = re.search(math_pattern, user_input) + if match: + expression = match.group().strip() + return self.calculate_math(expression) + + # Joke request + if any(word in user_input for word in ["joke", "funny", "laugh"]): + return random.choice(self.responses["jokes"]) + + # Story request + if any(word in user_input for word in ["story", "tell me", "narrative"]): + return self.tell_story() + + # Programming help + if any(word in user_input for word in ["programming", "code", "coding", "developer", "programmer"]): + return random.choice(self.responses["programming_tips"]) + + # Time and date + if any(word in user_input for word in ["time", "date", "what time", "what date"]): + now = datetime.datetime.now() + return f"Current time: {now.strftime('%H:%M:%S')}, Date: {now.strftime('%Y-%m-%d')}" + + # Default responses + default_responses = [ + "That's interesting! Can you tell me more about that?", + "I'm not sure I understand. Could you rephrase that?", + "That's a great question! Let me think about it...", + "I'm learning new things every day. What else would you like to know?", + "Fascinating! I'd love to hear more about your thoughts on this." + ] + + return random.choice(default_responses) + + def chat(self): + """Main chat loop""" + print(f"šŸ¤– {self.name} is online!") + print("=" * 50) + print("Type 'quit' or 'exit' to end the conversation") + print("Try asking about weather, math, jokes, stories, or programming!") + print("=" * 50) + + while True: + try: + user_input = input("\nYou: ").strip() + + if user_input.lower() in ['quit', 'exit', 'bye']: + print(f"\n{self.name}: {random.choice(self.responses['farewell'])}") + break + + if not user_input: + continue + + response = self.process_message(user_input) + print(f"\n{self.name}: {response}") + + # Store bot response + self.conversation_history.append(f"Bot: {response}") + + except KeyboardInterrupt: + print(f"\n\n{self.name}: Goodbye! Thanks for chatting!") + break + except Exception as e: + print(f"\n{self.name}: Oops! Something went wrong: {e}") + + def save_conversation(self, filename="conversation_history.json"): + """Save conversation history to file""" + try: + with open(filename, 'w') as f: + json.dump(self.conversation_history, f, indent=2) + print(f"Conversation saved to {filename}") + except Exception as e: + print(f"Could not save conversation: {e}") + +def main(): + """Main function to run the chatbot""" + print("šŸš€ Starting AI Chatbot...") + + # Create and run chatbot + bot = AIChatbot() + bot.chat() + + # Ask if user wants to save conversation + try: + save = input("\nWould you like to save this conversation? (y/n): ").lower() + if save == 'y': + bot.save_conversation() + except: + pass + + print("\nšŸ‘‹ Thanks for using AI Chatbot!") + +if __name__ == "__main__": + main() diff --git a/Array/question.java b/Array/question.java new file mode 100644 index 00000000..25a2d444 --- /dev/null +++ b/Array/question.java @@ -0,0 +1,34 @@ +import java.util.*; + +class Solution { + public String longestCommonPrefix(String[] strs) { + + // Use a StringBuilder to efficiently build the result string + StringBuilder result = new StringBuilder(); + + // Sort the array of strings lexicographically + // After sorting, the common prefix of the whole array must be + // a prefix of both the first and last strings + Arrays.sort(strs); + + // Convert the first and last strings into character arrays + char[] first = strs[0].toCharArray(); + char[] last = strs[strs.length - 1].toCharArray(); + + // Find the minimum length between the first and last strings + int len = Math.min(first.length, last.length); + + // Compare characters one by one + for (int i = 0; i < len; i++) { + // If characters don't match, stop comparing + if (first[i] != last[i]) { + break; + } + // Otherwise, append the character to the result + result.append(first[i]); + } + + // Return the longest common prefix + return result.toString(); + } +} diff --git a/Array/rotatematrix.java b/Array/rotatematrix.java new file mode 100644 index 00000000..e3b18ce8 --- /dev/null +++ b/Array/rotatematrix.java @@ -0,0 +1,37 @@ + +import java.util.*; +class rotatematrix { + static void rotate(int[][] matrix) { + for (int i = 0; i < matrix.length; i++) { + for (int j = i; j < matrix[0].length; j++) { + int temp = 0; + temp = matrix[i][j]; + matrix[i][j] = matrix[j][i]; + matrix[j][i] = temp; + } + } + for (int i = 0; i < matrix.length; i++) { + for (int j = 0; j < matrix.length / 2; j++) { + int temp = 0; + temp = matrix[i][j]; + matrix[i][j] = matrix[i][matrix.length - 1 - j]; + matrix[i][matrix.length - 1 - j] = temp; + } + } + } + + public static void main(String args[]) { + int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; + rotate(arr); + System.out.println("Rotated Image"); + for (int i = 0; i < arr.length; i++) { + for (int j = 0; j < arr.length; j++) { + System.out.print(arr[i][j] + " "); + } + System.out.println(); + } + + } +} + + diff --git a/C++ Code/heapSort.cpp b/C++ Code/heapSort.cpp new file mode 100644 index 00000000..4e20d122 --- /dev/null +++ b/C++ Code/heapSort.cpp @@ -0,0 +1,54 @@ +#include +using namespace std; + +// Maintains the max-heap property for subtree rooted at index i +void heapify(int arr[], int n, int i) +{ + int largest = i; // Assume current node is largest + int left = 2 * i + 1; // Left child index + int right = 2 * i + 2; // Right child index + + // If left child is larger than root + if (left < n && arr[left] > arr[largest]) + largest = left; + + // If right child is larger than current largest + if (right < n && arr[right] > arr[largest]) + largest = right; + + // If largest is not root, swap and continue heapifying + if (largest != i) + { + swap(arr[i], arr[largest]); + heapify(arr, n, largest); + } +} + +// Main function to perform Heap Sort +void heapSort(int arr[], int n) +{ + // Build max-heap + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + + // Extract elements from heap one by one + for (int i = n - 1; i >= 0; i--) + { + // Move current root (max element) to end + swap(arr[0], arr[i]); + // Call heapify on reduced heap + heapify(arr, i, 0); + } +} + +int main() +{ + int arr[] = {12, 11, 13, 5, 6, 7}; + int n = sizeof(arr) / sizeof(arr[0]); + + heapSort(arr, n); + + // Print sorted array + for (int i = 0; i < n; i++) + cout << arr[i] << " "; +} diff --git a/C/Tariff_Calculation.c b/C/Tariff_Calculation.c new file mode 100644 index 00000000..ebe06590 --- /dev/null +++ b/C/Tariff_Calculation.c @@ -0,0 +1,115 @@ +#include +#include + +struct Consumer { + char name[50]; + char type; + int time; + double energy; + double tariff; +}; + +void calculateTariff(struct Consumer *consumer) { + consumer->tariff = 0.0; + + if (consumer->type == 'D') { + consumer->tariff = 0.1 * consumer->energy; + } else if (consumer->type == 'I') { + consumer->tariff = 0.15 * consumer->energy; + } else { + printf("Invalid consumer type for %s.\n", consumer->name); + } + + if (consumer->time >= 9 && consumer->time <= 17) { + consumer->tariff += 0.05 * consumer->energy; + } else { + consumer->tariff += 0.03 * consumer->energy; + } +} + +int main() { + int numConsumers; + printf("Enter the number of consumers: "); + scanf("%d", &numConsumers); + + struct Consumer *consumers = (struct Consumer *)malloc(numConsumers * sizeof(struct Consumer)); + if (consumers == NULL) { + printf("Memory allocation failed. Exiting...\n"); + return 1; + } + + for (int i = 0; i < numConsumers; i++) { + printf("Enter consumer %d information:\n", i + 1); + printf("Name: "); + scanf("%s", consumers[i].name); + printf("Type (D for domestic, I for industrial): "); + scanf(" %c", &consumers[i].type); + printf("Time (in hours): "); + scanf("%d", &consumers[i].time); + printf("Energy consumed (in kWh): "); + scanf("%lf", &consumers[i].energy); + + calculateTariff(&consumers[i]); + } + + int choice; + while (1) { + printf("\nMenu:\n"); + printf("1. View Consumer Information\n"); + printf("2. Update Consumer Information\n"); + printf("3. Delete Consumer Information\n"); + printf("4. Exit\n"); + printf("Enter your choice: "); + scanf("%d", &choice); + + switch (choice) { + case 1: // View Consumer Information + printf("Enter the consumer number to view (1 to %d): ", numConsumers); + int viewIndex; + scanf("%d", &viewIndex); + if (viewIndex >= 1 && viewIndex <= numConsumers) { + struct Consumer consumer = consumers[viewIndex - 1]; + printf("Consumer Information:\n"); + printf("Name: %s, Type: %c, Tariff: $%.2lf\n", consumer.name, consumer.type, consumer.tariff); + } else { + printf("Invalid input. Please enter a valid consumer number.\n"); + } + break; + + case 2: // Update Consumer Information + printf("Enter the consumer number to update (1 to %d): ", numConsumers); + int updateIndex; + scanf("%d", &updateIndex); + if (updateIndex >= 1 && updateIndex <= numConsumers) { + struct Consumer *consumer = &consumers[updateIndex - 1]; + printf("Update Consumer Information for %s:\n", consumer->name); + // Prompt user to update fields like type, time, energy, etc. + // Then recalculate tariff using calculateTariff function. + } else { + printf("Invalid input. Please enter a valid consumer number.\n"); + } + break; + + case 3: // Delete Consumer Information + printf("Enter the consumer number to delete (1 to %d): ", numConsumers); + int deleteIndex; + scanf("%d", &deleteIndex); + if (deleteIndex >= 1 && deleteIndex <= numConsumers) { + // Implement code to delete the selected consumer, which may require shifting elements in the array. + // Be sure to free any memory if needed. + } else { + printf("Invalid input. Please enter a valid consumer number.\n"); + } + break; + + case 4: // Exit + free(consumers); // Free dynamically allocated memory + return 0; + + default: + printf("Invalid choice. Please select a valid option.\n"); + } + } + + return 0; +} diff --git a/File_Organizer/file_organizer.py b/File_Organizer/file_organizer.py new file mode 100644 index 00000000..b0dd5914 --- /dev/null +++ b/File_Organizer/file_organizer.py @@ -0,0 +1,432 @@ +#!/usr/bin/env python3 +""" +Smart File Organizer +==================== + +An intelligent file organization tool that automatically sorts and organizes +files based on their types, creation dates, and custom rules. + +Features: +- Automatic file type detection and sorting +- Custom organization rules and patterns +- Duplicate file detection and handling +- File metadata analysis +- Batch operations and scheduling +- Safe file operations with backup +- Progress tracking and logging +- GUI and command-line interfaces + +Author: AI Assistant +Language: Python 3 +Dependencies: os, shutil, pathlib, datetime, hashlib, json, logging +""" + +import os +import shutil +import hashlib +import json +import logging +from pathlib import Path +from datetime import datetime, timedelta +from collections import defaultdict +import mimetypes +import argparse +import sys + +class FileOrganizer: + def __init__(self, source_dir, destination_dir=None, dry_run=False): + self.source_dir = Path(source_dir) + self.destination_dir = Path(destination_dir) if destination_dir else self.source_dir + self.dry_run = dry_run + + # Setup logging + self.setup_logging() + + # File type mappings + self.file_types = { + 'images': ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.svg', '.webp', '.ico'], + 'videos': ['.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.webm', '.m4v'], + 'audio': ['.mp3', '.wav', '.flac', '.aac', '.ogg', '.wma', '.m4a'], + 'documents': ['.pdf', '.doc', '.docx', '.txt', '.rtf', '.odt', '.xls', '.xlsx', '.ppt', '.pptx'], + 'archives': ['.zip', '.rar', '.7z', '.tar', '.gz', '.bz2'], + 'code': ['.py', '.js', '.html', '.css', '.java', '.cpp', '.c', '.php', '.rb', '.go'], + 'executables': ['.exe', '.msi', '.deb', '.rpm', '.dmg', '.app'], + 'fonts': ['.ttf', '.otf', '.woff', '.woff2'], + 'data': ['.json', '.xml', '.csv', '.sql', '.db', '.sqlite'] + } + + # Organization statistics + self.stats = { + 'files_processed': 0, + 'files_moved': 0, + 'files_copied': 0, + 'duplicates_found': 0, + 'errors': 0, + 'start_time': None, + 'end_time': None + } + + # Duplicate detection + self.file_hashes = {} + self.duplicates = [] + + def setup_logging(self): + """Setup logging configuration""" + log_filename = f"file_organizer_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log" + logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler(log_filename), + logging.StreamHandler(sys.stdout) + ] + ) + self.logger = logging.getLogger(__name__) + + def get_file_type(self, file_path): + """Determine file type based on extension and MIME type""" + file_path = Path(file_path) + extension = file_path.suffix.lower() + + # Check by extension first + for category, extensions in self.file_types.items(): + if extension in extensions: + return category + + # Check by MIME type + mime_type, _ = mimetypes.guess_type(str(file_path)) + if mime_type: + if mime_type.startswith('image/'): + return 'images' + elif mime_type.startswith('video/'): + return 'videos' + elif mime_type.startswith('audio/'): + return 'audio' + elif mime_type.startswith('text/'): + return 'documents' + + return 'other' + + def calculate_file_hash(self, file_path): + """Calculate MD5 hash of file for duplicate detection""" + try: + hash_md5 = hashlib.md5() + with open(file_path, "rb") as f: + for chunk in iter(lambda: f.read(4096), b""): + hash_md5.update(chunk) + return hash_md5.hexdigest() + except Exception as e: + self.logger.error(f"Error calculating hash for {file_path}: {e}") + return None + + def find_duplicates(self, files): + """Find duplicate files based on hash comparison""" + self.logger.info("Scanning for duplicate files...") + + for file_path in files: + file_hash = self.calculate_file_hash(file_path) + if file_hash: + if file_hash in self.file_hashes: + # Duplicate found + original_file = self.file_hashes[file_hash] + self.duplicates.append({ + 'original': original_file, + 'duplicate': file_path, + 'hash': file_hash, + 'size': file_path.stat().st_size + }) + self.stats['duplicates_found'] += 1 + else: + self.file_hashes[file_hash] = file_path + + self.logger.info(f"Found {len(self.duplicates)} duplicate files") + return self.duplicates + + def organize_by_type(self, files): + """Organize files by their type""" + self.logger.info("Organizing files by type...") + + for file_path in files: + try: + file_type = self.get_file_type(file_path) + destination_folder = self.destination_dir / file_type + + # Create destination folder if it doesn't exist + if not self.dry_run: + destination_folder.mkdir(parents=True, exist_ok=True) + + # Generate destination path + destination_path = destination_folder / file_path.name + + # Handle name conflicts + counter = 1 + original_destination = destination_path + while destination_path.exists(): + stem = original_destination.stem + suffix = original_destination.suffix + destination_path = destination_folder / f"{stem}_{counter}{suffix}" + counter += 1 + + # Move or copy file + if not self.dry_run: + shutil.move(str(file_path), str(destination_path)) + self.logger.info(f"Moved: {file_path} -> {destination_path}") + else: + self.logger.info(f"[DRY RUN] Would move: {file_path} -> {destination_path}") + + self.stats['files_moved'] += 1 + + except Exception as e: + self.logger.error(f"Error organizing {file_path}: {e}") + self.stats['errors'] += 1 + + self.stats['files_processed'] += 1 + + def organize_by_date(self, files): + """Organize files by creation date""" + self.logger.info("Organizing files by date...") + + for file_path in files: + try: + # Get file creation time + creation_time = datetime.fromtimestamp(file_path.stat().st_ctime) + date_folder = creation_time.strftime('%Y-%m-%d') + + destination_folder = self.destination_dir / 'by_date' / date_folder + + # Create destination folder if it doesn't exist + if not self.dry_run: + destination_folder.mkdir(parents=True, exist_ok=True) + + # Generate destination path + destination_path = destination_folder / file_path.name + + # Handle name conflicts + counter = 1 + original_destination = destination_path + while destination_path.exists(): + stem = original_destination.stem + suffix = original_destination.suffix + destination_path = destination_folder / f"{stem}_{counter}{suffix}" + counter += 1 + + # Move file + if not self.dry_run: + shutil.move(str(file_path), str(destination_path)) + self.logger.info(f"Moved: {file_path} -> {destination_path}") + else: + self.logger.info(f"[DRY RUN] Would move: {file_path} -> {destination_path}") + + self.stats['files_moved'] += 1 + + except Exception as e: + self.logger.error(f"Error organizing {file_path}: {e}") + self.stats['errors'] += 1 + + self.stats['files_processed'] += 1 + + def organize_by_size(self, files): + """Organize files by size ranges""" + self.logger.info("Organizing files by size...") + + size_ranges = { + 'tiny': (0, 1024), # < 1KB + 'small': (1024, 1024*1024), # 1KB - 1MB + 'medium': (1024*1024, 10*1024*1024), # 1MB - 10MB + 'large': (10*1024*1024, 100*1024*1024), # 10MB - 100MB + 'huge': (100*1024*1024, float('inf')) # > 100MB + } + + for file_path in files: + try: + file_size = file_path.stat().st_size + + # Determine size category + size_category = 'other' + for category, (min_size, max_size) in size_ranges.items(): + if min_size <= file_size < max_size: + size_category = category + break + + destination_folder = self.destination_dir / 'by_size' / size_category + + # Create destination folder if it doesn't exist + if not self.dry_run: + destination_folder.mkdir(parents=True, exist_ok=True) + + # Generate destination path + destination_path = destination_folder / file_path.name + + # Handle name conflicts + counter = 1 + original_destination = destination_path + while destination_path.exists(): + stem = original_destination.stem + suffix = original_destination.suffix + destination_path = destination_folder / f"{stem}_{counter}{suffix}" + counter += 1 + + # Move file + if not self.dry_run: + shutil.move(str(file_path), str(destination_path)) + self.logger.info(f"Moved: {file_path} -> {destination_path}") + else: + self.logger.info(f"[DRY RUN] Would move: {file_path} -> {destination_path}") + + self.stats['files_moved'] += 1 + + except Exception as e: + self.logger.error(f"Error organizing {file_path}: {e}") + self.stats['errors'] += 1 + + self.stats['files_processed'] += 1 + + def clean_empty_folders(self): + """Remove empty folders after organization""" + self.logger.info("Cleaning up empty folders...") + + def remove_empty_dirs(path): + if not path.is_dir(): + return + + # Remove empty subdirectories first + for subdir in path.iterdir(): + if subdir.is_dir(): + remove_empty_dirs(subdir) + + # Remove current directory if empty + try: + if not any(path.iterdir()): + path.rmdir() + self.logger.info(f"Removed empty folder: {path}") + except OSError: + pass # Directory not empty or permission denied + + if not self.dry_run: + remove_empty_dirs(self.source_dir) + + def generate_report(self): + """Generate organization report""" + self.stats['end_time'] = datetime.now() + duration = self.stats['end_time'] - self.stats['start_time'] + + report = f""" +File Organization Report +======================== +Start Time: {self.stats['start_time']} +End Time: {self.stats['end_time']} +Duration: {duration} + +Statistics: +- Files Processed: {self.stats['files_processed']} +- Files Moved: {self.stats['files_moved']} +- Files Copied: {self.stats['files_copied']} +- Duplicates Found: {self.stats['duplicates_found']} +- Errors: {self.stats['errors']} + +Duplicate Files: +""" + + for dup in self.duplicates: + report += f"- {dup['duplicate']} (duplicate of {dup['original']})\n" + + return report + + def organize(self, mode='type', recursive=True, include_hidden=False): + """Main organization method""" + self.stats['start_time'] = datetime.now() + self.logger.info(f"Starting file organization in mode: {mode}") + + # Get all files + if recursive: + files = list(self.source_dir.rglob('*')) + else: + files = list(self.source_dir.iterdir()) + + # Filter files only (exclude directories) + files = [f for f in files if f.is_file()] + + # Filter hidden files if requested + if not include_hidden: + files = [f for f in files if not f.name.startswith('.')] + + self.logger.info(f"Found {len(files)} files to organize") + + # Find duplicates first + self.find_duplicates(files) + + # Organize files based on mode + if mode == 'type': + self.organize_by_type(files) + elif mode == 'date': + self.organize_by_date(files) + elif mode == 'size': + self.organize_by_size(files) + else: + self.logger.error(f"Unknown organization mode: {mode}") + return + + # Clean up empty folders + self.clean_empty_folders() + + # Generate and save report + report = self.generate_report() + self.logger.info(report) + + # Save report to file + report_file = f"organization_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt" + with open(report_file, 'w') as f: + f.write(report) + + self.logger.info(f"Report saved to: {report_file}") + +def main(): + """Main function with command line interface""" + parser = argparse.ArgumentParser(description='Smart File Organizer') + parser.add_argument('source_dir', help='Source directory to organize') + parser.add_argument('-d', '--destination', help='Destination directory (default: same as source)') + parser.add_argument('-m', '--mode', choices=['type', 'date', 'size'], + default='type', help='Organization mode') + parser.add_argument('--dry-run', action='store_true', + help='Show what would be done without actually moving files') + parser.add_argument('--no-recursive', action='store_true', + help='Do not process subdirectories') + parser.add_argument('--include-hidden', action='store_true', + help='Include hidden files') + + args = parser.parse_args() + + # Validate source directory + source_path = Path(args.source_dir) + if not source_path.exists(): + print(f"Error: Source directory '{args.source_dir}' does not exist") + sys.exit(1) + + if not source_path.is_dir(): + print(f"Error: '{args.source_dir}' is not a directory") + sys.exit(1) + + # Create organizer + organizer = FileOrganizer( + source_dir=args.source_dir, + destination_dir=args.destination, + dry_run=args.dry_run + ) + + # Run organization + try: + organizer.organize( + mode=args.mode, + recursive=not args.no_recursive, + include_hidden=args.include_hidden + ) + print("File organization completed successfully!") + except KeyboardInterrupt: + print("\nOperation cancelled by user") + sys.exit(1) + except Exception as e: + print(f"Error during organization: {e}") + sys.exit(1) + +if __name__ == "__main__": + main() diff --git a/Java/concurrentBank.java b/Java/BankingSystem.java similarity index 100% rename from Java/concurrentBank.java rename to Java/BankingSystem.java diff --git a/Java/BubbleSortExample.java b/Java/BubbleSortExample.java new file mode 100644 index 00000000..b9f7dbab --- /dev/null +++ b/Java/BubbleSortExample.java @@ -0,0 +1,39 @@ +public class BubbleSortExample { + public static void main(String[] args) { + int[] arr = {5, 1, 4, 2, 8}; + + bubbleSort(arr); + + System.out.println("Sorted array:"); + for (int num : arr) { + System.out.print(num + " "); + } + } + + // Bubble Sort function + public static void bubbleSort(int[] arr) { + int n = arr.length; + boolean swapped; + + // Outer loop - number of passes + for (int i = 0; i < n - 1; i++) { + swapped = false; // flag to detect any swap in this pass + + // Inner loop - compare adjacent elements + for (int j = 0; j < n - 1 - i; j++) { + if (arr[j] > arr[j + 1]) { + // swap arr[j] and arr[j + 1] + int temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + + swapped = true; + } + } + + // If no swaps occurred, array is already sorted + if (!swapped) + break; + } + } +} diff --git a/Java/ContainsDuplicate.java b/Java/ContainsDuplicate.java new file mode 100644 index 00000000..5ba721e7 --- /dev/null +++ b/Java/ContainsDuplicate.java @@ -0,0 +1,16 @@ +import java.util.HashSet; + +class ContainsDuplicate { + public boolean containsDuplicate(int[] nums) { + HashSet seen = new HashSet<>(); + + for (int num : nums) { + if (seen.contains(num)) { + return true; // Found a duplicate + } + seen.add(num); + } + + return false; // No duplicates found + } +} diff --git a/Java/ExceptionHandelling.java b/Java/ExceptionHandelling.java new file mode 100644 index 00000000..cf4a652e --- /dev/null +++ b/Java/ExceptionHandelling.java @@ -0,0 +1,48 @@ +import java.io.*; + +class Exceptionhandelling { + public static void main(String[] args) { + + // String s set an empty string and calling getLength() + String s = ""; + + try { + System.out.println(getLength(s)); + } + catch (IllegalArgumentException e) { + System.out.println( + "IllegalArgumentException caught"); + } + + // String s set to a value and calling getLength() + s = "GeeksforGeeks"; + + try { + System.out.println(getLength(s)); + } + catch (IllegalArgumentException e) { + System.out.println( + "IllegalArgumentException caught"); + } + + // Setting s as null and calling getLength() + s = null; + + try { + System.out.println(getLength(s)); + } + catch (IllegalArgumentException e) { + System.out.println( + "IllegalArgumentException caught"); + } + } + + public static int getLength(String s) + { + if (s == null) + throw new IllegalArgumentException( + "The argument cannot be null"); + + return s.length(); + } +} \ No newline at end of file diff --git a/Java/Heap/DesignPattern.java b/Java/Heap/DesignPattern.java new file mode 100644 index 00000000..006d037a --- /dev/null +++ b/Java/Heap/DesignPattern.java @@ -0,0 +1,77 @@ +import java.util.*; + +class DesignPattern { + private static int timeStamp = 0; + + private static class Tweet { + int id; + int time; + Tweet next; + + public Tweet(int id, int time) { + this.id = id; + this.time = time; + } + } + + + private Map> followMap; + + private Map tweetMap; + + public Twitter() { + followMap = new HashMap<>(); + tweetMap = new HashMap<>(); + } + + + public void postTweet(int userId, int tweetId) { + Tweet newTweet = new Tweet(tweetId, timeStamp++); + if (tweetMap.containsKey(userId)) { + newTweet.next = tweetMap.get(userId); + } + tweetMap.put(userId, newTweet); + } + + + public List getNewsFeed(int userId) { + List result = new ArrayList<>(); + + PriorityQueue pq = new PriorityQueue<>((a, b) -> b.time - a.time); + + // Add own tweets + if (tweetMap.containsKey(userId)) { + pq.offer(tweetMap.get(userId)); + } + + + if (followMap.containsKey(userId)) { + for (int followee : followMap.get(userId)) { + if (tweetMap.containsKey(followee)) { + pq.offer(tweetMap.get(followee)); + } + } + } + + + while (!pq.isEmpty() && result.size() < 10) { + Tweet t = pq.poll(); + result.add(t.id); + if (t.next != null) pq.offer(t.next); + } + return result; + } + + + public void follow(int followerId, int followeeId) { + if (followerId == followeeId) return; + followMap.putIfAbsent(followerId, new HashSet<>()); + followMap.get(followerId).add(followeeId); + } + + /** Follower unfollows a followee */ + public void unfollow(int followerId, int followeeId) { + if (!followMap.containsKey(followerId)) return; + followMap.get(followerId).remove(followeeId); + } +} diff --git a/Java/Heap/HandsOfStraights.java b/Java/Heap/HandsOfStraights.java new file mode 100644 index 00000000..cae4d891 --- /dev/null +++ b/Java/Heap/HandsOfStraights.java @@ -0,0 +1,41 @@ +import java.util.*; + +public class HandOfStraights { + + public static boolean isNStraightHand(int[] hand, int groupSize) { + + if (hand.length % groupSize != 0) return false; + + + TreeMap cardCount = new TreeMap<>(); + for (int card : hand) { + cardCount.put(card, cardCount.getOrDefault(card, 0) + 1); + } + + + for (int card : cardCount.keySet()) { + int freq = cardCount.get(card); + if (freq > 0) { + + for (int next = card; next < card + groupSize; next++) { + if (cardCount.getOrDefault(next, 0) < freq) { + return false; + } + cardCount.put(next, cardCount.get(next) - freq); + } + } + } + + return true; + } + + public static void main(String[] args) { + int[] hand1 = {1,2,3,6,2,3,4,7,8}; + int groupSize1 = 3; + System.out.println("Output 1: " + isNStraightHand(hand1, groupSize1)); // true + + int[] hand2 = {1,2,3,4,5}; + int groupSize2 = 4; + System.out.println("Output 2: " + isNStraightHand(hand2, groupSize2)); // false + } +} diff --git a/Java/Heap/MedianFinder.java b/Java/Heap/MedianFinder.java new file mode 100644 index 00000000..dd8f2989 --- /dev/null +++ b/Java/Heap/MedianFinder.java @@ -0,0 +1,59 @@ +import java.util.*; + +public class MedianFinder { + private PriorityQueue maxHeap; + private PriorityQueue minHeap; + + + public MedianFinder() { + + maxHeap = new PriorityQueue<>(Collections.reverseOrder()); + + minHeap = new PriorityQueue<>(); + } + + + public void addNum(int num) { + + maxHeap.offer(num); + + + minHeap.offer(maxHeap.poll()); + + + if (maxHeap.size() < minHeap.size()) { + maxHeap.offer(minHeap.poll()); + } + } + + + public double findMedian() { + if (maxHeap.size() == minHeap.size()) { + + return (maxHeap.peek() + minHeap.peek()) / 2.0; + } else { + + return maxHeap.peek(); + } + } + + + public static void main(String[] args) { + MedianFinder mf = new MedianFinder(); + + mf.addNum(1); + System.out.println("After adding 1, Median = " + mf.findMedian()); + + mf.addNum(2); + System.out.println("After adding 2, Median = " + mf.findMedian()); + + mf.addNum(3); + System.out.println("After adding 3, Median = " + mf.findMedian()); + + mf.addNum(4); + System.out.println("After adding 4, Median = " + mf.findMedian()); + + mf.addNum(5); + System.out.println("After adding 5, Median = " + mf.findMedian()); + } +} diff --git a/Java/Heap/MergeMSortedLists.java b/Java/Heap/MergeMSortedLists.java new file mode 100644 index 00000000..c0ab9146 --- /dev/null +++ b/Java/Heap/MergeMSortedLists.java @@ -0,0 +1,62 @@ +import java.util.*; + +class ListNode { + int val; + ListNode next; + ListNode(int x) { val = x; } +} + +public class MergeMSortedLists { + + public static ListNode mergeKLists(ListNode[] lists) { + PriorityQueue minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a.val)); + + + for (ListNode node : lists) { + if (node != null) minHeap.offer(node); + } + + ListNode dummy = new ListNode(0); + ListNode tail = dummy; + + while (!minHeap.isEmpty()) { + ListNode smallest = minHeap.poll(); + tail.next = smallest; + tail = tail.next; + if (smallest.next != null) { + minHeap.offer(smallest.next); + } + } + + return dummy.next; + } + + + private static void printList(ListNode head) { + while (head != null) { + System.out.print(head.val + " "); + head = head.next; + } + System.out.println(); + } + + public static void main(String[] args) { + + ListNode l1 = new ListNode(1); + l1.next = new ListNode(4); + l1.next.next = new ListNode(5); + + ListNode l2 = new ListNode(1); + l2.next = new ListNode(3); + l2.next.next = new ListNode(4); + + ListNode l3 = new ListNode(2); + l3.next = new ListNode(6); + + ListNode[] lists = {l1, l2, l3}; + ListNode merged = mergeKLists(lists); + + System.out.print("Merged Linked List: "); + printList(merged); + } +} diff --git a/Java/Heap/TaskScheduler.java b/Java/Heap/TaskScheduler.java new file mode 100644 index 00000000..05c2ddad --- /dev/null +++ b/Java/Heap/TaskScheduler.java @@ -0,0 +1,38 @@ +import java.util.*; + +public class TaskScheduler { + + public static int leastInterval(char[] tasks, int n) { + int[] freq = new int[26]; + for (char c : tasks) { + freq[c - 'A']++; + } + + Arrays.sort(freq); + int maxFreq = freq[25]; + int idleSlots = (maxFreq - 1) * n; + + + for (int i = 24; i >= 0 && idleSlots > 0; i--) { + idleSlots -= Math.min(freq[i], maxFreq - 1); + } + + idleSlots = Math.max(0, idleSlots); + + return tasks.length + idleSlots; + } + + public static void main(String[] args) { + char[] tasks1 = {'A','A','A','B','B','B'}; + int n1 = 2; + System.out.println("Output 1: " + leastInterval(tasks1, n1)); // 8 + + char[] tasks2 = {'A','C','A','B','D','B'}; + int n2 = 1; + System.out.println("Output 2: " + leastInterval(tasks2, n2)); // 6 + + char[] tasks3 = {'A','A','A','B','B','B'}; + int n3 = 0; + System.out.println("Output 3: " + leastInterval(tasks3, n3)); // 6 + } +} diff --git a/Java/Heap/TopKFrequentElement.java b/Java/Heap/TopKFrequentElement.java new file mode 100644 index 00000000..be17c306 --- /dev/null +++ b/Java/Heap/TopKFrequentElement.java @@ -0,0 +1,40 @@ +import java.util.*; + +public class TopKFrequentElement { + + public static int[] topKFrequent(int[] nums, int k) { + + Map freqMap = new HashMap<>(); + for (int num : nums) { + freqMap.put(num, freqMap.getOrDefault(num, 0) + 1); + } + + + PriorityQueue> minHeap = + new PriorityQueue<>((a, b) -> a.getValue() - b.getValue()); + + for (Map.Entry entry : freqMap.entrySet()) { + minHeap.offer(entry); + if (minHeap.size() > k) { + minHeap.poll(); + } + } + + + int[] result = new int[k]; + for (int i = k - 1; i >= 0; i--) { + result[i] = minHeap.poll().getKey(); + } + + return result; + } + + + public static void main(String[] args) { + int[] nums = {1, 1, 1, 2, 2, 3, 3, 3, 3, 4}; + int k = 2; + + int[] res = topKFrequent(nums, k); + System.out.println("Top " + k + " frequent elements: " + Arrays.toString(res)); + } +} diff --git a/Java/Java-ChatApplication/ChatClient.java b/Java/Java-ChatApplication/ChatClient.java new file mode 100644 index 00000000..7744d8ef --- /dev/null +++ b/Java/Java-ChatApplication/ChatClient.java @@ -0,0 +1,45 @@ +import java.io.*; +import java.net.*; +import java.util.Scanner; + +public class ChatClient { + private static final String SERVER_ADDRESS = "localhost"; + private static final int SERVER_PORT = 12348; + + public static void main(String[] args) { + try (Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT); + PrintWriter out = new PrintWriter(socket.getOutputStream(), true); + BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) { + + Scanner scanner = new Scanner(System.in); + + // Server will first send "Enter your name: " + String prompt = in.readLine(); + System.out.print(prompt); // show "Enter your name: " + String name = scanner.nextLine(); + out.println(name); + + // Thread to listen and print server messages (includes ANSI) + new Thread(() -> { + String msg; + try { + while ((msg = in.readLine()) != null) { + System.out.println(msg); + } + } catch (IOException e) { + // connection closed + } + }).start(); + + // Read user input and send it + String input; + while (scanner.hasNextLine()) { + input = scanner.nextLine(); + out.println(input); + } + + } catch (IOException e) { + System.err.println("Unable to connect to server: " + e.getMessage()); + } + } +} diff --git a/Java/Java-ChatApplication/ChatServer.java b/Java/Java-ChatApplication/ChatServer.java new file mode 100644 index 00000000..d8385c37 --- /dev/null +++ b/Java/Java-ChatApplication/ChatServer.java @@ -0,0 +1,93 @@ +import java.io.*; +import java.net.*; +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; + +public class ChatServer { + private static final int PORT = 12348; + private static final Set clients = new HashSet<>(); + + // ANSI color codes + private static final String RESET = "\u001B[0m"; + private static final String[] COLORS = { + "\u001B[31m", // RED + "\u001B[32m", // GREEN + "\u001B[33m", // YELLOW + "\u001B[34m", // BLUE + "\u001B[35m", // PURPLE + "\u001B[36m", // CYAN + "\u001B[37m" // WHITE + }; + private static final AtomicInteger colorIndex = new AtomicInteger(0); + + public static void main(String[] args) { + System.out.println("Chat server has started on port " + PORT + "..."); + try (ServerSocket serverSocket = new ServerSocket(PORT)) { + while (true) { + Socket socket = serverSocket.accept(); + ClientHandler handler = new ClientHandler(socket); + synchronized (clients) { + clients.add(handler); + } + handler.start(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static class ClientHandler extends Thread { + private final Socket socket; + private PrintWriter out; + private BufferedReader in; + private String name; + private final String color; // assigned color for both name and messages + + ClientHandler(Socket socket) { + this.socket = socket; + this.color = COLORS[colorIndex.getAndUpdate(i -> (i + 1) % COLORS.length)]; + } + + @Override + public void run() { + try { + in = new BufferedReader(new InputStreamReader(socket.getInputStream())); + out = new PrintWriter(socket.getOutputStream(), true); + + // Ask for name + out.println("Enter your name: "); + name = in.readLine(); + if (name == null || name.trim().isEmpty()) { + name = "Anonymous"; + } + + // Announce join (colored) + broadcast("šŸ”” " + color + name + RESET + " has joined the chat."); + + String message; + while ((message = in.readLine()) != null) { + // Broadcast colored message: color applies to both name and message text + broadcast(color + name + RESET + ": " + color + message + RESET); + System.out.println(name + ": " + message); // server log (optional) + } + } catch (IOException e) { + // client disconnected unexpectedly + } finally { + // clean up + try { socket.close(); } catch (IOException ignored) {} + synchronized (clients) { + clients.remove(this); + } + broadcast("āŒ " + color + name + RESET + " has left the chat."); + } + } + + private void broadcast(String msg) { + synchronized (clients) { + for (ClientHandler c : clients) { + c.out.println(msg); + } + } + } + } +} diff --git a/Java/Java-ChatApplication/README.md b/Java/Java-ChatApplication/README.md new file mode 100644 index 00000000..10c75823 --- /dev/null +++ b/Java/Java-ChatApplication/README.md @@ -0,0 +1,88 @@ +# Chat Application + +## Overview + +This chat application is a simple multi-user online chat system implemented in Java using socket programming. It allows multiple users to connect to a central server, send messages, and receive messages from other users in real-time. + +## Components + +- **ChatServer**: The server class that manages connections from multiple clients, assigns unique user IDs, and broadcasts messages to all connected clients. +- **ChatClient**: The client class that connects to the server, sends messages, and receives messages from other clients. + +## Features + +- Supports multiple clients chatting simultaneously. +- Each client can send and receive messages. +- The server maintains a list of connected users. + +## Implementation Details + +### Server Implementation + +- **Class**: `ChatServer` +- **Port**: Configured to run on port **12348** (can be changed). +- **Functionality**: + - Listens for incoming client connections. + - Manages a set of connected clients and broadcasts messages to all users. + - Each client is handled in a separate thread to enable simultaneous connections. + +### Client Implementation + +- **Class**: `ChatClient` +- **Functionality**: + - Connects to the `ChatServer` using sockets. + - Sends messages to the server and listens for incoming messages. + - Simple text-based user interface for message input and display. + +## How to Run the Application + +### Prerequisites + +- Java Development Kit (JDK) installed on your machine. +- IntelliJ IDEA (or any Java IDE) for running the code. + +### Running the Chat Server + +1. Open the `ChatServer` class in IntelliJ IDEA. +2. Run the `ChatServer` class. You should see the message indicating that the server has started: + + +----------------------------------------------------------------------- + +### Running the Chat Clients + +1. Open the `ChatClient` class in IntelliJ IDEA. +2. Create multiple run configurations for the clients (e.g., `ChatClient`, `Client1`, `Client2`). +3. Use the **"Multiple Run"** feature to start all client instances simultaneously or run each client instance one by one. + + + **Open Run → Edit Configurations... + + Create a new Application configuration: + + Click + → Application. + + Name: Client1 + + Main class: TermInYear.ChatClient (use the selector to find it) + +4. After starting the clients, you can send messages from any client and see them received by the others. + +## Usage + +1. **Chatting**: Each client can type a message and press Enter to send it to the server. The server will broadcast the message to all connected clients. +2. **Exit**: To close a client, simply terminate the client window. + +## Testing the Application + +- Open multiple client instances and verify that messages are successfully sent and received between users. +- Check the server console for logs of received messages and broadcast actions. + +## Troubleshooting + +- If you encounter a `java.net.ConnectException: Connection refused`, ensure that the `ChatServer` is running before starting the clients. +- Ensure that the port specified in the server matches the port clients are trying to connect to. + +## Conclusion + +This chat application serves as a basic example of client-server communication using sockets in Java. diff --git a/Java/MissingNumber.java b/Java/MissingNumber.java new file mode 100644 index 00000000..55f24a44 --- /dev/null +++ b/Java/MissingNumber.java @@ -0,0 +1,13 @@ +class MissingNumber { + public int missingNumber(int[] nums) { + int n = nums.length; + int expectedSum = n * (n + 1) / 2; // Sum of first n natural numbers + int actualSum = 0; + + for (int num : nums) { + actualSum += num; + } + + return expectedSum - actualSum; // The difference is the missing number + } +} diff --git a/Java/ProductOfArrayExceptSelf.java b/Java/ProductOfArrayExceptSelf.java new file mode 100644 index 00000000..931346d5 --- /dev/null +++ b/Java/ProductOfArrayExceptSelf.java @@ -0,0 +1,20 @@ +class ProductOfArrayExceptSelf { + public int[] productExceptSelf(int[] nums) { + int n = nums.length; + int[] result = new int[n]; + + int prefix = 1; + for (int i = 0; i < n; i++) { + result[i] = prefix; + prefix *= nums[i]; + } + + int suffix = 1; + for (int i = n - 1; i >= 0; i--) { + result[i] *= suffix; + suffix *= nums[i]; + } + + return result; + } +} diff --git a/Java/RotateArray.java b/Java/RotateArray.java new file mode 100644 index 00000000..f4725760 --- /dev/null +++ b/Java/RotateArray.java @@ -0,0 +1,20 @@ +class RotateArray { + public void rotate(int[] nums, int k) { + int n = nums.length; + k = k % n; // Handle cases where k > n + + reverse(nums, 0, n - 1); // Reverse the entire array + reverse(nums, 0, k - 1); // Reverse the first k elements + reverse(nums, k, n - 1); // Reverse the remaining elements + } + + private void reverse(int[] nums, int start, int end) { + while (start < end) { + int temp = nums[start]; + nums[start] = nums[end]; + nums[end] = temp; + start++; + end--; + } + } +} diff --git a/Java/coding.java b/Java/coding.java new file mode 100644 index 00000000..71049139 --- /dev/null +++ b/Java/coding.java @@ -0,0 +1,112 @@ +import java.util.*; + +class Node { + int frequency; + char character; + Node left, right; + + Node(char character, int frequency) { + this.character = character; + this.frequency = frequency; + left = right = null; + } +} + +class HuffmanCoding { + private static Node root; + + // Comparator to sort nodes based on frequency + private static class NodeComparator implements Comparator { + public int compare(Node n1, Node n2) { + return n1.frequency - n2.frequency; + } + } + + // Build the Huffman Tree + private static void buildHuffmanTree(String text) { + Map frequencyMap = new HashMap<>(); + for (char c : text.toCharArray()) { + frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1); + } + + PriorityQueue priorityQueue = new PriorityQueue<>(new NodeComparator()); + for (Map.Entry entry : frequencyMap.entrySet()) { + priorityQueue.add(new Node(entry.getKey(), entry.getValue())); + } + + while (priorityQueue.size() > 1) { + Node left = priorityQueue.poll(); + Node right = priorityQueue.poll(); + Node newNode = new Node('\0', left.frequency + right.frequency); + newNode.left = left; + newNode.right = right; + priorityQueue.add(newNode); + } + + root = priorityQueue.poll(); + } + + // Generate the Huffman codes + private static void generateCodes(Node node, String code, Map huffmanCode) { + if (node == null) return; + + if (node.left == null && node.right == null) { + // Handle single character case - assign code "0" if empty + huffmanCode.put(node.character, code.isEmpty() ? "0" : code); + return; + } + + generateCodes(node.left, code + "0", huffmanCode); + generateCodes(node.right, code + "1", huffmanCode); + } + + // Encode the input text + public static String encode(String text) { + if (text == null || text.isEmpty()) { + return ""; + } + + buildHuffmanTree(text); + Map huffmanCode = new HashMap<>(); + generateCodes(root, "", huffmanCode); + + StringBuilder encodedText = new StringBuilder(); + for (char c : text.toCharArray()) { + encodedText.append(huffmanCode.get(c)); + } + + return encodedText.toString(); + } + + // Decode the encoded text + public static String decode(String encodedText) { + if (encodedText == null || encodedText.isEmpty() || root == null) { + return ""; + } + + StringBuilder decodedText = new StringBuilder(); + Node currentNode = root; + + for (char bit : encodedText.toCharArray()) { + currentNode = (bit == '0') ? currentNode.left : currentNode.right; + + if (currentNode.left == null && currentNode.right == null) { + decodedText.append(currentNode.character); + currentNode = root; + } + } + + return decodedText.toString(); + } + + public static void main(String[] args) { + String text = "hello huffman"; + System.out.println("Original Text: " + text); + + String encodedText = encode(text); + System.out.println("Encoded Text: " + encodedText); + + String decodedText = decode(encodedText); + System.out.println("Decoded Text: " + decodedText); + } +} diff --git a/Java/library.java b/Java/library.java new file mode 100644 index 00000000..a037ce75 --- /dev/null +++ b/Java/library.java @@ -0,0 +1,188 @@ +import java.io.*; +import java.util.*; + +// Book class +class Book implements Serializable { + private String title; + private String author; + private boolean isIssued; + + public Book(String title, String author) { + this.title = title; + this.author = author; + this.isIssued = false; + } + + public String getTitle() { return title; } + public String getAuthor() { return author; } + public boolean isIssued() { return isIssued; } + + public void issueBook() throws Exception { + if (isIssued) throw new Exception("Book already issued!"); + this.isIssued = true; + } + + public void returnBook() { + this.isIssued = false; + } + + @Override + public String toString() { + return title + " by " + author + (isIssued ? " [Issued]" : " [Available]"); + } +} + +// Library class +class Library implements Serializable { + private List books; + private Map issuedBooks; // bookTitle -> studentName + + public Library() { + books = new ArrayList<>(); + issuedBooks = new HashMap<>(); + } + + public void addBook(Book book) { + books.add(book); + } + + public void showBooks() { + if (books.isEmpty()) { + System.out.println("No books in library."); + return; + } + for (Book b : books) { + System.out.println(b); + } + } + + public void issueBook(String title, String student) { + for (Book b : books) { + if (b.getTitle().equalsIgnoreCase(title)) { + try { + b.issueBook(); + issuedBooks.put(title, student); + System.out.println("Book issued to " + student); + } catch (Exception e) { + System.out.println("Error: " + e.getMessage()); + } + return; + } + } + System.out.println("Book not found!"); + } + + public void returnBook(String title) { + for (Book b : books) { + if (b.getTitle().equalsIgnoreCase(title)) { + if (b.isIssued()) { + b.returnBook(); + issuedBooks.remove(title); + System.out.println("Book returned successfully!"); + } else { + System.out.println("This book was not issued."); + } + return; + } + } + System.out.println("Book not found!"); + } +} + +// Background thread for auto-saving library data +class AutoSave extends Thread { + private Library library; + private String filename; + + public AutoSave(Library library, String filename) { + this.library = library; + this.filename = filename; + } + + public void run() { + while (true) { + try { + saveLibrary(); + Thread.sleep(5000); // autosave every 5 seconds + } catch (Exception e) { + System.out.println("AutoSave Error: " + e.getMessage()); + } + } + } + + private void saveLibrary() throws IOException { + try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) { + oos.writeObject(library); + } + System.out.println("[AutoSaved library data]"); + } +} + +// Main class +public class LibrarySystem { + private static final String FILE_NAME = "library.dat"; + + // Method to load library data + public static Library loadLibrary() { + try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE_NAME))) { + return (Library) ois.readObject(); + } catch (Exception e) { + return new Library(); // new library if no data found + } + } + + public static void main(String[] args) { + Library library = loadLibrary(); + AutoSave autoSave = new AutoSave(library, FILE_NAME); + autoSave.setDaemon(true); // run in background + autoSave.start(); + + Scanner sc = new Scanner(System.in); + while (true) { + System.out.println("\n--- Library Menu ---"); + System.out.println("1. Add Book"); + System.out.println("2. Show Books"); + System.out.println("3. Issue Book"); + System.out.println("4. Return Book"); + System.out.println("5. Exit"); + System.out.print("Enter choice: "); + int choice = sc.nextInt(); + sc.nextLine(); + + switch (choice) { + case 1: + System.out.print("Enter title: "); + String title = sc.nextLine(); + System.out.print("Enter author: "); + String author = sc.nextLine(); + library.addBook(new Book(title, author)); + break; + + case 2: + library.showBooks(); + break; + + case 3: + System.out.print("Enter book title to issue: "); + String issueTitle = sc.nextLine(); + System.out.print("Enter student name: "); + String student = sc.nextLine(); + library.issueBook(issueTitle, student); + break; + + case 4: + System.out.print("Enter book title to return: "); + String returnTitle = sc.nextLine(); + library.returnBook(returnTitle); + break; + + case 5: + System.out.println("Exiting..."); + System.exit(0); + + default: + System.out.println("Invalid choice."); + } + } + } +} diff --git a/Java/moveX.java b/Java/moveX.java index 67660a33..72ae1e91 100644 --- a/Java/moveX.java +++ b/Java/moveX.java @@ -1,4 +1,3 @@ -package recursion; public class moveX { diff --git a/Java/shortestJobFirst.java b/Java/shortestJobFirst.java new file mode 100644 index 00000000..3242055f --- /dev/null +++ b/Java/shortestJobFirst.java @@ -0,0 +1,49 @@ +import java.util.Arrays; + +public class shortestJobFirst { + + // Function to calculate average + // waiting time using Shortest + // Job First algorithm + static float shortestJobFirst(int[] jobs) { + // Sort the jobs in ascending order + Arrays.sort(jobs); + + // Initialize total waiting time + float waitTime = 0; + // Initialize total time taken + int totalTime = 0; + // Get the number of jobs + int n = jobs.length; + + // Iterate through each job + // to calculate waiting time + for (int i = 0; i < n; ++i) { + + // Add current total + // time to waiting time + waitTime += totalTime; + + // Add current job's + // time to total time + totalTime += jobs[i]; + } + + // Return the average waiting time + return waitTime / n; + } + + public static void main(String[] args) { + int[] jobs = {4, 3, 7, 1, 2}; + + System.out.print("Array Representing Job Durations: "); + for (int i = 0; i < jobs.length; i++) { + System.out.print(jobs[i] + " "); + } + System.out.println(); + + float ans = shortestJobFirst(jobs); + System.out.println("Average waiting time: " + ans); + } +} + diff --git a/Password_Generator/README.md b/Password_Generator/README.md new file mode 100644 index 00000000..963de7bb --- /dev/null +++ b/Password_Generator/README.md @@ -0,0 +1,165 @@ +# Advanced Password Generator šŸ” + +A comprehensive and secure password generator that creates strong, customizable passwords with advanced security features and analysis capabilities. + +## Features + +- šŸ”’ **Secure Generation**: Uses cryptographically secure random number generation +- šŸŽÆ **Customizable Options**: Control length, character sets, and requirements +- šŸ“Š **Strength Analysis**: Detailed password strength evaluation and feedback +- 🧠 **Passphrase Generation**: Create memorable passphrases using common words +- šŸ“ˆ **Bulk Generation**: Generate multiple passwords at once +- šŸ“ **Password History**: Track generated passwords with timestamps +- šŸ’¾ **Export Functionality**: Save password history to files +- šŸ” **Pattern Detection**: Identifies common weak patterns +- šŸ“Š **Entropy Calculation**: Measures password randomness and security + +## Installation + +```bash +# Clone the repository +git clone +cd Password_Generator + +# No external dependencies required - uses only Python standard library +python password_generator.py +``` + +## Usage + +### Interactive Mode +```bash +python password_generator.py +``` + +### Programmatic Usage +```python +from password_generator import PasswordGenerator + +# Create generator instance +generator = PasswordGenerator() + +# Generate a secure password +password = generator.generate_password( + length=16, + include_uppercase=True, + include_lowercase=True, + include_digits=True, + include_symbols=True, + min_uppercase=2, + min_lowercase=2, + min_digits=2, + min_symbols=2 +) + +# Analyze password strength +analysis = generator.analyze_password_strength(password) +print(f"Password: {password}") +print(f"Strength: {analysis['strength']}") +print(f"Score: {analysis['score']}/8") +``` + +## Password Generation Options + +### Single Password +- **Length**: 8-128 characters (default: 12) +- **Character Sets**: Uppercase, lowercase, digits, symbols +- **Minimum Requirements**: Set minimum counts for each character type +- **Exclusions**: Remove similar/ambiguous characters + +### Passphrase Generation +- **Word Count**: 3-10 words (default: 4) +- **Separators**: Custom separators between words +- **Capitalization**: Optional word capitalization +- **Numbers & Symbols**: Optional random additions + +### Bulk Generation +- Generate multiple passwords with same settings +- Useful for creating password lists +- Maintains individual password strength + +## Password Strength Analysis + +The generator provides comprehensive strength analysis: + +- **Length Analysis**: Evaluates password length +- **Character Variety**: Checks for multiple character types +- **Pattern Detection**: Identifies common weak patterns +- **Entropy Calculation**: Measures randomness and security +- **Strength Levels**: Weak, Medium, Strong, Very Strong + +### Strength Scoring +- **0-1**: Weak (easily cracked) +- **2-3**: Medium (moderate security) +- **4-5**: Strong (good security) +- **6-8**: Very Strong (excellent security) + +## Security Features + +- **Cryptographically Secure**: Uses `secrets` module for true randomness +- **No Weak Patterns**: Avoids common patterns like "123", "abc", "qwerty" +- **Character Exclusions**: Option to exclude similar/ambiguous characters +- **Minimum Requirements**: Ensures password meets complexity requirements +- **Entropy Analysis**: Calculates and reports password entropy + +## Examples + +### Strong Password Generation +``` +Generated Password: K9#mP2$vL8@nQ4! +Strength: VERY_STRONG +Score: 8/8 +Entropy: 78.45 +``` + +### Passphrase Generation +``` +Generated Passphrase: Dragon-Sunset-Mountain-River-42! +Strength: STRONG +Score: 6/8 +``` + +### Bulk Generation +``` +Generated 5 passwords: + 1. mK7#nP9$vL2@qR5! + 2. X3&bN8*vM4@tS6# + 3. Q9$cF2#wH5@yU7! + 4. Z6&dG8*vJ3@kI4# + 5. L1$eH9#xK7@mN2! +``` + +## File Structure + +``` +Password_Generator/ +ā”œā”€ā”€ password_generator.py # Main generator class and functions +ā”œā”€ā”€ README.md # This documentation +└── requirements.txt # Dependencies (none required) +``` + +## Contributing + +Contributions are welcome! Areas for improvement: +- Additional character sets +- More sophisticated pattern detection +- Integration with password managers +- GUI interface +- Additional export formats +- Password policy validation + +## Security Notes + +- This tool generates passwords locally - no data is sent to external servers +- Password history is stored locally and can be exported +- Use strong, unique passwords for all accounts +- Consider using a password manager for long-term storage +- Regularly update passwords for critical accounts + +## License + +This project is open source and available under the MIT License. + +--- + +**Remember**: The best password is one that's both strong and memorable. Use this tool responsibly and never share your passwords! diff --git a/Password_Generator/password_generator.py b/Password_Generator/password_generator.py new file mode 100644 index 00000000..00dfbc5e --- /dev/null +++ b/Password_Generator/password_generator.py @@ -0,0 +1,463 @@ +#!/usr/bin/env python3 +""" +Advanced Password Generator +=========================== + +A comprehensive password generator that creates secure, customizable passwords +with various complexity levels and security features. + +Features: +- Multiple password generation strategies +- Customizable length and character sets +- Password strength analysis +- Secure random generation +- Password history and validation +- Export/import functionality + +Author: AI Assistant +Language: Python 3 +Dependencies: secrets, string, random, json, datetime +""" + +import secrets +import string +import random +import json +import datetime +import hashlib +import base64 + +class PasswordGenerator: + def __init__(self): + self.password_history = [] + self.strength_levels = { + "weak": 0, + "medium": 1, + "strong": 2, + "very_strong": 3 + } + + # Character sets + self.char_sets = { + "lowercase": string.ascii_lowercase, + "uppercase": string.ascii_uppercase, + "digits": string.digits, + "symbols": "!@#$%^&*()_+-=[]{}|;:,.<>?", + "extended": "~`!@#$%^&*()_+-=[]{}|;:,.<>?/\\\"'" + } + + def generate_password(self, length=12, include_uppercase=True, include_lowercase=True, + include_digits=True, include_symbols=True, exclude_similar=True, + exclude_ambiguous=True, min_uppercase=1, min_lowercase=1, + min_digits=1, min_symbols=1): + """ + Generate a secure password with specified requirements + + Args: + length (int): Password length + include_uppercase (bool): Include uppercase letters + include_lowercase (bool): Include lowercase letters + include_digits (bool): Include digits + include_symbols (bool): Include symbols + exclude_similar (bool): Exclude similar characters (0, O, l, 1) + exclude_ambiguous (bool): Exclude ambiguous characters + min_uppercase (int): Minimum uppercase letters required + min_lowercase (int): Minimum lowercase letters required + min_digits (int): Minimum digits required + min_symbols (int): Minimum symbols required + + Returns: + str: Generated password + """ + + # Build character pool + char_pool = "" + required_chars = [] + + if include_lowercase: + chars = self.char_sets["lowercase"] + if exclude_similar: + chars = chars.replace('l', '').replace('o', '') + if exclude_ambiguous: + chars = chars.replace('i', '').replace('j', '') + char_pool += chars + required_chars.extend(random.choices(chars, k=min_lowercase)) + + if include_uppercase: + chars = self.char_sets["uppercase"] + if exclude_similar: + chars = chars.replace('O', '').replace('I', '') + if exclude_ambiguous: + chars = chars.replace('I', '').replace('J', '') + char_pool += chars + required_chars.extend(random.choices(chars, k=min_uppercase)) + + if include_digits: + chars = self.char_sets["digits"] + if exclude_similar: + chars = chars.replace('0', '').replace('1', '') + char_pool += chars + required_chars.extend(random.choices(chars, k=min_digits)) + + if include_symbols: + chars = self.char_sets["symbols"] + if exclude_ambiguous: + chars = chars.replace('(', '').replace(')', '').replace('[', '').replace(']', '') + char_pool += chars + required_chars.extend(random.choices(chars, k=min_symbols)) + + if not char_pool: + raise ValueError("At least one character set must be included") + + # Generate remaining characters + remaining_length = length - len(required_chars) + if remaining_length < 0: + raise ValueError("Minimum requirements exceed password length") + + additional_chars = [secrets.choice(char_pool) for _ in range(remaining_length)] + + # Combine and shuffle + all_chars = required_chars + additional_chars + random.shuffle(all_chars) + + password = ''.join(all_chars) + + # Store in history + self._add_to_history(password) + + return password + + def generate_passphrase(self, word_count=4, separator="-", capitalize=True, + include_numbers=True, include_symbols=False): + """ + Generate a memorable passphrase using common words + + Args: + word_count (int): Number of words in passphrase + separator (str): Separator between words + capitalize (bool): Capitalize first letter of each word + include_numbers (bool): Include random numbers + include_symbols (bool): Include random symbols + + Returns: + str: Generated passphrase + """ + + # Common word list for passphrases + word_list = [ + "apple", "banana", "cherry", "dragon", "eagle", "forest", "garden", + "house", "island", "jungle", "knight", "ladder", "mountain", "ocean", + "palace", "queen", "river", "sunset", "tiger", "umbrella", "violet", + "window", "yellow", "zebra", "adventure", "beautiful", "creative", + "dancing", "electric", "fantastic", "guitar", "harmony", "incredible", + "journey", "knowledge", "laughter", "magical", "nature", "optimistic", + "peaceful", "quality", "rainbow", "sunshine", "treasure", "unique", + "victory", "wonderful", "excellent", "yesterday", "zealous" + ] + + # Select random words + words = random.sample(word_list, word_count) + + # Apply modifications + if capitalize: + words = [word.capitalize() for word in words] + + # Add numbers and symbols if requested + if include_numbers: + words.append(str(random.randint(10, 99))) + + if include_symbols: + symbols = "!@#$%^&*" + words.append(random.choice(symbols)) + + passphrase = separator.join(words) + + # Store in history + self._add_to_history(passphrase) + + return passphrase + + def analyze_password_strength(self, password): + """ + Analyze password strength and provide detailed feedback + + Args: + password (str): Password to analyze + + Returns: + dict: Analysis results + """ + + score = 0 + feedback = [] + + # Length analysis + length = len(password) + if length < 8: + feedback.append("Password is too short (minimum 8 characters recommended)") + elif length >= 12: + score += 2 + feedback.append("Good password length") + else: + score += 1 + + # Character variety analysis + has_lower = any(c.islower() for c in password) + has_upper = any(c.isupper() for c in password) + has_digit = any(c.isdigit() for c in password) + has_symbol = any(c in string.punctuation for c in password) + + char_types = sum([has_lower, has_upper, has_digit, has_symbol]) + + if char_types >= 4: + score += 3 + feedback.append("Excellent character variety") + elif char_types == 3: + score += 2 + feedback.append("Good character variety") + elif char_types == 2: + score += 1 + feedback.append("Consider adding more character types") + else: + feedback.append("Password uses only one character type") + + # Pattern analysis + if self._has_common_patterns(password): + score -= 1 + feedback.append("Avoid common patterns (123, abc, qwerty)") + + # Entropy calculation + entropy = self._calculate_entropy(password) + if entropy > 60: + score += 2 + feedback.append("High entropy - very secure") + elif entropy > 40: + score += 1 + feedback.append("Good entropy") + else: + feedback.append("Low entropy - consider more randomness") + + # Determine strength level + if score >= 6: + strength = "very_strong" + elif score >= 4: + strength = "strong" + elif score >= 2: + strength = "medium" + else: + strength = "weak" + + return { + "password": password, + "length": length, + "strength": strength, + "score": score, + "entropy": entropy, + "feedback": feedback, + "character_types": { + "lowercase": has_lower, + "uppercase": has_upper, + "digits": has_digit, + "symbols": has_symbol + } + } + + def _has_common_patterns(self, password): + """Check for common patterns in password""" + common_patterns = [ + "123", "abc", "qwerty", "password", "admin", "user", + "letmein", "welcome", "monkey", "dragon", "master" + ] + + password_lower = password.lower() + return any(pattern in password_lower for pattern in common_patterns) + + def _calculate_entropy(self, password): + """Calculate password entropy""" + char_set_size = 0 + + if any(c.islower() for c in password): + char_set_size += 26 + if any(c.isupper() for c in password): + char_set_size += 26 + if any(c.isdigit() for c in password): + char_set_size += 10 + if any(c in string.punctuation for c in password): + char_set_size += 32 + + if char_set_size == 0: + return 0 + + entropy = len(password) * (char_set_size ** 0.5) + return entropy + + def _add_to_history(self, password): + """Add password to history with metadata""" + entry = { + "password": password, + "timestamp": datetime.datetime.now().isoformat(), + "hash": hashlib.sha256(password.encode()).hexdigest()[:16] + } + self.password_history.append(entry) + + # Keep only last 50 passwords + if len(self.password_history) > 50: + self.password_history = self.password_history[-50:] + + def export_passwords(self, filename="password_export.json", include_passwords=True): + """Export password history to file""" + export_data = { + "export_date": datetime.datetime.now().isoformat(), + "total_passwords": len(self.password_history), + "passwords": [] + } + + for entry in self.password_history: + if include_passwords: + export_data["passwords"].append(entry) + else: + # Export only metadata without actual passwords + export_data["passwords"].append({ + "timestamp": entry["timestamp"], + "hash": entry["hash"] + }) + + with open(filename, 'w') as f: + json.dump(export_data, f, indent=2) + + return f"Exported {len(self.password_history)} passwords to {filename}" + + def generate_bulk_passwords(self, count=10, **kwargs): + """Generate multiple passwords at once""" + passwords = [] + for _ in range(count): + password = self.generate_password(**kwargs) + passwords.append(password) + return passwords + +def main(): + """Main function to run the password generator""" + print("šŸ” Advanced Password Generator") + print("=" * 50) + + generator = PasswordGenerator() + + while True: + print("\nOptions:") + print("1. Generate Single Password") + print("2. Generate Passphrase") + print("3. Generate Multiple Passwords") + print("4. Analyze Password Strength") + print("5. View Password History") + print("6. Export Passwords") + print("7. Exit") + + choice = input("\nEnter your choice (1-7): ").strip() + + if choice == "1": + try: + length = int(input("Password length (default 12): ") or "12") + include_upper = input("Include uppercase? (y/n, default y): ").lower() != 'n' + include_lower = input("Include lowercase? (y/n, default y): ").lower() != 'n' + include_digits = input("Include digits? (y/n, default y): ").lower() != 'n' + include_symbols = input("Include symbols? (y/n, default y): ").lower() != 'n' + + password = generator.generate_password( + length=length, + include_uppercase=include_upper, + include_lowercase=include_lower, + include_digits=include_digits, + include_symbols=include_symbols + ) + + print(f"\nGenerated Password: {password}") + + # Analyze strength + analysis = generator.analyze_password_strength(password) + print(f"Strength: {analysis['strength'].upper()}") + print(f"Score: {analysis['score']}/8") + print("Feedback:") + for feedback in analysis['feedback']: + print(f" - {feedback}") + + except ValueError as e: + print(f"Error: {e}") + + elif choice == "2": + try: + word_count = int(input("Number of words (default 4): ") or "4") + separator = input("Separator (default '-'): ") or "-" + capitalize = input("Capitalize words? (y/n, default y): ").lower() != 'n' + include_numbers = input("Include numbers? (y/n, default n): ").lower() == 'y' + include_symbols = input("Include symbols? (y/n, default n): ").lower() == 'y' + + passphrase = generator.generate_passphrase( + word_count=word_count, + separator=separator, + capitalize=capitalize, + include_numbers=include_numbers, + include_symbols=include_symbols + ) + + print(f"\nGenerated Passphrase: {passphrase}") + + except ValueError as e: + print(f"Error: {e}") + + elif choice == "3": + try: + count = int(input("Number of passwords to generate (default 10): ") or "10") + length = int(input("Password length (default 12): ") or "12") + + passwords = generator.generate_bulk_passwords(count=count, length=length) + + print(f"\nGenerated {count} passwords:") + for i, password in enumerate(passwords, 1): + print(f"{i:2d}. {password}") + + except ValueError as e: + print(f"Error: {e}") + + elif choice == "4": + password = input("Enter password to analyze: ").strip() + if password: + analysis = generator.analyze_password_strength(password) + print(f"\nPassword Analysis:") + print(f"Password: {analysis['password']}") + print(f"Length: {analysis['length']}") + print(f"Strength: {analysis['strength'].upper()}") + print(f"Score: {analysis['score']}/8") + print(f"Entropy: {analysis['entropy']:.2f}") + print("Character Types:") + for char_type, present in analysis['character_types'].items(): + status = "āœ“" if present else "āœ—" + print(f" {char_type}: {status}") + print("Feedback:") + for feedback in analysis['feedback']: + print(f" - {feedback}") + + elif choice == "5": + if generator.password_history: + print(f"\nPassword History ({len(generator.password_history)} entries):") + for i, entry in enumerate(generator.password_history[-10:], 1): + timestamp = datetime.datetime.fromisoformat(entry['timestamp']) + print(f"{i:2d}. {entry['password']} ({timestamp.strftime('%Y-%m-%d %H:%M')})") + else: + print("No passwords in history yet.") + + elif choice == "6": + include_passwords = input("Include actual passwords in export? (y/n, default n): ").lower() == 'y' + filename = input("Export filename (default password_export.json): ") or "password_export.json" + + result = generator.export_passwords(filename, include_passwords) + print(f"\n{result}") + + elif choice == "7": + print("Goodbye! Stay secure! šŸ”") + break + + else: + print("Invalid choice. Please try again.") + +if __name__ == "__main__": + main() diff --git a/Python/Voicebook.py b/Python/Voicebook.py new file mode 100644 index 00000000..9cd42e76 --- /dev/null +++ b/Python/Voicebook.py @@ -0,0 +1,59 @@ +import speech_recognition as sheru +import pyttsx3 +import pywhatkit +import wikipedia + +def Take_query(): + + + Hello() + + while(True): + + + query = takeCommand().lower() + if "open geeksforgeeks" in query: + speak("Opening GeeksforGeeks ") + + # in the open method we just to give the link + # of the website and it automatically open + # it in your default browser + webbrowser.open("www.geeksforgeeks.com") + continue + + elif "open google" in query: + speak("Opening Google ") + webbrowser.open("www.google.com") + continue + + elif "which day it is" in query: + tellDay() + continue + + elif "tell me the time" in query: + tellTime() + continue + + # this will exit and terminate the program + elif "bye" in query: + speak("Bye. Check Out GFG for more exicting things") + exit() + + elif "from wikipedia" in query: + + + speak("Checking the wikipedia ") + query = query.replace("wikipedia", "") + + # it will give the summary of 4 lines from + # wikipedia we can increase and decrease + # it also. + result = wikipedia.summary(query, sentences=4) + speak("According to wikipedia") + speak(result) + + elif "tell me your name" in query: + speak("I am Jarvis. Your deskstop Assistant") + +def speak(audio) +speak diff --git a/README.md b/README.md index cf550893..8384a8fa 100644 --- a/README.md +++ b/README.md @@ -2,15 +2,35 @@ Welcome to the Programming Language Projects repository! This repository is a collection of various web development projects implemented using a variety of web technologies, including Python, Java, CPP, and various Programming Languages. Whether you are a programmer, a DSA enthusiast, or a beginner, you'll find a diverse range of projects here to explore, learn from, and contribute to. +## Programming Language Algorithms + +A collection of algorithms implemented in JavaScript and Java. + ## Contributing -If you'd like to contribute to this repository, please refer to the contributing guidelines provided in the [CONTRIBUTING](CONTRIBUTING.md) file. We welcome your contributions and appreciate your help in making this repository even better! -We particularly appreciate well-documented and commented code to help others understand your work. +If you'd like to contribute to this repository, please refer to the contributing guidelines provided in the (CONTRIBUTING.md) file. We welcome your contributions and appreciate your help in making this repository even better! We particularly appreciate well-documented and commented code to help others understand your work. + +We welcome contributions from everyone, especially during Hacktoberfest! +To participate: + +1. Fork this repository. +2. Create a new branch for your changes. +3. Add your algorithm or improve existing ones. +4. Open a pull request. + +## Hacktoberfest + +This repository is open for Hacktoberfest contributions. +Please make sure your pull request follows our guidelines. ## Code of Conduct Please note that by contributing to this repository, you agree to abide by the [Code of Conduct](CODE_OF_CONDUCT.md). We expect all contributors to be respectful and considerate of others' work and opinions. Any violations of this code will not be tolerated. +## License + +MIT + ## Documentation Comprehensive documentation of your Programming Language projects is essential. Ensure you include detailed explanations of your project's algorithm, architecture, features, and how to set up and run it. Comment your code effectively to assist others in understanding your implementation. A clear README is crucial to help users and contributors get started with your project. diff --git a/Snake_Game/README.md b/Snake_Game/README.md new file mode 100644 index 00000000..20c89104 --- /dev/null +++ b/Snake_Game/README.md @@ -0,0 +1,170 @@ +# Snake Game - Classic Arcade Experience šŸ + +A modern, feature-rich implementation of the classic Snake game built with Python and Pygame. Experience the nostalgia of arcade gaming with enhanced graphics, multiple difficulty levels, and smooth gameplay. + +## Features + +- šŸŽ® **Classic Gameplay**: Traditional Snake game mechanics with modern enhancements +- šŸŽÆ **Multiple Difficulty Levels**: Easy, Medium, and Hard modes +- šŸ† **Score System**: Track your score and compete for high scores +- šŸ“Š **Level Progression**: Speed increases as you advance through levels +- šŸŽ **Special Food Types**: Normal, bonus, and special food with different point values +- āøļø **Pause Functionality**: Pause and resume gameplay anytime +- šŸŽØ **Beautiful Graphics**: Smooth animations and colorful visuals +- šŸ’¾ **High Score Persistence**: Your best scores are saved automatically +- šŸŽµ **Sound Effects**: Optional audio feedback (can be extended) + +## Installation + +### Prerequisites +- Python 3.6 or higher +- Pygame library + +### Setup +```bash +# Clone the repository +git clone +cd Snake_Game + +# Install Pygame +pip install pygame + +# Run the game +python snake_game.py +``` + +### Alternative Installation +```bash +# Using pip with requirements +pip install -r requirements.txt +python snake_game.py +``` + +## How to Play + +### Basic Controls +- **Arrow Keys** or **WASD**: Move the snake +- **Space**: Pause/Resume game +- **ESC**: Return to main menu or exit +- **R**: Restart game (when game over) +- **H**: View high scores + +### Game Rules +1. Control the snake to eat food and grow longer +2. Avoid hitting walls or your own body +3. Different food types give different points: + - **Red Food**: 10 points (normal) + - **Yellow Food**: 25 points (bonus) + - **Purple Food**: 50 points (special) +4. Speed increases every 50 points (new level) +5. Try to achieve the highest score possible! + +### Difficulty Levels +- **Easy**: Slower speed, more forgiving gameplay +- **Medium**: Balanced speed and challenge (default) +- **Hard**: Faster speed, more challenging gameplay + +## Game Features + +### Visual Elements +- **Snake Head**: Dark green with white border +- **Snake Body**: Bright green segments +- **Food Types**: Different colors and effects +- **UI Elements**: Score, high score, level display +- **Smooth Animations**: Fluid movement and transitions + +### Scoring System +- **Normal Food**: 10 points +- **Bonus Food**: 25 points +- **Special Food**: 50 points +- **Level Bonus**: Speed increases every 50 points +- **High Score**: Automatically saved and displayed + +### Game States +- **Main Menu**: Choose difficulty and view options +- **Playing**: Active gameplay +- **Paused**: Game paused, can resume +- **Game Over**: Final score and restart options +- **High Scores**: View your best performance + +## Technical Details + +### Architecture +- **Object-Oriented Design**: Clean, modular code structure +- **State Management**: Proper game state handling +- **Event-Driven**: Responsive input handling +- **Performance Optimized**: Smooth 60 FPS gameplay + +### File Structure +``` +Snake_Game/ +ā”œā”€ā”€ snake_game.py # Main game file +ā”œā”€ā”€ README.md # This documentation +ā”œā”€ā”€ requirements.txt # Dependencies +└── high_score.json # High score storage (auto-generated) +``` + +### Dependencies +- **pygame**: Game development library +- **json**: High score persistence +- **random**: Food placement +- **sys**: System operations +- **os**: File operations + +## Customization + +### Easy Modifications +- **Colors**: Change color scheme in constants section +- **Speed**: Adjust initial speed and level progression +- **Grid Size**: Modify GRID_SIZE for different resolutions +- **Food Types**: Add new food types with custom behaviors +- **Scoring**: Adjust point values for different food types + +### Advanced Customization +- **Sound Effects**: Add audio with pygame.mixer +- **Power-ups**: Implement special abilities +- **Multiplayer**: Add two-player mode +- **Themes**: Create different visual themes +- **Mobile Support**: Adapt for touch controls + +## Troubleshooting + +### Common Issues +1. **Pygame not found**: Install with `pip install pygame` +2. **Game runs too fast/slow**: Adjust speed settings in code +3. **Controls not responsive**: Check for conflicting key mappings +4. **High score not saving**: Ensure write permissions in game directory + +### Performance Tips +- Close other applications for better performance +- Use fullscreen mode for smoother gameplay +- Adjust speed settings if game feels sluggish + +## Contributing + +Contributions are welcome! Areas for improvement: +- **New Features**: Power-ups, obstacles, multiplayer +- **Visual Enhancements**: Better graphics, animations, effects +- **Audio**: Sound effects and background music +- **Mobile Support**: Touch controls and mobile optimization +- **AI Mode**: Computer-controlled snake opponent +- **Level Editor**: Custom level creation tools + +## Future Enhancements + +- **Multiplayer Mode**: Local and online multiplayer +- **Power-ups**: Speed boost, invincibility, score multiplier +- **Obstacles**: Walls and barriers to navigate +- **Themes**: Multiple visual themes and skins +- **Achievements**: Unlockable achievements and rewards +- **Statistics**: Detailed gameplay statistics and analytics + +## License + +This project is open source and available under the MIT License. + +--- + +**Enjoy the classic Snake experience with modern enhancements!** šŸšŸŽ® + +Try to beat your high score and challenge your friends! diff --git a/Snake_Game/requirements.txt b/Snake_Game/requirements.txt new file mode 100644 index 00000000..5d2caa22 --- /dev/null +++ b/Snake_Game/requirements.txt @@ -0,0 +1 @@ +pygame>=2.0.0 diff --git a/Snake_Game/snake_game.py b/Snake_Game/snake_game.py new file mode 100644 index 00000000..33999d8d --- /dev/null +++ b/Snake_Game/snake_game.py @@ -0,0 +1,488 @@ +#!/usr/bin/env python3 +""" +Snake Game - Classic Arcade Game +================================ + +A modern implementation of the classic Snake game with enhanced features: +- Smooth gameplay with customizable speed +- Score tracking and high score system +- Multiple difficulty levels +- Beautiful graphics and animations +- Sound effects (optional) +- Pause functionality +- Game over screen with restart option + +Author: AI Assistant +Language: Python 3 +Dependencies: pygame, random, sys, os +""" + +import pygame +import random +import sys +import os +import json +from enum import Enum + +# Initialize Pygame +pygame.init() + +# Constants +WINDOW_WIDTH = 800 +WINDOW_HEIGHT = 600 +GRID_SIZE = 20 +GRID_WIDTH = WINDOW_WIDTH // GRID_SIZE +GRID_HEIGHT = WINDOW_HEIGHT // GRID_SIZE + +# Colors (RGB) +BLACK = (0, 0, 0) +WHITE = (255, 255, 255) +GREEN = (0, 255, 0) +RED = (255, 0, 0) +BLUE = (0, 0, 255) +YELLOW = (255, 255, 0) +PURPLE = (128, 0, 128) +ORANGE = (255, 165, 0) +GRAY = (128, 128, 128) +DARK_GREEN = (0, 150, 0) +LIGHT_GREEN = (144, 238, 144) + +# Game states +class GameState(Enum): + MENU = 1 + PLAYING = 2 + PAUSED = 3 + GAME_OVER = 4 + HIGH_SCORES = 5 + +# Directions +class Direction(Enum): + UP = (0, -1) + DOWN = (0, 1) + LEFT = (-1, 0) + RIGHT = (1, 0) + +class Snake: + def __init__(self, x, y): + self.body = [(x, y)] + self.direction = Direction.RIGHT + self.grow = False + + def move(self): + head_x, head_y = self.body[0] + dx, dy = self.direction.value + new_head = (head_x + dx, head_y + dy) + + self.body.insert(0, new_head) + + if not self.grow: + self.body.pop() + else: + self.grow = False + + def change_direction(self, new_direction): + # Prevent reversing into itself + if (self.direction == Direction.UP and new_direction == Direction.DOWN) or \ + (self.direction == Direction.DOWN and new_direction == Direction.UP) or \ + (self.direction == Direction.LEFT and new_direction == Direction.RIGHT) or \ + (self.direction == Direction.RIGHT and new_direction == Direction.LEFT): + return + self.direction = new_direction + + def grow_snake(self): + self.grow = True + + def check_collision(self): + head_x, head_y = self.body[0] + + # Check wall collision + if head_x < 0 or head_x >= GRID_WIDTH or head_y < 0 or head_y >= GRID_HEIGHT: + return True + + # Check self collision + if (head_x, head_y) in self.body[1:]: + return True + + return False + + def draw(self, screen): + for i, (x, y) in enumerate(self.body): + rect = pygame.Rect(x * GRID_SIZE, y * GRID_SIZE, GRID_SIZE, GRID_SIZE) + + if i == 0: # Head + pygame.draw.rect(screen, DARK_GREEN, rect) + pygame.draw.rect(screen, WHITE, rect, 2) + else: # Body + pygame.draw.rect(screen, GREEN, rect) + pygame.draw.rect(screen, WHITE, rect, 1) + +class Food: + def __init__(self): + self.position = self.generate_position() + self.type = random.choice(['normal', 'bonus', 'special']) + self.color = self.get_color() + + def generate_position(self): + x = random.randint(0, GRID_WIDTH - 1) + y = random.randint(0, GRID_HEIGHT - 1) + return (x, y) + + def get_color(self): + colors = { + 'normal': RED, + 'bonus': YELLOW, + 'special': PURPLE + } + return colors[self.type] + + def draw(self, screen): + x, y = self.position + rect = pygame.Rect(x * GRID_SIZE, y * GRID_SIZE, GRID_SIZE, GRID_SIZE) + pygame.draw.rect(screen, self.color, rect) + pygame.draw.rect(screen, WHITE, rect, 2) + + # Add special effects for different food types + if self.type == 'bonus': + inner_rect = pygame.Rect(x * GRID_SIZE + 4, y * GRID_SIZE + 4, + GRID_SIZE - 8, GRID_SIZE - 8) + pygame.draw.rect(screen, ORANGE, inner_rect) + elif self.type == 'special': + center_x = x * GRID_SIZE + GRID_SIZE // 2 + center_y = y * GRID_SIZE + GRID_SIZE // 2 + pygame.draw.circle(screen, WHITE, (center_x, center_y), 4) + +class Game: + def __init__(self): + self.screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) + pygame.display.set_caption("Snake Game - Classic Arcade") + self.clock = pygame.time.Clock() + self.font = pygame.font.Font(None, 36) + self.small_font = pygame.font.Font(None, 24) + self.large_font = pygame.font.Font(None, 72) + + self.state = GameState.MENU + self.score = 0 + self.high_score = self.load_high_score() + self.level = 1 + self.speed = 10 + self.snake = None + self.food = None + self.paused = False + + # Game settings + self.difficulty = "Medium" + self.sound_enabled = True + + def load_high_score(self): + try: + with open('high_score.json', 'r') as f: + data = json.load(f) + return data.get('high_score', 0) + except FileNotFoundError: + return 0 + + def save_high_score(self): + data = {'high_score': self.high_score} + with open('high_score.json', 'w') as f: + json.dump(data, f) + + def start_game(self): + self.state = GameState.PLAYING + self.score = 0 + self.level = 1 + self.speed = 10 + + # Initialize snake in center + start_x = GRID_WIDTH // 2 + start_y = GRID_HEIGHT // 2 + self.snake = Snake(start_x, start_y) + + # Generate first food + self.food = Food() + + # Adjust speed based on difficulty + if self.difficulty == "Easy": + self.speed = 8 + elif self.difficulty == "Hard": + self.speed = 15 + else: # Medium + self.speed = 10 + + def handle_events(self): + for event in pygame.event.get(): + if event.type == pygame.QUIT: + return False + + if event.type == pygame.KEYDOWN: + if self.state == GameState.MENU: + self.handle_menu_input(event.key) + elif self.state == GameState.PLAYING: + self.handle_game_input(event.key) + elif self.state == GameState.PAUSED: + self.handle_pause_input(event.key) + elif self.state == GameState.GAME_OVER: + self.handle_game_over_input(event.key) + elif self.state == GameState.HIGH_SCORES: + self.handle_high_scores_input(event.key) + + return True + + def handle_menu_input(self, key): + if key == pygame.K_1: + self.difficulty = "Easy" + self.start_game() + elif key == pygame.K_2: + self.difficulty = "Medium" + self.start_game() + elif key == pygame.K_3: + self.difficulty = "Hard" + self.start_game() + elif key == pygame.K_h: + self.state = GameState.HIGH_SCORES + elif key == pygame.K_ESCAPE: + return False + + def handle_game_input(self, key): + if key == pygame.K_UP or key == pygame.K_w: + self.snake.change_direction(Direction.UP) + elif key == pygame.K_DOWN or key == pygame.K_s: + self.snake.change_direction(Direction.DOWN) + elif key == pygame.K_LEFT or key == pygame.K_a: + self.snake.change_direction(Direction.LEFT) + elif key == pygame.K_RIGHT or key == pygame.K_d: + self.snake.change_direction(Direction.RIGHT) + elif key == pygame.K_SPACE: + self.state = GameState.PAUSED + elif key == pygame.K_ESCAPE: + self.state = GameState.MENU + + def handle_pause_input(self, key): + if key == pygame.K_SPACE: + self.state = GameState.PLAYING + elif key == pygame.K_ESCAPE: + self.state = GameState.MENU + + def handle_game_over_input(self, key): + if key == pygame.K_r: + self.start_game() + elif key == pygame.K_m: + self.state = GameState.MENU + elif key == pygame.K_ESCAPE: + return False + + def handle_high_scores_input(self, key): + if key == pygame.K_ESCAPE or key == pygame.K_m: + self.state = GameState.MENU + + def update_game(self): + if self.state != GameState.PLAYING: + return + + self.snake.move() + + # Check collision + if self.snake.check_collision(): + self.game_over() + return + + # Check food collision + if self.snake.body[0] == self.food.position: + self.eat_food() + + # Level up based on score + new_level = (self.score // 50) + 1 + if new_level > self.level: + self.level = new_level + self.speed = min(20, self.speed + 1) # Increase speed, max 20 + + def eat_food(self): + # Add score based on food type + if self.food.type == 'normal': + self.score += 10 + elif self.food.type == 'bonus': + self.score += 25 + elif self.food.type == 'special': + self.score += 50 + + self.snake.grow_snake() + + # Generate new food + self.food = Food() + + # Make sure food doesn't spawn on snake + while self.food.position in self.snake.body: + self.food = Food() + + # Update high score + if self.score > self.high_score: + self.high_score = self.score + self.save_high_score() + + def game_over(self): + self.state = GameState.GAME_OVER + + def draw_menu(self): + self.screen.fill(BLACK) + + # Title + title_text = self.large_font.render("SNAKE GAME", True, GREEN) + title_rect = title_text.get_rect(center=(WINDOW_WIDTH//2, 100)) + self.screen.blit(title_text, title_rect) + + # Subtitle + subtitle_text = self.font.render("Classic Arcade Experience", True, WHITE) + subtitle_rect = subtitle_text.get_rect(center=(WINDOW_WIDTH//2, 150)) + self.screen.blit(subtitle_text, subtitle_rect) + + # Menu options + menu_options = [ + "1. Easy Mode", + "2. Medium Mode (Default)", + "3. Hard Mode", + "H. High Scores", + "ESC. Exit" + ] + + y_offset = 250 + for option in menu_options: + text = self.font.render(option, True, WHITE) + text_rect = text.get_rect(center=(WINDOW_WIDTH//2, y_offset)) + self.screen.blit(text, text_rect) + y_offset += 50 + + # Instructions + instructions = [ + "Controls:", + "Arrow Keys or WASD - Move", + "Space - Pause", + "ESC - Menu/Exit" + ] + + y_offset = 500 + for instruction in instructions: + text = self.small_font.render(instruction, True, GRAY) + text_rect = text.get_rect(center=(WINDOW_WIDTH//2, y_offset)) + self.screen.blit(text, text_rect) + y_offset += 25 + + def draw_game(self): + self.screen.fill(BLACK) + + # Draw snake and food + self.snake.draw(self.screen) + self.food.draw(self.screen) + + # Draw UI + score_text = self.font.render(f"Score: {self.score}", True, WHITE) + self.screen.blit(score_text, (10, 10)) + + high_score_text = self.font.render(f"High Score: {self.high_score}", True, WHITE) + self.screen.blit(high_score_text, (10, 50)) + + level_text = self.font.render(f"Level: {self.level}", True, WHITE) + self.screen.blit(level_text, (10, 90)) + + # Pause indicator + if self.state == GameState.PAUSED: + pause_text = self.large_font.render("PAUSED", True, YELLOW) + pause_rect = pause_text.get_rect(center=(WINDOW_WIDTH//2, WINDOW_HEIGHT//2)) + self.screen.blit(pause_text, pause_rect) + + resume_text = self.font.render("Press SPACE to resume", True, WHITE) + resume_rect = resume_text.get_rect(center=(WINDOW_WIDTH//2, WINDOW_HEIGHT//2 + 50)) + self.screen.blit(resume_text, resume_rect) + + def draw_game_over(self): + self.screen.fill(BLACK) + + # Game Over text + game_over_text = self.large_font.render("GAME OVER", True, RED) + game_over_rect = game_over_text.get_rect(center=(WINDOW_WIDTH//2, 200)) + self.screen.blit(game_over_text, game_over_rect) + + # Final score + final_score_text = self.font.render(f"Final Score: {self.score}", True, WHITE) + final_score_rect = final_score_text.get_rect(center=(WINDOW_WIDTH//2, 280)) + self.screen.blit(final_score_text, final_score_rect) + + # High score + if self.score == self.high_score: + new_record_text = self.font.render("NEW HIGH SCORE!", True, YELLOW) + new_record_rect = new_record_text.get_rect(center=(WINDOW_WIDTH//2, 320)) + self.screen.blit(new_record_text, new_record_rect) + + # Options + options = [ + "R. Play Again", + "M. Main Menu", + "ESC. Exit" + ] + + y_offset = 400 + for option in options: + text = self.font.render(option, True, WHITE) + text_rect = text.get_rect(center=(WINDOW_WIDTH//2, y_offset)) + self.screen.blit(text, text_rect) + y_offset += 50 + + def draw_high_scores(self): + self.screen.fill(BLACK) + + # Title + title_text = self.large_font.render("HIGH SCORES", True, GREEN) + title_rect = title_text.get_rect(center=(WINDOW_WIDTH//2, 100)) + self.screen.blit(title_text, title_rect) + + # High score + high_score_text = self.font.render(f"Best Score: {self.high_score}", True, YELLOW) + high_score_rect = high_score_text.get_rect(center=(WINDOW_WIDTH//2, 200)) + self.screen.blit(high_score_text, high_score_rect) + + # Instructions + instruction_text = self.font.render("Press ESC or M to return to menu", True, WHITE) + instruction_rect = instruction_text.get_rect(center=(WINDOW_WIDTH//2, 300)) + self.screen.blit(instruction_text, instruction_rect) + + def draw(self): + if self.state == GameState.MENU: + self.draw_menu() + elif self.state == GameState.PLAYING or self.state == GameState.PAUSED: + self.draw_game() + elif self.state == GameState.GAME_OVER: + self.draw_game_over() + elif self.state == GameState.HIGH_SCORES: + self.draw_high_scores() + + pygame.display.flip() + + def run(self): + running = True + + while running: + running = self.handle_events() + + if self.state == GameState.PLAYING: + self.update_game() + + self.draw() + self.clock.tick(self.speed) + + pygame.quit() + sys.exit() + +def main(): + """Main function to run the Snake Game""" + print("šŸ Starting Snake Game...") + print("Controls:") + print(" Arrow Keys or WASD - Move") + print(" Space - Pause") + print(" ESC - Menu/Exit") + print(" R - Restart (Game Over)") + print(" H - High Scores") + print("\nEnjoy the game!") + + game = Game() + game.run() + +if __name__ == "__main__": + main() diff --git a/hellow-world.java b/hellow-world.java new file mode 100644 index 00000000..076e51a5 --- /dev/null +++ b/hellow-world.java @@ -0,0 +1,7 @@ +class Test +{ + public static void main(String []args) + { + System.out.println("My First Java Program."); + } +}; diff --git a/javascript/findMin.js b/javascript/findMin.js new file mode 100644 index 00000000..5f1c163e --- /dev/null +++ b/javascript/findMin.js @@ -0,0 +1,22 @@ +/** + * Finds the minimum value in an array of numbers. + * @param {number[]} arr - The array to search. + * @returns {number} The minimum value. + */ +function findMin(arr) { + if (!Array.isArray(arr) || arr.length === 0) { + throw new Error('Input must be a non-empty array'); + } + let min = arr[0]; + for (let i = 1; i < arr.length; i++) { + if (arr[i] < min) { + min = arr[i]; + } + } + return min; +} + +// Example usage: +// console.log(findMin([3, 1, 4, 1, 5, 9])); // Output: 1 + +module.exports = findMin; \ No newline at end of file diff --git a/pandas/Average Salary of Each Department.py b/pandas/Average Salary of Each Department.py new file mode 100644 index 00000000..ac282d5d --- /dev/null +++ b/pandas/Average Salary of Each Department.py @@ -0,0 +1,14 @@ +Employee = pd.DataFrame({ + 'id': [1, 2, 3, 4], + 'name': ['Alice', 'Bob', 'Charlie', 'David'], + 'salary': [5000, 7000, 6000, 8000], + 'departmentId': [1, 1, 2, 2] +}) +Department = pd.DataFrame({ + 'id': [1, 2], + 'name': ['HR', 'Engineering'] +}) + +merged = Employee.merge(Department, left_on='departmentId', right_on='id') +result = merged.groupby('name_y', as_index=False)['salary'].mean().rename(columns={'name_y': 'department'}) +print(result) diff --git a/pandas/Customers Who Never Ordered.py b/pandas/Customers Who Never Ordered.py new file mode 100644 index 00000000..89152990 --- /dev/null +++ b/pandas/Customers Who Never Ordered.py @@ -0,0 +1,12 @@ +Customers = pd.DataFrame({ + 'id': [1, 2, 3], + 'name': ['Alice', 'Bob', 'Charlie'] +}) +Orders = pd.DataFrame({ + 'id': [1, 2], + 'customerId': [1, 2] +}) + +merged = Customers.merge(Orders, left_on='id', right_on='customerId', how='left') +result = merged[merged['customerId'].isna()][['name']] +print(result) diff --git a/pandas/Department Highest Salary.py b/pandas/Department Highest Salary.py new file mode 100644 index 00000000..56c1b8c2 --- /dev/null +++ b/pandas/Department Highest Salary.py @@ -0,0 +1,16 @@ +Employee = pd.DataFrame({ + 'id': [1, 2, 3, 4], + 'name': ['Alice', 'Bob', 'Charlie', 'David'], + 'salary': [5000, 7000, 6000, 7000], + 'departmentId': [1, 1, 2, 2] +}) + +Department = pd.DataFrame({ + 'id': [1, 2], + 'name': ['HR', 'Engineering'] +}) + +merged = Employee.merge(Department, left_on='departmentId', right_on='id', suffixes=('', '_dept')) +max_salary = merged.groupby('departmentId')['salary'].transform('max') +result = merged[merged['salary'] == max_salary][['name_dept', 'name', 'salary']] +print(result) diff --git a/pandas/Employees Earning More Than Their Managers.py b/pandas/Employees Earning More Than Their Managers.py new file mode 100644 index 00000000..fcc173cb --- /dev/null +++ b/pandas/Employees Earning More Than Their Managers.py @@ -0,0 +1,13 @@ +import pandas as pd + +data = { + 'id': [1, 2, 3, 4], + 'name': ['Alice', 'Bob', 'Charlie', 'David'], + 'salary': [5000, 7000, 6000, 8000], + 'managerId': [None, 1, 1, 2] +} +Employee = pd.DataFrame(data) + +df = Employee.merge(Employee, left_on='managerId', right_on='id', suffixes=('', '_manager')) +result = df[df['salary'] > df['salary_manager']][['name']] +print(result) diff --git a/pandas/Second Highest Salary.py b/pandas/Second Highest Salary.py new file mode 100644 index 00000000..037febac --- /dev/null +++ b/pandas/Second Highest Salary.py @@ -0,0 +1,6 @@ +Employee = pd.DataFrame({ + 'id': [1, 2, 3], + 'salary': [100, 200, 300] +}) +second_highest = Employee['salary'].drop_duplicates().nlargest(2).min() +print(second_highest)