IOS Swift 2.0 Card shuffling function [duplicate] - ios

This question already has answers here:
How do I shuffle an array in Swift?
(25 answers)
Closed 6 years ago.
Noob here, I am trying to create a card game using a standard deck of 52 cards. Here is the code I would like to make into a func so I dont have to manually write it out every single time. I am creating 5 different players so this would be replicated to other players.
func firstPlayerCardShuffle() {
var firstPlayerCard1Num = (Int(arc4random_uniform(UInt32(13)) + 2))
var firstPlayerCard1Suit = suits[Int(arc4random_uniform(UInt32(suits.count)))]
var firstPlayerCard1 = "\(firstPlayerCard1Num) of \(firstPlayerCard1Suit)"
var firstPlayerCard2Num = (Int(arc4random_uniform(UInt32(13)) + 2))
var firstPlayerCard2Suit = suits[Int(arc4random_uniform(UInt32(suits.count)))]
var firstPlayerCard2 = "\(firstPlayerCard2Num) of \(firstPlayerCard2Suit)"
return(firstPlayerCard1,firstPlayerCard2)
}
Can someone let me know what I'm missing.

Not a direct answer to your question, but I think you'll want something like this:
enum Number: String {
case Two = "two"
case Three = "three"
case Four = "four"
case Five = "five"
case Six = "six"
case Seven = "seven"
case Eight = "eight"
case Nine = "nine"
case Ten = "ten"
case Jack = "jack"
case Queen = "queen"
case King = "king"
case Ace = "ace"
static var randomNumber: Number {
return [Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace][Int(arc4random_uniform(13))]
}
}
enum Suit: String {
case Spades = "spades"
case Hearts = "hearts"
case Diamonds = "diamonds"
case Clubs = "clubs"
static var randomSuit: Suit {
return [Spades, Hearts, Diamonds, Clubs][Int(arc4random_uniform(4))]
}
}
struct Card: CustomStringConvertible, Equatable {
let number: Number
let suit: Suit
var description: String {
return "\(number.rawValue) of \(suit.rawValue)"
}
static var randomCard: Card {
return Card(number: Number.randomNumber, suit: Suit.randomSuit)
}
static func randomCards(count count: Int) -> [Card] {
guard count > 0 else {
return []
}
guard count <= 52 else {
fatalError("There only are 52 unique cards.")
}
let cards = randomCards(count: count - 1)
while true {
let card = randomCard
if !cards.contains(card) {
return cards + [card]
}
}
}
}
func == (left: Card, right: Card) -> Bool {
return left.number == right.number && left.suit == right.suit
}
let randomCards = Card.randomCards(count: 5)
print(randomCards)
// prints five random cards
Let me know if you have any other questions.

Related

The initialization of my playerCard does not work

I'm new to swift and I'm trying to make a simple card game where the player and computer draws a card and whoever has the largest card wins. But when I call my compareCards function, I got an error: constant 'playerCard' used before being initialized. I thought I already initialized playerCard so I'm wondering if someone could tell me what's wrong with my code? Thank you.
import Foundation
func randomInteger(upper: Int) -> Int {
return Int(arc4random_uniform(UInt32(upper)))
}
enum Rank: Int{
case two = 2,
three,
four, five,
six,
seven,
eight,
nine,
ten,
jack,
queen,
king,
ace
static func allValues() -> [Rank]{
return [two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace]
}
}
enum Suit: Int{
case clubs = 1,
diamonds,
hearts,
spades
static func allValues() -> [Suit]{
return [spades, hearts, diamonds, clubs]
}
}
struct Card{
var rank: Rank = .two
var suit: Suit = .clubs
init(rank: Rank, suit: Suit){
self.rank = rank
self.suit = suit
}
}
class Deck{
var deck: [Card] = []
var rankArray: [Rank] = []
var suitArray: [Suit] = []
init(){
rankArray = Rank.allValues()
suitArray = Suit.allValues()
for aRank in rankArray{
for aSuit in suitArray{
let aCard = Card(rank: aRank, suit: aSuit)
deck.append(aCard)
}
}
}
func drawOne() -> Card?{
if deck.count != 0{
let randomCard = randomInteger(upper: deck.count)
let aCard = deck[randomCard]
deck.remove(at: randomCard)
return aCard
}
else{
return nil
}
}
}
func compareCards(playerCard: Card, computerCard: Card) -> String{
var isPlayerGreater: Bool = false
if playerCard.rank != computerCard.rank{
if playerCard.rank.rawValue > computerCard.rank.rawValue{
isPlayerGreater = true
}
}
if playerCard.suit.rawValue > computerCard.suit.rawValue{
isPlayerGreater = true
}
if isPlayerGreater == true{
return "The player won with the \(playerCard.rank) of \(playerCard.suit)!"
}
else{
return "The computer won with the \(computerCard.rank) of \(computerCard.suit)!"
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
let playerCard: Card
let computerCard: Card
let aDeck = Deck()
if let aCard = aDeck.drawOne(){
playerCard = Card(rank: aCard.rank, suit: aCard.suit)
}
if let aCard = aDeck.drawOne(){
computerCard = Card(rank: aCard.rank, suit: aCard.suit)
}
var result: String = compareCards(playerCard: playerCard, computerCard: computerCard)
print(result)
because you didn't initialize. your darawOne() function is nullable and you set condition " if aDeck -> playercard = aDeck". what about if result == nil???
I change your last code to this:
let aDeck = Deck()
if let aCard = aDeck.drawOne(), let seCard = aDeck.drawOne(){
let playerCard = Card(rank: aCard.rank, suit: aCard.suit)
let computerCard = Card(rank: aCard.rank, suit: seCard.suit)
let result: String = compareCards(playerCard: playerCard, computerCard: computerCard)
print(result)
}
Below code works well.
let aDeck = Deck()
if let playerCard = aDeck.drawOne(), let computerCard = aDeck.drawOne() {
var result: String = compareCards(playerCard: playerCard, computerCard: computerCard)
print(result)
}
Error was thrown by compiler because you have declared two non-optional constants but not initialised it.
Your problem is that you must init playerCard and computerCard before using it. If your code will not pass if let statement your cards will not init.
Here you have two options atleast either provide a default value to your variables either mark them as force unwrapped so the compiler will ignore not inited state as you telling that you 100% sure variables will be at run time.
The second option will look next:
Replace your
let playerCard: Card
let computerCard: Card
With:
var playerCard: Card!
var computerCard: Card!
You need to just declare playerCard and computerCard variable with var keyword instead of let
You can use let when you know that once you assign a value to a variable, it doesn't change and with using var you can change the value to a variable.
var playerCard: Card
var computerCard: Card
let aDeck = Deck()
if let aCard = aDeck.drawOne(){
playerCard = Card(rank: aCard.rank, suit: aCard.suit) //you are assigning/changing the value here of playerCard variable.
}
if let aCard = aDeck.drawOne(){
computerCard = Card(rank: aCard.rank, suit: aCard.suit) //you are assigning/changing the value here of playerCard variable.
}

make comparisons between 2 dice toss in an IOS app

I have an app with 2 image views. each one randomly displays an image of a dice face (from 1 to 6), the end results looks like the simulation of a dice toss for a player and for the computer.
it looks like this :
I have an array that contains the names for each image that is displayed :
let des: Array = ["one", "two", "three", "four", "five", "six"]
I also have a function that randomizes the image that is displayed for the 2 players
UIView.animate(withDuration: 0.5) {
self.dicePlayer.image = UIImage(named: self.des.randomElement() ?? "one")
self.diceComputer.image = UIImage(named: self.des.randomElement() ?? "two")
}
// on appelle la fonction qui gere les scores
gestionDesScores()
}
I would like to make comparison between those 2 tosses (i.e : if player one dice toss is superior to player 2 toss, then the player wins and vice versa).
Have your dice values in an enum:
enum Die: String,CaseIterable{
case One = "one"
case Two = "two"
case Three = "three"
case Four = "four"
case Five = "five"
case Six = "six"
}
Add an extension :
extension CaseIterable where Self: Equatable {
var index: Self.AllCases.Index? {
return Self.allCases.firstIndex { self == $0 }
}
}
And your throwDie method can look like :
func throwDice(){
let userResult = Die.allCases.randomElement()
let computerResult = Die.allCases.randomElement()
UIView.animate(withDuration: 0.2, animations: {
self.dicePlayer.image = UIImage(named: userResult?.rawValue ?? "one")
self.diceComputer.image = UIImage(named: computerResult?.rawValue ?? "one")
}) { (_) in
print("Index Value : \(computerResult?.index) : \(computerResult?.rawValue)")
//You may use the indexValue for comparison and the rawValue to assign your image
}
}
Self explanatory, I believe.
You can try
let fImg = self.des.randomElement() ?? "one"
let sImg = self.des.randomElement() ?? "two"
UIView.animate(withDuration: 0.5) {
self.dicePlayer.image = UIImage(named:fImg)
self.diceComputer.image = UIImage(named:sImg)
}
Then
if let fIndex = des.index(of:fImg) ,
let sIndex = des.index(of:sImg) ,
fIndex == (sIndex - 1) {
// wins
}
I would recommend storing the two tosses as human readable Int values. Add these properties to your class:
var playerToss = 1
var computerToss = 1
Then modify your function like this:
func lancerDeDes() {
self.playerToss = Int.random(in: 1...6)
self.computerToss = Int.random(in: 1...6)
UIView.animate(withDuration: 0.5) {
// subtract 1 because des array is indexed 0...5 not 1...6
self.dicePlayer.image = UIImage(named: self.des[self.playerToss - 1])
self.diceComputer.image = UIImage(named: self.des[self.computerToss - 1])
}
// on appelle la fonction qui gere les scores
gestionDesScores()
}
Then you can just compare playerToss and computerToss directly:
if self.playerToss > self.computerToss {
// the player wins!
}
Storing the values as Int will aid you in debugging in addition to making the comparison easier.
Magic Numbers
In your program, I think it is clear what 6 represents. In general though it is wise to avoid magic numbers (uncommented numbers) in your code. So you could write the rolls as:
self.playerToss = Int.random(in: des.indices) + 1
self.computerToss = Int.random(in: des.indices) + 1
By using des.indices to obtain the range 0...5 from the des array, you ensure that the code would work correctly even if the number of values in the des array changed.
I personally would still store the rolls in the range 1...6 for debugging purposes, but you could avoid the + 1 and - 1 by storing the rolls in the range 0...5.

Get a random unique element from an Array until all elements have been picked in Swift

I have the following array:
var notebookCovers = ["cover1", "cover2", "cover3", "cover4", "cover4", "cover6", "cover7", "cover8", "cover9", "cover10"]
and a UIButton that when it's pressed it generates a new UIImage with one of the elements of the array.
What I need to do is every time the button is tapped to generate random but unique element from the array (without repeating the elements) until they've all been selected and then restart the array again.
So far, I have it getting a random element but it's repeated and I cannot figure out how to it so it gets a unique image every time
func createNewNotebook() {
let newNotebook = Notebook()
let randomInt = randomNumber()
newNotebook.coverImageString = notebookCovers[randomInt]
notebooks.insert(newNotebook, at: 0)
collectionView.reloadData()
}
func randomNumber() -> Int {
var previousNumber = arc4random_uniform(UInt32(notebookCovers.count))
var randomNumber = arc4random_uniform(UInt32(notebookCovers.count - 1))
notebookCovers.shuffle()
if randomNumber == previousNumber {
randomNumber = UInt32(notebookCovers.count - 1)
}
previousNumber = randomNumber
return Int(randomNumber)
}
Set is a collection type that holds unique elements. Converting your notebooks array to Set also lets you take advantage of its randomElement function
var aSet = Set(notebooks)
let element = aSet.randomElement()
aSet.remove(element)
Copy the array. Shuffle the copy. Now just keep removing the first element until the copy is empty. When it is empty, start over.
Example:
let arr = [1,2,3,4,5]
var copy = [Int]()
for _ in 1...30 { // just to demonstrate what happens
if copy.isEmpty { copy = arr; copy.shuffle() }
let element = copy.removeFirst() ; print(element, terminator:" ")
}
// 4 2 3 5 1 1 5 3 2 4 4 1 2 3 5 1 4 5 2 3 3 5 4 2 1 3 2 4 5 1
If you want to create a looping solution:
let originalSet = Set(arrayLiteral: "a","b","c")
var selectableSet = originalSet
func repeatingRandomObject() -> String {
if selectableSet.isEmpty {
selectableSet = originalSet
}
return selectableSet.remove(selectableSet.randomElement()!)!
}
force unwrapping is kind of safe here, since we know that the result will never be nil. If you don't want to force unwrap:
let originalSet = Set(arrayLiteral: "a","b","c")
var selectableSet = originalSet
func repeatingRandomObject() -> String? {
if selectableSet.isEmpty {
selectableSet = originalSet
}
guard let randomElement = selectableSet.randomElement() else { return nil }
return selectableSet.remove(randomElement)
}
You can try something like this,
var notebookCovers = ["cover1", "cover2", "cover3", "cover4", "cover4", "cover6", "cover7", "cover8", "cover9", "cover10"]
var tappedNotebooks: [String] = []
func tapping() {
let notebook = notebookCovers[Int.random(in: 0...notebookCovers.count - 1)]
if tappedNotebooks.contains(notebook){
print("already exists trying again!")
tapping()
} else {
tappedNotebooks.append(notebook)
print("appended", notebook)
}
if tappedNotebooks == notebookCovers {
tappedNotebooks = []
print("cleared Tapped notebooks")
}
}
It is possible with shuffle:
struct AnantShuffler<Base: MutableCollection> {
private var collection: Base
private var index: Base.Index
public init?(collection: Base) {
guard !collection.isEmpty else {
return nil
}
self.collection = collection
self.index = collection.startIndex
}
public mutating func next() -> Base.Iterator.Element {
let result = collection[index]
collection.formIndex(after: &index)
if index == collection.endIndex {
collection.shuffle()
index = collection.startIndex
}
return result
}
}
fileprivate extension MutableCollection {
/// Shuffles the contents of this collection.
mutating func shuffle() {
let c = count
guard c > 1 else { return }
for (firstUnshuffled, unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
let d: Int = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
let i = index(firstUnshuffled, offsetBy: d)
swapAt(firstUnshuffled, i)
}
}
}
Use:
let shuffler = AnantShuffler(collection: ["c1","c2","c3"].shuffled())
shuffler?.next()

Swift Anagram checker

I am attempting to build an anagram checker for swift. This is my code. In case you don't know an anagram checker checks if two strings have the same characters in them but, order does not matter.
func checkForAnagram(#firstString: String, #secondString: String) -> Bool {
var firstStringArray: [Character] = []
var secondStringArray: [Character] = []
/* if case matters delete the next four lines
and make sure your variables are not constants */
var first = firstString
var second = secondString
first = first.lowercaseString
second = second.lowercaseString
for charactersOne in first {
firstStringArray += [charactersOne]
}
for charactersTwo in second {
secondStringArray += [charactersTwo]
}
if firstStringArray.count != secondStringArray.count {
return false
} else {
for elements in firstStringArray {
if secondStringArray.contains(elements){
return true
} else {
return false
}
}
}
}
var a = "Hello"
var b = "oellh"
var c = "World"
checkForAnagram(firstString: a, secondString: b)
I am getting an error message of.
'[Character]' does not have a member 'contains'
The accepted answer is compact and elegant, but very inefficient if compared to other solutions.
I'll now propose and discuss the implementation of a few variants of anagram checker. To measure performance, I'll use the different variants to find the anagrams of a given word out of an array of 50,000+ words.
// Variant 1: Sorting of Character
// Measured time: 30.46 s
func anagramCheck1(a: String, b: String) -> Bool {
return a.characters.sorted() == b.characters.sorted()
}
This is essentially the solution of the accepted answer, written in Swift 3 syntax. It's very slow because Swift's String, unlike NSString, is based on Character, which handles Unicode characters properly.
A more efficient solution exploits the NSCountedSet class, which allows us to represent a string as a set of characters, each with its own count. Two strings are anagrams if they map to the same NSCountedSet.
Note: checking string lengths as a precondition makes the implementation always more efficient.
// Variant 2: NSCountedSet of Character
// Measured time: 4.81 s
func anagramCheck2(a: String, b: String) -> Bool {
guard a.characters.count == b.characters.count else { return false }
let aSet = NSCountedSet()
let bSet = NSCountedSet()
for c in a.characters {
aSet.add(c)
}
for c in b.characters {
bSet.add(c)
}
return aSet == bSet
}
Better but not excellent. Here, one of the "culprits" is the use of the native Swift Character type (from Swift's String). Moving back to good old Objective-C types (NSString and unichar) makes things more efficient.
// Variant 3: NSCountedSet of unichar
// Measured time: 1.31 s
func anagramCheck3(a: String, b: String) -> Bool {
let aString = a as NSString
let bString = b as NSString
let length = aString.length
guard length == bString.length else { return false }
let aSet = NSCountedSet()
let bSet = NSCountedSet()
for i in 0..<length {
aSet.add(aString.character(at: i))
bSet.add(bString.character(at: i))
}
return aSet == bSet
}
Using NSCountedSet is fine, but before we compare two NSCountedSet objects, we fully populate them. A useful alternative is to fully populate the NSCountedSet for only one of the two strings, and then, while we populate the NSCountedSet for the other string, we fail early if the other string contains a character that is not found in the NSCountedSet of the first string.
// Variant 4: NSCountedSet of unichar and early exit
// Measured time: 1.07 s
func anagramCheck4(a: String, b: String) -> Bool {
let aString = a as NSString
let bString = b as NSString
let length = aString.length
guard length == bString.length else { return false }
let aSet = NSCountedSet()
let bSet = NSCountedSet()
for i in 0..<length {
aSet.add(aString.character(at: i))
}
for i in 0..<length {
let c = bString.character(at: i)
if bSet.count(for: c) >= aSet.count(for: c) {
return false
}
bSet.add(c)
}
return true
}
This is about the best timing we are going to get (with Swift). However, for completeness, let me discuss one more variant of this kind.
The next alternative exploits a Swift Dictionary of type [unichar: Int] to store the number of repetitions for each character instead of NSCountedSet. It's slightly slower than the previous two variants, but we can reuse it later to obtain a faster implementation.
// Variant 5: counting repetitions with [unichar:Int]
// Measured time: 1.36
func anagramCheck5(a: String, b: String) -> Bool {
let aString = a as NSString
let bString = b as NSString
let length = aString.length
guard length == bString.length else { return false }
var aDic = [unichar:Int]()
var bDic = [unichar:Int]()
for i in 0..<length {
let c = aString.character(at: i)
aDic[c] = (aDic[c] ?? 0) + 1
}
for i in 0..<length {
let c = bString.character(at: i)
let count = (bDic[c] ?? 0) + 1
if count > aDic[c] ?? 0 {
return false
}
bDic[c] = count
}
return true
}
Note that a vanilla Objective-C implementation using NSCountedSet, corresponding to Variant 3, is faster than all the previous versions by a rather large margin.
// Variant 6: Objective-C and NSCountedSet
// Measured time: 0.65 s
- (BOOL)anagramChecker:(NSString *)a with:(NSString *)b {
if (a.length != b.length) {
return NO;
}
NSCountedSet *aSet = [[NSCountedSet alloc] init];
NSCountedSet *bSet = [[NSCountedSet alloc] init];
for (int i = 0; i < a.length; i++) {
[aSet addObject:#([a characterAtIndex:i])];
[bSet addObject:#([b characterAtIndex:i])];
}
return [aSet isEqual:bSet];
}
Another way we can improve upon the previous attempts is to observe that, if we need to find the anagram of a given word, we might as well consider that word as fixed, and thus we could build the corresponding structure (NSCountedSet, Dictionary, ...) for that word only once.
// Finding all the anagrams of word in words
// Variant 7: counting repetitions with [unichar:Int]
// Measured time: 0.58 s
func anagrams(word: String, from words: [String]) -> [String] {
let anagrammedWord = word as NSString
let length = anagrammedWord.length
var aDic = [unichar:Int]()
for i in 0..<length {
let c = anagrammedWord.character(at: i)
aDic[c] = (aDic[c] ?? 0) + 1
}
let foundWords = words.filter {
let string = $0 as NSString
guard length == string.length else { return false }
var bDic = [unichar:Int]()
for i in 0..<length {
let c = string.character(at: i)
let count = (bDic[c] ?? 0) + 1
if count > aDic[c] ?? 0 {
return false
}
bDic[c] = count
}
return true
}
return foundWords
}
Now, in the previous variant we have counted with a [unichar:Int] Dictionary. This proves slightly more efficient than using an NSCountedSet of unichar, either with early exit (0.60 s) or without (0.87 s).
You should try
func checkForAnagram(firstString firstString: String, secondString: String) -> Bool {
return firstString.lowercaseString.characters.sort() == secondString.lowercaseString.characters.sort()
}
func checkAnagrams(str1: String, str2: String) -> Bool {
guard str1.count == str2.count else { return false }
var dictionary = Dictionary<Character, Int>()
for index in 0..<str1.count {
let value1 = str1[str1.index(str1.startIndex, offsetBy: index)]
let value2 = str2[str2.index(str2.startIndex, offsetBy: index)]
dictionary[value1] = (dictionary[value1] ?? 0) + 1
dictionary[value2] = (dictionary[value2] ?? 0) - 1
}
return !dictionary.contains(where: {(_, value) in
return value != 0
})
}
Time complexity - O(n)
// Make sure name your variables correctly so you won't confuse
// Mutate the constants parameter, lowercase to handle capital letters and the sorted them to compare both. Finally check is there are equal return true or false.
func anagram(str1: String, srt2: String)->Bool{
let string1 = str1.lowercased().sorted()
let string2 = srt2.lowercased().sorted()
if string1 == string2 {
return true
}
return false
}
// This answer also would work
// Convert your parameters on Array, then sorted them and compare them
func ana(str1: String, str2: String)->Bool{
let a = Array(str1)
let b = Array(str2)
if a.sorted() == b.sorted() {
return true
}
return false
}
Don't forget whitespaces
func isAnagram(_ stringOne: String, stringTwo: String) -> Bool {
return stringOne.lowercased().sorted().filter { $0 != " "} stringTwo.lowercased().sorted().filter { $0 != " "}
}
Swift 4.1 Function will give you 3 questions answer for Anagram :-
1. Input Strings (a,b) are Anagram ? //Bool
2. If not an Anagram then number of count require to change Characters in strings(a,b) to make them anagram ? // Int
3. If not an Anagram then list of Characters needs to be change in strings(a,b) to make them anagram ? // [Character]
STEP 1:- Copy and Paste below function in to your required class:-
//MARK:- Anagram checker
func anagramChecker(a:String,b:String) -> (Bool,Int,[Character]) {
var aCharacters = Array(a)
var bCharacters = Array(b)
var count = 0
var isAnagram = true
var replacementRequiredWords:[Character] = [Character]()
if aCharacters.count == bCharacters.count {
let listA = aCharacters.filter { !bCharacters.contains($0) }
for i in 0 ..< listA.count {
if !replacementRequiredWords.contains(listA[i]) {
count = count + 1
replacementRequiredWords.append(listA[i])
isAnagram = false
}
}
let listB = bCharacters.filter { !aCharacters.contains($0) }
for i in 0 ..< listB.count {
if !replacementRequiredWords.contains(listB[i]) {
count = count + 1
replacementRequiredWords.append(listB[i])
isAnagram = false
}
}
}else{
//cant be an anagram
count = -1
}
return (isAnagram,count,replacementRequiredWords)
}
STEP 2 :- Make two Input Strings for test
// Input Strings
var a = "aeb"
var b = "abs"
STEP 3:- Print results :-
print("isAnagram : \(isAnagram(a: a, b: b).0)")
print("number of count require to change strings in anagram : \(isAnagram(a: a, b: b).1)")//-1 will come in case of cant be a Anagram
print("list of Characters needs to be change : \(isAnagram(a: a, b: b).2)")
Results of above exercise:-
isAnagram : false
number of count require to change strings in anagram : 2
list of Characters needs to be change : ["e", "s"]
Hope this 10 minutes exercise will give some support to my Swift
family for solving Anagram related problems easily. :)
We can use dictionary to construct a new data structure container. Then compare the value by key/character of the string.
func anagram(str1: String, str2 : String) -> Bool {
var dict1 = [Character: Int]()
var dict2 = [Character:Int]()
for i in str1 {
if let count = dict1[i] {
dict1[i] = count + 1
} else {
dict1[i] = 1
}
}
for j in str2 {
if let count = dict2[j] {
dict2[j] = count + 1
} else {
dict2[j] = 1
}
}
return dict1 == dict2 ? true : false
}
// input -> "anna", "aann"
// The count will look like:
// ["a": 2, "n": 2] & ["a": 2, "n": 2]
// then return true
Another easy that I just realise doing an Anagram function in Swift 5.X
func checkForAnagram(firstString firstString: String, secondString: String) -> Bool {
return !firstString.isEmpty && firstString.sorted() == secondString.sorted()
}
class Solution {
func isAnagram(_ s: String, _ t: String) -> Bool {
guard s.count == t.count else { return false }
let dictS = s.reduce(into: [Character: Int]()) { $0[$1, default: 0] += 1 }
let dictT = t.reduce(into: [Character: Int]()) { $0[$1, default: 0] += 1 }
for letter in s {
if let count = dictS[letter] {
guard count == dictT[letter] else { return false }
}
}
return true
}
}
Check two strings are anagram using inout method in Swift
func checkAnagramString(str1: inout String, str2: inout String)-> Bool{
var result:Bool = false
str1 = str1.lowercased().trimmingCharacters(in: .whitespace)
str2 = str2.lowercased().trimmingCharacters(in: .whitespaces)
if (str1.count != str2.count) {
return result
}
for c in str1 {
if str2.contains(c){
result = true
}
else{
result = false
return result
}
}
return result
}
Call function to check strings are anagram or not
var str1 = "tommarvoloriddle"
var str2 = "iamlordvoldemort"
print(checkAnagramString(str1: &str1, str2: &str2)) //Output = true.
func isAnagram(word1: String, word2: String) -> Bool {
let set1 = Set(word1)
let set2 = Set(word2)
return set1 == set2
}
or
func isAnagram(word1: String,word2: String) -> Bool {
return word1.lowercased().sorted() == word2.lowercased().sorted()
}

How to make computer generate predefined set of numbers in Swift?

I want to make the computer generate predefined set of numbers one-by-one. How is it possible in Swift? Is it possible using arrays?
For example: I want to generate [1,2,3,4] in that same order one-by-one. By generate I mean to show up like how random numbers show up when you type in arcrandom_uniform().
Example:
var randomNumber = [1,2,3,4,5]
var guessInt = guess.text.toInt()
Then when I type ..
if Int(randomNumber) == guessInt {
//conditions
}
The error shows as : Cannot assgn to the result of ths expresson
Sometimes I get the error as Int' is not convertible to '[Int]' swift
The code won't work! Help ?
Here's the code for #David Skrundz :
` #IBAction func guessButton(sender: AnyObject) {
var randomNumber = [1,2,3,4,7,8,9,5]
var guessInt = guess.text.toInt()
func generator() -> () -> Int {
var currentIndex = 0
let array = Array(1...5)
func generate() -> Int {
let value = array[currentIndex++]
if currentIndex >= array.count {
currentIndex = 0
}
return value
}
return generate
}
let gen = generator()
gen() // Returns 1
gen() // Returns 2
gen() // Returns 3
gen() // Returns 4
gen() // Returns 1
let answer = gen()
if answer == guessInt {
resultLabel.text = "Bingoo..! "}
else {
resultLabel.text = "Oh such a bad guesser! It was a \(answer)"
}
println(answer)
}
`
Any idea how to fix this code the problem mentioned below ! ? Please !
You may want the range operator:
for index in 1...5 {
println("\(index)")
}
If you want to generate the next element in a repeating sequence, you could use
func generator() -> () -> Int {
var currentIndex = 0
let array = Array(1...4)
func generate() -> Int {
let value = array[currentIndex++]
if currentIndex >= array.count {
currentIndex = 0
}
return value
}
return generate
}
And to use it:
let gen = generator()
gen() // Returns 1
gen() // Returns 2
gen() // Returns 3
gen() // Returns 4
gen() // Returns 1

Resources