RLPark 1.0.0
Reinforcement Learning Framework in Java
|
00001 package rlpark.plugin.rltoys.math; 00002 00003 public class GrayCode { 00004 static private final byte Base = 2; 00005 00006 static public byte byteToGrayCode(byte value) { 00007 int positiveValue = value >= 0 ? value : Byte.MAX_VALUE - value; 00008 return (byte) toGrayCode(toBaseNArray(Byte.SIZE, positiveValue)); 00009 } 00010 00011 static public short shortToGrayCode(short value) { 00012 int positiveValue = value >= 0 ? value : Short.MAX_VALUE - value; 00013 return (short) toGrayCode(toBaseNArray(Short.SIZE, positiveValue)); 00014 } 00015 00016 static public int intToGrayCode(int value) { 00017 int positiveValue = value >= 0 ? value : (int) ((long) Integer.MAX_VALUE - value); 00018 return toGrayCode(toBaseNArray(Integer.SIZE, positiveValue)); 00019 } 00020 00024 static private int toGrayCode(int[] baseN) { 00025 int digits = baseN.length; 00026 int gray[] = new int[digits]; 00027 int shift = 0; 00028 for (int i = digits - 1; i >= 0; i--) { 00029 gray[i] = (baseN[i] - shift) % Base; 00030 shift += gray[i] - Base; 00031 } 00032 return toInt(gray); 00033 } 00034 00035 private static int toInt(int[] gray) { 00036 int value = 0; 00037 for (int i = 0; i < gray.length; i++) 00038 value = value | gray[i] << i; 00039 return value; 00040 } 00041 00042 protected static int[] toBaseNArray(int digits, int value) { 00043 int[] baseN = new int[digits]; 00044 int tempvalue = value; 00045 for (int i = 0; i < digits; i++) { 00046 baseN[i] = tempvalue % Base; 00047 tempvalue /= Base; 00048 } 00049 return baseN; 00050 } 00051 00052 public static byte[] toGrayCode(byte[] rawData) { 00053 byte[] result = rawData.clone(); 00054 for (int i = 0; i < rawData.length; i++) 00055 result[i] = byteToGrayCode(rawData[i]); 00056 return result; 00057 } 00058 }