tailieunhanh - Mastering Algorithms with Perl phần 4

Hiệu suất của phiên bản đệ quy có thể được tăng cường bằng cách chuyển đệ quy vào lặp đi lặp lại, xem phần "Loại bỏ đệ quy từ Sắp xếp nhanh." Nếu bạn mong đợi của các phím của bạn sẽ được tương tự, hãy thử thêm này trước khi trở lại trong phân vùng (): | while loop. If you don t mind explicit loop controls such as next use this alternate implementation for intersection. It s about 10 faster with our test sub intersection my i sizei 0 scalar keys _ 0 my j sizej Find the smallest hash to start. for j 1 j @_ j sizej scalar keys _ j i sizei j sizej if sizej sizei my possible intersection TRYELEM Check each possible member against all the remaining sets. foreach possible keys splice @_ i 1 foreach @_ next TRYELEM unless exists _- possible intersection possible undef Page 215 return intersection Here is the union written in traditional procedural programming style explicitly loop over the parameters sub union my union while @_ Just keep accumulating the keys slice by slice. @union keys _ 0 shift return union or for those who like their code more in the functional programming style or more terse sub union return map _ @_ or even sub union map _ @_ The acts here as a disambiguator it forces the . . . to be understood as an anonymous hash reference instead of a block. We initialize the values to undef instead of 1 for two reasons Some day we might want to store something more than just a Boolean value in the hash. That day is in fact quite soon see the section Sets of Sets later in this chapter. Initializing to anything but undef such as with ones @hash @keys 1 x @keys is much slower because the list full of ones on the righthand side has to be generated. There is only one undef in Perl but the ones would be all saved as individual copies. Using just the one undef saves space. Testing with exists hash key is also slightly faster than hash key . In the former just the existence of the hash key is confirmed the value itself isn t fetched. In the latter not only must the hash value be fetched but it must be converted to a Boolean value as well. This argument doesn t of course matter as far as the undef versus 1 debate is There are two separate existence issues in hashes whether an element with a .

TỪ KHÓA LIÊN QUAN