Producing the nth largest number from a vector in R [closed] - r

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to have a user enter a number from 0 to 1 (nth number). Returning the nth largest number within say a vector. So when n=1 it acts as the maximum of the vector outputting the largest number. I am new to coding in r. Any help on improving my code would be grateful let alone getting it to work.
KFUN <- function() {
bob <- c(1,2,3,6)
ANSWER <- readline("Enter k value:")
k <- ANSWER
if(k <= 1 && k >= 0) {
if(0 < k <= .25) {
bob[c(4)]
}
if(.25 < k && k <= .5) {
bob[c(3)]
}
if(.5 < k && k <= .75) {
bob[c(2)]
}
if(.75 < k && k <=1) {
bob[c(1)]
}
}
else {
stop("That is not within 0 to 1!")
}
}
KFUN()
Best

Try 'order' function:
nth_largest= function(vect, n){
vect[rev(order(vect))][n]
}
bob <- c(3,6,1,2)
nth_largest(bob, 1)
[1] 6
nth_largest(bob, 2)
[1] 3
nth_largest(bob, 3)
[1] 2
nth_largest(bob, 4)
[1] 1

Related

Prime Number generator from 2 to 100 in r [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Can someone help me and show me the reason why my prime number generator doesn't work?:
d=0
primeno<- c(2:100)
for(i in primeno)
{
for(j in 1:i)
{
if(j %% i == 0)
d=d+1
}
if(d==2)
print ("Prime")
d=0
}
Only inverts the indexes (j %% i) for (i %% j), the number is the index "i" and divisor is the index "j".
d=0
primeno<- c(2:100)
for(i in primeno)
{
for(j in 1:i)
{
if(i %% j == 0)
d=d+1
}
if(d==2)
cat(i,"- Prime \n")
d=0
}
Now, this works:
d=0
primeno<- c(2:100)
for(i in 2:length(primeno)){
for(j in 1:i){
if(i %% j == 0){
d=d+1
}
}
if(d==2){
print(i)
print ("Prime")
}
d <- 0
}

Simulate from a distribution function using Rejection Method

I am trying to simulate data 10000 observations for the following distribution:
{ 3x(1-x)2 0 < x < 1
f(x) = { 3(2-x)(1-x)2 1 ≤ x < 2
{ 0 otherwise
Using the rejection method, I am boxing the distribution by the following rectangle: x=0,x=2,y=0,y=2
However, there is some fault in my code below as it doesn't seem to work. Can any one please advise on a fix?
n=10000
t=0
x=0
while(t<n)
{u=runif(1,0,2)
y=runif(1,0,2)
if {(u in c(0:1))
fun=3*u*(1-u)^2
else (u in c(1:2))
fun=3*(2-u)*(1-u)^2}
if (y<fun)
{t=t+1
x[t]=u}}
You have a bunch of R syntax errors. You should review a basic R introduction. be careful with placement of braces. Also there is no in keyword in R.
n <- 10000
t <- 0
x <- 0
while(t<n) {
u <- runif(1,0,2)
y <- runif(1,0,2)
if (u > 0 & u < 1) {
fun <- 3*u*(1-u)^2
} else if (u >= 1 & u < 2) {
fun <- 3*(2-u)*(1-u)^2
} else {
fun <- 0
}
if (y<fun){
t <- t+1
x[t] <- u
}
}

R: N-Queens finding the Diagonal

Made a post earlier today expressing I was trying to find a solution to the N-Queens problem. The first part of this is determining the following function:
>safe(chess.piece,chess.board)
Where:
>chess.board <- matrix(0,8,8)
>chess.board[r,c] <- 1 #1 represents the queen which can be placed in any row/column on the board
>chess.piece <- c(x,x) #basically and row/column value I choose in the 8x8 matrix
Currentley I have the following code for the horizontal and vertical planes:
>safe <- function(a,b){
if((sum(b[a[1],])<1) & (sum(b[,a[2]])<1))
{return(TRUE)
}else{
return(FALSE)
}
}
Basically works on summing the rows/columns and checking if greater (FALSE) or equal (TRUE) to 0. But how in the world do I find the diagonal sum of the chess.board matrix based on the rows/columns determined by the chess.piece ?! I am ripping my hair out over this as I am decently new to R but I need a solution and just can't seem to figure it out.
Any help would be greatly appreciated! Thanks in advance, J.S
Consider you have to check if board element (x,y) can be attacked from any diagonal element or not. (x,y) can be attacked diagonally if any element lying on its diagonal element is a queen.Assume (p,q) is board element having a queen.Now condition for element(x,y) to lie on diagonal coordinates of board element (p,q) would be p+q == x+y or p-q == x-y .This can also be interpreted as the condition for elements (p,q) and (x,y) to lie on same diagonal.So, if there is queen at (p,q) and we have to check whether (x,y) can be attacked by this queen or not, the condition for this would be:-
if((board[p][q] == 1 ) && ((p+q == x+y) || (p-q == x-y))){
return true;
}
Complete function for checking if element at (x,y) i.e., board[x,y] is attacked by diagonal elements or not would be:-
for(int p=1;p<board.length;p++){
for(int q=1;q<board.length;q++){
if(p==x && q==y){ //skipping check if element under consideration is same
continue;
}
if((board[p][q] == 1 )&& ((p+q == x+y) || (p-q == x-y))){
return true;
}
}
}
Complete function for checking if element (x,y) is attacked or not would be:-
public static boolean is_attacked(int x,int y,int board[][],int n){
for(int i = 1;i < board.length;i++){
if(board[x][i] == 1){ //if any cell in xth row is 1 i.e.,queen is there in that row
return true;
}
}
for(int i = 1;i < board.length;i++){
if(board[i][y] == 1){ //if any cell in yth column is 1 i.e.,queen is there in that column
return true;
}
}
for(int p=1;p<board.length;p++){
for(int q=1;q<board.length;q++){
if(p==x && q==y){
continue;
}
if((board[p][q]== 1 )&& ((p+q== x+y) || (p-q == x-y))){
return true;
}
}
}
return false;
}
Hope this helps!!!
One approach is to write a couple of functions to extract partial diagonals from a square matrix, using the fact that you can use 1-dimensional indexing since matrices are just vectors under the hood and these diagonals correspond to certain arithmetical sequences of indices:
udiag <- function(A,i,j){
n <- nrow(A)
a <- i + n*(j-1) - (n-1)*min(n-i,j-1)
b <- i + n*(j-1) + (n-1)*min(i-1,n-j)
A[seq(a,b,n-1)]
}
ddiag <- function(A,i,j){
n <- nrow(A)
a <- i + n*(j-1) - (n+1)*min(i-1,j-1)
b <- i + n*(j-1) + (n+1)*min(n-i,n-j)
A[seq(a,b,n+1)]
}
These two functions extract the upward slanting and downward slanting diagonals respectively. You can use these two functions and write your safe like this:
safe <- function(x,y){
i <- x[1]
j <- x[2]
sum(y[i,]) == 0 & sum(y[,j]) == 0 & sum(udiag(y,i,j)) == 0 & sum(ddiag(y,i,j)) == 0
}
On Edit: In view of the intended application, I wrote udiag() and ddiag() to work with square matrices only. Since they may have other uses in potentially nonsquare matrices, they can be easily modified to handle such cases:
udiag <- function(A,i,j){
m <- nrow(A)
n <- ncol(A)
a <- i + m*(j-1) - (m-1)*min(m-i,j-1)
b <- i + m*(j-1) + (m-1)*min(i-1,n-j)
A[seq(a,b,m-1)]
}
ddiag <- function(A,i,j){
m <- nrow(A)
n <- ncol(A)
a <- i + m*(j-1) - (m+1)*min(i-1,j-1)
b <- i + m*(j-1) + (m+1)*min(m-i,n-j)
A[seq(a,b,m+1)]
}
For example:
> A <- matrix(1:12,nrow = 3)
> A
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
> udiag(A,2,3)
[1] 6 8 10
> ddiag(A,2,3)
[1] 4 8 12

R: recursive too slow [duplicate]

This question already has answers here:
Why is my recursive function so slow in R?
(7 answers)
Closed 7 years ago.
I have R running function:
f <- function (n) {
if ( n == 1) return (0)
if ( n == 2) return (1)
else return ( f(n-1) + f(n-2))
}
f(50) takes very long time to calculate. f(35) takes approx 30 seconds. Is there any way to make it faster in R?
Edit. Thanks for help! I used this and it gave me f(50) instantly.
> f <- local({
+ memo <- c(1, 1, rep(NA,100))
+ f <- function(x) {
+ if(x == 1) return(0)
+ if(x == 2) return(1)
+ if(x > length(memo))
+ stop("’x’ too big for implementation")
+ if(!is.na(memo[x])) return(memo[x])
+ ans <- f(x-1) + f(x-2)
+ memo[x] <<- ans
+ ans
+ }
+ })
This is a comment problem with recursive functions that can be solved by tail-recursion. Unfortunately, it appears that R does not support tail call optimization. Fortunately, you can always use the iterative solution, which you should be fairly fast since it does not have to allocate stack frames:
fIter <- function(n) {
if ( n < 2 )
n
else {
f <- c(0, 1)
for (i in 2:n) {
t <- f[2]
f[2] <- sum(f)
f[1] <- t
}
f[2]
}
}
fIter(100)'
This program runs in ~0.45 seconds on ideone. I don't know R personally, source of program: http://rosettacode.org/wiki/Fibonacci_numbers#R

given "N" find p & q such that p+q=N and p*q is maximum [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I need the logic/idea behind a rough solution I have come up with.
The problem is:
Given N, where 1<=N<=1000000
Now i need to find two numbers p and q such that p + q = N && p * q = maximum.
I chose to use this (((N+1)/2)*((N/2))); which basically gives me the maximum product with the minimum sum. But I am kind of interested in the proof of this logic.
Any help or leads?
#include<stdio.h>
typedef unsigned long uint;
unsigned long calc(uint);
int main(void) {
short i = 0;
uint k = 0;
scanf("%i", &i);
while(i--) {
scanf("%lu", &k);
printf("%lu\n", calc(k));
}
return 0;
}
uint calc(uint k){
return (((k+1)/2)*((k/2)));
}
Let
f(p) = p * (N - p) = p * N - p ^ 2
Then:
f'(p) = N - 2 * p
f''(p) = - 2
Since f''(p) < 0, simply solving for f'(p) = 0 gives us a local maxima.
When f'(p) = 0,
p = N / 2
=> q = N / 2
You also need to test the end-points f(0) and f(N), but both of these evaluate to zero, so our maxima is the global maximum.
Note: This is basically saying that of all the rectangles of a certain perimeter, the square has the largest area.

Resources