Skip to content

Instantly share code, notes, and snippets.

@nwstephens
Last active March 28, 2023 23:27
Show Gist options
  • Save nwstephens/f969abc61aac07dc1fce914a4a6eb0a5 to your computer and use it in GitHub Desktop.
Save nwstephens/f969abc61aac07dc1fce914a4a6eb0a5 to your computer and use it in GitHub Desktop.
Integers that describe their own digits
# Integers that describe their own digits
# Nathan Stephens
# 3/28/2023
###################
# Background
###################
# We seek numbers whose digits describe how many digits are in that same number
# For example, consider 42,101,000, which has 8 digits.
# We index those digits 0-7, and consider how many of each index are in the number.
# There are four 0's
# There are two 1's
# There is one 3
# And there is one 4
###################
###################
# Solutions
###################
# 4: 1210
# 4: 2020
# 5: 21200
# 6: #N/A
# 7: 3211000
# 8: 42101000
# 9: 521001000
# 10: 6210001000
# 11: 72100001000
# 12: 821000001000
# 13: 9210000001000
###################
# Input size
n<-7
s<-0:(n-1)
# Prune permutation inputs
prune<-as.list(as.data.frame(matrix(s, n, n)))
prune[length(prune)]<-0L
prune<-lapply(prune, function(x) head(x, n-3))
# Create permutations and prune
M<-expand.grid(prune)
M<-M[apply(M, 1, sum)==n, ]
# Identify results
f<-function(x, s) all(sort(x)==rep(s, x))
ind<-which(apply(M, 1, f, s))
out<-as.numeric(apply(M[ind, ], 1, paste, collapse=""))
out
###################
# Alternative code
###################
s<--1+1:7
M<-expand.grid(as.data.frame(matrix(s, length(s), length(s))))
M[which(apply(M, 1, function(x) all(sort(x)==rep(s, x)))), ]
@nwstephens
Copy link
Author

The alternative code calculates results in three lines, but there is no pruning, so computations are slow.

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