Monday, December 9, 2013

Binary representation of an int type value with bitset::to_string

Get the binary representation of an integral type using bitset's to_string method:
#include <bitset>
#include <iostream>
#include <string>

template <typename T>
std::string getBinary(T t) {
  unsigned long val = t;
  std::bitset<8 * sizeof t> bits(val);
  return bits.to_string();
}

int main() {
  using namespace std;
  while (cin) {
    unsigned short x;
    cin >> x;
    cout << getBinary(x) << '\n';
  }
}

Saturday, March 7, 2009

Transpose list

transposeList <- function(aList) {
if (length(aList) == 0) {
return(c())
}

colNames <- names(aList[[1]])
result <- replicate(length(colNames), list())
names(result) <- colNames
rowNames <- names(aList)
for (row in rowNames) {
for (col in colNames) {
result[[col]][[row]] = aList[[row]][[col]]
}
}
return(result)
}
What's a better way to do this?

Saturday, June 21, 2008

static field shared between instances of generic

The documentation says that one implementation is shared. I guess it makes sense this translates to one copy of the class variables getting shared as well.
public class GenericStatic<T> {
static String o = "";
String oo() {
return o += "o";
}

public static void main(String[] args) {
GenericStatic<Object> a = new GenericStatic<Object>();
GenericStatic<String> b = new GenericStatic<String>();
System.out.println(a.oo());
System.out.println(b.oo());
}
}
$ javac GenericStatic.java
$ java GenericStatic
o
oo

Wednesday, June 18, 2008

R: keeping a 1-d subset of a matrix a matrix

By default, if a subsetting operations yields a one-dimensional matrix (row or column vector), the dimensions are dropped.
> (m <- matrix(1:4, nrow=2))
[,1] [,2]
[1,] 1 3
[2,] 2 4
> (v <- m[1, 1:2])
[1] 1 3
This can cause problems when we want to go ahead and continue using the result in matrix operations:
> v %*% m %*% t(v)
Error in v %*% m %*% t(v) : non-conformable arguments


The solution is to explicitly tell R not to drop the dimensions:
> (v <- m[1, 1:2, drop=FALSE])
[,1] [,2]
[1,] 1 3
> v %*% m %*% t(v)
[,1]
[1,] 52


Something else to look at: removing a column, given its name in a variable: Chris Handorf, subsetting a dataframe

Friday, June 13, 2008

printf("%02d", n)

irb(main):005:0> printf "%02d\n", 3
03
=> nil
irb(main):006:0> printf "%02d\n", 13
13
=> nil
irb(main):007:0> printf "%02d\n", 113
113
=> nil

Use printf to format numbers, filling in with zeros for 1 digit numbers. *
(This is Ruby but I'm marking this as C since that's where I'm most likely to end up using it.)

Thursday, June 12, 2008

get flat output in Maxima

I think I've written before this before but a search didn't turn it up. This just concerns getting "flat", all-on-one-line, non-fancy ASCII output from Maxima. (This is especially useful when the output is destined to be converted into C code.)

(%i8) display2d: false$
(%i9) %e^t;

(%o9) %e^t
(%i10) display2d: true$
(%i11) %e^t
;
t
(%o11) %e

Wednesday, June 11, 2008

Speaking game using python and Mac OS X's say

#!/usr/bin/env python

import os
import random

def say(word):
os.system("say " + word)

class Score:
def __init__(self):
self.total = 0
self.correct = 0

if __name__ == '__main__':
pairs = [["bed", "bad"], ["sped", "speed"],
["wary", "very"], ["bull", "ball"],
["mall", "mole"], ["pale", "pull"],
["soup", "stoop"], ["file", "fill"]]
scores = {}
for pair in pairs:
scores["".join(pair)] = Score()
input = ""

print("To quit, enter q")
while input != "q":
pair = random.choice(pairs)
word = random.choice(pair)
print("1) " + pair[0])
print("2) " + pair[1])
say(word)
input = raw_input("What did the computer say?: ")
input = input.strip()

if input != "q":
key = "".join(pair)
score = scores[key]
score.total += 1
if input == word:
score.correct += 1
print("Correct!")
else:
print("Wrong!")
print("You\'ve gotten the right answer for "
+ " vs ".join(pair) + " "
+ str(score.correct) + " out of "
+ str(score.total) + " times")
Here's a little game to drill you on somewhat similar sounding pairs of English words. I'm sure much could be done to improve it. Is the use of a class here kosher with Python practice? What's contrary to idiom here?