Arrays vs String &
Programming with Loops and Arrays
Cosmin E. Oancea
cosmin.oancea@diku.dk
Department of Computer Science (DIKU)
University of Copenhagen
October 2023
Focus of the next four weeks
Learn how to program:
modeling the solution to a problem in the simplest way that
results in an implementation that has reasonable performance.
Requires reasoning about:
datastructures: what is the simplest or most natural way to
represent and manipulate data, for solving a given problem?
complexity: on any input (dataset), the number of operations
of our implementation is a constant factor away from the
optimal one.
Data Structure
A data structure is:
I a structured way to store data;
I methods to operate on this data (e.g., insert/delete/modify).
So far you have only stored data in variables, which is
limiting (e.g., because you need to know in advance how
many variables you need);
Solution: Arrays;
Arrays are similar to Strings (to some extent).
Today’s Lecture
Strings
Arrays vs Strings
Array Cheat Sheet
Three Ways to Add One to Each Element of an Array
Multi-Dimensional Arrays
Online Programming
Strings and Text
strings is a data structure that consists of a sequence of
characters;
one can use a for-loop to go through a string one character
at a time;
the length of the string is the number of characters it has.
"ducklings".length;
← 9
Index and Sub-Strings
we start counting (characters) from 0;
the operator [i] returns the ith character;
” ducklings ” [ 0 ] ;
← ”d ”
The method substring(n, m) returns the part of the
string from the n’th character to the m’th character, including
the first but excluding the last.
” ducklings ” . s u b s t r i n g ( 1 ,5 ) ;
← ” uckl ”
We can leave out m or both arguments.
” ducklings ” . s u b s t r i n g ( 1 ) ;
← ” ucklings ”
” ducklings ” . s u b s t r i n g ( ) ;
← ” ducklings ”
Methods
Certain values, like strings, have functions attached to them.
These function are called methods.
You can think of them as ordinary functions, where you just
give the first argument in a peculiar way.
"Shannon".toLowerCase();
results in "shannon"
"Eating apples".substring(3,8);
results in "ing a"
Today’s Lecture
Strings
Arrays vs Strings
Array Cheat Sheet
Three Ways to Add One to Each Element of an Array
Multi-Dimensional Arrays
Online Programming
Arrays
An array is a collection of values—think organized
consecutively in memory—where each value is identified by
an index (again we count from zero).
Think of a sequence of boxes, and we can teleport in front of
each box, i.e., it takes the same amount of time to peek
inside the ith box, regardless of the i or the number of boxes.
The values that make up an array are called its elements or
items.
In JavaScript, the elements of an array
I need not have the same type,
I but it’s a really good idea that they do.
let words = ["We", "like", "green", "apples"];
let weirdo = ["hello", 2.0, 5*10, [10, 20]];
Working With Arrays
function mult(numbers) {
let res = 1;
for(i=0; i < numbers.length; i++) { // loop
res = res * numbers[i];
}
return res;
}
let arr_nums = [2, 5, 8, 10]; //array literal
let p = mult(arr_nums);
Working With Arrays
function mult(numbers) {
let res = 1;
for(i=0; i < numbers.length; i++) { // loop
res = res * numbers[i];
}
return res;
}
let arr_nums = [2, 5, 8, 10]; //array literal
let p = mult(arr_nums);
arr nums = [2, 5, 8, 10] declares an array literal,
i.e., creates an array whose elements are 2, 5, 8, 10:
I arr nums[0] is 2;
I arr nums[2] is 8.
function mult computes the product of an array of numbers
Working With Arrays
function mult(numbers) {
let res = 1;
for(i=0; i < numbers.length; i++) { // loop
res = res * numbers[i];
}
return res;
}
let arr_nums = [2, 5, 8, 10]; //array literal
let p = mult(arr_nums);
arr nums = [2, 5, 8, 10] declares an array literal,
i.e., creates an array whose elements are 2, 5, 8, 10:
I arr nums[0] is 2;
I arr nums[2] is 8.
function mult computes the product of an array of numbers
The result is: p = 2 ∗ 5 ∗ 8 ∗ 10 = 800 (on whiteboard)
Working With Arrays
function make_ducklings() {
let prefixes = "JKLMN";
let suffix = "ack";
let ducklings = []; // empty array
let i; // "let" declares a variable
for (i=0; i < prefixes.length; i++) {
let letter = prefixes[i];
ducklings.push(letter + suffix);
}
return ducklings;
}
Working With Arrays
function make_ducklings() {
let prefixes = "JKLMN";
let suffix = "ack";
let ducklings = []; // empty array
let i; // "let" declares a variable
for (i=0; i < prefixes.length; i++) {
let letter = prefixes[i];
ducklings.push(letter + suffix);
}
return ducklings;
}
for (i=0; i < prefixes.length; i++)
loops over each character in the string prefixes;
letter = prefixes[i]: gets the ith letter of prefixes;
letter + suffix: does what?
Working With Arrays
function make_ducklings() {
let prefixes = "JKLMN";
let suffix = "ack";
let ducklings = []; // empty array
let i; // "let" declares a variable
for (i=0; i < prefixes.length; i++) {
let letter = prefixes[i];
ducklings.push(letter + suffix);
}
return ducklings;
}
for (i=0; i < prefixes.length; i++)
loops over each character in the string prefixes;
letter = prefixes[i]: gets the ith letter of prefixes;
letter + suffix: does what? string-like concatenation;
ducklings.push(el):
Working With Arrays
function make_ducklings() {
let prefixes = "JKLMN";
let suffix = "ack";
let ducklings = []; // empty array
let i; // "let" declares a variable
for (i=0; i < prefixes.length; i++) {
let letter = prefixes[i];
ducklings.push(letter + suffix);
}
return ducklings;
}
for (i=0; i < prefixes.length; i++)
loops over each character in the string prefixes;
letter = prefixes[i]: gets the ith letter of prefixes;
letter + suffix: does what? string-like concatenation;
ducklings.push(el): inserts el at the end of array ducklings;
Working With Arrays
function make_ducklings() {
let prefixes = "JKLMN";
let suffix = "ack";
let ducklings = []; // empty array
let i; // "let" declares a variable
for (i=0; i < prefixes.length; i++) {
let letter = prefixes[i];
ducklings.push(letter + suffix);
}
return ducklings;
}
for (i=0; i < prefixes.length; i++)
loops over each character in the string prefixes;
letter = prefixes[i]: gets the ith letter of prefixes;
letter + suffix: does what? string-like concatenation;
ducklings.push(el): inserts el at the end of array ducklings;
The result is array: ["Jack","Kack","Lack","Mack","Nack"].
Can I Have a Slice of That String Array?
the operator [i] returns the ith character element;
we start counting characters elements from 0;
The method substring(n, m) slice(n, m) returns
the part of the string array from the n’th character element
to the m’th character element, including the first but
excluding the last. We can leave out m or both arguments.
Can I Have a Slice of That String Array?
the operator [i] returns the ith character element;
we start counting characters elements from 0;
The method substring(n, m) slice(n, m) returns
the part of the string array from the n’th character element
to the m’th character element, including the first but
excluding the last. We can leave out m or both arguments.
An array literal is a new kind of expression that has syntax:
[ Exp0 , Exp2 , . . . , Expn−1 ]
The empty array is produced by expression: []
l e t arr nums = [ 2 , 2+3 , 8 , 2 * 5 ] ;
co n s o l e . l o g ( a r r n u m s ) ; / / p r i n t s : [ 2 , 5 , 8 , 1 0 ]
Can I Have a Slice of That String Array?
the operator [i] returns the ith character element;
we start counting characters elements from 0;
The method substring(n, m) slice(n, m) returns
the part of the string array from the n’th character element
to the m’th character element, including the first but
excluding the last. We can leave out m or both arguments.
An array literal is a new kind of expression that has syntax:
[ Exp0 , Exp2 , . . . , Expn−1 ]
The empty array is produced by expression: []
l e t arr nums = [ 2 , 2+3 , 8 , 2 * 5 ] ;
co n s o l e . l o g ( a r r n u m s ) ; / / p r i n t s : [ 2 , 5 , 8 , 1 0 ]
push appends a new element at the end of an array. Syntax:
Expproducing producing
an array .push( Expan element )
Some Useful Array Methods
Method Params Description
push x Inserts item x at the end of the array.
pop Removes the last element and returns it.
concat other Creates a new array consisting of the elements
in the array on which it is called, followed in
order by the elements of the other array.
join sep Creates & returns a new string by concatenating
all array elements, each two separated by sep.
indexOf x Returns the index in the array of the first index
whose value is x, or -1 if it is not there.
sort Sorts the items of the array, in place.
reverse Reverses the elements of an array, in place.
slice m, n Returns a new array containing the elements at
indices m, m + 1, . . . , n − 1, of the original array.
splice many Changes an array by removing or replacing
existing elements and/or adding new elements.
Strings are Immutable — Arrays are Mutable
Setting/Updating the element at position ind exp of an array
arr with a new value val exp is achieved with the statement:
arr[ ind_exp ] = val_exp;
ind exp is an expression that produces and integer,
val exp is an expression that produces a value of the same
type as the array element type (for sanity’s sake).
Strings are Immutable — Arrays are Mutable
Setting/Updating the element at position ind exp of an array
arr with a new value val exp is achieved with the statement:
arr[ ind_exp ] = val_exp;
ind exp is an expression that produces and integer,
val exp is an expression that produces a value of the same
type as the array element type (for sanity’s sake).
function mutateString ( ) {
l e t s = ” TEST ” ;
s [ 2 ] = ”X ” ;
return s ;
}
m u t a t e S t r i n g ( ) ; / / r e s u l t s i n ” TEST ”
f u n c t i o n m u t a t e Ar r a y ( ) {
let arr = [ ’T ’ , ’E ’ , ’S ’ , ’T ’ ] ;
a r r [ 2 ] = ’X ’ ;
return arr ;
}
m u t a t e Ar r a y ( ) ; / / r e s u l t s i n [ ” T ” , ” E ” , ” X ” , ” T ” ]
Mutation is Good — Mutation is Bad
let a = [4 , 2 , 44];
let b = a ;
let r = [4 , 2 , 44];
let s = r . slice ( ) ;
b [ 1 ] = 24;
s [ 1 ] = 24;
co n s o l e . l o g ( ” a i s : ” , a ) ;
/ / a i s : [ 4 , 24 , 44]
co n s o l e . l o g ( ” b i s : ” , b ) ;
/ / b i s : [ 4 , 24 , 44]
co n s o l e . l o g ( ” r i s : ” , r ) ;
/ / r i s : [ 4 , 2 , 44]
co n s o l e . l o g ( ” s i s : ” , s ) ;
/ / s i s : [ 4 , 24 , 44]
Mutation is Good — Mutation is Bad
let a = [4 , 2 , 44];
let b = a ; a
0 1 2
let r = [4 , 2 , 44];
let s = r . slice ( ) ;
4 24 44
b [ 1 ] = 24; b
s [ 1 ] = 24;
co n s o l e . l o g ( ” a i s : ” , a ) ; 0 1 2
/ / a i s : [ 4 , 24 , 44]
co n s o l e . l o g ( ” b i s : ” , b ) ;
r 4 2 44
/ / b i s : [ 4 , 24 , 44]
co n s o l e . l o g ( ” r i s : ” , r ) ; 0 1 2
/ / r i s : [ 4 , 2 , 44] s 4 24 44
co n s o l e . l o g ( ” s i s : ” , s ) ;
/ / s i s : [ 4 , 24 , 44]
Today’s Lecture
Strings
Arrays vs Strings
Array Cheat Sheet
Three Ways to Add One to Each Element of an Array
Multi-Dimensional Arrays
Online Programming
Let’s Recap: How Do We Create An Array?
[]: empty-array literal (expression):
l e t a r r n u m s = [ ] ; / / a r r n u m s i s an a r r a y w i t h z e r o e l e m e n t s .
co n s o l e . l o g ( a r r n u m s . l e n g t h ) ; / / p r i n t s 0
[ e1 ,. . .,en ]: creates an array with elements e1 ,. . .,en
l e t a r r s t r s = [ ” I ” , ” l o ve ” , ” prog ” + ” ramming ” , ” ! ” ] ;
co n s o l e . l o g ( a r r s t r s ) ;
/ / p r i n t s : [ ” I ” , ” l o v e ” , ” programming ” , ” ! ” ]
Let’s Recap: How Do We Create An Array?
[]: empty-array literal (expression):
l e t a r r n u m s = [ ] ; / / a r r n u m s i s an a r r a y w i t h z e r o e l e m e n t s .
co n s o l e . l o g ( a r r n u m s . l e n g t h ) ; / / p r i n t s 0
[ e1 ,. . .,en ]: creates an array with elements e1 ,. . .,en
l e t a r r s t r s = [ ” I ” , ” l o ve ” , ” prog ” + ” ramming ” , ” ! ” ] ;
co n s o l e . l o g ( a r r s t r s ) ;
/ / p r i n t s : [ ” I ” , ” l o v e ” , ” programming ” , ” ! ” ]
new Array(nexp ): an expression that creates a new array of length (determined by the
evaluation of expression) nexp ; all its elements are uninitialized:
l e t a r r = new A r r a y ( 1 + 2 * 2 ) ;
co n s o l e . l o g ( a r r . l e n g t h ) ; / / p r i n t s : 5
co n s o l e . l o g ( a r r [ 0 ] ) ; / / p r i n t s : undefined
Let’s Recap: How Do We Create An Array?
[]: empty-array literal (expression):
l e t a r r n u m s = [ ] ; / / a r r n u m s i s an a r r a y w i t h z e r o e l e m e n t s .
co n s o l e . l o g ( a r r n u m s . l e n g t h ) ; / / p r i n t s 0
[ e1 ,. . .,en ]: creates an array with elements e1 ,. . .,en
l e t a r r s t r s = [ ” I ” , ” l o ve ” , ” prog ” + ” ramming ” , ” ! ” ] ;
co n s o l e . l o g ( a r r s t r s ) ;
/ / p r i n t s : [ ” I ” , ” l o v e ” , ” programming ” , ” ! ” ]
new Array(nexp ): an expression that creates a new array of length (determined by the
evaluation of expression) nexp ; all its elements are uninitialized:
l e t a r r = new A r r a y ( 1 + 2 * 2 ) ;
co n s o l e . l o g ( a r r . l e n g t h ) ; / / p r i n t s : 5
co n s o l e . l o g ( a r r [ 0 ] ) ; / / p r i n t s : undefined
new Array(nexp ).fill(vexp ): an expression that creates a new array of length nexp with
all elements initialized to the value resulted from the evaluation of expression vexp :
l e t a r r = new A r r a y ( 2 + 3 ) . f i l l ( 3 * 1 1 ) ;
co n s o l e . l o g ( a r r , l e n g t h ) ; / / p r i n t s : 5
co n s o l e . l o g ( a r r ) ; / / p r i n t s : [ 3 3 ,3 3 ,3 3 ,3 3 ,3 3 ]
Let’s Recap: How Do We Read and/or Modify an Array?
exp arr[exp ind]: returns the element at position exp ind from the array exp arr
exp arr is an expression whose evaluation produces an array;
exp ind is an expression whose evaluation produces an integer.
l e t a r r s t r s = [ ” I ” , ” l o ve ” , ” prog ” + ” ramming ” , ” ! ” ] ;
co n s o l e . l o g ( a r r s t r s [ a r r s t r s . l e n g t h −2] ) ;
l e t p e n u l t i m a t e e l e m e n t = a r r s t r s [ a r r s t r s . l e n g t h −2];
co n s o l e . l o g ( p e n u l t i m a t e e l e m e n t ) ;
What does it print?
Let’s Recap: How Do We Read and/or Modify an Array?
exp arr[exp ind]: returns the element at position exp ind from the array exp arr
exp arr is an expression whose evaluation produces an array;
exp ind is an expression whose evaluation produces an integer.
l e t a r r s t r s = [ ” I ” , ” l o ve ” , ” prog ” + ” ramming ” , ” ! ” ] ;
co n s o l e . l o g ( a r r s t r s [ a r r s t r s . l e n g t h −2] ) ;
l e t p e n u l t i m a t e e l e m e n t = a r r s t r s [ a r r s t r s . l e n g t h −2];
co n s o l e . l o g ( p e n u l t i m a t e e l e m e n t ) ;
What does it print? Prints: ”programming” twice
exp arr.push(exp elm): adds a new element (resulted from evaluating expression
exp elm) to the end of array exp arr:
a r r s t r s . push ( ” F a l s e ! ” ) ;
co n s o l e . l o g ( a r r s t r s . l e n g t h ) ; / / p r i n t s : 5
co n s o l e . l o g ( a r r s t r s ) ;
What does it print?
Let’s Recap: How Do We Read and/or Modify an Array?
exp arr[exp ind]: returns the element at position exp ind from the array exp arr
exp arr is an expression whose evaluation produces an array;
exp ind is an expression whose evaluation produces an integer.
l e t a r r s t r s = [ ” I ” , ” l o ve ” , ” prog ” + ” ramming ” , ” ! ” ] ;
co n s o l e . l o g ( a r r s t r s [ a r r s t r s . l e n g t h −2] ) ;
l e t p e n u l t i m a t e e l e m e n t = a r r s t r s [ a r r s t r s . l e n g t h −2];
co n s o l e . l o g ( p e n u l t i m a t e e l e m e n t ) ;
What does it print? Prints: ”programming” twice
exp arr.push(exp elm): adds a new element (resulted from evaluating expression
exp elm) to the end of array exp arr:
a r r s t r s . push ( ” F a l s e ! ” ) ;
co n s o l e . l o g ( a r r s t r s . l e n g t h ) ; / / p r i n t s : 5
co n s o l e . l o g ( a r r s t r s ) ;
What does it print? Prints: [”I”, ”love”, ”programming”, ”!”, ”False!”]
exp arr.pop(): removes the last element from the array (resulted from evaluating
the expression) exp arr and returns it:
l e t l a s t e l m = a r r s t r s . pop ( ) ;
co n s o l e . l o g ( a r r s t r s . l e n g t h ) ; / / p r i n t s : 4
co n s o l e . l o g ( l a s t e l m ) ; co n s o l e . l o g ( a r r s t r s ) ;
What does it print?
Let’s Recap: How Do We Read and/or Modify an Array?
exp arr[exp ind]: returns the element at position exp ind from the array exp arr
exp arr is an expression whose evaluation produces an array;
exp ind is an expression whose evaluation produces an integer.
l e t a r r s t r s = [ ” I ” , ” l o ve ” , ” prog ” + ” ramming ” , ” ! ” ] ;
co n s o l e . l o g ( a r r s t r s [ a r r s t r s . l e n g t h −2] ) ;
l e t p e n u l t i m a t e e l e m e n t = a r r s t r s [ a r r s t r s . l e n g t h −2];
co n s o l e . l o g ( p e n u l t i m a t e e l e m e n t ) ;
What does it print? Prints: ”programming” twice
exp arr.push(exp elm): adds a new element (resulted from evaluating expression
exp elm) to the end of array exp arr:
a r r s t r s . push ( ” F a l s e ! ” ) ;
co n s o l e . l o g ( a r r s t r s . l e n g t h ) ; / / p r i n t s : 5
co n s o l e . l o g ( a r r s t r s ) ;
What does it print? Prints: [”I”, ”love”, ”programming”, ”!”, ”False!”]
exp arr.pop(): removes the last element from the array (resulted from evaluating
the expression) exp arr and returns it:
l e t l a s t e l m = a r r s t r s . pop ( ) ;
co n s o l e . l o g ( a r r s t r s . l e n g t h ) ; / / p r i n t s : 4
co n s o l e . l o g ( l a s t e l m ) ; co n s o l e . l o g ( a r r s t r s ) ;
What does it print? Prints: ”False!”, then prints: [”I”, ”love”, ”programming”, ”!”]
Today’s Lecture
Strings
Arrays vs Strings
Array Cheat Sheet
Three Ways to Add One to Each Element of an Array
Multi-Dimensional Arrays
Online Programming
1st Version: Create an Empty Array and Push into It
Problem: write a function that returns a new array by adding one
to each element of an input array.
Textual description of the implementation plan:
declare a variable that is initialized to an empty array
(and is intended to hold the result array);
inside a for loop that traverses the elements of the input array do the following:
1 save the current element of the input array in a variable,
2 add one to the current element,
3 push the new element (resulted from step 2) to the end of the
result array;
return the result array.
1st Version: Create an Empty Array and Push into It
Problem: write a function that returns a new array by adding one
to each element of an input array.
Textual description of the implementation plan:
declare a variable that is initialized to an empty array
(and is intended to hold the result array);
inside a for loop that traverses the elements of the input array do the following:
1 save the current element of the input array in a variable,
2 add one to the current element,
3 push the new element (resulted from step 2) to the end of the
result array;
return the result array.
f u n c t i o n a d d O n e To Ar r a yVe r s i o n 1 ( i n p u t a r r a y ) {
l e t r e s u l t a r r a y = [ ] ; / / i n i t i a l i z e t h e r e s u l t a r r a y t o empty
for ( l e t i =0; i < i n p u t a r r a y . length ; i = i +1) {
l e t current element = i n p u t a r r a y [ i ] ;
l e t new element = c u r r e n t e l e m e n t + 1 ;
r e s u l t a r r a y . push ( new element ) ; / / append new e l e m e n t a t t h e end
}
return r e s ul t a r r ay ;
}
l e t a r r = [ 1 ,2 ,3 ,4 ,5 ] ;
co n s o l e . l o g ( a d d O n e To Ar r a yVe r s i o n 2 ( a r r ) ) ; / / P r i n t s : [ 2 , 3 , 4 , 5 , 6 ]
co n s o l e . l o g ( a r r ) ; / / P r i n t s : [ 1 ,2 ,3 ,4 ,5 ]
2nd Version: Create a New Array and Update its Elements
Problem: write a function that returns a new array by adding one
to each element of an input array.
Textual description of the implementation plan:
declare a variable that is initialized to an array of the same size as the input array
(and is intended to hold the result array);
inside a for loop that traverses the elements of the input array do the following:
1 save the current element of the input array in a variable,
2 add one to the current element,
3 assign to/update the current element of the result array to the value
resulted from step 2;
return the result array.
2nd Version: Create a New Array and Update its Elements
Problem: write a function that returns a new array by adding one
to each element of an input array.
Textual description of the implementation plan:
declare a variable that is initialized to an array of the same size as the input array
(and is intended to hold the result array);
inside a for loop that traverses the elements of the input array do the following:
1 save the current element of the input array in a variable,
2 add one to the current element,
3 assign to/update the current element of the result array to the value
resulted from step 2;
return the result array.
f u n c t i o n a d d O n e To Ar r a yVe r s i o n 2 ( i n p u t a r r a y ) {
l e t r e s u l t a r r a y = new A r r a y ( i n p u t a r r a y . l e n g t h ) ; // initialized
for ( l e t i =0; i < i n p u t a r r a y . length ; i = i +1) {
l e t current element = i n p u t a r r a y [ i ] ;
l e t new element = c u r r e n t e l e m e n t + 1 ;
r e s u l t a r r a y [ i ] = new element ; / / u p d a t e c u r r e n t element of r e s u l t
}
return r e s ul t a r r ay ;
}
l e t a r r = [ 1 ,2 ,3 ,4 ,5 ] ;
co n s o l e . l o g ( a d d O n e To Ar r a yVe r s i o n 2 ( a r r ) ) ; / / P r i n t s : [ 2 ,3 ,4 ,5 ,6 ]
co n s o l e . l o g ( a r r ) ; // Prints : [ 1 ,2 ,3 ,4 ,5 ]
3nd Version: Update the Input Array (In Place)
Problem: write a function that updates (i.e., in-place) all elements
of an input array by adding one to each of them.
Textual description of the implementation plan:
no initialization is required since we will update the input array in place,
inside a for loop that traverses the elements of the input array do the following:
1 save the current element of the input array in a variable,
2 add one to the current element,
3 assign to/update the current element of the input array to the value
resulted from step 2;
no need to return anything since the input array will be updated.
3nd Version: Update the Input Array (In Place)
Problem: write a function that updates (i.e., in-place) all elements
of an input array by adding one to each of them.
Textual description of the implementation plan:
no initialization is required since we will update the input array in place,
inside a for loop that traverses the elements of the input array do the following:
1 save the current element of the input array in a variable,
2 add one to the current element,
3 assign to/update the current element of the input array to the value
resulted from step 2;
no need to return anything since the input array will be updated.
f u n c t i o n a d d O n e To Ar r a yVe r s i o n 3 ( i n p u t a r r a y ) {
/ / no i n i t i a l i z a t i o n s i n c e we w i l l u p d a t e t h e i n p u t a r r a y i n p l a c e
for ( l e t i =0; i < i n p u t a r r a y . length ; i = i +1) {
l e t current element = i n p u t a r r a y [ i ] ;
l e t new element = c u r r e n t e l e m e n t + 1 ;
i n p u t a r r a y [ i ] = new element ; / / u p d a t e c u r r e n t e l e m e n t o f i n p u t
} / / no need t o r e t u r n a n y t h i n g
}
...
l e t a r r = [ 1 ,2 ,3 ,4 ,5 ] ;
a d d O n e To Ar r a yVe r s i o n 3 ( a r r ) ;
co n s o l e . l o g ( a r r ) ; / / p r i n t s [ 2 , 3 , 4 , 5 , 6 ]
Today’s Lecture
Strings
Arrays vs Strings
Array Cheat Sheet
Three Ways to Add One to Each Element of an Array
Multi-Dimensional Arrays
Online Programming
What is a Matrix (of numbers)?
The elements of an array can be, e.g., numbers or string or ...?
What is a Matrix (of numbers)?
The elements of an array can be, e.g., numbers or string or ...?
A matrix is an array whose elements are arrays of numbers.
an m × n matrix consists of m rows,
each row is represented by an array of n numeric elements,
the matrix is thus an array of length m of rows!
Write a function that return a string representation of a matrix:
What is a Matrix (of numbers)?
The elements of an array can be, e.g., numbers or string or ...?
A matrix is an array whose elements are arrays of numbers.
an m × n matrix consists of m rows,
each row is represented by an array of n numeric elements,
the matrix is thus an array of length m of rows!
Write a function that return a string representation of a matrix:
f u n ct i o n matrix2String ( matrix ) {
l e t r e s s t r = ” ” ; / / i n i t i a l i z e r e s u l t t o empty s t r i n g
f o r ( l e t i = 0 ; i < m a t r i x . l e n g t h ; i = i + 1 ) { / / l o o p o v e r m a t r i x ’ s r o ws
l e t row = m a t r i x [ i ] ; / / g e t t h e c u r r e n t row
/ / append t o r e s u l t a s t r i n g r e p r e s e n t a t i o n o f t h e row :
r e s s t r = r e s s t r + ” \ t [ ” + row . t o S t r i n g ( ) + ” ] \ n ”
}
return r e s s t r ;
}
l e t mat = [ [ 1 ,2 ,3 ] , [ 4 ,5 ,6 ] , [ 7 ,8 ,9 ] ] ;
l e t m a t s t r = m a t r i x 2 S t r i n g ( mat ) ;
co n s o l e . l o g ( m a t s t r ) ;
1st Version: Build a Matrix of Random Numbers by Push
A matrix is an array whose elements are arrays of numbers.
Creating a m × n matrix (2-dimensional array) of random numbers:
f u n c t i o n mkMa trixVe r1 (m, n ) {
l e t m a t r i x = [ ] ; / / i n i t i a l i z e t o empty a r r a y
f o r ( l e t i = 0 ; i < m; i = i + 1 ) { / / e a ch i t e r a t i o n b u i l d s a row :
l e t row = [ ] ; / / i n i t i a l i z e c u r r e n t row t o t h e empty a r r a y
for ( l e t j = 0; j < n ; j = j +1) {
/ / c r e a t e a random number between 0 and 1 ( e x c l u s i v e ) :
l e t new element = Math . random ( ) ;
/ / append t h e new e l e m e n t a t t h e end o f c u r r e n t row :
row . push ( new element ) ;
}
m a t r i x . push ( row ) ; / / add t h e new row ( e l e m e n t ) t o m a t r i x
}
return matrix ;
}
l e t mat = mkMa trixVe r1 ( 3 , 5 ) ;
co n s o l e . l o g ( m a t r i x 2 S t r i n g ( mat ) ) ;
2nd Version: Build a Matrix of Randoms by Update
A matrix is an array whose elements are arrays of numbers.
Creating a m × n matrix (2-dimensional array) of random numbers:
f u n c t i o n mkMa trixVe r2 (m, n ) {
l e t m a t r i x = new A r r a y (m ) ; / / i n i t i a l i z e t o an a r r a y o f l e n g t h m
f o r ( l e t i = 0 ; i < m; i = i + 1 ) {
/ / s e t e a ch m a t r i x row t o an u n i t i a l i z e d a r r a y o f s i z e n
m a t r i x [ i ] = new A r r a y ( n ) ;
}
/ / s e t e a ch e l e m e n t o f t h e m a t r i x t o a random numbers :
f o r ( l e t i = 0 ; i < m; i = i + 1 ) { / / f o r e a ch row i :
f o r ( l e t j = 0 ; j < n ; j = j + 1 ) { / / f o r e a ch column j :
/ / s e t t h e e l e m e n t a t row i and column j t o a new random :
m a t r i x [ i ] [ j ] = Math . random ( ) ;
}
}
return matrix ;
}
l e t mat = mkMa trixVe r2 ( 3 , 5 ) ;
co n s o l e . l o g ( m a t r i x 2 S t r i n g ( mat ) ) ;
Today’s Lecture
Strings
Arrays vs Strings
Array Cheat Sheet
Three Ways to Add One to Each Element of an Array
Multi-Dimensional Arrays
Online Programming
A Very Important Algorithm
Ci,j = Σq−1
k=0 Ai,k · Bk,j
What is the formula above?
A Very Important Algorithm
Ci,j = Σq−1
k=0 Ai,k · Bk,j
What is the formula above? Matrix Multiplication:
input: A is a m × q matrix and B is a q × n matrix,
result: C is a m × n matrix,
the element on row i and column j of C is computed by summing up all the products
Ai,k · Bk,j , where k = 0, . . . , q − 1.
A Very Important Algorithm
Ci,j = Σq−1
k=0 Ai,k · Bk,j
What is the formula above? Matrix Multiplication:
input: A is a m × q matrix and B is a q × n matrix,
result: C is a m × n matrix,
the element on row i and column j of C is computed by summing up all the products
Ai,k · Bk,j , where k = 0, . . . , q − 1.
f u n c t i o n matMult ( A , B ) {
l e t m = A . length ; l e t q = B . length ; l e t n = B [ 0 ] . length ;
/ / i n i t i a l i z e C t o a 2D a r r a y o f m x n u n i n i t i a l i z e d e l e m e n t s :
l e t C = new A r r a y (m ) ;
f o r ( l e t i = 0 ; i < m; i = i + 1 ) { C [ i ] = new A r r a y ( n ) ; }
f o r ( l e t i = 0 ; i < m; i = i + 1 ) { / / f o r e a ch row i :
f o r ( l e t j = 0 ; j < n ; j = j + 1 ) { / / f o r e a ch column j :
/ / compute and s e t t h e e l e m e n t o f C a t row i and column j :
l e t sum = 0 ;
for ( l e t k = 0; k < q ; k = k +1) {
sum = sum + A [ i ] [ k ] * B [ k ] [ j ] ;
}
C [ i ] [ j ] = sum ;
}
return C;
}
Summary
Array is a fundamental data-structure
(deep learning, quantum computing, . . .),
There are lots of goodies in the standard library for both
strings and arrays,
Matrices are just arrays whose elements are arrays,
three-dimensional arrays are arrays of arrays of arrays,
...
programming with one dimensional arrays extends naturally
to programming with multi-dimensional arrays:
a good example of language composibility!