Scala dice program - scala

I've just started Scala at University and we're currently just doing the basics but I'm moved ahead and want to try making some basic programs to get ahead. I'm currently trying to make a basic dice role guessing program.
I want to add in a feature to replay the game, the counter is to tell the user how many attempts to guess. I know I can add it in somewhere with counter += 1 just not sure where in the program to put it.
Currently compiling does nothing until I input something and I'm unsure why, then when I input something I don't get any results from the if statements it just terminates the program.
import scala.io.StdIn.readInt
import scala.util.Random
object GuessTheNumber {
def main(args: Array[String]): Unit = {
var play = true
var counter = 0 //Allows counting input
var responseGuess = readInt()
val numRange = Random.nextInt(12)
println("Enter your guess of the result of 2, 6 sided dice.")
while(play) {
if (responseGuess == numRange)
println ("You got it right!")
else if (numRange < responseGuess)
("Your guess was too large by" + (responseGuess - numRange) + " the corrrect answer was " + numRange)
else if (numRange > responseGuess)
( "Your guess was too small by" + (numRange - responseGuess) + " the correct answer was " + numRange)
else if (responseGuess < 1)
("Your guess is too small enter 2-12")
else if (responseGuess > 12)
("You entered an invalid number, 2 dice can only equate to a maximum of 12")
}
}
}

A couple things:
You should ask for a guess (the println) before you go get it from the input
All of your else if blocks were missing println statements
You aren't using your counter
Your numRange is incorrect, right now it would return 0 to 11 inclusive
I made those changes, and moved the readInt() inside the while loop to give people multiple chances to guess, once they guess the answer then the loop exited.
var play = true
val numRange = 2 + Random.nextInt(11)
while(play) {
println("Enter your guess of the result of 2, 6 sided dice.")
var responseGuess = readInt()
if (responseGuess == numRange) {
println ("You got it right!")
play = false
}
else if (numRange < responseGuess)
println("Your guess was too large")
else if (numRange > responseGuess)
println( "Your guess was too small")
else if (responseGuess < 2)
println("Your guess is too small enter 2-12")
else if (responseGuess > 12)
println("You entered an invalid number, 2 dice can only equate to a maximum of 12")
}
You can build off of this to get the functionality you need.

You had a few basic errors, but, a really good first attempt. I have included most of the comments in context for clarity. Here is a quick summary of some of the things that needed minor corrections
You forgot to include println in every else clause
You didn't reset the value of play variable causing your program to be stuck in an infinite loop. The while loop kept executing without asking user for any input giving the illusion that nothing was printing
The counter needs to be updated after every attempt within the loop
import scala.io.StdIn.readInt
import scala.io.StdIn.readChar
import scala.util.Random
object GuessTheNumber {
def main(args: Array[String]): Unit = {
var play = true
var counter = 1 //Allows counting input
// Start a loop. As long as the user says he wants to continue, we keep entering the loop
while (play) {
// The game is slightly more clear in my humble opinion if you ask him/her this question after every attempt.
// Otherwise you just have a blinking cursor on screen, without prompting user for input
println("Enter your guess of the result of 2, 6 sided dice.")
// Read his current response
val responseGuess = readInt()
// If you don't have `1 +`, then, 0 could be a potential result
val numRange = 2 + Random.nextInt(11)
if (responseGuess == numRange)
println(s"You got it right! in $counter attempts")
// You were missing println in each of the following cases. Hence the lack of response from your program, since,
// it didn't know you wanted it to print that response
else if (numRange < responseGuess)
println("Your guess was too large by " + (responseGuess - numRange) + " the correct answer was " + numRange)
else if (numRange > responseGuess)
println( "Your guess was too small by " + (numRange - responseGuess) + " the correct answer was " + numRange)
else if (responseGuess < 1)
println("Your guess is too small enter 2-12")
else if (responseGuess > 12)
println("You entered an invalid number, 2 dice can only equate to a maximum of 12")
println("Do you want to continue? (Y/N)")
// Now you are reading a character instead of an integer. Basically a Y or an N
play = readChar() match { // Not sure if you have gotten this far in your course. This syntax is referred to as pattern matching.
// Its basically the same as using if / else
case 'Y' | 'y' => true // If he enters Y or y, we assume he wants to continue.
case _ => // For any other input we abort
println(s"You tried $counter times") // When he does decide to quit, lets tell him how many times he tried
false
}
// After every attempt increment counter within your loop
counter += 1
}
}
}
Hope this helps.

Related

Programs for printing reverse triangle patterns with * in scala

I am trying to explore Scala. I am new to Scala. This might be a simple question and searched in google to get below scenario to solve. But couldn't get answers. Instead of Scala I am getting Java related things.
My requirement to print format like below.
* * * * *
* * * *
* * *
*
Can someone suggest me how to get this format.
Thanks in advance.
Kanti
Just for the sake of illustration, here are two possible solution to the problem.
The first one is completely imperative, while the second one is more functional.
The idea is that this serves as an example to help you think how to solve problems in a programmatic way.
As many of us have already commented, if you do not understand the basic ideas behind the solution, then this code will be useless in the long term.
Here is the imperative solution, the idea is simple, we need to print n lines, each line contains n - i starts (where i is the number of the line, starting at 0). The starts are separated by an empty space.
Finally, before printing the starts, we need some padding, looking at example inputs, you can see that the padding starts at 0 and increases by 1 for each line.
def printReverseTriangle(n: Int): Unit = {
var i = 0
var padding = 0
while (i < n) {
var j = padding
while (j > 0) {
print(" ")
j -= 1
}
var k = n - i
while (k > 0) {
print("* ")
k -= 1
}
println()
i += 1
padding += 1
}
}
And here is a more functional approach.
As you can see, in this case we do not need to mutate anything, all the high level operators do that for us. And we only need to focus on the description of the solution.
def printReverseTriangle(size: Int): Unit = {
def makeReverseTriangle(size: Int): List[String] =
List.tabulate(size) { i =>
(" " * (size - i)) + ("* " * i)
}.reverse
println(makeReverseTriangle(size).mkString("\n"))
}
To add an alternative to Luis's answer, here's a recursive solution:
import scala.annotation.tailrec
def printStars(i: Int): Unit = {
#tailrec
def loop(j: Int): Unit = {
if(j > 0) {
val stars = Range(0, j).map(_ => "*").mkString(" ") // make stars
if(i == j) println(stars) // no need for spaces
else println((" " * (i - j)) + stars) // spaces before the stars
loop(j - 1)
}
}
loop(i)
}
printStars(3)
// * * *
// * *
// *
This function will take a maximum triangle size (i), and for that size until i is no longer greater than 0 it will print out the correct number of stars (and spaces), then decrement by 1.
Note: Range(0, j).map(_ => "*").mkString(" ") can be replaced with List.tabulate(j)(_ => "*").mkString(" ") per Luis's answer - I'm not sure which is faster (I've not tested it).

How to take Python Input with mistakes

I'm making a script where you guess a movie based off of a quote from it. What I'm wondering is how I make it so that I can take "Terminator" and "The Terminator" and allow spelling mistakes to still be correct.
I tried to look it up but found pretty much nothing.
#Guess that movie, gives a quote and you have to guess it for points, add a high score system.
from random import randint
points = 0
quote1 = randint(0,3)
quote2 = randint(0,3)
quote3 = randint(0,3)
quote4 = randint(0,3)
movieQuoteEasy = ["You're going to need a bigger boat.", "I'll be back.", "Here's Johnny!", "Say hello to my little friend!"]
movieQuoteMedi = ["Luca Brazi Sleeps with the fishes.", "Whatever doesn't kill you simply makes you... stranger.", "You talking to me?", "I love the smell of Napalm in the morning."]
movieQuoteHard = ["Rosebud...", "How am I funny to you? what makes me so funny.", "They call it a Royal with Cheese.", "Go ahead, make my day."]
movieQuoteExtr = ["I tried... at least I did that.", "Gentlemen, you can't fight here this is the way room!", "I'm having an old friend for Dinner.", "The greatest trick the devil pulled was convincing the world he didn't exist."]
movieAnswerEasy = ["Jaws", "The Terminator", "The Shining", "Scarface"]
movieAnswerMedi = ["The Godfather", "The Dark Knight", "Taxi Driver", "Apocalypse Now"]
movieAnswerHard = ["Casablanca", "Goodfellas", "Pulp Fiction", "Dirty Hary"]
movieAnswerExtr = ["One Flew Over the Cuckos Nest", 'Dr. Strangelove', "Silence of the Lambs", "The Usual Suspects"]
print("Welcome to Guess That Movie!")
input()
#Easy Question
print("Easy: " + movieQuoteEasy[quote1])
guess1 = input()
#Takes the value for use input and checks it against the correct answer.
if guess1 == movieAnswerEasy[quote1]:
print("Correct!")
points += 5
print("You have " + str(points) + " points!")
else:
print("Wrong, the correct answer was " + movieAnswerEasy[quote1])
#Medium Question
print("Medium: " + movieQuoteMedi[quote2])
guess2 = input()
#Takes the value for use input and checks it against the correct answer.
if guess2 == movieAnswerMedi[quote2]:
print("Correct!")
points += 5
print("You have " + str(points) + " points!")
else:
print("Wrong, the correct answer was " + movieAnswerMedi[quote1])
#Hard Question
print("Hard: " + movieQuoteHard[quote3])
guess3 = input()
#Takes the value for use input and checks it against the correct answer.
if guess3 == movieAnswerHard[quote3]:
print("Correct!")
points += 5
print("You have " + str(points) + " points!")
else:
print("Wrong, the correct answer was " + movieAnswerHard[quote3])
#Extream Question
print("Insane: " + movieQuoteExtr[quote4])
guess4 = input()
# Takes the value for use input and checks it against the correct answer.
if guess4 == movieAnswerExtr[quote4]:
print("Correct!")
points += 5
print("You have " + str(points) + " points!")
else:
print("Wrong, the correct answer was " + movieAnswerExtr[quote4])
print("\nGreat job, you have " + str(points) + " points.")
input()
exit()
I want to be able to take in 'The Terminator' and just 'terminator'
I know how to solve your problem. The first thing you can do is add .lower() to the end of your input. This will put all of the letters in the user's input in lower case. Like this: guess1 = input().lower. Now it doesn't matter if the user types in upper or lower case. Also; you should do this:
guess1 = input(">>> ").lower() #Allows the user to input lower case letters.
if "terminator" in guess1: #This is probably what you are looking for.
#If the program detects the keyword 'terminator'
#in your guess, then the if statement will execute.
#Whatever happens when the user is correct.
else:
#Whatever happens when the user is incorrect.
I hope I helped you!

Adding a new name/item to a list and calling that variable globally?

I'm pretty much brand new to coding and decided to start with Python. I have been working on a simple "Number Guessing Game" and have evolved it a bit more each iteration.
I decided that I want to make it a little bit more robust that just finishing after the number is guessed.
I want the user/player to enter their name, have that name stored, and then used throughout... until the end, when they're asked if they want to play again and if it's the 'same user?" and if they say, "No.", I want it to append a new name to the list and then go through the game again.
This is what I've got so far... please be gentle... I know there's some errors :(
import sys
import os
import random
global player
while True:
def GuessingGame():
player = []
player.append(input("Please Enter Your Name:\n")),
# player_name = input("Please enter your name: \n")
print(f"Hello, {player[0]}! Let's get started!\n")
number = 500
count = 1
guess = int(input("Guess a number between 1 and 1000: \n"))
while guess != number:
count += 1
if guess > (number + 10):
print("TOO HIGH, a little lower...")
elif guess < (number - 10):
print("TOO LOW... guess higher!")
elif guess > (number + 5):
print("You're getting warmer, but still TOO HIGH, a little lower...")
elif guess < (number - 5):
print("You're getting warmer, but still TOO LOW... higher!")
elif guess < number:
print("You're REALLY warm, but still a bit TOO LOW")
elif guess > number:
print("You're REALLY, but still a bit TOO HIGH")
guess = int(input("Try again...\n"))
if guess == number:
print(f"You got it!!! It took you {count} tries to guess {number}\n")
response1 = str(input("Would you like to try again? Y or N\n"))
if response1 == ("y" or "Y"):
sameplayer = str(input("Is this still {player[0]}? Y1 or N1\n"))
if sameplayer == ("y1" or "Y1"):
GuessingGame()
else:
newplayer = player.extend(str(input("Please Enter New Player's Name:\n")))
print(f"Hello, {player[1]}!, Let's Get Started!")
return
GuessingGame()
Again, this is the first time I'm sharing anything I've done... so please don't just wreck me :)
Here i copy the same code you wrote, but with a little bit of modifications that i felt were needed to be made.
from random import randint
player = None
def GuessingGame():
global player
if player is None:
player = input("Please Enter Your Name:\n")
print(f"Hello, {player}! Let's get started!\n")
number = randint(1, 1000)
guess = int(input("Guess a number between 1 and 1000: \n"))
count = 1
while guess != number:
if guess > (number + 10):
print("TOO HIGH, a little lower...")
elif guess < (number - 10):
print("TOO LOW... guess higher!")
elif guess > (number + 5):
print("You're getting warmer, but still TOO HIGH, a little lower...")
elif guess < (number - 5):
print("You're getting warmer, but still TOO LOW... higher!")
elif guess < number:
print("You're REALLY warm, but still a bit TOO LOW")
elif guess > number:
print("You're REALLY, but still a bit TOO HIGH")
if guess == number:
break
else:
count += 1
guess = int(input("Try again...\n"))
print(f"You got it!!! It took you {count} tries to guess {number}\n")
response1 = str(input("Would you like to try again? Y or N\n"))
if response1.lower() == 'y':
sameplayer = str(input(f"Is this still {player}? Y or N\n"))
if sameplayer.lower() == 'n':
player = None
return
else:
return
while True:
GuessingGame()
Let me know if you got any questions.

Prime Numbers Swift 3

After hours of Googling, I'm still at a standstill. I would appreciate if someone would point out the error in my formula or coding choice. Please keep in mind I'm new to Swift. I'm not used to non C-style for loops.
if textField.text != "" {
input = Double(textField.text!)! // parse input
// return if number less than 2 entered
if input < 2 {
resultLabel.text = "Enter a number greater than or equal to 2."
return;
}
// get square root of input and parse to int
inputSquared = Int(sqrt(input));
// loop from 2 to input iterating by 1
for i in stride(from: 2, through: input, by: 1) {
if inputSquared % Int(i) == 0 {
resultLabel.text = "\(Int(input)) is not a prime number."
}
else {
resultLabel.text = "\(Int(input)) is a prime number!"
}
}
}
I didn't know the formula on how to find a prime number. After looking up multiple formulas I have sorta settled on this one. Every result is a prime number, however. So my if condition is wrong. I just don't know how to fix it.
Check my algorithm.It works.But I'm not sure this is an effective algorithm for prime number
var input:Int = 30
var isPrime:Bool = true
if(input == 2){
print("Input value 2 is prim number")
}
else if(input < 2){
print("Input value must greater than 2")
}
else{
for i in 2...input-1{
if((input%i) == 0){
isPrime = false
break;
}
}
if(isPrime){
print("Your Input Value \(input) is Prime!")
}
}
A couple of solutions that work have been posted, but none of them explain why yours doesn't. Some of the comments get close, however.
Your basic problem is that you take the square root of input, then iterate from 2 to the input checking if the integer part of the square root is divisible by i. You got that the wrong way round. You need to iterate from 2 to the square root and check that the input is divisible by i. If it is, you stop because input is not prime. If you get to the end without finding a divisor, you have a prime.
try this code in playground you will get this better idea and try to use playground when you try the swift as you are not familiar with swift playground is best.
let input = 13 // add your code that take value from textfield
var prime = 1
// throw error less than 2 entered
if input < 2 {
assertionFailure("number should be 2 or greater")
}
// loop from 2 to input iterating by 1
for i in stride(from: 2, to: input, by: 1) {
if input % i == 0{
prime = 0
}
}
if prime == 1 {
print("\(input) number is prime")
} else {
print("\(input) number is not prime")
}

Difficulty getting readLine() to work as desired on HackerRank

I'm attempting to submit the HackerRank Day 6 Challenge for 30 Days of Code.
I'm able to complete the task without issue in an Xcode Playground, however HackerRank's site says there is no output from my method. I encountered an issue yesterday due to browser flakiness, but cleaning caches, switching from Safari to Chrome, etc. don't seem to resolve the issue I'm encountering here. I think my problem lies in inputString.
Task
Given a string, S, of length N that is indexed from 0 to N-1, print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line (see the Sample below for more detail).
Input Format
The first line contains an integer, (the number of test cases).
Each line of the subsequent lines contain a String, .
Constraints
1 <= T <= 10
2 <= length of S < 10,000
Output Format
For each String (where 0 <= j <= T-1), print S's even-indexed characters, followed by a space, followed by S's odd-indexed characters.
This is the code I'm submitting:
import Foundation
let inputString = readLine()!
func tweakString(string: String) {
// split string into an array of lines based on char set
var lineArray = string.components(separatedBy: .newlines)
// extract the number of test cases
let testCases = Int(lineArray[0])
// remove the first line containing the number of unit tests
lineArray.remove(at: 0)
/*
Satisfy constraints specified in the task
*/
guard lineArray.count >= 1 && lineArray.count <= 10 && testCases == lineArray.count else { return }
for line in lineArray {
switch line.characters.count {
// to match constraint specified in the task
case 2...10000:
let characterArray = Array(line.characters)
let evenCharacters = characterArray.enumerated().filter({$0.0 % 2 == 0}).map({$0.1})
let oddCharacters = characterArray.enumerated().filter({$0.0 % 2 == 1}).map({$0.1})
print(String(evenCharacters) + " " + String(oddCharacters))
default:
break
}
}
}
tweakString(string: inputString)
I think my issue lies the inputString. I'm taking it "as-is" and formatting it within my method. I've found solutions for Day 6, but I can't seem to find any current ones in Swift.
Thank you for reading. I welcome thoughts on how to get this thing to pass.
readLine() reads a single line from standard input, which
means that your inputString contains only the first line from
the input data. You have to call readLine() in a loop to get
the remaining input data.
So your program could look like this:
func tweakString(string: String) -> String {
// For a single input string, compute the output string according to the challenge rules ...
return result
}
let N = Int(readLine()!)! // Number of test cases
// For each test case:
for _ in 1...N {
let input = readLine()!
let output = tweakString(string: input)
print(output)
}
(The forced unwraps are acceptable here because the format of
the input data is documented in the challenge description.)
Hi Adrian you should call readLine()! every row . Here an example answer for that challenge;
import Foundation
func letsReview(str:String){
var evenCharacters = ""
var oddCharacters = ""
var index = 0
for char in str.characters{
if index % 2 == 0 {
evenCharacters += String(char)
}
else{
oddCharacters += String(char)
}
index += 1
}
print (evenCharacters + " " + oddCharacters)
}
let rowCount = Int(readLine()!)!
for _ in 0..<rowCount {
letsReview(str:String(readLine()!)!)
}