Processing Sequences of Elements Technical Trainer Telerik Corporation www.telerik.com Doncho Minkov.

Slides:



Advertisements
Similar presentations
Lists, Stacks, Queues Svetlin Nakov Telerik Corporation
Advertisements

Generics, Lists, Interfaces
Arrays.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
Elementary Data Structures: Part 2: Strings, 2D Arrays, Graphs
Pointers in C Rohit Khokher
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
Arrays. Topics Tables of Data Arrays – Single Dimensional Parsing a String into Multiple Tokens Arrays - Multi-dimensional.
For use of IST410 Students only Arrays-1 Arrays. For use of IST410 Students only Arrays-2 Objectives l Declaring arrays l Instantiating arrays l Using.
Java: How to Program Arrays and ArrayLists Summary Yingcai Xiao.
Arrays. A group of data with same type stored under one variable. It is assumed that elements in that group are ordered in series. In C# language arrays.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Chapter 8 Arrays and Strings
Chapter 9 Introduction to Arrays
Arrays (Part II). Two- and Multidimensional Arrays Two-dimensional array: collection of a fixed number of components (of the same type) arranged in two.
1.7 Arrays academy.zariba.com 1. Lecture Content 1.Basic Operations with Arrays 2.Console Input & Output of Arrays 3.Iterating Over Arrays 4.List 5.Cloning.
Lists, Stacks, Queues Svetlin Nakov Telerik Corporation
Processing Matrices and Multidimensional Tables Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Java Unit 9: Arrays Declaring and Processing Arrays.
Subroutines in Computer Programming Svetlin Nakov Telerik Corporation
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
INF120 Basics in JAVA Programming AUBG, COS dept, Spring 2014 Lecture 10 Title: Arrays, Part 2 Multidimensional Arrays Reference: MalikFarrell, chap 1,
Subroutines in Computer Programming Svetlin Nakov Telerik Corporation
C Static Arrays Pepper. What is an array? Memory locations – same type – next to each other (contiguous) – Same name – Indexed by position number of type.
Processing Sequences of Elements Svetlin Nakov Telerik Corporation
Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
CHAPTER: 12. Array is a collection of variables of the same data type that are referenced by a common name. An Array of 10 Elements of type double.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
Multidimensional Arrays, Sets, Dictionaries Processing Matrices, Multidimensional Arrays, Dictionaries, Sets SoftUni Team Technical Trainers Software University.
Class Opener:. Identifying Matrices Student Check:
Arrays, Lists, Stacks, Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Unit 12 JavaScript Arrays Instructor: Brent Presley.
Section 3 - Arrays and Methods. Arrays Array: collection of group of data variables of same type, sharing the same name for convenience - Easy to search.
Arrays. Collections We would like to be able to keep lots of information at once Example: Keep all the students in the class Grade each one without writing.
Processing Sequences of Elements Technical Trainer Telerik Corporation Doncho Minkov.
Computer Science: A Structured Programming Approach Using C1 8-7 Two-Dimensional Arrays The arrays we have discussed so far are known as one- dimensional.
C# E1 CSC 298 Arrays in C#. C# E2 1D arrays  A collection of objects of the same type  array of integers of size 10 int[] a = new int[10];  The size.
Computer Programming for Engineers
Multidimensional Arrays Computer and Programming.
Processing Matrices and Multidimensional Tables Telerik Software Academy C# Fundamentals – Part 2.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Visual C# 2005 Using Arrays. Visual C# Objectives Declare an array and assign values to array elements Initialize an array Use subscripts to access.
1.8 Multidimensional Arrays academy.zariba.com 1.
MULTI-DIMENSIONAL ARRAYS 1. Multi-dimensional Arrays The types of arrays discussed so far are all linear arrays. That is, they all dealt with a single.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
ARRAYS Multidimensional realities Image courtesy of
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
Lists and Matrices Lists: Variable-Size Arrays Matrices: Arrays of Arrays (Tables) SoftUni Team Technical Trainers Software University
Module 5: Programming with C#. Overview Using Arrays Using Collections Using Interfaces Using Exception Handling Using Delegates and Events.
Processing Sequences of Elements
Lecture 10 Collections Richard Gesick.
Chapter 6: Using Arrays.
Computing with C# and the .NET Framework
Arrays, Lists, Stacks, Queues
Multidimensional Arrays
C# Arrays.
Chapter 5: Programming with C#
Multidimensional Arrays
C# Programming Arrays in C# Declaring Arrays of Different Types Initializing Array Accessing Array Elements Creating User Interfaces Using Windows Standards.
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
JavaScript Arrays.
Multidimensional array
Fundaments of Game Design
Arrays and Strings CSCI293 - C# September 26, 2005.
Presentation transcript:

Processing Sequences of Elements Technical Trainer Telerik Corporation Doncho Minkov

1. Matrices and Multidimensional Arrays  Declaring  Usage 2. Jagged Arrays  Declaring  Usage 3. The Array Class  Sorting  Binary Search 2

Using Array of Arrays, Matrices and Cubes

 Multidimensional arrays have more than one dimension (2, 3, …)  The most important multidimensional arrays are the 2-dimensional  Known as matrices or tables  Example of matrix of integers with 2 rows and 4 columns:

 Declaring multidimensional arrays:  Creating a multidimensional array  Use new keyword  Must specify the size of each dimension int[,] intMatrix; float[,] floatMatrix; string[,,] strCube; int[,] intMatrix = new int[3, 4]; float[,] floatMatrix = new float[8, 2]; string[,,] stringCube = new string[5, 5, 5]; 5

 Creating and initializing with values multidimensional array:  Matrices are represented by a list of rows  Rows consist of list of values  The first dimension comes first, the second comes next (inside the first) 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 cols) 6

 Accessing N-dimensional array element:  Getting element value example:  Setting element value example: nDimensionalArray[index1, …, indexn] int[,] array = {{1, 2}, {3, 4}} int element11 = array[1, 1]; // element11 = 4 int[,] array = new int[3, 4]; for (int row=0; row<array.GetLength(0); row++) for (int col=0; col<array.GetLength(1); col++) for (int col=0; col<array.GetLength(1); col++) array[row, col] = row + col; array[row, col] = row + col; Number of rows Number of columns 7

 Reading a matrix from the console int rows = int.Parse(Console.ReadLine()); int columns = int.Parse(Console.ReadLine()); int[,] matrix = new int[rows, columns]; String inputNumber; 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, column); Console.Write("matrix[{0},{1}] = ", row, column); inputNumber = Console.ReadLine(); inputNumber = Console.ReadLine(); matrix[row, column] = int.Parse(inputNumber); matrix[row, column] = int.Parse(inputNumber); }} 8

 Printing a matrix on the console: for (int row=0; row<matrix.GetLength(0); row++) { for (int col=0; col<matrix.GetLength(1); col++) for (int col=0; col<matrix.GetLength(1); col++) { Console.Write("{0} ", matrix[row, col]); Console.Write("{0} ", matrix[row, col]); } Console.WriteLine(); Console.WriteLine();} 9

Live Demo

 Finding a 2 x 2 platform in a matrix with a maximal sum of its elements 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; 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, col+1] + matrix[row+1, col] + matrix[row+1, col+1]; int sum = matrix[row, col] + matrix[row, col+1] + matrix[row+1, col] + matrix[row+1, col+1]; if (sum > bestSum) if (sum > bestSum) bestSum = sum; bestSum = sum; } 11

Live Demo

What are Jagged Arrays and How to Use Them?

 Jagged arrays are like multidimensional arrays  But each dimension has different size  A jagged array is array of arrays  Each of the arrays has different length  How to create jagged array? int[][] jagged = new int[3][]; jagged[0] = new int[3]; jagged[1] = new int[2]; jagged[2] = new int[5]; 14

 When creating jagged arrays  Initially the array is created of null arrays  Need to initialize each of them int[][] jagged=new int[n][]; for (int i=0; i<n; i++) { jagged[i] = new int[i]; } jagged[i] = new int[i]; } 15

Live Demo

 Check the numbers of a set with remainders 0,1,2 when dividing to 3  Example  1, 2, 3, 4, 55, 66, 113, 124, 557  First we need to count the numbers  Done with a iteration  Make jagged array with appropriate sizes  When finding such a number  Add it to the array 17

foreach (var number in numbers) { int remainder = number % 3; int remainder = number % 3; sizes[remainder]++; sizes[remainder]++;}… foreach (var number in numbers) { int remainder = number % 3; int remainder = number % 3; int index = positions[remainder]; int index = positions[remainder]; numbersByRemainder[remainder][index] = number; numbersByRemainder[remainder][index] = number; positions[remainder]++; positions[remainder]++;} 18

Live Demo

What Can We Use?

 Parent of all arrays  All arrays inherit Array  All arrays have the same:  Basic functionality  Basic properties 21

Methods of ArrayMethods of Array  Important methods and properties of System.Array  Rank – number of dimensions  Length – number of all elements through all dimensions  GetLength(index) – returns the number of elements in the specified dimension  Dimensions are numbered from 0 22

Methods of Array (2)Methods of Array (2)  GetEnumerator() – returns IEnumerator for the array elements  BinarySearch(…) – searches for a given element into a sorted array (uses binary search)  IndexOf(…) – searches for a given element and returns the index of the first occurrence (if any)  LastIndexOf(…) – searches for a given element and returns the last occurrence index  Copy(src, dest, len) – copies array elements; has many overloads 23

Methods of Array (3)Methods of Array (3)  Reverse(…) – inverts the arrays elements upside down  Clear(…) – assigns value 0 (null) for each elements  CreateInstance(…) – creates an array  Accepts as parameters the number of dimensions, start index and number of elements  Implements ICloneable, IList, ICollection and IEnumerable interfaces 24

Sorting ArraysSorting Arrays

 Sorting in.NET is usually done with System.Array.Sort()  Sort(Array) – sorts array elements  Elements should implement IComparable  Sort(Array, IComparer) – sorts array elements by given external IComparer  Sort(Array, Comparison ) – sorts array elements by given comparison operation  Can be used with lambda expression 26

Sorting Arrays – ExampleSorting Arrays – Example 27 static void Main() { String[] beers = {"Zagorka", "Ariana", String[] beers = {"Zagorka", "Ariana", "Shumensko","Astika", "Kamenitza", "Bolqrka", "Shumensko","Astika", "Kamenitza", "Bolqrka", "Amstel"}; "Amstel"}; Console.WriteLine("Unsorted: {0}", Console.WriteLine("Unsorted: {0}", String.Join(", ", beers)); String.Join(", ", beers)); // Elements of beers array are of String type, // Elements of beers array are of String type, // which implement IComparable // which implement IComparable Array.Sort(beers); Array.Sort(beers); Console.WriteLine("Sorted: {0}", Console.WriteLine("Sorted: {0}", String.Join(", ", beers)); String.Join(", ", beers)); // Result: Sorted: Amstel, Ariana, Astika, // Result: Sorted: Amstel, Ariana, Astika, // Bolyarka, Kamenitza, Shumensko, Zagorka // Bolyarka, Kamenitza, Shumensko, Zagorka}

Sorting with IComparer and Lambda Expressions – Example 28 class Student { …} public class StudentAgeComparer : IComparer public class StudentAgeComparer : IComparer { public int Compare(Student firstStudent, Student secondStudent) public int Compare(Student firstStudent, Student secondStudent) { return firstStudent.Age.CompareTo(secondStudent.Age); return firstStudent.Age.CompareTo(secondStudent.Age); }}… Array.Sort(students, new StudentAgeComparer()); … Array.Sort(students, (x, y) => x.Name.CompareTo(y.Name));

Sorting with IComparer and Lambda Expressions Live Demo

Binary SearchBinary Search

 Binary search is a fast method for searching for an element in a sorted array  Has guaranteed running time of O(log(n)) for searching among arrays of with n elements  Implemented in the Array.BinarySearch( Array, object) method  Returns the index of the found object or a negative number when not found 31

Binary Search (2)Binary Search (2)  All requirements of the Sort() method are applicable for BinarySearch()  Either all elements should implement IComparable or instance of IComparer should be passed 32

Binary Search – ExampleBinary Search – Example 33 static void Main() { String[] beers = {"Zagorka", "Ariana", String[] beers = {"Zagorka", "Ariana", "Shumensko","Astika", "Kamenitza", "Bolqrka", "Shumensko","Astika", "Kamenitza", "Bolqrka", "Amstel"}; "Amstel"}; Array.Sort(beers); Array.Sort(beers); string target = "Astika"; string target = "Astika"; int index = Array.BinarySearch(beers, target); int index = Array.BinarySearch(beers, target); Console.WriteLine("{0} is found at index {1}.", Console.WriteLine("{0} is found at index {1}.", target, index); target, index); // Result: Astika is found at index 2. // Result: Astika is found at index 2. target = "Heineken"; target = "Heineken"; index = Array.BinarySearch(beers, target); index = Array.BinarySearch(beers, target); Console.WriteLine("{0} is not found (index={1}).", Console.WriteLine("{0} is not found (index={1}).", target, index); target, index); // Result: Mastika is not found (index=-5). // Result: Mastika is not found (index=-5).}

Binary SearchBinary Search Live Demo

Working with ArraysWorking with Arrays Best PracticesBest Practices

Advices for Working with Arrays  When given method returns an array and should return an empty array, return an array with 0 elements, instead of null  Arrays are passed by reference  To be sure that given method will not change the passed array, pass a copy of it  Clone() returns shallow copy of the array  You should implement your own deep clone when working with reference types 36

Questions?Questions?

1. Write a program that fills and prints a matrix of size (n, n) as shown below: (examples for n = 4) a)b) c)d) * 38

2. Write a program that reads a rectangular matrix of size N x M and finds in it the square 3 x 3 that has maximal sum of its elements. 3. Write a program, that reads from the console an array of N integers and an integer K, sorts the array and using the method Array.BinarySearch() finds the largest number in the array which is ≤ K. 4. You are given an array of strings. Write a method that sorts the array by the length of its elements (the number of characters composing them). 39

5. * Write a class Matrix, to holds a matrix of integers. Overload the operators for adding, subtracting and multiplying of matrices, indexer for accessing the matrix content and ToString(). 6. * Write a program that finds the largest area of equal neighbor elements in a rectangular matrix and prints its size. Hint: you can use "Depth-first search" or "Breadth-first search" (find them in Wikipedia). Depth-first searchBreadth-first searchDepth-first searchBreadth-first search