How to efficiently get a collection that contains multiple nested collections - arrays

Title might not be the best, an improvement would be much appreciated!
What i mean is actually very simple question:
Say i have a School class containing an array of Students that has an array of Notebooks, and i want to refer all the Notebooks in my School
public class School{
students: Student[];
}
public class Student{
notebooks: Notebook[]
}
How should i refer to all of the Notebooks in my school?
Looking for a more efficient way from saving all the Notebooks in a separate array achieved with a for loop..
Thanks in advance :)

It all depends on what you want to do with the output or each individual notebook? This function closely replicates to for loops without all the boilerplate.
school.students.forEach(function(student) {
student.notebooks.forEach(function(notebook) {
doSomethingWithNotebook(notebook);
});
});
// this returns all notebooks for all students and puts it into a single (flat) array
var allNotebooks = school.students.reduce(function(collection, student) {
return collection.concat(sudent.notebooks);
}, []);
// now you can do things like filter out only New notebooks
var newNotebooks = allNotebooks.filter(notebook => notebook.isNew);

Conceptually, my reflex would be to look for something like an n-dimensional array/matrix, think
myMatrix[ [school][student][notebook[]] ]
(but with valid syntax),
and then figure out how to pull myMatrix[[anything][anything][Notbooks[]]].
This would end up avoiding the for loop, but anything that's going to let you select all of the 3nested elements I'm pretty dang sure is going to be just as complex with those elements stored nested or not.
Not a definitive answer per se, but without more details on what you need, the best I can do is offer up avenues of thought.

Related

FireStore and maps/arrays, document-list to array in Kotlin

I've finally started to understand a lot of info regarding FireStore, but I'm wondering if I can get some assistance.
If I had a setup similar to or like this:
          races
                Android
                      name: Android
                      size: medium
                       stats          <---- this is the map
                                str: 10
                                sex: 12.... (more values)
How would I parse this? I am looking to make specific TextViews apply values found in the database so that I can simply update the database and my app will populate those values so that hard coding and code updating won't be nearly as troublesome in the future.
I currently use something like this:
val androidRef = db.collection("races").document("Android")
androidRef.get().addOnSuccessListener { document ->
if (document != null) {
oneOfTheTextViews.text = document.getString("str")
} else {
}
The issue is currently I can only seem to access from collection (races) / document (android) / then a single field (I have "str" set as a single field, not part of a map or array)
What would the best practice be to do this? Should I not nest them at all? And if I can reference said nesting/mapping/array, what functions need to be called? (To be clear, I am not asking only whether or not it is possible - the reference guides and documents allude to such - but what property/class/method/etc needs to be called in order to access only one of those values or point to one of those values?).
Second question: Is there a way to get a list of document names? If I have several races, and simply want to make a spinner or recycler view based on document names as part of a collection, can I read that to the app?
What would the best practice be to do this?
If you want to get the value of your str property which is nested within your stats map, please change the following line of code:
oneOfTheTextViews.text = document.getString("str")
to
oneOfTheTextViews.text = document.getString("stats.str")
If your str property is a number and not a String, then instead of the above line of code please use this one:
oneOfTheTextViews.text = document.getLong("stats.str")
Should I not nest them at all?
No, you can nest as many properties as you want within a Map.
Is there a way to get a list of document names?
Yes, simply iterate the collection and get the document ids using getId() function.

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.

Ruby: Hash, Arrays and Objects for storage information

I am learning Ruby, reading few books, tutorials, foruns and so one... so, I am brand new to this.
I am trying to develop a stock system so I can learn doing.
My questions are the following:
I created the following to store transactions: (just few parts of the code)
transactions.push type: "BUY", date: Date.strptime(date.to_s, '%d/%m/%Y'), quantity: quantity, price: price.to_money(:BRL), fees: fees.to_money(:BRL)
And one colleague here suggested to create a Transaction class to store this.
So, for the next storage information that I had, I did:
#dividends_from_stock << DividendsFromStock.new(row["Approved"], row["Value"], row["Type"], row["Last Day With"], row["Payment Day"])
Now, FIRST question: which way is better? Hash in Array or Object in Array? And why?
This #dividends_from_stock is returned by the method 'dividends'.
I want to find all the dividends that were paid above a specific date:
puts ciel3.dividends.find_all {|dividend| Date.parse(dividend.last_day_with) > Date.parse('12/05/2014')}
I get the following:
#<DividendsFromStock:0x2785e60>
#<DividendsFromStock:0x2785410>
#<DividendsFromStock:0x2784a68>
#<DividendsFromStock:0x27840c0>
#<DividendsFromStock:0x1ec91f8>
#<DividendsFromStock:0x2797ce0>
#<DividendsFromStock:0x2797338>
#<DividendsFromStock:0x2796990>
Ok with this I am able to spot (I think) all the objects that has date higher than the 12/05/2014. But (SECOND question) how can I get the information regarding the 'value' (or other information) stored inside the objects?
Generally it is always better to define classes. Classes have names. They will help you understand what is going on when your program gets big. You can always see the class of each variable like this: var.class. If you use hashes everywhere, you will be confused because these calls will always return Hash. But if you define classes for things, you will see your class names.
Define methods in your classes that return the information you need. If you define a method called to_s, Ruby will call it behind the scenes on the object when you print it or use it in an interpolation (puts "Some #{var} here").
You probably want a first-class model of some kind to represent the concept of a trade/transaction and a list of transactions that serves as a ledger.
I'd advise steering closer to a database for this instead of manipulating toy objects in memory. Sequel can be a pretty simple ORM if used minimally, but ActiveRecord is often a lot more beginner friendly and has fewer sharp edges.
Using naked hashes or arrays is good for prototyping and seeing if something works in principle. Beyond that it's important to give things proper classes so you can relate them properly and start to refine how these things fit together.
I'd even start with TransactionHistory being a class derived from Array where you get all that functionality for free, then can go and add on custom things as necessary.
For example, you have a pretty gnarly interface to DividendsFromStock which could be cleaned up by having that format of row be accepted to the initialize function as-is.
Don't forget to write a to_s or inspect method for any custom classes you want to be able to print or have a look at. These are usually super simple to write and come in very handy when debugging.
thank you!
I will answer my question, based on the information provided by tadman and Ilya Vassilevsky (and also B. Seven).
1- It is better to create a class, and the objects. It will help me organize my code, and debug. Localize who is who and doing what. Also seems better to use with DB.
2- I am a little bit shamed with my question after figure out the solution. It is far simpler than I was thinking. Just needed two steps:
willpay = ciel3.dividends.find_all {|dividend| Date.parse(dividend.last_day_with) > Date.parse('10/09/2015')}
willpay.each do |dividend|
puts "#{ciel3.code} has approved #{dividend.type} on #{dividend.approved} and will pay by #{dividend.payment_day} the value of #{dividend.value.format} per share, for those that had the asset on #{dividend.last_day_with}"
puts
end

Arrays in swift

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
}

How to effectively garbage collect in AS3

I have a flash game that I'm building where I have an array keeping track of a bunch of power ups on the screen. When the player goes an grabs one it needs to disappear from the screen (which is easy) but it also needs to be removed from the array so that collision detection loops don't become really cumbersome. I tried using splice, but I keep get null reference errors, here's the relevant code.
public function collect():void {
try {
Main.powerUps.splice(index, 1);
stage.removeChild(this);
}catch (e:Error) {
trace("Error in splice");
}
}
}
Then when I create my PowerUp object I pass it a parameter that gets assigned to index which is the length of the array of Power Ups at the time. Can anyone see what's wrong with this code or (preferably) provide a more elegant solution? Thanks in advance for any help.
Elegant solution: use indexOf() and splice() together!
var index:int = Main.powerUps.indexOf( powerup );
Main.powerUps.splice(index, 1);
Where powerup is a reference to the object stored within the array Main.powerUps.
I also created a little class a while back that may be useful to you:
https://github.com/MartyWallace/Lotus/blob/master/Lotus/lotus/utils/Set.as
It has a .remove() method so you can just do:
powerUps.remove(powerup);

Resources