We spend a lot of time talking about it. And to be honest, in my opinion, not very much time actually doing anything about it.
Competence is the ability to do something successfully or efficiently.
It follows logically, that when you develop your competences, you will, afterwards, be able to do something (successfully) that you were not able to do before. Or you will be able to do it more efficiently, ie better or faster.
Usually it is not enough to acquire a skill. “Use it or lose it” they say. I was actually speaking pretty good german when I was 15. Today I’m anything but fluent, and struggling with Duolingo to regain the skills I had 28 years ago. I do read technical german pretty well. And that testifies to the fact, that I have used the part of my “german competences” that relates to technical texts. Whereas I have not used the part that allows me to speak or understand spoken, german.
It’s the same with the skills you need at your job. You may acquire some skills at a course, by reading a book, by getting peer-training. But if you don’t use them afterwards, you loose them.
Far too often we spend time attending a course, get back to work, and not use the things we learned. The net result is that we wasted the time and money spend on the course. Noone made sure that we had the time to use our new skills. Or that procedures in the organization was changed accordingly. Maybe we learned skills that we don’t really need.
It would be fun to learn to weld. And even better if my boss would pay for it. But I would never get to use that skill at work. Or at home. So it would be a bloody waste of time! It would probably be bloody in a literal sense as well…
That is one problem. Developing skills and competences that are not actually useful. Or used. I have had it happen to me several times. I’ve even paid for useless courses and activities out of my own pocket.
The other problem is labelling.
We all agree that competence development is positive. We want more of it. It is nice, and necessary. Therefore it is not surprising, that we would like to label activities that does not really develop any competences, as developing competences. I have been required to register, as competence development, giving an introduction to ebook readers. I agree that the participants in the course, the colleagues subjected to me talking about ebook readers for 1½ hours, had their competences developed. Or at least I hope they had.
But how is giving that introduction developing my competences? As an academic I am able to argue for, or againts, anything, sometimes even at the same time. But my competences regarding ebook readers were definitely not developed. I might have gotten slightly better at giving introductions. But I did not learn anything new about ebook readers.
Why do I care? Well. First of all I abhor newspeak. If something is not developing competences, dont claim that that is what is happening. It might be interesting. It might be beneficial. But if competences are not developed, they are not developed, and please do not claim that they were.
Secondly, it generates the impression that we are spending a lot of resources on developing competences. That is a problem if that impression is false. We will wake up some day, and wonder why we did not learn what was necessary to survive in a changing library landscape. It will be a mystery to us, because we thought we were spending a lot of time developing all sorts of competences. But in reality we did not develop anything.
Anyway. Assume we have five cases, with two values for a given treatment, each labelled “AVO” and “INT”. How to get a barchart, where each cases is one bar, and the bars are coloured based on the percentages of the two values?
## cases treatment value
## 1 1 AVO 0.9769620
## 2 2 AVO 0.3739160
## 3 3 AVO 0.7615020
## 4 4 AVO 0.8224916
## 5 5 AVO 0.5735444
## 6 1 INT 0.6914124
## 7 2 INT 0.3890619
## 8 3 INT 0.4689460
## 9 4 INT 0.5433097
## 10 5 INT 0.9248920
OK, nice and tidy data.
What I want is a bar for case 1, filled with percentages. One color with 0.976/(0.976+0.691) and another color for 0.691/(0.976+0.691).
library(ggplot2)
ggplot(df)+
geom_col(aes(y=value, x=cases, fill=treatment), position = "fill")
We’re using geom_col. That is a shorthand for geom_bar with stat=“identity”, and is the shortcut to expressing values in the barchart.
The y-value is the value from df, the x-value is the cases. And we’re colouring the bars based on the value in treatment. The position=“fill” stack the bars, and normalize the heights. If we wanted to just stack the elements, we would use position=“stack”:
ggplot(df)+
geom_col(aes(y=value, x=cases, fill=treatment), position = "stack")
This is a great, like really great, cheatsheet for ggplot:
Testing for a Royal Flush. All values of suits should be identical. And the values should be T, J, Q, K, A. That is simple. Check if all the values that should be in the hand, if it is a Royal Flush are there. Then check if the suit is the same for all cards in the hand. If both are true, return TRUE.
Straight Flush: All cards are consecutive values of same suit.
Testing for the same suit is copy-paste from above. Testing for consecutive values is a little bit more tricky. I cant just sort the values, since K is before Q in the alphabet. So I’m using dplyr::recode() to recode the T, J, Q, K, A values to numbers. The I can convert them to numeric and sort them. And I’ll just have to figure out if the values are consecutive.
I had to google a bit. But diff() does it. It calculates the difference between the elements. It is possible to define a lag, but here the default of 1 does the trick. It returns the second element in the vector, minus the first element. And the third element minus the second.
When I have five elements, and they have consecutive values, diff() will return a vector of 4 ones.
We are not interested in the suits here. First I get the values. Then I use table() to get the counts of the different values. Passing that to max() returns 4, if there are four identical values.
Full House: Three of a kind and a pair. I use the same functionality as in is_four_of_a_kind. The trick here is, that the max of the tabulation of values should be 3. But the minimum should also be 2.
Flush: All cards of the same suit. In is_straight_flush I test if the suits are the same. That is what I need here, I just skip the part where I test if the values are consecutive.
Three of a Kind: Three cards of the same value. That is basically the same as the function is_four_of_a_kind() above. The maximum value from the table should just be 3 instead of 4:
Two Pairs: Two different pairs. First I use values() to get the values of the hand. I’m not interested in the suits.
Then I tabulate the testvalues. I get a count of the number each value occurs in the hand.
But I’m no interested in that number. If there are two pairs in the hand, I will get two values, that occurs two times.
So if I run table() on the result again, I get a count of how many times the count 2 occurs. If the count 2 occurs twice, there are two hands.
It will return FALSE if there are three of a kind. I’m interested in the highest rank a hand can get, so that should not be a problem.
High Card: Highest value card. I don’t need to test for this. If a hand has not gotten a higher rank, it will always have this.
Nice. I now have a set of functions that I can use to figure out what hand has the highest rank.
Lets put that together:
rank <- function(testhand){
res <- 1 # The hand will never get a rank lower than 1.
if(is_pair(testhand)){res <- 2}
if(is_two_pairs(testhand)){res <- 3}
if(is_three_of_a_kind(testhand)){res <- 4}
if(is_straight(testhand)){res <- 5}
if(is_flush(testhand)){res <- 6}
if(is_full_house(testhand)){res <- 7}
if(is_four_of_a_kind(testhand)){res <- 8}
if(is_straight_flush(testhand)){res <- 9}
if(is_royal_flush(testhand)){res <- 10}
return(res)
}
That should solve a lot of the cases. However. What if the rank of two hands are the same?
If both hands have rank 9, that is if they are both straight flush, the hand with the highest card wins. There is no reason to test for the rest of the cards.
For all the others, I need functions that breaks the tie. It it should be broken.
Most of those determinations will be based on the value of the cards. So I might as well have a function that recodes ace to 14 etc.
recode_value <- function(values){
as.numeric(recode(values, T = "10", J = "11", Q = "12", K = "13", A = "14"))
}
For High Card, the hand with the highest value card wins. If the highest value card in both hand 1 and hand 2 is equal, we look at the second highest card in each hand. Etc. Only if the values are identical in the two hands is there a tie.
All right. That was not easy… First I get the values for the two hands. Then I recode them to numerical values, and sort them.
If the two hands have equal values, it is a tie. Otherwise, while the last element in the first vector containing the values is equal to the last element in the second vector, I get rid of the last element in both vectors.
When that is done, the last element in the two vectors is compared. The hand with the highest value wins.
The funcion returns 0 if it is a tie, 1 if hand1 wins, and 2 if hand2 wins.
This was actually the hardest part to write.
Next. Breaking the tie between two hands each having one pair.
First I’m picking out the values of the pairs in the two hands. If hand1 has a pair of 8’s and hand2 has a pair of 7’s, hand1 wins.
If the pairs are of the same value. Then I pick out the values of the rest of the cards. I am making a dangerous assumption here. This will only work if the two hands actually only have one pair. I hope it works, but this is one of the places where it could go wrong.
Two Pairs: Two different pairs.
The hand with the highest value pair wins. If those values are identical, the value of the second pair determines the winner. If that is also equal, the value of the fifth remaining card, determines the winner.
Only if that is also equal, is there a tie. Therefore, there can only be a tie, if all values of all cards are equal.
break_two_pairs <- function(hand1, hand2){
v1 <- values(hand1)
v2 <- values(hand2)
v1 <- recode_value(v1)
v2 <- recode_value(v2)
v1 <- table(v1)
v2 <- table(v2)
v1_pair <- sort(as.numeric(names(v1)[v1==2]))
v2_pair <- sort(as.numeric(names(v2)[v2==2])) # now v1_pair and v2_pair contains the values of each of the pairs in each of the hands.
if(identical(v1_pair,v2_pair)){ # If the pairs have the same value, pick out the fifth value, and compare them.
v1 <- as.numeric(names(v1)[!v1==2])
v2 <- as.numeric(names(v2)[!v2==2])
if(v1>v2){
return(1)
break()
}
if(v2>v1){
return(2)
break()
}
if(v1==v2){
return(0)
break()
}
} else {
v1 <- rev_recode_value(v1_pair)
v2 <- rev_recode_value(v2_pair)
return(break_high_card(v1,v2))
}
}
Kinda the same as for one pair. v1_pair and v2_pair ends up with vectors containing the values of the two pairs in the two hands.
If these two vectors are identical, we need to look at the fifth value.
If not, I reverse_recode the values of the pairs, and use break_high_card, to determine which is larger.
Three of a Kind: Three cards of the same value.
Again I’m making the assumption that the two hands passed to this function have three of a kind. And nothing better than that.
This is a bit simpler. There is no way that both hands can have three of a kind with the same value. So I don’t need to consider the remaining cards. The assumption here is that there is only on deck of cards involved. This is another place where things can go wrong. But lets try!
I convert to values, recode them, tabulates them. And pick out the values that occur three times. Then I just compare them.
Straight: All cards are consecutive values.
Once more I assume that the two hands passed to this function actually only contains a straigth. It is rather simple. As the values must be consecutive, the highest value in each hand determines the winner.
I read in the file to data, make a column h1 containing the first 14 characters of each line in the datafile, and a column h2 containing the rest of the line.
rowwise() groups the dataframe by row – so it doesn’t matter that my winner() function is not that vectorized. For each set of hands I calculate the winner, filter the result so I only have the rows where hand 1 wins. And then I get the number of rows – which are the answer.
Lessons learned
Some. rowwise() is a usefull function. I’m certain I dont understand everything about it, but it would seem to solve a fair number of the problems I’ve had using non-vectorized functions.
I should probably also learn to set aside some time for re-factoring my code before publishing it.
3797 is a prime. What is interesting about this prime, is that if we truncate it one digit at a time from left, ie:
3797, 797, 97, 7 every step is also prime. And if we do the same from the right, we see the same property:
3797, 379, 37, 3.
There are 11 primes with this property. What is the sum of them?
2, 3, 5 and 7 are not considered to be truncatable primes.
And that gives us a hint. The first digit of a truncatble prime must be either 2, 3, 5 or 7. And the last digit must be 3, 5 or 7.
Lets begin by loading the package numbers:
library(numbers)
That gives us couple of useful functions. isPrime(x) returns true if x is prime. And Primes(x,y) returns all primes between x and y.
I am going to need a couple of functions. One that repeatedly truncates a number from the left, and returns true if all the steps in the sequence are prime. And another that does the same, just from the rigth.
truncleft <- function(x){
res <- TRUE
while(x>9){
x <- x %/% 10
res <- isPrime(x)*res
}
return(as.logical(res))
}
truncright <- function(x){
res <- TRUE
while(x>9){
x <- x - (x %/% 10**floor(log10(x)))*(10**floor(log10(x)))
res <- isPrime(x)*res
}
return(as.logical(res))
}
Now I can determine if a given number is truncatable prime from both left and right. Next, finding all 11 primes with that property.
Lets take a chance, and see if not number 11 is found before we reach 1000000
Yep. The difficult part is finding number 11. The first four primes with this property have two digits – you can find them manually. The next four are a bit more difficult. Number 10 is the example Project Euler provides.
Lessons learned
Well – purrr is pretty useful. But I already knew that.
This problem is basically about making a sudoku solver, that can be automated. If you don’t know what a sudoku is – google it and come back.
I have solved a LOT of sudokus. Manually. There are several techniques, but some of them are not that easy to code. And of course I’ll need a method that guarantees a solution.
It is called backtracking. The process is to look at all the empty cells.
In the first one – insert the lowest allowed value, and progress to the next empty cell. Insert the lowest allowed value in it. Continue until you reach a cell with no allowed values. When you do that, go back to the previous cell, and insert the next-lowest allowed value. And then go back (forward?) to the next cell. If the cell you went back to also have no allowed values, you go one step futher back. Continue until you reach the last cell in the puzzle.
So. We’ll need a few things.
First of all we’ll need a matrix in which to keep the sudoku.
I’m going with a matrix rather than a dataframe after reading the R Inferno (https://www.burns-stat.com/pages/Tutor/R_inferno.pdf), that suggests that there is no reason to work with a dataframe if a matrix will do.
I’ll need a couple, or three (actually more like five) functions to figure out what values are allowd for a given cell in a given sudoku.
And I’ll need a way to keep track of which cells that are “frozen”, and which cells should be filled out.
Lets begin by making a matrix to keep the puzzle in. Project Euler provides us with a puzzle and the matching solution. And a file with 50 puzzles that needs to be solved.
The structure is rather simple. 500 rows. First one row with an identifier, eg “Grid 01”. And then 9 rows with just the rows of digits, 0 for the empty cells.
We’ll need to pick out first the rows 1 to 10, then rows 11 to 20 etc.
Nice and simple, 50 rows with an 81 character long string of digits. This is the first puzzle in the file. It is also the puzzle where we are provided with a solution.
We now need to convert that to a matrix.
Or – we don’t need to. There are certainly techniques that would allow me to handle it as-is. But I think it is more intuitive to get it into a matrix.
So, lets do that.
mat <- matrix(as.numeric(unlist(strsplit(prob_df[1,2],""))),9,9,byrow=TRUE)
mat
Neat. Split the string in individual characters. Unlist it, and cast it to numeric. Then pass it all to matrix(), noting that we want 9 rows and 9 columns. And that the matrix should be filled by row.
Depending on where you count from, the first empty cell is 1,2. Given the values that are already filled in, what values are allowed in that cell?
First, what values are allowed based on the row? From inspection it is obvious that only the values 1, 4, 5, 6, 7, 8 and 9 are allowed. Lets write a function for that:
The function takes a row-number, in this example 1, and a matrix. mat[x,] returns the values in that row. And setdiff returns the values that are in 1:9 but not in the list of values already in the row.
More or less the exact same thing for the column:
# returnerer tilladte værdier i kolonne y i en matrix mat
colall <- function(y,mat){
setdiff(1:9, mat[,y])
}
colall(2, mat)
## [1] 1 2 3 4 5 6 7 8 9
What about the frame, the 3×3 set of numbers?
I need a subset of the matrix. For our example, cell 1,2, I need the columns 1, 2 and 3. And the rows 1, 2 and 3. Or a vector 1:3. Thankfully there is symmetry, so column 1 gives the same vector as row 1. I need a function that returns 1:3 when I pass it 1, 2 or 3. 4:6 for the values 4, 5 or 6. and 7:9 for the values 7, 8 or 9.
My good colleague Henrik has tried to solve the same problem using Python. And he suggested that the way to do it is by integer division. In this way:
Then add 1. For x = 1,2 or 3, the result is 1, for x = 4, 5 or 6, the result is 2. And for 7 through 9, we get 3.
We can then use that to look up the vector we need in a list, and return the unlisted number.
At first I had done it with three if-statements. This solution is a bit more elegant, and Henrik thinks that if-statements should be outlawed. So in the interest of keeping the peace in our office, I’m going with that.
Now I can write a function that returns the values allowed in a given cell in a given matrix, given the values that are already filled out in the frame that cell is in:
fraall <- function(x,y,mat){
res <- mat[getint(x),getint(y)]
setdiff(1:9, res)
}
The function takes the coordinates of the cell, and a matrix. Based on that, getint() returns the vectors describing the frame, and saves that subframe in res. Then I use the setdiff() function in the same way I’ve done previously.
That gives me all the constraints. What values are allowed based on row, column and frame. The intersection between these three vectors gives me the allowed values for the cell. It is now simple to write a function that returns the values allowed for a given cell in a given matrix:
allowed <- function(x,y,mat){
res <- intersect(rowall(x,mat), colall(y,mat))
res <- intersect(res, fraall(x,y,mat))
return(res)
}
Actually this is all I need for solving quite a lot of sudokus. Go through all the empty cells. Figure out what values are allowed. If only one value is allowed, plot it into the cell. Repeat until there are no more empty cells where only one value is allowed. A lot of sudokus can be solved with only that method.
The ones that cannot be solved in this way can be solved by the backtracking algorithm. But that is slow, so it might be a good idea to simplify the those puzzles by filling out what can be filled out with this method first.
So let’s write a function that does exactly that.
First I’ll need a list of the empty cells. The which() function can help me.
test <- which(mat ==0, arr.ind=T)
nrow(test)
## [1] 49
Which parts of the matrix is equal to 0? and arr.ind tells that what we want returned (when which is used on an array) is the array indeces. There are 56 0’es in the puzzle.
The first pair of values is 2,1, the next is 4,1 etc. And if I take each one of those, looks at the allowed values for those positions in the matrix, and, if there is only one value allowed, place that value in that position, I get a step closer to the solution.
This does exactly that:
for(i in 1:nrow(test)){
all <- allowed(test[i,1],test[i,2],mat)
if(length(all)==1){
mat[test[i,1],test[i,2]] <- all
}
}
nrow(which(mat ==0, arr.ind=T))
## [1] 43
And, hey presto, 6 empty cells were filled. The logic is: Find the list of allowed values based on the values in the list of empty cells. If the length is 1, set the current cell to that value.
Now I need to get a new list of empty cells:
test <- which(mat ==0, arr.ind=T)
And I could do it again:
for(i in 1:nrow(test)){
all <- allowed(test[i,1],test[i,2],mat)
if(length(all)==1){
mat[test[i,1],test[i,2]] <- all
}
}
nrow(which(mat ==0, arr.ind=T))
## [1] 29
14 previously empty cells filled!
Lets make a function that does that again and again, until there is no more improvement.
We’ll start by writing a function that does it one time:
singlevalues <- function(mat){
test <- which(mat ==0, arr.ind=T)
for(i in 1:nrow(test)){
all <- allowed(test[i,1],test[i,2],mat)
if(length(all)==1){
mat[test[i,1],test[i,2]] <- all
}
}
return(mat)
}
Then I need to run that several times. When the number of empty cells after running it is the same as the number of empty cells before, stop. No more values can be filled in.
Take a matrix. Set oldlen to 1, and newlen to 0. As long ans oldlen is larger than newlen, do this:
Set oldlen to the number of 0’es in the matrix. Run the singlevalues function from above. Find out how many empty cells, or zeroes there are now, and set newlen to that. If newlen is equal to 0, stop everything, otherwise repeat. And finally return the changed matrix.
But not every puzzle can be solved in that way. Now for the brutish way…
First of all, lets get a fresh copy of the original puzzle read in. And a fresh list of empyt cells.
All righty! Nu kan jeg løse en del sudokuer alene ved denne metode. Så er der resten…
mat <- matrix(as.numeric(unlist(strsplit(prob_df[1,2],""))),9,9,byrow=TRUE)
test <- which(mat ==0, arr.ind=T)
nrow(test)
## [1] 49
Back to the 49 empty cells.
The algorithm is as follows.
Set i <- 1
Get the row and column indeces from test[i,1] and test[i,2] respectively.
Identify the list of allowed values for that cell.
Set the value of the cell to the lowest of the allowed values.
Increment i <- i + 1.
Get the row and column indeces again.
Get the list of allowed values for that cell. If there are no allowed values, decrement i <- i -1.
If there are allowed values, set the value of the cell to the lowest of the allowed values.
When we return to a cell that already has a value, we should not set it to the lowest allowed value. We should set it to the next lowest. That is the lowest of the allowed values, excluding the value that was already there.
If we get to a cell with no allowed values (excluding the one that might already be there), the value of the cell should be set to 0, and i should be decrementet.
This function does that.
solve <- function(mat){
i <- 1
test <- which(mat ==0, arr.ind=T)
while(nrow(which(mat==0,arr.ind=T))>0){
allowedvalues <- allowed(test[i,1],test[i,2],mat)
currentvalue <- mat[test[i,1],test[i,2]]
allowedvalues <- allowedvalues[allowedvalues>currentvalue]
if(length(allowedvalues)==0){
mat[test[i,1],test[i,2]] <- 0
i <- i -1
} else{
mat[test[i,1],test[i,2]] <- min(allowedvalues)
i <- i + 1
}
}
mat
}
The function takes a matrix. It sets the counter/pointer i to 1.
Then a test-matrix is generated, containing all the positions that are empty.
While the number of empty places in the matrix is larger than zero do this:
Find the allowed values.
Find the current value in the cell.
Remove all allowed values that are smaller than the current value. In that way, taking the minimum of the remaining allowed values, will always give us the next lowest value. And if the original value was 0, we will get the lowest.
If there are no allowed values, set the value of the cell to zero, and decrement the counter.
If there are allowed values, set the value of the cell to the lowest of the remaining allowed values, and increment the counter.
I now have two functions that solves sudokus. solve(), that bruteforces it and will always get a solution. And
repsinglevalues() that uses logic, gets a solution sometimes, but not always.
I also have a dataframe with 50 sudokus that I need to solve.
And what was the task again? Take the three first digits in the first row. Concatenate them to a single three digit number. Do that for all 50 puzzles. Add them all up. That should be the answer.
answer <- 0
for(i in 1:50){
mat <- matrix(as.numeric(unlist(strsplit(prob_df[i,2],""))),9,9,byrow=TRUE)
mat <- repsinglevalues(mat)
mat <- solve(mat)
answer <<- answer + as.numeric(paste(mat[1,1:3],collapse=""))
}
Set a variable answer to zero.
Pick out the sudokus one by one.
Run the logic-solving function on it.
Then run the brute-force function on the result of that.
Pick out the three first digits in row 1, collapse them, cast as numeric, and add to the answer-variable.
Done!
Lessons learned
Errors in the logic are a bit difficult to locate. I forgot to take into account that the list of allowed values in the brute-force solution does not include the value that is already in the cell. That made the function run for eternity. Or something pretty close. Had I not made that mistake, I would finished this problem a day earlier.
Technically the lesson has not been learned yet. But below there is a note ot speed. Adding just one extra value to the puzzle reduces the time it takes to bruteforce the solution significantly.
Set-functions, here specifically setdiff(), are neat!
Notes on speed
OK. I needed a function for returning a vector for getting the relevant frame in the matrix. As I mentioned, my colleague Henrik thought it should be done wit integer division rather than if-statements.
This was the way I originally did it:
ifgetint <- function(x){
if(x %in% c(1:3)){
res <- c(1:3)
} else if(x %in% c(4:6)){
res <- c(4:6)
} else {
res <- c(7:9)
}
return(res)
}
## Unit: nanoseconds
## expr min lq mean median uq max neval cld
## ifgetint 50 55 60.824 56 58 3906 1000 a
## getint 52 57 78.630 59 60 17763 1000 a
Actually my original way of doing it was a little bit faster.
library(ggplot2)
autoplot(mbm)
So. I found two methods for solving sudokus. It would be interesting to compare them. I can’t do that on just any sudoku. I need to use one that can be solved with both methods. Luckily the first problem in the set can do just that.
mat <- matrix(as.numeric(unlist(strsplit(prob_df[1,2],""))),9,9,byrow=TRUE)
solve(mat)
## Unit: milliseconds
## expr min lq mean median uq
## solve(mat) 47.681675 52.437511 55.053319 53.852274 54.621338
## repsinglevalues(mat) 6.637329 7.001639 7.631094 7.157844 7.393044
## max neval cld
## 171.67914 100 b
## 11.03237 100 a
No surprise there. The logical method is much faster. Something like 8 times faster.
autoplot(mbm)
How much of a difference does it make when part of the sudoku has been solved already? By inspection (ie, trial and error) I find sudoku number 11. The original puzzle has 53 empty cells. By filling out what can be filled out using logic, that is reduced to 52 empty cells.
How much faster is it to solve sudoku number 11, when an additional cell has been filled out using logic?
mat is the original sudoku. redmat is the sudoku partially solved by logic.
i <- 11
mat <- matrix(as.numeric(unlist(strsplit(prob_df[i,2],""))),9,9,byrow=TRUE)
redmat <- repsinglevalues(mat)
mbm <- microbenchmark(solve(mat),solve(redmat), times=10)
mbm
## Unit: milliseconds
## expr min lq mean median uq max neval
## solve(mat) 767.3325 777.2788 794.4597 781.4264 791.7815 911.4314 10
## solve(redmat) 544.3811 546.2505 574.9207 549.2904 553.6324 690.5734 10
## cld
## b
## a
Wow! That really makes a difference!! Filling in just a single extra value using logic cuts about one third of the time it takes to solve the sudoku.
Just a short note to help me remember the melt()-function.
Lets create some messy data:
ID <- 1:10
T1 <- runif(10,10,20)
T2 <- runif(10,20,30)
T3 <- runif(10,30,40)
df <- data.frame(ID=ID, T1=T1, T2=T2, T3=T3)
This is heavily inspired by a practical problem a student came to us with. There is 10 different patients, at time = T1, there is a certain value measured on the patient. At time = T2 the same value is measured. And again at time = T3, where T1<T2<T3.
We would now like to plot the development of those values as a function of time (or just T1,T2 and T3).
How to do that?
Using reshape2, and making sure we have the tidyverse packages loaded:
Back to the hopeless examples of probabilities from school.
In a bag there are 15 black balls and six white ones. Project Euler talks about discs, math-teachers has always used balls as examples, and they where always white and black. So I’ll stick with that.
It you draw two balls from the bag, there is a 50/50 chance of drawing 2 black balls:
(15/21)*(14/20)
## [1] 0.5
I’m told that the next set of balls in the bag with that property, is 85 black balls and 35 white ones:
(85/120)
(85/120)*(84/119)
## [1] 0.5
Find the mix of black and white balls, that gives a probability of 50/50 of drawing 2 black balls, given that there should be more than 10¹² = 1000000000000 balls in the rather large bag.
That should be straight-forward.
Lets call the number of black balls b and the number of white balls w. And lets define the total number of balls in the back as n=w+b
The probability of drawing two black balls is:
(b/n)((b-1)/(n-1)) = ½
n = w + b > 10¹²
Two equations with two unknowns.
The probability can be rearranged:
(b/n)((b-1)/(n-1)) = ½ <=>
b(b-1) / n(n-1) = ½ <=>
(b² – b) / (n² – n) = ½ <=>
b² – b = ½(n² – n) <=>
2b² – 2b = n² – n <=>
2b² – 2b – n² + n = 0
Hm. Maybe it is not that simple after all. First of all I don’t know if n is 100000000000 or 100000000001. That actually makes a pretty big difference:
1000000000001**2 - 1000000000000**2
## [1] 1.999978e+12
Second of all, I need to find integer solutions. An analytical solution might not give integer results. And I can’t have one third of a ball in the bag.
Googling “finding integer solutions to equations” give, as the first result, a link to the wikipedia article on “Diophantine equations”.
Which apparently are equations that should have integer solutions.
All right, a couple of the problems I’ve tackled earlier, and quite a lot of Project Euler problems I’ve given up on appears to be about solving these Diophantine equations.
So. Nice. The last link of the wikipedia page is to https://www.alpertron.com.ar/QUAD.HTM.
I should probably read up on the methods. But that will have to wait.
The point is, that this Diophantine equation can be solved by:
b~n+1~ = 3b~n~ + 2n~n~ -2
n~n+1~ = 4b~n~ + 3n~n~ -3
The idea is that we have a solution (b~n~, n~n~). And these two equations allows us to calculate the next solution, (b~n+1~, n~n+1~)
Lets try that, we was given that (15,21) was a solution. The next should be (85,120). Do we get that?
Qap’la, it works. Nice. Now I just need to run through this until n~n+1~ gets above 10¹².
b <- 15
n <- 21
while(n<10**12){
b_n <- 3*b + 2*n -2
n_n <- 4*b + 3*n -3
b <- b_n
n <- n_n
}
answer <- b
Lessons learned:
Solving Diophantine equations is at the heart of a lot of these problems. I’ve learned a new tools to handle them!
If you want to subscript stuff in RMarkdown, you place a ~ on each side of what you want subscripted.
Other stuff to note: Maybe it is time someone wrote a new solver for Diophantine equations. The one I found is 19 years old. Something to do in Shiny perhaps?
The problem tells us that if the square root of a natural number is not an integer, it is irrational.
Project Euler also claims that it is well known. I did not know it.
We are then told that the square root of 2 is 1.4142135623730950… And that the digital sum of the first 100 digits is 475.
The task is now to take the first 100 natural numbers. And find the total of the digital sums for the first 100 digits for all the irrational square roots.
Lets begin by figuring out how to handle that many digits. R does not support more than around 15 places after the decimal point.
The library Rmpfr can handle arbitrary precision:
library(Rmpfr)
## Loading required package: gmp
##
## Attaching package: 'gmp'
## The following objects are masked from 'package:base':
##
## %*%, apply, crossprod, matrix, tcrossprod
## C code of R package 'Rmpfr': GMP using 64 bits per limb
##
## Attaching package: 'Rmpfr'
## The following objects are masked from 'package:stats':
##
## dbinom, dnorm, dpois, pnorm
## The following objects are masked from 'package:base':
##
## cbind, pmax, pmin, rbind
a <- sqrt(mpfr(2,500))
The variable a now contains the square root of 2 with a precision of 500 bytes. I’m not quite sure how many decimal places that actually translates to. But testing the following code allows me to conclude with confidence that it is at least 100.
A thing to note here is, that
a <- mpfr(sqrt(2),500)
and
a <- sqrt(mpfr(2,500))
are not equal. In the first exampel sqrt(2) is evaluated before saving the value with the high precision. Start by converting the number 2 to a high precision representation, before doing math on it.
Next is writing a function that will return the digital sum of the first 100 digits of a number.
digitsum <- function(x){
s <- 0
for(i in 1:100){
s <- s + floor(x)
x <- (x - floor(x))*10
}
s
}
First s is initialized to 0. Then floor(x) gives us the first digit in x. We add that to s, and subtract it from x, and multiply by 10. Repeat that 100 times, and you get the sum of the first 100 digits in x.
Let us test that it works. Project Euler told us what the result for sqrt(2) is:
digitsum(a)
## 1 'mpfr' number of precision 500 bits
## [1] 475
Nice, the correct result (not that that guarantees that I’ve done everything correctly).
Now, lets find all the irrational square roots we need to look at:
library(purrr)
t <- 1:100
s <- t %>%
keep(~as.logical(sqrt(.x)%%1))
I need to practice this way of coding a bit more. t contains the first 100 natural numbers. I pass that to the keep()-function, and the predicate function takes the square root of each number, take the modulus 1, and convert it to a logical value. If the modulus of the square root is 0, the square root is an integer, and 0 i false. So we’re keeping all the non-integer squareroots.
Now I’ll convert all the natural numbers to the mpfr-class. The next line takes the square root. The third line calculate the digitalsum. And the final line gives us the result.
s <- mpfr(s,500)
r <- sqrt(s)
r <- digitsum(r)
sum(r)
## 1 'mpfr' number of precision 500 bits
## [1] Censored
Lessons learned:
Rmpfr allows us to work with (more or less) arbitrary precision.
But we need to convert numbers to the relevant class before doing math on it.
## i t
## 1 1 lorem
## 2 2 do
## 3 3 do
## 4 4 Do
## 5 5 ipsum
## 6 6 do
## 7 7 Do
## 8 8 (do)
## 9 9 dolor
## 10 10 <NA>
## 11 NA test
How to replace the first three “do”s with “lorem” and the next set of “do”s with “ipsum”
Using fill() from the tidyr package is straight forward. It takes a vector, locates all NA, and replaces them with the last, non-NA value.
Simple enough, change all the variations of “do” to NA, run fill(). Done.
One problem, there might be NAs in the dataset, that we do not want to affect.
Solution – there might be a more elegant one, but this works:
Change the NAs to something that do not occur in the data
Change to variations of “do” to NA
Use the fill()-function
Change the NAs from step 1 back to NA
library(tidyr)
rpl <- "replacement"
m[is.na(m$t),]$t <- rpl
doset <- c("do", "Do", "(do)")
m[(m$t %in% doset),]$t <- NA
m <- m %>% fill(t)
m[(m$t == rpl),]$t <- NA
m
## i t
## 1 1 lorem
## 2 2 lorem
## 3 3 lorem
## 4 4 lorem
## 5 5 ipsum
## 6 6 ipsum
## 7 7 ipsum
## 8 8 ipsum
## 9 9 dolor
## 10 10 <NA>
## 11 NA test
Done!
Oh, and by the way, this is my first post generated directly from RStudio!