I am trying to build a basic quiz app to improve my, so I was able to use if and else statement to know when they entered the right answer or not then I will print out their score, I was able to achieve this, so the main issue is that I want to add all the sores together and tell them the total they have scored. my code is below. thanks in advance.
import 'dart:io';
import 'dart:math';
void main() {
print("Hi, welcome to quize app");
print("what is your name?");
String? username = stdin.readLineSync();
print("welcome ${username}");
print("Who is Christiano ronaldo?");
List? answers1 = [26, 30, 37, 36];
List? answers2 = ['Musician', 'Footballer', 'Swimmer'];
List? answers3 = [3, 5, 7, 17];
List? answers4 = ['Yes', 'No'];
int? ans1 = 36;
String? ans2 = 'Footballer';
int? ans3 = 17;
String? ans4 = 'no';
int? num1 = (0 + 10);
int? num2 = (0 + 0);
int? num3 = (10 + 10 + 20);
print(answers1);
int? userans1 = int.parse(stdin.readLineSync()!);
print("Who the next president of Nigeria?");
print(answers2);
String? userans2 = stdin.readLineSync();
print(
"How many times did national Grid collaps in 2022 alone? please type in numbers:");
print(answers3);
int? userans3 = int.parse(stdin.readLineSync()!);
print('Is Nigerian air still functioning?');
print(answers4);
String? userans4 = stdin.readLineSync();
print('end of quize');
print('calculating answers...');
if (userans1 == ans1) {
String? cal = "$num1";
print("In question number one (1) you got $cal");
} else {
String? cal1 = "$num2";
print("In question number one (1) you got $cal1");
}
if (userans2 == ans2) {
String? cal = "$num1";
print("In question Number two (2) you got $cal");
} else {
String? cal1 = "$num2";
print("In question Number two (2) you got $cal1");
}
if (userans3 == ans3) {
String? cal = "$num1";
print("In question Number three (3) you got $cal");
} else {
String? cal1 = "$num2";
print("In question Number three (3) you got $cal1");
}
if (userans4 == ans4) {
String? cal = "$num1";
print("In question Number four (4) you got $cal");
} else {
String? cal1 = "$num2";
print("In question Number four (4) you got $cal1");
}
}
It is not just about Dart, it is a general programming logic question.
You can declare a variable of type int to hold the total score and start it with value of 0 like the following:
int totalScore = 0;
then every time the user answers a question correctly, just add the score of the question to the answer, for example:
if (userans1 == ans1) {
String? cal = "$num1";
print("In question number one (1) you got $cal");
totalScore += 10; // 10 is the score user received, replace it with the correct score.
}
Note: totalScore += 10 is equivalent to totalScore = totalScore + 10
At the end, you will have the Total Score in our variable, do whatever you want with it.
That's it!
Related
I want to count the number of letters, digits and special characters in the following string:
let phrase = "The final score was 32-31!"
I tried:
for tempChar in phrase {
if (tempChar >= "a" && tempChar <= "z") {
letterCounter++
}
// etc.
but I'm getting errors. I tried all sorts of other variations on this - still getting error - such as:
could not find an overload for '<=' that accepts the supplied arguments
For Swift 5 see rustylepord's answer.
Update for Swift 3:
let letters = CharacterSet.letters
let digits = CharacterSet.decimalDigits
var letterCount = 0
var digitCount = 0
for uni in phrase.unicodeScalars {
if letters.contains(uni) {
letterCount += 1
} else if digits.contains(uni) {
digitCount += 1
}
}
(Previous answer for older Swift versions)
A possible Swift solution:
var letterCounter = 0
var digitCount = 0
let phrase = "The final score was 32-31!"
for tempChar in phrase.unicodeScalars {
if tempChar.isAlpha() {
letterCounter++
} else if tempChar.isDigit() {
digitCount++
}
}
Update: The above solution works only with characters in the ASCII character set,
i.e. it does not recognize Ä, é or ø as letters. The following alternative
solution uses NSCharacterSet from the Foundation framework, which can test characters
based on their Unicode character classes:
let letters = NSCharacterSet.letterCharacterSet()
let digits = NSCharacterSet.decimalDigitCharacterSet()
var letterCount = 0
var digitCount = 0
for uni in phrase.unicodeScalars {
if letters.longCharacterIsMember(uni.value) {
letterCount++
} else if digits.longCharacterIsMember(uni.value) {
digitCount++
}
}
Update 2: As of Xcode 6 beta 4, the first solution does not work anymore, because
the isAlpha() and related (ASCII-only) methods have been removed from Swift.
The second solution still works.
Use the values of unicodeScalars
let phrase = "The final score was 32-31!"
var letterCounter = 0, digitCounter = 0
for scalar in phrase.unicodeScalars {
let value = scalar.value
if (value >= 65 && value <= 90) || (value >= 97 && value <= 122) {++letterCounter}
if (value >= 48 && value <= 57) {++digitCounter}
}
println(letterCounter)
println(digitCounter)
For Swift 5 you can do the following for simple strings, but be vigilant about handling characters like "1️⃣" , "④" these would be treated as numbers as well.
let phrase = "The final score was 32-31!"
var numberOfDigits = 0;
var numberOfLetters = 0;
var numberOfSymbols = 0;
phrase.forEach {
if ($0.isNumber) {
numberOfDigits += 1;
}
else if ($0.isLetter) {
numberOfLetters += 1
}
else if ($0.isSymbol || $0.isPunctuation || $0.isCurrencySymbol || $0.isMathSymbol) {
numberOfSymbols += 1;
}
}
print(#"\#(numberOfDigits) || \#(numberOfLetters) || \#(numberOfSymbols)"#);
I've created a short extension for letter and digits count for a String
extension String {
var letterCount : Int {
return self.unicodeScalars.filter({ CharacterSet.letters.contains($0) }).count
}
var digitCount : Int {
return self.unicodeScalars.filter({ CharacterSet.decimalDigits.contains($0) }).count
}
}
or a function to get a count for any CharacterSet you put in
extension String {
func characterCount(for set: CharacterSet) -> Int {
return self.unicodeScalars.filter({ set.contains($0) }).count
}
}
usage:
let phrase = "the final score is 23-13!"
let letterCount = phrase.characterCount(for: .letters)
In case you only need one information (letter or number or sign) you can do it in one line:
let phrase = "The final score was 32-31!"
let count = phrase.filter{ $0.isLetter }.count
print(count) // "16\n"
But doing phrase.filter several times is inefficient because it loops through the whole string.
I'm attempting to get a user input number and find the sum of all the digits. I'm having issues with larger numbers, however, as they won't register under an Int64. Any idea as to what structures I could use to store the value? (I tried UInt64 and that didn't work very well with negatives, however, I'd prefer something larger than UInt64, anyways. I'm having a hard time implementing a UInt128 from Is there a number type with bigger capacity than u_long/UInt64 in Swift?)
import Foundation
func getInteger() -> Int64 {
var value:Int64 = 0
while true {
//we aren't doing anything with input, so we make it a constant
let input = readLine()
//ensure its not nil
if let unwrappedInput = input {
if let unwrappedInt = Int64(unwrappedInput) {
value = unwrappedInt
break
}
}
else { print("You entered a nil. Try again:") }
}
return value
}
print("Please enter an integer")
// Gets user input
var input = getInteger()
var arr = [Int] ()
var sum = 0
var negative = false
// If input is less than 0, makes it positive
if input < 0 {
input = (input * -1)
negative = true
}
if (input < 10) && (input >= 1) && (negative == true) {
var remain = (-1)*(input%10)
arr.append(Int(remain))
input = (input/10)
}
else {
var remain = (input%10)
arr.append(Int(remain))
input = (input/10)
}
}
// Adds numbers in array to find sum of digits
var i:Int = 0
var size:Int = (arr.count - 1)
while i<=size {
sum = sum + arr[i]
i = (i+1)
}
// Prints sum
print("\(sum)")
You can use a string to perform the operation you describe. Loop through each character and convert it to an integer and add to the sum. Be careful to handle errors.
I need to generate a random number.
It appears the arc4random function no longer exists as well as the arc4random_uniform function.
The options I have are arc4random_stir(), arc4random_buf(UnsafeMutablePointer<Void>, Int), and arc4random_addrandom(UnsafeMutablePointer<UInt8>, Int32).
I can't find any docs on the functions and no comments in the header files give hints.
let randomIntFrom0To10 = Int.random(in: 1..<10)
let randomFloat = Float.random(in: 0..<1)
// if you want to get a random element in an array
let greetings = ["hey", "hi", "hello", "hola"]
greetings.randomElement()
You could try as well:
let diceRoll = Int(arc4random_uniform(UInt32(6)))
I had to add "UInt32" to make it work.
Just call this function and provide minimum and maximum range of number and you will get a random number.
eg.like randomNumber(MIN: 0, MAX: 10) and You will get number between 0 to 9.
func randomNumber(MIN: Int, MAX: Int)-> Int{
return Int(arc4random_uniform(UInt32(MAX-MIN)) + UInt32(MIN));
}
Note:- You will always get output an Integer number.
After some investigation I wrote this:
import Foundation
struct Math {
private static var seeded = false
static func randomFractional() -> CGFloat {
if !Math.seeded {
let time = Int(NSDate().timeIntervalSinceReferenceDate)
srand48(time)
Math.seeded = true
}
return CGFloat(drand48())
}
}
Now you can just do Math.randomFraction() to get random numbers [0..1[ without having to remember seeding first. Hope this helps someone :o)
Update with swift 4.2 :
let randomInt = Int.random(in: 1..<5)
let randomFloat = Float.random(in: 1..<10)
let randomDouble = Double.random(in: 1...100)
let randomCGFloat = CGFloat.random(in: 1...1000)
Another option is to use the xorshift128plus algorithm:
func xorshift128plus(seed0 : UInt64, _ seed1 : UInt64) -> () -> UInt64 {
var state0 : UInt64 = seed0
var state1 : UInt64 = seed1
if state0 == 0 && state1 == 0 {
state0 = 1 // both state variables cannot be 0
}
func rand() -> UInt64 {
var s1 : UInt64 = state0
let s0 : UInt64 = state1
state0 = s0
s1 ^= s1 << 23
s1 ^= s1 >> 17
s1 ^= s0
s1 ^= s0 >> 26
state1 = s1
return UInt64.addWithOverflow(state0, state1).0
}
return rand
}
This algorithm has a period of 2^128 - 1 and passes all the tests of the BigCrush test suite. Note that while this is a high-quality pseudo-random number generator with a long period, it is not a cryptographically secure random number generator.
You could seed it from the current time or any other random source of entropy. For example, if you had a function called urand64() that read a UInt64 from /dev/urandom, you could use it like this:
let rand = xorshift128plus(urand64(), urand64())
for _ in 1...10 {
print(rand())
}
let MAX : UInt32 = 9
let MIN : UInt32 = 1
func randomNumber()
{
var random_number = Int(arc4random_uniform(MAX) + MIN)
print ("random = ", random_number);
}
In Swift 3 :
It will generate random number between 0 to limit
let limit : UInt32 = 6
print("Random Number : \(arc4random_uniform(limit))")
My implementation as an Int extension. Will generate random numbers in range from..<to
public extension Int {
static func random(from: Int, to: Int) -> Int {
guard to > from else {
assertionFailure("Can not generate negative random numbers")
return 0
}
return Int(arc4random_uniform(UInt32(to - from)) + UInt32(from))
}
}
This is how I get a random number between 2 int's!
func randomNumber(MIN: Int, MAX: Int)-> Int{
var list : [Int] = []
for i in MIN...MAX {
list.append(i)
}
return list[Int(arc4random_uniform(UInt32(list.count)))]
}
usage:
print("My Random Number is: \(randomNumber(MIN:-10,MAX:10))")
Another option is to use GKMersenneTwisterRandomSource from GameKit. The docs say:
A deterministic pseudo-random source that generates random numbers
based on a mersenne twister algorithm. This is a deterministic random
source suitable for creating reliable gameplay mechanics. It is
slightly slower than an Arc4 source, but more random, in that it has a
longer period until repeating sequences. While deterministic, this is
not a cryptographic random source. It is however suitable for
obfuscation of gameplay data.
import GameKit
let minValue = 0
let maxValue = 100
var randomDistribution: GKRandomDistribution?
let randomSource = GKMersenneTwisterRandomSource()
randomDistribution = GKRandomDistribution(randomSource: randomSource, lowestValue: minValue, highestValue: maxValue)
let number = randomDistribution?.nextInt() ?? 0
print(number)
Example taken from Apple's sample code: https://github.com/carekit-apple/CareKit/blob/master/CareKitPrototypingTool/OCKPrototyper/CareKitPatient/RandomNumberGeneratorHelper.swift
I'm late to the party 🤩🎉
Using a function that allows you to change the size of the array and the range selection on the fly is the most versatile method. You can also use map so it's very concise. I use it in all of my performance testing/bench marking.
elements is the number of items in the array
only including numbers from 0...max
func randArr(_ elements: Int, _ max: Int) -> [Int] {
return (0..<elements).map{ _ in Int.random(in: 0...max) }
}
Code Sense / Placeholders look like this.
randArr(elements: Int, max: Int)
10 elements in my array ranging from 0 to 1000.
randArr(10, 1000) // [554, 8, 54, 87, 10, 33, 349, 888, 2, 77]
you can use this in specific rate:
let die = [1, 2, 3, 4, 5, 6]
let firstRoll = die[Int(arc4random_uniform(UInt32(die.count)))]
let secondRoll = die[Int(arc4random_uniform(UInt32(die.count)))]
Lets Code with Swift for the random number or random string :)
let quotes: NSArray = ["R", "A", "N", "D", "O", "M"]
let randomNumber = arc4random_uniform(UInt32(quotes.count))
let quoteString = quotes[Int(randomNumber)]
print(quoteString)
it will give you output randomly.
Don't forget that some numbers will repeat! so you need to do something like....
my totalQuestions was 47.
func getRandomNumbers(totalQuestions:Int) -> NSMutableArray
{
var arrayOfRandomQuestions: [Int] = []
print("arraySizeRequired = 40")
print("totalQuestions = \(totalQuestions)")
//This will output a 40 random numbers between 0 and totalQuestions (47)
while arrayOfRandomQuestions.count < 40
{
let limit: UInt32 = UInt32(totalQuestions)
let theRandomNumber = (Int(arc4random_uniform(limit)))
if arrayOfRandomQuestions.contains(theRandomNumber)
{
print("ping")
}
else
{
//item not found
arrayOfRandomQuestions.append(theRandomNumber)
}
}
print("Random Number set = \(arrayOfRandomQuestions)")
print("arrayOutputCount = \(arrayOfRandomQuestions.count)")
return arrayOfRandomQuestions as! NSMutableArray
}
look, i had the same problem but i insert
the function as a global variable
as
var RNumber = Int(arc4random_uniform(9)+1)
func GetCase(){
your code
}
obviously this is not efficent, so then i just copy and paste the code into the function so it could be reusable, then xcode suggest me to set the var as constant so my code were
func GetCase() {
let RNumber = Int(arc4random_uniform(9)+1)
if categoria == 1 {
}
}
well thats a part of my code so xcode tell me something of inmutable and initialization but, it build the app anyway and that advice simply dissapear
hope it helps
I'd like to generate multiple different random numbers in Swift. Here is the procedure.
Set up an empty array
Generate a random number
Check if the array is empty
a. If the array is empty, insert the random number
b. If the array is not empty, compare the random number to the numbers in array
i. If the numbers are the same, repeat 2
ii. if the numbers are not the same, insert the random number and repeat 2
import UIKit
//the random number generator
func randomInt(min: Int, max:Int) -> Int {
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
var temp = [Int]()
for var i = 0; i<4; i++ {
var randomNumber = randomInt(1, 5)
if temp.isEmpty{
temp.append(randomNumber)
} else {
//I don't know how to continue...
}
}
If you use your method the problem is, that you will create a new random-number each time. So you possibly could have the same random-number 4 times and so your array will only have one element.
So, if you just want to have an array of numbers from within a specific range of numbers (for example 0-100), in a random order, you can first fill an array with numbers in 'normal' order. For example with for loop etc:
var min = 1
var max = 5
for var i = min; i<= max; i++ {
temp.append(i)
}
After that, you can use a shuffle method to shuffle all elements of the array with the shuffle method from this answer:
func shuffle<C: MutableCollectionType where C.Index == Int>(var list: C) -> C {
let count = countElements(list)
for i in 0..<(count - 1) {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
swap(&list[i], &list[j])
}
return list
}
Ater that you can do something like that:
shuffle(temp) // e.g., [3, 1, 2, 4, 5]
The construct you’re looking for with your approach might be something like:
var temp: [Int] = []
while temp.count < 4 {
var randomNumber: Int
do {
randomNumber = randomInt(1, 5)
} while contains(temp, randomNumber)
temp.append(randomNumber)
}
This will be fine for tiny ranges like yours, but for larger ranges it will be very slow, because for the last few numbers you are waiting for the random number to hit precisely the remaining handful of possibilities. I just tried generating from a range of 200 in a playground and it took 9 seconds.
If you want a random selection of numbers with guaranteed coverage over a range, you could generate it like by taking that range and shuffling it, like this:
func shuffle<S: SequenceType>(source: S) -> [S.Generator.Element] {
var rangen = GeneratorOf { arc4random() }
let a = Array(Zip2(rangen, source))
return a.sorted { $0.0 < $1.0 }.map { $0.1 }
}
let min = 1, max = 5
shuffle(min...max)
If you want a selection of n non-repeating random numbers from a range 0..<m, there’s a particularly pretty algorithm to do this that generates an ascending sequence of random numbers from that range:
func randomGeneratorOf(#n: Int, #from: Int) -> GeneratorOf<Int> {
var select = UInt32(n)
var remaining = UInt32(from)
var i = 0
return GeneratorOf {
while i < from {
if arc4random_uniform(remaining) < select {
--select
--remaining
return i++
}
else {
--remaining
++i
}
}
return nil
}
}
Which you could use like so:
let engines = [
"Duck","Emily","Gordon","Henry", "Mavis",
"Belle","James","Edward","Thomas","Toby"
]
let picks = Array(randomGeneratorOf(n: 3, from: engines.count))
for engine in PermutationGenerator(elements: engines, indices: picks) {
println(engine)
}
Below is my suggestion.
I like this way since it is short and simple :)
let totalCount: Int = 150 //Any number you asssign
var randomNumArray: [Int] = []
var i = 0
while randomNumArray.count < totalCount {
i++
let rand = Int(arc4random_uniform(UInt32(totalCount)))
for(var ii = 0; ii < totalCount; ii++){
if randomNumArray.contains(rand){
print("do nothing")
} else {
randomNumArray.append(rand)
}
}
}
I want to count the number of letters, digits and special characters in the following string:
let phrase = "The final score was 32-31!"
I tried:
for tempChar in phrase {
if (tempChar >= "a" && tempChar <= "z") {
letterCounter++
}
// etc.
but I'm getting errors. I tried all sorts of other variations on this - still getting error - such as:
could not find an overload for '<=' that accepts the supplied arguments
For Swift 5 see rustylepord's answer.
Update for Swift 3:
let letters = CharacterSet.letters
let digits = CharacterSet.decimalDigits
var letterCount = 0
var digitCount = 0
for uni in phrase.unicodeScalars {
if letters.contains(uni) {
letterCount += 1
} else if digits.contains(uni) {
digitCount += 1
}
}
(Previous answer for older Swift versions)
A possible Swift solution:
var letterCounter = 0
var digitCount = 0
let phrase = "The final score was 32-31!"
for tempChar in phrase.unicodeScalars {
if tempChar.isAlpha() {
letterCounter++
} else if tempChar.isDigit() {
digitCount++
}
}
Update: The above solution works only with characters in the ASCII character set,
i.e. it does not recognize Ä, é or ø as letters. The following alternative
solution uses NSCharacterSet from the Foundation framework, which can test characters
based on their Unicode character classes:
let letters = NSCharacterSet.letterCharacterSet()
let digits = NSCharacterSet.decimalDigitCharacterSet()
var letterCount = 0
var digitCount = 0
for uni in phrase.unicodeScalars {
if letters.longCharacterIsMember(uni.value) {
letterCount++
} else if digits.longCharacterIsMember(uni.value) {
digitCount++
}
}
Update 2: As of Xcode 6 beta 4, the first solution does not work anymore, because
the isAlpha() and related (ASCII-only) methods have been removed from Swift.
The second solution still works.
Use the values of unicodeScalars
let phrase = "The final score was 32-31!"
var letterCounter = 0, digitCounter = 0
for scalar in phrase.unicodeScalars {
let value = scalar.value
if (value >= 65 && value <= 90) || (value >= 97 && value <= 122) {++letterCounter}
if (value >= 48 && value <= 57) {++digitCounter}
}
println(letterCounter)
println(digitCounter)
For Swift 5 you can do the following for simple strings, but be vigilant about handling characters like "1️⃣" , "④" these would be treated as numbers as well.
let phrase = "The final score was 32-31!"
var numberOfDigits = 0;
var numberOfLetters = 0;
var numberOfSymbols = 0;
phrase.forEach {
if ($0.isNumber) {
numberOfDigits += 1;
}
else if ($0.isLetter) {
numberOfLetters += 1
}
else if ($0.isSymbol || $0.isPunctuation || $0.isCurrencySymbol || $0.isMathSymbol) {
numberOfSymbols += 1;
}
}
print(#"\#(numberOfDigits) || \#(numberOfLetters) || \#(numberOfSymbols)"#);
I've created a short extension for letter and digits count for a String
extension String {
var letterCount : Int {
return self.unicodeScalars.filter({ CharacterSet.letters.contains($0) }).count
}
var digitCount : Int {
return self.unicodeScalars.filter({ CharacterSet.decimalDigits.contains($0) }).count
}
}
or a function to get a count for any CharacterSet you put in
extension String {
func characterCount(for set: CharacterSet) -> Int {
return self.unicodeScalars.filter({ set.contains($0) }).count
}
}
usage:
let phrase = "the final score is 23-13!"
let letterCount = phrase.characterCount(for: .letters)
In case you only need one information (letter or number or sign) you can do it in one line:
let phrase = "The final score was 32-31!"
let count = phrase.filter{ $0.isLetter }.count
print(count) // "16\n"
But doing phrase.filter several times is inefficient because it loops through the whole string.