LoginSignup
0
0

More than 5 years have passed since last update.

algorithm > 自然数と0が交互に来るようにする実装

Last updated at Posted at 2015-12-17

0と自然数[1,2,3]が交互に来るようにする実装。

力技で実装した。

NnPWWz.c
#include <iostream>
using namespace std;

int getNextIndex_1(int curIdx)
{
    // [0, 1, 10, 2, 20, 3, ..., 8, 80], then [0, 1, ...]
    int work = curIdx;
    if (work >= 10) {
        if (work >= 80) {
            return 1;
        }
        return (work / 10) + 1;
    }
    work = work % 10;
    if (curIdx == 0) {
        return 1;
    }
    return curIdx * 10;
}

int main() {
    int idx = 0;
    int useIdx;

    // [0, 1, 0, 2, 0, 3, ... 0, 8], then [0, 1, ...]
    //
    for(int loop=0; loop < 20; loop++) {
        useIdx = idx % 10; // needed
        cout << useIdx << endl;
        idx = getNextIndex_1(idx);
    }

    return 0;
}
結果
Success time: 0 memory: 3460 signal:0
0
1
0
2
0
3
0
4
0
5
0
6
0
7
0
8
0
1
0
2

読みやすさの点では配列を使うほうがいいかもしれない。

関数の外で10の剰余を取るのがいけてない。

ポインタなり参照なり使って、2つ前の状態を覚える変数を別途用意すればまた違うようにできる。

関数内でstatic変数を使うのはしたくはない。

使い道。

  • 0: primaryな処理
  • 1,2,3,4...8: secondaryな処理

primaryな処理を繰り返しながらsecondaryな処理をする。
インスタンスは[0..8]で定義しているとする。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0