A few questions about arrays


#1

Just finished stumbling through the Lurkers level in the Desert campaign on Python. I am glad that it taught me about arrays briefly over a couple levels, but even by this point in the desert I still can’t confidently say I’ve mastered or even truly understand how to work arrays.

I went back to the Forest and did the level Wild Horses as well and it helped a bit with the findFriends function. However, I’m honestly not confident I could use that code from scratch if asked to either.

So on to the questions:

  1. I get that the index starts at “0”, but how do I know what indexes there are? or are we defining the index as 0? Example: “enemyIndex = 0”. I’m guessing the latter but I want to be sure it is.

  2. “enemy = enemies[enemyIndex]” I don’t honestly understand this line in the least, well aside from were defining the second half into “enemy”. So how does this line work?

  3. I also noticed that the use of the arrays I’ve seen thus far has had “enemyIndex += 1” at the end of the loop rather than within a part that would only happen unless a condition were met.
    Example:

while enemyIndex < len(enemies):
    enemy = enemies[enemyIndex]
    if enemy.type == 'munchkin':
        while enemy.health > 0:
            hero.attack(enemy)
    enemyIndex += 1
while enemyIndex < len(enemies):

3: continued: Why is this? or rather why isn’t it like when we are incrementally increasing a value? Such as:

if enemy:
    if enemy.health > 0:
        hero.attack(enemy)
    elif enemy.health =< 0:
        edefeated += 1

Just kind of threw it together, sorry if it’s a little sloppy.

4: And any other knowledge or tips that would be good to know about arrays I may not be aware of that could help me understand them better?

Again, any and all help is appreciated.


#2

@Xector64 to answer a few of your questions:

.1. Let us define a variable called enemies and set it equal to the available enemies in the game

enemies = hero.findEnemies()

Now that enemies is defined. We check a property of the array called length. If an array has anything in it then the length will be > 0.

if enemies.length > 0:
    hero.say( "There are " + enemies.length + " enemies here with me in the game!")

To speak directly about the word “index”, I would believe it is correct to say that there really is only one “index”, however there are many “positions” in that index.

define index: an alphabetical list of names, subjects, etc., with references to the places where they occur, typically found at the end of a book.

So in our programming “index” we have a list of numbers. 0,1,2,3 … depending on the number of elements in the array. Again I believe it is correct to ask, “Where in the arrays index is the "thrower" enemy?”

So when we use variables we are actually storing the location in the index. We use the name index as part of the variable name to help us define the purpose behind the variable. For example:

enemies = hero.findEnemies()
enemyIndex = 0
while (enemyIndex < enemies.length):
    if (enemies[ enemyIndex ].type == "thrower" ):
        hero.say("The thrower enemy is at index position " + enemyIndex )
    enemyIndex += 1

The reason why we initialize the variable to 0 is that the arrays first position in the index is zero.



.2. Lets start by saying that we have a classroom full of students and they are all very disorderly. Now what if you could magically make them all line up in a row? This would be similar to the code segment we have in the game called hero.findFriends() it essentially goes out and creates a list of all the ally game characters.

So now that we have them all lined up they are just like the array. Lets say we like counting from left to right, then we can say that the student in the first spot, lets count from 0, is the students[0] student. And so fourth. Well referring to Mark as students[0] will become very odd, especially if we ask him to read out loud from the current chapter on Computer Science.

Imagine it, “students[0] please stand up and read Chapter 2 Arrays starting from how we define them”. Mark will surely feel like less of a person being called students[0]. But Mark is still the first student in our line, he is the one furthest on the left. So even though this isn’t how we would refer to him in real life, in the world of programming it is as valid.

Now lets be a good teacher and choose to create a variable named Mark and set that equal to students[0] because after all they are one in the same person and Mark seems to like the idea of having a variable refer to him that was named after him!

mark = students[0]

Now in our code anywhere we wish to talk about Mark we can use our variable mark. Think about it though, couldn’t we just as easily named the variable student? In this case it refers to a single student and not the entire class list. This is the same as in our game. We are just asking to select 1 enemy from the list of many enemies. An array is a “list” of things.

If you need to, think of the array as a bunch of box cars on a locomotive train. In our case each boxcar only holds one student (or enemy). enemies[0] or enemies[ enemyIndex ] where enemyIndex = 0 both refer to the contents stored in the array at that location. Like box car number 0. Tell me what is in boxcar number 0.



.3. Let me ask you this question, “If you fail to increment the position in the array, then what happens to your logic statement that is looked at that terminates the array?

enemyIndex < len(enemies)

if enemyIndex = 0 and len(enemies) is equal to 10 because there were 10 students in our class. What happens if I never increment enemyIndex ?

0 < 10 is always true and the loop will never end.



.4. If you still have questions please ask I would be glad to further give examples.


#3

@Harry_the_Wanderer Wow that is amazing! Thank you so much, this makes so much more sense now. I can’t say till I’ve learned and used arrays more that I fully understand them yet, but this has definitely gotten me a lot closer to doing so. Had to read this all a couple times to study it further till it all finally sunk in and clicked, but it makes perfect sense now.

1: Though I hadn’t thought of it in that way it does make sense that I am taking available variables and putting them inside the index. As well as it being able to access the if statement so long as the condition of the variable for enemies was “thrower” was true for it’s placement within the defined saved value of the index. (though understanding the code and explaining that line was a whole different kind of battle.)

2: It’s also nice to understand why to use enemies or items rather than enemy or item in defining or using it in functions. Just hadn’t clicked till now that it was going over the list of enemies rather than honing in on a specific target. I also get that the index begins at 0, though I still don’t understand the purpose of it starting at 0. I imagine it is either just how it is, or something I haven’t got to learning yet. Thanks to this information I understand how it works better at least though.

3: Ah, that does make sense, I’ve made a few mistakes and ended up with infinite loops. This being one of the many reasons among why I ended up there.

4: One question does come to mind, but it backtracks to the index starting at 0 quandary. Does this perhaps have something to do with the accessing the last element of an array with “-1”? I haven’t gotten to that part in my learning quite yet, so I haven’t worried too much on the subject, but it does have me curious.

You are a great help, and I appreciate it all very much.


#4

@Xector64 You are welcome, while I have the time, I like to help.

Why start at 0?

  1. Because Edsger W. Dijkstra said so and wise programmers listened (jokingly)
  2. Because if was found to be more efficient
  3. Because it may allow for a more elegant mathematical solution
  4. Because it was found to lower mistakes in the long run
  5. Because the programming language requires it to be so.
  6. Because its all a bunch of Zeros and Ones and Binary starts at Zero

Fun fact LUA starts at 1 !

Here is another resource that talks about 0. I don’t fully like the way everything was said but there are some interesting points, and the author takes another approach if Dijkstra was too difficult.

Why start at 0 is a question that many people ask. Just google “why do we start at zero in programming”, you will have enough reading to take you into next week.


And yes, if we start at 0, we refer to the last index position as `enemies.length - 1`. This is easily seen if you write down numbers on a page. If you start at 1 and count to 10, you will have 10 numbers. Now below this start at 0 and count upwards until you read the number 10 on the first line. The last number in the new sequence is 9 if both rows contain 10 numbers.

Therefore we have " -1 ". We shift the entire sequence by -1 or one place to the left, if we started on the left and wrote numbers in the row going to the right. In truth we could have started with any number, positive or negative, but programmers like things tidy as Dijkstra noted.


If I said Einstein thought it was a good idea, would that help? (joke) In many ways thought, it is like that.

However from a practical standpoint I can see where starting at 1 is just as valid. I have learned over the years to simply accept the notation being used and can work with any convention. This is where code comments are essential.


And of course where would we be without wikipedia:

The section on the Origin is a rather interesting read.


#5

“the subscript [i.e. the index] refers to an offset from the starting position of an array, so the first element has an offset of zero.” (wiki linked above) - neat :slight_smile:


#6

@Harry_the_Wanderer That clears that up. It would make since that it would simplify it in the long run since we don’t have to add any counterbalance for the basic use of arrays if we start the index at 0 rather than 1. Though I must admit I think I prefer the way you explained it over the first article’s explanation. Plus a little humor goes a long ways. Thanks to the article though I now am curious to using multiple arrays in coding but I’m not quite yet there and should probably work my way up to it. After all it is great to get help but if I just keep asking all the questions I get from the answers you give it’ll likely never end.

The origin read was interesting, though I did have to read it a few times before it finally clicked in. Guess that’s what I get for reading it before I’ve even fully woken up. Though it was kind of surprising to learn just how early on this was found, or at least to me it was. I didn’t even know BCPL was a thing till reading this or that there was even a precursor for the C language, I mean I suppose if I had put more thought into it I should of realized there was, but it just never happened.

Honestly I started in Python as a starting point due to what someone else is learning thinking it would be easier to help them understand better if I understood more directly the language she was using. Though I want to learn more than one language in the end. Preferably would like to become efficient in using Python, JavaScript and LUA eventually as well as learning more on HTML5 so I can use that if I have a need to take route with it at some point. It’s just all so exciting to me. Going to take it one thing at a time though, wouldn’t want to overwhelm myself.

Again thanks for everything, always very much appreciated.


#7

@Xector64 Fun fact about computers. In the 18th century if you mentioned that you just got a new computer and pointed to the metal box on your desk, the person who to you just talked to might wonder if Mr. Swift was really telling the truth. They might also gasp in horror wondering where the air holes were and what kind of a person you are for keeping someone locked up in a metal cage without any windows. Or perhaps how savage the tiny creature you caged might be, observing that it was a formidable cage indeed.

Interestingly enough the first computer language might have just been English?
http://www.cciw.com/content/computer_etymology.html

Or perhaps Latin, but it is hard to say when the term would have applied to humans in a way to make sense of a “first language” :slight_smile:


#8

@Harry_the_Wanderer That is a pretty interesting bit of information. Kind of fun to think what someone from that era would do and how they would react to today’s technology in computers and coding. Though I shouldn’t get too caught up in talking about such as last time I did so it got into a conversation of the possible differences there would be if such as the Roman and Greek science and technology would of taken different routes.

As well as a “first language”, but its all still amazing to think on. You seem to know quite a bit of the history behind all of it though. It’s quite impressive.


#9

@Xector64 It would be interesting to think about writing code in latin:

Heros.impetum()

for instance. Or is that now getting too Harry Potterish. lol.

Perhaps we should build a secret language into CC where if you knew latin it would add some cool bonus to your attacks etc. Maybe it could be a language of the ancients taught to the coding wizards that finally reach the Volcano campaign?

What do you think @nick ?

get +1 Ancient Book of Code


#10

@Harry_the_Wanderer would be an interesting concept to say the least, though it does hit that feeling of “Harry Potterish”. Still could be fun though, and an interesting way to learn new things.

Maybe even adding a special level that if you beat it you get a special piece of armor or weapon, like the viking helmet for instance. Different thing on different terms I get, but the concept of it though. Nothing game-breaking, but just something nice to work towards for those that are interested in doing so. I personally like the idea regardless of whether my idea is good or bad though.

More new array issues

Also while here in this thread, I do feel like I may of accidentally skipped over some levels following what levels it was guiding me to do. As I’m now at “The Trials”, and I’ve gotten my array for enemies and mushrooms down, but can’t seem to define them in ways that get him to go after the enemies near him. He will go after one on the right then another cross map while every enemy that he comes in range of just follows and whittles away his health till he dies. I thought to use enemy.type to narrow down his scope but…then he just goes after that enemy type across the map and same result. I can’t seem to figure out how to add distanceTo into arrays either so that’s been a struggle.

So, should I assume there are levels I need to go and do prior to this to learn how to pass this stage then? or is it that I’m just overlooking it?

while True:
    enemies = hero.findEnemies()
    enemyIndex = 0
    while enemies:
        enemy = enemies[enemyIndex]
        if enemy:
            hero.attack(enemy)
        enemyIndex += 1
    mushrooms = hero.findNearest(hero.findItems())
    mushroomIndex = 0
    while mushrooms:
        mushroom = mushrooms[mushroomIndex]
        if mushroom:
            hero.moveXY(mushroom.pos.x, mushroom.pos.y)
        mushroomIndex += 1

the basic form of what I got thus far, in case it might be containing any mistakes. I know I still need to define when to get the mushrooms and for him to go there, but I’ve been working on the enemy problem first so it’s kind of just been sitting there. (edit: on second thought not sure i need to add a “when” to gather the mushrooms, do I?)


#11

@Xector64 The Trials is a hard level. I don’t think I beat this until I did a equipment upgrade. I cannot remember though.

To find the nearest enemy to attack use something more like:

enemies = hero.findEnemies()
enemy = hero.findNearest(enemies)

Like what you are doing for the items.

Also mushrooms = hero.findNearest(hero.findItems()) returns a single mushroom, not an array.

mushrooms = hero.findItems() returns an array of items


#12

Oh…that would make a lot more sense than…well everything I did. Lol. Thanks again.