Mic*_*dry 5 language-agnostic algorithm math
所以,我正在尝试做一些类似于paginator(页码列表)的东西,其中当前的数字在中间或尽可能接近
我解决它的每一种方式都很难和奇怪,只是想知道是否有一个很好的方式来做:)
给定:
a
:当前页码x
:第一页编号y
:最后一页编号n
:需要数量我想生成一个数字列表,其中a
尽可能靠近中心,同时保持在x
和y
所以f(5, 1, 10, 5)
会返回,[3, 4, 5, 6, 7]
但f(1, 1, 10, 5)
会返回[1, 2, 3, 4, 5]
并f(9, 1, 10, 5)
返回[6, 7, 8, 9, 10]
谁能想到一种很好的方式来获得那种东西?
在ruby中以一种可能复杂的方式实现,它可以更简单吗?
def numbers_around(current:, total:, required: 5)
required_before = (required - 1) / 2
required_after = (required - 1) / 2
before_x = current - required_before
after_x = current + required_after
if before_x < 1
after_x += before_x.abs + 1
before_x = 1
end
if after_x > total
before_x -= (after_x - total)
after_x = total
end
(before_x..after_x)
end
Run Code Online (Sandbox Code Playgroud)
由于您不会提及您想要执行的语言,因此以下是我用 C++ 编写的一些解释代码:
std::vector<int> getPageNumbers(int first, int last, int page, int count) {
int begin = page - (count / 2);
if (begin < first) {
begin = first;
}
int cur = 0;
std::vector<int> result;
while (begin + cur <= last && cur < count) {
result.push_back(begin + cur);
++cur;
}
cur = 0;
while (begin - cur >= first && result.size() < count) {
++cur;
result.insert(result.begin(), begin-cur);
}
return result;
}
int main() {
std::vector<int> foo = getPageNumbers(1,10,10,4);
std::vector<int>::iterator it;
for (it = foo.begin(); it != foo.end(); ++it) {
std::cout << *it << " " << std::endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它的作用基本上是:
page - (count/2)
(count/2
很好,您不需要减去零,因为例如2.5
将四舍五入到2
)。first
,则从第一个开始count
或直到当前元素小于第一页,就继续在开头插入元素这是我现在的基本尝试。该代码是可执行的。