D
D
DeusModus2010-12-17 23:33:33
PHP
DeusModus, 2010-12-17 23:33:33

Algorithm for counting the number of pages (can you suggest a better one)

I dug into one system and was a little crazy about the amount of code that counts the number of pages there (something like pagination). Tons of variables, checks.
I thought about what is so complicated here and wrote my own implementation:

  1. <?php
  2. /**
  3. * Описание алгоритма:
  4. * Алгоритм печатает количество страниц, основываясь на трех константах:
  5. * 1. Количество элементов(всего)
  6. * 2. Желаемое количество элементов на страницу
  7. * 3. Максимальное количество дополнений(ситуация, когда на последней странице 1-2 элемента)
  8. */
  9. define('RESULTS_COUNT', 12349);
  10. define('RESULTS_PER_PAGE', 17);
  11. define('MAX_ADDITIONS', 7);
  12.  
  13. $results_per_page = RESULTS_PER_PAGE>0?RESULTS_PER_PAGE:1; // дополнительная проверка на division by zero
  14.  
  15. if(RESULTS_COUNT<$results_per_page || RESULTS_COUNT==$results_per_page){
  16.   exit('1 page for '.RESULTS_COUNT.' results.');
  17. }
  18.  
  19. $exact_pages_count = RESULTS_COUNT / $results_per_page;
  20. if (is_int($exact_pages_count)) {
  21.   exit($exact_pages_count.' pages for '.RESULTS_COUNT.' results.');
  22. }
  23. else {
  24.   $rough_estimate_pages = intval($exact_pages_count);
  25.   $number_of_surplus=RESULTS_COUNT-($results_per_page*$rough_estimate_pages);
  26.   $pages_of_surplus=$number_of_surplus<=MAX_ADDITIONS?$rough_estimate_pages:$rough_estimate_pages++;
  27.   exit($rough_estimate_pages.' pages for '.RESULTS_COUNT.' results.');
  28. }
  29. ?>
* This source code was highlighted with Source Code Highlighter.


Perhaps you have a better solution for the same problem? If yes, that would be interesting to see.

Answer the question

In order to leave comments, you need to log in

6 answer(s)
N
niko83, 2010-12-18
@DeusModus

% - remainder of division
floor() - round down
$countPages = floor(RESULTS_COUNT/RESULTS_PER_PAGE);
if (RESULTS_COUNT%RESULTS_PER_PAGE >= MAX_ADDITIONS){
$countPages++;
};
return $countPages;

C
Cheese, 2010-12-18
@Cheese

something is not clear, you need to calculate how many pages the received number of results will take with a given number of elements per page?

V
Vladimir Chernyshev, 2010-12-18
@VolCh

if(RESULTS_COUNT<$results_per_page || RESULTS_COUNT==$results_per_page)

O_o
There is a comparison operator <=

K
Kalantyr, 2010-12-18
@Kalantyr

Oh, just the day before yesterday it was necessary to solve this problem for a Silverlight application (C# language). Here's what happened:
public static IDictionary<int, IEnumerable> DivideItems(IEnumerable sourceItems, int itemsAtPage)
{
var result = new Dictionary<int, IEnumerable>();
var array = sourceItems.ToArray();
var j = 0;
var pageNumber = 1;
while (j < array.Length)
{
var ar = new T[Math.Min(itemsAtPage, array.Length - j)];
for (var i = 0; i < ar.Length; i++)
ar[i] = array[j + i];
j += ar.Length;
result.Add(pageNumber, ar);
pageNumber++;
}
return result;
}
Это Generic-метод, T - любой тип. Функция принимает коллекцию объектов и максимальное число объектов на странице. Возвращает пары <[номер страницы] : [коллекция объектов страницы]>
Похоже, <code/> не совсем точно показывает обобщенные типы, так что вот на всякий случай скриншот:

O
OlegTar, 2010-12-18
@OlegTar

DeusModus
The Cheese algorithm just solves the problem. Cheese, after all, uses ceil - finding the smallest integer that is greater than the resulting number.

O
OlegTar, 2010-12-19
@OlegTar

The author, maybe in this system the number of records is not initially considered, for acceleration.
For example, 5 pages are displayed first, you poke on the fifth page, if it is not there, then you are thrown to the very last page that is.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question