If I have an array with elements linked to xassets with names like "card1", "card2", etc up to "card100" is there a quicker way to write these elements in the array format without having to write out all 100?
Also if this has been answered already please let me know or link to it. About 2 days into trying to teach myself to program.
Not exactly sure what you're asking but you may want to look at loops - Swift Loops. You can add items to an array in a for loop from 1 to 100.
Is this what you are looking for ?
let cards = Array(1...100).map({"card\($0)"})
Related
I want to create an array that contains the same value repeated for a very large number of times, say 1,000,000.
I was thinking to use something like Array.fill(1000000)(0). However, after reading the documentation for Scala 2.11.8, I found that there is no such members of Array in this version.
Is there any other ways that can create the array without using loop? Thanks in advance for your help.
This will do the trick:
Array.fill[Int](1000000)(0)
Read more here: https://alvinalexander.com/scala/scala-list-class-examples
You can use range to iterate through required length (1000000 times in your case) and then return a default value which is 0 in each iteration as below.
val arr:Array[Int] = (1 to 1000000 map(_ => 0)).toArray
Stream.continually(0).take(1000000).toArray would do that .. but why in the world would you want something like this???
This question already has answers here:
How to copy end of the Array in swift?
(6 answers)
Closed 6 years ago.
Swift's implementation of arrays is throwing me for a loop again! (Haw, haw.) All I want is to take an array of arbitrary length and get a new array (or an array slice) from it that has the first element removed.
Why is this so hard?
I just want to be able to do something like this:
let suffix = someArray.suffixFrom(1)
But I can't figure out how to do this. It seems the closest method I've found requires knowing the length of the array, which I don't know because it's computed inline and I really really hate having to split such a simple concept up into a bunch of variables and lines.
Elaboration:
I have a string split by colons (:) and I just want to create a Set containing all the :-delimited components excluding the first one.
So that a string "one:two:three" would return a set containing ["two", "three"]. Since I can create a Set from an array, all I really need is to get the suffix of the array, but I don't know how many components there are because it's inline:
return Set(attributeName?.componentsSeparatedByString(":").suffixFrom(1))
Why does Swift make this so hard?
Edit: Before a bunch of you suggest it, I'm well aware I could extend the array class to do this myself, but I'm writing a framework and I don't want to do that, and I also don't want to have to write a bloody utility function to do something so darned simple.
The CollectionType.dropFirst(_:) does exactly what you need, with the exact syntax you're looking for.
let suffix = someArray.dropFirst(1)
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
I'm sure others have already asked this, but is it possible to insert an element into the next available index of an array without using a for-loop to find that index first? Almost like a list.add() function but for arrays in C.
no, you will have to loop through the array.
If it's really list functionality you want you could implement a simple linked list instead of using arrays, for example like this: http://www.cprogramming.com/tutorial/c/lesson15.html
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
How have you explained nested arrays to a programmer. I'm thinking someone that has an entry level understanding of programming, but is trying to do more complicated coding.
The array with array works, but they can't quite get their mind around the idea.
Edit: example of a nested array:
array(
'array1' => array(
'key1' => 'val1',
'key2' => 'val2',
),
'array2' => array(
'key1' => 'val1',
'key2' => 'val2',
),
);
Of course, they are usually more complicated than this and maybe that's the problem.
Tell them to think of an array as a list- it helps to give them something less abstract, like a grocery list. Then, a nested array is simply a list of lists.
Maybe I have a todo list, a grocery list, and a wishlist at amazon.com . Now I have a list of all of my lists, and I can look at all of those elements in each list by stepping through them.
A nested array is a set within a set. So, a library has a set of books, a book has a set of chapters. A chapter has a set of paragraphs, a paragraph has a set of sentences. A sentence has a set of words.
For each book in library
For each chapter in book
For each paragraph in chapter
etc...
How have you explained it? It doesn't seem like a big jump for someone that understands one dimensional arrays to be able to grasp the concept that instead of an int or a string that each array element contains another array instead.
Perhaps an analogy comparing directories will help, a one dimensional array would be analogous to a directory that contains a bunch of files, a two-dimensional array to a directory which contains several other directories, each containing a bunch of files, etc.
Draw it.
A variable is a box
1 dimensional array is a row of boxes.
2 dimensional array is a grid of boxes.
3 dimensional array is a cube of boxes.
If they have having trouble with the general concept, don't attempt to visually explain 4 dimensions.
Use a bitmap as an example. In C, you can make a bitmap of an X like this:
int x[5][5] = {
{ 1,0,0,0,1 },
{ 0,1,0,1,0 },
{ 0,0,1,0,0 },
{ 0,1,0,1,0 },
{ 1,0,0,0,1 }
};
Then show them how to use nested for loops to display the bitmap.
Examples always help, and this also gets them to think of nested arrays as multi-dimensional arrays. Actually it's probably better to understand multi-dimensional arrays in a language like C before learning about the "nested" arrays in languages like Python where you can have different levels of nesting in the same array.
Sports can provide appropriate analogies to describe applying nested arrays. A team is an array of people, a competition is an array of teams that play against each other.
However its a case of finding the analogy that clicks with the learner. Find the right analogy and you'll get even the slowest of learners to understand. Just ensure you're analogies are water tight. Like abstractions, they are leaky.
A concrete example is the index at the back of a book. A list of words, each word associated with a list of page numbers.
apples - 1, 2, 3-4
bears - 32-35, 79, 83
cats - 14, 15
If you are looking at C type, non-ragged, arrays, comparing it to numbers, the base 10 part, and there digits might help. Another good source for this same effect would be time as it has a non uniform base 60s = 1m, 60m = 1h, 24h = 1day, 7day = 1week
2 dimensions is easy to explain. Just think of a table. 3 dimensions just think of a cube or other 3d image. 4 dimensions think of a series of images like a movie with the 4th dimension being time.
4+ dimensions is hard to visualize using that model. But think of it as a filing cabinet with another file cabinet inside helps. You open the drawer and out pops a filing cabinet. You find the drawer you want and open that drawer and out pops another filing cabinet....over and over until finally you get your paper.
Perhaps you are explaining it from the context of someone who understands an array of arrays. I would attempt to trick them into realizing that they already understand them by starting at the smallest(read inner array)...and slowly expanding out, giving them plenty of time to ask questions until they are done.
Drawing helps, but you need to give the student in this case some information and go slowly, most programmers I know tend to go to fast and to like to explain things EVEN when the listener no longer is tracking what is being said.
I am a metaphor guy, so I would probably cook something up about a series of boxes with each one numbered, each box then containing a similiar(but much smaller series) also numbered. I would take this to only two levels get understanding and then perhaps talk about 3 dimensions for confirmation. But I would avoid 4 dimensions on the grounds that they may get hung in the idea that there is no such thing as 4 dimensions, or you can't measure time, or other such metaphorical landmines/distractions...cause that's the other problem, programmers tend to be ADD and enjoy getting side tracked.
Also why aren't you using a hash of hashes, much easier to reference. :)
Bottom line, baby steps.
an array is just an object - a thing. everything should be simple to understand once they get that