Random musings about programming stuff like laying in the grass and watching the clouds go by ...

 

Find the unique element in a vector

Assume a vector with repeating and unique elements, for example:

x <- c(3, 5, 4, 5, 3)

How do you find the unique element? One way is to use the base R table function:

x <- c(3, 5, 4, 5, 3)
library(magrittr)
table(x) %>%
  data.table::as.data.table(.)
#    x N
# 1: 3 2
# 2: 4 1
# 3: 5 2

# 4 appears 1 time, so this is the unique element

Another possibility: use the vctrs package:

c(3, 5, 4, 5, 3) %>%
  vctrs::vec_count(.)
#   key count
# 1   5     2
# 2   3     2
# 3   4     1

Now assume the vector contains 2n + 1 elements, where n elements are repeating and 1 element is unique. A possibility to find that unique element is to use the amazing bitwise XOR operator:

c(3, 5, 4, 5, 3) %>%
  purrr::reduce(
    .x = .,
    .f = bitops::bitXor
  )
# 4

This uses the fact that the XOR bitwise operator is commutative, associative and that an element XORed with itself is zero. Pretty nifty, or?

 

Calculate pi

The other day I stumbled upon 20 controversial programming opinions. One of the opinions: "If you’re a developer, you should be able to write code". Job candidates were given the task to calculate pi using the Leibniz formula and many candidates failed.

I realized with horror that probably I would have also failed the test...

In the comments, somebody gave this solution in Python:

from itertools import cycle, count, islice

n = 5000000
ones = cycle([1, -1])
odds = count(1, 2)
fracs = map(lambda x: 1.0 / (x[0] * x[1]), zip(ones, odds))

print(sum(islice(fracs, n)) * 4)

Here my attempt in R:

calculate_pi <- function(n)
{
  x <- seq(from = 1, to = n, by = 2)
  times <- length(x)
  sign <- rep(c(1, -1), times)

  y <- sign[1:times] * 1/x

  out <- 4 * sum(y)
  return(out)
 }

calculate_pi(5e2)
# [1] 3.137593

As you can see, I did not care how efficient the calculation was. I still don't know how to calculate pi to an accuracy of 5 decimal places (still a very long way to go to become a developer)... If you have a hint for me, please let me know.

Here other ways to calculate pi in R and in Python.

 

Make a promise. Show up. Do the work. Repeat.