AS3: Array Guidance - arrays

Ok so I'll start off with what I am trying to do here with an Array. So I have a grid of 1-59, Now the user gets to pick 5 numbers. When the user picks a number it goes into a box in the top corner of the screen. So what I am trying to make an Array for is a user selects a number it goes into the first box then the second number goes into the second one and so on.
I am still new to AS3 and I have been reading about Arrays, but I'm still stuck on how to do this or even start it. Thanks for the help guys.

Well, you know you need five elements in the array, so:
private var m_arr:Array = new Array(5);
That'll get you an array with five elements, which can be filled later.
Next, it sounds like you need to keep track of which number gets picked first, which number gets picked second, and so on. So let's make a place-holder and initialize it to 0:
private var m_iNextElement:int = 0;
Then whenever they select a number, just say:
m_arr[m_iNextElement] = theNumber;
m_iNextElement++;
As Fygo already mentioned, you could just do this instead:
private var m_arr:Array = new Array();
.
.
.
m_arr.push(number1);
.
.
.
m_arr.push(number2); // and so on
Whichever is better depends on the situation. Last, you need to find some way to tie each element of the array to a graphical element of some sort. There are many ways you could do this, but if you're using MXML, you could consider making the array bindable:
[Bindable]
private var m_arr:Array = new Array(5);
Then you could have in the MXML:
<local:Box id="box1" text="{m_arr[0]}" />
<local:Box id="box2" text="{m_arr[1]}" /> <!-- etc. -->

var nums:Array = [];
//when the user picks whatever number, you call:
nums.push(the_number_that_the_user_selected);
Is that all you wanted to achieve?

Actionscript offers your basic index array [] and associative array {} as well as some fancier ones like vector. It sounds like you simply need to do something with an index array.
Check out this tutorial, it's all about shuffling arrays. http://code.tutsplus.com/tutorials/quick-tip-how-to-randomly-shuffle-an-array-in-as3--active-8776

Related

How can I change an Element in an array, that contains a specific String?

As it is said in the title I could use some help regarding a problem I have with my App.
My App scans a Barcode and offers to safe this barcode in a table together with a second String that can be put in which describes the number of times you want to save this barcode.
The customInit of the cell displays this as the barcode on the left and a grey number on the right representing the count. All of this information is saved in an array of form list=["972537657, 12"; ...]
My last functionality I want to implement is to have a function check for a maybe already existing barcode in the table and if there is instead of inserting a new row with the same barcode and a different number I want my app to just add the number I put in , to the number of the already existing table element with this specific barcode.
My problem: The logic in this works fine ; if there is an already existing element execute this function if not just insert a new row with the input data.
But I Have no idea how to tell the app what to change and how I can access this element of the array.
Maybe someone has an idea (I can also add some of my code if someone would like to inspect my problem further)
First, find the index of the string your looking for, then remove it and insert it at the index.
let arr:Array = ["a","b","c"]
let indexOfA = arr.index(of: "a")
arr.remove(at: indexOfA)
arr.insert("YourString", at: indexOfA)
if you only care about the duplication, why don't use Set instead of Array.
var barcode:Set = ["972537657","972537651","972537653"]
let result = barcode.insert("972537651")
if result.inserted {
print("insert")
}else {
print("duplication")
}

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

Remove a Movieclip from an Array

I'm very new to ActionScript 3.0, so be gentle. :P
I'm making a simple 'custom gun' program where you can cycle through the different parts of the weapon to give it a unique appearance. For example, you have the 'barrel' and the magazine'. Each part is a movieclip with frames for the different options.
Parent Movie Clip: Barrel
Frames within are labeled, each with an MC.
Each MC in there has 4 layers labeled "Paint, Details, Metal, Light".
I have an array of the current parts:
var paintList:Array = new Array (Base.Paint, Bar.BarStandard.Paint, Mag.MagStandard.Paint /*, etc.*/);
Now what I need is to remove a specific piece from that array. So for the above example, how would I just remove the Bar.BarStandard.Paint and add instead Bar.BarExtended.Paint?
Hopefully this makes sense and someone can help! :C
When working with arrays and removing values from within arrays you use splice
Using splice;
arrayName.splice(indexValue, deleteCount)
arrayName you replace with the name of your array
indexValue you replace with the position that the value you want to remove from the array falls
deleteCount is the amount of values you want to delete
Example with your code;
var paintList:Array = new Array (Base.Paint, Bar.BarStandard.Paint, Mag.MagStandard.Paint, etc.);
The value you want to replace is the 2nd value, therefore
paintList.splice(2,1)
And to add another value to that position.
arrayName[indexNumber] = newValue;
Again with your code;
paintList[2] = Bar.BarExtended.Paint;

How can I create arrays within a loop (within another loop) and pass them back out in Javascript?

I'm using Google Docs Spreadsheet API to keep track of a competition between some of my friends. I have some big ideas, but I'm stumped right now. I'm trying to create 20 different arrays inside of loops (see below) and then evaluate each one outside of the loop, and I really don't want to write 20 "if...then" statements.
NOTE: the following SUMMARY may or may not help you answer my question. You might want to skip down to the code, then read this if you need it :)
Summary of the program: Each player assigns point values in favor of one possible outcome of a set of binary-outcome events. As the events happen, players either gain the points assigned if their outcome occurs, or gain no points if the opposite outcome occurs. My goal is to 1) figure out exactly when a player is eliminated, and 2) highlight all remaining events that must be won for them to have a chance at tying for first.
Instead of trying to somehow evaluate all possibilities (5 players picking, 2^16 outcomes... I have zero computer science knowledge, but this seems like an incredibly huge task even for the modern computer) I've come up with an alternate idea. The script loops through each player, against each other opponent. It calculates the maximum number of points a player can score based on their value assignments and the already determined game. For one player and one opponent, it checks the best possible outcome by the player against that opponent, and if there is any opponent he cannot beat, even in the best case, then he is eliminated.
This part is easy-- after the loop runs inside the loop, I just adjust a global variable that I created earlier, and when the outer loop is done, just grab those variables and write them to the sheet.
Unfortunately, this misses the case of where he could have a best case against each individual opponent, but not against multiple opponents at once.
So the next step is what I'm trying to do now. I'm not even sure I can give a good explanation without just showing you the entire spreadsheet w/script, but I'll try. So what I want to do now is calculate the "value" of each event for each player against a given other player. If both player and opponent assigned points in favor of the same event outcome for one event, the event's value is the difference between the picks (positive if player picked higher, negative if lower), and it's the SUM if they picked opposite event outcomes. Now, I do the same thing as before-- take a best-case scenario for a player against a given opponent-- but now I check by how much the player can beat the opponent in a best-case scenario. Then I evaluate the (absolute value of the) event value against this difference, and if it's greater, then the event is a must win (or must lose if the event value is negative). And, if an event is both a "must-win" and a "must lose" event, then the player is eliminated.
The problem is that this second step requires me to create a new array of values for each player-opponent combination, and then do things with the values after they're created.
I realize one approach would be to create 20 different arrays, and throughout the entire loops, keep checking "if (player == "1" && opponent == 2){}" and populate the arrays accordingly, but this seems kind of ridiculous. And more importantly, this entire project is my attempt at learning javascript, so what's the point in using a time-intensive workaround that doesn't teach me anything new?
I'm trying to understand square bracket notation, since it seems to be the answer to my question, but a lot of people are also suggesting that it's impossible to create variable names by concatenating with the value of another variable... so anyway, here's what I'm trying. I'd really appreciate either a fix to my approach, or a better approach.
for (var player=1; player<6; player++){
if(player==1){look up certain columns in the spreadsheet and save them to variables}
//ditto for other players
for(var opponent=1; opponent<6; opponent++){
if(player!=opponent){
if(opponent==1){save more values to variables}
//ditto for other players
for(var row=9; row<24; row++) {
//Now the script goes down each row of an array containing the original
//spreadsheet info, and, based on information determined by the variables
//created above, get values corresponding to the player and opponent.
//So what I'd like to do here is create "array[1,2]==" and then "array[1,3]=="
//and so forth, creating them globally (I think I understand that term by now)
//so I can refer to them outside of the loops later to do some evaluatin'.
}
}}
//get array[1,2]...array[5,4] and do some operations with them.
Thanks for getting through this little novel... really looking forward to your advice and ideas!
How can I create arrays within a loop (within another loop)?
Code update 2
As you said: "i am trying to understand square bracket notation" You may take a look at my new demo and the code:
function getTeam(){
var array = [[1,2,3],[4,5,6],[7,8,9]]; // arrays within arrays
// array myTeam
var myTeam = [[],[],[],[]];
var playerNames = ["John", "Bert", "Dave", "Milton"];
var ages =[];
var weight = 104;
// loop over the team arrayadd each player (name, age and weight) to the team
for (i=0; i < myTeam.length; i++){
// fill the age array in a loop
for (j=0;j<myTeam.length;j++) {
ages[j] = 23 + j;
}
myTeam[i].push([playerNames[i], ages[i], weight]);
}
return myTeam;
}
And pass them back out in Javascript
Could you elaborate on this part?
Update
var valuesOfPlayers=[];
for (var player=1; player<6; player++){
// look up certain columns in the spreadsheet and save them to variables
// you could call a funcntion and return the values you
// collected in an array within an array as in the demo above
valuesOfPlayers[player] = lookupColumnValues(player);
for(var opponent=1; opponent<6; opponent++){
if(player!=opponent){
// save more values to variables
valuesOfPlayers[player] = addValuesToVar(player);
}
for(var row=9; row<24; row++) {
// if you collect the values in your first and second if clause
// what other information do you want to collect
// Please elaborate this part?
}
}}
One workaround:
I could create an array before the execution of the loops.
At the start of each loop, I could push a string literal to the array containing the value of player and opponent.
After the loops are done, I could split the array into multiple arrays, or just evaluate them in one big array using regular expressions.
I'd still rather create new arrays each time-- seems like it is a more universal way of doing this, and learning how would be more educational for me than using this workaround.

Array of Colors error. Bug?

K. I'm getting stuck here.
I'm trying to make an array with different color values.
My problem is that when I do...
teamColor[i] = currentColor... all color values in my array turn into the currentColor.
(I would upload more code, but that would be a massive mess, considering that I have code everywhere with references from movie clips that are as far as 3 layers deep. HOWEVER, this would be irrelevant anyways (probably), because I tested this with color values on my main timeline, without any references to or from anything deeply nested)
I'm GUESSING that this is just some horrible bug, but if it's not (and I hope it isn't), please guide me in what to do to fix this problem.
I would like to add that I tried adding strings in there and that the strings remained their original, intended, value, while the color exhibited the same phenomenon.
[Partially resolved]:
I changed my code by creating separate variables for each color instead of putting the variables into an array (not what I really wanted to do, but it works). My code looks like this:
`
if (teamColor != 0)
{
this["team"+teamColor+"Color"] = new ColorTransform(0,0,0,1,currentColor.redOffset,currentColor.greenOffset,currentColor.blueOffset,0)
teamColor = 0
namebox.addboxes()//function in a movieclip
}`
teamColor is now an int that is changed based on which box a user clicks from a movie clip that has a dynamically generated name, based off of what the variable value in a loop was when it was created. (E.G: 'tempboxname[ttns].name = i;')
teamColor is then equal to that name when the user clicks it.
I have another movieclip with colors in it and the above function is called to check if any teamColor change has occurred, and if it has, act accordingly. (The idea of having teamColor equal to 0 is so that if the user clicks twice, nothing changes. I other conditionals for other colors, all within the same function).
That is how I fixed me code.
It's not what I wanted, because it's not an array (meaning a seemingly infinite number of teamColors, and thus, teams) but it'll do for me. If anyone has any suggestions, feel free to suggest.
I'm no ActionScript wiz, but what it looks like to me is that currentColor is an object that is being passed into the array by reference. This means that all array entries that you assigned currentColor will be pointing at the same currentColor object, not a copy. My advice is to make a copy and then assign that into the array.
It would be much better if you could give me more code to look at. For instance, the loop that contains that code segment would be nice. If I find a different error I'll edit my answer.
here i'm creating and then adding simple 0xRRGGBB color objects into a vector. the color objects are then parsed into 0xRRGGBB hexadecimal strings and traced.
certainly it's not exactly what your looking for, but hopefully it will help you.
var red:uint = 0xFF0000;
var green:uint = 0x00FF00;
var blue:uint = 0x0000FF;
var colors:Vector.<uint> = new Vector.<uint>()
colors.push(red, green, blue);
for each (var color:uint in colors)
{
var output:String = color.toString(16);
while (output.length < 6)
output = "0" + output;
trace("0x" + output.toUpperCase());
}
Output:
//0xFF0000
//0x00FF00
//0x0000FF

Resources