Monday, July 23, 2018

[R] selecting m highest values in each row and their column indices from data frame

A simple microtask : you are given a data frame of numerical data. You want to find maximum values of each row with corresponding column names, and add them at the right end of the original data frame. Here is my solution using user-defined functions that invokes sort(). May not be an efficient or R-native code though. Leave a comment please for a better solution.

maxval1 = function(x) {
  q <- sort(x)
  return(q[length(x)])
}
maxcol1 = function(x) {
  q <- sort(x)
  return(names(q)[length(x)])
}
df <- cbind(df, val1 = apply(df, 1, maxval1), col1 = apply(df, 1, maxcol1))
df <- data.frame(df)

The above code appends maximum value of each row and matching column names at the end of existing data frame df. You only need to replace length(x) by length(x) - k for (k+1)th highest value / index. Or you can replace it with 0, 1, ..., k for lowest value / index.


Saturday, July 21, 2018

Project Euler #110 - 41 days spent on a problem

Project Euler Problem #110 is an extended version of #108. The latter can be solved with simple brute force code pretty quickly, but the former obviously defies such simple-minded approach. One should generalize #108 in order to solve #110.

I solved #108 in Jun 10 by brute force. I immediately started finding the general rule. It took me, however, about 40 (four zero) days in the end. Even though I haven't been on this problem 24/7 for the last 41 days, I must have attempted over 50 times in total.

I am proud of myself not having searched for any solution or hint in the mean time. There are other problems for which I spent 2~3 weeks to solve, but 41 days on #110 is definitely my personal record.

* Most of the 50 attempts were purely speculative (even without pen and paper). Not much progress with the brain-only attempts, so I decided to revise #108 code to rearrange and extend the result. That helped in the end; even with it I still had to spend another 2~3 days until finally figuring out the rule.

Philips SAECO Xsmall espresso machine repaired

I have a SAECO Xsmall espresso machine. I bought it in Dec 2014, and brewed 2~3 cups of espresso per day on the average over the last 6 year...