Recent Entries 10
- pattern minor 112d ago"Choose a number between 0-9" gameThis is a simple "Choose a number between 0-9" Game. It works perfectly but I'd like to know if there's a way to make my code smaller with the exact same functionality. ``` package firstGame; import java.util.Scanner; public class Player { static Scanner p2Name = new Scanner(System.in); static Scanner p1Name = new Scanner(System.in); static Scanner p3Name = new Scanner(System.in); static Scanner p1Num = new Scanner(System.in); static Scanner p2Num = new Scanner(System.in); static Scanner p3Num = new Scanner(System.in); String name; int age; int size; public static void main(String[] args) { // Create a random number generator (0-9) int number = (int) (Math.random() * 10); // Get Player1's name System.out.print("Player 1, please enter your name : "); String p1 = p1Name.nextLine(); System.out.println("Welcome " + p1 + "!"); // Get Player1's chosen number System.out.println("Please enter a number between 0 and 9"); int p1Choice = p1Num.nextInt(); System.out.println(""); // Get Player2's name System.out.print("Player 2, please enter your name : "); String p2 = p2Name.nextLine(); System.out.println("Welcome " + p2 + "!"); // Get Player2's chosen number System.out.println("Please enter a number between 0 and 9"); int p2Choice = p2Num.nextInt(); System.out.println(""); // Get Player3's name System.out.print("Player 3, please enter your name : "); String p3 = p3Name.nextLine(); System.out.println("Welcome " + p3 + "!"); // Get Player3's chosen number System.out.println("Please enter a number between 0 and 9"); int p3Choice = p3Num.nextInt(); System.out.println("");
- pattern moderate 112d agoGuess a number between 1 and 100This is my attempt at writing a guessing game. Where can I improve my code to make it more succinct? Link to Revision 1 (Guess a number between 1 and 100 (revision 1)) ``` //Program.CS namespace MidPointGame { class Program { static void Main(string[] args) { RunTheGame game = new RunTheGame(); } } } //Game.CS namespace MidPointGame { class RunTheGame { int _number; public RunTheGame() { const int lbound = 1; const int ubound = 100; int guessCount; bool keepPlaying = true; bool computerPlays = false; string whoGuessed = ""; Console.WriteLine("Welcome to the numberline game"); Console.WriteLine("Try and guess the number in the fewest guesses possible"); Console.WriteLine("The boundary numbers are included in the range."); Console.WriteLine("Lets begin"); while (keepPlaying) { GenerateNumber(); if (computerPlays) { whoGuessed = "The comupter"; guessCount = ComputerGuess(lbound, ubound); } else { Console.WriteLine($"\nGuess a number between {lbound} and {ubound}."); guessCount = HumanGuess(); whoGuessed = "You"; } Console.WriteLine($"\n{whoGuessed} guessed it in {guessCount} tries"); ContinuePlaying(ref keepPlaying,ref computerPlays); } Console.WriteLine("Thank you for playing\nPress any key to close the program."); Console.ReadKey(); } int HumanGuess() { int _guessCount = 0; int difference = 999; while (difference !=0) { difference = ValidateInput() - _number;
- pattern moderate 112d ago"Guess the number Game" in CJust started learning C. I hope my code adheres to best practices and idioms ``` #include #include #include #include int main(void) { int iRandomNum; int iGuess; srand(time(NULL)); iRandomNum = (rand() % 10); printf("Guess a number between 1 and 10:"); scanf("%d", &iGuess); // isdigit function expects a character so the guess value has to be ascii value of the digit character iGuess += 48; if (isdigit(iGuess)){ iGuess -=48; // change back to the original value for comparison with random number if (iGuess == iRandomNum){ printf("You Guessed Correctly\n"); } else{ printf("The correct answer was %d\n",iRandomNum); printf("You guessed %d\n",iGuess); } } else{ printf("This is not a digit!\n"); } } ```
- pattern minor 112d agoSemi-complex Guess My NumberPlease understand my request before commenting, I'm looking for positive critiques of my work. Anything I've done which could be done better while using the same, or similar, restrictions on data types and #include files that I've used. To put it another way, if you see anything that could be done more efficiently, using the same restrictions, please advise. I know there's more elegant ways to do this. I'm just trying to push my understanding of the basic C++ constructs, before getting into more advanced C++ implementations. code: ``` //02_ex_03_guess_my_number_aplha #include #include #include using namespace std; int main() { bool exitGame = false; bool playAgain = true; bool roundOver = false; char playAgainYes = 'y'; int playModeSelect = 0; int computersNumber = 0; int tooLow = 0; int tooHigh = 101; int playersNumber = 0; int tries = 0; enum playMode { playerVersusCpu = 1, cpuVersusPlayer, exitMenu}; srand(static_cast(time(0))); cout > playModeSelect; switch (playModeSelect) { case playerVersusCpu: cout > playersNumber; if (playersNumber > computersNumber) { cout > playAgainYes; if (playAgainYes == 'y') { playAgain = true; cout > playersNumber; tries = 0; tooLow = 0; tooHigh = 101; do { computersNumber = rand() % 100 + 1; while ((computersNumber != playersNumber) && (computersNumber > tooLow) && (computersNumber tooLow) && (computersNumber playersNumber)) { tooHigh = computersNumber; } } } while (computersNumber
- pattern minor 112d agoGuess number with lower or higher hintsProblem statement Two players - Alice and Bob. Alice needs to guess a number \$n\$, from range \$[1, N]\$, \$N \le 200\$ - In \$i\$th turn, Alice guesses a number \$i\$ - Bob chooses to tell the relation between \$i\$ and \$n\$ (\$n \lt i\$, \$n = i\$ or \$n \gt i\$). Bob could tell what he wants, unless it conflicts with what he says before - Each turn costs \$i\$ - Alice wants to minimize the total costs - Bob wants to maximum the total costs What is the minimal cost if both players take the best strategy? Any performance improvement ideas in terms of algorithm time complexity, code bugs or code style advice is appreciated. More specific question: I do not know how Bob could make sure there is no conflict to what he said in the past -- if he tells number wrong at one time. For example, if \$n\$ is 20, Alice guess \$i\$ = 50, if Bob tells alice \$i\$ is smaller (Bob lies), then Alice will always guess a number > 50, how could Alice achieve the final goal? I think Bob could lie, but finally he should help Alice achieve the final goal, even if in the middle Alice may take more steps (more costs) -- because of some conclusion Bob tells in the middle is not correct. If anyone have any ideas about how Bob could lie (which will maximum cost for Bob as one goal), while at the same time he still make sure no conflict in the future (and finally guide Alice to the right number), it will be great. The major ideas of my code is, I try to use Dynamic programming approach to build dp structure from bottom up, dp[(i,j)] means for numbers start from `i` and ends with `j`, what are minimal cost for Alice. Both `i` and `j` are inclusive. ``` import sys from collections import defaultdict class Solution(object): def getMoneyAmount(self, n): """ :type n: int :rtype: int """ dp = defaultdict(lambda : sys.maxint) # key: tuple (start, end), value: min cost for end in range(1, n+1):
- pattern minor 112d ago"Number guessing game" in PythonI am new to Python and I have tried to come up with a code for the number guessing game. But I am pretty sure this is not the right way to do it. I am able to get the right output, however, my code is pretty long. Any ideas on using a different logic or to reduce the code size would help. I also would like to know how to code profile a python code for performance. I am using IDLE and Python 3.+ ``` import random def main(): while(True): inputchoice = input("Are you ready? Y/N : ") if(inputchoice.strip() in ("y","Y","yes","Yes","YES","YEs","yeS","YeS","yEs","yES")): print("Ok. Lets begin") randomnumberguessinggame() break elif(inputchoice.strip() in ("no","No","NO","nO","n","N")): print("Let me know when you are ready") break else: print("Invalid Entry. Try again") def randomnumberguessinggame(): print("Get ready to start guessing") actualnumber = random.randrange(0,1000) #print("The number to be guessed is %d"%actualnumber) flag = True; while(flag): try: guessednumber = int(input("Enter your guess ")) if(guessednumber > actualnumber): print("That was a wrong guess. Your guess is higher than my number") while(True): retry = input("Would you like to try again? Y/N : ") if(retry.strip() in ("y","Y","yes","Yes","YES","YEs","yeS","YeS","yEs","yES")): flag = True; break elif(retry.strip() in ("no","No","NO","nO","n","N")): flag = False; break else: print("Invalid Entry. Try again") elif(guessednumber < actualnumber): print("That was a wrong guess. Your guess is lower than my number") while(True):
- pattern moderate 112d agoProgram that guesses your number using bitwise operationsI got the idea for this program from this site. functions.cpp: ``` #include #include #include namespace my { int getOneOrZero() { return (rand() >> 14); // >> the bitwise operator } // getArray leaves the numbers ( 0-99 ) that have in their bit position represented by bigFlag the num ( 0 or 1 ) void printNums(int8_t bitFlag, int num) // num is from getOneOrZero() so it's 1 or 0; { for (int counter = 0; counter > answer; std::cin.ignore(32767,'\n'); if (std::cin.fail()) std::cin.clear(); if (answer == 'y' || answer == 'n' || answer == 'r') // I could use switch but nevermind return answer; } } void turnsPassed(int turns) { std::cout << "\n This is turn " << turns << "\n\n"; } int swapZeroOrOne(int num) { switch (num) { case 0 : return 1; case 1 : return 0; default: std::cout << "\nSwapZeroOrOne ERROR !\n"; break; } } int getUpdateForGuessNum(int8_t flag, int num, char answer) { switch (answer) { case 'n' : { int newNum = swapZeroOrOne(num); return newNum*flag; } case 'y' : return num*flag; case 'r' : break; default : std::cout << "\n ERROR ! In getUpdateForGuessNum\n"; break; } } } ``` main.cpp: ``` #include #include #include #include #include "functions.hpp" #include "constants.hpp" #include // for system() commands >.(time(0))); Reset : // goto ! system("cls"); int guessNum = 0; // guessing loop ! for (int counter = 0; counter < 7; ++counter) { if (counter == 0) std::cout << "\n Think of a number between 0 to 99\n"; my::turnsPassed(counter + 1); // +1 cause counter starts from 0 int num {my::getOneOrZero()}; // this gives a randomness to the numbers shown each time you run the programm my::printNums(myVar::bitFlag[counter],num); char answer { my::getAnswer() }; if (a
- pattern minor 112d agoPrinting blocks in guessing gameI wrote a guessing game and I want it to be reduced because there are a lot of `if` statements basically handling the same task with a minor difference. Is there an efficient way to handle all these tasks with less coding? ``` public class master { public static void main(String[] args) { int turn = 9; System.out.println("Welcome to the guessing game"); System.out.println("You have 10 turns to guess"); System.out.println("Your time will be recorded,the faster you finish the better the points"); System.out.println("Enter your minimum value"); int min = In.getInt(); System.out.println("Enter your maximum value"); int max = In.getInt(); System.out.println("Press 1 to begin the game"); int begin = In.getInt(); if (max > min && begin == 1) { int random = (int) ((max - min) * Math.random()) + min; long lStartTime = System.nanoTime(); System.out.println("Enter your guess"); int guess = In.getInt(); while (guess != random && turn > 0) { if (guess > random) { System.out.println("Too High, try decreasing it"); } else if (guess = 0 && seconds = 5) { System.out.println("You won the game"); System.out.println("You have finished in under 10 seconds"); System.out.println("The final score is 500"); System.out.println("Turns Taken:" + " " + ((9 - turn) + 1)); System.out.println("Time Taken:" + " " + seconds + " " + "seconds"); } if (guess == random && turn >= 0 && seconds = 0) { System.out.println("You won the game"); System.out.println("You have finished in under 5 seconds"); System.out.println("The final score is 1000"); System.out.println("Turns Taken:" + " " + ((9 - turn) + 1)); System.out.println("Time Taken:" + " " + seconds + " " + "seconds"); } if (guess == random && turn >= 0 && seconds > 10 && seconds = 0 && seconds > 25 && seconds = 0 && seconds > 60 && seconds = 0
- pattern minor 112d agoGuessing game - Is it a 40?User has number in head, the program must guess the number. ``` public class GuessingGame extends JFrame{ JButton newGameButton, highButton, lowButton, correctButton, exitButton; JLabel initialTextLabel, enterLabel; JTextArea commentTextArea; JScrollPane scroll; private int guess, high = 101, low = 0, tries = 1; public guessingGame() { title("Guessing Game"); newGameButton = new JButton("Start Game"); exitButton = new JButton("Exit Game"); highButton = new JButton("Too High"); lowButton = new JButton("Too Low"); correctButton = new JButton("Correct!"); commentTextArea = new JTextArea(null,10,30); scroll = new JScrollPane(commentTextArea); commentTextArea.setEditable(false); initialTextLabel = new JLabel("Think of a number between 0 & 100 can the computer guess it"); enterLabel = new JLabel("Is your number: "); //add components highButton.setVisible(false); lowButton.setVisible(false); correctButton.setVisible(false); //set default jframe size //create and register the button event handlers }//end of GuessGame constructor //highButtonHandler class class highButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { high = guess; guess = low + (guess - low) / 2; tries++; commentTextArea.append("Is the number " + guess + " too small, too high or correct.\n"); } }//end of high class //lowButtonHandler class class lowButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { low = guess; guess = guess + (high - guess) / 2; tries++; commentTextArea.append("Is the number " + guess + " too small, too high or correct.\n"); }
- pattern minor 112d agoGuess three random numbers in orderWe were given a homework assignment to create a C++ program that generates 3 different random numbers each time and the user is supposed to guess the three of them AND in order. I already achieved that, however I'm not very satisfied with how long my code is, especially with the fact that I had so many if statements. We were told at the beginning of the year that good programming is the ability to write less but more efficiently. (We haven't learned anything about arrays or vectors yet) but I'm still curious to know what are other ways to compare the 3 generated numbers and the 3 user input numbers, all while keeping the order criterion in mind) PS. 3 guesses of 3 numbers in order -> User wins. If the users fails to guess the 3 numbers in their order within 10 attempts, they lose + I also kept the generated numbers to print out just for testing purposes. ALSO, we were required to have 3 functions so that's why I didn't write everything in just one. Long story short, is there any way to write the conditions more concisely and efficiently instead of having to do a for statement for each and every possibility? I still haven't learned arrays since I'm just beginning but all suggestions and methods applicable in C++ are fascinatingly admired and highly appreciated, thank you very much! Here's my code: ``` #include using namespace std; #include #include #include void randnumbers(int&, int&, int&); // Random Numbers Prototype void guessnumbers(int&, int&, int&); // Guess Numbers Prototype int main() { // --> Guesses of Numbers and their Orders int guesses = 0; for (int counter = 0; counter = 3) cout 6: "; cin >> nb1 >> nb2 >> nb3; } ```