Giter Site home page Giter Site logo

quiz's Introduction

Exercise #1: Quiz Game

exercise status: released

Exercise details

This exercise is broken into two parts to help simplify the process of explaining it as well as to make it easier to solve. The second part is harder than the first, so if you get stuck feel free to move on to another problem then come back to part 2 later.

Note: I didn't break this into multiple exercises like I do for some exercises because both of these combined should only take ~30m to cover in screencasts.

Part 1

Create a program that will read in a quiz provided via a CSV file (more details below) and will then give the quiz to a user keeping track of how many questions they get right and how many they get incorrect. Regardless of whether the answer is correct or wrong the next question should be asked immediately afterwards.

The CSV file should default to problems.csv (example shown below), but the user should be able to customize the filename via a flag.

The CSV file will be in a format like below, where the first column is a question and the second column in the same row is the answer to that question.

5+5,10
7+3,10
1+1,2
8+3,11
1+2,3
8+6,14
3+1,4
1+4,5
5+1,6
2+3,5
3+3,6
2+4,6
5+2,7

You can assume that quizzes will be relatively short (< 100 questions) and will have single word/number answers.

At the end of the quiz the program should output the total number of questions correct and how many questions there were in total. Questions given invalid answers are considered incorrect.

NOTE: CSV files may have questions with commas in them. Eg: "what 2+2, sir?",4 is a valid row in a CSV. I suggest you look into the CSV package in Go and don't try to write your own CSV parser.

Part 2

Adapt your program from part 1 to add a timer. The default time limit should be 30 seconds, but should also be customizable via a flag.

Your quiz should stop as soon as the time limit has exceeded. That is, you shouldn't wait for the user to answer one final questions but should ideally stop the quiz entirely even if you are currently waiting on an answer from the end user.

Users should be asked to press enter (or some other key) before the timer starts, and then the questions should be printed out to the screen one at a time until the user provides an answer. Regardless of whether the answer is correct or wrong the next question should be asked.

At the end of the quiz the program should still output the total number of questions correct and how many questions there were in total. Questions given invalid answers or unanswered are considered incorrect.

Bonus

As a bonus exercises you can also...

  1. Add string trimming and cleanup to help ensure that correct answers with extra whitespace, capitalization, etc are not considered incorrect. Hint: Check out the strings package.
  2. Add an option (a new flag) to shuffle the quiz order each time it is run.

quiz's People

Contributors

abdul-manaan avatar andreis avatar barisere avatar bartbucknill avatar csos95 avatar dennisvis avatar dimdiden avatar dvrkps avatar ehernandez-xk avatar hackeryarn avatar hellosputnik avatar joncalhoun avatar kalexmills avatar kannanenator avatar kdlug avatar kseverinsen avatar liikt avatar mirekwalczak avatar real-mielofon avatar siredmar avatar teimurjan avatar vancelongwill avatar viveksyngh avatar wbgalvao avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

quiz's Issues

Release this exercise

Tasks to be completed:

[ ] Write the first draft of the code
[ ] Outline the screencast
[ ] Record the screencast
[ ] Upload the screencast
[ ] Add the screencast to the course on gophercises.com

Create a student example

Look over the README.md then attempt to complete the exercise and submit your solution as a directory inside of the students directory. Eg if you have a github username of joncalhoun then place your code in students/joncalhoun/your_code.go

For more info on how these are used see the README in the students directory.

Goroutine for timer

Hello. I wrote code that looks like mycode. So I wanted to ask about difference between creating 2 channels (answer and time) and 1 goroutine for timer only is there any disadvantages in my code?

panic: runtime error: index out of range [1] with length 1

$ go build . && ./quiz -csv=problems.csv
panic: runtime error: index out of range [1] with length 1

goroutine 1 [running]:
main.parseLines(0xc00000c030, 0x1, 0x1, 0x1, 0x0, 0x0)
        /home/mitul/go/src/gophercises/quiz/main.go:44 +0x14f
main.main()
        /home/mitul/go/src/gophercises/quiz/main.go:24 +0x2d9

facing run time error after running the solution 1 , i've not gone through the solution 2 video yet
But looking for an answer for why this error happening ?

Handle wrong answers

Let's take @csos95 's implementation. Suppose one question is answered wrong. How to add that question BACK to the range, so it can be asked again later?

goroutine leak - kind of...

Hi there,

Thanks for putting together these exercises! They're giving me a way to learn some areas of Go I don't get a chance to use very often at work.

I have a question regarding this lesson. This question is a bit long, so thanks in advance for reading through it.

Like your solution, my solution for gathering user input used a goroutine. Also, as with your solution, my solution used a time.Timer to timeout. Finally, as with your solution, my solution "kind of sort of" leaks the goroutine that's monitoring stdin for user input. That goroutine might also write to a closed channel once the user does hit "Return".

I say it "kind of sort of" leaks this goroutine because the process will exit shortly after the timeout, so the leak in this case is very short-lived. But still... And if the parent goroutine closes the channel after a timeout the application will panic:

panic: send on closed channel

goroutine 25 [running]:
main.main.func1(0xc4200762a0)
	/Users/rich_youngkin/Software/repos/go/src/github.com/youngkin/gophercises/quiz/solution/main.go:38 +0x121
created by main.main
	/Users/rich_youngkin/Software/repos/go/src/github.com/youngkin/gophercises/quiz/solution/main.go:35 +0x5d2

To make this happen I closed the channel on what is now line 44 in your part 2 solution:

		select {
		case <-timer.C:
			fmt.Println()
        Added ======>	close(answerCh)    <======= this line
			break problemloop
		case answer := <-answerCh:
			if answer == p.a {
				correct++
			}
		}

This is all a bit messy. I've spent some time thinking about how to have the user input goroutine also timeout and exit without attempting to write to the potentially closed channel. But after issuing the read to stdin it seems like there's no nice way to timeout the actual waiting for input, or to check if a timeout occurred while waiting for user input. For example, this won't reliably work as the order in which the case conditions are evaluated is random:

	ans, _ := in.ReadString('\n')
	select {
	case c <- ans:
		return
	case <-ctx.Done():
		return
	}

I was wondering if you had any thoughts about how to accomplish this and ensure the goroutine eventually exits without attempting to write to the channel.

Cheers,
Rich

Project 1

Pydroid3class QuizQuestion:
def init(self, question, options, correct_option):
self.question = question
self.options = options
self.correct_option = correct_option

class QuizGame:
def init(self, questions):
self.questions = questions
self.score = 0

def display_question(self, question_obj):
    print(question_obj.question)
    for index, option in enumerate(question_obj.options, start=1):
        print(f"{index}. {option}")

def get_user_answer(self, question_obj):
    while True:
        try:
            user_answer = int(input("Your answer (enter the option number): "))
            if 1 <= user_answer <= len(question_obj.options):
                return user_answer
            else:
                print("Invalid input. Please enter a valid option number.")
        except ValueError:
            print("Invalid input. Please enter a number.")

def evaluate_answer(self, question_obj, user_answer):
    if user_answer == question_obj.correct_option:
        print("Correct!")
        self.score += 1
    else:
        print(f"Wrong! The correct answer was option {question_obj.correct_option}.")

def play_game(self):
    for question_obj in self.questions:
        self.display_question(question_obj)
        user_answer = self.get_user_answer(question_obj)
        self.evaluate_answer(question_obj, user_answer)
        print()  # Add a newline for better readability

def show_score(self):
    print(f"Your final score: {self.score}/{len(self.questions)}")

Define quiz questions

question1 = QuizQuestion("What is the capital of France?", ["Paris", "Berlin", "Madrid"], 1)
question2 = QuizQuestion("Which programming language is this quiz written in?", ["Java", "Python", "C++"], 2)
question3 = QuizQuestion("What is 2 + 2?", ["3", "4", "5"], 2)

Create a list of quiz questions

quiz_questions = [question1, question2, question3]

Create a QuizGame instance

quiz_game = QuizGame(quiz_questions)

Start the quiz game

quiz_game.play_game()

Display the final score

quiz_game.show_score()

Timeout for each question

Hello,

Please, I misunderstood part 2 of the exercise before seeing the solution.

I was thinking that the timeout is for each question and I struggled with it for many days before watching the solution.
This question of StackOverflow explained the challenges I face through https://stackoverflow.com/questions/50797563/how-to-cancel-fmt-scanf-after-a-certain-timeout I am not the author of the question

Can you provide us a solution for part 2 if the timeout is for each solution?

Creating a channel inside the loop?

Firstly thanks for creating these screencasts and making it public.
In the quiz exercise, Problem #2, I see that a channel is being created on every iteration, is that required? As I can create the channel outside the loop as well.

quiz/main.go

Line 34 in 3b2250f

answerCh := make(chan string)

Create a student example

Look over the README.md then attempt to complete the exercise and submit your solution as a directory inside of the students directory. Eg if you have a github username of joncalhoun then place your code in students/joncalhoun/your_code.go

For more info on how these are used see the README in the students directory.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.