I am very happy to continue writing this article. In today's example, we will use the data type data. frame, and learn how to combine and calculate two vectors and how to sort them. We will use what we have learned to solve the fourth problem of Project Euler, that is, to find the maximum number of input files in a collection. A number is a symmetric number like 1534351. if you rearrange the number in the reverse order, the result will be the same as the original number. Start!
# Preparation exercise
X <-Y <-y- 1 : 9
Data <- Expand. Grid ( X = x , Y = y )
Print ( Data )
Z <- Data $ X * Data $ Y
# A 9-9 multiplication table
Z <- Matrix ( Z , Ncol = 9 )
Set. Seed ( 1 )
X <- Round ( Runif ( 10 ) , 2 )
Print ( X )
Order ( X )
X [ Order ( X ) [ 1 ] ]
Which. Min ( X )
X [ Which. Min ( X ) ]
X [ Order ( X ) ]
Y <- 1 : 10
Data <- Data. Frame ( X , Y )
Class ( Data )
Head ( Data )
Data [ 1 , ]
Data [ , 1 ]
Data $ X
Data [ Order ( Data $ X ) , ]
# Project Euler 4
# In the product of two three-digit numbers, find the maximum number of replies
# Create a function to reverse the numerical order
Reverse <- Function ( N ) {
Reversed <- 0
While ( N> 0 ) {
Reversed <- 10 * Reversed + N % 10
N <-N %/% 10
}
Return ( Reversed )
}
# Search for the number of replies from large to small
X <-Y <-y-999 : 100
Data <- Expand. Grid ( X = x , Y = y )
Data $ Prod <- Data $ X * Data $ Y
Data <-Data [ Order ( Data $ Prod , Decreasing = T ) , ]
Head ( Data )
Value <- Data $ ProdFor ( I In 1 : Length ( Value ) ) { Isequal <- ( Value [ I ] = Reverse ( Value [ I] ) ) If ( Isequal ) { Print ( Data [ I , ] ) Break } }
The result is 906609. In this example, the product is sorted first and then the number of input records is determined. The first result is the answer, so the speed is faster. If you do not need the expand. Grid function, you can use nested for combined computing. Another method is to convert the number into a character using the rev function of R itself, cut it into a string of vectors, and use rev to reverse it and judge.
From data science and R language http://xccds1977.blogspot.com/