Javaでは以下のように方向を管理するクラスDirectionが作れ、直感的に使えます。
Java
1public enum Direction { 2 FRONT(0), 3 RIGHT(1), 4 BACK(2), 5 LEFT(3), 6 DOWN(0), 7 UP(2); 8 9 private int value; 10 11 Direction(int value) { 12 this.value = value; 13 } 14 public void turnRight() { 15 this.value = (this.value + 3) % 4; 16 } 17 public void turnLeft() { 18 this.value = (this.value + 1) % 4; 19 } 20 public void reverse() { 21 this.value = (this.value + 2) % 4; 22 } 23 public int get() { 24 return this.value; 25 } 26} 27 28public class Test { 29 public static void main(String[] args) { 30 Direction a = Direction.FRONT; 31 Direction b = Direction.LEFT; 32 System.out.println("a: " + a.get()); // a: 0 33 System.out.println("b: " + b.get()); // b: 3 34 b.turnRight(); 35 System.out.println("b: " + b.get()); // b: 2 36 } 37}
JavaScriptとC++とGolangとPythonではそれぞれ、どのようにこのようなクラスを実装すれば良いのでしょうか?(見た目の綺麗さの面や処理速度的な面、妥協点について)
4つまとめてでなくて構わないのでお聞かせ下さい。
と思っていたのですが、以上のJavaのコードは間違っていたのでC++で書いたものを載せます。すみません。
C++
1#include <iostream> 2 3class Direction { 4public: 5 static const int FRONT = 0; 6 static const int RIGHT = 1; 7 static const int BACK = 2; 8 static const int LEFT = 3; 9 static const int DOWN = 0; 10 static const int UP = 2; 11private: 12 int value; 13 14public: 15 Direction() { 16 this->value = FRONT; 17 } 18 Direction(int value) { 19 this->value = value; 20 } 21 void turnRight() { 22 this->value = (this->value + 3) % 4; 23 } 24 void turnLeft() { 25 this->value = (this->value + 1) % 4; 26 } 27 void reverse() { 28 this->value = (this->value + 2) % 4; 29 } 30 int get() { 31 return this->value; 32 } 33}; 34 35int main() { 36 Direction a(Direction::FRONT); 37 std::cout << a.get() << std::endl; 38 a.turnLeft(); 39 std::cout << a.get() << std::endl; 40 return 0; 41}
回答2件
あなたの回答
tips
プレビュー