Transcript
ArraysArraysProcessing Sequences of ElementsProcessing Sequences of Elements
Svetlin NakovSvetlin NakovTelerik Telerik
CorporationCorporationwww.telerik.www.telerik.comcom
Table of ContentsTable of Contents
1.1. Declaring and Creating ArraysDeclaring and Creating Arrays
2.2. Accessing Array ElementsAccessing Array Elements
3.3. Console Input and Output of ArraysConsole Input and Output of Arrays
4.4. Iterating Over Arrays Using Iterating Over Arrays Using forfor and and foreachforeach
5.5. Matrices and Multidimensional Matrices and Multidimensional ArraysArrays
6.6. Dynamic ArraysDynamic Arrays Lists<T>Lists<T>
Copying ArraysCopying Arrays
Declaring and Declaring and Creating Creating Arrays Arrays
What are Arrays?What are Arrays?
An array is a sequence of elementsAn array is a sequence of elements All elements are of the same typeAll elements are of the same type The order of the elements is fixedThe order of the elements is fixed Has fixed size (Has fixed size (Array.LengthArray.Length))
0 1 2 3 40 1 2 3 4Array Array of 5 of 5
elemenelementsts
ElemeElement nt
indexindex
ElemenElement of an t of an arrayarray
…… …… …… …… ……
Declaring ArraysDeclaring Arrays
Declaration defines the type of the Declaration defines the type of the elementselements
Square brackets Square brackets [][] mean "array" mean "array" Examples:Examples:
Declaring array of integers:Declaring array of integers:
Declaring array of strings:Declaring array of strings:
int[] myIntArray;int[] myIntArray;
string[] myStringArray;string[] myStringArray;
Creating ArraysCreating Arrays
Use the operator Use the operator newnew Specify array lengthSpecify array length
Example creating (allocating) array Example creating (allocating) array of 5 integers:of 5 integers:
myIntArray = new int[5];myIntArray = new int[5];
myIntArraymyIntArray
managed heapmanaged heap(dynamic memory)(dynamic memory)
0 1 2 3 40 1 2 3 4
…… …… …… …… ……
Creating and Initializing Creating and Initializing ArraysArrays
Creating and initializing can be Creating and initializing can be done together:done together:
The The newnew operator is not required operator is not required when using curly brackets when using curly brackets initializationinitialization
myIntArray = {1, 2, 3, 4, 5};myIntArray = {1, 2, 3, 4, 5};
myIntArraymyIntArray
managed heapmanaged heap(dynamic memory)(dynamic memory)
0 1 2 3 40 1 2 3 4
…… …… …… …… ……
Creating Array – Creating Array – ExampleExample
Creating an array that contains the Creating an array that contains the names of the days of the weeknames of the days of the week
string[] daysOfWeek =string[] daysOfWeek ={{ "Monday","Monday", "Tuesday","Tuesday", "Wednesday","Wednesday", "Thursday","Thursday", "Friday","Friday", "Saturday","Saturday", "Sunday""Sunday"};};
Days of Days of WeekWeekLive DemoLive Demo
Accessing Array Accessing Array ElementsElements
Read and Modify Elements by IndexRead and Modify Elements by Index
How to Access Array How to Access Array Element?Element?
Array elements are accessed using Array elements are accessed using the square brackets operator the square brackets operator [][] (indexer)(indexer) Array indexer takes element’s index Array indexer takes element’s index
as parameteras parameter The first element has index The first element has index 00 The last element has index The last element has index Length-1Length-1
Array elements can be retrieved Array elements can be retrieved and changed by the and changed by the [][] operator operator
Reversing an Array – Reversing an Array – ExampleExample
Reversing the contents of an arrayReversing the contents of an array
int[] array = new int[] {1, 2, 3, 4, 5};int[] array = new int[] {1, 2, 3, 4, 5};
// Get array size// Get array sizeint length = array.Length;int length = array.Length;
// Declare and create the reversed array// Declare and create the reversed arrayint[] reversed = new int[length];int[] reversed = new int[length]; // Initialize the reversed array// Initialize the reversed arrayfor (int index = 0; index < length; index++)for (int index = 0; index < length; index++){{ reversed[length-index-1] = array[index];reversed[length-index-1] = array[index];}}
Reversing an Reversing an ArrayArray
Live DemoLive Demo
Arrays: Input and Arrays: Input and OutputOutputReading and Printing Arrays on the Reading and Printing Arrays on the
ConsoleConsole
Reading Arrays From the Reading Arrays From the ConsoleConsole
First, read from the console the First, read from the console the length of the arraylength of the array
Next, create the array of given Next, create the array of given size and read its elements in a size and read its elements in a forfor looploop
int n = int.Parse(Console.ReadLine());int n = int.Parse(Console.ReadLine());
int[] arr = new int[n];int[] arr = new int[n];for (int i=0; i<n; i++)for (int i=0; i<n; i++){{ arr[i] = int.Parse(Console.ReadLine());arr[i] = int.Parse(Console.ReadLine());}}
Symmetry Check – Symmetry Check – ExampleExample
Read Read intint array from the console array from the console and and check if it is symmetric:check if it is symmetric:
bool isSymmetric = true;bool isSymmetric = true;for (int i=0; i<(array.Length+1)/2; i++)for (int i=0; i<(array.Length+1)/2; i++){{ if (array[i] != array[n-i-1])if (array[i] != array[n-i-1]) {{ isSymmetric = false;isSymmetric = false; }}}}
11 22 33 22 1111 22 22 11 11 22 33 33 22 11
Symmetry CheckSymmetry CheckLive DemoLive Demo
Printing Arrays on the Printing Arrays on the ConsoleConsole
Process all elements of the arrayProcess all elements of the array Print each element to the consolePrint each element to the console Separate elements with white space Separate elements with white space
or a new lineor a new linestring[] array = {"one", "two", "three"};string[] array = {"one", "two", "three"};
// Process all elements of the array// Process all elements of the arrayfor (int index = 0; index < array.Length; index++)for (int index = 0; index < array.Length; index++){{ // Print each element on a separate line// Print each element on a separate line Console.WriteLine("element[{0}] = {1}",Console.WriteLine("element[{0}] = {1}", index, array[index]);index, array[index]);}}
Printing ArraysPrinting ArraysLive DemoLive Demo
Processing Array Processing Array Elements Using Elements Using forfor
and and foreachforeach
Processing Arrays: Processing Arrays: forfor StatementStatement
Use Use forfor loop to process an array loop to process an array whenwhen Need to keep track of the indexNeed to keep track of the index Processing is not strictly Processing is not strictly
sequential from the first to the last sequential from the first to the last elementelement
In the loop body use the element In the loop body use the element at the loop index (at the loop index (array[index]array[index]):):for (int index = 0; index < array.Length; for (int index = 0; index < array.Length; index++)index++){{ squares[index] = array[index] * squares[index] = array[index] * array[index];array[index];}}
Processing Arrays Using Processing Arrays Using forfor Loop – ExamplesLoop – Examples
Printing array of integers in Printing array of integers in reversed order:reversed order:
Initialize all array elements with Initialize all array elements with their corresponding index number:their corresponding index number:
Console.WriteLine("Reversed: ");Console.WriteLine("Reversed: ");for (int i = array.Length-1; i >= 0; i--)for (int i = array.Length-1; i >= 0; i--){{ Console.Write(array[i] + " ");Console.Write(array[i] + " ");}}// Result: 5 4 3 2 1// Result: 5 4 3 2 1
for (int index = 0; index < array.Length-1; for (int index = 0; index < array.Length-1; index++)index++){{ array[index] = index;array[index] = index;}}
Processing Arrays: Processing Arrays: foreachforeach
How How foreachforeach loop works? loop works?
typetype – the type of the element – the type of the element valuevalue – local name of variable – local name of variable arrayarray – processing array – processing array
Used when no indexing is neededUsed when no indexing is needed All elements are accessed one by All elements are accessed one by
oneone Elements can not be modified (read Elements can not be modified (read
only)only)
foreach (type value in array)foreach (type value in array)
Processing ArraysProcessing Arrays Using Using foreachforeach – –
ExampleExample Print all elements of a Print all elements of a string[]string[]
array:array:string[] capitals =string[] capitals ={{ "Sofia","Sofia", "Washington","Washington", "London","London", "Paris""Paris"};};foreach (string capital in capitals)foreach (string capital in capitals){{ Console.WriteLine(capital);Console.WriteLine(capital);}}
Processing ArraysProcessing ArraysLive DemoLive Demo
Multidimensional Multidimensional Arrays Arrays Using Array of Arrays, Matrices and Using Array of Arrays, Matrices and
CubesCubes
What is Multidimensional What is Multidimensional Array?Array?
Multidimensional arraysMultidimensional arrays have more have more than one dimension (2, 3, …)than one dimension (2, 3, …) The most important The most important
multidimensional arrays are the 2-multidimensional arrays are the 2-dimensionaldimensional Known as Known as matricesmatrices or or tablestables
Example of matrix of integers with Example of matrix of integers with 2 rows and 4 columns:2 rows and 4 columns:
55 00 -2-2 44
55 66 77 88
0 1 2 3
0
1
Declaring and Creating Declaring and Creating Multidimensional ArraysMultidimensional Arrays
Declaring multidimensional arrays:Declaring multidimensional arrays:
Creating a multidimensional arrayCreating a multidimensional array Use Use newnew keyword keyword Must specify the size of each Must specify the size of each
dimensiondimension
int[,] intMatrix;int[,] intMatrix;float[,] floatMatrix;float[,] floatMatrix;string[,,] strCube;string[,,] strCube;
int[,] intMatrix = new int[3, 4];int[,] intMatrix = new int[3, 4];float[,] floatMatrix = new float[8, 2];float[,] floatMatrix = new float[8, 2];string[,,] stringCube = new string[5, 5, 5];string[,,] stringCube = new string[5, 5, 5];
Initializing Initializing Multidimensional Arrays Multidimensional Arrays
with Valueswith Values Creating and initializing with values Creating and initializing with values
multidimensional array:multidimensional array:
Matrices are represented by a list of Matrices are represented by a list of rowsrows Rows consist of list of valuesRows consist of list of values
The first dimension comes first, the The first dimension comes first, the second comes next (inside the first)second comes next (inside the first)
int[,] matrix = int[,] matrix = {{ {1, 2, 3, 4}, // row 0 values{1, 2, 3, 4}, // row 0 values {5, 6, 7, 8}, // row 1 values{5, 6, 7, 8}, // row 1 values}; // The matrix size is 2 x 4 (2 rows, 4 }; // The matrix size is 2 x 4 (2 rows, 4 cols)cols)
Accessing The Elements of Accessing The Elements of Multidimensional ArraysMultidimensional Arrays
Accessing N-dimensional array Accessing N-dimensional array element:element:
Getting element value example:Getting element value example:
Setting element value example:Setting element value example:
nDimensionalArray[index1, … , indexn]nDimensionalArray[index1, … , indexn]
int[,] array = {{1, 2}, {3, 4}}int[,] array = {{1, 2}, {3, 4}}int element11 = array[1, 1]; //element11 = 4int element11 = array[1, 1]; //element11 = 4
int[,] array = new int[3, 4];int[,] array = new int[3, 4];for (int row=0; row<array.GetLength(0); row+for (int row=0; row<array.GetLength(0); row++)+) for (int col=0; col<array.GetLength(1); for (int col=0; col<array.GetLength(1); col++)col++) array[row, col] = row + col;array[row, col] = row + col;
NumbNumber of er of rowsrows
Number Number of of
columncolumnss
Reading Matrix – Reading Matrix – ExampleExample
Reading a matrix from the consoleReading a matrix from the console
int rows = int.Parse(Console.ReadLine());int rows = int.Parse(Console.ReadLine());int columns = int.Parse(Console.ReadLine());int columns = int.Parse(Console.ReadLine());int[,] matrix = new int[rows, columns];int[,] matrix = new int[rows, columns];String inputNumber;String inputNumber;for (int row=0; row<rows; row++)for (int row=0; row<rows; row++){{ for (int column=0; column<cols; column++)for (int column=0; column<cols; column++) {{ Console.Write("matrix[{0},{1}] = ", row, Console.Write("matrix[{0},{1}] = ", row, column);column); inputNumber = Console.ReadLine();inputNumber = Console.ReadLine(); matrix[row, column] = matrix[row, column] = int.Parse(inputNumber);int.Parse(inputNumber); }}}}
Printing Matrix – Printing Matrix – ExampleExample
Printing a matrix on the console:Printing a matrix on the console:
for (int row=0; row<matrix.GetLength(0); row+for (int row=0; row<matrix.GetLength(0); row++)+){{ for (int col=0; col<matrix.GetLength(1); for (int col=0; col<matrix.GetLength(1); col++)col++) {{ Console.Write("{0} ", matrix[row, col]);Console.Write("{0} ", matrix[row, col]); }} Console.WriteLine();Console.WriteLine();}}
Reading and Reading and Printing Printing MatricesMatrices
Live DemoLive Demo
Finding a 2 x 2 platform in a matrix Finding a 2 x 2 platform in a matrix with a maximal sum of its elementswith a maximal sum of its elementsint[,] matrix = {int[,] matrix = { {7, 1, 3, 3, 2, 1},{7, 1, 3, 3, 2, 1}, {1, 3, 9, 8, 5, 6},{1, 3, 9, 8, 5, 6}, {4, 6, 7, 9, 1, 0} {4, 6, 7, 9, 1, 0} };};int bestSum = int.MinValue;int bestSum = int.MinValue;for (int row=0; row<matrix.GetLength(0)-1; row++)for (int row=0; row<matrix.GetLength(0)-1; row++) for (int col=0; col<matrix.GetLength(1)-1; col+for (int col=0; col<matrix.GetLength(1)-1; col++)+) {{ int sum = matrix[row, col] + matrix[row, int sum = matrix[row, col] + matrix[row, col+1] col+1]
+ matrix[row+1, col] + matrix[row+1, col+1];+ matrix[row+1, col] + matrix[row+1, col+1]; if (sum > bestSum)if (sum > bestSum) bestSum = sum;bestSum = sum; }}
Maximal Platform – Maximal Platform – ExampleExample
Maximal Maximal PlatformPlatform
Live DemoLive Demo
Dynamic Dynamic ArraysArraysList<T>List<T>
ListsLists ListsLists are arrays that resize dynamicallyare arrays that resize dynamically
When adding or removing elementsWhen adding or removing elements Also have indexers ( like Also have indexers ( like ArrayArray)) TT is the type that the List will hold is the type that the List will hold
E.g. E.g. List<int>List<int> will hold will hold integersintegers List<object>List<object> will hold will hold objectsobjects
Basic Methods and PropertiesBasic Methods and Properties Add(TAdd(T element)element) – adds new element to the – adds new element to the endend
Remove(element)Remove(element) – removes the element – removes the element CountCount – returns the – returns the current size of the current size of the ListList
List Example List Example List<int> intList=new List<int>();List<int> intList=new List<int>();for( int i=0; i<5; i++)for( int i=0; i<5; i++){{ intList.Add(i);intList.Add(i);}}
38
int[] intArray=new int[5];int[] intArray=new int[5];for( int i=0; i<5; i++)for( int i=0; i<5; i++){{ intArray[i] = i;intArray[i] = i;}}
Is the same asIs the same as
The main differenceThe main difference When using lists we don't have to When using lists we don't have to
know the exact number of know the exact number of elementselements
Lists vs. ArraysLists vs. Arrays Lets have an array with capacity of Lets have an array with capacity of
5 elements5 elements
If we want to add a sixth element If we want to add a sixth element ( we have already added 5) we have ( we have already added 5) we have to doto do
With List we simply doWith List we simply do 39
int[] intArray=new int[5];int[] intArray=new int[5];
int[] copyArray = intArray;int[] copyArray = intArray;intArray = new int[6];intArray = new int[6];for (int i = 0; i < 5; i++)for (int i = 0; i < 5; i++){{ intArray[i] = copyArray[i];intArray[i] = copyArray[i];}}intArray[5]=newValue;intArray[5]=newValue;
list.Add(newValue);list.Add(newValue);
Lists <T>Lists <T>Live DemoLive Demo
40
Copying ArraysCopying ArraysThe Array ClassThe Array Class
Copying ArraysCopying Arrays Sometimes we must copy the values Sometimes we must copy the values
from one array to another onefrom one array to another one If we do it the intuitive way wIf we do it the intuitive way we would e would
copy not only the values but the copy not only the values but the reference to the arrayreference to the array Changing some of the values in one array Changing some of the values in one array
will affect the otherwill affect the other
The way to avoid this is using The way to avoid this is using Array.Copy()Array.Copy()
This way only the values will be copied This way only the values will be copied but not the referencebut not the reference
Array.Copy(sourceArray, copyArray);Array.Copy(sourceArray, copyArray);
int[] copyArray=array;int[] copyArray=array;
SummarySummary Arrays are a fixed-length sequences Arrays are a fixed-length sequences
of elements of the same typeof elements of the same type Array elements are accessible by Array elements are accessible by
indexindex Can be read and modifiedCan be read and modified
Iteration over array elements can Iteration over array elements can be done with be done with forfor and and foreachforeach loops loops
Matrices (2-dimensional arrays) are Matrices (2-dimensional arrays) are very useful for presenting tabular very useful for presenting tabular datadata
QuestionsQuestions??
QuestionsQuestions??
ArraysArrays
http://academy.telerik.com
ExercisesExercises
1.1. Write a program that allocates array of 20 Write a program that allocates array of 20 integers and initializes each element by its integers and initializes each element by its index multiplied by 5. Print the obtained array index multiplied by 5. Print the obtained array on the console.on the console.
2.2. Write a program that reads two arrays from Write a program that reads two arrays from the console and compares them element by the console and compares them element by element.element.
3.3. Write a program that compares two Write a program that compares two charchar arrays lexicographically (letter by letter).arrays lexicographically (letter by letter).
4.4. Write a program that finds the maximal Write a program that finds the maximal sequence of equal elements in an array.sequence of equal elements in an array.
Example: {2, 1, 1, 2, 3, 3, Example: {2, 1, 1, 2, 3, 3, 2, 2, 22, 2, 2, 1} , 1} {2, 2, {2, 2, 2}.2}.
Exercises (2)Exercises (2)5.5. Write a program that finds the maximal Write a program that finds the maximal
increasing sequence in an array. Example: increasing sequence in an array. Example: {3, {3, 2, 3, 42, 3, 4, 2, 2, 4} , 2, 2, 4} {2, 3, 4}. {2, 3, 4}.
6.6. Write a program that reads two integer Write a program that reads two integer numbers N and K and an array of N numbers N and K and an array of N elements from the console. Find in the elements from the console. Find in the array those K elements that have maximal array those K elements that have maximal sum.sum.
7.7. Sorting an array means to arrange its Sorting an array means to arrange its elements in increasing order. Write a elements in increasing order. Write a program to sort an array. Use the program to sort an array. Use the "selection sort" algorithm: Find the "selection sort" algorithm: Find the smallest element, move it at the first smallest element, move it at the first position, find the smallest from the rest, position, find the smallest from the rest, move it at the second position, etc.move it at the second position, etc.
Exercises (3)Exercises (3)
8.8. Write a program that finds the sequence of Write a program that finds the sequence of maximal sum in given array. Example:maximal sum in given array. Example:
{2, 3, -6, -1, {2, 3, -6, -1, 2, -1, 6, 42, -1, 6, 4, -8, 8} , -8, 8} {2, -1, 6, 4} {2, -1, 6, 4}
Can you do it with only one loop (with single Can you do it with only one loop (with single scan through the elements of the array)?scan through the elements of the array)?
9.9. Write a program that finds the most frequent Write a program that finds the most frequent number in an array. Example:number in an array. Example:
{{44, 1, 1, , 1, 1, 44, 2, 3, , 2, 3, 44, , 44, 1, 2, , 1, 2, 44, 9, 3} , 9, 3} 4 (5 4 (5 times)times)
10.10.Write a program that finds in given array of Write a program that finds in given array of integers a sequence of given sum S (if integers a sequence of given sum S (if present). Example:present). Example: {4, 3, 1, {4, 3, 1, 4, 2, 54, 2, 5, 8}, , 8}, S=11 S=11 {4, 2, 5} {4, 2, 5}
Exercises (4)Exercises (4)
11.11.Write a program that fills and prints a Write a program that fills and prints a matrix of size (n, n) as shown below: matrix of size (n, n) as shown below: (examples for n = 4)(examples for n = 4)
11 55 99 1313
22 66 1010 1414
33 77 1111 1515
44 88 1212 1616
77 1111 1414 1616
44 88 1212 1515
22 55 99 1313
11 33 66 1010
11 88 99 1616
22 77 1010 1515
33 66 1111 1414
44 55 1212 1313
11 1212 1111 1010
22 1313 1616 99
33 1414 1515 88
44 55 66 77
a) b)
c) d)
Exercises (5)Exercises (5)
12.12.Write a program that reads a Write a program that reads a rectangular matrix of size N x M and rectangular matrix of size N x M and finds in it the square 3 x 3 that has finds in it the square 3 x 3 that has maximal sum of its elements.maximal sum of its elements.
13.13.We are given a matrix of strings of size We are given a matrix of strings of size N x M. N x M. Sequences in the matrix Sequences in the matrix we we define as sets of several neighbor define as sets of several neighbor elements located on the same line, elements located on the same line, column or diagonal. Write a program column or diagonal. Write a program that finds the longest sequence of that finds the longest sequence of equal strings in the matrix. Examples:equal strings in the matrix. Examples:haha fiffif
iihhoo hihi
fofo hhaa hihi xx
xx
xxxxxx
hhoo
hhaa
xxxx
ss qqqq ss
pppp
pppp ss
pppp
qqqq ss
ha, ha, ha s, s, s
Exercises (6)Exercises (6)
14.14.Write a program that finds the index of given Write a program that finds the index of given element in a sorted array of integers by using element in a sorted array of integers by using the the binarybinary searchsearch algorithm (find it in algorithm (find it in Wikipedia).Wikipedia).
15.15.Write a program that creates an array Write a program that creates an array containing all letters from the alphabet (A-Z). containing all letters from the alphabet (A-Z). Read a word from the console and print the Read a word from the console and print the index of each of its letters in the array.index of each of its letters in the array.
16.16.Write a program that sorts an array of integers Write a program that sorts an array of integers using the using the mergemerge sort algorithm (find it in sort algorithm (find it in Wikipedia).Wikipedia).
17.17.Write a program that sorts an array of strings Write a program that sorts an array of strings using the using the quickquick sortsort algorithm (find it in algorithm (find it in Wikipedia).Wikipedia).
Exercises (7)Exercises (7)
18.18.Write a program that finds all prime numbers Write a program that finds all prime numbers in the range in the range [1...10 000 000].[1...10 000 000]. Use the sieve of Use the sieve of Eratosthenes algorithm (find it in Wikipedia).Eratosthenes algorithm (find it in Wikipedia).
19.19.* We are given an array of integers and a * We are given an array of integers and a number S. Write a program to find if there number S. Write a program to find if there exists a subset of the elements of the array exists a subset of the elements of the array that has a sum S. Example:that has a sum S. Example:
arrarr={2, ={2, 11, , 22, 4, 3, , 4, 3, 55, 2, , 2, 66}, S=14 }, S=14 yes yes (1+2+5+6)(1+2+5+6)
20.20.* Write a program that reads three integer * Write a program that reads three integer numbers N, K and S and an array of N elements numbers N, K and S and an array of N elements from the console. Find in the array a subset of from the console. Find in the array a subset of K elements that have sum S or indicate about K elements that have sum S or indicate about its absence.its absence.
Exercises (8)Exercises (8)
21.21.* Write a program that reads an array of * Write a program that reads an array of integers and removes from it a minimal integers and removes from it a minimal number of elements in such way that the number of elements in such way that the remaining array is sorted in increasing remaining array is sorted in increasing order. Print the remaining sorted array. order. Print the remaining sorted array. Example:Example:
{6, {6, 11, 4, , 4, 33, 0, , 0, 33, 6, , 6, 44, , 55} } {1, 3, 3, 4, 5} {1, 3, 3, 4, 5}
22.22.* Write a program that reads a number N * Write a program that reads a number N and generates and prints all the and generates and prints all the permutations of the numbers [1 … N]. permutations of the numbers [1 … N]. Example:Example:
n = 3 n = 3 {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}1}, {3, 1, 2}, {3, 2, 1}
Exercises (9)Exercises (9)
23.23.Write a program that reads two numbers N Write a program that reads two numbers N and K and generates all the variations of K and K and generates all the variations of K elements from the set [1..N]. Example:elements from the set [1..N]. Example:
N = 3, K = 2 N = 3, K = 2 {1, 1}, {1, 2}, {1, 3}, {2, {1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}
24.24.Write a program that reads two numbers N Write a program that reads two numbers N and K and generates all the combinations of and K and generates all the combinations of K distinct elements from the set [1..N]. K distinct elements from the set [1..N]. Example:Example:
N = 5, K = 2 N = 5, K = 2 {1, 2}, {1, 3}, {1, 4}, {1, {1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 3}, {2, 4}, {2, 5}, {3, 4}, {3, 5}, 5}, {2, 3}, {2, 4}, {2, 5}, {3, 4}, {3, 5}, {4, 5}{4, 5}
Exercises (10)Exercises (10)
25.25.Write a program that fills a matrix of Write a program that fills a matrix of size (N, N) as shown in the examples size (N, N) as shown in the examples (for N(for N=4=4):):1616 1515 1313 1010
1414 1212 99 66
1111 88 55 33
77 44 22 11
77 1111 1414 1616
44 88 1212 1515
22 55 99 1313
11 33 66 1010
1010 1111 1212 1313
99 22 33 1414
88 11 44 1515
77 66 55 1616
11 1212 1111 1010
22 1313 1616 99
33 1414 1515 88
44 55 66 77
a) b)
*c) *d)
Exercises (11)Exercises (11)
26.26.* Write a program that finds the largest area * Write a program that finds the largest area of equal neighbor elements in a rectangular of equal neighbor elements in a rectangular matrix and prints its size. Example:matrix and prints its size. Example:
Hint: you can use the algorithm "Depth-first Hint: you can use the algorithm "Depth-first search" or "Breadth-first search" (find them search" or "Breadth-first search" (find them in Wikipedia).in Wikipedia).
11 33 22 22 22 44
33 33 33 22 44 44
44 33 11 22 33 33
44 33 11 33 33 11
44 33 33 33 11 11
13
top related