Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Port the provided C code into Arturo while preserving the original functionality.
#include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; unsigned int p; for (; (n & 1) == 0; n >>= 1) { ++total; } for (p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ++count; }...
tau: function [x] -> size factors x found: 0 i:1 while [found<100][ if 0 = i % tau i [ prints pad to :string i 5 found: found + 1 if 0 = found % 10 -> print "" ] i: i + 1 ]
Convert this C block to Arturo, preserving its control flow and logic.
#include <stdbool.h> #include <stdio.h> bool is_prime(int n) { int i = 5; if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } while (i * i <= n) { if (n % i == 0) { return false; } ...
primes: select 1..5000 => prime? loop split.every: 3 select primes 'p [25 = sum digits p] 'a -> print map a => [pad to :string & 5]
Convert the following code from C to Arturo, ensuring the logic remains intact.
#include <stdbool.h> #include <stdio.h> bool is_prime(int n) { int i = 5; if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } while (i * i <= n) { if (n % i == 0) { return false; } ...
primes: select 1..5000 => prime? loop split.every: 3 select primes 'p [25 = sum digits p] 'a -> print map a => [pad to :string & 5]
Produce a language-to-language conversion: from C to Arturo, same semantics.
#include <stdbool.h> #include <stdio.h> bool primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; switch (r) { case 2: case 3: case 5: case 7: break; default: return false; } n /= 10; sum +...
pDigits: [2 3 5 7] lst: map pDigits 'd -> @[d] result: new [] while [0 <> size lst][ nextList: new [] loop lst 'digitSeq [ currSum: sum digitSeq loop pDigits 'n [ newSum: currSum + n newDigitSeq: digitSeq ++ n case [newSum] when? [<13] -> 'ne...
Maintain the same structure and functionality when rewriting this code in Arturo.
#include <stdbool.h> #include <stdio.h> bool primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; switch (r) { case 2: case 3: case 5: case 7: break; default: return false; } n /= 10; sum +...
pDigits: [2 3 5 7] lst: map pDigits 'd -> @[d] result: new [] while [0 <> size lst][ nextList: new [] loop lst 'digitSeq [ currSum: sum digitSeq loop pDigits 'n [ newSum: currSum + n newDigitSeq: digitSeq ++ n case [newSum] when? [<13] -> 'ne...
Change the following C code into Arturo without altering its purpose.
#include<stdio.h> typedef struct{ int a; }layer1; typedef struct{ layer1 l1; float b,c; }layer2; typedef struct{ layer2 l2; layer1 l1; int d,e; }layer3; void showCake(layer3 cake){ printf("\ncake.d = %d",cake.d); printf("\ncake.e = %d",cake.e); printf("\ncake.l1.a = %d",cake.l1.a); printf("\ncake.l2.b = %...
x: #[ name: "John" surname: "Doe" age: 34 hobbies: [ "Cycling", "History", "Programming", "Languages", "Psychology", "Buddhism" ] sayHello: function [][ print "Hello there!" ] ] print ["Name of first person:" x\name] y: new x y\na...
Port the following code from C to Arturo with equivalent syntax and logic.
#include<stdio.h> typedef struct{ int a; }layer1; typedef struct{ layer1 l1; float b,c; }layer2; typedef struct{ layer2 l2; layer1 l1; int d,e; }layer3; void showCake(layer3 cake){ printf("\ncake.d = %d",cake.d); printf("\ncake.e = %d",cake.e); printf("\ncake.l1.a = %d",cake.l1.a); printf("\ncake.l2.b = %...
x: #[ name: "John" surname: "Doe" age: 34 hobbies: [ "Cycling", "History", "Programming", "Languages", "Psychology", "Buddhism" ] sayHello: function [][ print "Hello there!" ] ] print ["Name of first person:" x\name] y: new x y\na...
Keep all operations the same but rewrite the snippet in Arturo.
#include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gmp.h> bool is_prime(uint32_t n) { if (n == 2) return true; if (n < 2 || n % 2 == 0) return false; for (uint32_t p = 3; p * p <= n; p += 2) { if (n % p == 0) ret...
perms: function [n][ str: repeat to :string n 2 result: new [] lim: dec size digits n loop 0..lim 'd -> 'result ++ slice str d lim+d return to [:integer] result ] circulars: new [] circular?: function [x][ if not? prime? x -> return false loop perms x 'y [ if not? prime? ...
Transform the following C implementation into Arturo, maintaining the same output and logic.
#include <stdio.h> #include <stdlib.h> #include <math.h> #define LIMIT 10000 unsigned int sieve(unsigned int n, unsigned int **list) { unsigned char *sieve = calloc(n+1, 1); unsigned int i, j, max = 0; for (i = 2; i*i <= n; i++) if (!sieve[i]) for (j = i+i; j <= n; j += i) ...
primes: select 0..10000 => prime? frobenius: function [n] -> sub sub primes\[n] * primes\[n+1] primes\[n] primes\[n+1] frob: 0 lst: new [] j: new 0 while [frob < 10000] [ 'lst ++ frob: <= frobenius j inc 'j ] loop split.every:10 chop lst 'a -> print map a => [pad to :string & 5]
Generate an equivalent Arturo version of this C code.
#include <stdio.h> #include <stdlib.h> #include <math.h> #define LIMIT 10000 unsigned int sieve(unsigned int n, unsigned int **list) { unsigned char *sieve = calloc(n+1, 1); unsigned int i, j, max = 0; for (i = 2; i*i <= n; i++) if (!sieve[i]) for (j = i+i; j <= n; j += i) ...
primes: select 0..10000 => prime? frobenius: function [n] -> sub sub primes\[n] * primes\[n+1] primes\[n] primes\[n+1] frob: 0 lst: new [] j: new 0 while [frob < 10000] [ 'lst ++ frob: <= frobenius j inc 'j ] loop split.every:10 chop lst 'a -> print map a => [pad to :string & 5]
Generate a Arturo translation of this C snippet without changing its computational steps.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef int(*cmp_func)(const void*, const void*); void perm_sort(void *a, int n, size_t msize, cmp_func _cmp) { char *p, *q, *tmp = malloc(msize); # define A(i) ((char *)a + msize * (i)) # define swap(a, b) {\ memcpy(tmp, a, msize);\ memcpy(a, b, msize);...
sorted?: function [arr][ previous: first arr loop slice arr 1 (size arr)-1 'item [ if not? item > previous -> return false previous: item ] return true ] permutationSort: function [items][ loop permutate items 'perm [ if sorted? perm -> return perm ] ] print permutatio...
Translate the given C code snippet into Arturo without altering its behavior.
#include <stdio.h> #include <math.h> typedef unsigned long long ulong; ulong root(ulong base, ulong n) { ulong n1, n2, n3, c, d, e; if (base < 2) return base; if (n == 0) return 1; n1 = n - 1; n2 = n; n3 = n1; c = 1; d = (n3 + base) / n2; e = (n3 * d + base / (ulong)powl(d, n1)) ...
iroot: function [b n][ if b<2 -> return b n1: n-1 n2: n n3: n1 c: 1 d: (n3+b)/n2 e: ((n3*d) + b/d^n1)/n2 while [and? c<>d c<>e][ c: d d: e e: ((n3*e) + b/e^n1)/n2 ] if d<e -> return d return e ] print ["3rd root of 8:" iroot 8 3] print ["3rd root o...
Convert this C block to Arturo, preserving its control flow and logic.
#include <stdio.h> #include <math.h> typedef unsigned long long ulong; ulong root(ulong base, ulong n) { ulong n1, n2, n3, c, d, e; if (base < 2) return base; if (n == 0) return 1; n1 = n - 1; n2 = n; n3 = n1; c = 1; d = (n3 + base) / n2; e = (n3 * d + base / (ulong)powl(d, n1)) ...
iroot: function [b n][ if b<2 -> return b n1: n-1 n2: n n3: n1 c: 1 d: (n3+b)/n2 e: ((n3*d) + b/d^n1)/n2 while [and? c<>d c<>e][ c: d d: e e: ((n3*e) + b/e^n1)/n2 ] if d<e -> return d return e ] print ["3rd root of 8:" iroot 8 3] print ["3rd root o...
Convert the following code from C to Arturo, ensuring the logic remains intact.
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <gmp.h> int *primeSieve(int limit, int *length) { int i, p, *primes; int j, pc = 0; limit++; bool *c = calloc(limit, sizeof(bool)); c[0] = true; c[1] = true; for (i = 4; i < limit; i += 2) c[i] = true; p = 3; ...
firstPrimes: select 1..100 => prime? primorial: function [n][ product first.n: n firstPrimes ] fortunates: [] i: 1 while [8 > size fortunates][ m: 3 pmi: primorial i while -> not? prime? m + pmi -> m: m+2 fortunates: unique fortunates ++ m i: i + 1 ] print sort fortunates
Generate a Arturo translation of this C snippet without changing its computational steps.
int meaning_of_life();
meaningOfLife: function [][ 42 ] if standalone? -> print ~"Library: The meaning of life is |meaningOfLife|"
Maintain the same structure and functionality when rewriting this code in Arturo.
int meaning_of_life();
meaningOfLife: function [][ 42 ] if standalone? -> print ~"Library: The meaning of life is |meaningOfLife|"
Generate an equivalent Arturo version of this C code.
#define _POSIX_SOURCE #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <stddef.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> struct functionInfo { char* name; int timesCalled; char marked; }; void addToList(...
source: to :block read arg\0 frequencies: #[] inspectBlock: function [blk][ loop blk 'item [ case [] when? [word? item][ sItem: to :string item if set? sItem -> if function? var sItem [ if? key? frequencies sItem -> ...
Convert this C snippet to Arturo and keep its semantics consistent.
#include <sqlite3.h> #include <stdlib.h> #include <stdio.h> int main() { sqlite3 *db = NULL; char *errmsg; const char *code = "CREATE TABLE employee (\n" " empID INTEGER PRIMARY KEY AUTOINCREMENT,\n" " firstName TEXT NOT NULL,\n" " lastName TEXT NOT NULL,\n" " AGE INTEGER NOT NULL,\n" " DOB DATE...
createTable: function [][ query db {!sql DROP TABLE IF EXISTS users} query db {!sql CREATE TABLE users ( ID INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, email TEXT NOT NULL, age INTEGER ) } ] addUser: ...
Convert this C snippet to Arturo and keep its semantics consistent.
#include <sqlite3.h> #include <stdlib.h> #include <stdio.h> int main() { sqlite3 *db = NULL; char *errmsg; const char *code = "CREATE TABLE employee (\n" " empID INTEGER PRIMARY KEY AUTOINCREMENT,\n" " firstName TEXT NOT NULL,\n" " lastName TEXT NOT NULL,\n" " AGE INTEGER NOT NULL,\n" " DOB DATE...
createTable: function [][ query db {!sql DROP TABLE IF EXISTS users} query db {!sql CREATE TABLE users ( ID INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, email TEXT NOT NULL, age INTEGER ) } ] addUser: ...
Port the provided C code into Arturo while preserving the original functionality.
#include <stdbool.h> #include <stdio.h> bool is_prime(unsigned int n) { if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) { return fals...
sumd: function [n][ s: sum digits n (1 = size digits s)? -> return s -> return sumd s ] nice?: function [x] -> and? prime? x prime? sumd x loop split.every:10 select 500..1000 => nice? 'a -> print map a => [pad to :string & 4]
Please provide an equivalent version of this C code in Arturo.
#include <stdbool.h> #include <stdio.h> bool is_prime(unsigned int n) { if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) { return fals...
sumd: function [n][ s: sum digits n (1 = size digits s)? -> return s -> return sumd s ] nice?: function [x] -> and? prime? x prime? sumd x loop split.every:10 select 500..1000 => nice? 'a -> print map a => [pad to :string & 4]
Write a version of this C function in Arturo with identical behavior.
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int days[] = {31,29,31,30,31,30,31,31,30,31,30,31}; int m, y, w; if (argc < 2 || (y = atoi(argv[1])) <= 1752) return 1; days[1] -= (y % 4) || (!(y % 100) && (y % 400)); w = y * 365 + 97 * (y - 1) / 400 + ...
lastSundayForMonth: function [m,y][ ensure -> in? m 1..12 daysOfMonth: @[0 31 (leap? y)? -> 28 -> 27 31 30 31 30 31 31 30 31 30 31] loop range get daysOfMonth m 1 [d][ dt: to :date.format:"yyyy-M-dd" ~"|y|-|m|-|d|" if dt\Day = "Sunday" -> return dt ] ] getLastSundays: function [year][ ...
Produce a language-to-language conversion: from C to Arturo, same semantics.
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int days[] = {31,29,31,30,31,30,31,31,30,31,30,31}; int m, y, w; if (argc < 2 || (y = atoi(argv[1])) <= 1752) return 1; days[1] -= (y % 4) || (!(y % 100) && (y % 400)); w = y * 365 + 97 * (y - 1) / 400 + ...
lastSundayForMonth: function [m,y][ ensure -> in? m 1..12 daysOfMonth: @[0 31 (leap? y)? -> 28 -> 27 31 30 31 30 31 31 30 31 30 31] loop range get daysOfMonth m 1 [d][ dt: to :date.format:"yyyy-M-dd" ~"|y|-|m|-|d|" if dt\Day = "Sunday" -> return dt ] ] getLastSundays: function [year][ ...
Write a version of this C function in Arturo with identical behavior.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> int randInt(int low, int high) { return (rand() % (high - low)) + low; } void shuffle(int *const array, const int n) { if (n > 1) { int i; for (i = 0; i < n - 1; i++) { int j = randI...
latinSquare: function [n][ square: new [] variants: shuffle permutate 0..n-1 while -> n > size square [ row: sample variants 'square ++ @[row] filter 'variants 'variant [ reject: false loop.with:'i variant 'col [ if col = row\[i] -> ...
Can you help me rewrite this code in Arturo instead of C, keeping it the same logically?
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <glib.h> int string_compare(gconstpointer p1, gconstpointer p2) { const char* const* s1 = p1; const char* const* s2 = p2; return strcmp(*s1, *s2); } GPtrArray* load_dictionary(const char* file, GError** error_ptr) { GError* error = N...
wordset: map read.lines relative "unixdict.txt" => strip rotateable?: function [w][ loop 1..dec size w 'i [ rotated: rotate w i if or? [rotated = w][not? contains? wordset rotated] -> return false ] return true ] results: new [] loop select wordset 'word [3 =< size word] 'word...
Rewrite this program in Arturo while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <stdlib.h> int turn(int base, int n) { int sum = 0; while (n != 0) { int rem = n % base; n = n / base; sum += rem; } return sum % base; } void fairshare(int base, int count) { int i; printf("Base %2d:", base); for (i = 0; i < count; i++)...
thueMorse: function [base, howmany][ i: 0 result: new [] while [howmany > size result][ 'result ++ (sum digits.base:base i) % base i: i + 1 ] return result ] loop [2 3 5 11] 'b -> print [ (pad.right "Base "++(to :string b) 7)++" =>" join.with:" " map to [:strin...
Generate an equivalent Arturo version of this C code.
#include <stdio.h> #include <string.h> #include <locale.h> typedef int bool; typedef unsigned long long ull; #define TRUE 1 #define FALSE 0 char as_digit(int d) { return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a'; } void revstr(char *str) { int i, len = strlen(str); char t; for (i = 0; i < le...
esthetic?: function [n, b][ if n=0 -> return false k: n % b l: n / b while [l>0][ j: l % b if 1 <> abs k-j -> return false l: l / b k: j ] return true ] HEX: "0000000000ABCDEF" getHex: function [ds][ map ds 'd [ (d < 10)? -> to :string d ...
Rewrite this program in Arturo while keeping its functionality equivalent to the C version.
#include <stdio.h> int ispr(unsigned int n) { if ((n & 1) == 0 || n < 2) return n == 2; for (unsigned int j = 3; j * j <= n; j += 2) if (n % j == 0) return 0; return 1; } int main() { unsigned int c = 0, nc, pc = 9, i, a, b, l, ps[128], nxt[128]; for (a = 0, b = 1; a < pc; a = b++) ps[a] = b; ...
descending: @[ loop 1..9 'a [ loop 1..dec a 'b [ loop 1..dec b 'c [ loop 1..dec c 'd [ loop 1..dec d 'e [ loop 1..dec e 'f [ loop 1..dec f 'g [ loop 1..dec g 'h [ ...
Write the same code in Arturo as shown below in C.
#include <stdio.h> #include <stdlib.h> #include <locale.h> wchar_t poker[] = L"♥♦♣♠"; wchar_t four_two[] = L"\x56db\x5341\x4e8c"; int main() { if (!setlocale(LC_CTYPE, "")) { fprintf(stderr, "Locale failure, check your env vars\n"); return 1; } #ifdef __STDC_ISO_10646__ printf(...
text: "你好" print ["text:" text] print ["length:" size text] print ["contains string '好'?:" contains? text "好"] print ["contains character '平'?:" contains? text `平`] print ["text as ascii:" as.ascii text]
Convert this C block to Arturo, preserving its control flow and logic.
#include<stdlib.h> #include<string.h> #include<stdio.h> int flag = 1; void heapPermute(int n, int arr[],int arrLen){ int temp; int i; if(n==1){ printf("\n["); for(i=0;i<arrLen;i++) printf("%d,",arr[i]); printf("\b] Sign : %d",flag); flag*=-1; } else{ for(i=0;i<n-1;i++){ heapPermute(n-1,ar...
permutations: function [arr][ d: 1 c: array.of: size arr 0 xs: new arr sign: 1 ret: new @[@[xs, sign]] while [true][ while [d > 1][ d: d-1 c\[d]: 0 ] while [c\[d] >= d][ d: d+1 if d >= size arr -> return ret ] ...
Rewrite the snippet below in Arturo so it works the same as the original C code.
#include <stdio.h> #include <stdlib.h> #include <time.h> int compareInts(const void *i1, const void *i2) { int a = *((int *)i1); int b = *((int *)i2); return a - b; } int main() { int i, j, nsum, vsum, vcount, values[6], numbers[4]; srand(time(NULL)); for (;;) { vsum = 0; for (...
vals: [] while [or? 75 > sum vals 2 > size select vals => [&>=15]] [ vals: new [] while [6 > size vals][ rands: new map 1..4 => [random 1 6] remove 'rands .once (min rands) 'vals ++ sum rands ] ] print ["values:" vals ] print ["with sum:" sum vals]
Generate a Arturo translation of this C snippet without changing its computational steps.
#include <stdio.h> #include <stdlib.h> #define TRUE 1 #define FALSE 0 typedef int bool; int next_in_cycle(int *c, int len, int index) { return c[index % len]; } void kolakoski(int *c, int *s, int clen, int slen) { int i = 0, j, k = 0; while (TRUE) { s[i] = next_in_cycle(c, clen, k); if (...
kolakoski: function [a, length][ result: array.of: length 0 i: new 0 k: new 0 loop.forever a 'x [ result\[i]: x if result\[k] > 1 [ loop 1..dec result\[k] 'j [ inc 'i if i = length -> return result result\[i]: result\[i-1] ...
Change the programming language of this snippet from C to Arturo without modifying what it does.
#include <stdio.h> int main() { int i, gprev = 0; int s[7] = {1, 2, 2, 3, 4, 4, 5}; for (i = 0; i < 7; ++i) { int curr = s[i]; int prev = 0; if (i > 0 && curr == prev) printf("%d\n", i); prev = curr; } for (i = 0; i < 7; ++i) { int curr = s[i]; ...
Red[] s: [1 2 2 3 4 4 5] repeat i length? s [ curr: s/:i if all [i > 1 curr = prev][ print i ] prev: curr ]
Maintain the same structure and functionality when rewriting this code in Arturo.
#include <stdio.h> #define MAX 15 int count_divisors(int n) { int i, count = 0; for (i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; } int main() { int i, k, n, seq[MAX]; ...
firstNumWithDivisors: function [n][ i: 0 while ø [ if n = size factors i -> return i i: i+1 ] ] print map 1..15 => firstNumWithDivisors
Maintain the same structure and functionality when rewriting this code in Arturo.
#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...
bar: "▁▂▃▄▅▆▇█" barcount: to :floating dec size bar while ø [ line: input "Numbers separated by spaces: " numbers: to [:floating] split.words line mn: min numbers mx: max numbers extent: mx-mn sparkLine: new "" loop numbers 'n [ i: to :integer barcount*(n-mn)//extent 'sparkL...
Generate a Arturo translation of this C snippet without changing its computational steps.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct edit_s edit_t, *edit; struct edit_s { char c1, c2; int n; edit next; }; void leven(char *a, char *b) { int i, j, la = strlen(a), lb = strlen(b); edit *tbl = malloc(sizeof(edit) * (1 + la)); tbl[0] = calloc((1 + la) * (1 + lb), sizeof(edit...
print join.with:"\n" levenshtein.align "place" "palace" print join.with:"\n" levenshtein.align "rosettacode" "raisethysword"
Change the programming language of this snippet from C to Arturo without modifying what it does.
#include <stdio.h> #include <stdlib.h> struct node { int val, len; struct node *next; }; void lis(int *v, int len) { int i; struct node *p, *n = calloc(len, sizeof *n); for (i = 0; i < len; i++) n[i].val = v[i]; for (i = len; i--; ) { for (p = n + i; p++ < n + len; ) { if (p->val > n[i].val && p->len...
lis: function [d][ l: new [[]] loop d 'num [ x: [] loop l 'seq [ if positive? size seq [ if and? num > last seq (size seq) > size x -> x: seq ] ] 'l ++ @[x ++ @[num]] ] result: [] loop...
Write a version of this C function in Arturo with identical behavior.
#define STATIC_ASSERT(COND,MSG) typedef char static_assertion_##MSG[(!!(COND))*2-1] #define COMPILE_TIME_ASSERT3(X,L) STATIC_ASSERT(X,static_assertion_at_line_##L) #define COMPILE_TIME_ASSERT2(X,L) COMPILE_TIME_ASSERT3(X,L) #define COMPILE_TIME_ASSERT(X) COMPILE_TIME_ASSERT2(X,__LINE__) COMPILE_TIME_ASSERT(sizeof...
sumThemUp: function [x,y][ x+y ] alias.infix '--> 'sumThemUp do [ print 3 --> 4 ]
Convert the following code from C to Arturo, ensuring the logic remains intact.
#include <stdio.h> #include <math.h> int main() { int i, p, low, high, pow = 1, osc; int oddSq[120]; for (p = 0; p < 5; ++p) { low = (int)ceil(sqrt((double)pow)); if (!(low%2)) ++low; pow *= 10; high = (int)sqrt((double)pow); for (i = low, osc = 0; i <= high; i += 2)...
Red[] n: 11 limit: sqrt 1000 while [n < limit][ print n * n n: n + 2 ]
Preserve the algorithm and functionality while converting the code from C to Arturo.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_WORD_SIZE 80 #define MIN_LENGTH 9 #define WORD_SIZE (MIN_LENGTH + 1) void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("O...
wordset: map read.lines relative "unixdict.txt" => strip wordset: select wordset 'word -> 9 =< size word lastWord: "" newWord: " " count: 0 loop 0..(size wordset)-9 'i [ loop 0..8 'j -> newWord\[j]: wordset\[i+j]\[j] if and? [in? newWord wordset][lastWord <> newWord][ count: count + 1 ...
Rewrite this program in Arturo while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <stdbool.h> int digit_sum(int n) { int sum; for (sum = 0; n; n /= 10) sum += n % 10; return sum; } bool prime(int n) { if (n<4) return n>=2; for (int d=2; d*d <= n; d++) if (n%d == 0) return false; return true; } int main() { for (int i=1; i<100; i++) ...
print select 1..100 'x -> and? [prime? sum digits x^2] [prime? sum digits x^3]
Produce a language-to-language conversion: from C# to Erlang, same semantics.
using System; using System.Linq; using System.Collections.Generic; public struct Card { public Card(string rank, string suit) : this() { Rank = rank; Suit = suit; } public string Rank { get; } public string Suit { get; } public override string ToString() => $"{Rank} of {Suit}"...
-module( playing_cards ). -export( [deal/2, deal/3, deck/0, print/1, shuffle/1, sort_pips/1, sort_suites/1, task/0] ). -record( card, {pip, suite} ). -spec( deal( N_cards::integer(), Deck::[#card{}]) -> {Hand::[#card{}], Deck::[#card{}]} ). deal( N_cards, Deck ) -> lists:split( N_cards, Deck ). -spec( deal( N_hands:...
Maintain the same structure and functionality when rewriting this code in Erlang.
using System; namespace LastSundayOfEachMonth { class Program { static void Main() { Console.Write("Year to calculate: "); string strYear = Console.ReadLine(); int year = Convert.ToInt32(strYear); DateTime date; for (int i = 1; i <= ...
-module(last_sundays). -export([in_year/1]). in_year(Year) -> [lastday(Year, Month, 7) || Month <- lists:seq(1, 12)]. lastday(Year, Month, WeekDay) -> Ldm = calendar:last_day_of_the_month(Year, Month), Diff = calendar:day_of_the_week(Year, Month, Ldm) rem WeekDay, {Year, Month, Ldm - Diff}.
Ensure the translated Erlang code behaves exactly like the original C# snippet.
using System; namespace LastSundayOfEachMonth { class Program { static void Main() { Console.Write("Year to calculate: "); string strYear = Console.ReadLine(); int year = Convert.ToInt32(strYear); DateTime date; for (int i = 1; i <= ...
-module(last_sundays). -export([in_year/1]). in_year(Year) -> [lastday(Year, Month, 7) || Month <- lists:seq(1, 12)]. lastday(Year, Month, WeekDay) -> Ldm = calendar:last_day_of_the_month(Year, Month), Diff = calendar:day_of_the_week(Year, Month, Ldm) rem WeekDay, {Year, Month, Ldm - Diff}.
Translate the given C# code snippet into Erlang without altering its behavior.
using System; using System.Collections; using System.Collections.Generic; using System.Linq; public static class LIS { public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) => values == null ? throw new ArgumentNullException() : FindRecImpl(values, Sequence<T>.E...
-module(longest_increasing_subsequence). -export([test_naive/0, test_memo/0, test_patience/0, test_patience2/0, test_compare/1]). test_compare(N) when N =< 20 -> Funs = [ {"Naive", fun lis/1}, {"Memo", fun memo/1}, {"Patience", fun patience_lis/1}, {"Patience2", fun patience2/1...
Translate the given C# code snippet into Erlang without altering its behavior.
using System; using System.Dynamic; using System.Collections.Generic; public class Program { public static void Main() { string varname = Console.ReadLine(); dynamic expando = new ExpandoObject(); var map = expando as IDictionary<string, object>; map.Add(varname, "Hello...
-module( dynamic_variable_names ). -export( [task/0] ). task() -> {ok,[Variable_name]} = io:fread( "Variable name? ", "~a" ), Form = runtime_evaluation:form_from_string( erlang:atom_to_list(Variable_name) ++ "." ), io:fwrite( "~p has value ~p~n", [Variable_name, runtime_evaluation:evaluate_form(Form, {Var...
Write the same code in Erlang as shown below in C#.
var objDE = new System.DirectoryServices.DirectoryEntry("LDAP:
-module(ldap_example). -export( [main/1] ). main( [Host, DN, Password] ) -> {ok, Handle} = eldap:open( [Host] ), ok = eldap:simple_bind( Handle, DN, Password ), eldap:close( Handle ).
Write the same code in Erlang as shown below in C#.
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] hidatoMoves = {(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)}; priva...
-module( solve_hidato_puzzle ). -export( [create/2, solve/1, task/0] ). -compile({no_auto_import,[max/2]}). create( Grid_list, Number_list ) -> Squares = lists:flatten( [create_column(X, Y) || {X, Y} <- Grid_list] ), lists:foldl( fun store/2, dict:from_list(Squares), Number_list ). print( Grid_list ) when ...
Produce a functionally identical Erlang code for the snippet given in C#.
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] hidatoMoves = {(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)}; priva...
-module( solve_hidato_puzzle ). -export( [create/2, solve/1, task/0] ). -compile({no_auto_import,[max/2]}). create( Grid_list, Number_list ) -> Squares = lists:flatten( [create_column(X, Y) || {X, Y} <- Grid_list] ), lists:foldl( fun store/2, dict:from_list(Squares), Number_list ). print( Grid_list ) when ...
Produce a language-to-language conversion: from C# to Erlang, same semantics.
XmlReader XReader; XReader = XmlReader.Create(new StringReader("<inventory title=... </inventory>")); XReader = XmlReader.Create("xmlfile.xml"); IXPathNavigable XDocument = new XPathDocument(XReader); XPathNavigator Nav = XDocument.CreateNavigator(); Nav = Nav.SelectSingleNode(" if(Nav.MoveToFirst()) { ...
-module(xml_xpath). -include_lib("xmerl/include/xmerl.hrl"). -export([main/0]). main() -> XMLDocument = "<inventory title=\"OmniCorp Store #45x10^3\"> <section name=\"health\"> <item upc=\"123456789\" stock=\"12\"> <name>Invisibility Cream</name> <price>14.50</pric...
Translate this program into Erlang but keep the logic exactly as in C#.
using System; using System.Collections.Generic; using System.IO; namespace IBeforeE { class Program { static bool IsOppPlausibleWord(string word) { if (!word.Contains("c") && word.Contains("ei")) { return true; } if (word.Contains("cie")) { ...
-module(cei). -export([plaus/0,count/3]). plaus() -> ...
Generate a Erlang translation of this C# snippet without changing its computational steps.
using System; using System.Collections.Generic; using System.IO; namespace IBeforeE { class Program { static bool IsOppPlausibleWord(string word) { if (!word.Contains("c") && word.Contains("ei")) { return true; } if (word.Contains("cie")) { ...
-module(cei). -export([plaus/0,count/3]). plaus() -> ...
Port the following code from C# to Erlang with equivalent syntax and logic.
using System; using System.Collections.Generic; using System.Linq; namespace HashJoin { public class AgeName { public AgeName(byte age, string name) { Age = age; Name = name; } public byte Age { get; private set; } public string Name { get; privat...
-module( hash_join ). -export( [task/0] ). task() -> Table_1 = [{27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"}, {28, "Alan"}], Table_2 = [{"Jonah", "Whales"}, {"Jonah", "Spiders"}, {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"}], Dict = lists:foldl( fun dict_append/2, dict:new(), ...
Write a version of this C# function in Erlang with identical behavior.
using System; public delegate Church Church(Church f); public static class ChurchNumeral { public static readonly Church ChurchZero = _ => x => x; public static readonly Church ChurchOne = f => f; public static Church Successor(this Church n) => f => x => f(n(f)(x)); public static Church Add(this ...
-module(church). -export([main/1, zero/1]). zero(_) -> fun(F) -> F end. succ(N) -> fun(F) -> fun(X) -> F((N(F))(X)) end end. add(N,M) -> fun(F) -> fun(X) -> (M(F))((N(F))(X)) end end. mult(N,M) -> fun(F) -> fun(X) -> (M(N(F)))(X) end end. power(B,E) -> E(B). to_int(C) -> CountUp = fun(I) -> I + 1 end, (C(Coun...
Generate an equivalent Erlang version of this C# code.
using System; public delegate Church Church(Church f); public static class ChurchNumeral { public static readonly Church ChurchZero = _ => x => x; public static readonly Church ChurchOne = f => f; public static Church Successor(this Church n) => f => x => f(n(f)(x)); public static Church Add(this ...
-module(church). -export([main/1, zero/1]). zero(_) -> fun(F) -> F end. succ(N) -> fun(F) -> fun(X) -> F((N(F))(X)) end end. add(N,M) -> fun(F) -> fun(X) -> (M(F))((N(F))(X)) end end. mult(N,M) -> fun(F) -> fun(X) -> (M(N(F)))(X) end end. power(B,E) -> E(B). to_int(C) -> CountUp = fun(I) -> I + 1 end, (C(Coun...
Ensure the translated Erlang code behaves exactly like the original C# snippet.
using System; using System.Numerics; class AgmPie { static BigInteger IntSqRoot(BigInteger valu, BigInteger guess) { BigInteger term; do { term = valu / guess; if (BigInteger.Abs(term - guess) <= 1) break; guess += term; guess >>= 1; } while (true); return guess; } ...
-module(pi). -export([agmPi/1, agmPiBody/5]). agmPi(Loops) -> A = 1, B = 1/math:sqrt(2), J = 1, Running_divisor = 0.25, A_n_plus_one = 0.5*(A+B), B_n_plus_one = math:sqrt(A*B), Step_difference = A_n_plus_one - A, agmPiBody(Loops-1, Running_divisor-(math:pow(Step_difference, 2)*J), ...
Can you help me rewrite this code in Erlang instead of C#, keeping it the same logically?
using System; using System.Numerics; class AgmPie { static BigInteger IntSqRoot(BigInteger valu, BigInteger guess) { BigInteger term; do { term = valu / guess; if (BigInteger.Abs(term - guess) <= 1) break; guess += term; guess >>= 1; } while (true); return guess; } ...
-module(pi). -export([agmPi/1, agmPiBody/5]). agmPi(Loops) -> A = 1, B = 1/math:sqrt(2), J = 1, Running_divisor = 0.25, A_n_plus_one = 0.5*(A+B), B_n_plus_one = math:sqrt(A*B), Step_difference = A_n_plus_one - A, agmPiBody(Loops-1, Running_divisor-(math:pow(Step_difference, 2)*J), ...
Can you help me rewrite this code in Erlang instead of C#, keeping it the same logically?
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; namespace EgyptianFractions { class Program { class Rational : IComparable<Rational>, IComparable<int> { public BigInteger Num { get; } public B...
-module(egypt). -import(lists, [reverse/1, seq/2]). -export([frac/2, show/2, rosetta/0]). rosetta() -> Fractions = [{N, D, second(frac(N, D))} || N <- seq(2,99), D <- seq(N+1, 99)], {Longest, A1, B1} = findmax(fun length/1, Fractions), io:format("~b/~b has ~b terms.~n", [A1, B1, Longest]), {Largest, A...
Ensure the translated Erlang code behaves exactly like the original C# snippet.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using static System.Console; using static System.Linq.Enumerable; namespace WorldCupGroupStage { public static class WorldCupGroupStage { static int[][] _histogram; static WorldCupGroupStage() { ...
-module(world_cup). -export([group_stage/0]). group_stage() -> Results = [[3,0],[1,1],[0,3]], Teams = [1,2,3,4], Matches = combos(2,Teams), AllResults = combinations(Matches,Results), AllPoints = [lists:flatten([lists:zip(L1,L2) || {L1,L2} <- L]) || L <- AllResults], TotalPoints = [ [ {T,lists:sum([Poi...
Convert this C# block to Erlang, preserving its control flow and logic.
using System; using BI = System.Numerics.BigInteger; using static System.Console; class Program { static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) { q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }   static string dump(int digs, bool show = false) {...
-mode(compile). fac(N) -> fac(N, 1). fac(N, A) when N < 2 -> A; fac(N, A) -> fac(N - 1, N*A). pow(_, N) when N < 0 -> pow_domain_error; pow(2, N) -> 1 bsl N; pow(A, N) -> ipow(A, N). ipow(_, 0) -> 1; ipow(A, 1) -> A; ipow(A, 2) -> A*A; ipow(A, N) -> case N band 1 of 0 -> X = ipow(A, N bsr 1), X*X; ...
Produce a language-to-language conversion: from C# to Erlang, same semantics.
using System; using BI = System.Numerics.BigInteger; using static System.Console; class Program { static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) { q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }   static string dump(int digs, bool show = false) {...
-mode(compile). fac(N) -> fac(N, 1). fac(N, A) when N < 2 -> A; fac(N, A) -> fac(N - 1, N*A). pow(_, N) when N < 0 -> pow_domain_error; pow(2, N) -> 1 bsl N; pow(A, N) -> ipow(A, N). ipow(_, 0) -> 1; ipow(A, 1) -> A; ipow(A, 2) -> A*A; ipow(A, N) -> case N band 1 of 0 -> X = ipow(A, N bsr 1), X*X; ...
Please provide an equivalent version of this C# code in Erlang.
using System; class Program { const long Lm = (long)1e18; const string Fm = "D18"; struct LI { public long lo, ml, mh, hi, tp; } static void inc(ref LI d, LI s) { if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; } if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; } if ((d....
-mode(compile). main(_) -> ets:new(pN, [set, named_table, protected]), io:format("~w~n", [p(6666)]). p(0) -> 1; p(N) -> case ets:lookup(pN, N) of [{N, Pn}] -> Pn; [] -> Terms = [p(N - G) || G <- gpentagonals(N)], Pn = sum_partitions(Terms), ets:insert(pN...
Please provide an equivalent version of this Python code in Swift.
def is_repeated(text): 'check if the first part of the string is repeated throughout the string' for x in range(len(text)//2, 0, -1): if text.startswith(text[x:]): return x return 0 matchstr = for line in matchstr.split(): ln = is_repeated(line) print('%r has a repetition length of %i i.e....
import Foundation func repString(_ input: String) -> [String] { return (1..<(1 + input.count / 2)).compactMap({x -> String? in let i = input.index(input.startIndex, offsetBy: x) return input.hasPrefix(input[i...]) ? String(input.prefix(x)) : nil }) } let testCases = """ 1001110011 ...
Maintain the same structure and functionality when rewriting this code in Swift.
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def sequence(max_n=None): previous = 0 n = 0 while True: n += 1 ii = previous ...
func divisorCount(number: Int) -> Int { var n = number var total = 1 while n % 2 == 0 { total += 1 n /= 2 } var p = 3 while p * p <= n { var count = 1 while n % p == 0 { count += 1 n /= p } total *= count ...
Translate this program into Swift but keep the logic exactly as in Python.
>>> from itertools import product >>> nuggets = set(range(101)) >>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)): nuggets.discard(6*s + 9*n + 20*t) >>> max(nuggets) 43 >>>
func maxNugget(limit: Int) -> Int { var (max, sixes, nines, twenties, i) = (0, 0, 0, 0, 0) mainLoop: while i < limit { sixes = 0 while sixes * 6 < i { if sixes * 6 == i { i += 1 continue mainLoop } nines = 0 while nines * 9 < i { if sixes * 6 + nines * 9 =...
Change the following Python code into Swift without altering its purpose.
from __future__ import division def jaro(s, t): s_len = len(s) t_len = len(t) if s_len == 0 and t_len == 0: return 1 match_distance = (max(s_len, t_len) // 2) - 1 s_matches = [False] * s_len t_matches = [False] * t_len matches = 0 transpositions = 0 for i in ran...
func jaroWinklerMatch(_ s: String, _ t: String) -> Double { let s_len: Int = s.count let t_len: Int = t.count if s_len == 0 && t_len == 0 { return 1.0 } if s_len == 0 || t_len == 0 { return 0.0 } var match_distance: Int = 0 if s_len == 1 && t_len == 1...
Write the same algorithm in Swift as shown in this Python implementation.
def lpd(n): for i in range(n-1,0,-1): if n%i==0: return i return 1 for i in range(1,101): print("{:3}".format(lpd(i)), end=i%10==0 and '\n' or '')
import Foundation func largestProperDivisor(_ n : Int) -> Int? { guard n > 0 else { return nil } if (n & 1) == 0 { return n >> 1 } var p = 3 while p * p <= n { if n % p == 0 { return n / p } p += 2 } return 1 } for n in (1..<101) { ...
Port the following code from Python to Swift with equivalent syntax and logic.
mask64 = (1 << 64) - 1 mask32 = (1 << 32) - 1 const = 0x2545F4914F6CDD1D class Xorshift_star(): def __init__(self, seed=0): self.state = seed & mask64 def seed(self, num): self.state = num & mask64 def next_int(self): "return random int between 0 and 2**32" x =...
import Foundation struct XorshiftStar { private let magic: UInt64 = 0x2545F4914F6CDD1D private var state: UInt64 init(seed: UInt64) { state = seed } mutating func nextInt() -> UInt64 { state ^= state &>> 12 state ^= state &<< 25 state ^= state &>> 27 return (state &* magic) &>> 32 ...
Produce a language-to-language conversion: from Python to Swift, same semantics.
import itertools def riseEqFall(num): height = 0 d1 = num % 10 num //= 10 while num: d2 = num % 10 height += (d1<d2) - (d1>d2) d1 = d2 num //= 10 return height == 0 def sequence(start, fn): num=start-1 while True: num += 1 while...
import Foundation func equalRisesAndFalls(_ n: Int) -> Bool { var total = 0 var previousDigit = -1 var m = n while m > 0 { let digit = m % 10 m /= 10 if previousDigit > digit { total += 1 } else if previousDigit >= 0 && previousDigit < digit { tot...
Generate a Swift translation of this Python snippet without changing its computational steps.
>>> def isSelfDescribing(n): s = str(n) return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s)) >>> [x for x in range(4000000) if isSelfDescribing(x)] [1210, 2020, 21200, 3211000] >>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)] [(1210, True), (2020, True...
import Foundation extension BinaryInteger { @inlinable public var isSelfDescribing: Bool { let stringChars = String(self).map({ String($0) }) let counts = stringChars.reduce(into: [Int: Int](), {res, char in res[Int(char), default: 0] += 1}) for (i, n) in stringChars.enumerated() where counts[i, defau...
Generate an equivalent Swift version of this Python code.
with open('unixdict.txt', 'rt') as f: for line in f.readlines(): if not any(c in 'aiou' for c in line) and sum(c=='e' for c in line)>3: print(line.strip())
import Foundation func e3(_ word: String) -> Bool { var ecount = 0 for ch in word { switch (ch) { case "a", "A", "i", "I", "o", "O", "u", "U": return false case "e", "E": ecount += 1 default: break } } return ecount > 3 } do {...
Produce a language-to-language conversion: from Python to Swift, same semantics.
def isLongAlternator(s): def p(a, b): return isVowel(a) != isVowel(b) return 9 < len(s) and all(map(p, s, s[1:])) def isVowel(c): return c in 'aeiou' def main(): matches = [ x for x in readFile('unixdict.txt').splitlines() if isLongAlternator(x) ] ...
import Foundation func isVowel(_ char: Character) -> Bool { switch (char) { case "a", "A", "e", "E", "i", "I", "o", "O", "u", "U": return true default: return false } } func alternatingVowelsAndConsonants(word: String) -> Bool { return zip(word, word.dropFirst()).allSatisfy{isVowel...
Produce a language-to-language conversion: from Python to Swift, same semantics.
from math import sqrt, cos, exp DEG = 0.017453292519943295769236907684886127134 RE = 6371000 dd = 0.001 FIN = 10000000 def rho(a): return exp(-a / 8500.0) def height(a, z, d): return sqrt((RE + a)**2 + d**2 - 2 * d * (RE + a) * cos((180 - z) * DEG...
import Foundation extension Double { var radians: Double { self * .pi / 180 } } func columnDensity(_ a: Double, _ z: Double) -> Double { func rho(_ a: Double) -> Double { exp(-a / 8500) } func height(_ d: Double) -> Double { let aa = 6_371_000 + a let hh = aa * aa + d * d - 2 * d * aa * cos((180 ...
Can you help me rewrite this code in Swift instead of Python, keeping it the same logically?
import urllib.request as request with request.urlopen("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") as f: a = f.read().decode("ASCII").split() for s in a: if len(s) > 11 and "the" in s: print(s)
import Foundation let minLength = 12 let substring = "the" do { try String(contentsOfFile: "unixdict.txt", encoding: String.Encoding.ascii) .components(separatedBy: "\n") .filter{$0.count >= minLength && $0.contains(substring)} .enumerated() .forEach{print(String(format: "%2d. %@",...
Rewrite this program in Swift while keeping its functionality equivalent to the Python version.
var num = 12 var pointer = ptr(num) print pointer @unsafe pointer.addr = 0xFFFE
class MyClass { } func printAddress<T>(of pointer: UnsafePointer<T>) { print(pointer) } func test() { var x = 42 var y = 3.14 var z = "foo" var obj = MyClass() withUnsafePointer(to: &x) { print($0) } withUnsafePointer(to: &y) { print($0) } withUnsafePointer(to: &z) { print(...
Convert the following code from Python to Swift, ensuring the logic remains intact.
import urllib.request urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt") dictionary = open("unixdict.txt","r") wordList = dictionary.read().split('\n') dictionary.close() for word in wordList: if len(word)>5 and word[:3].lower()==word[-3:].lower(): print(wo...
import Foundation do { try String(contentsOfFile: "unixdict.txt", encoding: String.Encoding.ascii) .components(separatedBy: "\n") .filter{$0.count > 5 && $0.prefix(3) == $0.suffix(3)} .enumerated() .forEach{print("\($0.0 + 1). \($0.1)")} } catch { print(error.localizedDescriptio...
Keep all operations the same but rewrite the snippet in Swift.
import urllib.request from collections import Counter urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt") dictionary = open("unixdict.txt","r") wordList = dictionary.read().split('\n') dictionary.close() for word in wordList: if len(word)>10: frequency = Co...
import Foundation func containsAllVowelsOnce(_ word: String) -> Bool { var vowels = 0 for ch in word { var bit = 0 switch (ch) { case "a", "A": bit = 1 case "e", "E": bit = 2 case "i", "I": bit = 4 case "o", "O": bi...
Port the following code from Python to Swift with equivalent syntax and logic.
import urllib.request urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt") dictionary = open("unixdict.txt","r") wordList = dictionary.read().split('\n') dictionary.close() oddWordSet = set({}) for word in wordList: if len(word)>=9 and word[::2] in wordList: ...
import Foundation let minLength = 5 func loadDictionary(_ path: String) throws -> Set<String> { let contents = try String(contentsOfFile: path, encoding: String.Encoding.ascii) return Set<String>(contents.components(separatedBy: "\n").filter{$0.count >= minLength}) } func pad(string: String, width: Int) -> S...
Generate an equivalent Swift version of this Python code.
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 Foundation let dxs = [ -0.533, 0.270, 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.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047, -0.095, 0.695, 0.340, -...
Change the programming language of this snippet from Python to Swift without modifying what it does.
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 Foundation let dxs = [ -0.533, 0.270, 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.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047, -0.095, 0.695, 0.340, -...
Translate the given Python code snippet into Swift without altering its behavior.
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 Foundation var cave: [Int:[Int]] = [ 1: [2, 3, 4], 2: [1, 5, 6], 3: [1, 7, 8], 4: [1, 9, 10], 5: [2, 9, 11], 6: [2, 7, 12], 7: [3, 6, 13], 8: [3, 10, 14], 9: [4, 5, 15], 10: [4, 8, 16], 11: [5, 12, 17], 12: [6, 11, 18], 13: [7, 14, 18], 14: [8, 13, 19], ...
Convert this Python block to Swift, preserving its control flow and logic.
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 Foundation public class MD5 { private let s: [UInt32] = [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, ...
Change the following Python code into Swift without altering its purpose.
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) ...
var historyOfHistory = [Int]() var history:Int = 0 { willSet { historyOfHistory.append(history) } } history = 2 history = 3 history = 4 println(historyOfHistory)
Please provide an equivalent version of this Python code in Swift.
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): ...
import Foundation func jacobi(a: Int, n: Int) -> Int { var a = a % n var n = n var res = 1 while a != 0 { while a & 1 == 0 { a >>= 1 if n % 8 == 3 || n % 8 == 5 { res = -res } } (a, n) = (n, a) if a % 4 == 3 && n % 4 == 3 { res = -res } a %= n ...
Can you help me rewrite this code in Swift 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): ...
import Foundation func jacobi(a: Int, n: Int) -> Int { var a = a % n var n = n var res = 1 while a != 0 { while a & 1 == 0 { a >>= 1 if n % 8 == 3 || n % 8 == 5 { res = -res } } (a, n) = (n, a) if a % 4 == 3 && n % 4 == 3 { res = -res } a %= n ...
Change the following Python code into Swift without altering its purpose.
>>> 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, ...
extension Array { public mutating func satalloShuffle() { for i in stride(from: index(before: endIndex), through: 1, by: -1) { swapAt(i, .random(in: 0..<i)) } } public func satalloShuffled() -> [Element] { var arr = Array(self) arr.satalloShuffle() return arr } } let testCases = [ ...
Produce a language-to-language conversion: from Python to Swift, same semantics.
>>> 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, ...
extension Array { public mutating func satalloShuffle() { for i in stride(from: index(before: endIndex), through: 1, by: -1) { swapAt(i, .random(in: 0..<i)) } } public func satalloShuffled() -> [Element] { var arr = Array(self) arr.satalloShuffle() return arr } } let testCases = [ ...
Change the programming language of this snippet from Python to Swift 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...
struct RecursiveFunc<F> { let o : RecursiveFunc<F> -> F } func Y<A, B>(f: (A -> B) -> A -> B) -> A -> B { let r = RecursiveFunc<A -> B> { w in f { w.o(w)($0) } } return r.o(r) } let fac = Y { (f: Int -> Int) in { $0 <= 1 ? 1 : $0 * f($0-1) } } let fib = Y { (f: Int -> Int) in { $0 <= 2 ? 1 : f($0-1)+f($0-2)...
Can you help me rewrite this code in Swift instead of Python, keeping it the same logically?
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...
var fact = Array(repeating: 0, count: 12) fact[0] = 1 for n in 1..<12 { fact[n] = fact[n - 1] * n } for b in 9...12 { print("The factorions for base \(b) are:") for i in 1..<1500000 { var sum = 0 var j = i while j > 0 { sum += fact[j % b] j /= b } if sum == i { print("\...
Transform the following Python implementation into Swift, maintaining the same output and logic.
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...
var fact = Array(repeating: 0, count: 12) fact[0] = 1 for n in 1..<12 { fact[n] = fact[n - 1] * n } for b in 9...12 { print("The factorions for base \(b) are:") for i in 1..<1500000 { var sum = 0 var j = i while j > 0 { sum += fact[j % b] j /= b } if sum == i { print("\...
Transform the following Python implementation into Swift, maintaining the same output and logic.
import sys print " ".join(sys.argv[1:])
#!/usr/bin/swift import Foundation print(Process.arguments[1..<Process.arguments.count].joinWithSeparator(" "))
Translate this program into Swift but keep the logic exactly as in Python.
import sys print " ".join(sys.argv[1:])
#!/usr/bin/swift import Foundation print(Process.arguments[1..<Process.arguments.count].joinWithSeparator(" "))
Translate this program into Swift but keep the logic exactly as in Python.
def factorize(n): assert(isinstance(n, int)) if n < 0: n = -n if n < 2: return k = 0 while 0 == n%2: k += 1 n //= 2 if 0 < k: yield (2,k) p = 3 while p*p <= n: k = 0 while 0 == n%p: k += 1 n //...
import Foundation func divisorCount(number: Int) -> Int { var n = number var total = 1 while (n & 1) == 0 { total += 1 n >>= 1 } var p = 3 while p * p <= n { var count = 1 while n % p == 0 { count += 1 n /= p } t...
Preserve the algorithm and functionality while converting the code from Python to Swift.
def factorize(n): assert(isinstance(n, int)) if n < 0: n = -n if n < 2: return k = 0 while 0 == n%2: k += 1 n //= 2 if 0 < k: yield (2,k) p = 3 while p*p <= n: k = 0 while 0 == n%p: k += 1 n //...
import Foundation func divisorCount(number: Int) -> Int { var n = number var total = 1 while (n & 1) == 0 { total += 1 n >>= 1 } var p = 3 while p * p <= n { var count = 1 while n % p == 0 { count += 1 n /= p } t...
Change the programming language of this snippet from Python to Swift without modifying what it does.
def mertens(count): m = [None, 1] for n in range(2, count+1): m.append(1) for k in range(2, n+1): m[n] -= m[n//k] return m ms = mertens(1000) print("The first 99 Mertens numbers are:") print(" ", end=' ') col = 1 for n in ms[1:100]: print("{:2d}".format(n), end='...
import Foundation func mertensNumbers(max: Int) -> [Int] { var mertens = Array(repeating: 1, count: max + 1) for n in 2...max { for k in 2...n { mertens[n] -= mertens[n / k] } } return mertens } let max = 1000 let mertens = mertensNumbers(max: max) let count = 200 let colu...
Change the following Python code into Swift without altering its purpose.
import random class Card(object): suits = ("Clubs","Hearts","Spades","Diamonds") pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace") def __init__(self, pip,suit): self.pip=pip self.suit=suit def __str__(self): return "%s %s"%(self.pip,self.suit) class De...
struct Card: CustomStringConvertible { enum Suit: String, CaseIterable, CustomStringConvertible { case clubs = "♣️" case diamonds = "♦️" case hearts = "♥️" case spades = "♠️" var description: String { rawValue } } let suit: Suit let value: Int var description: String { let valueAsString: String ...
Can you help me rewrite this code in Swift instead of Python, keeping it the same logically?
from math import gcd from functools import lru_cache from itertools import islice, count @lru_cache(maxsize=None) def φ(n): return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1) def perfect_totient(): for n0 in count(1): parts, n = 0, n0 while n != 1: n = φ(n) parts...
public func totient(n: Int) -> Int { var n = n var i = 2 var tot = n while i * i <= n { if n % i == 0 { while n % i == 0 { n /= i } tot -= tot / i } if i == 2 { i = 1 } i += 2 } if n > 1 { tot -= tot / n } return tot } public struct PerfectT...
Rewrite this program in Swift while keeping its functionality equivalent to the Python version.
from math import gcd from functools import lru_cache from itertools import islice, count @lru_cache(maxsize=None) def φ(n): return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1) def perfect_totient(): for n0 in count(1): parts, n = 0, n0 while n != 1: n = φ(n) parts...
public func totient(n: Int) -> Int { var n = n var i = 2 var tot = n while i * i <= n { if n % i == 0 { while n % i == 0 { n /= i } tot -= tot / i } if i == 2 { i = 1 } i += 2 } if n > 1 { tot -= tot / n } return tot } public struct PerfectT...
Convert the following code from Python to Swift, ensuring the logic remains intact.
from math import (comb, factorial) def lah(n, k): if k == 1: return factorial(n) if k == n: return 1 if k > n: return 0 if k < 1 or n < 1: return 0 return comb(n, k) * factorial(n - 1) // factorial(k - 1) def main(): print("Unsigned Lah numbe...
import BigInt import Foundation @inlinable public func factorial<T: BinaryInteger>(_ n: T) -> T { guard n != 0 else { return 1 } return stride(from: n, to: 0, by: -1).reduce(1, *) } @inlinable public func lah<T: BinaryInteger>(n: T, k: T) -> T { if k == 1 { return factorial(n) } else if k == n { ...
Translate the given Python code snippet into Swift without altering its behavior.
from math import (comb, factorial) def lah(n, k): if k == 1: return factorial(n) if k == n: return 1 if k > n: return 0 if k < 1 or n < 1: return 0 return comb(n, k) * factorial(n - 1) // factorial(k - 1) def main(): print("Unsigned Lah numbe...
import BigInt import Foundation @inlinable public func factorial<T: BinaryInteger>(_ n: T) -> T { guard n != 0 else { return 1 } return stride(from: n, to: 0, by: -1).reduce(1, *) } @inlinable public func lah<T: BinaryInteger>(n: T, k: T) -> T { if k == 1 { return factorial(n) } else if k == n { ...