Trouble finding the correct syntax creating vars in objects - arrays

Up until now I have been creating var inside the classes I made. e.g.
var backpack:Array = new Array("food", "water");
I want to create objects dynamically now like:
player = {};
player.backpack = ("food", "water"); // not the right syntax
OR
player = {backpack:Array = new Array("food", "water")} // not right either.
Any help? Thanks in advance. I can do this with simple vars like int, but can't find the answer to arrays.

ActionScript's generic object properties don't have any variable type associated with them. You assign them one of the following ways.
Example 1
player = {backpack: new Array("food", "water")};
Example 2
player.backpack = new Array("food", "water");
Example 3
player["backpack"] = new Array("food", "water");

You can use square brackets to define literal arrays. Not only is it shorter, but it's also faster (see this post).
The correct syntax for your two examples are
player = {};
player.backpack = ["food", "water"];
and
player = {backpack: ["food", "water"]};
Also, if you find it easier, you can use it in the first line of code you wrote.
var backpack:Array = ["food", "water"];

Related

Look for coincidences in two arrays and create another one without the items that are repeated

I am creating an app that gives rewards to the users, so they can obtain randomly complements to their avatars. I have a list of items that they can win and another list of items that they already have. My problem is that I don't know how to look for a match between the two arrays and create another without the ones that they already have.
var availableAvatar =['Csimple','Calien','Ccosmonaut','CgreenAereal','ChappyBirthday']
var userAvatars=['Ccosmonaut','ChappyBirthday']
I tried with the filter method but it creates an array of the matches and I don't know how to do it the other way.
What I need:
var possibleAward=['Csimple','Calien','CgreenAereal']
var random = avatarP[Math.floor(Math.random() * possibleAward.length)];
Thank you very much.
The array filter function is perfect for this:
var availableAvatars = ['Csimple','Calien','Ccosmonaut','CgreenAereal','ChappyBirthday']
var userAvatars = ['Ccosmonaut','ChappyBirthday']
var possibleAvatars = availableAvatars.filter(x => !userAvatars.includes(x));
var randomAvatar = possibleAvatars[Math.floor(Math.random() * possibleAvatars.length)];
console.log(possibleAvatars);
console.log(randomAvatar);
var availableAvatar =['Csimple','Calien','Ccosmonaut','CgreenAereal','ChappyBirthday']
var userAvatars=['Ccosmonaut','ChappyBirthday']
var possibleRewards = availableAvatar.filter(element => {
return !userAvatars.includes(element);
});
console.log(possibleRewards);

Remove random item from array and push to new array

Thank you in advance! I'm new to coding and learning how to deal with Arrays. I am trying to remove random items from an array (deck of cards), and populate a new array (called hand). The problem I always seem to have with arrays is taking the results of one and creating a new function/array/ etc.. Currently, I am outputting 2 separate arrays and I can't seem to push them into one.
let deck = ["dA","dQ","dK","dJ","d10","d09","d08",
"d07","d06","d05","d04","d03","d02","hA","hQ","hK",
"hJ","h10","h09","h08","h07","h06","h05","h04","h03"];
var hand = deck.splice(Math.floor(Math.random()*deck.length),1);
console.log(hand)
var hand = deck.splice(Math.floor(Math.random()*deck.length),1);
console.log(hand);
In your code, just you need to push the value returned from splice method rather than directly assigning it.
By this way every time a new value that gets deleted and will be added to the new array called hand. Hope this helps. :-)
let deck = ["dA","dQ","dK","dJ","d10","d09","d08",
"d07","d06","d05","d04","d03","d02","hA","hQ","hK",
"hJ","h10","h09","h08","h07","h06","h05","h04","h03"];
var hand = [];
const getSelectedCard = () => deck.splice(Math.floor(Math.random()*deck.length),1)
let selectedCard = getSelectedCard();
hand.push(...selectedCard) //or hand.push(selectedCard[0])
console.log(hand);
selectedCard = getSelectedCard();
hand.push(...selectedCard)
console.log(hand);

Modifying an array of dictionaries in Swift

I’m new to Swift and have been having some troubles figuring out some aspects of Arrays and Dictionaries.
I have an array of dictionaries, for which I have used Type Aliases - e.g.
typealias myDicts = Dictionary<String, Double>
var myArray : [myDicts] = [
["id":0,
"lat”:55.555555,
"lng”:-55.555555,
"distance":0],
["id":1,
"lat": 44.444444,
"lng”:-44.444444,
"distance":0]
]
I then want to iterate through the dictionaries in the array and change the “distance” key value. I did it like this:
for dict:myDicts in myArray {
dict["distance"] = 5
}
Or even specifically making sure 5 is a double with many different approaches including e.g.
for dict:myDicts in myArray {
let numberFive : Double = 5
dict["distance"] = numberFive
}
All my attempts cause an error:
#lvalue $T5' is not identical to '(String, Double)
It seems to be acting as if the Dictionaries inside were immutable “let” rather than “var”. So I randomly tried this:
for (var dict:myDicts) in myArray {
dict["distance"] = 5
}
This removes the error and the key is indeed assigned 5 within the for loop, but this doesn't seem to actually modify the array itself in the long run. What am I doing wrong?
The implicitly declared variable in a for-in loop in Swift is constant by default (let), that's why you can't modify it directly in the loop.
The for-in documentation has this:
for index in 1...5 {
println("\(index) times 5 is \(index * 5)")
}
In the example above, index is a constant whose value is automatically
set at the start of each iteration of the loop. As such, it does not
have to be declared before it is used. It is implicitly declared
simply by its inclusion in the loop declaration, without the need for
a let declaration keyword.
As you've discovered, you can make it a variable by explicitly declaring it with var. However, in this case, you're trying to modify a dictionary which is a struct and, therefore, a value type and it is copied on assignment. When you do dict["distance"] = 5 you're actually modifying a copy of the dictionary and not the original stored in the array.
You can still modify the dictionary in the array, you just have to do it directly by looping over the array by index:
for index in 0..<myArray.count {
myArray[index]["distance"] = 5
}
This way, you're sure to by modifying the original dictionary instead of a copy of it.
That being said, #matt's suggestion to use a custom class is usually the best route to take.
You're not doing anything wrong. That's how Swift works. You have two options:
Use NSMutableDictionary rather than a Swift dictionary.
Use a custom class instead of a dictionary. In a way this is a better solution anyway because it's what you should have been doing all along in a situation where all the dictionaries have the same structure.
The "custom class" I'm talking about would be a mere "value class", a bundle of properties. This was kind of a pain to make in Objective-C, but in Swift it's trivial, so I now do this a lot. The thing is that you can stick the class definition for your custom class anywhere; it doesn't need a file of its own, and of course in Swift you don't have the interface/implementation foo to grapple with, let alone memory management and other stuff. So this is just a few lines of code that you can stick right in with the code you've already got.
Here's an example from my own code:
class Model {
var task : NSURLSessionTask!
var im : UIImage!
var text : String!
var picurl : String!
}
We then have an array of Model and away we go.
So, in your example:
class MyDict : NSObject {
var id = 0.0
var lat = 0.0
var lng = 0.0
var distance = 0.0
}
var myArray = [MyDict]()
let d1 = MyDict()
d1.id = 0
d1.lat = 55.55
d1.lng = -55.55
d1.distance = 0
let d2 = MyDict()
d2.id = 0
d2.lat = 44.44
d2.lng = -44.44
d2.distance = 0
myArray = [d1,d2]
// now we come to the actual heart of the matter
for d in myArray {
d.distance = 5
}
println(myArray[0].distance) // it worked
println(myArray[1].distance) // it worked
Yes, the dictionary retrieved in the loop is immutable, hence you cannot change.
I'm afraid your last attempt just creates a mutable copy of it.
One possible workaround is to use NSMutableDictionary:
typealias myDicts = NSMutableDictionary
Have a class wrapper for the Swift dictionary or array.
class MyDictionary: NSObject {
var data : Dictionary<String,Any>!
init(_ data: Dictionary<String,Any>) {
self.data = data
}}
MyDictionary.data

Array Declaration in CFScript

Please consider the following documentation:
http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=CFScript_11.html#1161053
I'm studying the description of following code:
<cfscript>
//Set the variables
acceptedApplicants[1] = "Cora Cardozo";
acceptedApplicants[2] = "Betty Bethone";
acceptedApplicants[3] = "Albert Albertson";
rejectedApplicants[1] = "Erma Erp";
rejectedApplicants[2] = "David Dalhousie";
rejectedApplicants[3] = "Franny Farkle";
applicants.accepted=acceptedApplicants;
applicants.rejected=rejectedApplicants;
rejectCode=StructNew();
rejectCode["David Dalhousie"] = "score";
rejectCode["Franny Farkle"] = "too late";
The description says that, "Creates two one-dimensional arrays, one with the accepted applicants and another with the rejected applicants. "
I'm new to ColdFusion and I don't see any array declaration using the array keyword in the above code just like the following doc:
http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=arrayStruct_03.html#1121128
Please explain.
You need to initialize your acceptedApplicants and rejectedApplicants arrays
There should be
acceptedApplicants = [];
rejectedApplicants= [];
somewhere above in the code. Like Peter said, if this is in a function make sure you var those variables.

Is there a way to convert a struct into an array without using a loop?

I'm curious, is there another way to convert a struct into an array in Coldfusion without looping over it? I know it can be done this way if we use a for in loop:
local.array = [];
for (local.value in local.struct)
{
arrayAppend(local.array, local.value);
}
Does StructKeyArray suit your requirements?
Description
Finds the keys in a ColdFusion
structure.
If you are trying to maintain order in your structure you could always use a Java LinkedHashMap like so:
cfmlLinkedMap = createObject("Java", "java.util.LinkedHashMap").init();
cfmlLinkedMap["a"] = "Apple";
cfmlLinkedMap["b"] = "Banana";
cfmlLinkedMap["c"] = "Carrot";
for(key in cfmlLinkedMap){
writedump(cfmlLinkedMap[key]);
}
You could also do the same thing in a more "java" way not sure why you'd want to but its always an option:
//no need to init
linkedMap = createObject("Java", "java.util.LinkedHashMap");
//java way
linkedMap.put("d","Dragonfruit");
linkedMap.put("e","Eggplant");
linkedMap.put("f","Fig");
//loop through values
iterator = linkedMap.entrySet().iterator();
while(iterator.hasNext()){
writedump(iterator.next().value);
}
//or
//loop through keys
iterator = linkedMap.keySet().iterator();
while(iterator.hasNext()){
writedump(linkedMap.get(iterator.next()));
}
Just remember that the keys are case SeNsItIvE!
In Coldfusion 10 or Railo 4, if you want an array of values (instead of keys), you can use the Underscore.cfc library like so:
_ = new Underscore();// instantiate the library
valueArray = _.toArray({first: 'one', second: 'two'});// returns: ['one','two']
Note: Coldfusion structures are unordered, so you are not guaranteed to have any specific order for the values in the resulting array.
(Disclaimer: I wrote Underscore.cfc)

Resources