Difference between revisions of "W1301 Arrays"

From Coder Merlin
Line 168: Line 168:
== Filtering One-Dimensional Arrays ==
== Filtering One-Dimensional Arrays ==


When you're working with a one-dimensional array, it may be useful to remove specific elements that aren't needed from the array. Fortunately, removing elements from an array is quite straightforward. Simply by using the '''filter()''' method,  
When you're working with a one-dimensional array, it may be useful to remove specific elements that aren't needed from the array. Fortunately, removing elements from an array is quite straightforward. Simply by using the '''filter()''' method, one can filter out specific elements within an array. Let's take a look at how it works.
 
<syntaxhighlight lang="swift">
let words = ["hello", "world", "this", "is", "a", "list", "of", "strings"]
let filtered = words.filter { word in
  return word.count >= 3
} // filtered is ["hello", "world", "this", "list", "strings"]
</syntaxhighlight>


{{ComingSoon|
{{ComingSoon|

Revision as of 08:51, 7 January 2022

Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder

Background[edit]

Key ConceptsKeyConceptsIcon.png
  • Abstract Data Types, or ADTs, represent models for data structures. The model specifies the required behavior (semantics) of the type, such as supported operations and the impact of those operations on the type.
  • The model specifies the required semantics (behavior) of the type, such as supported operations and the impact of those operations on the type.
  • ADTs are theoretical and are used in designing and analyzing algorithms and data structures. Compilers, however, may implement specific data structures fulfilling most, if not all, of the requirements of an ADT.

Arrays[edit]

The Array Data Structure is a collection of elements each of which can be identified by an index. An array is stored so that the position of the element in memory (or other storage) can be easily calculated based only on the index. For example, consider an array of integers:

Array Data Structure


In this array, each integer requires thirty-two bits (or four bytes). Thus, there are four bytes from the beginning of each element to the beginning of the next element. This allows us to calculate the position of an integer in this array by adding the product of the element index (starting from zero) and the bytes required per element to the foundation address. In this case, the formula would be:

0x0800 + (4 * index)

Arrays are very common data structures and used in almost every program. CPUs generally enable assembly language programs to easily work with arrays. As an example, a base plus index mode enables a program to access an element by storing the foundation address in the base register and specifying the index (scaled by the size of each element) in the index register.

ADT Properties[edit]

As an abstract data type, arrays are:

  • A collection type, meaning that a single variable conceptually “contains” many elements
  • Each item in the data structure is termed an element
  • The collection is ordered, that is, the order of the elements is maintained
  • Elements can be accessed randomly, that is, there is no need to access elements in any particular order
  • The array is homogeneous, that is, all of the elements are of the same type


One-Dimensional Array Declaration[edit]

The first step in using a one-dimensional array is to declare the array following the outlined syntax below.

The following is a syntax template you can use of a one-dimensional array declaration:

Data_Type Array_Name [Const_Int_Expression];

Reference information regarding array declaration:

  • Data_Type defines what type of data is stored in the array. Commonly used array types within a one-dimensional array are Int, String, Char, Bool, Var.
  • Array_Name defines the name of the array in the array declaration.
  • Const_Int_Expression defines the array size. This value must be greater than zero. When an array is defined as size 'n', the array indices will range from 0 to n-1.

Arrays can also be created of a determined size and initialized with an initial value with the following convention:

 var initailizedArray = [ArrayType](count: NumbeOfElements, repeatedValue: InitialValue) 

For instance, the array can be set to hold four elements with each element of the array holding an initial value of zero with the following array definition.

var holderArray = [Int](count: 4, repeatedValue: 0)

Fun Use Case[edit]

Arrays in Swift can store elements of any type, known as heterogeneous collections. To define an array in swift to store elements of any type, simply specify the variable as [Any].

Example

var test = [1, 2.4, "abc", "def", 4] as [Any]

Once you are ready to print the contents of the array simply use the following:

print("The Array: \(test)")

Resulting in the following:

The Array: [1, 2.4, "abc", "def", 4] 

Performing Operations on a One-Dimensional Array[edit]

An array can be instantiated using a series of literals. For example:

   let oddNumbers = [1, 3, 5, 7, 9, 11]
   var states = ["California", "Florida", "Texas"]

An empty array can be instantiated by explicitly specifying its type:

    var emptyDoubleArray = [Double]()

The first element of a non-empty array is accessed using an index or subscript of 0. For example:

    let firstState = states[0]

One can determine if an array is empty using the isEmpty property and determine the number of items in the array using the count property:

    if !states.isEmpty {
        print("The array contains \(states.count) states.")
    }

A shortcut to access the first and last elements makes use of the first and last property which return a type of Element? (optional Element).

    print("The first state in the array is \(states.first!)")
    print("The last state in the array is \(states.last!)")

Adding a single element to the end of an array can be accomplished with append:

    states.append("New York")

We can also insert an element at a specific index in the array:

    states.insert("New Jersey", at:1)


This shifts the other elements in the array to “make room” for the new element.
Finally, elements can be removed with the remove method:

    states.remove(at: 2)

Traversing One-Dimensional Arrays[edit]

Traversing is another key operation used when working with one-dimensional arrays. Traversing - also known as looping - is a great way to print specific items within an array, or iterate through a one-dimensional array in a method.

Let's use the simple example of iterating through a small array of state capitals to show the benefits of traversing a one-dimensional array.

We'll start by defining the array:

let statecapitals = [
    "Arizona": "Phoenix",
    "California": "Sacremento",
    "Florida": "Tallahassee"
    "Texas": "Austin"
]

Now that the array is defined, let's use a for loop to iterate through the array and print each state and the associated state capital.

for statecapital in statecapitals {
    print("\(statecapital.value) is the state capital of\(statecapital.key)")
}

When traversing a one-dimensional array it may be important to access or print array items starting at the end of the list. To achieve this, use the swift method reversed().

for statecapital in statecapitals.reversed() {
    print("\(statecapitals.value) is the state capital \(statecapitals.key)")
}

Searching a One-Dimensional Array[edit]

Oftentimes, you'll need to find a specific item in an array or determine if an object exists within an array. To find elements within an array the contains() method can be very useful. Let's take a look at how contains() can be applied.

if statecapitals.contains(where: {$0.name == "Phoenix"}) {
print("\(statecapitals.key) exists")
   // Here, we're looking to see if the element name exists within the array.

} else {
print("\(statecapitals.key) does not exist in the array")
// If there is no "Phoenix" element in the array.
}

Once you've determined the object to be in the array, you can get the element with the following function.

if let capital = statecapitals.first(where: {$0.name == "Phoenix"}) {
   // Now you can use capital as you wish
} else {
   // the capital could not be found.
}

Filtering One-Dimensional Arrays[edit]

When you're working with a one-dimensional array, it may be useful to remove specific elements that aren't needed from the array. Fortunately, removing elements from an array is quite straightforward. Simply by using the filter() method, one can filter out specific elements within an array. Let's take a look at how it works.

let words = ["hello", "world", "this", "is", "a", "list", "of", "strings"]
let filtered = words.filter { word in
  return word.count >= 3
} // filtered is ["hello", "world", "this", "list", "strings"]
ComingSoonIcon.png
Coming Soon
  • Preconditions


Python

Python[edit]

Note: Python does not have arrays; lists are used instead

A list can be instantiated using a series of literals. For example:

oddNumbers = [1, 3, 5, 7, 9, 11]
states = ["California", "Florida", "Texas"]

An empty list can be instantiated:

emptyArray = []

The first element of a non-empty list is accessed using an index or subscript of 0. For example:

firstState = states[0]

One can determine if a list is empty by checking it's length:

if len( states ) > 0:
    print("The array contains " + str(len(states)) + " states.")

or by simply using if:

if states:
    print("The array contains " + str(len(states)) + " states.")

The last element of a list can be accessed by using -1 as the index. The first element can be accessed by calling the negative length(e.g. states[-len(states)])

print("The first state in the array is " + states[-len(states)])
print("The last state in the array is " + states[-1])

We can use indices to iterate over each element at a specific location in a list with a for loop:

for i in range(0, len(states)):
    print(states[i])

A very easy way to iterate over all elements in a list makes use of a for loop:

for state in states:
    print("State: " + state)

Adding a single element to the end of a list can be accomplished with append:

states.append("New York")

We can also insert an element at a specific index in the list:

states.insert(1,"New Jersey")

This shifts the other elements in the list to “make room” for the new element.
Finally, elements can be removed with the del keyword:

del states[2]

Exercises[edit]

ExercisesExercisesIcon.png
  •  M1301-10  Complete  Merlin Mission Manager  Mission M1301-10.

Quiz[edit]

1 For the array: int stats[4]; What is the range of the index?

0 to 5
0 to 4
1 to 6
0 to 3

2 Arrays can be passed as parameters to a method either by value or by reference.

False
True

3 int [] nums = {2, 3, 5, 8, 9, 11};

1,3,5,7
1,2,3,4
0,2,4,6
0,1,2,3

4 How to create a one-dimensional string array called holder?

int holder = (String)()
int holder = [String]()
var holder = (String)()
var holder = [String]()

5 The first value of the array called holder can set to 50 in the following way?

holder[zero] = 50;
holder[0] = 50;
holder[1] = 50;
holder[one] = 50;

6 int [] holder = {1, 2, 3, 4, 5}; How would you access the third element in holder?

holder(3)
holder[4]
holder(4)
holder[3]

7 A method can return a value of type array.

True
False

8 Which of the following statements outputs the fourth value in the holder array?

System.out.println(holder[3]);
holder[3];
holder[3];
System.out.println(holder[4]);

9 A one-dimensional array is an example of a structured data type.

True
False

10 What value is at index 1 in this array? String[] names = {"Michael", "Kobe", "Larry", "Magic"};

Magic
Larry
Michael
Kobe