Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Transform the following C implementation into R, maintaining the same output and logic. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define foreach(a, b, c) for (int a = b; a < c; a++)
#define for_i foreach(i, 0, n)
#define for_j foreach(j, 0, n)
#define for_k foreach(k, 0, n)
#define for_ij for_i for_j
#define for_ijk for_ij for_k
#define _dim int n
#define _swap(x, y) { typeof(x) tmp = x; ... | library(Matrix)
A <- matrix(c(1, 3, 5, 2, 4, 7, 1, 1, 0), 3, 3, byrow=T)
dim(A) <- c(3, 3)
expand(lu(A))
|
Maintain the same structure and functionality when rewriting this code in R. | #include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
typedef const char * String;
typedef struct sTable {
String * *rows;
int n_rows,n_cols;
} *Table;
typedef int (*CompareFctn)(String a, String b);
struct {
CompareFctn compare;
int column;
int ... | tablesort <- function(x, ordering="lexicographic", column=1, reverse=false)
{
}
tablesort(mytable, column=3)
|
Write the same algorithm in R as shown in this C implementation. | #include<math.h>
#include<stdio.h>
int
main ()
{
double inputs[11], check = 400, result;
int i;
printf ("\nPlease enter 11 numbers :");
for (i = 0; i < 11; i++)
{
scanf ("%lf", &inputs[i]);
}
printf ("\n\n\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :");
for (i = 10; i >= 0; i-... | S <- scan(n=11)
f <- function(x) sqrt(abs(x)) + 5*x^3
for (i in rev(S)) {
res <- f(i)
if (res > 400)
print("Too large!")
else
print(res)
}
|
Ensure the translated R code behaves exactly like the original C snippet. | #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
typedef struct{
double x,y;
}point;
void pythagorasTree(point a,point b,int times){
point c,d,e;
c.x = b.x - (a.y - b.y);
c.y = b.y - (b.x - a.x);
d.x = a.x - (a.y - b.y);
d.y = a.y - (b.x - a.x);
e.x = d.x + ( b.x - a.x - (a... |
pythtree <- function(ax,ay,bx,by,d) {
if(d<0) {return()}; clr="darkgreen";
dx=bx-ax; dy=ay-by;
x3=bx-dy; y3=by-dx;
x4=ax-dy; y4=ay-dx;
x5=x4+(dx-dy)/2; y5=y4-(dx+dy)/2;
segments(ax,-ay,bx,-by, col=clr);
segments(bx,-by,x3,-y3, col=clr);
segments(x3,-y3,x4,-y4, col=clr);
segments(x4,-y4,ax,-ay, col=cl... |
Port the following code from C to R with equivalent syntax and logic. | #include <stdio.h>
#include <string.h>
typedef struct { char v[16]; } deck;
typedef unsigned int uint;
uint n, d, best[16];
void tryswaps(deck *a, uint f, uint s) {
# define A a->v
# define B b.v
if (d > best[n]) best[n] = d;
while (1) {
if ((A[s] == s || (A[s] == -1 && !(f & 1U << s)))
&& (d + best[s] >= bes... | topswops <- function(x){
i <- 0
while(x[1] != 1){
first <- x[1]
if(first == length(x)){
x <- rev(x)
} else{
x <- c(x[first:1], x[(first+1):length(x)])
}
i <- i + 1
}
return(i)
}
library(iterpc)
result <- NULL
for(i in 1:10){
I <- iterpc(i, labels = 1:i, ordered = T)
A <- ... |
Rewrite the snippet below in R so it works the same as the original C code. | #include <stdio.h>
unsigned int lpd(unsigned int n) {
if (n<=1) return 1;
int i;
for (i=n-1; i>0; i--)
if (n%i == 0) return i;
}
int main() {
int i;
for (i=1; i<=100; i++) {
printf("%3d", lpd(i));
if (i % 10 == 0) printf("\n");
}
return 0;
}
| largest_proper_divisor <- function(n){
if(n == 1) return(1)
lpd = 1
for(i in seq(1, n-1, 1)){
if(n %% i == 0)
lpd = i
}
message(paste0("The largest proper divisor of ", n, " is ", lpd))
return(lpd)
}
for (i in 1:100){
largest_proper_divisor(i)
}
|
Can you help me rewrite this code in R instead of C, keeping it the same logically? | #include<stdio.h>
#include<stdlib.h>
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
int prime( int n ) {
int p, pn=1;
if(n==1) return 2;
for(p=3;pn<n;p+=2) {
if(isprime(p)) pn++;
}... | library(primes)
nth_prime(10001)
|
Write a version of this C function in R with identical behavior. | #include<stdio.h>
#include<stdlib.h>
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
int prime( int n ) {
int p, pn=1;
if(n==1) return 2;
for(p=3;pn<n;p+=2) {
if(isprime(p)) pn++;
}... | library(primes)
nth_prime(10001)
|
Translate the given C code snippet into R without altering its behavior. | #include<stdio.h>
int main()
{
int num = 9876432,diff[] = {4,2,2,2},i,j,k=0;
char str[10];
start:snprintf(str,10,"%d",num);
for(i=0;str[i+1]!=00;i++){
if(str[i]=='0'||str[i]=='5'||num%(str[i]-'0')!=0){
num -= diff[k];
k = (k+1)%4;
goto start;
}
for(j=i+1;str[j]!=00;j++)
if(str[i]==str... | largest_LynchBell_number <- function(from, to){
from = round(from)
to = round(to)
to_chosen = to
if(to > 9876432) to = 9876432
LynchBell = NULL
range <- to:from
range <- range[range %% 5 != 0]
for(n in range){
splitted <- strsplit(toString(n), "")[[1]]
if("0" %in% splitted | "5" ... |
Generate a R translation of this C snippet without changing its computational steps. | #include<stdio.h>
int main()
{
int num = 9876432,diff[] = {4,2,2,2},i,j,k=0;
char str[10];
start:snprintf(str,10,"%d",num);
for(i=0;str[i+1]!=00;i++){
if(str[i]=='0'||str[i]=='5'||num%(str[i]-'0')!=0){
num -= diff[k];
k = (k+1)%4;
goto start;
}
for(j=i+1;str[j]!=00;j++)
if(str[i]==str... | largest_LynchBell_number <- function(from, to){
from = round(from)
to = round(to)
to_chosen = to
if(to > 9876432) to = 9876432
LynchBell = NULL
range <- to:from
range <- range[range %% 5 != 0]
for(n in range){
splitted <- strsplit(toString(n), "")[[1]]
if("0" %in% splitted | "5" ... |
Maintain the same structure and functionality when rewriting this code in R. | #include <stdio.h>
#include <stdlib.h>
typedef struct func_t *func;
typedef struct func_t {
func (*fn) (func, func);
func _;
int num;
} func_t;
func new(func(*f)(func, func), func _) {
func x = malloc(sizeof(func_t));
x->fn = f;
x->_ = _;
x->num = 0;
... | Y <- function(f) {
(function(x) { (x)(x) })( function(y) { f( (function(a) {y(y)})(a) ) } )
}
|
Write the same code in R as shown below in C. | #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int locale_ok = 0;
wchar_t s_suits[] = L"♠♥♦♣";
const char *s_suits_ascii[] = { "S", "H", "D", "C" };
const char *s_nums[] = { "WHAT",
"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K",
"OVERFLOW"
};
typedef struct { int suit, number, _s;... | pips <- c("2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace")
suit <- c("Clubs", "Diamonds", "Hearts", "Spades")
deck <- data.frame(pips=rep(pips, 4), suit=rep(suit, each=13))
shuffle <- function(deck)
{
n <- nrow(deck)
ord <- sample(seq_len(n), size=n)
deck[ord,]
}
deal <- functio... |
Rewrite this program in R while keeping its functionality equivalent to the C version. | main(){printf("Code Golf");}
|
cat("Code Golf")
cat(rlang::string(c(0x43, 0x6F, 0x64, 0x65, 0x20,
0x47, 0x6F, 0x6C, 0x66)))
|
Translate the given C code snippet into R without altering its behavior. | main(){printf("Code Golf");}
|
cat("Code Golf")
cat(rlang::string(c(0x43, 0x6F, 0x64, 0x65, 0x20,
0x47, 0x6F, 0x6C, 0x66)))
|
Rewrite this program in R while keeping its functionality equivalent to the C version. | #include <stdint.h>
#include <stdio.h>
uint64_t factorial(uint64_t n) {
uint64_t res = 1;
if (n == 0) return res;
while (n > 0) res *= n--;
return res;
}
uint64_t lah(uint64_t n, uint64_t k) {
if (k == 1) return factorial(n);
if (k == n) return 1;
if (k > n) return 0;
if (k < 1 || n < ... | Lah_numbers <- function(n, k, type = "unsigned") {
if (n == k)
return(1)
if (n == 0 | k == 0)
return(0)
if (k == 1)
return(factorial(n))
if (k > n)
return(NA)
if (type == "unsigned")
return((factorial(n) * factorial(n - 1)) / (factorial(k) * fac... |
Please provide an equivalent version of this C code in R. | #include <stdint.h>
#include <stdio.h>
uint64_t factorial(uint64_t n) {
uint64_t res = 1;
if (n == 0) return res;
while (n > 0) res *= n--;
return res;
}
uint64_t lah(uint64_t n, uint64_t k) {
if (k == 1) return factorial(n);
if (k == n) return 1;
if (k > n) return 0;
if (k < 1 || n < ... | Lah_numbers <- function(n, k, type = "unsigned") {
if (n == k)
return(1)
if (n == 0 | k == 0)
return(0)
if (k == 1)
return(factorial(n))
if (k > n)
return(NA)
if (type == "unsigned")
return((factorial(n) * factorial(n - 1)) / (factorial(k) * fac... |
Change the programming language of this snippet from C to R without modifying what it does. | #include<stdlib.h>
#include<stdio.h>
int
main ()
{
int i;
char *str = getenv ("LANG");
for (i = 0; str[i + 2] != 00; i++)
{
if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f')
|| (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F'))
{
printf
("Uni... | if (any(grepl("UTF", toupper(Sys.getenv(c("LANG", "LC_ALL", "LC_CTYPE")))))) {
cat("Unicode is supported on this terminal and U+25B3 is : \u25b3\n")
} else {
cat("Unicode is not supported on this terminal.")
}
|
Keep all operations the same but rewrite the snippet in R. | #include<stdlib.h>
#include<stdio.h>
int
main ()
{
int i;
char *str = getenv ("LANG");
for (i = 0; str[i + 2] != 00; i++)
{
if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f')
|| (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F'))
{
printf
("Uni... | if (any(grepl("UTF", toupper(Sys.getenv(c("LANG", "LC_ALL", "LC_CTYPE")))))) {
cat("Unicode is supported on this terminal and U+25B3 is : \u25b3\n")
} else {
cat("Unicode is not supported on this terminal.")
}
|
Write a version of this C function in R with identical behavior. | int meaning_of_life();
|
meaningOfLife <- function() {
42
}
main <- function(args) {
cat("Main: The meaning of life is", meaningOfLife(), "\n")
}
if (length(sys.frames()) > 0) {
args <- commandArgs(trailingOnly = FALSE)
main(args)
q("no")
}
|
Rewrite the snippet below in R so it works the same as the original C code. | int meaning_of_life();
|
meaningOfLife <- function() {
42
}
main <- function(args) {
cat("Main: The meaning of life is", meaningOfLife(), "\n")
}
if (length(sys.frames()) > 0) {
args <- commandArgs(trailingOnly = FALSE)
main(args)
q("no")
}
|
Transform the following C implementation into R, maintaining the same output and logic. | #include<string.h>
#include<stdlib.h>
#include<locale.h>
#include<stdio.h>
#include<wchar.h>
#include<math.h>
int main(int argC,char* argV[])
{
double* arr,min,max;
char* str;
int i,len;
if(argC == 1)
printf("Usage : %s <data points separated by spaces or commas>",argV[0]);
else{
arr = (double*)malloc((argC-1... | [1] "▂▁▄▃▆▅█▇"
[1] "▁▂▃▄▅▆▇█▇▆▅▄▃▂▁"
[1] "▂▁▄▃▆▅█▇"
[1] "▁▁▅▅██"
[1] "▁▁██"
[1] "▁▁██"
|
Port the provided C code into R while preserving the original functionality. |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "wren.h"
struct MemoryStruct {
char *memory;
size_t size;
};
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct MemoryStruct *m... | YahooSearch <- function(query, page=1, .opts=list(), ignoreMarkUpErrors=TRUE)
{
if(!require(RCurl) || !require(XML))
{
stop("Could not load required packages")
}
query <- curlEscape(query)
b <- 10*(page-1)+1
theurl <- paste("http://uk.search.yahoo.com/search?p=",
query, ... |
Please provide an equivalent version of this C code in R. |
char * put_sound( char* file_sound )
{
String PID_SOUND;
system( file_sound );
PID_SOUND = `pidof aplay`;
char ot = Set_new_sep(' ');
Fn_let( PID_SOUND, Get_token(PID_SOUND, 1));
Set_token_sep(ot);
return PID_SOUND;
}
void kill_sound( char * PID_SOUND )
{
String pid;
pid = `pidof aplay`;
... |
library(sound)
media_dir <- file.path(Sys.getenv("SYSTEMROOT"), "Media")
chimes <- loadSample(file.path(media_dir, "chimes.wav"))
chord <- loadSample(file.path(media_dir, "chord.wav"))
play(appendSample(chimes, chord))
play(chimes + chord)
play(cutSample(chimes, 0, 0.2))
for(i in 1:3) play(chimes) ... |
Preserve the algorithm and functionality while converting the code from C to R. | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define SIM_N 5
#define PRINT_DISCARDED 1
#define min(x,y) ((x<y)?(x):(y))
typedef uint8_t card_t;
unsigned int rand_n(unsigned int n) {
unsigned int out, mask = 1;
while (mask < n) mask = mask<<1 | 1;
do {
out =... | magictrick<-function(){
deck=c(rep("B",26),rep("R",26))
deck=sample(deck,52)
blackpile=character(0)
redpile=character(0)
discardpile=character(0)
while(length(deck)>0){
if(deck[1]=="B"){
blackpile=c(blackpile,deck[2])
deck=deck[-2]
}else{
redpile=c(redpile,deck[2])
deck=deck[... |
Change the programming language of this snippet from C to R without modifying what it does. | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define SIM_N 5
#define PRINT_DISCARDED 1
#define min(x,y) ((x<y)?(x):(y))
typedef uint8_t card_t;
unsigned int rand_n(unsigned int n) {
unsigned int out, mask = 1;
while (mask < n) mask = mask<<1 | 1;
do {
out =... | magictrick<-function(){
deck=c(rep("B",26),rep("R",26))
deck=sample(deck,52)
blackpile=character(0)
redpile=character(0)
discardpile=character(0)
while(length(deck)>0){
if(deck[1]=="B"){
blackpile=c(blackpile,deck[2])
deck=deck[-2]
}else{
redpile=c(redpile,deck[2])
deck=deck[... |
Generate an equivalent R version of this C code. | #include <stdio.h>
int main(void)
{
puts( "%!PS-Adobe-3.0 EPSF\n"
"%%BoundingBox: -10 -10 400 565\n"
"/a{0 0 moveto 0 .4 translate 0 0 lineto stroke -1 1 scale}def\n"
"/b{a 90 rotate}def");
char i;
for (i = 'c'; i <= 'z'; i++)
printf("/%c{%c %c}def\n", i, i-1, i-2);
puts("0 setlinewidth z showpage\n%%EOF... |
fibow <- function(n) {
t2="0"; t1="01"; t="";
if(n<2) {n=2}
for (i in 2:n) {t=paste0(t1,t2); t2=t1; t1=t}
return(t)
}
pfibofractal <- function(n, w, h, d, clr) {
dx=d; x=y=x2=y2=tx=dy=nr=0;
if(n<2) {n=2}
fw=fibow(n); nf=nchar(fw);
pf = paste0("FiboFractR", n, ".png");
ttl=paste0("Fibonacci word/fr... |
Change the following C code into R without altering its purpose. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
long long x, y, dx, dy, scale, clen, cscale;
typedef struct { double r, g, b; } rgb;
rgb ** pix;
void sc_up()
{
scale *= 2; x *= 2; y *= 2;
cscale *= 3;
}
void h_rgb(long long x, long long y)
{
rgb *p = &pix[y][x];
# define SAT 1
d... |
pSierpinskiT <- function(ord, fn="", ttl="", clr="navy") {
m=640; abbr="STR"; dftt="Sierpinski triangle";
n=2^ord; M <- matrix(c(0), ncol=n, nrow=n, byrow=TRUE);
cat(" *** START", abbr, date(), "\n");
if(fn=="") {pf=paste0(abbr,"o", ord)} else {pf=paste0(fn, ".png")};
if(ttl!="") {dftt=ttl}; ttl=paste0(dftt... |
Maintain the same structure and functionality when rewriting this code in R. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
long long x, y, dx, dy, scale, clen, cscale;
typedef struct { double r, g, b; } rgb;
rgb ** pix;
void sc_up()
{
scale *= 2; x *= 2; y *= 2;
cscale *= 3;
}
void h_rgb(long long x, long long y)
{
rgb *p = &pix[y][x];
# define SAT 1
d... |
pSierpinskiT <- function(ord, fn="", ttl="", clr="navy") {
m=640; abbr="STR"; dftt="Sierpinski triangle";
n=2^ord; M <- matrix(c(0), ncol=n, nrow=n, byrow=TRUE);
cat(" *** START", abbr, date(), "\n");
if(fn=="") {pf=paste0(abbr,"o", ord)} else {pf=paste0(fn, ".png")};
if(ttl!="") {dftt=ttl}; ttl=paste0(dftt... |
Preserve the algorithm and functionality while converting the code from C to R. | #include<stdio.h>
#include<conio.h>
#include<math.h>
#include<dos.h>
typedef struct{
char str[3];
int key;
}note;
note sequence[] = {{"Do",0},{"Re",2},{"Mi",4},{"Fa",5},{"So",7},{"La",9},{"Ti",11},{"Do",12}};
int main(void)
{
int i=0;
while(!kbhit())
{
printf("\t%s",sequence[i].str);
sound(261.63*pow(2,... | install.packages("audio")
library(audio)
hz=c(1635,1835,2060,2183,2450,2750,3087,3270)
for (i in 1:8){
play(audioSample(sin(1:1000), hz[i]))
Sys.sleep(.7)
}
|
Generate an equivalent R version of this C code. | #include<stdio.h>
#include<conio.h>
#include<math.h>
#include<dos.h>
typedef struct{
char str[3];
int key;
}note;
note sequence[] = {{"Do",0},{"Re",2},{"Mi",4},{"Fa",5},{"So",7},{"La",9},{"Ti",11},{"Do",12}};
int main(void)
{
int i=0;
while(!kbhit())
{
printf("\t%s",sequence[i].str);
sound(261.63*pow(2,... | install.packages("audio")
library(audio)
hz=c(1635,1835,2060,2183,2450,2750,3087,3270)
for (i in 1:8){
play(audioSample(sin(1:1000), hz[i]))
Sys.sleep(.7)
}
|
Convert this C snippet to R and keep its semantics consistent. |
#include <ctime>
#include <cstdint>
extern "C" {
int64_t from date(const char* string) {
struct tm tmInfo = {0};
strptime(string, "%Y-%m-%d", &tmInfo);
return mktime(&tmInfo);
}
}
|
df_patient <- read.table(text = "
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz
", header = TRUE, sep = ",")
df_visits <- read.table(text = "
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,... |
Translate this program into R but keep the logic exactly as in C. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N_SITES 150
double site[N_SITES][2];
unsigned char rgb[N_SITES][3];
int size_x = 640, size_y = 480;
inline double sq2(double x, double y)
{
return x * x + y * y;
}
#define for_k for (k = 0; k < N_SITES; k++)
int nearest_site(double x, double y)
{
... |
randHclr <- function() {
m=255;r=g=b=0;
r <- sample(0:m, 1, replace=TRUE);
g <- sample(0:m, 1, replace=TRUE);
b <- sample(0:m, 1, replace=TRUE);
return(rgb(r,g,b,maxColorValue=m));
}
Metric <- function(x, y, mt) {
if(mt==1) {return(sqrt(x*x + y*y))}
if(mt==2) {return(abs(x) + abs(y))}
if(mt==3) {retur... |
Convert this C snippet to R and keep its semantics consistent. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N_SITES 150
double site[N_SITES][2];
unsigned char rgb[N_SITES][3];
int size_x = 640, size_y = 480;
inline double sq2(double x, double y)
{
return x * x + y * y;
}
#define for_k for (k = 0; k < N_SITES; k++)
int nearest_site(double x, double y)
{
... |
randHclr <- function() {
m=255;r=g=b=0;
r <- sample(0:m, 1, replace=TRUE);
g <- sample(0:m, 1, replace=TRUE);
b <- sample(0:m, 1, replace=TRUE);
return(rgb(r,g,b,maxColorValue=m));
}
Metric <- function(x, y, mt) {
if(mt==1) {return(sqrt(x*x + y*y))}
if(mt==2) {return(abs(x) + abs(y))}
if(mt==3) {retur... |
Rewrite this program in R while keeping its functionality equivalent to the C version. | #include <stdio.h>
#include <stdlib.h>
typedef struct {
char *name;
int weight;
int value;
int count;
} item_t;
item_t items[] = {
{"map", 9, 150, 1},
{"compass", 13, 35, 1},
{"water", 153, 200, 2},
{"sandwich", ... | library(tidyverse)
library(rvest)
task_html= read_html("http://rosettacode.org/wiki/Knapsack_problem/Bounded")
task_table= html_nodes(html, "table")[[1]] %>%
html_table(table, header= T, trim= T) %>%
set_names(c("items", "weight", "value", "pieces")) %>%
filter(items != "knapsack") %>%
mutate(weight= as.numeri... |
Produce a language-to-language conversion: from C to R, same semantics. | #include <libxml/parser.h>
#include <libxml/xpath.h>
xmlDocPtr getdoc (char *docname) {
xmlDocPtr doc;
doc = xmlParseFile(docname);
return doc;
}
xmlXPathObjectPtr getnodeset (xmlDocPtr doc, xmlChar *xpath){
xmlXPathContextPtr context;
xmlXPathObjectPtr result;
context = xmlXPathNewContext(doc);
result = ... | library("XML")
doc <- xmlInternalTreeParse("test3.xml")
getNodeSet(doc, "//item")[[1]]
sapply(getNodeSet(doc, "//price"), xmlValue)
sapply(getNodeSet(doc, "//name"), xmlValue)
|
Translate the given C code snippet into R without altering its behavior. | #include <stdint.h>
#include <stdio.h>
#include <glib.h>
typedef struct named_number_tag {
const char* name;
uint64_t number;
} named_number;
const named_number named_numbers[] = {
{ "hundred", 100 },
{ "thousand", 1000 },
{ "million", 1000000 },
{ "billion", 1000000000 },
{ "trillion", 10... |
integerToText <- function(value_n_1) {
english_words_for_numbers <- list(
simples = c(
'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
),
tens = c('twe... |
Maintain the same structure and functionality when rewriting this code in R. | #include <stdio.h>
#include <stdlib.h>
int isprime( long int n ) {
int i=3;
if(!(n%2)) return 0;
while( i*i < n ) {
if(!(n%i)) return 0;
i+=2;
}
return 1;
}
int main(void) {
long int n=600851475143, j=3;
while(!isprime(n)) {
if(!(n%j)) n/=j;
j+=2;
}
... | sieve <- function(n) {
if (n < 2)
return (NULL)
primes <- rep(TRUE, n)
primes[1] <- FALSE
for (i in 1:floor(sqrt(n)))
if (primes[i])
primes[seq(i*i, n, by = i)] <- FALSE
which(primes)
}
prime.factors <- function(n) {
primes <- sieve(floor(sqrt(n)))
factor... |
Produce a functionally identical R code for the snippet given in C. | #include<stdlib.h>
#include<ctype.h>
#include<stdio.h>
int** doublyEvenMagicSquare(int n) {
if (n < 4 || n % 4 != 0)
return NULL;
int bits = 38505;
int size = n * n;
int mult = n / 4,i,r,c,bitPos;
int** result = (int**)malloc(n*sizeof(int*));
for(i=0;i<n;i++)
result[i] = (int*)malloc(n*sizeof(int));
fo... | magic <- function(n) {
if (n %% 2 == 1) {
p <- (n + 1) %/% 2 - 2
ii <- seq(n)
outer(ii, ii, function(i, j) n * ((i + j + p) %% n) + (i + 2 * (j - 1)) %% n + 1)
} else if (n %% 4 == 0) {
p <- n * (n + 1) + 1
ii <- seq(n)
outer(ii, ii, function(i, j) ifelse((i %/% 2 - j %/% 2) %% 2 == 0, p - n... |
Change the following C code into R without altering its purpose. | #include <stdio.h>
#include <unistd.h>
int main()
{
int i;
printf("\033[?1049h\033[H");
printf("Alternate screen buffer\n");
for (i = 5; i; i--) {
printf("\rgoing back in %d...", i);
fflush(stdout);
sleep(1);
}
printf("\033[?1049l");
return 0;
}
| cat("\033[?1049h\033[H")
cat("Alternate screen buffer\n")
for (i in 5:1) {
cat("\rgoing back in ", i, "...", sep = "")
Sys.sleep(1)
cat("\33[2J")
}
cat("\033[?1049l")
|
Translate this program into R but keep the logic exactly as in C. | #include <stdio.h>
typedef struct {int val, op, left, right;} Node;
Node nodes[10000];
int iNodes;
int b;
float eval(Node x){
if (x.op != -1){
float l = eval(nodes[x.left]), r = eval(nodes[x.right]);
switch(x.op){
case 0: return l+r;
case 1: return l-r;
case 2:... | library(gtools)
solve24 <- function(vals=c(8, 4, 2, 1),
goal=24,
ops=c("+", "-", "*", "/")) {
val.perms <- as.data.frame(t(
permutations(length(vals), length(vals))))
nop <- length(vals)-1
op.perms <- as.data.frame(t(
do.call(expand.... |
Preserve the algorithm and functionality while converting the code from C to R. | #include <stdio.h>
typedef struct {int val, op, left, right;} Node;
Node nodes[10000];
int iNodes;
int b;
float eval(Node x){
if (x.op != -1){
float l = eval(nodes[x.left]), r = eval(nodes[x.right]);
switch(x.op){
case 0: return l+r;
case 1: return l-r;
case 2:... | library(gtools)
solve24 <- function(vals=c(8, 4, 2, 1),
goal=24,
ops=c("+", "-", "*", "/")) {
val.perms <- as.data.frame(t(
permutations(length(vals), length(vals))))
nop <- length(vals)-1
op.perms <- as.data.frame(t(
do.call(expand.... |
Keep all operations the same but rewrite the snippet in R. | #include <stdio.h>
#define JOBS 12
#define jobs(a) for (switch_to(a = 0); a < JOBS || !printf("\n"); switch_to(++a))
typedef struct { int seq, cnt; } env_t;
env_t env[JOBS] = {{0, 0}};
int *seq, *cnt;
void hail()
{
printf("% 4d", *seq);
if (*seq == 1) return;
++*cnt;
*seq = (*seq & 1) ? 3 * *seq + 1 : *seq / 2;
... | code <- quote(
if (n == 1) n else {
count <- count + 1;
n <- if (n %% 2 == 1) 3 * n + 1 else n/2
})
eprint <- function(envs, var="n")
cat(paste(sprintf("%4d", sapply(envs, `[[`, var)), collapse=" "), "\n")
envs <- mapply(function(...) list2env(list(...)), n=1:12, count=0)... |
Can you help me rewrite this code in R instead of C, keeping it the same logically? | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define STACK_SIZE 80
#define BUFFER_SIZE 100
typedef int bool;
typedef struct {
char name;
bool val;
} var;
typedef struct {
int top;
bool els[STACK_SIZE];
} stack_of_bool;
char expr[BUFFER_SIZE];
int expr_le... | truth_table <- function(x) {
vars <- unique(unlist(strsplit(x, "[^a-zA-Z]+")))
vars <- vars[vars != ""]
perm <- expand.grid(rep(list(c(FALSE, TRUE)), length(vars)))
names(perm) <- vars
perm[ , x] <- with(perm, eval(parse(text = x)))
perm
}
"%^%" <- xor
truth_table("!A")
truth_table("A | B")
t... |
Change the following C code into R without altering its purpose. | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define STACK_SIZE 80
#define BUFFER_SIZE 100
typedef int bool;
typedef struct {
char name;
bool val;
} var;
typedef struct {
int top;
bool els[STACK_SIZE];
} stack_of_bool;
char expr[BUFFER_SIZE];
int expr_le... | truth_table <- function(x) {
vars <- unique(unlist(strsplit(x, "[^a-zA-Z]+")))
vars <- vars[vars != ""]
perm <- expand.grid(rep(list(c(FALSE, TRUE)), length(vars)))
names(perm) <- vars
perm[ , x] <- with(perm, eval(parse(text = x)))
perm
}
"%^%" <- xor
truth_table("!A")
truth_table("A | B")
t... |
Change the programming language of this snippet from C to R without modifying what it does. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>
int main() {
for (unsigned int d = 2; d <= 9; ++d) {
printf("First 10 super-%u numbers:\n", d);
char digits[16] = { 0 };
memset(digits, '0' + d, d);
mpz_t bignum;
mpz_init(bignum);
for (unsig... | library(Rmpfr)
options(scipen = 999)
find_super_d_number <- function(d, N = 10){
super_number <- c(NA)
n = 0
n_found = 0
while(length(super_number) < N){
n = n + 1
test = d * mpfr(n, precBits = 200) ** d
test_formatted = .mpfr2str(test)$str
iterable = strsplit(test_form... |
Rewrite this program in R while keeping its functionality equivalent to the C version. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>
int main() {
for (unsigned int d = 2; d <= 9; ++d) {
printf("First 10 super-%u numbers:\n", d);
char digits[16] = { 0 };
memset(digits, '0' + d, d);
mpz_t bignum;
mpz_init(bignum);
for (unsig... | library(Rmpfr)
options(scipen = 999)
find_super_d_number <- function(d, N = 10){
super_number <- c(NA)
n = 0
n_found = 0
while(length(super_number) < N){
n = n + 1
test = d * mpfr(n, precBits = 200) ** d
test_formatted = .mpfr2str(test)$str
iterable = strsplit(test_form... |
Generate an equivalent R version of this C code. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int day(int y, int m, int d) {
return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530;
}
void cycle(int diff, int l, char *t) {
int p = round(100 * sin(2 * M_PI * diff / l));
printf("%12s cycle: %3i%%", t, p);
if (abs(p) < 15)
... | bioR <- function(bDay, targetDay) {
bDay <- as.Date(bDay)
targetDay <- as.Date(targetDay)
n <- as.numeric(targetDay - bDay)
cycles <- c(23, 28, 33)
mods <- n %% cycles
bioR <- c(sin(2 * pi * mods / cycles))
loc <- mods / cycles
current <- ifelse(bioR > 0, ': Up', ': Down')
curre... |
Convert this C snippet to R and keep its semantics consistent. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int day(int y, int m, int d) {
return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530;
}
void cycle(int diff, int l, char *t) {
int p = round(100 * sin(2 * M_PI * diff / l));
printf("%12s cycle: %3i%%", t, p);
if (abs(p) < 15)
... | bioR <- function(bDay, targetDay) {
bDay <- as.Date(bDay)
targetDay <- as.Date(targetDay)
n <- as.numeric(targetDay - bDay)
cycles <- c(23, 28, 33)
mods <- n %% cycles
bioR <- c(sin(2 * pi * mods / cycles))
loc <- mods / cycles
current <- ifelse(bioR > 0, ': Up', ': Down')
curre... |
Rewrite the snippet below in R so it works the same as the original C code. | #include <stdio.h>
#include <stdlib.h>
int
main()
{
int i;
srand(time(NULL));
for (i = 0; i < 10; i++)
puts((rand() % 2) ? "heads" : "tails");
return 0;
}
| ?RNG
help.search("Distribution", package="stats")
|
Convert the following code from C to R, ensuring the logic remains intact. | #include <stdio.h>
#include <stdlib.h>
int
main()
{
int i;
srand(time(NULL));
for (i = 0; i < 10; i++)
puts((rand() % 2) ? "heads" : "tails");
return 0;
}
| ?RNG
help.search("Distribution", package="stats")
|
Produce a functionally identical R code for the snippet given in C. | #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<time.h>
#define pi M_PI
int main(){
time_t t;
double side, vertices[3][3],seedX,seedY,windowSide;
int i,iter,choice;
printf("Enter triangle side length : ");
scanf("%lf",&side);
printf("Enter number of iterations : ");
sc... |
pChaosGameS3 <- function(size, lim, clr, fn, ttl)
{
cat(" *** START:", date(), "size=",size, "lim=",lim, "clr=",clr, "\n");
sz1=floor(size/2); sz2=floor(sz1*sqrt(3)); xf=yf=v=0;
M <- matrix(c(0), ncol=size, nrow=size, byrow=TRUE);
x <- sample(1:size, 1, replace=FALSE);
y <- sample(1:sz2, 1, replace=FALSE)... |
Produce a language-to-language conversion: from C to R, same semantics. | #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<time.h>
#define pi M_PI
int main(){
time_t t;
double side, vertices[3][3],seedX,seedY,windowSide;
int i,iter,choice;
printf("Enter triangle side length : ");
scanf("%lf",&side);
printf("Enter number of iterations : ");
sc... |
pChaosGameS3 <- function(size, lim, clr, fn, ttl)
{
cat(" *** START:", date(), "size=",size, "lim=",lim, "clr=",clr, "\n");
sz1=floor(size/2); sz2=floor(sz1*sqrt(3)); xf=yf=v=0;
M <- matrix(c(0), ncol=size, nrow=size, byrow=TRUE);
x <- sample(1:size, 1, replace=FALSE);
y <- sample(1:sz2, 1, replace=FALSE)... |
Transform the following C implementation into R, maintaining the same output and logic. |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <time.h>
#define NMAX 10000000
double mean(double* values, int n)
{
int i;
double s = 0;
for ( i = 0; i < n; i++ )
s += values[i];
return s / n;
}
double stddev(double* values, int n)
{
int i;
d... | n <- 100000
u <- sqrt(-2*log(runif(n)))
v <- 2*pi*runif(n)
x <- u*cos(v)
y <- v*sin(v)
hist(x)
|
Translate this program into R but keep the logic exactly as in C. | #include <stdio.h>
#include <math.h>
#include <stdlib.h>
double Pvalue (const double *restrict ARRAY1, const size_t ARRAY1_SIZE, const double *restrict ARRAY2, const size_t ARRAY2_SIZE) {
if (ARRAY1_SIZE <= 1) {
return 1.0;
} else if (ARRAY2_SIZE <= 1) {
return 1.0;
}
double fmean1 = 0.0, fmean2 = 0.0;
for (s... |
printf <- function(...) cat(sprintf(...))
d1 <- c(27.5,21.0,19.0,23.6,17.0,17.9,16.9,20.1,21.9,22.6,23.1,19.6,19.0,21.7,21.4)
d2 <- c(27.1,22.0,20.8,23.4,23.4,23.5,25.8,22.0,24.8,20.2,21.9,22.1,22.9,20.5,24.4)
d3 <- c(17.2,20.9,22.6,18.1,21.7,21.4,23.5,24.2,14.7,21.8)
d4 <- c(21.5,22.8,21.0,23.0,21.6,23.6,22.5,20.7,... |
Generate an equivalent R version of this C code. | #include <stdio.h>
#include <math.h>
#include <stdlib.h>
double Pvalue (const double *restrict ARRAY1, const size_t ARRAY1_SIZE, const double *restrict ARRAY2, const size_t ARRAY2_SIZE) {
if (ARRAY1_SIZE <= 1) {
return 1.0;
} else if (ARRAY2_SIZE <= 1) {
return 1.0;
}
double fmean1 = 0.0, fmean2 = 0.0;
for (s... |
printf <- function(...) cat(sprintf(...))
d1 <- c(27.5,21.0,19.0,23.6,17.0,17.9,16.9,20.1,21.9,22.6,23.1,19.6,19.0,21.7,21.4)
d2 <- c(27.1,22.0,20.8,23.4,23.4,23.5,25.8,22.0,24.8,20.2,21.9,22.1,22.9,20.5,24.4)
d3 <- c(17.2,20.9,22.6,18.1,21.7,21.4,23.5,24.2,14.7,21.8)
d4 <- c(21.5,22.8,21.0,23.0,21.6,23.6,22.5,20.7,... |
Preserve the algorithm and functionality while converting the code from C to R. |
#include<graphics.h>
#include<math.h>
#define pi M_PI
void sunflower(int winWidth, int winHeight, double diskRatio, int iter){
double factor = .5 + sqrt(1.25),r,theta;
double x = winWidth/2.0, y = winHeight/2.0;
double maxRad = pow(iter,factor)/iter;
int i;
setbkcolor(LIGHTBLUE);
for(i=0;i<=iter;i++){
... | phi=1/2+sqrt(5)/2
r=seq(0,1,length.out=2000)
theta=numeric(length(r))
theta[1]=0
for(i in 2:length(r)){
theta[i]=theta[i-1]+phi*2*pi
}
x=r*cos(theta)
y=r*sin(theta)
par(bg="black")
plot(x,y)
size=seq(.5,2,length.out = length(x))
thick=seq(.1,2,length.out = length(x))
for(i in 1:length(x)){
points(x[i],y[i],cex=size... |
Convert this Python snippet to Haskell and keep its semantics consistent. |
import curses
from random import randrange, choice
from collections import defaultdict
letter_codes = [ord(ch) for ch in 'WASDRQwasdrq']
actions = ['Up', 'Left', 'Down', 'Right', 'Restart', 'Exit']
actions_dict = dict(zip(letter_codes, actions * 2))
def get_user_action(keyboard):
char = "N"
while char not in... | import System.IO
import Data.List
import Data.Maybe
import Control.Monad
import Data.Random
import Data.Random.Distribution.Categorical
import System.Console.ANSI
import Control.Lens
prob4 :: Double
prob4 = 0.1
type Position = [[Int]]
combine, shift :: [Int]->[Int]
combine (x:y:l) | x==y = (2*x) : combine l
combi... |
Rewrite this program in Haskell while keeping its functionality equivalent to the Python version. |
from random import randint
from collections import namedtuple
import random
from pprint import pprint as pp
from collections import Counter
playercount = 2
maxscore = 100
maxgames = 100000
Game = namedtuple('Game', 'players, maxscore, rounds')
Round = namedtuple('Round', 'who, start, scores, safe')
class Play... |
module Main where
import System.Random (randomRIO)
import Text.Printf (printf)
data PInfo = PInfo { stack :: Int
, score :: Int
, rolls :: Int
, next :: Bool
, won :: Bool
, name :: String
}
type... |
Keep all operations the same but rewrite the snippet in Haskell. |
from random import randint
from collections import namedtuple
import random
from pprint import pprint as pp
from collections import Counter
playercount = 2
maxscore = 100
maxgames = 100000
Game = namedtuple('Game', 'players, maxscore, rounds')
Round = namedtuple('Round', 'who, start, scores, safe')
class Play... |
module Main where
import System.Random (randomRIO)
import Text.Printf (printf)
data PInfo = PInfo { stack :: Int
, score :: Int
, rolls :: Int
, next :: Bool
, won :: Bool
, name :: String
}
type... |
Convert the following code from Python to Haskell, ensuring the logic remains intact. | print('\n'.join((f'{x[0]}: {" ".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in
(x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w)
for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if... |
import Data.Bifunctor (first)
import Data.Char (toUpper)
import Data.Function (on)
import Data.List ((\\), groupBy, intersect, nub, sortOn)
import Data.Ord (Down(..))
consonants :: String
consonants = cons ++ map toUpper cons
where cons = ['a'..'z'] \\ "aeiou"
onlyConsonants :: String -> String
onlyConsonan... |
Translate the given Python code snippet into Haskell without altering its behavior. | import random
from typing import List, Callable, Optional
def modifier(x: float) -> float:
return 2*(.5 - x) if x < 0.5 else 2*(x - .5)
def modified_random_distribution(modifier: Callable[[float], float],
n: int) -> List[float]:
d: List[float] = []
while len(d)... | import System.Random
import Data.List
import Text.Printf
modify :: Ord a => (a -> a) -> [a] -> [a]
modify f = foldMap test . pairs
where
pairs lst = zip lst (tail lst)
test (r1, r2) = if r2 < f r1 then [r1] else []
vShape x = if x < 0.5 then 2*(0.5-x) else 2*(x-0.5)
hist b lst = zip [0,b..] res
where
... |
Port the following code from Python to Haskell with equivalent syntax and logic. | import random
from typing import List, Callable, Optional
def modifier(x: float) -> float:
return 2*(.5 - x) if x < 0.5 else 2*(x - .5)
def modified_random_distribution(modifier: Callable[[float], float],
n: int) -> List[float]:
d: List[float] = []
while len(d)... | import System.Random
import Data.List
import Text.Printf
modify :: Ord a => (a -> a) -> [a] -> [a]
modify f = foldMap test . pairs
where
pairs lst = zip lst (tail lst)
test (r1, r2) = if r2 < f r1 then [r1] else []
vShape x = if x < 0.5 then 2*(0.5-x) else 2*(x-0.5)
hist b lst = zip [0,b..] res
where
... |
Preserve the algorithm and functionality while converting the code from Python to Haskell. |
def common_list_elements(*lists):
return list(set.intersection(*(set(list_) for list_ in lists)))
if __name__ == "__main__":
test_cases = [
([2, 5, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 9, 8, 4], [1, 3, 7, 6, 9]),
([2, 2, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 2, 2, 4], [2, 3, 7, 6, 2]),
]
for c... | import qualified Data.Set as Set
task :: Ord a => [[a]] -> [a]
task [] = []
task xs = Set.toAscList . foldl1 Set.intersection . map Set.fromList $ xs
main = print $ task [[2,5,1,3,8,9,4,6], [3,5,6,2,9,8,4], [1,3,7,6,9]]
|
Convert the following code from Python to Haskell, ensuring the logic remains intact. |
def Dijkstra(Graph, source):
infinity = float('infinity')
n = len(graph)
dist = [infinity]*n
previous = [infinity]*n
dist[source] = 0
Q = list(range(n))
while Q:
u = min(Q, key=lambda n:dist[n])
Q.remove(u)
if dist[... | #!/usr/bin/runhaskell
import Data.Maybe (fromMaybe)
average :: (Int, Int) -> (Int, Int) -> (Int, Int)
average (x, y) (x_, y_) = ((x + x_) `div` 2, (y + y_) `div` 2)
notBlocked :: [String] -> ((Int, Int), (Int, Int)) -> Bool
notBlocked maze (_, (x, y)) = ' ' == (maze !! y) !! x
substitute :: [a] -> Int -> a -... |
Convert this Python snippet to Haskell and keep its semantics consistent. | import math
dxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251,
-0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915,
2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193,
0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, ... | import Data.List (mapAccumL, genericLength)
import Text.Printf
funnel :: (Num a) => (a -> a -> a) -> [a] -> [a]
funnel rule = snd . mapAccumL (\x dx -> (rule x dx, x + dx)) 0
mean :: (Fractional a) => [a] -> a
mean xs = sum xs / genericLength xs
stddev :: (Floating a) => [a] -> a
stddev xs = sqrt $ sum [(x-m)**2 | ... |
Keep all operations the same but rewrite the snippet in Haskell. | import math
dxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251,
-0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915,
2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193,
0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, ... | import Data.List (mapAccumL, genericLength)
import Text.Printf
funnel :: (Num a) => (a -> a -> a) -> [a] -> [a]
funnel rule = snd . mapAccumL (\x dx -> (rule x dx, x + dx)) 0
mean :: (Fractional a) => [a] -> a
mean xs = sum xs / genericLength xs
stddev :: (Floating a) => [a] -> a
stddev xs = sqrt $ sum [(x-m)**2 | ... |
Keep all operations the same but rewrite the snippet in Haskell. | import random
class WumpusGame(object):
def __init__(self, edges=[]):
if edges:
cave = {}
N = max([edges[i][0] for i in range(len(edges))])
for i in range(N):
exits = [edge[1] for edge in edges if edge[0] == i]
cave[i] = exits
else:
cave = {1: [2,3,4], 2: [1,5,6], 3: [1,7,8], 4: [1... | import System.Random
import System.IO
import Data.List
import Data.Char
import Control.Monad
cave :: [[Int]]
cave = [
[1,4,7], [0,2,9], [1,3,11], [2,4,13], [0,3,5],
[4,6,14], [5,7,16], [0,6,8], [7,9,17], [1,8,10],
[9,11,18], [2,10,12], [11,13,19], [3,12,14], [5,13,15],
[14,16,19], [... |
Port the provided Python code into Haskell while preserving the original functionality. | import math
rotate_amounts = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15,... | import Control.Monad (replicateM)
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Char8 as BLC
import Data.Binary.Get
import Data.Binary.Put
import Data.Bits
import Data.Array (Array, listArray, (!))
import Data.List (foldl)
import Data.Word (Word32)
import Numeric (showHex)
type... |
Transform the following Python implementation into Haskell, maintaining the same output and logic. | from itertools import product
xx = '-5 +5'.split()
pp = '2 3'.split()
texts = '-x**p -(x)**p (-x)**p -(x**p)'.split()
print('Integer variable exponentiation')
for x, p in product(xx, pp):
print(f' x,p = {x:2},{p}; ', end=' ')
x, p = int(x), int(p)
print('; '.join(f"{t} =={eval(t):4}" for t in texts))
pr... |
main = do
print [-5^2,-(5)^2,(-5)^2,-(5^2)]
print [-5^^2,-(5)^^2,(-5)^^2,-(5^^2)]
print [-5**2,-(5)**2,(-5)**2,-(5**2)]
print [-5^3,-(5)^3,(-5)^3,-(5^3)]
print [-5^^3,-(5)^^3,(-5)^^3,-(5^^3)]
print [-5**3,-(5)**3,(-5)**3,-(5**3)]
|
Preserve the algorithm and functionality while converting the code from Python to Haskell. | from itertools import product
xx = '-5 +5'.split()
pp = '2 3'.split()
texts = '-x**p -(x)**p (-x)**p -(x**p)'.split()
print('Integer variable exponentiation')
for x, p in product(xx, pp):
print(f' x,p = {x:2},{p}; ', end=' ')
x, p = int(x), int(p)
print('; '.join(f"{t} =={eval(t):4}" for t in texts))
pr... |
main = do
print [-5^2,-(5)^2,(-5)^2,-(5^2)]
print [-5^^2,-(5)^^2,(-5)^^2,-(5^^2)]
print [-5**2,-(5)**2,(-5)**2,-(5**2)]
print [-5^3,-(5)^3,(-5)^3,-(5^3)]
print [-5^^3,-(5)^^3,(-5)^^3,-(5^^3)]
print [-5**3,-(5)**3,(-5)**3,-(5**3)]
|
Transform the following Python implementation into Haskell, maintaining the same output and logic. | import sys
HIST = {}
def trace(frame, event, arg):
for name,val in frame.f_locals.items():
if name not in HIST:
HIST[name] = []
else:
if HIST[name][-1] is val:
continue
HIST[name].append(val)
return trace
def undo(name):
HIST[name].pop(-1)
... | import Data.IORef
newtype HVar a = HVar (IORef [a])
newHVar :: a -> IO (HVar a)
newHVar value = fmap HVar (newIORef [value])
readHVar :: HVar a -> IO a
readHVar (HVar ref) = fmap head (readIORef ref)
writeHVar :: a -> HVar a -> IO ()
writeHVar value (HVar ref) = modifyIORef ref (value:)
undoHVar :: HVar a -> IO ()... |
Ensure the translated Haskell code behaves exactly like the original Python snippet. |
import sys
if len(sys.argv)!=2:
print("Usage : python " + sys.argv[0] + " <filename>")
exit()
dataFile = open(sys.argv[1],"r")
fileData = dataFile.read().split('\n')
dataFile.close()
[print(i) for i in fileData[::-1]]
| import qualified Data.Text as T
import qualified Data.Text.IO as TIO
main :: IO ()
main = TIO.interact $ T.unlines . reverse . T.lines
|
Convert this Python block to Haskell, preserving its control flow and logic. | LIST = ["1a3c52debeffd", "2b6178c97a938stf", "3ycxdb1fgxa2yz"]
print(sorted([ch for ch in set([c for c in ''.join(LIST)]) if all(w.count(ch) == 1 for w in LIST)]))
| import qualified Data.Map.Strict as M
import Data.Maybe (fromJust)
import qualified Data.Set as S
onceInEach :: [String] -> String
onceInEach [] = []
onceInEach ws@(x : xs) =
S.elems $
S.filter
((wordCount ==) . fromJust . flip M.lookup freq)
( foldr
(S.intersection . S.fromList)
... |
Port the following code from Python to Haskell with equivalent syntax and logic. |
from math import floor, pow
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def odd(n):
return n and 1 != 0
def jacobsthal(n):
return floor((pow(2,n)+odd(n))/3)
def jacobsthal_lucas(n):
return int(pow(2,n)+pow(-1,n))
d... | jacobsthal :: [Integer]
jacobsthal = 0 : 1 : zipWith (\x y -> 2 * x + y) jacobsthal (tail jacobsthal)
jacobsthalLucas :: [Integer]
jacobsthalLucas = 2 : 1 : zipWith (\x y -> 2 * x + y) jacobsthalLucas (tail jacobsthalLucas)
jacobsthalOblong :: [Integer]
jacobsthalOblong = zipWith (*) jacobsthal (tail jacobsthal)
isP... |
Port the provided Python code into Haskell while preserving the original functionality. |
from math import floor, pow
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def odd(n):
return n and 1 != 0
def jacobsthal(n):
return floor((pow(2,n)+odd(n))/3)
def jacobsthal_lucas(n):
return int(pow(2,n)+pow(-1,n))
d... | jacobsthal :: [Integer]
jacobsthal = 0 : 1 : zipWith (\x y -> 2 * x + y) jacobsthal (tail jacobsthal)
jacobsthalLucas :: [Integer]
jacobsthalLucas = 2 : 1 : zipWith (\x y -> 2 * x + y) jacobsthalLucas (tail jacobsthalLucas)
jacobsthalOblong :: [Integer]
jacobsthalOblong = zipWith (*) jacobsthal (tail jacobsthal)
isP... |
Ensure the translated Haskell code behaves exactly like the original Python snippet. |
from sympy import Sieve
def nsuccprimes(count, mx):
"return tuple of <count> successive primes <= mx (generator)"
sieve = Sieve()
sieve.extend(mx)
primes = sieve._list
return zip(*(primes[n:] for n in range(count)))
def check_value_diffs(diffs, values):
"Differences between successive values ... |
import Data.Numbers.Primes (primes)
type Result = [(String, [Int])]
oneMillionPrimes :: Integral p => [p]
oneMillionPrimes = takeWhile (<1_000_000) primes
getGroups :: [Int] -> Result
getGroups [] = []
getGroups ps@(n:x:y:z:xs)
| x-n == 6 && y-x == 4 && z-y == 2 = ("(6 4 2)", [n, x, y, z]) : getGroups... |
Please provide an equivalent version of this Python code in Haskell. |
def digitSumsPrime(n):
def go(bases):
return all(
isPrime(digitSum(b)(n))
for b in bases
)
return go
def digitSum(base):
def go(n):
q, r = divmod(n, base)
return go(q) + r if n else 0
return go
def main():
xs = [
... | import Data.Bifunctor (first)
import Data.List.Split (chunksOf)
import Data.Numbers.Primes (isPrime)
digitSumsPrime :: Int -> [Int] -> Bool
digitSumsPrime n = all (isPrime . digitSum n)
digitSum :: Int -> Int -> Int
digitSum n base = go n
where
go 0 = 0
go n = uncurry (+) (first go $ quotRem n base)
mai... |
Rewrite this program in Haskell while keeping its functionality equivalent to the Python version. |
from itertools import accumulate, chain, takewhile
def primeSums():
return (
x for x in enumerate(
accumulate(
chain([(0, 0)], primes()),
lambda a, p: (p, p + a[1])
)
) if isPrime(x[1][1])
)
def main():
for x in take... | import Data.List (scanl)
import Data.Numbers.Primes (isPrime, primes)
indexedPrimeSums :: [(Integer, Integer, Integer)]
indexedPrimeSums =
filter (\(_, _, n) -> isPrime n) $
scanl
(\(i, _, m) p -> (succ i, p, p + m))
(0, 0, 0)
primes
main :: IO ()
main =
mapM_ print $
takeWhile (\(_, ... |
Translate this program into Haskell but keep the logic exactly as in Python. |
from itertools import accumulate, chain, takewhile
def primeSums():
return (
x for x in enumerate(
accumulate(
chain([(0, 0)], primes()),
lambda a, p: (p, p + a[1])
)
) if isPrime(x[1][1])
)
def main():
for x in take... | import Data.List (scanl)
import Data.Numbers.Primes (isPrime, primes)
indexedPrimeSums :: [(Integer, Integer, Integer)]
indexedPrimeSums =
filter (\(_, _, n) -> isPrime n) $
scanl
(\(i, _, m) p -> (succ i, p, p + m))
(0, 0, 0)
primes
main :: IO ()
main =
mapM_ print $
takeWhile (\(_, ... |
Produce a language-to-language conversion: from Python to Haskell, same semantics. |
from itertools import (chain, permutations)
from functools import (reduce)
from math import (gcd)
def main():
digits = [1, 2, 3, 4, 6, 7, 8, 9]
lcmDigits = reduce(lcm, digits)
sevenDigits = ((delete)(digits)(x) for x in [1, 4, 7])
print(
max(
(
... | import Data.List (maximumBy, permutations, delete)
import Data.Ord (comparing)
import Data.Bool (bool)
unDigits :: [Int] -> Int
unDigits = foldl ((+) . (10 *)) 0
ds :: [Int]
ds = [1, 2, 3, 4, 6, 7, 8, 9]
lcmDigits :: Int
lcmDigits = foldr1 lcm ds
sevenDigits :: [[Int]]
sevenDigits = (`delete` ds) <$> [1, 4, 7]
... |
Convert this Python snippet to Haskell and keep its semantics consistent. |
from itertools import (chain, permutations)
from functools import (reduce)
from math import (gcd)
def main():
digits = [1, 2, 3, 4, 6, 7, 8, 9]
lcmDigits = reduce(lcm, digits)
sevenDigits = ((delete)(digits)(x) for x in [1, 4, 7])
print(
max(
(
... | import Data.List (maximumBy, permutations, delete)
import Data.Ord (comparing)
import Data.Bool (bool)
unDigits :: [Int] -> Int
unDigits = foldl ((+) . (10 *)) 0
ds :: [Int]
ds = [1, 2, 3, 4, 6, 7, 8, 9]
lcmDigits :: Int
lcmDigits = foldr1 lcm ds
sevenDigits :: [[Int]]
sevenDigits = (`delete` ds) <$> [1, 4, 7]
... |
Please provide an equivalent version of this Python code in Haskell. | def jacobi(a, n):
if n <= 0:
raise ValueError("'n' must be a positive integer.")
if n % 2 == 0:
raise ValueError("'n' must be odd.")
a %= n
result = 1
while a != 0:
while a % 2 == 0:
a /= 2
n_mod_8 = n % 8
if n_mod_8 in (3, 5):
... | jacobi :: Integer -> Integer -> Integer
jacobi 0 1 = 1
jacobi 0 _ = 0
jacobi a n =
let a_mod_n = rem a n
in if even a_mod_n
then case rem n 8 of
1 -> jacobi (div a_mod_n 2) n
3 -> negate $ jacobi (div a_mod_n 2) n
5 -> negate $ jacobi (div a_mod_n 2) n
... |
Can you help me rewrite this code in Haskell instead of Python, keeping it the same logically? | def jacobi(a, n):
if n <= 0:
raise ValueError("'n' must be a positive integer.")
if n % 2 == 0:
raise ValueError("'n' must be odd.")
a %= n
result = 1
while a != 0:
while a % 2 == 0:
a /= 2
n_mod_8 = n % 8
if n_mod_8 in (3, 5):
... | jacobi :: Integer -> Integer -> Integer
jacobi 0 1 = 1
jacobi 0 _ = 0
jacobi a n =
let a_mod_n = rem a n
in if even a_mod_n
then case rem n 8 of
1 -> jacobi (div a_mod_n 2) n
3 -> negate $ jacobi (div a_mod_n 2) n
5 -> negate $ jacobi (div a_mod_n 2) n
... |
Produce a functionally identical Haskell code for the snippet given in Python. | from itertools import permutations
from operator import mul
from math import fsum
from spermutations import spermutations
def prod(lst):
return reduce(mul, lst, 1)
def perm(a):
n = len(a)
r = range(n)
s = permutations(r)
return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)
def det(a):
... | sPermutations :: [a] -> [([a], Int)]
sPermutations = flip zip (cycle [1, -1]) . foldl aux [[]]
where
aux items x = do
(f, item) <- zip (cycle [reverse, id]) items
f (insertEv x item)
insertEv x [] = [[x]]
insertEv x l@(y:ys) = (x : l) : ((y :) <$>) (insertEv x ys)
elemPos :: [[a]] -> Int -> I... |
Keep all operations the same but rewrite the snippet in Haskell. | from itertools import permutations
from operator import mul
from math import fsum
from spermutations import spermutations
def prod(lst):
return reduce(mul, lst, 1)
def perm(a):
n = len(a)
r = range(n)
s = permutations(r)
return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)
def det(a):
... | sPermutations :: [a] -> [([a], Int)]
sPermutations = flip zip (cycle [1, -1]) . foldl aux [[]]
where
aux items x = do
(f, item) <- zip (cycle [reverse, id]) items
f (insertEv x item)
insertEv x [] = [[x]]
insertEv x l@(y:ys) = (x : l) : ((y :) <$>) (insertEv x ys)
elemPos :: [[a]] -> Int -> I... |
Translate this program into Haskell but keep the logic exactly as in Python. | Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> x = [n for n in range(1000) if str(sum(int(d) for d in str(n))) in str(n)]
>>> len(x)
48
>>> for i in range(0, len(x), (stride:= 10)): print(str(x[i... | import Data.Char (digitToInt)
import Data.List (isInfixOf)
import Data.List.Split (chunksOf)
digitSumIsSubString :: String -> Bool
digitSumIsSubString =
isInfixOf
=<< show . foldr ((+) . digitToInt) 0
main :: IO ()
main =
mapM_ putStrLn $
showMatches digitSumIsSubString <$> [999, 10000]
showMatches :... |
Write a version of this Python function in Haskell with identical behavior. | Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> x = [n for n in range(1000) if str(sum(int(d) for d in str(n))) in str(n)]
>>> len(x)
48
>>> for i in range(0, len(x), (stride:= 10)): print(str(x[i... | import Data.Char (digitToInt)
import Data.List (isInfixOf)
import Data.List.Split (chunksOf)
digitSumIsSubString :: String -> Bool
digitSumIsSubString =
isInfixOf
=<< show . foldr ((+) . digitToInt) 0
main :: IO ()
main =
mapM_ putStrLn $
showMatches digitSumIsSubString <$> [999, 10000]
showMatches :... |
Translate this program into Haskell but keep the logic exactly as in Python. | >>> from random import randrange
>>> def sattoloCycle(items):
for i in range(len(items) - 1, 0, -1):
j = randrange(i)
items[j], items[i] = items[i], items[j]
>>>
>>> for _ in range(10):
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sattoloCycle(lst)
print(lst)
[5, 8, 1, 2, 6, 4, 3, 9, 10, 7]
[5, 9, 8, 10, 4, ... | import Control.Monad ((>=>), (>>=), forM_)
import Control.Monad.Primitive
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as M
import System.Random.MWC
type MutVec m a = M.MVector (PrimState m) a
cyclicPermM :: PrimMonad m => Gen (PrimState m) -> MutVec m a -> m (MutVec m a)
cyclicPermM rand... |
Transform the following Python implementation into Haskell, maintaining the same output and logic. | >>> from random import randrange
>>> def sattoloCycle(items):
for i in range(len(items) - 1, 0, -1):
j = randrange(i)
items[j], items[i] = items[i], items[j]
>>>
>>> for _ in range(10):
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sattoloCycle(lst)
print(lst)
[5, 8, 1, 2, 6, 4, 3, 9, 10, 7]
[5, 9, 8, 10, 4, ... | import Control.Monad ((>=>), (>>=), forM_)
import Control.Monad.Primitive
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as M
import System.Random.MWC
type MutVec m a = M.MVector (PrimState m) a
cyclicPermM :: PrimMonad m => Gen (PrimState m) -> MutVec m a -> m (MutVec m a)
cyclicPermM rand... |
Rewrite this program in Haskell while keeping its functionality equivalent to the Python version. | from ftplib import FTP
ftp = FTP('kernel.org')
ftp.login()
ftp.cwd('/pub/linux/kernel')
ftp.set_pasv(True)
print ftp.retrlines('LIST')
print ftp.retrbinary('RETR README', open('README', 'wb').write)
ftp.quit()
| module Main (main) where
import Control.Exception (bracket)
import Control.Monad (void)
import Data.Foldable (for_)
import Network.FTP.Client
( cwd
, easyConnectFTP
, getbinary
, loginAnon
... |
Ensure the translated Haskell code behaves exactly like the original Python snippet. | >>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> conn.execute()
<sqlite3.Cursor object at 0x013265C0>
>>>
|
import Database.SQLite.Simple
main = do
db <- open "postal.db"
execute_ db "\
\CREATE TABLE address (\
\addrID INTEGER PRIMARY KEY AUTOINCREMENT, \
\addrStreet TEXT NOT NULL, \
\addrCity TEXT NOT NULL, \
\addrState TEXT NOT NULL, \
\addrZIP TEXT NOT N... |
Convert this Python block to Haskell, preserving its control flow and logic. |
from itertools import count, islice
def isBrazil(n):
return 7 <= n and (
0 == n % 2 or any(
map(monoDigit(n), range(2, n - 1))
)
)
def monoDigit(n):
def go(base):
def g(b, n):
(q, d) = divmod(n, b)
def p(qr):
retu... | import Data.Numbers.Primes (primes)
isBrazil :: Int -> Bool
isBrazil n = 7 <= n && (even n || any (monoDigit n) [2 .. n - 2])
monoDigit :: Int -> Int -> Bool
monoDigit n b =
let (q, d) = quotRem n b
in d ==
snd
(until
(uncurry (flip ((||) . (d /=)) . (0 ==)))
((`quotRem` b) . fst)
... |
Produce a functionally identical Haskell code for the snippet given in Python. |
from itertools import count, islice
def isBrazil(n):
return 7 <= n and (
0 == n % 2 or any(
map(monoDigit(n), range(2, n - 1))
)
)
def monoDigit(n):
def go(base):
def g(b, n):
(q, d) = divmod(n, b)
def p(qr):
retu... | import Data.Numbers.Primes (primes)
isBrazil :: Int -> Bool
isBrazil n = 7 <= n && (even n || any (monoDigit n) [2 .. n - 2])
monoDigit :: Int -> Int -> Bool
monoDigit n b =
let (q, d) = quotRem n b
in d ==
snd
(until
(uncurry (flip ((||) . (d /=)) . (0 ==)))
((`quotRem` b) . fst)
... |
Produce a functionally identical Haskell code for the snippet given in Python. | >>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\n')
...
>>>
| module Main (main) where
main :: IO ()
main = writeFile "/dev/tape" "Hello from Rosetta Code!"
|
Keep all operations the same but rewrite the snippet in Haskell. | from itertools import islice
class Recamans():
"Recamán's sequence generator callable class"
def __init__(self):
self.a = None
self.n = None
def __call__(self):
"Recamán's sequence generator"
nxt = 0
a, n = {nxt}, 0
self.a = a
self.n = n
... | recaman :: Int -> [Int]
recaman n = fst <$> reverse (go n)
where
go 0 = []
go 1 = [(0, 1)]
go x =
let xs@((r, i):_) = go (pred x)
back = r - i
in ( if 0 < back && not (any ((back ==) . fst) xs)
then back
else r + i
, succ i) :
... |
Transform the following Python implementation into Haskell, maintaining the same output and logic. | from itertools import islice
class Recamans():
"Recamán's sequence generator callable class"
def __init__(self):
self.a = None
self.n = None
def __call__(self):
"Recamán's sequence generator"
nxt = 0
a, n = {nxt}, 0
self.a = a
self.n = n
... | recaman :: Int -> [Int]
recaman n = fst <$> reverse (go n)
where
go 0 = []
go 1 = [(0, 1)]
go x =
let xs@((r, i):_) = go (pred x)
back = r - i
in ( if 0 < back && not (any ((back ==) . fst) xs)
then back
else r + i
, succ i) :
... |
Change the programming language of this snippet from Python to Haskell without modifying what it does. | >>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1))
>>> [ Y(fac)(i) for i in range(10) ]
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
>>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))
>>> [ Y(fib)(i) for i i... | newtype Mu a = Roll
{ unroll :: Mu a -> a }
fix :: (a -> a) -> a
fix = g <*> (Roll . g)
where
g = (. (>>= id) unroll)
- this version is not in tail call position...
fac :: Integer -> Integer
fac =
(fix $ \f n i -> if i <= 0 then n else f (i * n) (i - 1)) 1
{
fibs :: () -> [Integer]
fibs() =
f... |
Preserve the algorithm and functionality while converting the code from Python to Haskell. | from collections import namedtuple
Circle = namedtuple("Circle", "x y r")
circles = [
Circle( 1.6417233788, 1.6121789534, 0.0848270516),
Circle(-1.4944608174, 1.2077959613, 1.1039549836),
Circle( 0.6110294452, -0.6907087527, 0.9089162485),
Circle( 0.3844862411, 0.2923344616, 0.2375743054),
Circ... | data Circle = Circle { cx :: Double, cy :: Double, cr :: Double }
isInside :: Double -> Double -> Circle -> Bool
isInside x y c = (x - cx c) ^ 2 + (y - cy c) ^ 2 <= (cr c ^ 2)
isInsideAny :: Double -> Double -> [Circle] -> Bool
isInsideAny x y = any (isInside x y)
approximatedArea :: [Circle] -> Int -> Double
approx... |
Transform the following Python implementation into Haskell, maintaining the same output and logic. | from collections import namedtuple
Circle = namedtuple("Circle", "x y r")
circles = [
Circle( 1.6417233788, 1.6121789534, 0.0848270516),
Circle(-1.4944608174, 1.2077959613, 1.1039549836),
Circle( 0.6110294452, -0.6907087527, 0.9089162485),
Circle( 0.3844862411, 0.2923344616, 0.2375743054),
Circ... | data Circle = Circle { cx :: Double, cy :: Double, cr :: Double }
isInside :: Double -> Double -> Circle -> Bool
isInside x y c = (x - cx c) ^ 2 + (y - cy c) ^ 2 <= (cr c ^ 2)
isInsideAny :: Double -> Double -> [Circle] -> Bool
isInsideAny x y = any (isInside x y)
approximatedArea :: [Circle] -> Int -> Double
approx... |
Convert this Python snippet to Haskell and keep its semantics consistent. | fact = [1]
for n in range(1, 12):
fact.append(fact[n-1] * n)
for b in range(9, 12+1):
print(f"The factorions for base {b} are:")
for i in range(1, 1500000):
fact_sum = 0
j = i
while j > 0:
d = j % b
fact_sum += fact[d]
j = j//b
if fact_su... | import Text.Printf (printf)
import Data.List (unfoldr)
import Control.Monad (guard)
factorion :: Int -> Int -> Bool
factorion b n = f b n == n
where
f b = sum . map (product . enumFromTo 1) . unfoldr (\x -> guard (x > 0) >> pure (x `mod` b, x `div` b))
main :: IO ()
main = mapM_ (uncurry (printf "Factorions for ba... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.