func updateTotalScore() -> Int {
var totalScoreDefault = NSUserDefaults.standardUserDefaults()
var highScoreAB1 = defaults.integerForKey("highScoreAB1")
var highScoreAB2 = defaults.integerForKey("highScoreAB2")
var highScoreAB3 = defaults.integerForKey("highScoreAB3")
var highScoreAB4 = defaults.integerForKey("highScoreAB4")
var highScoreAB5 = defaults.integerForKey("HighScoreAB5")
var highScoreAB6 = defaults.integerForKey("highScoreAB6")
var highScoreAB7 = defaults.integerForKey("highScoreAB7")
totalScoreDefault =
(defaults.integerForKey("highScoreAB1") + defaults.integerForKey("highScoreAB2")) + (defaults.integerForKey("highScoreAB3") + defaults.integerForKey("highScoreAB4")) + (defaults.integerForKey("highScoreAB5") + defaults.integerForKey("highScoreAB6")) + defaults.integerForKey("highScoreAB7") }
Adding multiple keys to get a total score default throws the following error. I tried grouping them together into pairs, and that did not work. Thank you in advance. This is a continuation from a post from yesterday.
Just as an addition to Logan's answer, because you are saying that you have problems with "complex expression" compiler error. This should compile:
func updateTotalScore() -> Int {
let defaults = NSUserDefaults.standardUserDefaults()
let totalScoretDefault =
defaults.integerForKey("highScoreAB1") +
defaults.integerForKey("highScoreAB2") +
defaults.integerForKey("highScoreAB3") +
defaults.integerForKey("highScoreAB4") +
defaults.integerForKey("highScoreAB5") +
defaults.integerForKey("highScoreAB6") +
defaults.integerForKey("highScoreAB7")
return totalScoretDefault
}
It looks like you are trying to add all of the highscores up into one UserDefault named totalScoreDefault. If so, you need to be setting the totalScoreDefault like so:
default.setInteger(highScoreAB1 + ... + highScoreAB7, forKey: "totalScoreDefault")
// You can also consider adding all highScores up before
// this to make the setInteger portion look cleaner.
var totalScore = 0
for var i = 1; i < 8; i++ {
totalScore += defaults.integerForKey("highScoreAB\(i)")
}
defaults.setInteger(totalScore, forKey: "totalScoreDefault")
Related
Hello i practice on hackerRank using swift and now i have a problem. My code works great in swift playground, and return the expected result, but in HackerRank i have runtime error ~ no response on stdout ~ I've tried to reset code and refresh page. What could be the problem?
func diagonalDifference(arr: [[Int]]) -> Int {
// Write your code here
let rowNumber = arr[0][0]
var leftD = 0
var rightD = 0
for i in 1...rowNumber {
leftD += arr[i][i - 1]
}
var increasedNum = 0
for i in (1...rowNumber).reversed() {
rightD += arr[i][increasedNum]
increasedNum += 1
}
var absoluteDifference = leftD - rightD
if absoluteDifference < 0 {
absoluteDifference = absoluteDifference * -1
}
return absoluteDifference
}
Here is the challenge page:
https://www.hackerrank.com/challenges/diagonal-difference/problem
Your problem is a misunderstanding of what is passed to your diagonalDifference() function. The code which calls that function uses the first line of input to correctly size the array, but that value is not passed to your function in arr[0][0]. Instead, you should use arr.count to determine the dimensions of the array, then you should be indexing the array as 0..<arr.count.
To fix your code
change:
let rowNumber = arr[0][0]
to:
let rowNumber = arr.count
change:
leftD += arr[i][i - 1]
to:
leftD += arr[i][i]
And change both instances of
1...rowNumber
to:
0..<rowNumber
func diagonalDifference(arr: [[Int]]) -> Int {
var difference = 0
for i in 0..<arr.count {
difference += (arr[i][i] - arr[i][arr.count-1-i])
}
return Int(abs(difference))
}
I'm trying to write a function that has arrayOne, arrayTwo, and arrayThree as inputs. If arrayTwo has any 0s as its last elements, the function is supposed to remove these elements from the array, as well as the same elements from arrayOne. When I run the code and try to test it, I get the error: "Terminated by signal 4".
What could the problem be?
var arrayOneNew = arrayOne
var arrayTwoNew = arrayTwo
var arrayThreeNew = arrayThree
var endElement = arrayTwoNew.last
if endElement == 0 {
var counter = arrayTwoNew.count
while arrayTwoNew[counter] == 0 {
var elementToBeRemoved = arrayTwoNew.remove(at: counter - 1)
var 2ndElementToBeRemoved = arrayOneNew.remove(at: counter - 1)
}
}
Your main problem is that you are setting counter to arrayTwoNew.count which is 1 bigger than the last valid index in arrayTwoNew, so while arrayTwoNew[counter] == 0 crashes with index out of range.
Also:
var elementToBeRemoved = arrayTwoNew.remove(at: counter - 1)
is probably meant to remove the last item from arrayTwoNew, but that is more easily accomplished with:
arrayTwoNew.removeLast()
especially since you're not using elementToBeRemoved.
I think you're trying to do this:
while arrayTwoNew.last == 0 {
arrayTwoNew.removeLast()
arrayOneNew.removeLast()
arrayThreeNew.removeLast()
}
You are creating a new array "arrayTwoNew" which is mixed up with the original one at
var arrayTwoNew = arrayTwoNew.remove(at: counter - 1)
Now I'm also struggling with your .remove - this returns an element so won't work. I'd usually use a filter here but I'm not sure what you are doing!
//code with remove taken out (replace with filter?) to get you started:
let arrayOne = [1,2,3]
let arrayTwo = [2,3,4]
let arrayThree = [5,6,7]
var arrayOneNew = arrayOne
var arrayTwoNew = arrayTwo
var arrayThreeNew = arrayThree
var endIndex = arrayTwoNew.last
if endIndex == 0 {
let counter = arrayTwoNew.count
// arrayTwoNew = arrayTwoNew.remove(at: counter - 1)
while arrayTwoNew[counter] == 0 {
// arrayOneNew = arrayOneNew.remove(at: counter - 1)
}
}
Dispatching the queue messes up the order in the array as noted below. I'm trying to rank the array and then be able to translate it. So far its not working:
let top5 = Array(labels.sorted{ $0.confidence > $1.confidence}.prefix(upTo:5))
for lulu in top5 {
let translator = ROGoogleTranslate()
var params = ROGoogleTranslateParams()
params.source = "en"
params.target = "es"
params.text = "\(String(describing: lulu.label))"
translator.translate(params: params, callback: { (result) in
DispatchQueue.main.async {
self.textUno.text = self.textUno.text! + "\(lulu.label)" + " \(lulu.confidence*100)\n"
self.textDos.text = self.textDos.text! + "\(result)\n"
self.view.addSubview(self.textUno)
self.view.addSubview(self.textDos)
}
})
}
If I try to put the sorting out of DispatchQueue.main.async then the translation won't be lined up with the right word.
How can I fix this so that the array is sorted and the translation matches up ?
Translate the array first before ranking them.
Make it simpler first and make sure it is working and then put all the parts together.
If you really want to do it this way you will need to put them into a temporary array after sorting them and then use that at the end.
This, as you said, will return a jumbled result.
The below example is pretty close, needs a bit of a polish but you should be able to do it from this.
let top5 = Array(labels.sorted{ $0.confidence > $1.confidence}.prefix(upTo:5))
var tmparr : []
var count: Int = 0
for lulu in top5 {
let translator = ROGoogleTranslate()
count = count + 1
var params = ROGoogleTranslateParams()
params.source = "en"
params.target = "es"
params.text = "\(String(describing: lulu.label))"
params.ordernumber = count
translator.translate(params: params, callback: { (result) in
tmparr.append[params]
})
}
DispatchQueue.main.async {
for lulunew in tmparr {
if (lulunew.ordernumber == correctindex){
self.textUno.text = self.textUno.text! + "\(lulu.label)" + " \(lulu.confidence*100)\n"
self.textDos.text = self.textDos.text! + "\(result)\n"
self.view.addSubview(self.textUno)
self.view.addSubview(self.textDos)
}
}
}
Help. I just converted to swift 3 and am getting errors when I try to add two NSNumbers together i.e.:
var foodPrice: NSNumber!
var priceSum: NSNumber!
foodPrice = 6.79
priceSum = 11.89
var totalSum = NSNumber(foodPrice + priceSum) // <-- error here
OR
var totalSum = (foodPrice + priceSum) as NSNumber // <-- still error here
Doesn't matter how I change totalSum I can't get away from this error. Please help. This is my official SOS. Dazed and confused here. How do I make this work?
Why not write your own + override for NSNumber?
func + (lhs: NSNumber, rhs: NSNumber) -> NSNumber {
return NSNumber(value: lhs.floatValue + rhs.floatValue)
}
var foodPrice: NSNumber = 6.79
var priceSum: NSNumber = 11.89
var totalSum = foodPrice + priceSum // 18.68
I use floats here but you can use any type you need.
var foodPrice: NSNumber!
var priceSum: NSNumber!
foodPrice = 6.79
priceSum = 11.89
var totalSum = NSNumber(double: foodPrice.doubleValue + priceSum.doubleValue)
Try this out..!
Try
var totalSum = NSNumber(value: foodPrice.doubleValue + priceSum.doubleValue)
I would like to print the result of the bool value
When I do it I have "true" instead the amount.
I know it probably sounds really stupid but I'm just getting started with swift
var monthsWeek:Int?
var hoursWageHours:Double = 14.47
let months4WeeksHours:Double = 156.00
let months5WeeksHours:Double = 195.00
var normalpay:Double = 0
let months5weeks:Bool = true
let months4weeks:Bool = true
if months5weeks {
normalpay = hoursWageHours * months5WeeksHours
if months4weeks {
normalpay = hoursWageHours * months4WeeksHours
}
}
or woud that make more sence even if didnt print the result still
var monthsWeek:Int?
var hoursWageHours:Double = 14.47
let months4WeeksHours:Double = 156.00
let months5WeeksHours:Double = 195.00
var normalpay:Double = 0
if monthsWeek == 195 {
normalpay = hoursWageHours * months5WeeksHours
if monthsWeek == 4 {
normalpay = hoursWageHours * months4WeeksHours
}
}
monthsWeek = 4
I came here looking for an actual print of a bool. It turns out you can do this:
var a_bool = false
print("a_bool is ")
println(a_bool)
And you can do this with ints:
var a_int = 42
println("This is an int " + String(a_int))
You can't do this with bools though. However you can do:
println("This is a bool " + String(stringInterpolationSegment: a_bool))
This is the closet I can come up with for something like this:
println("a_bool is ", a_bool) // does not work
println("a_bool is " + a_bool) // also does not work
Later on, I learned you can use \(variable) embedding like this:
println("This is an int \(a_int)")
A boolean variable can take only 2 values (true or false).
So it is logical that when you print it you have true or false.