Explaining nested arrays to a programmer [closed] - arrays

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

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.

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

unsure of the best data type to use

I am creating a Sudoku project in vb.net, to such an end I need to store a list of all the possibilities for each square where the squares are indexed by one number. for example the computer needs to know that for square [8] the numbers {1,3,5,9} are possible etc... I began by using a jagged array however there is no apparent 'remove' method which needs to be called a lot. this makes my code looks ugly with all the redim statements in it and so I was curious as to whether a list or arraylist would be best suited to my purposes? I have discovered arraylists have a remove method but I have also read that array lists are all but deprecated and i want to know if there is a nicer solution to this.

AS3 randomizing an array and comparing it to a string

So, I am a basic programmer in flash and this weekend I have to make a small mini game. This is where I get confused...I have 1 movieclip which has 5 labels ( each showing a different shape). I also have a dynamic text field which I have text or (a string) that will need to match the movieclip. Meaning, if the text displays circle, and the shape is circle, if you click the screen you win. if they dont match, you lose. So I am asking this in order to find out, how to create 2 arrays, randomize them then compare the value. I know how to set everything on timers and give scores, I just cant get figure this part out. AS3 and I are having a bad day. Any ideas, even pseudo code helps...or just a flow , something please ! lol thanks in advance
Regarding randomizing an array, have a look at this elaborate article at Activetuts, which specifically aims at Actionscript. It provides documented code with clear illustrations and tips. You could also check out the Fisher-Yates shuffle for some pseudo-code.
I don't quite get your question with regards to comparing the strings.. In AS3, you can use == to see if the strings are equal.

ANTLR and arrays

I have question relating to implementation of arrays with Java+ANTLR combo. (I'm mainly talking about java/c style arrays).
So basically I'm asking how do you implement such feature, if there is such example already available or if someone could point me to anything that may point to solve it.
On other hand, I've searched a bit how would possible solution be. Main problem that I see
is that user may create arrays of various dimensions, even go crazy if he or she wants (like creating 5 dimension arrays or worse).
While grammar for something like this is fairly simple, like
new ID (INT (',' INT)* )
back end really gets involved a bit. As I said, user may input any number of dimensions, so array dimensions should be dynamically created. (at least as I see it, maybe I'm over complicating things?)
After searching I did found something that pretty much solves this problem perfectly, here is link to the question:
Is it possible to dynamically build a multi-dimensional array in Java?
Of course, my question is, is this viable example, it is a bit (to say at least), complicated? Is there more elegant solution to it?
Having that in mind, I was thinking maybe answer might be in the grounds of somehow transforming multidimensions
into more linear structure ? Could something like that be useful ? Simple search on stackoverflow pointed many solutions
to this, like:
Algorithm to convert a multi-dimensional array to a one-dimensional array
Would it be worth to search in that direction ?
Now, at the end, having in mind that arrays are really common feature in many languages, I must find it surprising that after searching ANTLR mailing list there is no similar question, which as I previously said leads me to believe that I'm maybe over complicating things ? (Unless I really suck at search?) I would really appreciate feedback.
Your syntax, if I'm not mistaken, corresponds to something like
new char 4,5,6,7
which is kind of strange. I expect that you really meant
new char[4,5,6,7]
However from a purely syntactic point of view, there's no reason not to just store the indices in an array and let the semantic analysis pass worry about it.

Resources