I am very new to Swift. I am trying to create func...
func circlesDisabledCondition(playerScoreValue: var) {
if playerScoreValue < 1 {
circle1.isEnabled = false
}
if playerScoreValue < 5 {
circle5.isEnabled = false
}
if playerScoreValue < 50 {
circle50.isEnabled = false
}
if playerScoreValue < 100 {
circle100.isEnabled = false
}
else {
circlesEnabled()
}
}
Of course (playerScoreValue: var) doesn't work, I have no idea how can I write it down.
Calling func example (wrong it is just example that I am looking for something like that...)
circlesDisabledCondition(playerScoreValue: player2ScoreValue)
I am looking for this output.
if player2ScoreValue < 1 {
circle1.isEnabled = false
}
if player2ScoreValue < 5 {
circle5.isEnabled = false
}
if player2ScoreValue < 50 {
circle50.isEnabled = false
}
if player2ScoreValue < 100 {
circle100.isEnabled = false
}
else {
circlesEnabled()
}
Many thanks
Replace var with whatever type your playerScoreValue is. If it's an integer, use Int, if it's a float, use float etc.
You can call your function with any variable or value as long as it's of the specified type.
Related
Can anyone explain me the backtracking algorithm? I'm trying to make a permutation program for example if n=2, program will print
1,2
2,1
Although I did this in high-school the teacher didn't really care about us hard enough for us to understand it and I didn't really understand it, neither the algorithms on the internet.
This is what I did so far in the playground but I find myself stuck. I get
1
0
1
0
import Foundation
let n = 2
var tempMatrix : [Int] = []
var resultString : String = ""
//1,2 || 2,1
//0,0
func initTempMatrix(){
for _ in 0..<n {
tempMatrix.append(0)
}
}
func resetMatrixValue(val: Int) {
tempMatrix[val] = 0
}
func isSolution() -> Bool {
for i in 0..<n-1 {
if tempMatrix[i] == 0 {
return false
}
}
return true
}
func isValid() -> Bool {
for i in 0..<n-1 {
if tempMatrix[n-1] == tempMatrix[i] {
return false
}
}
return true
}
func increaseMatrix(val: Int) -> Bool {
if tempMatrix[val] < n {
tempMatrix[val] += 1
return true
}
return false
}
func backtrack() {
initTempMatrix()
var k = 1
while k != 0 {
while !isSolution() {
if increaseMatrix(val: k-1) {
k+=1
}
}
if isValid() {
for i in 0..<tempMatrix.count {
resultString += "\(tempMatrix[i])"
print(resultString)
resultString = ""
}
}
resetMatrixValue(val: k-1)
k -= 1
}
}
backtrack()
I am trying to write a program to find the practical numbers, from an input from 1 to n.
Practical numbers : https://en.wikipedia.org/wiki/Practical_number
My code is running correctly but it is extremely slow - takes over 20 minutes when it should take 10 seconds. This happens when calculating numbers around 50 - it gets stuck at 44.
It is written in Swift
import Foundation
func getInteger() -> Int {
var firstNum:Int = 0
while true {
// get value from user. Using optional input since readLine returns an optional string.
let input = readLine()
// ensure string is not nil
if let unwrappedInput = input {
if let unwrappedInt = Int(unwrappedInput) {
firstNum = unwrappedInt
break
}
else { // the input doesn't convert into an int
print("`\(unwrappedInput)` is not an integer. Please enter an integer")
}
}
else { // did not enter anything
print("Please enter an integer")
}
}
return firstNum
}
func addOne(signArray: [Int]) -> [Int] { // finds the combinations
var signArray2 = [Int]()
for i in 0...signArray.count-1 {
signArray2.append (signArray[i])
}
for i in 0...signArray2.count-1 {
if signArray2[i] == 1 {
signArray2[i] = 0
}
else {
signArray2[i] = 1
break
}
}
return signArray2
}
func signEval (signArray: [Int], divArray: [Int], inNum: Int) -> Bool {// changes 2nd
var counts = 0
for i in 0...divArray.count-1 {
if signArray[i] == 0 {
counts = divArray[i] + counts }
if counts == inNum {
return true
}
}
return false
}
print("Please enter a number to find the summable numbers up to that number:")
var input2 = getInteger()// if num = 1 print 1 if num = 2 print 1 and 2 else print >2 1, 2
var inNum = 0
var numHalf = 0.0
var numRound = 0.0
var numCheck = false
var numCheck2 = false
var numQuarter = 0.0
var numSixth = 0.0
var divArray:[Int] = []
var theirArray = [Int]()
var signArray = [Int]()// array of 0s and 1s
var summableArray:[Int] = [1,2] // need to check if num is bigger than 2!
for input in 1...input2 {
numHalf = Double (input) / 2.0
numRound = round(numHalf)
if numRound == numHalf {
numCheck = true }
if input > 2 && numCheck == false { // odd numbers greater than one are not summable
}
else { // these are possible summable nums
numQuarter = Double (input) / 4.0
numRound = round(numQuarter)
if numRound == numQuarter {
numCheck = true
}
else {
numCheck = false
}
numSixth = Double(input) / 6.0
numRound = round(numSixth)
if numRound == numSixth {
numCheck2 = true }
else { numCheck2 = false}
if numCheck == true || numCheck2 == true {
theirArray = []
divArray = []
signArray = []
summableArray = []
for i in 1...input {
theirArray.append (i)
}
for i in 1...input { // creates an array of all the diviors of inputted number
if input%i == 0 {
divArray.append (i)
}
}
for j in 1...divArray.count {//
signArray.append(0)
}
for i in 1...input{
let x: Int = Int(pow(Double(2),Double(input-1)))// int 2 to the power of input -1
var Boolcheck = false
for q in 1...x-1 { // i to 2^n -1 (sequence to check)
Boolcheck = (signEval(signArray: signArray, divArray: divArray, inNum: i))// checks
signArray = addOne(signArray: signArray)// adding the ones to the array
if Boolcheck == true {
summableArray.append(i)// creates array of mini summable numbers
break
}
}
if summableArray.count == input {
print ("\(input)")
}
}
}
}
}
I've made this method:
func checkScore(player: Int) -> Bool {
var checkedFields: [Int] = []
var won: Bool = false
for var i = 0; i <= 9; i += 1 {
if(winningCombinations[i] == player) {
checkedFields.append(i)
}
}
for value in winningCombinations {
var hits = 0
for n in checkedFields {
if value.contains(n){
hits += 1
}
}
if hits == 3 {
won = true
}
}
return won
}
But when I try to build it everything becomes white and the build crashes. Am I doing something wrong here? I pass the value like this:
if self.checkScore(player) {
print("Won!")
}
(I see no error message!)
Your func checkScore(player: Int) accepts player, which is of type Int.
In your code you also say : if(winningCombinations[i] == player), meaning that you expect the elements in array winningCombinations to also be of type Int
But then you say
for value in winningCombinations {
var hits = 0
for n in checkedFields {
if value.contains(n){
If value is an element in winningCombination, it means that value is an int.. how can you say value.contains(n). Int cannot perform contains operation. Arrays can.
My question is simple in the C language, just access the global variable using access with a pointer -
demoFunc(int *someVar) {
*someVar = 1234;
return;
}
How do you do this in Swift? For simplicity and clarity, how do you do this for the following code?
class Example {
var globalInt : Int = 0;
func someMain() {
self.modifyVar(?&globalInt?); //Q: How do you do this?
return;
}
func modifyVar(?&someVar?) { //Q: ?
someVar = 1234; //Q: ?
return;
}
}
This code:
var toto = 3
class Example {
var globalInt = 0
func someMain() {
self.modifyVar(&globalInt)
}
func modifyVar(inout someVar: Int) {
someVar = 1234
}
}
let vc = Example()
print(vc.globalInt)
vc.someMain()
print(vc.globalInt)
print(toto)
vc.modifyVar(&toto)
print(toto)
produces
0
1234
3
1234
Trying to write a check for Prime numbers in the array. The array is populated randomly. But when processing the array code does not work... What am I doing wrong? Thank you!
update 2
Filling the array correctly. But with the test simple number, something is wrong. Specifically what is wrong can not say, but the point is that the rules of a simple number sorting is not working.
import Foundation
func randomArray(var i:Int,var k:Int, var array: [Int]=[], var newArray: [Int]=[]) ->Int {
for i=0;i<10;i++ {
array.append(Int(arc4random_uniform(10)))
}
for i=0;i<=array.count; i++ {
for k=2; k<array[i]; k++ {
if array[i] != 0 && array[i] != 1 && array[i]%k != 0 {
newArray.append(array[i])
} else {
return 0
}
}
}
return newArray[i]
}
randomArray(0, k: 0)
It's not clear to me what you want to do.
a) If you want to generate an array of length k at random and filter for prime numbers, use the code below. Note that this can give give you an array of length between 0 to k, because they may be no prime in the randomly generated array, or every number generated was a prime:
func isPrime(num: Int) -> Bool {
if num < 2 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
func randomArray(len: Int) -> [Int] {
var results = [Int]()
for _ in 0..<len {
results.append(Int(arc4random_uniform(10)))
}
return results.filter(isPrime)
}
b) If you want an array of k primes, use this instead:
func randomPrimeArray(len: Int) -> [Int] {
var results = [Int]()
while results.count < len {
let x = Int(arc4random_uniform(10))
if isPrime(x) {
results.append(x)
}
}
return results
}
if you want to filter prime numbers from an array use this code:
let primeNumbers = myArray.filter { number in
if number == 0 {
return false
}
return number % 2 == 0
}