A-M baby
This commit is contained in:
parent
764da6cbbb
commit
db842d013d
19005 changed files with 197040 additions and 7 deletions
6
Task/Gray-code/Scala/gray-code-1.scala
Normal file
6
Task/Gray-code/Scala/gray-code-1.scala
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
def encode(n: Int) = (n ^ (n >>> 1)).toBinaryString
|
||||
def decode(s: String) = Integer.parseInt( s.scanLeft(0)(_ ^ _.asDigit).tail.mkString , 2)
|
||||
|
||||
println("decimal binary gray decoded")
|
||||
for (i <- 0 to 31; g = encode(i))
|
||||
println("%7d %6s %5s %7s".format(i, i.toBinaryString, g, decode(g)))
|
||||
19
Task/Gray-code/Scala/gray-code-2.scala
Normal file
19
Task/Gray-code/Scala/gray-code-2.scala
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
def encode(n: Long) = n ^ (n >>> 1)
|
||||
|
||||
def decode(n: Long) = {
|
||||
var g = 0L
|
||||
var bits = n
|
||||
while (bits > 0) {
|
||||
g ^= bits
|
||||
bits >>= 1
|
||||
}
|
||||
g
|
||||
}
|
||||
|
||||
def toBin(n: Long) = ("0000" + n.toBinaryString) takeRight 5
|
||||
|
||||
println("decimal binary gray decoded")
|
||||
for (i <- 0 until 32) {
|
||||
val g = encode(i)
|
||||
println("%7d %6s %5s %7s".format(i, toBin(i), toBin(g), decode(g)))
|
||||
}
|
||||
4
Task/Gray-code/Scala/gray-code-3.scala
Normal file
4
Task/Gray-code/Scala/gray-code-3.scala
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
def decode(n:Long)={
|
||||
def calc(g:Long,bits:Long):Long=if (bits>0) calc(g^bits, bits>>1) else g
|
||||
calc(0, n)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue