Arrays in swift - arrays

I have very little programming experience and I am new to Swift. I am trying to create a type of poker game and I am not sure how to set the arrays. I need multiple players and each of these players will have multiple variables such as how much is there current bet, did they fold, how much money do they have, etc.
My questions is, I imagine this will be handled with arrays but I am not sure how to handle which player and which variable of that player I am executing commands on at any one time.
Any suggestions?

You'll probably get down voted, because things like this can be found easily on the web. Nevertheless:
You probably would want to use classes instead of arrays. Especially in swift where:
An array stores values of the same type in an ordered list
Look up for classes or read it at apple's site: class reference
A class looks like:
class Player {
let name = "Pete"
var cardArray = ["1c","1h"] // array of type String. "1c" and "1h" could mean "ace of clubs" and "ace of hearts", pocket ace!
var cardDict = ["clubs": [1], "hearts": [1]] // same as above, but with a dictionary and an array inside to make sure the combination are unique
}

Related

How does Ruby's Combined Comparison Operator work?

First question on stackoverflow :)
I'm going through the Ruby course on Codecademy and I'm stuck on something.
fruits = ["orange", "apple", "banana", "pear", "grapes"]
fruits.sort! {|first, second| second <=> first}
print fruits
I don't know how to phrase this question. On Codecademy the assignment was to set up the array to be displayed in reverse on the console. After some research, I was able to figure it out. I understand how it works and the order to put it in the code not why. I'm aware that "<=>" compares two objects, but how do the items within the array become objects when we don't declare them as such?
Secondly, what is the purpose of writing this code in this way when we could do fruits.sort.reverse?
First question: At various points in its operation the sort method has to compare pairs of objects to see what their relative ordering should be. It does the comparison by applying the block you pass to sort, i.e., {|first, second| second <=> first}. Not sure what you mean by "how do the items within the array become objects when we don't declare them as such?". All data in ruby is an object, so there's no declaration or conversion needed given that all variables are object references.
Second question: Yes, you could do fruits.sort.reverse, but that would require additional work after the sort to do the reverse operation. Also, reverse can't handle more complex sorting tasks, such as sorting people by multiple criteria such as gender & last name, or hair color, height, and weight. Writing your own comparator can handle quite complex orderings.
String literals can be used to create string objects in Ruby, there is no need to use the String class to create the object. The following two are equivalent:
"Hello, world!"
String.new("Hello, world!")
More information can be found here.
Secondly, what is the purpose of writing this code in this way when we could do fruits.sort.reverse?
Please contact Codecademy about this, but I suspect it's for learning more about how <=> works.

Declare array of UIButtons

I want my swift code to create buttons using colors. I know I want to declare array but some of the things I have tried are not working. What I tried below is not working. I have tried to do various forms of wrapping but it did not work. The goal of this code is to not use any storyboards and do everything by code.
var red,blue = UIButton()
One compact way to declare two variables in one line is to use tuple notation:
let (red,blue) = (UIButton(), UIButton())
Perhaps that's what you're asking for. But there is no array in the story; it's hard to see why you mention arrays in the first place.
On the other hand, if you really do want an array as you claim, then it's hard to see what the names red and blue are for, since the elements of an array do not have names (with regard to the array). You could make an array of two new buttons by saying:
let arrayOfTwoButtons = (0..<2).map {_ in UIButton()}

How do I filter an array based on object's property with multiple OR statements

The question was difficult to put into words, but here is my situation. I have several Monster objects in an array called monsters. Each monster has a name property which is a String.
I have a second array called monsterNames, which contains several monster names (as Strings).
I want to be able to filter all the monster objects in monsters array based on whether the individual monster object's name property appears in the monsterNames array.
I have been looking at solutions so far I have only found solutions that filter based on a single condition, which allows me to only filter based on a single monster name in the monsterNames array. Can anybody help me find an efficient solution to this?
You could do something like:
let monsters: [Monster] = ...
let monsterNames: [String] = ...
let filteredMonsters = monsters.filter { monsterNames.contains($0.name) }
This doesn't perform all that well, since it will go over the names array up to n times for each monster, but if your names arrays is small, this won't be a problem.

How do I iterate through one array and move every other element to two new arrays in Swift?

I do realize similar questions have been asked before, I looked at them before seeking help. But they were either not in Swift or too complex for me to decipher. My question is different from How do I shuffle an array in Swift? in that I have already done some of the work, like shuffling. The title was actually different from the question asked, which was "How do I randomize or shuffle the elements within an array in Swift?" I am only interested in iterating the resulting array and I couldn't separate that part from the rest of the code in the answers given for a question that encompassed so much more. That said, there are some great suggestions on that page so I think people like me will benefit from having both pages available. Maybe someone can set up a reciprocal link on that page as I have done here.
Admittedly, I am new to Swift and not a seasoned programmer in any language, but please don't assume I am coming here seeking help without trying to figure it out on my own. I am spending many hours learning the fundamentals of all C based languages and reading the Swift literature at developer.apple.com.
So the question will be more obvious, I and attempting to build the card game War. Thus far I have accomplished constructing the (an array) deck of cards and randomized it (shuffled). I am stuck at looping through the resulting array of 52 objects and assigning (moving) them to the two players hands (two new arrays). I'm not sure how much of my code I should display in order to help me but if you need more, I'll gladly provide it. Please note that this is only an exercise, practice for me to learn how to write complex programs, and some code, like the function to randomize, is not mine, I found it right here at stackoverflow. I'd almost prefer if you didn't just hand me the code that will work, I'm not likely going to learn as much that way, but if providing steps in plain English so I can figure out the syntax is too much trouble, so be it, provide an example, I'm sure I'll get plenty of chances to write/use the syntax later.
One more note, I'm only working in a playground at the moment, when and if I can get all the code working, I'll move to the UI stuff.
Thanks in advance, Rick
/* Skipping past everything I did to get here,
the array (shuffledDeck) has 52 shuffled cards (elements) in it.
The array is NSMutableArray and contains strings like
2Hearts, 5Spades, 14Clubs, etc. Each suit has 14 cards.*/
shuffledDeck
// create vars to hold shuffled hands
var playerOneHand = []
var playerTwoHand = []
/* Started a for loop to assign cards to each hand
but don't know which method(s) is/are best to use
to remove the first or last card and alternately
append (move) it to the (hopefully) initialized
variables playerOneHand and PlayerTwoHand.
Optionally, since the cards are already shuffled,
I could just split the deck using the range method,
whichever is easier. I tried and failed at both ways.*/
var i = 0
for dealtCard in shuffledDeck {
}
var shuffledDeck:[String] = ["2Hearts", "5Spades", "14Clubs", "etc"]
//shuffledDeck will of course be your shuffled deck
var playerOneHand:[String] = []
var playerTwoHand:[String] = []
for (index, cardString) in enumerate(shuffledDeck) {
if index % 2 == 0 {
playerOneHand.append(cardString)
}else{
playerTwoHand.append(cardString)
}
}
I’m looping through every item in the shuffledDeck, but with that I use the index of the array to get a number. I use this number to see if that number devided by 2 is equal to 0 (the number is even) or not (uneven) if a number is even, I get the item that is in the array at the given index and add that item to the hand of player one. If the index is uneven I add the item to the second player’s hand. This means the first item goed to player one’s hand, the second item goes to the hand of the second player. the third Item goes back to the first player and so on.
As mentioned by Martin R you can use the range method to assign the first half of the deck to the first player and the second to the second player as follow:
let cards:[String] = ["2♦️","3♦️","4♦️","5♦️","6♦️","7♦️","8♦️","9♦️","T♦️","J♦️","Q♦️","K♦️","A♦️","2♠️","3♠️","4♠️","5♠️","6♠️","7♠️","8♠️","9♠️","T♠️","J♠️","Q♠️","K♠️","A♠️","2♥️","3♥️","4♥️","5♥️","6♥️","7♥️","8♥️","9♥️","T♥️","J♥️","Q♥️","K♥️","A♥️","2♣️","3♣️","4♣️","5♣️","6♣️","7♣️","8♣️","9♣️","T♣️","J♣️","Q♣️","K♣️","A♣️"]
extension Array {
var shuffled:[T] {
var elements = self
for index in 0..<elements.count - 1 {
swap(&elements[index], &elements[Int(arc4random_uniform(UInt32(elements.count - 1 - index))) + index])
}
return elements
}
}
let cardsShuffled = cards.shuffled
let playerOneHand = cardsShuffled[0...25]
let playerTwoHand = cardsShuffled[26...51]
Note: The shuffle extension was created using this answer as reference

Sort ArrayBuffer[A] in scala?

I have an array in Scala with the class ArrayBuffer[Actor], where Actor is a class that implements the Ordered[Actor] trait. How do I sort this array without coding it manually?
I know there is an object called Sorting, but it doesnt seem to work since ArrayBuffer doesn't implement/extend the right classes.
How do I sort ArrayBuffer[A] type arrays?
If you are using Scala 2.8, you could use the sortWith method of the ArrayBuffer[T] class, which is inherited from the SeqLike trait.
The following code snippet sorts an ArrayBuffer[T] object in ascending order:
def ascendingSort[T <% Ordered[T]](xs: ArrayBuffer[T]) = xs.sortWith(_ < _)
Note that this does not mutate the actual ArrayBuffer, but creates a new one with the elements in the right order.
If you are using Scala 2.7, you could use the stableSort method of the Sorting object. This takes the elements of the ArrayBuffer and produces an array of elements sorted in the right order (given by a closure as an argument, ascending as a default).
For example:
val a = new scala.collection.mutable.ArrayBuffer[Int]()
a += 5
a += 2
a += 3
scala.util.Sorting.stableSort(a)
The important question is what do you want to do with the ArrayBuffer. Usually, a Buffer is used internally in different algorithms in order to increase the performance of intermediate results. If you are using it for that, have a look at the ways of sorting the collection you want to return at the end of your algorithm. The Sorting object already provides a way of transforming an ArrayBuffer into a sorted Array.
From the scaladoc of the Buffer class:
Buffers are used to create sequences of elements incrementally
As you are using it with Actors, it might be used for some kind of actor queue - in which case, you might want to have a look at the Queue collection.
Hope it helps,
-- Flaviu Cipcigan
Btw, the Actor class here is my own class used for "Actors" in a world created using my new game engine for scala ("Awesome Game Engine for Scala ~ AGES"), so it has nothing to do with the concurrency actor class. Also, implementations of lists in scala are a jungle, everything is either deprecated or implemented in a lot of different ways...ArrayBuffer works for my need (my need being a variable size array for containing actors).
Hope this clarifies :)

Resources