0..6 の範囲でぐるぐる回る
0..6 の範囲でぐるぐる回るサンプルです。
以下の、上の段の数値を下の段の数値に変換するサンプルです。
-7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ↓に変換する 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0
プログラム
using System; using System.Collections.Generic; using System.Linq; class Program { static int Mod(int x, int m) { if (x >= 0) return x % m; return (m - (-x % m)) % m; } static void Main() { const int N = 7; for (int i = -20; i <= 20; i++) { Console.WriteLine("{0} {1}", i, Mod(i, N)); } } }
実行結果です。
-20 1 -19 2 -18 3 -17 4 -16 5 -15 6 -14 0 -13 1 -12 2 -11 3 -10 4 -9 5 -8 6 -7 0 -6 1 -5 2 -4 3 -3 4 -2 5 -1 6 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 0 8 1 9 2 10 3 11 4 12 5 13 6 14 0 15 1 16 2 17 3 18 4 19 5 20 6
ちなみに、負数の剰余はプログラミング言語によって振る舞いが異なるようです。Ruby だと % 演算子をそのまま使っても上記の値を取得できます。
[3] pry(main)> (-20..20).map {|i| "(#{i} #{i%7})" }.join(',') => "(-20 1),(-19 2),(-18 3),(-17 4),(-16 5),(-15 6),(-14 0),(-13 1),(-12 2), (-11 3),(-10 4),(-9 5),(-8 6),(-7 0),(-6 1),(-5 2),(-4 3),(-3 4),(-2 5),(-1 6), (0 0),(1 1),(2 2),(3 3),(4 4),(5 5),(6 6),(7 0),(8 1),(9 2),(10 3),(11 4),(12 5), (13 6),(14 0),(15 1),(16 2),(17 3),(18 4),(19 5),(20 6)"
参考
追記
上の Mod メソッドは以下のようにも書けます。
static long Mod(long x, long m) { return (x % m + m) % m; }