Skip to content

Instantly share code, notes, and snippets.

@cb372
Created October 20, 2011 04:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cb372/1300391 to your computer and use it in GitHub Desktop.
Save cb372/1300391 to your computer and use it in GitHub Desktop.
CodeJam 問題C. ビット数 first attempt
/*
* Ridiculous bit counting algorithm
* http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
*/
def f(x:Int):Int = {
var v = x - ((x >> 1) & 0x55555555)
v = (v & 0x33333333) + ((v >> 2) & 0x33333333)
(((v + (v >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24
}
def findMax(N: Int) = {
var max = 0
// Filter out the low-hanging fruit: case where both a and b are even
for (i <- (N/4 to N/2 filter(i => !(i%2 ==0 && (N-i)%2 == 0)))) {
max = math.max(max, f(i)+f(N-i))
}
max
}
import scala.io.Source
val lines = Source.fromFile("C-small-practice.in").getLines()
lines.toList.tail.zipWithIndex.foreach{ valAndIndex => println("Case #"+(valAndIndex._2+1)+": "+findMax(valAndIndex._1.toInt)) }
@sakamotodesu
Copy link

日本語コメントできるのかな?

f()がなにやってるのかよくわからん…じっくり読んでみるよ。
Scalaのソースコードって初めて見るけど、読みやすいね。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment