■
問題:座標のグリッド揃え
きれいにそろった図形というのはきれいな物です。
図形をそろえる上で、グリッド揃え等が必要になったりするでしょう。
これには座標をある一定のグリッド間隔に丸める必要があります。struct Position { int x; int y; } (Javaの場合にはclass)を int gridPitch に丸めるFitToGrid関数を書いて下さい。
http://www.ailight.jp/blog/kazuk/archive/2008/12/22/27144.aspx
例
グリッド揃えはよくあるオフィス系アプリケーションなんかで図形をドラッグ&ドロップで移動する時に近くの格子点に吸いつくあれでございます。gridPitch=100 で (10,10) を与えたら (0,0) が返る事を期待しています。
また、(60,60)では(100,100)、(20,90)では(0,100) です。
java で書いてみた。
/** * @author Aileron */ public class Test { /** * @author Aileron */ public static class FitToGrid { /** * @param position * @return fit position */ public Position fit(final Position position) { final int x = fit(position.x); final int y = fit(position.y); return new Position(x, y); } /** * @param value * @return fit value */ private int fit(final int value) { final int odd = value % gridPitch; final int carry = odd > gridPitchThreshold ? gridPitch : 0; return value - odd + carry; } /** * @param gridPitch */ public FitToGrid(final int gridPitch) { this.gridPitch = gridPitch; this.gridPitchThreshold = gridPitch / 2; } private final int gridPitch; private final int gridPitchThreshold; } /** * @author Aileron */ public static class Position { @Override public String toString() { return "x:" + x + ",y:" + y; } /** * @param x * @param y */ public Position(final int x, final int y) { this.x = x; this.y = y; } /** * x */ public final int x; /** * y */ public final int y; } /** * @param args */ public static void main(final String... args) { final FitToGrid fitToGrid = new FitToGrid(100); System.out.println(fitToGrid.fit(new Position(10, 10))); System.out.println(fitToGrid.fit(new Position(60, 60))); System.out.println(fitToGrid.fit(new Position(20, 90))); } }
python で書いてみた
class Position(object): def __init__(self, x, y): self.x = x self.y = y def fit(position, gridPitch=100): def f(value): odd = value % gridPitch; carry = odd > gridPitch/2 and gridPitch or 0; return value - odd + carry x = f(position.x) y = f(position.y) return Position(x,y) p = fit(Position(10,10),gridPitch=100) print 'x:' +str(p.x) + ',y:' + str(p.y) p = fit(Position(60,60),gridPitch=100) print 'x:' +str(p.x) + ',y:' + str(p.y) p = fit(Position(20,80),gridPitch=100) print 'x:' +str(p.x) + ',y:' + str(p.y)