Skip to content

Instantly share code, notes, and snippets.

View krishnanraman's full-sized avatar

Krishnan Raman krishnanraman

View GitHub Profile
# Find x such that x+1, 2x+3,3x+5 and 4x+7 are prime.
library(DescTools)
# This works
subset(expand.grid(x=1:1000),IsPrime(x+1) & IsPrime(2*x+3) & IsPrime(3*x+5) & IsPrime(4*x+7))
# Alternate solution
which(mapply(function(x) IsPrime(x+1) & IsPrime(2*x+3) & IsPrime(3*x+5) & IsPrime(4*x+7), 1:1000))
dim(subset(expand.grid(a=0:80,b=seq(2,80,2),c=c(0,2,5)), a+b+c == 80))
@krishnanraman
krishnanraman / aime4.R
Created February 3, 2024 00:44
AIME 2024 4
x<-0:9
n<-4
N<-100000
atleasttwomatch<- 0
allfourmatch<-0
for(i in 1:N) {
a<-sample(x,n)
b<-sample(x,n)
s<-length(a[is.element(a, b)])
if (s > 1) {
x<-seq(1,20)
n<-100000
mx<-c()
for (i in 1:n) {
mx<-c(mx,max(sample(x,10,replace=F)))
}
summary(mx)
Min. 1st Qu. Median Mean 3rd Qu. Max.
> x<-runif(100,0,2)
> y<-1+x+x^2+x^3
> summary(lm(y~x))
Call:
lm(formula = y ~ x)
Residuals:
Min 1Q Median 3Q Max
-1.334 -1.018 -0.213 0.677 2.742
@krishnanraman
krishnanraman / test.R
Created December 6, 2020 02:42
hierarchical model Stan
rm(list=ls())
library(rstan)
rstan_options(auto_write = FALSE)
options(mc.cores = parallel::detectCores())
N=1000
data = list(N=N,x1<-rnorm(N,5,2),x2<-rnorm(N,7,2),x3<-rnorm(N,9,2),y<-x1+x2+x3)
fit <- suppressMessages(stan(file = '~/Desktop/695/test.stan', data = data, iter=11000, warmup=1000, chains=2, seed=483892929, refresh=11000))
print(fit)
plot(fit)
rm(list =ls())
dev.off()
for(j in 1:4) {
n=1000
x=numeric(n)
y=numeric(n)
x[1] = rnorm(1,0,0.2)
y[1] = rnorm(1,0,0.2)
a=0.51
@krishnanraman
krishnanraman / gradientdescent.R
Created November 28, 2020 01:48
gradient descent for regression
# Goal: Find unknown scalar w to minimize L(w)
# L(w) = sum((y[i] - w*x[i])^2)
# (x[i], y[i]), i=1..n dataset for linear regression
#
# Repeat Iterative Procedure below until convergence:
# w[i+1] = w[i] - alpha * gradient(L(w), w=w[i])
#
set.seed(12345)
x=seq(-5,5,0.5)
y = 2*x + rnorm(length(x),0,1)
@krishnanraman
krishnanraman / 24.R
Last active October 22, 2020 21:41
24.R
n=10
op = c('+', '-', '*', '/')
perms = c()
while(length(perms) < 24) {
s = paste(sample(op,4), collapse='')
if (length(perms[perms==s]) == 0) {
perms =c(perms,s)
print(length(perms))
}
@krishnanraman
krishnanraman / r in scala.txt
Last active October 2, 2020 00:00
Using R from Scala
Step 0. You must have the latest & greatest version of R, and scala 2.10.1, for all of this to work.
Step 1. Download and unzip the MacOS X Binary jvmr_1.0.4.tgz from here: http://cran.r-project.org/web/packages/jvmr/index.html
Step 2. Create a lib folder, and copy jvmr_2.10-1.0.4.jar to that folder.
Step 3. Start R
Step 4. At the R console
>install.packages("jvmr")