//HW8: HANGMAN GAME import java.util.Scanner; public class Main { static Scanner scanner = new Scanner(System.in); static int lives = 5; static String inputWord; static String playerInputLetter; static char[] hangmasterInputWordArray; static boolean letterFound = false; static boolean youWin = false; public static void main(String[] args) { System.out.println("~*]HANGMAN[*~"); System.out.println("Good day, Hangmaster. Please enter the word that your victim will have to guess. =)"); System.out.println("Make sure the word only uses lowercase letters (a-z). No numbers or special characters! And NO SPACEBAR D:<"); System.out.println("Of course make sure that your precious victim isn't looking! ;]"); do { inputWord = scanner.nextLine().trim(); hangmasterInputWordArray = inputWord.toCharArray(); if (!isHangmasterInputValid()) { System.out.println("Invalid input! >=( Please enter a word using only lowercase letters (a-z). No numbers or special characters! And NO SPACEBAR D:<"); } } while (!isHangmasterInputValid()); drawHangman(); play(); } public static boolean isHangmasterInputValid() { if (inputWord == null || inputWord.isBlank()) { return false; } for(int i =0; i<hangmasterInputWordArray.length; i++) { char checkInputWordChar = hangmasterInputWordArray[i]; if (checkInputWordChar < 'a' || checkInputWordChar > 'z' ) { return false; } } return true; } public static boolean isPlayerInputValid() { if (playerInputLetter == null || playerInputLetter.isBlank()) { return false; } if (playerInputLetter.length() != 1) { System.out.println("Invalid input! Please input a valid lowercase LETTER! No capital letter, symbols or numbers =) And just ONE letter! AND NO SPACEBAR D:<"); return false; } char checkInputLetterChar = playerInputLetter.charAt(0); if (checkInputLetterChar < 'a' || checkInputLetterChar > 'z') { return false; } return true; } public static void drawHangman() { System.out.println("~*]HANGMAN[*~"); if(youWin) { System.out.println("*******************************************"); System.out.println("*__ _____ _ _ __ _____ _ _ *"); System.out.println("*\\ \\ / / _ \\| | | | \\ \\ / /_ _| \\ | |*"); System.out.println("* \\ V / | | | | | | \\ \\ /\\ / / | || \\| |*"); System.out.println("* | || |_| | |_| | \\ V V / | || |\\ |*"); System.out.println("* |_| \\___/ \\___/ \\_/\\_/ |___|_| \\_|*"); System.out.println("*******************************************"); System.out.println(); System.out.println(" \\😄/"); System.out.println(" ██"); System.out.println(" / \\"); return; } if(lives<3) { System.out.println("______________"); System.out.println("=============="); } else { System.out.println(); } if(lives<2) { System.out.println(" | ||"); } else if(lives<4) { System.out.println(" ||"); } else { System.out.println(); } if(lives == 5) { System.out.println(); System.out.println(); } switch(lives) { case 5: System.out.println(); System.out.println(" 🙂"); break; case 4: System.out.println(" 😐"); break; case 3: System.out.println(" ☹️ ||"); break; case 2: System.out.println(" 😨 ||"); break; case 1: System.out.println(" 😭 ||"); break; case 0: System.out.println(" | ||"); System.out.println(" ☠️ ||"); break; } if(lives>=4) { System.out.println(" /██\\"); System.out.println(" / \\"); } if(lives<4) { System.out.println(" /██\\ ||"); System.out.println(" / \\ ||"); } if(lives==4) { System.out.println(" ======"); System.out.println(" | |"); } if(lives==0) { System.out.println(" ||"); } else if(lives<1) { System.out.println(" ||"); System.out.println(" ||"); } else if(lives<4) { System.out.println(" ====== ||"); System.out.println(" | | ||"); } } public static void clearScreen() { try { if (System.getProperty("os.name").contains("Windows")) { new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor(); } else { System.out.print("\033[H\033[2J"); System.out.flush(); } } catch (Exception e) { System.out.println("Failed to clear screen."); } } public static void play() { char[] playerInputProgressArray = new char[hangmasterInputWordArray.length]; for (int i = 0; i < playerInputProgressArray.length; i++) { playerInputProgressArray[i] = '_'; } while (!(lives ==0)) { letterFound = false; if((new String(playerInputProgressArray).equals(new String(hangmasterInputWordArray)))) { youWin = true; drawHangman(); break; } System.out.println(playerInputProgressArray); if(lives>0) { System.out.println("Please input a valid lowercase LETTER! No capital letter, symbols or numbers =) And just ONE letter! AND NO SPACEBAR D:<"); } playerInputLetter = scanner.nextLine().trim(); while(!isPlayerInputValid()) { System.out.println("Invalid input! Please input a valid lowercase LETTER! No capital letter, symbols or numbers =) And just ONE letter! AND NO SPACEBAR D:<"); playerInputLetter= scanner.nextLine(); } System.out.println("Your choice is the letter: "+playerInputLetter); char playerInputLetterChar = playerInputLetter.charAt(0); for (int i = 0; i < hangmasterInputWordArray.length; i++) { if(playerInputLetterChar == hangmasterInputWordArray[i]) { playerInputProgressArray[i] = playerInputLetterChar; letterFound = true; } } if(!letterFound) { lives--; } drawHangman(); } if (youWin) { System.out.println("The word is: "+ inputWord); System.out.println("Congratulations, you survived! =D"); } else { System.out.println("TOO LATE, YOU FAILED >=]"); System.out.println("The word was: "+inputWord); System.out.println("☠-GAME OVER-☠"); } } }
Latest from community today
import java.io.*; import java.util.*; /* * To execute Java, please define "static void main" on a class * named Solution. * * If you need more classes, simply define them inline. */ class Solution { public static void main(String[] args) { ArrayList<String> strings = new ArrayList<String>(); strings.add("Hello, World!"); strings.add("Running Java " + Runtime.version().feature()); for (String string : strings) { System.out.println(string); } } }
class Solution implements Runnable { private String name; static private Integer val = 0; public Solution(String name) { this.name = name; } @Override public void run() { for(int i = 0; i<10000; i++) { add(); print(i); } } public synchronized void add() { int tmp = val; try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } val = tmp + 1; } public void print(int index) { System.out.println( this.name + " " + index + ": " + val); } public static void main(String[] args) { new Thread( new Solution("Proc-1") ).start(); new Thread( new Solution("Proc-2") ).start(); } }
// Online Java Compiler // Use this editor to write, compile and run your Java code online import java.util.*; class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); // all four possible moves int[][] moves = new int[4][2]; moves[0] = new int[]{0,1}; moves[1] = new int[]{1,0}; moves[2] = new int[]{0,-1}; moves[3] = new int[]{-1,0}; // define matrix int[][] mat = new int[N][N]; int k = 1; int direction = 0; int x = 0 , y = 0; for(int i = 0 ; i < N*N ; i++) { //assign and take a step mat[x][y] = k; k++; x += moves[direction][0]; y += moves[direction][1]; // check boundaries and already visited if (0 <= x && 0<= y && x < N && y <N && mat[x][y] == 0) { continue; } else { x -= moves[direction][0]; y -= moves[direction][1]; //change direction direction = direction == 3 ? 0 : direction +1; x += moves[direction][0]; y += moves[direction][1]; } //change k } for(int[] arr : mat) { System.out.println(Arrays.toString(arr)); } } }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { private final UserRepository userRepository; private final EmailService emailService; @Autowired public UserService(UserRepository userRepository, EmailService emailService) { this.userRepository = userRepository; this.emailService = emailService; } public boolean registerUser(String email) { if (userRepository.existsByEmail(email)) { return false; } User newUser = new User(email); userRepository.save(newUser); emailService.sendWelcomeEmail(email); return true; } }
class Solution implements Runnable { private String name; static private Integer val = 0; public Solution(String name) { this.name = name; } @Override public void run() { for(int i = 0; i<10000; i++) { add(); print(i); } } public synchronized void add() { int tmp = val; try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } val = tmp + 1; } public void print(int index) { System.out.println( this.name + " " + index + ": " + val); } public static void main(String[] args) { new Thread( new Solution("Proc-1") ).start(); new Thread( new Solution("Proc-2") ).start(); } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; class PhonePeController extends Controller { public function index() { return view('phonepe_form'); // A simple form to enter amount and pay } private function getPhonePeAccessToken() { $clientId = env('PHONEPE_CLIENT_ID'); $clientSecret = env('PHONEPE_CLIENT_SECRET'); Log::info('[PhonePe] Generating access token', [ 'client_id' => $clientId, 'client_version' => '1' ]); $response = Http::asForm()->post('https://api.phonepe.com/apis/identity-manager/v1/oauth/token', [ 'client_id' => $clientId, 'client_secret' => $clientSecret, 'grant_type' => 'client_credentials', 'client_version' => '1', ]); Log::info('[PhonePe] Token API Raw Response:', $response->json()); $responseJson = $response->json(); $accessToken = $responseJson['access_token'] ?? $responseJson['data']['accessToken'] ?? null; if ($accessToken) { Log::info('[PhonePe] Access token generated successfully'); return $accessToken; } Log::error('[PhonePe] Failed to generate access token', [ 'response' => $responseJson ]); return null; } public function createOrder(Request $request) { $request->validate([ 'amount' => 'required|numeric|min:1' ]); $accessToken = $this->getPhonePeAccessToken(); if (!$accessToken) { return back()->with('error', 'Access token generation failed.'); } $orderId = uniqid('TX'); // Unique Order ID $amount = $request->input('amount') * 100; // INR to paise $payload = [ "merchantOrderId" => $orderId, "amount" => $amount, "paymentFlow" => [ "type" => "PG_CHECKOUT", "message" => "Order #" . $orderId, "merchantUrls" => [ "redirectUrl" => route('phonepe.confirm') ] ] ]; Log::info('[PhonePe Production PG Checkout] Request Payload:', $payload); $response = Http::withHeaders([ 'Authorization' => 'O-Bearer ' . $accessToken, 'Content-Type' => 'application/json' ])->post('https://api.phonepe.com/apis/pg/checkout/v2/pay', $payload); Log::info('[PhonePe Production PG Checkout] Response:', $response->json()); $responseData = $response->json(); if ($response->ok() && isset($responseData['redirectUrl'])) { session(['phonepe_order_id' => $orderId]); return redirect()->away($responseData['redirectUrl']); } return back()->with('error', 'Payment initiation failed. Check logs.'); } public function confirmPayment(Request $request) { $orderId = $request->input('merchantOrderId') ?? session('phonepe_order_id'); Log::info('[PhonePe] Returned to confirm route', [ 'merchantOrderId' => $orderId, 'input' => $request->all() ]); if (!$orderId) { return view('phonepe_confirm')->with('status', 'Order ID missing.'); } // You can optionally check status here using status API return view('phonepe_confirm', [ 'status' => 'Redirected back from PhonePe.', 'orderId' => $orderId ]); } }
#include<iostream> #include<thread> #include<mutex> #include<condition_variable> #include<vector> #define N 1000 class BinarySemaphore{ private: std::mutex mtx_; std::condition_variable cv_; int binary_value; public: // always initialize with 1 value iet can have on 2 values i.e 1 or 0 BinarySemaphore(){ this->binary_value=1; } // down operation void acquire(){ std::unique_lock<std::mutex> lock(mtx_); // suspend if value is 0, else enter critical section cv_.wait(lock, [&](){ return (this->binary_value==1); }); this->binary_value=0; // entered critical section } // up operation void release(){ std::unique_lock<std::mutex> lock(mtx_); this->binary_value=1; cv_.notify_one(); } }; std::mutex mtx; BinarySemaphore mutual_exclusion_semaphore; // mutual exclusion semaphore prevents concurrenly access of read operation BinarySemaphore read_write_db_semaphore; // write mutex only for writers and not used by readers int readers_count=0; // number of processes currently in read write db int shared_data=0; // shared data void reader(int id){ // a reader acquires mutex lock mutual_exclusion_semaphore.acquire(); { std::lock_guard<std::mutex> lock(mtx); readers_count+=1; std::cout<<"Reader count: "<<readers_count<<std::endl; } // this is the first reader, lock wrt to block writers if(readers_count==1){ read_write_db_semaphore.acquire(); // entry code for critical section } mutual_exclusion_semaphore.release(); // reset mutex lock so that next reader can read the data // critical section i.e reading { std::lock_guard<std::mutex> lock(mtx); std::cout << "Reader " << id << " read: " << shared_data << std::endl; } // reduce reader count when exiting cs and release resource so that // writer can write when no reader is on cs mutual_exclusion_semaphore.acquire(); { std::lock_guard<std::mutex> lock(mtx); readers_count-=1; } if(readers_count==0){ read_write_db_semaphore.release(); // entry code for critical section } mutual_exclusion_semaphore.release(); } void writer(int id ){ // writer acquires read write resources read_write_db_semaphore.acquire(); { // critical section std::lock_guard<std::mutex> lock(mtx); shared_data+=1; std::cout << "Writer " << id << " read: " << shared_data << std::endl; } read_write_db_semaphore.release(); } int main() { /* // for loops runs threads sequentially and not concurrently // so it will always show reader count as 1 as it always gets decremented to 0 in a sequential manner // so no overlaps of readers are shown here std::thread reader_threads([] { for (int i=1;i<=N;i++){ reader(); } }); std::thread writers_thread([] { for (int i=1;i<=N;i++){ writer(); } }); reader_threads.join(); writers_thread.join(); */ std::vector<std::thread> threads; // Create mixed reader/writer threads for (int i = 0; i < N; i++) { if (i % 5 == 0) { // 20% writers, 80% readers threads.emplace_back(writer, i); } else { threads.emplace_back(reader, i); } } // Join all threads for (auto& t : threads) { t.join(); } std::cout << "Final value: " << shared_data << std::endl; return 0; }
#include <iostream> #include <thread> #include <cstring> #include <sys/socket.h> #include <unistd.h> #include <netinet/in.h> #include <mutex> #include <condition_variable> // Solving Producer consumer problem using Message Passing // (socket programming process to process communication) std::mutex mtx; std::condition_variable cv; bool isProducerReady = false; #define N 100 // on 100 message can be resolved at a time // Producer code class ProducerClass { private: int item=0; public: void operator()(void) { // Server code(producer) here which will send msg on demand to client (consumer) // creating socket, server socket is a file descriptor int serverSocket = socket(AF_INET, SOCK_STREAM, 0); if (serverSocket == -1) { perror("Socket creation failed"); return; } // Allow reusing the same address to prevent binding failures on quick restarts int opt = 1; setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); // defining the address sockaddr_in serverAddress; serverAddress.sin_family = AF_INET; serverAddress.sin_port = htons(8080); serverAddress.sin_addr.s_addr = INADDR_ANY; // bind socket if (bind(serverSocket, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0) { perror("Bind failed"); close(serverSocket); return; } // listen to assigned socket if (listen(serverSocket, 2) < 0) { perror("Listen failed"); close(serverSocket); return; } // when producer is ready i.e true, release the lock { std::lock_guard<std::mutex> lock(mtx); isProducerReady = true; cv.notify_one(); } // accept connections int clientSocket = accept(serverSocket, nullptr, nullptr); if (clientSocket < 0) { perror("Accept failed"); close(serverSocket); return; } char buffer[1024] = {0}; std::string leftover = ""; while (true) { int bytesReceived = recv(clientSocket, buffer, sizeof(buffer) - 1, 0); if (bytesReceived <= 0) break; // Connection closed buffer[bytesReceived] = '\0'; // null termination std::string receivedData = leftover + std::string(buffer); leftover.clear(); size_t pos; while ((pos = receivedData.find('\n')) != std::string::npos) { std::string message = receivedData.substr(0, pos); receivedData.erase(0, pos + 1); if (!message.empty()) { std::cout << "\nReceived: " << message << std::endl; { std::lock_guard<std::mutex> lock(mtx); item++; } std::string response = std::to_string(item) + "\n"; send(clientSocket, response.c_str(), response.length(), 0); } } leftover = receivedData; } close(clientSocket); close(serverSocket); } }; // Consumer code class ConsumerClass { public: void operator()(void) { std::unique_lock<std::mutex> lock(mtx); // wait until producer is ready(server setups) cv.wait(lock, [] { return isProducerReady; }); lock.unlock(); // creating socket int clientSocket = socket(AF_INET, SOCK_STREAM, 0); if (clientSocket == -1) { perror("Socket creation failed"); return; } // specifying address sockaddr_in serverAddress; serverAddress.sin_family = AF_INET; serverAddress.sin_port = htons(8080); serverAddress.sin_addr.s_addr = INADDR_ANY; // sending connection request if (connect(clientSocket, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0) { perror("Connection failed"); close(clientSocket); return; } // send empty messages for(int i=1;i<=N;i++){ // sending data std::string message = "_empty_string_\n"; send(clientSocket, message.c_str(), message.length(), 0); } // Receive responses char buffer[1024] = {0}; int totalResponses = 0; while (totalResponses < N) { int bytesRead = recv(clientSocket, buffer, sizeof(buffer) - 1, 0); if (bytesRead <= 0) break; // Stop when the server closes connection buffer[bytesRead] = '\0'; std::string receivedData(buffer); size_t pos; while ((pos = receivedData.find('\n')) != std::string::npos) { std::string response = receivedData.substr(0, pos); receivedData.erase(0, pos + 1); if (!response.empty()) { std::cout << "Server Response: " << response << std::endl; totalResponses++; } } } // Close socket close(clientSocket); } }; int main() { ProducerClass producer; ConsumerClass consumer; // create two threads for producer and client std::thread t1(producer); std::thread t2(consumer); t1.join(); t2.join(); return 0; }