Arrays and Matrices - Department of Computer Science

advertisement
CS 2073
Computer Programming w/Eng.
Applications
Ch 5
Arrays and Matrices
Turgay Korkmaz
Office: SB 4.01.13
Phone: (210) 458-7346
Fax: (210) 458-4437
e-mail: korkmaz@cs.utsa.edu
web: www.cs.utsa.edu/~korkmaz
1
Name Addr
Lecture++;
Lecture
Content
19
2
5.1 One-Dimensional Arrays

Suppose, you need to store years of 100
cars. Will you define 100 variables?
int y1, y2,…, y100;

An array is an indexed data structure to
represent several variables having the same
data type: int y[100];
y[0]
y[1]
y[2]
…
y[k-1]
y[k]
y[k+1]
…
y[98] y[99]
3
One-Dimensional Arrays
(cont’d)



An element of an array is accessed using the
array name and an index or subscript,
for example: y[5] which can be used like a variable
In C, the subscripts always start with 0 and
increment by 1, so y[5] is the sixth element
The name of the array is the address of the
first element and the subscript is the offset
y[0]
y[1]
y[2]
…
y[k-1]
y[k]
y[k+1]
…
y[98] y[99]
4
Definition and Initialization

An array is defined using a declaration
statement.
data_type array_name[size];




allocates memory for size elements
subscript of first element is 0
subscript of last element is size-1
size must be a constant
5
Example
int list[5];
list[0]
list[1]
list[2]
list[3]
list[4]





allocates memory for 5 integer variables
subscript of first element is 0
subscript of last element is 4
C does not check bounds on arrays
list[6] =5; /* may give segmentation fault
or overwrite other memory locations*/
6
Initializing Arrays


Arrays can be initialized at the time they
are declared.
Examples:
double taxrate[3] ={0.15, 0.25, 0.3};
char list[5] = {‘h’, ’e’, ’l’, ’l’, ’o’};
double vector[100] = {0.0};
/* assigns
zero to all 100 elements */
int s[] = {5,0,-5}; /*the size of s is 3*/
7
Assigning values to an array
For loops are often used to assign values to an array
list[0]
list[1]
list[2]
list[3]
Example:
int list[5], i;
for(i=0; i<5; i++){
list[i] = i;
}
OR
for(i=0; i<=4; i++){
list[i] = i;
}
list[4]
0
1
2
3
4
list[0]
list[1]
list[2]
list[3]
list[4]
8
Assigning values to an array
Give a for loop to assign the below values to list
4
3
2
1
0
list[0]
list[1]
list[2]
list[3]
list[4]
int list[5], i;
for(i=0; i<5; i++){
list[i] = 4-i;
}
9
Input from a data file
Arrays are often used to store information from a data file
int k;
double time[10], motion[10];
FILE *sensor3;
sensor3 = fopen(“sensor3.dat”, “r”);
for(k=0; k<10; k++) {
fscanf(sensor3, “%lf %lf”,
&time[k], &motion[k]);
}
10
Exercise
Show the contents of the arrays defined in
each of the following sets of statements.
int x[10] = {-5, 4, 3};
char letters[] = {'a', 'b', 'c'};
double z[4];
11
Exercise



int data[100], i;
Store random numbers [0,99] in data
for (i=0; i<100; i++)
data[i] = rand() % 100;
Store random numbers [10,109] in data
for (i=0; i<100; i++)
data[i] = (rand() % 100) + 10;
OR
for (i=0; i<100; i++)
data[i] = rand_int(10,109);
12
Computations on one-D arrays
13
Find Maximum

Find maximum value in data array
int data[100], max, i;
for (i=0; i<100; i++)
data[i] = rand_int(10,109);
max = data[0];
for (i=1; i<100; i++){
if (data[i] > max)
max = data[i];
}
printf("Max = %d\n",max);
14
Find average

Find average of values in data array
int data[100], sum, i, avg;
for (i=0; i<100; i++)
data[i] =
rand_int(10,109);
sum = 0;
for (i=0; i<100; i++){
sum = sum + data[i];
}
avg = (double)sum/100;
printf(“Avg = %lf\n", avg);
15
Number of elements greater
than average

After finding the average as shown in
previous slide, use the following code
count = 0;
for (i=0; i<100; i++){
if (data[i] > avg)
count++;
}
printf(“%d elements are “
“greater than avg”, count);
16
Find pair sum

Find sum of every pair in data and write into pair array
data[0]=5
data[1]=7
data[2]=15
data[3]=5
…
…
data[98]=3
data[99]=12
}
}
pair[0]=12
pair[1]=20
.
.
.
}
…
pair[49]=15
17
solution
int data[100], pair[50], i;
for (i=0; i<100; i++)
data[i] = rand_int(1,100);
for (i=0; i<50; i++){
pair[i]= data[2*i] + data[2*i+1];
}
18
Randomly re-shuffle numbers
30 times
data[0]=5
data[1]=7
data[2]=15
data[3]=5
…
…
data[98]=3
data[99]=12
.
.
.
data[0]=12
data[1]=7
data[2]=5
data[3]=15
…
…
data[98]=3
data[99]=5
19
solution
int data[100], i, j, k, tmp;
for (i=0; i<100; i++)
data[i] = rand_int(1,109);
for (n=0; n<30; n++){
i=rand_int(0,99);
j=rand_int(0,99);
tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
20
Copy array1 to array2 in
reverse order
0
1
2
3
4
5
array1
6
3
1
9
7
2
array2
2
7
9
1
3
6
21
Print sum of top-bottom pairs
A[0]=3
A[1]=6
…
A[49]=5
A[50]=3
A[98]=4
A[99]=5
+
….
+
+
22
Random numbers from an
irregular range


Suppose you want to generate 50
random numbers, but you want to
chose them uniformly from a set of
given numbers like 52 67 80 87 90 95
Can you do this using arrays?
23
Group avg


Suppose we have
a sorted array of
hundred grades.
We want to find
the average of
top ten, second
top ten students
etc.
Grade[0]
Grade[1]
….
Grade[9]
Grade[10]
…
Grade[19]
Grade[20]
…
Grade[90]
….
Grade[99]
}
}
}
24
Name Addr
Lecture++;
Lecture
Content
20
REVIEW
25
Name Addr
Lecture++;
Lecture
Content
21
MIDTERM 2
26
Name Addr
Lecture++;
Lecture
Content
22
27
Arrays as
Function Arguments
28
Function Arguments

Individual elements of an array can be passed
as regular arguments.
void donothing(int a, int b)
{
…
}
int main(void)
{
/* Declare variables and functions */
int array[5] = {1,2,3,4,5};
}
donothing(array[2], array[4]);
Calls donothing(3, 5);
29
Passing Arrays to Functions

Arrays are always pass by reference
Modifications to the array are reflected to main program
The array name is the address of the first element
The maximum size of the array must be specified at the
time the array is declared.
The actual number of array elements that are used will
vary, so the actual size of the array is usually passed as
another argument to the function




30
Exercise
main()
{
int a[2]={3, 5};
int c;
c = sum_arr(a, 2)
}
int sum_arr(int b[], int n)
{
int i, sum=0;
for(i=0; i < n; i++)
sum = sum + b[i];
return(sum);
}
a[0]=3
a[1]=5
c=? 8
b=
n=2
i=0 1 2
sum=0 3 8
31
Exercise
main()
{
int a[2]={3, 5};
int c;
c = sum_arr(a, 2)
}
int sum_arr(int b[], int n)
{
int i, sum=0;
for(i=0; i < n; i++)
sum = sum + b[i];
b[0] = 20;
return(sum);
}
a[0]=3 20
a[1]=5
c=? 8
b=
n=2
i=0 1 2
sum=0 3 8
32
Exercise
Write a function to find maximum value in the array data
int main()
{
int data[100],i, max;
int maximum(int fdata[],
int n)
{
int i, fmax;
fmax = fdata[0];
for (i=0; i<100; i++)
for (i=0; i<n; i++)
data[i] = rand() % 100;
if(fdata[i] > fmax)
fmax = fdata[i];
max = maximum(data,100);
return(fmax);
printf("Max = %d\n",max); }
return(0);
}
33
Exercise
What is the output of the following program?
void print(int pdata[], int n)
int main()
{
int i;
{
for (i=0; i<n; i++)
int data[10];
printf("data[%d]=%d\n",
i,pdata[i]);
for (i=0; i<10; i++)
return;
data[i] = rand() % 100; }
void modify(int fdata[], int n)
print(data,10);
{
int i;
modify(data,10);
for (i=0; i<n; i++)
print(data,10);
fdata[i] = 1;
return;
return(0);
34
}
}
Skip


Study 5.2, 5.3, and 5.5 from the
textbook.
We will go over section 5.4 Statistical
measurements in class
35
5.4 Statistical measurements



In engineering, analyzing the statistical
characteristics of data is important
Suppose we have an array of
measurements (double data)
Let us develop functions to compute
max, min, mean (average), median,
variance, std-dev of these measurements
36
max() and min()
double max(double x[], int n)
{
/* Declare variables. */
int k;
double max_x;
}
double min(double x[], int n)
{
/* Declare variables. */
int k;
double min_x;
/*
Determine maximum
value in the array. */
max_x = x[0];
for (k=1; k <= n-1; k++)
if (x[k] > max_x)
max_x = x[k];
/*
Determine minimum
value in the array. */
min_x = x[0];
for (k=1; k < n; k++)
if (x[k] < min_x)
min_x = x[k];
/* Return maximum value.*/
return max_x;
/* Return minimum value.*/
return min_x;
}
37
mean()
double mean(double x[], int n)
{
/* Declare variables. */
int k;
double sum;
/*
Determine sum of
values in the array. */
sum = x[0];
for (k=1; k<=n-1; k++)
sum = sum + x[k];
/* Return avg value.
return sum/n;
*/
}
38
median()
/* values in x must be sorted ! */
double median(double x[], int n)
{
/* Declare variables. */
int k;
double median_x;
/*
Determine median of
values in the array. */
k = floor(n/2);
if( n % 2 != 0)
median_x = x[k];
else
median_x = (x[k-1]+x[k])/2;
/* Return median value. */
return median_x;
}
Example:
x[]={7, 9, 15, 27, 29};
n=5;
median_x=15
x[]={3, 6, 7, 9};
n=4;
median_x=(6+7)/2
median_x=6.5
39
variance()
double variance(double x[], int n)
{
/* Declare variables. */
int k;
double mu, sum=0;
mu = mean(x, n);
for (k=0; k<=n-1; k++)
sum = sum + pow(x[k]-mu, 2);
/* Return variance value.
return sum/(n-1);
*/
}
40
std_dev()
double std_dev(double x[], int n)
{
/* Return standard deviation */
return sqrt(variance(x, n));
}
41
Name Addr
Lecture++;
Lecture
Content
23
42
5.6 Sorting an array
0
1
2
3
4
5
6
3
1
9
7
2
1
3
6
9
7
2
1
2
6
9
7
3
1
2
3
9
7
6
1
2
3
6
7
9
1
2
3
6
7
9
43
Selection Sort (solution 1)
void selection_sort(double x[], int n)
{
int k,j,m;
double temp;
}
for(k=0; k<=n-2; k++) {
m = k;
for(j=m+1; j<=n-1; j++)
if(x[j] < x[m])
m = j;
temp = x[k];
x[k] = x[m];
x[m] = temp
}
m = find_min_pos(x, n, k);
swap(x, k, m);
44
Selection Sort (solution 2)
void selection_sort(double x[], int n)
{
int k, m;
}
for(k=0; k<=n-2; k++){
m = find_min_pos(x, n, k);
swap(x, k, m);
}
45
Selection Sort cont’d
int find_min_pos(double fx[], int fn, int fk)
{
int j;
int m=fk;
for (j=m+1; i<=fn-1; j++)
if (fx[j] < fx[m])
m = j;
return(m);
}
46
Selection Sort cont’d
void swap(double sx[], int sk, int sm)
{
double temp;
temp = sx[sk];
sx[sk] = sx[sm];
sx[sm] = temp;
return;
}
47
Reverse an array
0
1
2
3
4
5
6
3
1
9
7
2
2
7
9
1
3
6
48
Reverse an Array
void reverse(double x[], int n)
{
int i=0, j=n-1;
while (i<j) {
swap(x,i,j);
i = i + 1;
j = j - 1;
}
return;
}
49
Merge two sorted array


Assume we have A and B arrays
containing sorted numbers
For example



A = { 3, 5, 7, 9, 12}
B = {4, 5, 10}
Merge these two arrays as a single
sorted array C, for example

C = {3, 4, 5, 5, 7, 9, 10, 12}
50
5.7 Search Algorithms

Unordered list



Linear search
In a loop compare each element in array
with the value you are looking for ()
Ordered list


Linear search
A better solution is known as Binary search
(but we will skip it this time, it is like
looking for a word in a dictionary)
51
Unordered list – linear search
int search1(int x[], int n, int value)
{
int i;
for(i=0; i < n; i++) {
if (x[i]== value)
return i;
}
return(-1);
}
52
Ordered list – linear search
int search2(int x[], int n, int value)
{
int i;
for(i=0; i < n; i++) {
if (x[i]== value)
return i;
else if (x[i] > value)
break;
}
return(-1);
}
53
Name Addr
Lecture++;
Lecture
Content
24
54
Strings (strings are discussed in
Section 6.6 of the textbook )

A string is an array of characters



Use printf to print strings


char data[10] = “Hello”;
char data2[] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’}
printf(“%s”,data);
Can be accessed char by char

data[0] is first character
H
End of String
Symbol
e
l
l
o
\0
0 1
2
3
4
5
data
6
7 8
9
55
Strings

Each character has an integer representation
a
b
c
d
e
…
…
…
…
z
97 98 99 100 101 ………………………112
A
B
C
65 66 67
0
1
2
D
E
…
…
…
…
Z
68 69 ……………………… 90
3
4
5
6
7
8
9
48 49 50 51 52 53 54 55 56 57
\0
0
\n
10
56
Strings

Characters can be interpreted as integers
char c = ‘A’;
printf(“%c \n”,c);
prints A
printf(“%d \n”,c);
prints 65
Printf(“%c \n”,65);
prints A
57
Exercise


Write a function to count the number of characters in
a string.
Idea: count the number of characters before \0
H
e
l
l
o
\0
58
Solution
int count_letters(char cdata[])
{
int i=0;
while (cdata[i] != '\0')
i = i + 1;
return(i);
}
59
Exercise


Write a function that prints a string in reverse
Idea: find the end of the string and print the
characters backwards.
H
e
l
l
o
\0
Output: olleH
60
Solution
void print_reverse(char pdata[])
{
int size,position;
size = count_letters(pdata);
position = size - 1;
while (position >= 0) {
printf("%c",pdata[position]);
position = position -1;
}
printf("\n");
return;
}
61
Exercise



Write a function that compares 2 strings S1 and S2
using lexicographic order.
Idea: compare character by character
Return



a neg value if S1 < S2,
0 if S1 == S2
a pos value if S1 > S2
H
e
l
l
o
\0
H
e
l
o
o
\0
l < o in lexicographic order
62
Solution (incomplete)
int compare(char cdata1[], char cdata2[])
{
int i= 0;
while (cdata1[i] == cdata2[i])
i = i + 1;
return (cdata1[i] - cdata2[i]);
}
63
Solution (complete)
int compare(char cdata1[], char cdata2[])
{
int i= 0;
while (cdata1[i] != ‘\0’ && cdata2[i] != ‘\0’
&& cdata1[i] == cdata2[i])
i = i + 1;
return (cdata1[i] - cdata2[i]);
}
64
Exercise: Spell out a number
in text using arrays of strings
Write a program that reads a number
between 1 and 999 from user and spells
out it in English.
For example:
 453
 Four hundred fifty three
 37
 Thirty seven
 204
 Two hundred four

65
Name Addr
Lecture++;
Lecture
Content
25
66
More Examples of one
dimensional arrays
67
Trace a program

Trace the following program and show how
variables change in memory.
int main()
{
int x[5]={3, 5, 3, 4, 5};
int i, j, count;
for(i = 0; i < 5; i++){
count = 1;
for(j = i+1; j < 5; j++){
if (x[i] == x[j]) count++;
}
printf(“%d %d \n”, x[i], count);
}
}
x[0]
3
x[1]
5
x[2]
3
x[3]
4
x[4]
5
i
?
j
?
count
?
68
Count how many times a
value appears in the array
int find_count(int cdata[], int n, int x)
{
int count = 0;
int i;
for (i = 0; i<n; i++){
if (cdata[i] == x)
6
3
1
9
7
2
count = count + 1;
1
2
3
0
4
5
}
return (count);
find_count(A,6,2) returns 1
}
find_count(A,4,2) returns 0
69
Insert unique RNs

Insert random numbers into an array so that each
number appears in the array at most once.
int A[6];
for (i=0; i<6; i++)
A[i] = rand() % 10;
6
3
1
9
A
6
2
Produces
Duplicates
70
Insert unique RNs (cont’s)

Insert random numbers into an array so that each
number appears in the array at most once.
void initialize(int idata[], int n)
{
6
int i=0, j, elem;
3
1
9
6
A
while (i<=n)
{
elem = rand() % 10;
if (find_count(idata,i,elem) == 0) {
Try a new
idata[i] = elem;
number
i = i + 1;
}
}
}
71
Intersection Set



Suppose we have two sets (groups) represented
by A and B
E.g., A is the set of students taking Math,
B is the set of students taking Science.
Find set C, the intersection of A and B, i.e.,
students taking both Math and Science
For each element ID in A
Search that ID in B
if found, put ID into C
3
9
7
6
1
2
4
5
8
72
Use arrays to represent A and B
Hand example
A
6
3
1
9
7
B
2
4
2
5
j=0 j=1 j=2
i=0
i=1
i=2
6
1
8
j=3
j=0 j=1 j=2 j=3 j=4 j=5 j=6
i=3 i=4 i=5 i=6 j=0 j=1 j=2 j=3 j=4
k=0 k=1 k=2 k=3
C
6
1
2
73
Solution
int intersection(int A[],int B[],
int C[], int n)
{
int i=0, j=0, k=0;
for(i=0; i < n; i++) {
for(j=0; j < n; j++) {
if (A[i]==B[j]){
C[k]=A[i];
k++;
break;
}
6
3
1
}
}
4
2
5
return(k);
6
1
2
}
9
7
2
6
1
8
74
Another Solution
int intersection(int A[], int B[],
int C[], int n)
{
int i=0, k=0, elem;
while (i < n) {
elem = A[i];
if(find_count(B,n,elem) == 1) {
C[k] = elem;
k = k + 1;
}
i = i + 1;
6
3
1
9
}
return(k);
4
2
5
6
}
6
1
2
7
2
1
8
75
What if A and B were sorted?
1
2
3
6
7
9
1
1




2
2
4
5
6
8
6
Will the previous solution work?
Yes, but we could find intersection set faster!
How?
See next slide
76
int sorted_intersection(int A[],int B[],
int C[], int n)
{
int i=0, j=0, k=0;
while( i < n && j < n ) {
if (A[i]==B[j]){
C[k]=A[i];
k++; i++; j++;
} else if (A[i] < B[j]) {
i++;
} else {
/* A[i] > B[j] */
j++;
}
}
return(k);
77
}
Exercise: union or difference



As in previous example suppose two
sets are given as arrays.
Find union and difference
For example




A={3,4,5} and B={2,3,5,7}
A U B = {2,3,4,5,7}
A – B = {4}
B – A = {2,7}
78
Exercise: Histogram


Suppose somehow we read npts integer
numbers from a file into an array declared by
int x[100]. We know that all the values are
integers between 0 and 10. Now suppose we
want to find how many 0’s ,1’s, …, 10’s exist in
the array x.
Write a function that will take x and npts as
the parameters and prints out the number of
0’s ,1’s, …, 10’s that exist in the array x
79
solution
void my_function(int x[], int npt)
{
int i, hist[11]={0};
for(i=0; i < npt; i++)
hist[x[i]]++;
for(i=0; i < 11; i++)
printf(“%d appears %d times\n”,
i, hist[i]);
return;
}
80
Number of Even values in a
given range


Suppose somehow we read 100 values from
a file into an array declared by int x[100].
We are now interested in finding the
number of even values in x that are happen
to be in a given range, say int Low=22,
High=53.
Write a function that will take x, Low, High
as parameters and return the number of
even values in x that are happen to be
between Low and High.
81
Exercise: strings (char array)

Write a function to check if v=“abcd”
appears in a given string A?
82
Name Addr
Lecture++;
Lecture
Content
26
83
5.8 Matrices (2D-array)


A matrix is a set of numbers arranged in a grid with rows and columns.
A matrix is defined using a type declaration statement.

datatype array_name[row_size][column_size];
4
1

int matrix[3][4];
0
4
1
0
2
2
Row 1
-1
2
4
3
2
Row 2
0
-1
3
1
3
Row 0
-1
4
0
-1
3
Column 0 Column 1
Column 2
Column 3
1
in memory 84
Accessing Array Elements
int matrix[3][4];
 matrix has 12 integer elements
 matrix[0][0] element in first row, first column
 matrix[2][3] element in last row, last column
 matrix is the address of the first element
 matrix[1] is the address of the Row 1
 matrix[1] is a one dimensional array (Row 1)
85
Initialization
int x[4][4] = {
int x[][4] = {
{2,
{7,
{5,
{2,
{2,
{7,
{5,
{2,
3,
4,
1,
5,
3,
4,
1,
5,
7, 2},
5, 9},
6, -3},
-1, 3}};
7, 2},
5, 9},
6, -3},
-1, 3}};
86
Initialization
int i, j, matrix[3][4];
for (i=0; i<3; i++)
for (j=0; j<4; j++)
matrix[i][j] = i;
matrix[i][j] = j;
j
0
i
1
j
2
3
0
0
0
0
0
1
1
1
1
1
2
2
2
2
2
0
0
i
1
2
0
0
0
1
1
1
1
2
2
2
2
3
3
3
3
87
Exercise

Write the nested loop to initialize a 2D
array as follow
0
1
1
2
2
3
2
3
4
3
4
5
int i, j, x[4][3];
for(i=0; i<4; i++)
for(j=0; j<3; j++)
x[i][j] = i+j;
88
2-Dim Arrays as Arguments to Functions
void print_m(int m[3][4],
int r, int c)
int i, j, matrix[3][4];
for (i=0; i<3; i++)
for (j=0; j<4; j++)
matrix[i][j] = i;
print_m(matrix, 3, 4);
void print_m(int m[][4],
int r, int c)
{
int i,j;
for (i=0; i < r; i++) {
for (j=0; j < c; j++)
printf("%.5d ",m[i][j]);
printf("\n");
}
printf("\n");
return;
}
89
Computations on 2D arrays
90
Max in 2D

Find the maximum of int matrix[3][4]
int max = matrix[0][0];
for (i=0; i<3; i++)
for (j=0; j<4; j++)
if (matrix[i][j] > max)
max = matrix[i][j];
0
0
0
1
1
2
0
3
2
1
-1
2
4
3
2
0
-1 3
1
91
Find a value in 2D

Find the number of times x appears in int matrix[3][4]
int count = 0;
for (i=0; i<3; i++)
for (j=0; j<4; j++)
if (matrix[i][j] == x)
count = count + 1;
0
0
0
1
1
2
0
3
2
1
-1
2
4
3
2
0
-1 3
1
92
Matrix sum

Compute the addition of two matrices
0
1
2
3
0
0
1
0
2
1
-1
2
4
3
2
0
-1 3
1
+
0
1
2
3
0
3
-1 3
1
1
1
4
2
0
2
2
1
1
3
0
=
0
3
1
0
2
3
3
3
1
0
6
6
3
2
2
0
4
4
93
solution
int matrix1[3][4],
matrix2[3][4],
sum[3][4];
// initialize matrix1 and matrix2
for (i=0; i<3; i++)
for (j=0; j<4; j++)
sum[i][j]= matrix1[i][j]+matrix2[i][j];
94
Exchange Two Rows
4
6
2
0
5
3
0
8
1
4
6
2
2
1
4
2
1
4
0
8
1
0
5
3
95
Transpose
a
1
5
3
4
2
6
void transpose(int a[NROWS][NCOLS],
int b[NCOLS][NROWS])
{
/* Declare Variables. */
int i, j;
/*
Transfer values to the
transpose matrix. */
for(i=0; i<NROWS; i++) {
for(j=0; j<NCOLS; j++) {
b[j][i] = a[i][j];
}
}
return;
b
1
4
5
2
3
6
}
96
mine sweeper



If m[i][j] is 0, there is no mine in cell m[i][j]
If m[i][j] is 1, there is a mine in cell m[i][j]
Print the number of mines around cell m[i][j]
[i][j]
97
Solution (1) - incomplete
count=0;
if(
m[i-1][j-1]
)
count++;
if(
m[i-1][j]
)
count++;
if(
m[i-1][j+1]
)
count++;
if(
m[i][j-1]
)
count++;
if(
m[i][j+1]
)
count++;
if(
m[i+1][j-1]
)
count++;
if(
m[i+1][j]
)
count++;
if(
m[i+1][j+1]
)
count++;
98
What if [i][j] is not in the
middle?
[i][j]
[i][j]
[i][j]
99
Solution (1) – complete
NR: is number of rows
NC: number of columns
count=0;
if( i>0 && j>0 &&
m[i-1][j-1]
) count++;
if( i>0 &&
m[i-1][j]
) count++;
if( i>0 && j<NC-1 &&
m[i-1][j+1]
) count++;
if( j>0 &&
m[i][j-1]
) count++;
if( j<NC-1 &&
m[i][j+1]
) count++;
if( i<NR-1 && j>0 &&
m[i+1][j-1]
) count++;
if( i<NR-1 &&
m[i+1][j]
) count++;
if( i<NR-1 && j<NC-1 &&
m[i+1][j+1]
) count++;
100
Solution (2)
NR: is number of rows, NC: number of columns
int r, c, count=0;
for(r=i-1; r <= i+1; r++) {
if (r < 0 || r >= NR) continue;
for(c=j-1; c <= j+1; c++) {
if (c < 0 || c >= NR) continue;
if (c == c) continue;
if( m[r][c]) count++;
}
}
101
Example:
Resize a picture


A b&w picture is usually represented using a two-dimensional array, where
each element (called pixel) of the array is an integer number denoting the
intensity of the light at a given pixel. Suppose we have a b&w picture with
the size of 100x200 pixels and we want to reduce its size to 50x100 pixels.
For this, we may consider 4 pixels from the original picture and take their
average to create one pixel in the new picture. For example:
4
5
3
2
1
0
6
1
6
1
2
3
2
10
6
2
4x6 original picture can be reduced to

4
3
1
5
2x3 resized picture
Write a function that takes orig[100][200] and resized[50][100] as
parameters and determines the values in resized picture as described above.
102
Matrix multiplication
double a[3][2], b[2][4], c[3][4];
 Find c = a * b;
3
5
1
4
2
6
x
2
3
7
1
4
5
6
8
=
22
29
45
35
18
40
47
21
26
33
43
49
3*2 + 4*4=22
3*3 + 4*5=29
3*7 + 4*6=45
3*1 + 4*8=35
5*2 + 2*4=18
5*3 + 2*5=40
5*7 + 2*6=47
5*1 + 2*8=21
1*2 + 6*4=26
1*3 + 6*5=33
1*7 + 6*6=43
1*1 + 6*8=49
103
Matrix Multiplication cont’d
j
j
0
1
2
i
3
5
1
0
4
2
6
x
1
2
3
2
3
7
1
4
5
6
8
1
2
3
0
22
29
45
35
= 1
18
40
47
21
2
26
33
43
49
i
j=0
i=0 3
0
4
x
2
4
c[i][j] =
k
=
a[i][k=0]*b[k=0][j] +
a[i][k=1]*b[k=1][j]
k
104
Matrix Multiplication cont’d
#define N 3
#define M 2
#define L 4
void matrix_mul(a[N][M], int b[M][L], int c[N][L])
{
int i, j, k;
for(i=0; i < N; i++) {
for(j=0; j < L; j++) {
c[i][j] = 0;
for(k=0; k < M; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
return;
}
105
Exercise: Find possible values
for cell s[i][j] in Sudoku
4
1
8
5
7
6
4
3
3
4
1
6
9
[i][j]
4
7
1
4
6
8
9
3
8
7
4
7
3
8
5
2
6
5
1
7
9
8
3
106
Exercise:
Dynamic programming
0
1
1
2
3
4
5
max
+
2
3
A[i][j] = max{A[i-1][j-1], A[i-1][j]+A[i][j-1]}
107
Exercise: Walks on 2d Arrays
write a code to print the values in the given order
x
x
x
x
x
x
x
x
x
x
x
x
x
108
Example:
Closest Points



3
2
1
1
2
Suppose somewhat we read 100 points in a 2-dimentional space (each point
is represented by (x,y)) and we store these points in an array declared by
double p[100][2] (you can think that p[i][0] is the x value and p[i][1] is
the y value of ith point).
We are now interested in finding the closest two points.
For example, if p[3][2] = {{1,1},
{2,1},
{1,3} };
Then we will say that points (1,1) and (2,1) are the closest two points.
Write a function that takes p[100][2] as a parameter and prints out the
closest two points. Suppose you have the following function:
double distance (double p1[ ], double p2[ ])
{
return sqrt( (p1[0]-p2[0])*(p1[0]-p2[0]) + (p1[1]-p2[1])*(p1[1]-p2[1]));
}
109
Skip





Study
Study
Study
Study
Study
Section
Section
Section
Section
Section
5.9 (terrain navigation)
5.10*
5.11* (optional)
5.12* (optional)
5.13* (optional)
110
Download