Giáo trình tiếng anh chuyên ngành khoa học máy tính phần 2 KS châu văn trung

270 415 0
Giáo trình tiếng anh chuyên ngành khoa học máy tính  phần 2   KS  châu văn trung

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

3 65 Chương 6: Mảng Chuỗi CHAPTER * Arrays and Strings M ảng ch u ỗ i MỤC ĐÍCH YÊU CẨU Sau học xong chương này, Dạn nắm vững khái n iệm mảng chuỗi, phương pháp xử lý m ảng ''huỗi ngơn ngữ lập trìn h C/C++, V isual B asic Java, với nội dung cụ th ể sau đây: ♦ Introduction to arrays ♦ Giới thiệu sơ lược m ảng ♦ Arrays in Visual Basic + Các mảng Visual basic ♦ Arrays in C/C++ and Java + Các mảng C/C ++ Java ♦ Searching + Tìm kiêm ♦ Sorting + Sắp xếp thứ tự Ngồi ra, cuối chương cịn zỏ phần tập có lời g iải, tập bổ sung đáp án Ìihằm giúp bọn thực h àn h áp dụng m ột cách hiệu vào công việc thực tế / 366 Chapter 6: Arrays anơ strings CHỦ DIỂM 6.1 INTRODUCTION TO ARRAYS G i ó i thiệu sơ lược mảnq An a r r a y is a group of memory locations all of the same type that have the same name Previously, in a program to calculate employee pay, the user would type in the employee number, the pay rate, and the number of hours worked There would be one variable to hold each piece of informa­ tion as shown in Fig 6-1, i-nd then the gross pay would be calculated employeeNum 101 hourly Rate 6.25 hours Worked grossPay 40 Fig 6-1 Individual variables for payroll If th e re w ere m ore th a n one em ployee, th e p ro g ram could have a loop for th e u ser to type in th e in form ation in to th e sam e variables for th e second em ployee and calculate th a t p e rso n ’s gross pay, then th e th ird , and so forth However, a problem would a ris e if the em­ ployer w anted to have a re p o rt co n tain in g a lis t of th e w eekly pay for all th e em ployees, th e average pay for th e w eek, an d th e n a list of all th e em ployees who received above th e average pay T he average could not be calculated until all th e em ployees’ in fo rm atio n was submitted In o r d e i'to com pare each p erso n ’s pay to th e av erag e, all th e infor­ m ation would need to be e n tered a second tim e Oane solution to this problem would be to have a different variable for each employee, as shown in Fig 6-2 Each person’s pay could be compared to the average This would be possible if there were only two or three employees, but completely im practical to declare separate variables for twenty or a hundred or a thousand employees The solution to this problem is to use an array Arrays allow the storing and m anipulating of large amounts of data Three arrays are declared, one to hold all the employee numbers, another for all the hourly rates and a third for all the hours worked, as shown in Fig 6-3 The information is entered in such a way th a t the employee whose num ber is in box receives the rate in box and worked the number of hours in box Each person’s gross pay is calculated and the average is found Each person’s data is still in memory and can quickly be examined to produce the list of people with pay above the average 367 Chương 6: Mảng Chuỗi employeeNuml 101 hourlyRatel 121 12I rn a hoursWorkedl grossPayl 11 11 FI □ 11 11 employeeNum2 hourlyRate2 hoursWorked2 grossPay2 121 131 hourlyRate3 hoursWorked3 grossPay3 employecNum3 Fig- 6-2 Individual variables íor three em ployees employeeNums 101 [01 102 [1] 103 [2] 104 [3] 105 [41 [n- ] hourlyRates 6.25 [0] 6.55 [1] 7.25 [2] 7.15 [3] 6.25 [4] [n-11 hoursWorked 40 [0] 38 [1] 42 [2] 40 [3] 37 [4] In-1] gross Pay [0] [1] [2] [3] [4] ln-11 Fig 6-3 Array variables for any number (n) of employees 6.1.1 M a n ip u la tin g A rra y s - x lý mảng The entire array is declared once and known by one name W hen it is declared, the exact num ber of memory locations to be set aside is speci­ fied All the locations m ust contain data of the same type Each e lem en t, or individual memory location in the array, is accessible through the use of its s u b s c r i p t or in d e x n u m b e r F o r e x a m p le , in F ig 6-3 em ployeeN um s[3] r e fe rs to th e e le m e n t in box n u m b e r of th e employeeNums array w hich contains “104,” or hourlyRates[4] would ac­ cess the elem ent in box of the hourlyRates array which contains “6.25.” The subscripts usually begin with Input and output for an array is accom plished through the use of loops Each tim e through the loop a different box in the array is filled or printed 368 Chapter 6: Arrays and Strings EXAM PLE 6.1 Pseudocode for a loop to f i l l or p rin t an array of n items would look like this: loop from lev = to lev = n -1 where n is the total number of items in the array input or output arrayllcv] end loop EXAM PLE 6.2 Most other processing of arrays also entails loops One com­ mon example is to calculate the sum of all the items in an integer array Pseudocode for summing an array would look like this: set the sum to before the loop starts loop from lev = to lev = n -1 where n is the total number of items in the array add the arrayllcv] to the running sum end loop Specific processing of arrays in Visual Basic, c, C++, and Java is dem­ onstrated later in th is chapter Each language handles them in a slightly different way However, in all languages the program m er must be careful not to try to process past the end of the array For example, if there are 10 item s in the array called grossPay, located in boxes [0] through [9], a statem ent including grossPay[20] would cause serious problems because there is no memory location with th a t designation 6.12 M u lti-D im e n s io n A rra y s - Các m ản g da c h iể u Regular single-dimension arrays are good for processing lists of items Sometimes, however, two-dimensional arrays are necessary mySales [0] [1] [2] [3] 250 350 220 210 300 325 315 310 IẵL 325 400 210 295 Fig 6-4 T w o-dim ensional array for sales E XAM PLE 6.3 A sales representative m ight have a report of th e sales for each m onth of each quarter, as shown in Fig 6-4 The rows [0] through [3] rep resen t th e four quarters of the year The columns [0] through [2] represent the th ree m onths in each quarter Each elem ent of th e array is Chương 6: Mảng Chuỗi 369 accessed through two subscripts, one for th e row and one for th e column, in that order For example, in Fig 6-4 the contents of en try mySales[l][2] IS “400.” Two-dimensional arrays follow the rules of single-dimension arrays The array is declared specifying the number of memory locations desired by stating the number of rows and the number of columns Each item in the array must contain the same type of data The entire array has one name and each elem ent is accessible through the use of its row and column numbers Most processing of these arrays is accomplished through the use of nested loops, one for the row and one for the column EXAMPLE 6.4 The pseudocode for printing a two-dimensional array looks like this: loop from row = to row = n -1 where n is the number of rows in the array loop from col = to col = m -1 where m is the number of columns in the array print out array[row][col] end col loop end row loop Arrays -of more than two dimensions are possible, but rarely used See Solved Problems 6.4 and 6.5 at the end of the chapter for an example 6.1.3 S trin g s - A S p e cia l K in d o f A rra y - C h uỗ i - Một kiểu mảng đặc biệt The array examples we have seen so far have been numeric It is also possible to m anipulate arrays of characters These arrays, usually called strings, are a special type.of array because they are used so frequently An array of strings is implemented as a two-dimensional array of characters EXAMPLE 6.5 Draw single-dimension arrays to contain the following strings: “JOAN,” “CHICAGO,” and “MAY” In addition, draw a two-dimensional a r­ ray to contain the strings: “corn,” “w heat,” and “rye.” The result is shown in Fig 6-5 370 Chapter 6: Arrays and String myName [01 J [21 [11 o [31 ! N m H [21 1 [31 c [1] A [21 Y myCity M «nd string A toi C - M LSI G 13] n 4] end String t m 161 o [51 A and string month 10] M [31 end string grains [01 [0] c m w r [2] r e e [11 h y [21 a end string end string F ig 6-5 Strings in one and tw o dim ensions Each language implements and m anipulates strings differently Usually special kinds of processing commands are available Many require some indication of w here the string ends, as shown in th e previous example The following sections explain the use of arrays in specific languages In each of these languages we have considered the following topics: declaring arrays, m anipulating arrays, two-dimensional arrays, strin g processing, and arrays as param eters to functions HƯỚNG DẪN ĐỌC HIEU CHỦ DIEM 6.1 6.1 G IỚ I T H IỆ U VỂ M ẢN G Một m ảng m ột nhóm vị trí nhớ có kiểu tên Trước trog chương trình đ ể tính số tiền p hải chi trả cho nhân viên người dùng cần phải gõ nhập mã số nhân viên, số tiền chi trả số làm việc Sẽ có biến đ ể g iữ mảng thơng tin m inh họa hình 6.1, sau số tiền chi trả gộp tính tốn employeeNum hourlyRate hoursWorked grossPay 101 H ìn h 6.1 Các biến riêng biệt dành cho chi trả lương _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _J _ _ _ _ 371 Chương 6: Mảng Chuỗi Nếu có nhiều nhăn viên chương trình có th ề có vòng lặp dành cho người dùng đ ể gõ nhập thông tin vào biến giống dành cho người cơng nhăn thứ hai tính khoảng tiền gộp mà người dó nhận được, sau đến người thứ ba v,v Tuy nhiên, toán nảy sinh người chủ muốn có bảng báo cáo có chứa danh sách chi trả hàng tuần tất nhăn viên, mức chi trả trung binh tuần mộtdanh sách tất nhân viên nhận số tiền bên trẽn mức chi trả trung bình S ố tiền trung bình khơng thể dược tính tốn đến tất nhăn viên nhập xong Để so sánh mức nhận tiền người với mức trung bình, tất thông tin cần phải nhập vào lần thứ hai Một giải pháp cho vấn đề bạn phải có biến khác dành cho nhăn viên m inh họa hình 6.2 Mỗi khoảng chi trả cho nhân viên phải so sánh với giá trị trung bình Điều thực có hai ba nhân viẽn, hồn tồn khơng thực tế bạn khai báo biến riêng biệt dành cho khoảng 20 100 1000 nhân viên Có giải pháp cho vấn đề sử dụng mảng Các mảng cho phép lưu trữ cách xử lý lượng liệu lớn Ba mảng dược khai báo, d ể giữ tất sô nhân viên, dùng cho tẩtcả định mức chi trả theo thứ ba dành cho tất làm việc minh họa hình 6.3 Thơng tin nhập vào theo cách thức cho nhân viên có sơ' định danh nằ m nhận định mức lương hoạt động sô nằm ô Mỗi khoản tiền chi trả gộp cá nhânsẽ tính tốn tìm giá trị trung bình Mỗi liệu cá nhân nằm nhớ có th ể nhanh chóng xem xét tạo nên danh sách người có mức chi trả bên trẽn mức trung binh hoursWorkedl employeeNuml hourlyRatel I 10 1 625 1 40 bourlyRate2 hoursWorked2 employeeNunứ 102 1 725 employeeNum3 hourlyRale3 103 1 655 B hoursWorkcd3 H grossPayl 1 grossPay2 1 grossPay3 H ìn h 6.2 Các biến riêng biệt dành cho ba nhân viên 372 Chapter 6: Arrays and Stringt employeeNums 101 10] 102 [11 103 [2] 104 [31 105 [41 ln-11 houriyRates 6.25 [0] 6.55 [11 7.25 [2] 7.15 [31 6.25 [41 in-11 hoursWorked 40 [0] 38 [1] 42 12] 40 [31 37 [41 ln-11 grossPay [0} [1] [2] [3] [4] [n-ề 1] H ìn h 6.3 Biến mảng dành cho số nhăn viên 6.1.1 X lỷ m ả n g Mảng tổng th ể khai báo lần biết tẽn Lúc khai báo, sơ xác vị trí nhớ xác lập nơi định Tất vị trí phải có chứa liệu kiểu Mỗi yếu tố (element) vị trí nhớ riêng biệt m ảng phải dược thông qua việc sử dụng số số subscript Ví dụ, hình 6.3, employeeNums[3] ám đến yểu tố ô số mảng employeeNUms có chứa “104” hourlyRates[4] truy cập , yếu tố ô với m ảng hourlyRates có chứa “6.25" Các chi số thường bắt dầu số Dữ liệu nhập vào xuấtra dành cho m ảng hồn thành thơng qua việc sử dụng vịng lặp Mỗi lần thơng qua vịng lặp có m ột khác mảng điền vào in V I D Ụ 6.1 Tạo mã giả cho vòng lặp đ ể điền in mảng n hạng mục loop from lev = to lev = n -1 where n is the tctal number of items in the arrm input or out-put array[lev] end loop V I D Ụ 6.2 Hầu hết việc xử lý m ảng củng chi tiết hóa vịng lặp Một ví dụ p h ổ biến tính tổng tất hạng mục m ảng nguyên Lập mã giả d ể tính tổng m ảng set the sum to before the loop starts loop from lev = to lev = n -1 where n is the total number of items in the array add the arrayDcv] to the running sum end loop 373 IChương 6: Máng Chuỗi Quy trình xử lý chuyên biệt mảng Visual Basic, C++ Java m inh họa sau chương Mỗi ngôn ngữ xù lý chúng theo cách thức khác Tuy nhiên, tất ngơn ngữ người lập trình phải cẩn thận không xử lý vượt sô cuối mảng Ví dụ, có 10 hạng mục mảng gọi grossPay, đặt từ [0] đến [9], m ột câu lệnh grossPay[20] xảy vấn đề chúng khơng có vị trí nhớ với sư thiết kế 6.1.2 Các m ản g n hiều ch iều (nhiều th ứ nguyên) Các mảng chiều bình thường tốt cho việc xử lý danh sách hạng mục Tuy nhiên, vẩn cần đến m ảng hai chiều mySales [0] [11 [2] [31 250 350 220 210 300 325 315 310 I2L 325 400 210 295 H ìn h 6.4 M ảng hai chiều cho việc kinh doanh V í D Ụ 6.3 Một người đại diện bán hàng có th ể có báo cáo việc kinh doanh hàng tháng quý, m inh họa hình 6.4 Các hàng từ [0] đến [3] đại diện cho quý năm cột từ [0] đến [12] đại diện cho tháng quý Mỗi thành phần mảng tiếp cận thông qua chl số, số cho hàng chi số cho cột theo thứ tự Ví dụ, hình 6.4 , nội dung cùa mySales[lJ[2] nhập vào 400 Các máng hai chiều tuân theo quy tác màng chiều Màng dược khai báo bàng xác định số vị trí nhớ mong muốn khai báo số hàng hay số cột Toàn màng có tên thành phần tiếp cận bàng cách dùng số hàng số cột Phần lớn quy trình xử lý mảng thực bàng cách sử dụng vòng lặp lồng, m ột vòng lặp cho hàng vịng lặp cho cột V Í D Ụ 6.4 Mã giả đ ể in mảng hai chiều có dạng sau: loop from row = to row = n -1 where n is the number of rows in the array loop from col = to col = m -1 where m is the number of columns in the array p rin t out array[row][col] end col loop end row loop 374 Chapter 6.ểArrays and Strings Cũng có th ể có khả nhiều han hai chiểu rắt sù dụng đ ể xem ví dụ Xem phần tập có lời giải 6.4 6.5 cuối chương 6.1.3 Các ch u ỗi - M ột lo i m ản g d ặ c b iệ t Các ví dụ mảng mà xem xét số Ngoài ta có th ể xử lý mảng ký tự N hững m ảng thường gọi chuỗi, loại mảng đặc biệt chúng dùng thường xuyên Một máng chuỗi thực thi dạng m ảng ký tự hai chiểu VI D Ụ 6.5 Hãy vẽ mảng mộtchiều có chứa chuỗi sau đây: JO A N ” “ , CHICAGO” “ AY” Bên cạnh đó, vẽ mảng hai , M chiều có chứa chuỗi “ corn", wheat” “ , rye” Kết m inh họa hình 6.5 myNam e [01 [11 [2] A C [1] H month [0] M [1] A [2] [0] 11] [2] toi c w r J myCity [01 I I [3] N [4] I •rid string [31 C [2] I 4] A [5] G [6] ° [3] n a [5] •ndrtrtng t •nd string m •nd string [3] üü grains [1 ] h y Í21 r e e and string H ình 6.5 Các chuỗi chiều hai chiểu Mỗi ngôn ngữ thực thi xử lý chuỗi theo cách thức khác Thông thường loại lệnh xử lý đặc biệt có sản Có nhiều loại yẽu cầu m ột vài định nơi mà chuỗi phải kết thúc minh họa ví dụ trước Phần sau giải thích cách dùng m ảng theo ngôn ngữ đặc biệt Trong ngôn ngữ phải xem xét chủ điểm sau đây: khai báo mảng, xử lý mảng, m ảng hai chiều, xử lý chuỗi m ảng chọn làm tham sô cho hàm 622 Chapter 9: Data Structures Before [0] [1] 10 12 [2] [3] [4] 14 15 - -1 -1 [51- [6] - [7] - - h ea d = avail= After deleting 14 [0] [1] [2] [3] 10 12 14 h e a d -0 av ail=2 15 - [4] - - [5] - [6] - (7] - - 9.5 Loại kết xuất số mục phần mã sau đăy dành cho lớp C++ L inkedList tĩnh không theo thứ tự? 9.6 viết hàm Java dành cho lớp L inkedList động không theo thứ tự d ể chèn nút đầu danh sách Tiẽu để hàm void InsertBeginning (Item x); 9.7 Loại kết xuất mục mã sau đáy sử dụng lớp Java ordered LinkedList? 9.8 Mục tiêu lập trình hướng đối tượng dó sử dụng lại nhiều m ã tốt Loại dịng hình 9.7a 9.7b cần phải thay đổi đ ể tạo nén lớp có chồng số nguyên thay vỉ ký tự? 9.9 (a) Thay đổi dòng c++ PrintStackO hàm số hình 9.7b d ể in chồng tất nội dung dòng (b) Kết xuất phần mã c++ th ế nịío “ Hello to you” người dùng nhập vào dòng nhắc? 9.10 Kết xuất mà mục mã Java đưa ra? 9.11 Cho lớp Java L inkedList hình 9.6, viết hàm phần tử đ ể bổ sung giá trị cho vào phần tử danh sách 623 Chương 9: cấu trúc dư liệu SUPPLEMENTARY PROBLEMS B a i tqp 9.12 9.13 9.14 9.15 9.16 sunq W hat is the difference between s ta tic a n d d y n a m ic data struc­ tures? Which type of ADT would be appropriate for the following applica­ tions? (a) Simulation of car wash (b) Packing and unpacking a suitcase (c) Parking lot th a t has one lane and only one way in or out (d) Checking incoming string to see if it is a palindrome (e) Simulation of a bank line (f) Todo list where all jobs have the same priority (g) Employee records Add a function to the LinkedList class class in Fig 9-4 th a t would insert the item in order and create an ordered list The function heading would be void I n s e r tln O r d e r d te m x); Draw the before and after array for Fig 9-5 if the node 10 is deleted instead of the node 14 W hat would be the output of the following sections of code for the unordered static C++ LinkedList class? LinkedList myli s t (7) ; mylist.PrintList('o'); mylist.PrintList('a'); for (int i = 2; i

Ngày đăng: 17/06/2015, 02:12

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan