cd ..

:~/Code Golf In R (7/23/2022)


I really enjoy writing R code. Programming always feels like a series of little puzzles to me. I love it. It makes my work feel like play. But occasionally, I also like to actually play with code.

The goal in code golf is to produce a program that solves a problem with as few characters as possible. There are some languages that are better than others for this game. In fact, there are some languages that are designed specifically for code golf. See: Golf Script. My R entries rarely stand a chance.

However, I recently worked on a code golf problem where R does pretty well. This problem comes from Here.

Here is the prompt for the challenge:

"An abundant number is a number for which the sum of its proper divisors (divisors not including the number itself) is greater than the number itself. For example 12 is abundant because its proper divisors are 1, 2, 3, 4, and 6 which add up to 16. Print all the abundant numbers from 1 to 200 inclusive, each on their own line."

My Solution in R (46 Characters)
a=1:200
t(t(a[((!outer(a,a,”%%”))%*%a)>=2*a]))
This code takes advantage of R’s matrix functions and operators.
a=1:200
This sets up an array of integers from 1 to 200 and saves it as "a". outer(a,a,”%%”) This makes a matrix with the remainder of dividing the row number by the column number.

Now our first hack. ! is logical negation, but it treats anything but 0 as true. Thus, negating the matrix of remainders will put FALSE anywhere there is a remainder and true anywhere there is no remainder. Thus, we get a logical matrix where each row has a TRUE in any column that is a divisor of that row number.
!outer(a,a,”%%”))%*%a
This multiplies the logical matrix with a itself. Since a logical matrix is treated as a matrix of 1s and 0s when passed into a numeric operation, this gives us the row sums. That is, the sum of the divisors of each row.
!outer(a,a,”%%”))%*%a)>=2*a
I now check which of the sums of divisors is greater than 2a. I use 2a since a itself is always a divisor using this method. This provides a logical vector of which numbers are abundant.
a[((!outer(a,a,”%%”))%*%a)>=2*a]
This now subsets a with the logical vector to provide which numbers are abundant.

The pair of
t(t())
functions simply transposes the vector twice so that each abundant number is printed on a new line. This is also a bit of a hack.