Answer the question
In order to leave comments, you need to log in
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:
- <?php
- /**
- * Описание алгоритма:
- * Алгоритм печатает количество страниц, основываясь на трех константах:
- * 1. Количество элементов(всего)
- * 2. Желаемое количество элементов на страницу
- * 3. Максимальное количество дополнений(ситуация, когда на последней странице 1-2 элемента)
- */
- define('RESULTS_COUNT', 12349);
- define('RESULTS_PER_PAGE', 17);
- define('MAX_ADDITIONS', 7);
-
- $results_per_page = RESULTS_PER_PAGE>0?RESULTS_PER_PAGE:1; // дополнительная проверка на division by zero
-
- if(RESULTS_COUNT<$results_per_page || RESULTS_COUNT==$results_per_page){
- exit('1 page for '.RESULTS_COUNT.' results.');
- }
-
- $exact_pages_count = RESULTS_COUNT / $results_per_page;
- if (is_int($exact_pages_count)) {
- exit($exact_pages_count.' pages for '.RESULTS_COUNT.' results.');
- }
- else {
- $rough_estimate_pages = intval($exact_pages_count);
- $number_of_surplus=RESULTS_COUNT-($results_per_page*$rough_estimate_pages);
- $pages_of_surplus=$number_of_surplus<=MAX_ADDITIONS?$rough_estimate_pages:$rough_estimate_pages++;
- exit($rough_estimate_pages.' pages for '.RESULTS_COUNT.' results.');
- }
- ?>
* This source code was highlighted with Source Code Highlighter.
Answer the question
In order to leave comments, you need to log in
% - remainder of division
floor() - round down
$countPages = floor(RESULTS_COUNT/RESULTS_PER_PAGE);
if (RESULTS_COUNT%RESULTS_PER_PAGE >= MAX_ADDITIONS){
$countPages++;
};
return $countPages;
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?
if(RESULTS_COUNT<$results_per_page || RESULTS_COUNT==$results_per_page)
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/> не совсем точно показывает обобщенные типы, так что вот на всякий случай скриншот:
DeusModus
The Cheese algorithm just solves the problem. Cheese, after all, uses ceil - finding the smallest integer that is greater than the resulting number.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question