この質問が重複しているため、この質問を閉じる前に、少なくとも正しい回答をここに投稿する必要があると思いました。
Eric Bainvile の答えは正しいものです。
int foo(const int position, const int period){return period - abs(position % (2 * period) - period);}
periodただし、これにより、[0, ] からの範囲と の周波数の三角波が得られ、[0, ]2 * periodからの範囲period / 2と の周期が必要periodです。fooこれは、期間の半分を関数に渡すか、関数を調整することで実現できます。
int foo(const int position, const int period){return period / 2 - abs(position % period - period / 2);}
このような単純な関数では、インライン化が望ましいと思われるため、最終的な結果は次のようになります。
for(auto position = 0; position < 5 * 2; ++position) cout << 5 / 2 - abs(position % 5 - 5 / 2) << endl;
要求されたもの:
0
1
2
1
0
0
1
2
1
0