Exercise 2-3
authorwatkinsr <ryanwatkins54@gmail.com>
Fri, 5 Jun 2020 14:40:08 +0000 (15:40 +0100)
committerwatkinsr <ryanwatkins54@gmail.com>
Fri, 5 Jun 2020 14:40:08 +0000 (15:40 +0100)
goproglang
main.go
popcount/popcount.go [new file with mode: 0644]

index b1c69033dcc0bd023f0834f68b814a6d4e51a86a..625fe71a7712e80677d9f27d831fba9d29b9a875 100755 (executable)
Binary files a/goproglang and b/goproglang differ
diff --git a/main.go b/main.go
index 0d36f5a17f450d77b8d16ec8a50be40e340a42ff..53b41eda4594e08941b978b6934e8df76e49682a 100644 (file)
--- a/main.go
+++ b/main.go
@@ -2,8 +2,10 @@ package main
 
 import (
   // "git.ryanwatkins.me/goproglang/httpserve"
+  "time"
   "fmt"
   "git.ryanwatkins.me/goproglang/tempconv"
+  "git.ryanwatkins.me/goproglang/popcount"
 )
 
 func main() {
@@ -11,4 +13,15 @@ func main() {
   fmt.Println(tempconv.CToF(tempconv.BoilingC))
   fmt.Println(tempconv.CToK(tempconv.AbsoluteZeroC))
   fmt.Println(tempconv.FToK(tempconv.CToF(tempconv.FreezingC)))
+
+  // Exercise 2-3
+  t := time.Now()
+  fmt.Printf("popcount: %d\n", popcount.PopCount2(120))
+  res := time.Since(t)
+  fmt.Printf("Time using single statement: %v\n", res)
+  
+  t = time.Now()
+  fmt.Printf("popcount: %d\n", popcount.PopCount(120))
+  res = time.Since(t)
+  fmt.Printf("Time using loop: %v\n", res)
 }
diff --git a/popcount/popcount.go b/popcount/popcount.go
new file mode 100644 (file)
index 0000000..5202d93
--- /dev/null
@@ -0,0 +1,29 @@
+package popcount
+
+// pc[i] is the population count of i
+var pc [256]byte
+
+func init() {
+  for i := range pc {
+    pc[i] = pc[i/2] + byte(i&1)
+  }
+}
+
+// PopCount returns the population count (number of set bits) of x
+func PopCount(x uint64) int {
+  var res int
+  for i := 0; i < 8; i++ {
+    res += int(pc[byte(x>>(i * 8))])
+  }
+  return res
+}
+func PopCount2(x uint64) int {
+  return int(pc[byte(x>>(0*8))] + 
+      pc[byte(x>>(1*8))] +
+      pc[byte(x>>(2*8))] +
+      pc[byte(x>>(3*8))] +
+      pc[byte(x>>(4*8))] +
+      pc[byte(x>>(5*8))] +
+      pc[byte(x>>(6*8))] +
+      pc[byte(x>>(7*8))])
+}