[Repost] Simulating an Epidemic

3Blue1Brown back with another awesome video!! Check it out!

Philosophy Essay: Against Representation

**This was for my ARTI/PHIL/PSYC 3550 class as my final essay and in summary, this essay argues against the classical models of cognitive science where representation is seen as essential to artificial intelligence. Final grade was a B+, so there are points where there might be thin spots, but overall, if y’all have any thoughts or points of disagreements, leave’em in the comments below. :)**

Introduction

Throughout much of our study and development of human cognition and its replication in the various forms of artificial intelligence, there has been an underlying assumption from which we have based our work on– that to replicate intelligent thought and intelligent behavior requires extensive representation. However, representation isn’t only unnecessary but that it would actually be detrimental to our efforts to create true artificial intelligence and our understanding of our own cognition if we keep the level of representation that we currently implement in our machines.

Embodied Cognition

“A machine can exist in an abstract plane where it can crunch numbers detached from the physical world. We, on the other hand, are enmeshed in it.”

A key difference between us and the machines we create is in our embodiment. A machine can exist in an abstract plane where it can crunch numbers detached from the physical world. We, on the other hand, are enmeshed in it. Our bodies constantly feed us information about the environment and we have no way of disconnecting from it. Our cognition is fundamentally embodied and our bodies affect the way we think and vice versa. 

This can be shown in our use of language. Language is a cognitive tool that both permits the expression of and the limitations of our cognition and how we use it tells us a lot about how we think. Since so much of our cognition is expressed and shaped within the constraints of our language, Language shows us just how much of our cognition is rooted in our bodies. For example, warmth is associated with affection (“warming up to someone”), weightiness is associated with value and importance, and exposure to immoral or unethical instances causes a feeling of uncleanliness [1]. In these cases, it shows that there is a reciprocal relationship between our cognition and our physiological form. 

This strong connection between body and mind means we often never have to completely hold our thought processes in our brains. For example, if we are working out a math problem, we can write it down and refer back to earlier steps to help complete later steps. This way, we only have to store the current step of the process in our brain, make the immediately relevant calculation and then the information can be stored and kept track of on an external medium. Since our brains are limited in its energy stores, it saves a lot of energy by processing information in small chunks and to externalise it like this. Rather than wasting time and energy replicating a model of the problem space internally to manipulate, we can just reference reality to inform us on what to do next. This ties back to cognitive technology [2] where external mediums can be used to bolster our cognitive processes and therefore, become an extension of our cognition. It makes sense, then, that since we can save energy, increase our cognitive abilities and make use of a body we were born with, a lower level of representation and a more embodied cognitive process will allow us to make better use of the body we possess and our energy resources and therefore, is a much more efficient way than the fully representational classical models. We will see how this need for efficiency means that, in our brains, just the minimal level of representation is used to allow us to “scrape by”.

Efficiency Argument

The human brain and its mysterious inner workings that we try to replicate in artificial intelligence have been shown to use far less representation than we thought. We can see this in all the ways that the brain fails to notice what should have been significant details like in the famous Gorilla Experiment [3] where participants, upon being asked to watch a clip of a basketball game, fail to spot when a person in a gorilla suit walks through the middle of the game. If the brain used the same level of representation as our machines, then all the participants should have made a complete internal model of the basketball game and noticed the gorilla. Instead, it seems that the brain is selective in its attention and by doing so, restricts the amount of information it needs to process at one time and is, therefore, more efficient.

” Rather, it seems that, for the most part, our brains can get by with as little representation as possible to be functional and be generally correct when it comes to problem-solving.”

Besides incomplete representation, the brain is also prone to a phenomenon called gist memory[4] where our memory can be, at times, approximative and at worst, unreliable. In a task where participants are asked to remember words with similar associations like “ice”, “snow”, and “winter” from a list, participants often say they remember a word, like “cold”, that wasn’t present on the list but also shared those associations. Other shortcomings like the notoriously unreliable eyewitness testimony have further exposed just how little our brain represents from the world. Rather, it seems that, for the most part, our brains can get by with as little representation as possible to be functional and be generally correct when it comes to problem-solving.

Evolution Argument

However, we are not the only ones capable of exhibiting intelligent behavior. In fact, much of intelligent behavior doesn’t need a brain but rather an interlocking system of simple operations that, when viewed gestalt, suggest intelligence. Roboticist Rodney Brooks coined the term “subsumption architecture”[5] to describe such a structure. We need to look no further than our own bodies for an example. Our immune system possesses remarkable adaptability and complexity[6] that, if we didn’t know any better, we might have thought that the individual cells within our body possess their own intelligence. From the outside, the operations of the cells that make up our immune system seem to be a conscious, coordinated effort but each cell is actually just responding to certain stimuli released by other cells like proteins or hormones. 

This sort of organisation can be seen in organisms like ants where they use very simple chemical markers that elicit simple behaviors that, when repeated within a colony of thousands or millions of members, can forage for food, wage war, maintain fungus farms and aphid herds, and build floating rafts to survive floods. Brooks himself built creatures based on crickets that showed how intelligent behavior like finding mates which require pathfinding and spatial reasoning can actually be the result of very simple physiochemical reactions within the body[5].

Therefore, not only is representation not needed at all for certain intelligent behaviors but even for the human brain, representation is only very minimally used. However, there is more to our intelligence than merely problem-solving and so far, it doesn’t seem like they’ve been accounted for. 

Rebuttals

Imagination, for one, hasn’t been accounted for. Imagination, according to Merriam-Webster, is “the act or power of forming a mental image of something not present to the senses or never before wholly perceived in reality”. This means that, necessarily, to be able to imagine means that the things we imagine must not already exist and therefore unable to be represented. It can be argued that our imagination is actually just a composite of previous experiences (representations) put together in novel ways to make something technically “new”. However, it must be considered that just because representations of something exists doesn’t mean that it’s necessarily real. For example, illusions and hallucinations causes a person to represent something that isn’t actually there. I am of the thought that the false representation of a non-actual object cannot be truly considered to be represented the same way we represent what’s real[see 7]. In the same vein, although I cannot yet explain the presence of these false representations, I argue that imagination, due to its focus on the non-actual, does not in fact rely on representations or at least, the type of representation as we currently understand it to be.

“We don’t know why it is so, it just feels right.”

Second, our memory, it might seem, also depends on representations. After all, memory is formed through the encoding of past experiences. However, I argue for limited representation, not the total elimination of representation. It is true that a certain type of memory (fact-based, non-phenomenal memory) may be represented but it still doesn’t account for other types. Muscle memory, for example, is formed through repetition of a movement and once formed, is accessed without conscious effort. This is different from the explicit content that makes up represented memories. Similarly, ability-based memory also seems to lack representation. For example, when teaching another to drive, it is hard to articulate the feeling of the car, how to know how far to turn or how far the hood extends past the steering wheel. Perhaps a better example can be found in our use of language. We can usually go about our day and communicate with no problem but once we are forced to slow down and explain the finer details of grammar or convention, we are often stumped. We don’t know why it is so, it just feels right. Efficiency once again plays a role here. By cutting out the thinking part of certain operations like driving a car or figuring out grammar before speaking, the brain doesn’t need to waste resources “reinventing the wheel” and rather, just knows that certain stimuli should entail certain reactions. You don’t need to think, “the light is green and green means go” before pressing the gas pedal. You do it automatically. This way, the process cuts out thinking and representing entirely and can go straight from sensing to reacting.

It was given for a long time that the representational theory of mind would be the basis on which we can produce higher cognition in our own creations but now we know better than to let that be the end-all-be-all. With a better understanding of the reciprocal relationship between our bodies and our cognition, studies that reveal just how little our own brains rely on complete representation, and the fact that not everything that looks intelligent is intelligent, it seems that representation is actually a rather inefficient and insufficient explanation for all the miracles we are capable of.

References

[1] McNerney, Samuel. “A Brief Guide to Embodied Cognition: Why You Are Not Your Brain.” Scientific American Blog Network, Scientific American, 4 Nov. 2011, blogs.scientificamerican.com/guest-blog/a-brief-guide-to-embodied-cognition-why-you-are-not-your-brain/.

[2] “Chapter 9: Extended Minds?” Mindware: an Introduction to the Philosophy of Cognitive Science, by Andy Clark, Oxford University Press, 2014, pp. 192–211.

[3] Simons, Daniel, director. Selective Attention Test. YouTube, YouTube, 10 Mar. 2010, www.youtube.com/watch?v=vJG698U2Mvo.

[4 ]Makin, Simon. “What Happens in the Brain When We Misremember.” Scientific American, Scientific American, 9 Sept. 2016, www.scientificamerican.com/article/what-happens-in-the-brain-when-we-misremember/

[5] Brooks, Rodney A. “Intelligence Without Reason.” The Artificial Life Route to Artificial Intelligence, 2018, pp. 25–81., doi:10.4324/9781351001885-2. 

[6]Chaplin, David D. “Overview of the Immune Response.” The Journal of Allergy and Clinical Immunology, U.S. National Library of Medicine, Feb. 2010, www.ncbi.nlm.nih.gov/pmc/articles/PMC2923430/

[7] Loar, Brian. “Transparent Experience and the Availability of Qualia.” Consciousness and Meaning, 2017, pp. 273–290., doi:10.1093/acprof:oso/9780199673353.003.0016.

[Repost] What is Code? by Paul Ford

I was recently assigned to read this entire article/essay/magazine in a class of mine and was blown away by how comprehensive it is. If you guys are just beginning to dip your toes into IT or software development, then this is a must-read!

To read the article:

https://www.bloomberg.com/graphics/2015-paul-ford-what-is-code/

Symbolic Logic: Conditional/Indirect Proofs and Proving Theorems

Hey guys! So, this time, we’re going look at other methods we can use to construct proofs when just deriving from the premises isn’t enough.

Conditional Proof (CP)

The setup:

Basically, you use this method when the conclusion or a part of the conclusion you want is a conditional. This makes it so you assume the predicate in order to derive the consequent. Here’s an example:

Indirect Proof (IP)

The setup:

For this method, you use this primarily when the conclusion is a negated statement. You assume the un-negated form of the conclusion and attempt to find a contradiction so that the assumption is false, thus ending at the negated form. It also works the other way around where the conclusion isn’t negated so you make the assumption negated instead and then use the DN rule at the end. It’s also super useful when proving theorems where you have a limited plan of action. An example:

Theorems

Theorems are formulas that can be proven true without premises so the proofs for theorems have the additional challenge of not being able to build off of premises. Therefore, the above two methods are essential to be able to do proofs of theorems. Here’s an example:

RULES

  1. All assumptions must be discharged(closed).
  2. Lines between different assumptions must not cross.
  3. Once discharged, steps within the subproof cannot be used anymore.

On to the next page for a few practice problems!

How To Read/Trace Recursive Methods

So, recursion, one of the hardest units in APCS. The concept is pretty easy but the execution is a bit trickier. Today, I’m going to pass on a trick that my teacher taught me on how to trace your way through a recursion problem.

I’m going to assume that y’all already know what recursion is and how it works so I’ll jump straight into tracing. Let’s start off with a basic problem.

This problem is from here.

about-death

First, you have to start from the bottom of the page and go up from there. As you go through every iteration of the recursive statement, you make a new line. So, this method with an x = 5 and y = 2, if solved, would look like this:

Asch_experiment.svg

The bottommost line contains the original call to the method with 5 and 2 being x and y, respectively. The right of the diagram shows the operations within the recursive call and all the way at the top, the 17 represents what is returned by the base case when x becomes 0.

Let’s look at a recursive method that also prints something out in each iteration of the recursive statement.

This problem is from here.

about-death

For these problems, you would have to see where the print statement is in relation to the recursive statement. If the print statement is before the recursive statement, then the order of the printed lines go up and vice versa. So the tracing would look like this if n = 3:

about-death.png

So the output would look like:

3

2

1

Blastoff!

If the println statement was after the recursive statement, you would have to write them next to the after arrow and Blastoff! would be printed first.

So, these are the basics. If you guys have any specific questions for specific problems, feel free to contact me and I’ll help however I can.

This is Lieutenant out.

Our Sunken Place |July Study Piece Part 1: The Psychology

“What good fortune for governments that people do not think.” – Adolf Hitler

 

In humans, there has always been an intrinsic struggle between the self and others. We must be able to maintain a distinct self-identity while at the same time be able to fit as one of the innumerous cogs of society. Because of this need to fit in, over the course of history, the actions and thoughts of the public have been hijacked many times to make them pliable under the will of their governors.

The idea of government and other governing institutions is to consolidate decision-making power into a central body so that the citizens are able to free their hands to do other things. However, this opens up the door to complacency where the public would rather not worry about the finer details of policy and lawmaking and doesn’t take notice before it’s too late.

There are several ways that we can be told information that is clearly wrong but we still believe what’s being said. In this first part to this month’s study piece, we’ll look at some of the ways that we can be suggested to second-guess our own thoughts, focusing on what we know so far from psychological studies.

Conformity: Informative vs Normative Social Influence

First, we’ll start off with a well-known experiment:Asch’s Line Experiment. In it, a group of students were asked which line (a, b, or c) most closely matched the length of the original line.

Asch_experiment.svg

In reality, within the group of students, there was only one that was truly a participant of the study; the rest of the group were confederates of the researchers. This is done to gauge how group pressure, even when the group is wrong, can sway a person’s public belief even if they secretly believe otherwise. In the trials where the group said the wrong answer, a significant portion of the time, the participant went along with what the group. After the study was concluded, when the participants of the study were debriefed, the participants admitted that they didn’t think the group was right but went along with it anyway.

Now imagine this scenario playing out in the real world with much higher stakes. This has happened many times throughout history. Ultimately, this study was done to gauge the level of conformity that we display in a group setting. In other words, this study demonstrated the power of normative social influence over our public actions: when others believe one thing or perform one action, we are more likely to also believe that thing or perform that action even if it’s against our values.

This sort of conformity is also why a person’s vote is kept confidential. Otherwise, their vote may not stand for what they truly believed in.

To more aptly illustrate, this is a famous poem called First They Came… by Martin Niemöller, a pastor and Nazi concentration camp survivor:

First they came for the communists, and I did not speak out – because I was not a communist;

Then they came for the socialists, and I did not speak out – because I was not a socialist;

Then they came for the trade unionists, and I did not speak out – because I was not a trade unionist;

Then they came for the Jews, and I did not speak out – because I was not a Jew;

Then they came for me – and there was no one left to speak out for me.

Inaction in a time of crisis is just as bad as having committed the crime itself.

On the other hand, we also have informational social influence. This type of influence is in how willing we are to accept the word and instructions of a person who seems to know better. Whereas normative influence comes from a person’s desire to be liked and accepted, informational influence comes from a person’s desire to reflect what seems to be the correct behavior or belief. This occurs more when the person in question doesn’t know what to do in a certain situation. This type of influence is partially why the bystander effect exists where since no one else if doing anything to help a dangerous situation, you as an individual are less likely to help as well. This is also why children in cults can be taught to hate things and people they’ve never seen and to fear things that they don’t even know. If it’s an adult or some other authority figure speaking, then it must be true because they know better.

That is simply not true.

Don’t give up the burden of individual thought just because you’re tired and don’t know who to believe anymore. This is the time when you need to think for yourself the most.

In part, this submission to peer pressure is evolutionarily hardwired into us so that we don’t get ostracised by the social group that we belong to. In the wild, this promotes our ability to survive by creating a like-mindedness among the members of a group so that everyone works better together. However, this also means that we are more likely to stay silent when we do see something that goes against our values especially when whatever’s happening doesn’t directly affect us.

Obedience

Obedience to an unsavory cause can stem from many reasons even when the person knows that what they’re doing is wrong. Most come from fear.

First, we’re going to look at another famous study: theMilgram Experiment. The experiment revealed the willingness of participants to harm another human being under the orders of an authority figure.

For brevity’s sake, this video helps illustrate both what the Milgram Experiment was and how it relates to this month’s topic (be warned: there are segments of original footage from concentration camps as well as the experiment — viewer discretion is advised):

Under the pressure of authority, even the ordinary, compassionate citizens would be willing to do great harm to others, sometimes with great conviction.

Power

Everyone knows the saying, “Power corrupts” and science can prove it. The first study we’re going to bring up is Professor Zimbardo’s infamousStanford Prison Experiment.

If you haven’t heard of what the experiment is, please watch this introductory video (that I found on YouTube):

In it, we saw how students who by all accounts were outstanding intellectuals at Stanford University turn into the abusive and abused that we hear about from news stories to the point where, to the students’ safety, the experiment had to stop at six days. All it took was six days.

The whole point of the experiment was to understand the developments of norms as well as the effects of labels and roles on people and their behavior. What we see that it only takes very little time for anyone to degenerate into a state of suspended morality.

It’s so easy to become used to ever-escalating levels of shocking events especially when the events separated from you by barriers. A different race, a different place, other humans. It shouldn’t matter who is suffering because of our actions. If it was happening to you, you would want others to stand up for you so why should you sit idle when it’s happening to others? This includes criminals, people who come from other lands, and those that aren’t able to speak for themselves (those with disabilities, mental conditions etc.).

If it only took that much time before bright, young college students who didn’t have any external pressure to perform as inhumanely as they did (they didn’t have any real benefit from treating fellow students like crap), then what would happen if we happened to live in a world where we thought we were the policemen of the world, that our way was the right way? We would adopt that role and grow into it, imposing our views, our values and our needs on others, thinking that since we know better, everyone else is better off doing what we think is best for them, never entertaining the idea that, just maybe, we don’t know better and it’s better that we don’t play God with the rest of the world. It’s easy to say that another Holocaust/Trail of Tears/Rape of Nanjing/genocide won’t happen to us or our country nowadays but at the same time, those that came before has demonstrated again and again that it is possible and might possibly happen again.

Cognitive Dissonance and Defense Mechanisms

A very effective way to squash a person’s conscience towards crimes committed or views held is to rationalise what is being done. Often, arbitrary standards are used to measure the victim to dehumanise them and make them a being that we can’t relate with and therefore don’t feel bad if they’re hurt, tortured or killed (includes mental and emotional hurting, torturing and killing). This is all to ease our cognitive dissonance and acts as a defence mechanism because no one likes to think they’re bad people doing bad things.

Rationalisation is the same as lying to yourself to justify your actions. It’s obvious to see with alcoholics and other addicts but it’s not so easy with yourself. This can take form in the associations we make to the people we hurt or through “alternative words”. This can be seen in the doublespeak-like fashion that we use to term unpleasant things. This might be euphemisms that we hear in day-to-day life or we might it hear it on the news and from our policymakers where concentration camps are referred to as “tent cities” and concentration camps for young children are called “tender age shelters”.

Other ways that people ease their cognitive dissonance is to victim-blame. Is it the victim’s fault for carrying their wallet in their back pocket when he gets pick-pocketed? People like to believe that bad things don’t just happen for no reason and that bad things won’t happen to good people. Rationalisation comes after the fact so many justifications didn’t apply at the time the event is happening. In other words, we make up faults in the other person to make it seem like the other person deserved it. It takes a very introspective person to recognise when they’ve been rationalising their actions and it takes a strong mind to own up to any actions they weren’t proud of.


In total, we will have three parts to this month’s study piece. We will, for the most part, focus on WWII and in particular on Japan and Nazi Germany. In the second part of this series, we will look at how the Japanese, who are normally a courteous and honor-focused people, managed to commit evils on par with and beyond those committed by the Nazis under Hitler’s rule. The third part will, then, be focused on Germany during WWII. Overall, we hope that by analysing these two instances of hate and unspeakable violence, we are better able to understand and recognise the very symptoms of intolerance and detached morality that led to what happened and prevent it from happening again today.


Additional Readings:

Causes and Motivations (Nazi Germany)

The Obedience Studies at 50

Post Hoc Rationalisation – Reasoning Our Intuition and Changing Our Minds

1984, The Handmaid’s Tale and Fahrenheit 451

Framing as a Propaganda Prop

The Hangman | A Poem

 

APCS Chapter 6: 2D Arrays and ArrayLists

Alright, it’s time to tackle 2D arrays and arrayLists. 2D arrays are basically arrays of arrays. First off, 2D arrays:

2D Arrays

To start off with, the declaration and instantiation. Since 2D arrays are objects, we will use the new operator. There are several ways to do this:

The “normal” way:

data type [] [] name = new data type [# of rows] [# of collumns];

Example: I want to create a 2D array called nums containing int data with 2 rows and 3 collumns:

int[] [] nums = new int[2][3];

If you want to create a jagged array where each row is of a different length, then you can input your values directly into the 2D array. There are several ways to do this but I’m going to show you guys the simplest one:

int[] [] nums =

{

{4, 5, 6, 4},

{7, 234, 34, 1},

{23, 57, 2}

};

(Of course, you can write this all on one line but this layout looks more intuitive.)

So, this is what the 2D array would look like visually:

getimage

If this were a rectangular 2D array and not a jagged array, any attempt to retrieve a data value from the index position (3, 2) would return null so keep that in mind if you are manipulating or accessing a 2D array. There is also a thing called sparseArrays and an FRQ concerning sparseArrays has popped up on the AP exams (although I don’t think it’s likely to pop up again but hey, the more you know…) so here’s a link that kind of explains it but I don’t really think you need to know it for this class because it’s a little more high-level.

Traversing Through a 2D Array

With 2D arrays, you also need to know how to traverse through them. You can do this through the basic three types of loops. I’m going to show an example of each.

For Loops

You can use both the for loop and a for each loop. In my examples, I’m going to use the loops to add up all the numbers in the 2D array. I’m going to use the nums array that I instantiated above (all of the loops work with regular 2D arrays as well as jagged 2D arrays). This is how to use a regular nested for loop to go through every element in a 2D array and add them up.

int sum = 0;

for (int row = 0; row < nums.length; row++)

for (int col = 0; col < nums[row].length; col++)

sum += nums[row][col];

For Each Loop

For each loops are a little less intuitive to use but in the first part of the parameters denote which type of data type you’re trying to handle within the array and the second part is the array that you want to traverse through.

int sum = 0;

for (int[] num : nums)  //this looks at each row of thes 2D array

for (int i : num)  //this looks at all the data values within each row

sum+= num;

Both of these loops do the same thing.

While Loops

As a rule of thumb, while loops are used when you don’t know how many times iterations you need the loop to go through. I’m just going to use the basic example I used above and write a while loop instead.

int row = 0, col = 0, sum = 0;

while (row < nums.length) {

while (col < nums[row].length) {

sum += nums[row][col];

col++; }

row++; }

 ArrayLists

APCS Ch 6: Sorting and Searching Methods

Sorting methods as it pertains to arrays isn’t the simplest thing to wrap your head around but the concept and the way they should work should be pretty intuitive. You would need to know about two main sorting methods in APCS; the selection sort and the insertion sort. Like the different types of loops, both of these sorting methods have pros and cons attached to them.

Selection Sort

A selection sort is a tedious affair. Basically, what it does is takes each value in each index position and compares that value to all the other values to the right of it (after it) in the array. When it finds the smallest/largest value that exists to the right of its index position, it swaps places with it. In this way, this method sorts all of its value in either ascending or descending order of value.

Let’s take a look at what a selection sort in ascending order looks like in code:

//nums is an array of int values

//the variables min and minIndex both hold int values

for (int i = 0; i < nums.length – 1; i++)

{

min = nums[i];

minIndex = i;

for (int j = i; j < nums.length; j++)

{

if (nums[j] < min)

{

min = nums[j];

minIndex = j;

}

}

int temp = nums[i];

nums[i] = nums[minIndex];

nums[minIndex] = temp;

}

This is a daunting bit of code at first. However, if we understand mechanically how this sorting method works, it might help you understand better. For example, if I had an array of int values, this is what the array would look like after every pass of the outer loop:

cap

(1) The outer loop started at index position 0, took the number 16 at index 0 and started to loop through the values after it to find the smallest number, which happened to be the number 1 at index position 5. Then, the numbers 1 and 16 swapped places due to the inner loop. That was the first pass of the outer loop.

(2) Then, the outer loop looked at index position 1 and picked up the number 3 at index 1 and looped through the values to the right to find the smallest number. Since there were no values to the right that was smaller than 3, the inner loop swapped the 3 at index 1 with 3 at index 1, which meant the 3 swapped with itself and stayed where it is.

This process would repeat until it got to the second to last number by which time, the last number in the array would already be in its final sorted position so the number of passes the outer loop needs to fully sort an array is always the length of the array minus 1. By this rule, if we were on the fourth pass of the outer loop, the first four values of the array would have been in their final sorted places.

Let’s break down the code and see what the first pass of the outer loop looks like:

for (int i = 0; i < nums.length – 1; i++)

The outer loop just goes through the whole length of the array. In the first pass, i would be set to 0.

min = nums[i];

minIndex = i;

This sets min to the number currently at the index position of whatever element the outer loop is currently looking at. So, min would be set to the number at index 0 on the first pass, which would be the number 16. The index of the smallest number would be default set to the index of the number that we’re currently looking at, which would be index 0.

 for (int j = i; j < nums.length; j++)

This inner loop would loop through all the index positions to the right of the number at the index position we’re currently looking at, which would be all the values stored in the index positions after index 0.

if (nums[j] < min){

min = nums[j];

minIndex = j; }

This if statement compares the current min value (16) to all the values right of its index position (0). If it finds a number that is smaller, it will set the smaller value to min and set its index position to minIndex. The inner loop would cause this if statement to compare whatever smallest number it has found so far to the numbers in the index positions to the right. When it came to the number 1 at index 5, it set min to 1 and minIndex to 5. After going through the rest of the array, it didn’t find any smaller value so those variables stayed the same and we exit out of the inner loop.

int temp = nums[i];

nums[i] = nums[minIndex];

nums[minIndex] = temp;

This piece of code should look familiar; after all, it should be a simple puzzle that confronts many beginner programmers. Basically, what this does is it swaps the two numbers at the two index positions. In this case, temp would be set to 16, then the index position 1 would be overridden with the value at minIndex(5) which is 1. Then, temp (16) would override what was at index 5, effectively swapping the 16 and 1. This repeats until it has touched all but the last index position in the array, at which point the array is fully sorted and the outer loop terminates.

See next page for Insertion Sort

APCS Ch 6: Arrays Basics

Arrays are basically lists of things. This list can contain both objects and primitive data. The basic array can be declared and instantiated as such:

(data type)[ ] (arrayname) = new (data type) [(number of elements)];

Since arrays are considered as objects, the declaration and instantiation follow the pattern of other objects. So, if I wanted the array to store a total of ten names, I would make the array like so:

String[ ] names = new String[10];

Arrays have index values for every element they contain. If I had an array called nums that contained the numbers 1, 2, and 3, the number 1 would have the index position of 0, the number 2 would have index position 1 and the number 3 would have the index position 2 and so on.

Like Strings, arrays have a method that returns the length of the object. In the case of arrays, you would call the method .length. The  .length method for arrays does not need the double parentheses.

So, if you wanted to know the length (or number of elements) of the array names, you would do this:

names.length;

We now go on to loops. This is quite simple. Looping through an array is pretty easy and intuitive. If I were to use a for loop to go through every element of the array names which contains 10 String objects, it would look something like this:

for (int i = 0; i < names.length; i++)

{

//body of the loop

}

AP Com Sci Chapter 2 Lab Review

Heya! This will be the first of the AP Com Sci lab solutions on Outlet. I will be uploading these labs starting from Chapter 2 because Chapter 1 is a no-brainer. For that matter, Chapter 2 is a no-brainer too. I will upload parts of the code because even though these posts are supposed to contain the “answers”,  you’re still going to have to know how to write these programs and know the concepts behind the programs to pass this class. I will not contribute to your failure. If you have any questions, you can comment them below or shoot me an email on the contact page.

For Chapter 2, I will only post about three labs, the Base Conversion Lab (pg 2-4), the Circle Labs (of which I’ll cover the Circle2 part on pg 5-7) and the String Manipulation Lab (pg 8-10) since the rest are the most fundamental basics and don’t have much to cover.

Let’s get right into it.