Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Maintain the same structure and functionality when rewriting this code in Swift. | ch32 = "0123456789bcdefghjkmnpqrstuvwxyz"
bool2ch = {f"{i:05b}": ch for i, ch in enumerate(ch32)}
ch2bool = {v : k for k, v in bool2ch.items()}
def bisect(val, mn, mx, bits):
mid = (mn + mx) / 2
if val < mid:
bits <<= 1
mx = mid
else:
... | let base32 = "0123456789bcdefghjkmnpqrstuvwxyz"
extension String {
subscript(i: Int) -> String {
String(self[index(startIndex, offsetBy: i)])
}
}
struct Coordinate {
var latitude: Double
var longitude: Double
func toString() -> String {
var latitudeHemisphere = ""
var longitudeHemisphere = ""
... |
Generate an equivalent Swift version of this Python code. | from sympy import isprime, divisors
def is_super_Poulet(n):
return not isprime(n) and 2**(n - 1) % n == 1 and all((2**d - 2) % d == 0 for d in divisors(n))
spoulets = [n for n in range(1, 1_100_000) if is_super_Poulet(n)]
print('The first 20 super-Poulet numbers are:', spoulets[:20])
idx1m, val1m = next((i, v)... | func divisors(number: UInt32) -> [UInt32] {
var result: [UInt32] = [1]
var power: UInt32 = 2
var n = number
while (n & 1) == 0 {
result.append(power)
power <<= 1
n >>= 1
}
var p: UInt32 = 3
while p * p <= n {
let size = result.count
power = p
w... |
Write the same code in Swift as shown below in Python. |
from functools import reduce
from operator import add
def wordleScore(target, guess):
return mapAccumL(amber)(
*first(charCounts)(
mapAccumL(green)(
[], zip(target, guess)
)
)
)[1]
def green(residue, tg):
t, g = tg
return (residue... | enum Colour : CustomStringConvertible {
case grey
case yellow
case green
var description : String {
switch self {
case .grey: return "grey"
case .yellow: return "yellow"
case .green: return "green"
}
}
}
func wordle(answer: String, guess: String) -> [Colour]? {
guard answer.count =... |
Change the following Python code into Swift without altering its purpose. | from functools import lru_cache
DIVS = {2, 3}
SUBS = {1}
class Minrec():
"Recursive, memoised minimised steps to 1"
def __init__(self, divs=DIVS, subs=SUBS):
self.divs, self.subs = divs, subs
@lru_cache(maxsize=None)
def _minrec(self, n):
"Recursive, memoised"
if n == 1:
... | func minToOne(divs: [Int], subs: [Int], upTo n: Int) -> ([Int], [[String]]) {
var table = Array(repeating: n + 2, count: n + 1)
var how = Array(repeating: [""], count: n + 2)
table[1] = 0
how[1] = ["="]
for t in 1..<n {
let thisPlus1 = table[t] + 1
for div in divs {
let dt = div * t
if... |
Rewrite the snippet below in Swift so it works the same as the original Python code. | from itertools import zip_longest
fc2 =
NAME, WT, COV = 0, 1, 2
def right_type(txt):
try:
return float(txt)
except ValueError:
return txt
def commas_to_list(the_list, lines, start_indent=0):
for n, line in lines:
indent = 0
while line.startswith(' ' * (4 * indent))... | import Foundation
extension String {
func paddedLeft(totalLen: Int) -> String {
let needed = totalLen - count
guard needed > 0 else {
return self
}
return String(repeating: " ", count: needed) + self
}
}
class FCNode {
let name: String
let weight: Int
var coverage: Double {
didS... |
Rewrite this program in Swift while keeping its functionality equivalent to the Python version. | def main():
resources = int(input("Cantidad de recursos: "))
processes = int(input("Cantidad de procesos: "))
max_resources = [int(i) for i in input("Recursos máximos: ").split()]
print("\n-- recursos asignados para cada proceso --")
currently_allocated = [[int(i) for i in input(f"proceso {j + 1}:... | import Foundation
print("Enter the number of resources: ", terminator: "")
guard let resources = Int(readLine(strippingNewline: true)!) else {
fatalError()
}
print("Enter the number of processes: ", terminator: "")
guard let processes = Int(readLine(strippingNewline: true)!) else {
fatalError()
}
var running =... |
Convert the following code from Python to Swift, ensuring the logic remains intact. |
def is_idoneal(num):
for a in range(1, num):
for b in range(a + 1, num):
if a * b + a + b > num:
break
for c in range(b + 1, num):
sum3 = a * b + b * c + a * c
if sum3 == num:
return False
if ... | import Foundation
func isIdoneal(_ n: Int) -> Bool {
for a in 1..<n {
for b in a + 1..<n {
if a * b + a + b > n {
break
}
for c in b + 1..<n {
let sum = a * b + b * c + a * c
if sum == n {
return false
... |
Write the same algorithm in Swift as shown in this Python implementation. | from itertools import count, islice
import numpy as np
from numpy import sin, cos, pi
ANGDIV = 12
ANG = 2*pi/ANGDIV
def draw_all(sols):
import matplotlib.pyplot as plt
def draw_track(ax, s):
turn, xend, yend = 0, [0], [0]
for d in s:
x0, y0 = xend[-1], yend[-1]
a = t... | enum Track: Int, Hashable {
case left = -1, straight, right
}
extension Track: Comparable {
static func < (lhs: Track, rhs: Track) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
func < (lhs: [Track], rhs: [Track]) -> Bool {
for (l, r) in zip(lhs, rhs) where l != r {
return l < r
}
return false
... |
Generate a Swift translation of this Python snippet without changing its computational steps. |
from __future__ import annotations
from itertools import chain
from typing import List
from typing import NamedTuple
from typing import Optional
class Shape(NamedTuple):
rows: int
cols: int
class Matrix(List):
@classmethod
def block(cls, blocks) -> Matrix:
m = Matrix()
... |
func strassenMultiply(matrix1: Matrix, matrix2: Matrix) -> Matrix {
precondition(matrix1.columns == matrix2.columns,
"Two matrices can only be matrix multiplied if one has dimensions mxn & the other has dimensions nxp where m, n, p are in R")
let maxColumns = Swift.max(matrix1.rows, matrix1.... |
Produce a functionally identical OCaml code for the snippet given in C++. | #include <windows.h>
#include <ctime>
#include <iostream>
#include <string>
const int WID = 60, HEI = 30, MAX_LEN = 600;
enum DIR { NORTH, EAST, SOUTH, WEST };
class snake {
public:
snake() {
console = GetStdHandle( STD_OUTPUT_HANDLE ); SetConsoleTitle( "Snake" );
COORD coord = { WID + 1, HEI + 2... |
open Sdl
let width, height = (640, 480)
type pos = int * int
type game_state = {
pos_snake: pos;
seg_snake: pos list;
dir_snake: [`left | `right | `up | `down];
pos_fruit: pos;
sleep_time: int;
game_over: bool;
}
let red = (255, 0, 0)
let blue = (0, 0, 255)
let green = (0, 255, 0)
let black = (0, 0,... |
Convert this C++ block to OCaml, preserving its control flow and logic. | #include <windows.h>
#include <string>
#include <math.h>
using namespace std;
const float PI = 3.1415926536f;
class myBitmap
{
public:
myBitmap() : pen( NULL ) {}
~myBitmap()
{
DeleteObject( pen );
DeleteDC( hdc );
DeleteObject( bmp );
}
bool create( int w, int h )
{
BITMAPINFO bi;
v... | #directory "+cairo"
#load "bigarray.cma"
#load "cairo.cma"
let img_name = "/tmp/fractree.png"
let width = 480
let height = 640
let level = 9
let line_width = 4.0
let color = (1.0, 0.5, 0.0)
let pi = 4.0 *. atan 1.0
let angle_split = pi *. 0.12
let angle_rand = pi *. 0.12
let () =
Random.self_init();
let sur... |
Can you help me rewrite this code in OCaml instead of C++, keeping it the same logically? | #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
enum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C };
enum indexes { PLAYER, COMPUTER, DRAW };
class stats
{
public:
stats() : _draw( 0 )
{
ZeroMemory( _moves, sizeof( _moves ) );
ZeroMemory( _win, sizeof( _win... | let pf = Printf.printf ;;
let looses a b = match a, b with
`R, `P -> true
| `P, `S -> true
| `S, `R -> true
| _, _ -> false ;;
let rec get_move () =
pf "[R]ock, [P]aper, [S]cisors [Q]uit? " ;
match String.uppercase (read_line ()) with
"P" -> `P
| "S" -> `S
| "R" -> `R
|... |
Convert this C++ block to OCaml, preserving its control flow and logic. |
#include <cln/integer.h>
#include <cln/integer_io.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <sstream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <map>
using namespace cln ;
class NextNum {
public :
NextNum ( cl_I & a , cl_I & b ) : first( a ) , s... | open Num
let fib =
let rec fib_aux f0 f1 = function
| 0 -> f0
| 1 -> f1
| n -> fib_aux f1 (f1 +/ f0) (n - 1)
in
fib_aux (num_of_int 0) (num_of_int 1) ;;
let create_fibo_string = function n -> string_of_num (fib n) ;;
let rec range i j = if i > j then [] else i :: (range (i + 1) j)
let n_max = 1000 ... |
Produce a functionally identical OCaml code for the snippet given in C++. |
#include <cln/integer.h>
#include <cln/integer_io.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <sstream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <map>
using namespace cln ;
class NextNum {
public :
NextNum ( cl_I & a , cl_I & b ) : first( a ) , s... | open Num
let fib =
let rec fib_aux f0 f1 = function
| 0 -> f0
| 1 -> f1
| n -> fib_aux f1 (f1 +/ f0) (n - 1)
in
fib_aux (num_of_int 0) (num_of_int 1) ;;
let create_fibo_string = function n -> string_of_num (fib n) ;;
let rec range i j = if i > j then [] else i :: (range (i + 1) j)
let n_max = 1000 ... |
Produce a language-to-language conversion: from C++ to OCaml, same semantics. | #include <iostream>
#include <iomanip>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/math/constants/constants.hpp>
typedef boost::multiprecision::cpp_dec_float_50 decfloat;
int main()
{
const decfloat ln_two = boost::math::constants::ln_two<decfloat>();
decfloat numerator = 1, denominator =... | local
fun log (n, k, last = sum, sum) = sum
| (n, k, last, sum) = log (n, k + 1, sum, sum + ( 1 / (k * n ^ k)))
| n = log (n, 1, 1, 0);
val ln2 = log 2
in
fun hickerson n = (fold (opt *,1) ` iota n) / (2 * ln2 ^ (n+1));
... |
Write a version of this C++ function in OCaml with identical behavior. | #include <iostream>
#include <iomanip>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/math/constants/constants.hpp>
typedef boost::multiprecision::cpp_dec_float_50 decfloat;
int main()
{
const decfloat ln_two = boost::math::constants::ln_two<decfloat>();
decfloat numerator = 1, denominator =... | local
fun log (n, k, last = sum, sum) = sum
| (n, k, last, sum) = log (n, k + 1, sum, sum + ( 1 / (k * n ^ k)))
| n = log (n, 1, 1, 0);
val ln2 = log 2
in
fun hickerson n = (fold (opt *,1) ` iota n) / (2 * ln2 ^ (n+1));
... |
Ensure the translated OCaml code behaves exactly like the original C++ snippet. | #include "stdafx.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string/case_conv.hpp>
using namespace std;
using namespace boost;
typedef boost::tokenizer<boost::char_separator<char> > Tokenizer;
static const char_separator<char> s... | #use "topfind"
#require "inifiles"
open Inifiles
let print_field ini (label, field) =
try
let v = ini#getval "params" field in
Printf.printf "%s: %s\n" label v
with Invalid_element _ ->
Printf.printf "%s: not defined\n" label
let () =
let ini = new inifile "./conf.ini" in
let lst = [
"Full nam... |
Translate the given C++ code snippet into OCaml without altering its behavior. | #include <iomanip>
#include <iostream>
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 false;
p += 2;
... | let rec digit_sum n =
if n < 10 then n else n mod 10 + digit_sum (n / 10)
let is_prime n =
let rec test x =
let q = n / x in x > q || x * q <> n && n mod (x + 2) <> 0 && test (x + 6)
in if n < 5 then n lor 1 = 3 else n land 1 <> 0 && n mod 3 <> 0 && test 5
let is_additive_prime n =
is_prime n && is_prime ... |
Translate the given C++ code snippet into OCaml without altering its behavior. | #include <iostream>
#include <string>
using namespace std;
int main() {
string dog = "Benjamin", Dog = "Samba", DOG = "Bernie";
cout << "The three dogs are named " << dog << ", " << Dog << ", and " << DOG << endl;
}
| let () =
let dog = "Benjamin" in
let dOG = "Samba" in
let dOg = "Bernie" in
Printf.printf "The three dogs are named %s, %s and %s.\n" dog dOG dOg
|
Rewrite the snippet below in OCaml so it works the same as the original C++ code. | #include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
const char* command_table =
"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy "
"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find "
"NFind NF... | let cmds = "\
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase ... |
Maintain the same structure and functionality when rewriting this code in OCaml. | #include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
const char* command_table =
"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy "
"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find "
"NFind NF... | let cmds = "\
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase ... |
Port the following code from C++ to OCaml with equivalent syntax and logic. | #include <iostream>
#include <time.h>
using namespace std;
class stooge
{
public:
void sort( int* arr, int start, int end )
{
if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] );
int n = end - start; if( n > 2 )
{
n /= 3; sort( arr, start, end - n );
sort( arr, start + n, en... | let swap ar i j =
let tmp = ar.(i) in
ar.(i) <- ar.(j);
ar.(j) <- tmp
let stoogesort ar =
let rec aux i j =
if ar.(j) < ar.(i) then
swap ar i j
else if j - i > 1 then begin
let t = (j - i + 1) / 3 in
aux (i) (j-t);
aux (i+t) (j);
aux (i) (j-t);
end
in
aux 0 (Array.... |
Preserve the algorithm and functionality while converting the code from C++ to OCaml. | #include <time.h>
#include <iostream>
using namespace std;
const int MAX = 126;
class shell
{
public:
shell()
{ _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; }
void sort( int* a, int count )
{
_cnt = count;
for( i... | let shellsort a =
let len = Array.length a in
let incSequence = [| 412771; 165103; 66041; 26417; 10567;
4231; 1693; 673; 269; 107; 43; 17; 7; 3; 1 |] in
Array.iter (fun increment ->
if (increment * 2) <= len then
for i = increment to pred len do
let temp = a.(i) in
... |
Convert this C++ snippet to OCaml and keep its semantics consistent. | #include <string>
#include <fstream>
#include <iostream>
int main( ) {
std::cout << "Which file do you want to look at ?\n" ;
std::string input ;
std::getline( std::cin , input ) ;
std::ifstream infile( input.c_str( ) , std::ios::in ) ;
std::string file( input ) ;
std::cout << "Which file line do you... | let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
let nth_line n filename =
let ic = open_in filename in
let rec aux i =
match input_line_opt ic with
| Some line ->
if i = n then begin
close_in ic;
(line)
end else aux (succ i)
| None ->
... |
Generate an equivalent OCaml version of this C++ code. | #include <string>
#include <fstream>
#include <iostream>
int main( ) {
std::cout << "Which file do you want to look at ?\n" ;
std::string input ;
std::getline( std::cin , input ) ;
std::ifstream infile( input.c_str( ) , std::ios::in ) ;
std::string file( input ) ;
std::cout << "Which file line do you... | let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
let nth_line n filename =
let ic = open_in filename in
let rec aux i =
match input_line_opt ic with
| Some line ->
if i = n then begin
close_in ic;
(line)
end else aux (succ i)
| None ->
... |
Port the following code from C++ to OCaml with equivalent syntax and logic. | #include <QByteArray>
#include <iostream>
int main( ) {
QByteArray text ( "http:
QByteArray encoded( text.toPercentEncoding( ) ) ;
std::cout << encoded.data( ) << '\n' ;
return 0 ;
}
| $ ocaml
# #use "topfind";;
# #require "netstring";;
# Netencoding.Url.encode "http://foo bar/" ;;
- : string = "http%3A%2F%2Ffoo+bar%2F"
|
Keep all operations the same but rewrite the snippet in OCaml. | #include <QByteArray>
#include <iostream>
int main( ) {
QByteArray text ( "http:
QByteArray encoded( text.toPercentEncoding( ) ) ;
std::cout << encoded.data( ) << '\n' ;
return 0 ;
}
| $ ocaml
# #use "topfind";;
# #require "netstring";;
# Netencoding.Url.encode "http://foo bar/" ;;
- : string = "http%3A%2F%2Ffoo+bar%2F"
|
Translate the given C++ code snippet into OCaml without altering its behavior. | #include <vector>
#include <algorithm>
#include <string>
template <class T>
struct sort_table_functor {
typedef bool (*CompFun)(const T &, const T &);
const CompFun ordering;
const int column;
const bool reverse;
sort_table_functor(CompFun o, int c, bool r) :
ordering(o), column(c), reverse(r) { }
boo... | let sort_table ?(ordering = compare) ?(column = 0) ?(reverse = false) table =
let cmp x y = ordering (List.nth x column) (List.nth y column) * (if reverse then -1 else 1) in
List.sort cmp table
|
Can you help me rewrite this code in OCaml instead of C++, keeping it the same logically? | #include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <iomanip>
int main( ) {
std::vector<double> input( 11 ) , results( 11 ) ;
std::cout << "Please enter 11 numbers!\n" ;
for ( int i = 0 ; i < input.size( ) ; i++ )
std::cin >> input[i];
std::transform( input.be... | let f x = sqrt x +. 5.0 *. (x ** 3.0)
let p x = x < 400.0
let () =
print_endline "Please enter 11 Numbers:";
let lst = Array.to_list (Array.init 11 (fun _ -> read_float ())) in
List.iter (fun x ->
let res = f x in
if p res
then Printf.printf "f(%g) = %g\n%!" x res
else Printf.eprintf "f(%g) :: Ov... |
Translate the given C++ code snippet into OCaml without altering its behavior. | #include <iostream>
#include <cctype>
#include <functional>
using namespace std;
bool odd()
{
function<void ()> prev = []{};
while(true) {
int c = cin.get();
if (!isalpha(c)) {
prev();
cout.put(c);
return c != '.';
}
prev = [=] { cout.put(c); prev(); };
}
}
bool even()
{
w... | let is_alpha c =
c >= 'a' && c <= 'z' ||
c >= 'A' && c <= 'Z'
let rec odd () =
let c = input_char stdin in
if is_alpha c
then (let e = odd () in print_char c; e)
else (c)
let rec even () =
let c = input_char stdin in
if is_alpha c
then (print_char c; even ())
else print_char c
let rev_odd_words (... |
Write the same algorithm in OCaml as shown in this C++ implementation. | #include <array>
#include <iostream>
class PCG32 {
private:
const uint64_t N = 6364136223846793005;
uint64_t state = 0x853c49e6748fea9b;
uint64_t inc = 0xda3e39cb94b95bdb;
public:
uint32_t nextInt() {
uint64_t old = state;
state = old * N + inc;
uint32_t shifted = (uint32_t)(((o... | let (>>) = Int64.shift_right_logical
let int32_bound n x =
Int64.(to_int ((mul (logand (of_int32 x) 0xffffffffL) (of_int n)) >> 32))
let int32_rotate_right x n =
Int32.(logor (shift_left x (-n land 31)) (shift_right_logical x n))
let pcg32_next inc st =
Int64.(add (mul st 0x5851f42d4c957f2dL) inc)
let pcg32_o... |
Ensure the translated OCaml code behaves exactly like the original C++ snippet. | #include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
template <typename T>
void print(const std::vector<T>& v) {
std::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, " "));
std::cout << '\n';
}
int main() {
std::vector<int> vec{1, 2, 3, 4, 5, 6, 7, 8, 9};
std::co... | # let rec rotate n = function
| h :: (_ :: _ as t) when n > 0 -> rotate (pred n) (t @ [h])
| l -> l
;;
val rotate : int -> 'a list -> 'a list = <fun>
# rotate 3 [1; 2; 3; 4; 5; 6; 7; 8; 9] ;;
- : int list = [4; 5; 6; 7; 8; 9; 1; 2; 3]
|
Port the provided C++ code into OCaml while preserving the original functionality. | #include <iostream>
#include <iomanip>
#include <bitset>
const int LIMIT = 100000;
std::bitset<16> digitset(int num, int base) {
std::bitset<16> set;
for (; num; num /= base) set.set(num % base);
return set;
}
int main() {
int c = 0;
for (int i=0; i<LIMIT; i++) {
if (digitset(i,10) == dig... | module CSet = Set.Make(struct
type t = char
let compare = compare
end)
let str2cset str = CSet.add_seq (String.to_seq str) CSet.empty
let has_same_digits n =
let deci = Format.sprintf "%d" n in
let hexa = Format.sprintf "%x" n in
CSet.equal (str2cset deci) (str2cset hexa)
let rec list_similar ?(acc=[]) ... |
Generate a OCaml translation of this C++ snippet without changing its computational steps. |
#include <iostream>
using namespace std;
int main()
{
long long int a = 30'00'000;
std::cout <<"And with the ' in C++ 14 : "<< a << endl;
return 0;
}
| Printf.printf "%d\n" 1_2_3;;
Printf.printf "%d\n" 0b1_0_1_0_1;;
Printf.printf "%d\n" 0xa_bc_d;;
Printf.printf "%d\n" 12__34;;
Printf.printf "%f\n" 1_2_3_4.2_5;;
Printf.printf "%f\n" 6.0_22e4;;
Printf.printf "%f\n" 1234_.25;;
Printf.printf "%f\n" 1234._25;;
Printf.printf "%f\n" 1234.25_;;
|
Keep all operations the same but rewrite the snippet in OCaml. | #include <iostream>
#include <set>
#include <cmath>
int main() {
std::set<int> values;
for (int a=2; a<=5; a++)
for (int b=2; b<=5; b++)
values.insert(std::pow(a, b));
for (int i : values)
std::cout << i << " ";
std::cout << std::endl;
return 0;
}
| module IntSet = Set.Make(Int)
let pow x =
let rec aux acc b = function
| 0 -> acc
| y -> aux (if y land 1 = 0 then acc else acc * b) (b * b) (y lsr 1)
in
aux 1 x
let distinct_powers first count =
let sq = Seq.(take count (ints first)) in
IntSet.of_seq (Seq.map_product pow sq sq)
let () = distinct... |
Generate an equivalent OCaml version of this C++ code. | #include <iostream>
int main() {
using namespace std;
cout << "Hello, World!" << endl;
return 0;
}
| print_string "Hello world!\n";;
|
Convert this C++ block to OCaml, preserving its control flow and logic. | #include <iostream>
int main() {
using namespace std;
cout << "Hello, World!" << endl;
return 0;
}
| print_string "Hello world!\n";;
|
Can you help me rewrite this code in OCaml instead of C++, keeping it the same logically? |
class matrixNG {
private:
virtual void consumeTerm(){}
virtual void consumeTerm(int n){}
virtual const bool needTerm(){}
protected: int cfn = 0, thisTerm;
bool haveTerm = false;
friend class NG;
};
class NG_4 : public matrixNG {
private: int a1, a, b1, b, t;
const bool needTerm() {
if... | module CF =
struct
type record_t =
{
terminated : bool;
m : int;
memo : int Array.t;
gen : unit -> int option;
}
type t = record_t ref
let make gen =
ref { terminated = false;
m = 0;
memo = ... |
Rewrite this program in OCaml while keeping its functionality equivalent to the C++ version. |
class matrixNG {
private:
virtual void consumeTerm(){}
virtual void consumeTerm(int n){}
virtual const bool needTerm(){}
protected: int cfn = 0, thisTerm;
bool haveTerm = false;
friend class NG;
};
class NG_4 : public matrixNG {
private: int a1, a, b1, b, t;
const bool needTerm() {
if... | module CF =
struct
type record_t =
{
terminated : bool;
m : int;
memo : int Array.t;
gen : unit -> int option;
}
type t = record_t ref
let make gen =
ref { terminated = false;
m = 0;
memo = ... |
Rewrite this program in OCaml while keeping its functionality equivalent to the C++ version. | #include <iostream>
int main()
{
std::cout <<
R"EOF( A raw string begins with R, then a double-quote ("), then an optional
identifier (here I've used "EOF"), then an opening parenthesis ('('). If you
use an identifier, it cannot be longer than 16 characters, and it cannot
contain a space, either op... | print_string {whatever|
'hahah', `this`
<is>
\a\
"Heredoc" ${example}
in OCaml
|whatever}
;;
|
Please provide an equivalent version of this C++ code in OCaml. | #include <algorithm>
#include <array>
#include <cassert>
#include <initializer_list>
#include <iostream>
constexpr size_t sp_rows = 3;
constexpr size_t sp_columns = 3;
constexpr size_t sp_cells = sp_rows * sp_columns;
constexpr int sp_limit = 4;
class abelian_sandpile {
friend std::ostream& operator<<(std::ostrea... |
module Make =
functor (M : sig val m : int val n : int end)
-> struct
type t = { grid : int array array ; unstable : ((int*int),unit) Hashtbl.t }
let make () = { grid = Array.init M.m (fun _ -> Array.make M.n 0); unstable = Hashtbl.create 10 }
let print {grid=grid} =
for i = 0... |
Port the following code from C++ to OCaml with equivalent syntax and logic. | #include <algorithm>
#include <array>
#include <cassert>
#include <initializer_list>
#include <iostream>
constexpr size_t sp_rows = 3;
constexpr size_t sp_columns = 3;
constexpr size_t sp_cells = sp_rows * sp_columns;
constexpr int sp_limit = 4;
class abelian_sandpile {
friend std::ostream& operator<<(std::ostrea... |
module Make =
functor (M : sig val m : int val n : int end)
-> struct
type t = { grid : int array array ; unstable : ((int*int),unit) Hashtbl.t }
let make () = { grid = Array.init M.m (fun _ -> Array.make M.n 0); unstable = Hashtbl.create 10 }
let print {grid=grid} =
for i = 0... |
Rewrite this program in OCaml while keeping its functionality equivalent to the C++ version. | #include <iomanip>
#include <iostream>
bool nondecimal(unsigned int n) {
for (; n > 0; n >>= 4) {
if ((n & 0xF) > 9)
return true;
}
return false;
}
int main() {
unsigned int count = 0;
for (unsigned int n = 0; n < 501; ++n) {
if (nondecimal(n)) {
++count;
... | let rec has_xdigit n =
n land 15 > 9 || n > 15 && has_xdigit (n lsr 4)
let () =
Seq.(ints 1 |> take 500 |> filter has_xdigit |> map string_of_int)
|> List.of_seq |> String.concat " " |> print_endline
|
Please provide an equivalent version of this C++ code in OCaml. | #include <iomanip>
#include <iostream>
bool nondecimal(unsigned int n) {
for (; n > 0; n >>= 4) {
if ((n & 0xF) > 9)
return true;
}
return false;
}
int main() {
unsigned int count = 0;
for (unsigned int n = 0; n < 501; ++n) {
if (nondecimal(n)) {
++count;
... | let rec has_xdigit n =
n land 15 > 9 || n > 15 && has_xdigit (n lsr 4)
let () =
Seq.(ints 1 |> take 500 |> filter has_xdigit |> map string_of_int)
|> List.of_seq |> String.concat " " |> print_endline
|
Produce a language-to-language conversion: from C++ to OCaml, same semantics. | int i;
void* address_of_i = &i;
| let address_of (x:'a) : nativeint =
if Obj.is_block (Obj.repr x) then
Nativeint.shift_left (Nativeint.of_int (Obj.magic x)) 1
else
invalid_arg "Can only find address of boxed values.";;
let () =
let a = 3.14 in
Printf.printf "%nx\n" (address_of a);;
let b = ref 42 in
Printf.printf "%nx\n" (address... |
Change the programming language of this snippet from C++ to OCaml without modifying what it does. | inline double multiply(double a, double b)
{
return a*b;
}
| let int_multiply x y = x * y
let float_multiply x y = x *. y
|
Generate a OCaml translation of this C++ snippet without changing its computational steps. | #include <gmpxx.h>
#include <iomanip>
#include <iostream>
using big_int = mpz_class;
bool is_probably_prime(const big_int& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;
}
big_int jacobsthal_number(unsigned int n) {
return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;
}
big_int jacobsthal_lucas... | let is_prime n =
let rec test x =
x * x > n || n mod x <> 0 && n mod (x + 2) <> 0 && test (x + 6)
in
if n < 5
then n land 2 <> 0
else n land 1 <> 0 && n mod 3 <> 0 && test 5
let seq_jacobsthal =
let rec next b a () = Seq.Cons (a, next (a + a + b) b) in
next 1
let seq_jacobsthal_oblong =
let rec ne... |
Can you help me rewrite this code in OCaml instead of C++, keeping it the same logically? | #include <gmpxx.h>
#include <iomanip>
#include <iostream>
using big_int = mpz_class;
bool is_probably_prime(const big_int& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;
}
big_int jacobsthal_number(unsigned int n) {
return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;
}
big_int jacobsthal_lucas... | let is_prime n =
let rec test x =
x * x > n || n mod x <> 0 && n mod (x + 2) <> 0 && test (x + 6)
in
if n < 5
then n land 2 <> 0
else n land 1 <> 0 && n mod 3 <> 0 && test 5
let seq_jacobsthal =
let rec next b a () = Seq.Cons (a, next (a + a + b) b) in
next 1
let seq_jacobsthal_oblong =
let rec ne... |
Generate an equivalent OCaml version of this C++ code. | #include <iostream>
#include <locale>
#include <primesieve.hpp>
int main() {
std::cout.imbue(std::locale(""));
std::cout << "The 10,001st prime is " << primesieve::nth_prime(10001) << ".\n";
}
| let () =
seq_primes |> Seq.drop 10000 |> Seq.take 1 |> Seq.iter (Printf.printf "%u\n")
|
Generate an equivalent OCaml version of this C++ code. | #include <gmpxx.h>
#include <iomanip>
#include <iostream>
bool is_prime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
... | let modpow m =
let rec loop p b e =
if e land 1 = 0
then if e = 0 then p else loop p (b * b mod m) (e lsr 1)
else loop (p * b mod m) (b * b mod m) (e lsr 1)
in loop 1
let is_deceptive n =
let rec loop x =
x * x <= n && (n mod x = 0 || n mod (x + 4) = 0 || loop (x + 6))
in
n land 1 <> 0 && n m... |
Generate a OCaml translation of this C++ snippet without changing its computational steps. | #include <gmpxx.h>
#include <iomanip>
#include <iostream>
bool is_prime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
... | let modpow m =
let rec loop p b e =
if e land 1 = 0
then if e = 0 then p else loop p (b * b mod m) (e lsr 1)
else loop (p * b mod m) (b * b mod m) (e lsr 1)
in loop 1
let is_deceptive n =
let rec loop x =
x * x <= n && (n mod x = 0 || n mod (x + 4) = 0 || loop (x + 6))
in
n land 1 <> 0 && n m... |
Can you help me rewrite this code in OCaml instead of C++, keeping it the same logically? | #include <ctime>
#include <string>
#include <iostream>
#include <algorithm>
class cycle{
public:
template <class T>
void cy( T* a, int len ) {
int i, j;
show( "original: ", a, len );
std::srand( unsigned( time( 0 ) ) );
for( int i = len - 1; i > 0; i-- ) {
do {
... | let sattolo_cycle arr =
for i = Array.length arr - 1 downto 1 do
let j = Random.int i in
let temp = arr.(i) in
arr.(i) <- arr.(j);
arr.(j) <- temp
done
|
Rewrite this program in OCaml while keeping its functionality equivalent to the C++ version. | #include <ctime>
#include <string>
#include <iostream>
#include <algorithm>
class cycle{
public:
template <class T>
void cy( T* a, int len ) {
int i, j;
show( "original: ", a, len );
std::srand( unsigned( time( 0 ) ) );
for( int i = len - 1; i > 0; i-- ) {
do {
... | let sattolo_cycle arr =
for i = Array.length arr - 1 downto 1 do
let j = Random.int i in
let temp = arr.(i) in
arr.(i) <- arr.(j);
arr.(j) <- temp
done
|
Port the following code from C++ to OCaml with equivalent syntax and logic. | #include <iostream>
#include <functional>
template <typename F>
struct RecursiveFunc {
std::function<F(RecursiveFunc)> o;
};
template <typename A, typename B>
std::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {
RecursiveFunc<std::function<B(A)>> r = {
std::function<std::function<B(... | let fix f g = (fun x a -> f (x x) a) (fun x a -> f (x x) a) g
|
Ensure the translated OCaml code behaves exactly like the original C++ snippet. | #include <iostream>
class factorion_t {
public:
factorion_t() {
f[0] = 1u;
for (uint n = 1u; n < 12u; n++)
f[n] = f[n - 1] * n;
}
bool operator()(uint i, uint b) const {
uint sum = 0;
for (uint j = i; j > 0u; j /= b)
sum += f[j % b];
return s... | let () =
let fact = Array.make 12 0 in
fact.(0) <- 1;
for n = 1 to pred 12 do
fact.(n) <- fact.(n-1) * n;
done;
for b = 9 to 12 do
Printf.printf "The factorions for base %d are:\n" b;
for i = 1 to pred 1_500_000 do
let sum = ref 0 in
let j = ref i in
while !j > 0 do
l... |
Write the same code in OCaml as shown below in C++. | #include <iostream>
class factorion_t {
public:
factorion_t() {
f[0] = 1u;
for (uint n = 1u; n < 12u; n++)
f[n] = f[n - 1] * n;
}
bool operator()(uint i, uint b) const {
uint sum = 0;
for (uint j = i; j > 0u; j /= b)
sum += f[j % b];
return s... | let () =
let fact = Array.make 12 0 in
fact.(0) <- 1;
for n = 1 to pred 12 do
fact.(n) <- fact.(n-1) * n;
done;
for b = 9 to 12 do
Printf.printf "The factorions for base %d are:\n" b;
for i = 1 to pred 1_500_000 do
let sum = ref 0 in
let j = ref i in
while !j > 0 do
l... |
Change the following C++ code into OCaml without altering its purpose. | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
bool InteractiveCompare(const string& s1, const string& s2)
{
if(s1 == s2) return false;
static int count = 0;
string response;
cout << "(" << ++count << ") Is " << s1 << " < " << s2 << "? ";
getline(cin, response);
... | let () =
let count = ref 0 in
let mycmp s1 s2 = (
incr count;
Printf.printf "(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: " (!count) s1 s2;
read_int ()
) in
let items = ["violet"; "red"; "green"; "indigo"; "blue"; "yellow"; "orange"] in
let sorted = List.sort mycmp items in
List.iter (Printf.p... |
Translate this program into OCaml but keep the logic exactly as in C++. |
#include <iostream>
#include <vector>
using std::cout;
using std::vector;
void distribute(int dist, vector<int> &List) {
if (dist > List.size() )
List.resize(dist);
for (int i=0; i < dist; i++)
List[i]++;
}
vector<int> beadSort(int *myints, int n) {
vector<int> list, list2, fifth ... | let rec columns l =
match List.filter ((<>) []) l with
[] -> []
| l -> List.map List.hd l :: columns (List.map List.tl l)
let replicate n x = Array.to_list (Array.make n x)
let bead_sort l =
List.map List.length (columns (columns (List.map (fun e -> replicate e 1) l)))
|
Produce a functionally identical OCaml code for the snippet given in C++. | void runCode(string code)
{
int c_len = code.length();
unsigned accumulator=0;
int bottles;
for(int i=0;i<c_len;i++)
{
switch(code[i])
{
case 'Q':
cout << code << endl;
break;
case 'H':
cout << "Hello, world!" <... | let hq9p line =
let accumulator = ref 0 in
for i = 0 to (String.length line - 1) do
match line.[i] with
| 'h' | 'H' -> print_endline "Hello, world!"
| 'q' | 'Q' -> print_endline line
| '9' -> beer 99
| '+' -> incr accumulator
done
|
Please provide an equivalent version of this C++ code in OCaml. | void runCode(string code)
{
int c_len = code.length();
unsigned accumulator=0;
int bottles;
for(int i=0;i<c_len;i++)
{
switch(code[i])
{
case 'Q':
cout << code << endl;
break;
case 'H':
cout << "Hello, world!" <... | let hq9p line =
let accumulator = ref 0 in
for i = 0 to (String.length line - 1) do
match line.[i] with
| 'h' | 'H' -> print_endline "Hello, world!"
| 'q' | 'Q' -> print_endline line
| '9' -> beer 99
| '+' -> incr accumulator
done
|
Change the programming language of this snippet from C++ to OCaml without modifying what it does. | #include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {
if (mod == 1)
return 0;
uint64_t result = 1;
base %= mod;
for (; exp > 0; exp >>= 1) {
if ((exp & 1) == 1)
result = (result * base) % mod;... | let modpow m =
let rec loop p b e =
if e land 1 = 0
then if e = 0 then p else loop p (b * b mod m) (e lsr 1)
else loop (p * b mod m) (b * b mod m) (e lsr 1)
in loop 1
let is_curzon k n =
let r = k * n in r = modpow (succ r) k n
let () =
List.iter (fun x ->
Seq.(ints 0 |> filter (is_curzon x) |... |
Write the same code in OCaml as shown below in C++. | #include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {
if (mod == 1)
return 0;
uint64_t result = 1;
base %= mod;
for (; exp > 0; exp >>= 1) {
if ((exp & 1) == 1)
result = (result * base) % mod;... | let modpow m =
let rec loop p b e =
if e land 1 = 0
then if e = 0 then p else loop p (b * b mod m) (e lsr 1)
else loop (p * b mod m) (b * b mod m) (e lsr 1)
in loop 1
let is_curzon k n =
let r = k * n in r = modpow (succ r) k n
let () =
List.iter (fun x ->
Seq.(ints 0 |> filter (is_curzon x) |... |
Convert this C++ snippet to OCaml and keep its semantics consistent. | #include <deque>
#include <algorithm>
#include <ostream>
#include <iterator>
namespace cards
{
class card
{
public:
enum pip_type { two, three, four, five, six, seven, eight, nine, ten,
jack, queen, king, ace, pip_count };
enum suite_type { hearts, spades, diamonds, clubs, suite_count };
... | type pip = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten |
Jack | Queen | King | Ace
let pips = [Two; Three; Four; Five; Six; Seven; Eight; Nine; Ten;
Jack; Queen; King; Ace]
type suit = Diamonds | Spades | Hearts | Clubs
let suits = [Diamonds; Spades; Hearts; Clubs]
type card = ... |
Please provide an equivalent version of this C++ code in OCaml. | #include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
int gcd(int a, int b) {
int c;
while (b) {
c = a;
a = b;
b = c % b;
}
return a;
}
int main() {
using intpair = std::pair<int,int>;
std::vector<intpair> pairs = {
{21,15}, {17,23}, {36,... | let rec is_coprime a = function
| 0 -> a = 1
| b -> is_coprime b (a mod b)
let () =
let p (a, b) =
Printf.printf "%u and %u are%s coprime\n" a b (if is_coprime a b then "" else " not")
in
List.iter p [21, 15; 17, 23; 36, 12; 18, 29; 60, 15]
|
Rewrite the snippet below in OCaml so it works the same as the original C++ code. | #include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
int gcd(int a, int b) {
int c;
while (b) {
c = a;
a = b;
b = c % b;
}
return a;
}
int main() {
using intpair = std::pair<int,int>;
std::vector<intpair> pairs = {
{21,15}, {17,23}, {36,... | let rec is_coprime a = function
| 0 -> a = 1
| b -> is_coprime b (a mod b)
let () =
let p (a, b) =
Printf.printf "%u and %u are%s coprime\n" a b (if is_coprime a b then "" else " not")
in
List.iter p [21, 15; 17, 23; 36, 12; 18, 29; 60, 15]
|
Generate a OCaml translation of this C++ snippet without changing its computational steps. | #include <iostream>
#include <map>
#include <tuple>
#include <vector>
using namespace std;
pair<int, int> twoSum(vector<int> numbers, int sum) {
auto m = map<int, int>();
for (size_t i = 0; i < numbers.size(); ++i) {
auto key = sum - numbers[i];
if (m.find(key) != m.end()) {
return make_pair(m[key], i);
... | let get_sums ~numbers ~sum =
let n = Array.length numbers in
let res = ref [] in
for i = 0 to n - 2 do
for j = i + 1 to n - 1 do
if numbers.(i) + numbers.(j) = sum then
res := (i, j) :: !res
done
done;
!res
let () =
let numbers = [| 0; 2; 11; 19; 90 |]
and sum = 21
in
let res =... |
Preserve the algorithm and functionality while converting the code from C++ to OCaml. | #include <cstdio>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum;
for (int x : lst) w.push_back({x, x});
while (w.size() > 0) { auto i = w[0]; w.erase(w.begin());
for (int x : lst) if ((sum = get<1>(i) + x) == 13)
... | let prime_digits_13 =
let digits = [2; 3; 5; 7] in
let rec next ds ns = function
| [] -> if ns = [] then [] else next digits [] (List.rev ns)
| (n, r) :: cs' as cs ->
match ds with
| d :: ds' when d < r -> next ds' (((n + d) * 10, r - d) :: ns) cs
| d :: ds' when d = r -> n + d :: ne... |
Write a version of this C++ function in OCaml with identical behavior. | #include <cstdio>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum;
for (int x : lst) w.push_back({x, x});
while (w.size() > 0) { auto i = w[0]; w.erase(w.begin());
for (int x : lst) if ((sum = get<1>(i) + x) == 13)
... | let prime_digits_13 =
let digits = [2; 3; 5; 7] in
let rec next ds ns = function
| [] -> if ns = [] then [] else next digits [] (List.rev ns)
| (n, r) :: cs' as cs ->
match ds with
| d :: ds' when d < r -> next ds' (((n + d) * 10, r - d) :: ns) cs
| d :: ds' when d = r -> n + d :: ne... |
Can you help me rewrite this code in OCaml instead of C++, keeping it the same logically? | #include <array>
#include <iostream>
#include <list>
#include <map>
#include <vector>
int main()
{
auto myNumbers = std::vector<std::string>{"one", "two", "three", "four"};
auto myColors = std::vector<std::string>{"red", "green", "blue"};
auto myArray = std::array<std::vector<std::string>, 2>{myNumber... | let rec copy t =
if Obj.is_int t then t else
let tag = Obj.tag t in
if tag = Obj.double_tag then t else
if tag = Obj.closure_tag then t else
if tag = Obj.string_tag then Obj.repr (String.copy (Obj.obj t)) else
if tag = 0 || tag = Obj.double_array_tag then begin
let size = Obj.size t in
... |
Generate a OCaml translation of this C++ snippet without changing its computational steps. | #include <array>
#include <iostream>
#include <list>
#include <map>
#include <vector>
int main()
{
auto myNumbers = std::vector<std::string>{"one", "two", "three", "four"};
auto myColors = std::vector<std::string>{"red", "green", "blue"};
auto myArray = std::array<std::vector<std::string>, 2>{myNumber... | let rec copy t =
if Obj.is_int t then t else
let tag = Obj.tag t in
if tag = Obj.double_tag then t else
if tag = Obj.closure_tag then t else
if tag = Obj.string_tag then Obj.repr (String.copy (Obj.obj t)) else
if tag = 0 || tag = Obj.double_array_tag then begin
let size = Obj.size t in
... |
Ensure the translated OCaml code behaves exactly like the original C++ snippet. | #include <algorithm>
template<typename ForwardIterator>
void permutation_sort(ForwardIterator begin, ForwardIterator end)
{
while (std::next_permutation(begin, end))
{
}
}
| let rec sorted = function
| e1 :: e2 :: r -> e1 <= e2 && sorted (e2 :: r)
| _ -> true
let rec insert e = function
| [] -> [[e]]
| h :: t as l -> (e :: l) :: List.map (fun t' -> h :: t') (insert e t)
let permute xs = List.fold_right (fun h z -> List.concat (List.map (insert h) z))
... |
Write the same algorithm in OCaml as shown in this C++ implementation. | int meaning_of_life();
| let meaning_of_life = 42
let main () =
Printf.printf "Main: The meaning of life is %d\n"
meaning_of_life
let () =
if not !Sys.interactive then
main ()
|
Translate this program into OCaml but keep the logic exactly as in C++. | int meaning_of_life();
| let meaning_of_life = 42
let main () =
Printf.printf "Main: The meaning of life is %d\n"
meaning_of_life
let () =
if not !Sys.interactive then
main ()
|
Convert this C++ block to OCaml, preserving its control flow and logic. | #include <iostream>
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 false;
p += 2;
if (n % p == 0)
... | let is_nice_prime n =
let rec test x =
x * x > n || n mod x <> 0 && n mod (x + 2) <> 0 && test (x + 6)
in
if n < 5
then n lor 1 = 3
else n land 1 <> 0 && n mod 3 <> 0 && (n + 6) mod 9 land 1 = 0 && test 5
let () =
Seq.(ints 500 |> take 500 |> filter is_nice_prime |> iter (Printf.printf " %u"))
|> pri... |
Write the same algorithm in OCaml as shown in this C++ implementation. | #include <iostream>
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 false;
p += 2;
if (n % p == 0)
... | let is_nice_prime n =
let rec test x =
x * x > n || n mod x <> 0 && n mod (x + 2) <> 0 && test (x + 6)
in
if n < 5
then n lor 1 = 3
else n land 1 <> 0 && n mod 3 <> 0 && (n + 6) mod 9 land 1 = 0 && test 5
let () =
Seq.(ints 500 |> take 500 |> filter is_nice_prime |> iter (Printf.printf " %u"))
|> pri... |
Preserve the algorithm and functionality while converting the code from C++ to OCaml. | #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
class lastSunday
{
public:
lastSunday()
{
m[0] = "JANUARY: "; m[1] = "FEBRUARY: "; m[2] = "MARCH: "; m[3] = "APRIL: ";
m[4] = "MAY: "; m[5] = "JUNE: "; m[6] = "JULY: "; m[7] = "AUGUST: ";... | let is_leap_year y =
if (y mod 100) = 0
then (y mod 400) = 0
else (y mod 4) = 0;;
let get_days y =
if is_leap_year y
then
[31;29;31;30;31;30;31;31;30;31;30;31]
else
[31;28;31;30;31;30;31;31;30;31;30;31];;
let print_date = Printf.printf "%d/%d/%d\n";;
let get_day_of_week y m d =
... |
Port the following code from C++ to OCaml with equivalent syntax and logic. | #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
class lastSunday
{
public:
lastSunday()
{
m[0] = "JANUARY: "; m[1] = "FEBRUARY: "; m[2] = "MARCH: "; m[3] = "APRIL: ";
m[4] = "MAY: "; m[5] = "JUNE: "; m[6] = "JULY: "; m[7] = "AUGUST: ";... | let is_leap_year y =
if (y mod 100) = 0
then (y mod 400) = 0
else (y mod 4) = 0;;
let get_days y =
if is_leap_year y
then
[31;29;31;30;31;30;31;31;30;31;30;31]
else
[31;28;31;30;31;30;31;31;30;31;30;31];;
let print_date = Printf.printf "%d/%d/%d\n";;
let get_day_of_week y m d =
... |
Write a version of this C++ function in OCaml with identical behavior. | #include <algorithm>
#include <ctime>
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
srand(time(0));
unsigned int attributes_total = 0;
unsigned int count = 0;
int attributes[6] = {};
int rolls[4] = {};
while(attributes_total < 75 || count ... |
let rand_die () : int = Random.int 6
let rand_attr () : int =
let four_rolls = [rand_die (); rand_die (); rand_die (); rand_die ()]
|> List.sort compare in
let three_best = List.tl four_rolls in
List.fold_left (+) 0 three_best
let rand_set () : int list=
[rand_attr (); rand_attr (); rand_attr ();
ra... |
Write the same code in OCaml as shown below in C++. | #include <iostream>
#include <sstream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <locale>
class Sparkline {
public:
Sparkline(std::wstring &cs) : charset( cs ){
}
virtual ~Sparkline(){
}
void print(std::string spark){
const char *delim = "... | let before_first_bar = 0x2580
let num_bars = 8
let sparkline numbers =
let max_num = List.fold_left max 0. numbers in
let scale = float_of_int num_bars /. max_num in
let bars = Buffer.create num_bars in
let add_bar number =
let scaled = scale *. number |> Float.round |> int_of_float in
if scaled <= 0 t... |
Transform the following C++ implementation into OCaml, maintaining the same output and logic. | #include <vector>
#include <list>
#include <algorithm>
#include <iostream>
template <typename T>
struct Node {
T value;
Node* prev_node;
};
template <typename Container>
Container lis(const Container& values) {
using E = typename Container::value_type;
using NodePtr = Node<E>*;
using ConstNodePtr ... | let longest l = List.fold_left (fun acc x -> if List.length acc < List.length x
then x
else acc) [] l
let subsequences d l =
let rec check_subsequences acc = function
| x::s -> check_subsequences (if (List.hd (List.rev x)) < d
... |
Write a version of this C++ function in OCaml with identical behavior. | #include <iostream>
void f(int n) {
if (n < 1) {
return;
}
int i = 1;
while (true) {
int sq = i * i;
while (sq > n) {
sq /= 10;
}
if (sq == n) {
printf("%3d %9d %4d\n", n, i * i, i);
return;
}
i++;
}
}
int... | let rec is_prefix a b =
if b > a then is_prefix a (b/10) else a = b
let rec smallest ?(i=1) n =
let square = i*i in
if is_prefix n square then square else smallest n ~i:(succ i)
let _ =
for n = 1 to 49 do
Printf.printf "%d%c" (smallest n) (if n mod 10 = 0 then '\n' else '\t')
done
|
Write the same algorithm in OCaml as shown in this C++ implementation. | #include <iostream>
void f(int n) {
if (n < 1) {
return;
}
int i = 1;
while (true) {
int sq = i * i;
while (sq > n) {
sq /= 10;
}
if (sq == n) {
printf("%3d %9d %4d\n", n, i * i, i);
return;
}
i++;
}
}
int... | let rec is_prefix a b =
if b > a then is_prefix a (b/10) else a = b
let rec smallest ?(i=1) n =
let square = i*i in
if is_prefix n square then square else smallest n ~i:(succ i)
let _ =
for n = 1 to 49 do
Printf.printf "%d%c" (smallest n) (if n mod 10 = 0 then '\n' else '\t')
done
|
Generate a OCaml translation of this C++ snippet without changing its computational steps. | #include <iostream>
#include <cmath>
#include <tuple>
struct point { double x, y; };
bool operator==(const point& lhs, const point& rhs)
{ return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y); }
enum result_category { NONE, ONE_COINCEDENT, ONE_DIAMETER, TWO, INFINITE };
using result_t = std::tuple<result_categor... |
type point = float * float
type radius = float
type circle = Circle of radius * point
type circ_output =
NoSolution
| OneSolution of circle
| TwoSolutions of circle * circle
| InfiniteSolutions
;;
let circles_2points_radius (x1, y1 : point) (x2, y2 : point) (r : radius) =
let (dx, dy) = (x2 -.... |
Port the provided C++ code into OCaml while preserving the original functionality. | #include <iostream>
#include <cmath>
#include <tuple>
struct point { double x, y; };
bool operator==(const point& lhs, const point& rhs)
{ return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y); }
enum result_category { NONE, ONE_COINCEDENT, ONE_DIAMETER, TWO, INFINITE };
using result_t = std::tuple<result_categor... |
type point = float * float
type radius = float
type circle = Circle of radius * point
type circ_output =
NoSolution
| OneSolution of circle
| TwoSolutions of circle * circle
| InfiniteSolutions
;;
let circles_2points_radius (x1, y1 : point) (x2, y2 : point) (r : radius) =
let (dx, dy) = (x2 -.... |
Ensure the translated OCaml code behaves exactly like the original C++ snippet. | #include <iostream>
#include <string>
#include <windows.h>
#include <mmsystem.h>
#pragma comment ( lib, "winmm.lib" )
using namespace std;
class recorder
{
public:
void start()
{
paused = rec = false; action = "IDLE";
while( true )
{
cout << endl << "==" << action << "==" << endl << endl;
cout <<... | #load "unix.cma"
let record bytes =
let buf = String.make bytes '\000' in
let ic = open_in "/dev/dsp" in
let chunk = 4096 in
for i = 0 to pred (bytes / chunk) do
ignore (input ic buf (i * chunk) chunk)
done;
close_in ic;
(buf)
let play buf len =
let oc = open_out "/dev/dsp" in
output_string oc... |
Maintain the same structure and functionality when rewriting this code in OCaml. | #include <windows.h>
#include <string>
#include <iostream>
const int BMP_SIZE = 612;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( ... | open Graphics
let round v =
int_of_float (floor (v +. 0.5))
let middle (x1, y1) (x2, y2) =
((x1 +. x2) /. 2.0,
(y1 +. y2) /. 2.0)
let draw_line (x1, y1) (x2, y2) =
moveto (round x1) (round y1);
lineto (round x2) (round y2);
;;
let draw_triangle (p1, p2, p3) =
draw_line p1 p2;
draw_line p2 p3;
draw_... |
Rewrite the snippet below in OCaml so it works the same as the original C++ code. | #include <windows.h>
#include <string>
#include <iostream>
const int BMP_SIZE = 612;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( ... | open Graphics
let round v =
int_of_float (floor (v +. 0.5))
let middle (x1, y1) (x2, y2) =
((x1 +. x2) /. 2.0,
(y1 +. y2) /. 2.0)
let draw_line (x1, y1) (x2, y2) =
moveto (round x1) (round y1);
lineto (round x2) (round y2);
;;
let draw_triangle (p1, p2, p3) =
draw_line p1 p2;
draw_line p2 p3;
draw_... |
Translate this program into OCaml but keep the logic exactly as in C++. | #include <windows.h>
#include <vector>
#include <string>
using namespace std;
struct Point {
int x, y;
};
class MyBitmap {
public:
MyBitmap() : pen_(nullptr) {}
~MyBitmap() {
DeleteObject(pen_);
DeleteDC(hdc_);
DeleteObject(bmp_);
}
bool Create(int w, int h) {
BITMAPINFO bi;
ZeroMem... | let n_sites = 220
let size_x = 640
let size_y = 480
let sq2 ~x ~y =
(x * x + y * y)
let rand_int_range a b =
a + Random.int (b - a + 1)
let nearest_site ~site ~x ~y =
let ret = ref 0 in
let dist = ref 0 in
Array.iteri (fun k (sx, sy) ->
let d = sq2 (x - sx) (y - sy) in
if k = 0 || d < !dist the... |
Keep all operations the same but rewrite the snippet in OCaml. | #include <windows.h>
#include <vector>
#include <string>
using namespace std;
struct Point {
int x, y;
};
class MyBitmap {
public:
MyBitmap() : pen_(nullptr) {}
~MyBitmap() {
DeleteObject(pen_);
DeleteDC(hdc_);
DeleteObject(bmp_);
}
bool Create(int w, int h) {
BITMAPINFO bi;
ZeroMem... | let n_sites = 220
let size_x = 640
let size_y = 480
let sq2 ~x ~y =
(x * x + y * y)
let rand_int_range a b =
a + Random.int (b - a + 1)
let nearest_site ~site ~x ~y =
let ret = ref 0 in
let dist = ref 0 in
Array.iteri (fun k (sx, sy) ->
let d = sq2 (x - sx) (y - sy) in
if k = 0 || d < !dist the... |
Translate this program into OCaml but keep the logic exactly as in C++. | #include <list>
template <typename T>
std::list<T> strandSort(std::list<T> lst) {
if (lst.size() <= 1)
return lst;
std::list<T> result;
std::list<T> sorted;
while (!lst.empty()) {
sorted.push_back(lst.front());
lst.pop_front();
for (typename std::list<T>::iterator it = lst.begin(); it != lst.en... | let rec strand_sort (cmp : 'a -> 'a -> int) : 'a list -> 'a list = function
[] -> []
| x::xs ->
let rec extract_strand x = function
[] -> [x], []
| x1::xs when cmp x x1 <= 0 ->
let strand, rest = extract_strand x1 xs in x::strand, rest
| x1::xs ->
let strand, rest = extract_strand x ... |
Generate a OCaml translation of this C++ snippet without changing its computational steps. | #include <iostream>
#include "xtensor/xarray.hpp"
#include "xtensor/xio.hpp"
#include "xtensor-io/ximage.hpp"
xt::xarray<int> init_grid (unsigned long x_dim, unsigned long y_dim)
{
xt::xarray<int>::shape_type shape = { x_dim, y_dim };
xt::xarray<int> grid(shape);
grid(x_dim/2, y_dim/2) = 64000;
r... | module Make =
functor (M : sig val m : int val n : int end)
-> struct
let grid = Array.init M.m (fun _ -> Array.make M.n 0)
let print () =
for i = 0 to M.m - 1
do for j = 0 to M.n - 1
do Printf.printf "%d " grid.(i).(j)
done
; print_newline ()
done
let unst... |
Ensure the translated OCaml code behaves exactly like the original C++ snippet. | #include <boost/spirit.hpp>
#include <boost/spirit/tree/ast.hpp>
#include <string>
#include <cassert>
#include <iostream>
#include <istream>
#include <ostream>
using boost::spirit::rule;
using boost::spirit::parser_tag;
using boost::spirit::ch_p;
using boost::spirit::real_p;
using boost::spirit::tree_no... | type expression =
| Const of float
| Sum of expression * expression
| Diff of expression * expression
| Prod of expression * expression
| Quot of expression * expression
let rec eval = function
| Const c -> c
| Sum (f, g) -> eval f +. eval g
| Diff(f, g) -> eval f -. eval g
| Prod(f, g) ... |
Port the following code from C++ to OCaml with equivalent syntax and logic. | #include <boost/spirit.hpp>
#include <boost/spirit/tree/ast.hpp>
#include <string>
#include <cassert>
#include <iostream>
#include <istream>
#include <ostream>
using boost::spirit::rule;
using boost::spirit::parser_tag;
using boost::spirit::ch_p;
using boost::spirit::real_p;
using boost::spirit::tree_no... | type expression =
| Const of float
| Sum of expression * expression
| Diff of expression * expression
| Prod of expression * expression
| Quot of expression * expression
let rec eval = function
| Const c -> c
| Sum (f, g) -> eval f +. eval g
| Diff(f, g) -> eval f -. eval g
| Prod(f, g) ... |
Convert the following code from C++ to OCaml, ensuring the logic remains intact. | #include <stdio.h>
#include <stdlib.h>
void clear() {
for(int n = 0;n < 10; n++) {
printf("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\r\n\r\n\r\n");
}
}
#define UP "00^00\r\n00|00\r\n00000\r\n"
#define DOWN "00000\r\n00|00\r\n00v00\r\n"
#define LEFT "00000\r\n<--00\r\n00000\r\n"
#define RIGHT "00000\r\n00-->\r\n00000\r\... | let remove x = List.filter (fun y -> y <> x)
let buttons_string b =
String.concat " " (List.map string_of_int b)
let position app x y =
let view = SFRenderWindow.getView app in
let width, height = SFView.getSize view in
let hw = width /. 2.0 in
let hh = height /. 2.0 in
(hw +. ((x /. 100.0) *. hw),
hh ... |
Port the provided C++ code into OCaml while preserving the original functionality. | #include <cstdint>
#include <iostream>
#include <string>
using integer = uint64_t;
bool square_free(integer n) {
if (n % 4 == 0)
return false;
for (integer p = 3; p * p <= n; p += 2) {
integer count = 0;
for (; n % p == 0; n /= p) {
if (++count > 1)
return f... | let squarefree (number: int) : bool =
let max = Float.of_int number |> sqrt |> Float.to_int |> (fun x -> x + 2) in
let rec inner i number2 =
if i == max
then true
else if number2 mod (i*i) == 0
then false
else inner (i+1) number2
in inner 2 number
;;
let li... |
Can you help me rewrite this code in OCaml instead of C++, keeping it the same logically? | #include <array>
#include <iomanip>
#include <iostream>
const int MC = 103 * 1000 * 10000 + 11 * 9 + 1;
std::array<bool, MC + 1> SV;
void sieve() {
std::array<int, 10000> dS;
for (int a = 9, i = 9999; a >= 0; a--) {
for (int b = 9; b >= 0; b--) {
for (int c = 9, s = a + b; c >= 0; c--) {
... | open List;
val rec selfNumberNr = fn NR =>
let
val rec sumdgt = fn 0 => 0 | n => Int.rem (n, 10) + sumdgt (Int.quot(n ,10));
val rec isSelf = fn ([],l1,l2) => []
| (x::tt,l1,l2) => if exists (fn i=>i=x) l1 orelse exists (fn i=>i=x) l2
then ( isSelf (tt,l1,l2)) else x::isSelf (tt,l1,l2) ;
val rec partco... |
Write a version of this C++ function in OCaml with identical behavior. | #include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
using tab_t = std::vector<std::vector<std::string>>;
tab_t tab1 {
{"27", "Jonah"}
, {"18", "Alan"}
, {"28", "Glory"}
, {"18", "Popeye"}
, {"28", "Alan"}
};
tab_t tab2 {
{"Jonah", "Whales"}
, {"Jonah", "Spiders"}
, {"Alan", "Ghosts"... | let hash_join table1 f1 table2 f2 =
let h = Hashtbl.create 42 in
List.iter (fun s ->
Hashtbl.add h (f1 s) s) table1;
List.concat (List.map (fun r ->
List.map (fun s -> s, r) (Hashtbl.find_all h (f2 r))) table2)
|
Write a version of this C++ function in OCaml with identical behavior. | #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> words;
std::ifstream in("words.txt");
if (!in) {
std::cerr << "Cannot open file words.txt.\n";
return EXIT_FAILURE;
... | module StrSet = Set.Make(String)
let read_line_seq ch =
let rec repeat () =
match input_line ch with
| s -> Seq.Cons (s, repeat)
| exception End_of_file -> Nil
in repeat
let string_rev s =
let last = pred (String.length s) in
String.init (succ last) (fun i -> s.[last - i])
let get_anadromes set =... |
Generate a OCaml translation of this C++ snippet without changing its computational steps. | #include <iostream>
#include <ratio>
#include <array>
#include <algorithm>
#include <random>
typedef short int Digit;
constexpr Digit nDigits{4};
constexpr Digit maximumDigit{9};
constexpr short int gameGoal{24};
typedef std::array<Digit, nDigits> digitSet;
digitSet d;
void printTrivialOperation(std::... | type expression =
| Const of float
| Sum of expression * expression
| Diff of expression * expression
| Prod of expression * expression
| Quot of expression * expression
let rec eval = function
| Const c -> c
| Sum (f, g) -> eval f +. eval g
| Diff(f, g) -> eval f -. eval g
| Prod(f, g)... |
Write the same code in OCaml as shown below in C++. | #include <iostream>
#include <ratio>
#include <array>
#include <algorithm>
#include <random>
typedef short int Digit;
constexpr Digit nDigits{4};
constexpr Digit maximumDigit{9};
constexpr short int gameGoal{24};
typedef std::array<Digit, nDigits> digitSet;
digitSet d;
void printTrivialOperation(std::... | type expression =
| Const of float
| Sum of expression * expression
| Diff of expression * expression
| Prod of expression * expression
| Quot of expression * expression
let rec eval = function
| Const c -> c
| Sum (f, g) -> eval f +. eval g
| Diff(f, g) -> eval f -. eval g
| Prod(f, g)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.