如何实现帧大小可配置的往复环绕索引?(Rust实现需求)
实现双向环绕索引(Ping-Pong Index)
问题需求
需要实现一种环绕索引逻辑,生成如下往复序列:
- 帧大小为3时,输出:
1 2 3 2 1 2 3 2 1… - 帧大小为4时,输出:
1 2 3 4 3 2 1 2 3 4 3 2 1…
需补全Rust代码中的loop_index函数,输入1到100的整数i,返回对应索引值;同时确认该索引模式的专业术语。
给定代码框架:
for i in 1..100 { let idx = loop_index(i); print!("{} ", idx); }
Rust实现代码
先拆解序列规律:
- 序列周期为
2*(帧大小-1)(比如帧大小3时周期为4,帧大小4时周期为6) - 单个周期内,前半段从1递增到帧大小,后半段从帧大小-1递减到1
基于规律实现通用版loop_index函数,支持自定义帧大小:
// 输入当前迭代序号i和帧大小,返回对应索引 fn loop_index(i: usize, frame_size: usize) -> usize { // 帧大小为1时,始终返回1 if frame_size == 1 { return 1; } let cycle = 2 * (frame_size - 1); // 计算当前在周期内的位置(从0开始) let pos = (i - 1) % cycle; if pos < frame_size { // 周期前半段:递增 pos + 1 } else { // 周期后半段:递减 2 * frame_size - pos - 1 } } // 调用示例(以帧大小3为例) fn main() { const TARGET_FRAME_SIZE: usize = 3; for i in 1..100 { let idx = loop_index(i, TARGET_FRAME_SIZE); print!("{} ", idx); } }
如果需要固定帧大小,可将帧大小硬编码到函数中简化调用:
const FRAME_SIZE: usize = 4; fn loop_index(i: usize) -> usize { if FRAME_SIZE == 1 { return 1; } let cycle = 2 * (FRAME_SIZE - 1); let pos = (i - 1) % cycle; pos < FRAME_SIZE ? pos + 1 : 2 * FRAME_SIZE - pos - 1 } fn main() { for i in 1..100 { let idx = loop_index(i); print!("{} ", idx); } }
专业术语
这种往复式的环绕索引模式通常被称为 Ping-Pong Index(往返索引),也可称为 Bidirectional Wrap-Around Index(双向环绕索引),常见于动画循环、音频淡入淡出、UI元素往复滚动等场景,用来实现“去-返”式的循环序列。
内容的提问来源于stack exchange,提问作者Purkylin
相关产品推荐
相关产品推荐

