Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Keep all operations the same but rewrite the snippet in Fortran. | #pragma once
#include <cmath>
#include <string>
#include <sstream>
#include <iomanip>
class Approx {
public:
Approx(double _v, double _s = 0.0) : v(_v), s(_s) {}
operator std::string() const {
std::ostringstream os("");
os << std::setprecision(15) << v << " ±" << std::setprecision(15) << s <<... | PROGRAM CALCULATE
REAL X1, Y1, X2, Y2
REAL X1E,Y1E,X2E,Y2E
DATA X1, Y1 ,X2, Y2 /100., 50., 200.,100./
DATA X1E,Y1E,X2E,Y2E/ 1.1, 1.2, 2.2, 2.3/
REAL DX,DY,D2,D,DXE,DYE,E
CHARACTER*1 C
PARAMETER (C = CHAR(241))
REAL SD
SD(X,P,S) = P*ABS(X)**(P - 1... |
Write a version of this C++ function in Fortran with identical behavior. | #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... | program tpk
implicit none
real, parameter :: overflow = 400.0
real :: a(11), res
integer :: i
write(*,*) "Input eleven numbers:"
read(*,*) a
a = a(11:1:-1)
do i = 1, 11
res = f(a(i))
write(*, "(a, f0.3, a)", advance = "no") "f(", a(i), ") = "
if(res > overflow) then
write(*, "(a... |
Port the following code from C++ to Fortran with equivalent syntax and logic. | #include <iostream>
#include <ctime>
class CRateState
{
protected:
time_t m_lastFlush;
time_t m_period;
size_t m_tickCount;
public:
CRateState(time_t period);
void Tick();
};
CRateState::CRateState(time_t period) : m_lastFlush(std::time(NULL)),
m_period(pe... | DO I = FIRST,LAST
IF (PROGRESSNOTE((I - FIRST)/(LAST - FIRST + 1.0))) WRITE (6,*) "Reached ",I,", towards ",LAST
...much computation...
END DO
|
Change the programming language of this snippet from C++ to Fortran without modifying what it does. | #include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
int topswops(int n) {
std::vector<int> list(n);
std::iota(std::begin(list), std::end(list), 1);
int max_steps = 0;
do {
auto temp_list = list;
for (int steps = 1; temp_list[0] != 1; ++steps) {
std::reverse(std::begin(te... | module top
implicit none
contains
recursive function f(x) result(m)
integer :: n, m, x(:),y(size(x)), fst
fst = x(1)
if (fst == 1) then
m = 0
else
y(1:fst) = x(fst:1:-1)
y(fst+1:) = x(fst+1:)
m = 1 + f(y)
end if
end function
recursive function perms(x) result(p)
integer, pointer :: p(:,:... |
Rewrite the snippet below in Fortran so it works the same as the original C++ code. | #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... | MODULE ELUDOM
INTEGER MSG,INF
LOGICAL DEFER
CONTAINS
CHARACTER*1 RECURSIVE FUNCTION GET(IN)
INTEGER IN
CHARACTER*1 C
READ (IN,1,ADVANCE="NO",EOR=3,END=4) C
1 FORMAT (A1,$)
2 IF (("A"<=C .AND. C<="Z").OR.("a"<=C .AND. C<="z")) THEN
... |
Ensure the translated Fortran code behaves exactly like the original C++ snippet. | #include <cassert>
#include <iomanip>
#include <iostream>
int largest_proper_divisor(int n) {
assert(n > 0);
if ((n & 1) == 0)
return n >> 1;
for (int p = 3; p * p <= n; p += 2) {
if (n % p == 0)
return n / p;
}
return 1;
}
int main() {
for (int n = 1; n < 101; ++n)... | program LargestProperDivisors
implicit none
integer i, lpd
do 10 i=1, 100
write (*,'(I3)',advance='no') lpd(i)
10 if (i/10*10 .eq. i) write (*,*)
end program
integer function lpd(n)
implicit none
integer n, i
if (n .le. 1) ... |
Translate the given C++ code snippet into Fortran without altering its behavior. | #include <iomanip>
#include <iostream>
bool equal_rises_and_falls(int n) {
int total = 0;
for (int previous_digit = -1; n > 0; n /= 10) {
int digit = n % 10;
if (previous_digit > digit)
++total;
else if (previous_digit >= 0 && previous_digit < digit)
--total;
... | PROGRAM A296712
INTEGER IDX, NUM, I
* Index and number start out at zero
IDX = 0
NUM = 0
* Find and write the first 200 numbers
WRITE (*,'(A)') 'The first 200 numbers are: '
DO 100 I = 1, 200
CALL NEXT NUM(IDX, NUM)
WRI... |
Translate this program into Fortran but keep the logic exactly as in C++. | #include <iostream>
#define _USE_MATH_DEFINES
#include <math.h>
double arcLength(double radius, double angle1, double angle2) {
return (360.0 - abs(angle2 - angle1)) * M_PI * radius / 180.0;
}
int main() {
auto al = arcLength(10.0, 10.0, 120.0);
std::cout << "arc length: " << al << '\n';
return 0;
}
| *-----------------------------------------------------------------------
* given: polar coordinates of two points on a circle of known radius
* find: length of the major arc between these points
*
*___Name_____Type___I/O___Description___________________________________
* RAD Real In Radius of circle, any ... |
Write the same algorithm in Fortran as shown in this C++ implementation. | #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... | INTEGER I
CHARACTER*666 I AM
I AM = "<col72
C 111111111122222222223333333333444444444455555555556666666666
C 123456789012345678901234567890123456789012345678901234567890123456789
1 ... |
Please provide an equivalent version of this C++ code in Fortran. | #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... | INTEGER I
CHARACTER*666 I AM
I AM = "<col72
C 111111111122222222223333333333444444444455555555556666666666
C 123456789012345678901234567890123456789012345678901234567890123456789
1 ... |
Rewrite this program in Fortran while keeping its functionality equivalent to the C++ version. |
class fifteenSolver{
const int Nr[16]{3,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3}, Nc[16]{3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2};
int n{},_n{}, N0[100]{},N3[100]{},N4[100]{};
unsigned long N2[100]{};
const bool fY(){
if (N4[n]<_n) return fN();
if (N2[n]==0x123456789abcdef0) {std::cout<<"Solution found in "<<n<<" moves ... | IF (NR.EQ.4) THEN
code specialised for NR = 4
ELSE IF (NR.EQ.3) THEN
code specialised for NR = 3
END IF
|
Write a version of this C++ function in Fortran with identical behavior. | int i;
void* address_of_i = &i;
| program test_loc
implicit none
integer :: i
real :: r
i = loc(r)
print *, i
end program
|
Write a version of this C++ function in Fortran with identical behavior. | #include <time.h>
#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>
typedef unsigned int uint;
using namespace std;
enum movDir { UP, DOWN, LEFT, RIGHT };
class tile
{
public:
tile() : val( 0 ), blocked( false ) {}
uint val;
bool blocked;
};
class g2048
{
public:
g2048() : d... | WRITE (MSG,1)
1 FORMAT ("|",<NC>(<W>("-"),"|"))
2 FORMAT ("|",<NC>(<W>(" "),"|"))
WRITE (MSG,22) ((" ",L1 = 1,W),"|",C = 1,NC)
22 FORMAT ("|",666A1)
4 FORMAT ("|",<NC - 1>(<W>("-"),"+"),<W>("-"),"|")
|
Rewrite the snippet below in Fortran so it works the same as the original C++ code. | while (true)
std::cout << "SPAM\n";
|
10 WRITE(*,*) 'SPAM'
GO TO 10
END
|
Maintain the same structure and functionality when rewriting this code in Fortran. | T* foo = new(arena) T;
| SUBROUTINE CHECK(A,N)
REAL A(:,:)
INTEGER N
REAL B(N,N)
INTEGER, ALLOCATABLE::TROUBLE(:)
INTEGER M
M = COUNT(A(1:N,1:N).LE.0)
ALLOCATE (TROUBLE(1:M**3))
DEALLOCATE(TROUBLE)
END SUBROUTINE CHECK
|
Port the provided C++ code into Fortran while preserving the original functionality. | T* foo = new(arena) T;
| SUBROUTINE CHECK(A,N)
REAL A(:,:)
INTEGER N
REAL B(N,N)
INTEGER, ALLOCATABLE::TROUBLE(:)
INTEGER M
M = COUNT(A(1:N,1:N).LE.0)
ALLOCATE (TROUBLE(1:M**3))
DEALLOCATE(TROUBLE)
END SUBROUTINE CHECK
|
Change the following C++ code into Fortran without altering its purpose. | #include <iostream>
#include <vector>
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *i... |
program f
implicit none
real, dimension(3,3) :: j, m
data j/ 2,-1, 1,-1,-2, 1,-1,-1,-1/
data m/2, 9, 4, 7, 5, 3, 6, 1, 8/
write(6,*) 'j example, determinant: ',det(j,3,-1)
write(6,*) 'j example, permanent: ',det(j,3,1)
write(6,*) 'maxima, determinant: ',det(m,3,-1)... |
Produce a functionally identical Fortran code for the snippet given in C++. | #include <iostream>
#include <vector>
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *i... |
program f
implicit none
real, dimension(3,3) :: j, m
data j/ 2,-1, 1,-1,-2, 1,-1,-1,-1/
data m/2, 9, 4, 7, 5, 3, 6, 1, 8/
write(6,*) 'j example, determinant: ',det(j,3,-1)
write(6,*) 'j example, permanent: ',det(j,3,1)
write(6,*) 'maxima, determinant: ',det(m,3,-1)... |
Change the following C++ code into Fortran without altering its purpose. | #include <iostream>
bool sameDigits(int n, int b) {
int f = n % b;
while ((n /= b) > 0) {
if (n % b != f) {
return false;
}
}
return true;
}
bool isBrazilian(int n) {
if (n < 7) return false;
if (n % 2 == 0)return true;
for (int b = 2; b < n - 1; b++) {
... |
PROGRAM BRAZILIAN
IMPLICIT NONE
INTEGER , PARAMETER :: MAX_NUMBER = 2000000 , NUMVARS = 20
LOGICAL , DIMENSION(1:MAX_NUMBER) :: b
INTEGER :: bcount
INTEGER :: bpos
CHARACTER(15) :: holder
CHARACTER(100) :: outline
LOGICAL , DIMENSION(1:MAX_NUMBER... |
Change the programming language of this snippet from C++ to Fortran without modifying what it does. | #include <iostream>
bool sameDigits(int n, int b) {
int f = n % b;
while ((n /= b) > 0) {
if (n % b != f) {
return false;
}
}
return true;
}
bool isBrazilian(int n) {
if (n < 7) return false;
if (n % 2 == 0)return true;
for (int b = 2; b < n - 1; b++) {
... |
PROGRAM BRAZILIAN
IMPLICIT NONE
INTEGER , PARAMETER :: MAX_NUMBER = 2000000 , NUMVARS = 20
LOGICAL , DIMENSION(1:MAX_NUMBER) :: b
INTEGER :: bcount
INTEGER :: bpos
CHARACTER(15) :: holder
CHARACTER(100) :: outline
LOGICAL , DIMENSION(1:MAX_NUMBER... |
Port the following code from C++ to Fortran with equivalent syntax and logic. | #include <iomanip>
#include <iostream>
unsigned int divisor_sum(unsigned int n) {
unsigned int total = 1, power = 2;
for (; (n & 1) == 0; power <<= 1, n >>= 1)
total += power;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int sum = 1;
for (power = p; n % p == 0;... | program DivSum
implicit none
integer i, j, col, divs(100)
do 10 i=1, 100, 1
10 divs(i) = 1
do 20 i=2, 100, 1
do 20 j=i, 100, i
20 divs(j) = divs(j) + i
col = 0
do 30 i=1, 100, 1
write (*,'(I4)',advance='no') divs(i)
... |
Change the programming language of this snippet from C++ to Fortran without modifying what it does. | #include <iomanip>
#include <iostream>
unsigned int divisor_sum(unsigned int n) {
unsigned int total = 1, power = 2;
for (; (n & 1) == 0; power <<= 1, n >>= 1)
total += power;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int sum = 1;
for (power = p; n % p == 0;... | program DivSum
implicit none
integer i, j, col, divs(100)
do 10 i=1, 100, 1
10 divs(i) = 1
do 20 i=2, 100, 1
do 20 j=i, 100, i
20 divs(j) = divs(j) + i
col = 0
do 30 i=1, 100, 1
write (*,'(I4)',advance='no') divs(i)
... |
Please provide an equivalent version of this C++ code in Fortran. |
#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 ... | program BeadSortTest
use iso_fortran_env
integer, dimension(7) :: a = (/ 7, 3, 5, 1, 2, 1, 20 /)
call beadsort(a)
print *, a
contains
subroutine beadsort(a)
integer, dimension(:), intent(inout) :: a
integer, dimension(maxval(a), maxval(a)) :: t
integer, dimension(maxval(a)) :: s
... |
Translate the given C++ code snippet into Fortran without altering its behavior. | 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!" <... | "bottle" // IF (B.NE.1) THEN "s" FI // " of beer"
|
Transform the following C++ implementation into Fortran, maintaining the same output and logic. | 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!" <... | "bottle" // IF (B.NE.1) THEN "s" FI // " of beer"
|
Convert the following code from C++ to Fortran, ensuring the logic remains intact. | #include <iomanip>
#include <iostream>
#include <vector>
constexpr int MU_MAX = 1'000'000;
std::vector<int> MU;
int mobiusFunction(int n) {
if (!MU.empty()) {
return MU[n];
}
MU.resize(MU_MAX + 1, 1);
int root = sqrt(MU_MAX);
for (int i = 2; i <= root; i++) {
if (MU[i] == 1)... | program moebius
use iso_fortran_env, only: output_unit
integer, parameter :: mu_max=1000000, line_break=20
integer, parameter :: sqroot=int(sqrt(real(mu_max)))
integer :: i, j
integer, dimension(mu_max) :: mu
mu = 1
do i = 2, sqroot
if (mu(i)... |
Produce a functionally identical Fortran code for the snippet given in C++. | #include <iomanip>
#include <iostream>
#include <vector>
std::vector<int> mertens_numbers(int max) {
std::vector<int> m(max + 1, 1);
for (int n = 2; n <= max; ++n) {
for (int k = 2; k <= n; ++k)
m[n] -= m[n / k];
}
return m;
}
int main() {
const int max = 1000;
auto m(merte... | program Mertens
implicit none
integer M(1000), n, k, zero, cross
C Generate Mertens numbers
M(1) = 1
do 10 n=2, 1000
M(n) = 1
do 10 k=2, n
M(n) = M(n) - M(n/k)
10 continue
C Print table
write (*,"('The first 99 Mertens num... |
Convert this C++ snippet to Fortran and keep its semantics consistent. | #include <cmath>
#include <iomanip>
#include <iostream>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
for (; (n & 1) == 0; n >>= 1)
++total;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p)
... | program divprod
implicit none
integer divis(50), i, j
do 10 i=1, 50
10 divis(i) = 1
do 20 i=1, 50
do 20 j=i, 50, i
20 divis(j) = divis(j)*i
do 30 i=1, 50
write (*,'(I10)',advance='no') divis(i)
30 if (i/5 .ne. (i-1)/5) write (*,... |
Change the programming language of this snippet from C++ to Fortran without modifying what it does. | #include <cmath>
#include <iomanip>
#include <iostream>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
for (; (n & 1) == 0; n >>= 1)
++total;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p)
... | program divprod
implicit none
integer divis(50), i, j
do 10 i=1, 50
10 divis(i) = 1
do 20 i=1, 50
do 20 j=i, 50, i
20 divis(j) = divis(j)*i
do 30 i=1, 50
write (*,'(I10)',advance='no') divis(i)
30 if (i/5 .ne. (i-1)/5) write (*,... |
Produce a functionally identical Fortran code for the snippet given in C++. | #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 };
... | MODULE Cards
IMPLICIT NONE
TYPE Card
CHARACTER(5) :: value
CHARACTER(8) :: suit
END TYPE Card
TYPE(Card) :: deck(52), hand(52)
TYPE(Card) :: temp
CHARACTER(5) :: pip(13) = (/"Two ", "Three", "Four ", "Five ", "Six ", "Seven", "Eight", "Nine ", "Ten ", &
"Jack ", "Q... |
Write the same code in Fortran as shown below in C++. | #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);
... | program twosum
implicit none
integer, parameter, dimension(5) :: list = (/ 0, 2, 11, 19, 90/)
integer, parameter :: target_val = 21
integer :: nelem
integer :: i, j
logical :: success = .false.
nelem = size(list)
outer:do i = 1,nelem
do j = i+1,nelem
success = list(i) + list(j) == target_... |
Change the following C++ code into Fortran without altering its purpose. | #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);
... | program twosum
implicit none
integer, parameter, dimension(5) :: list = (/ 0, 2, 11, 19, 90/)
integer, parameter :: target_val = 21
integer :: nelem
integer :: i, j
logical :: success = .false.
nelem = size(list)
outer:do i = 1,nelem
do j = i+1,nelem
success = list(i) + list(j) == target_... |
Preserve the algorithm and functionality while converting the code from C++ to Fortran. | #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: ";... | D = DAYNUM(Y,M,D)
DAYNUM(Y,M,D) = D
|
Translate the given C++ code snippet into Fortran without altering its behavior. | #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: ";... | D = DAYNUM(Y,M,D)
DAYNUM(Y,M,D) = D
|
Write the same code in Fortran as shown below in C++. | #include <iostream>
int circlesort(int* arr, int lo, int hi, int swaps) {
if(lo == hi) {
return swaps;
}
int high = hi;
int low = lo;
int mid = (high - low) / 2;
while(lo < hi) {
if(arr[lo] > arr[hi]) {
int temp = arr[lo];
arr[lo] = arr[hi];
a... |
module circlesort
implicit none
logical, private :: csr
public :: circle_sort
contains
recursive logical function csr(a, left, right,n) result(swapped)
implicit none
integer, intent(in) :: left, right,n
integer, intent(inout) :: a(n)
integer :: lo, hi, mid
integer :: temp
logi... |
Rewrite this program in Fortran while keeping its functionality equivalent to the C++ version. | #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... |
program circles
implicit none
double precision :: P1(2), P2(2), R
P1 = (/0.1234d0, 0.9876d0/)
P2 = (/0.8765d0,0.2345d0/)
R = 2.0d0
call print_centers(P1,P2,R)
P1 = (/0.0d0, 2.0d0/)
P2 = (/0.0d0,0.0d0/)
R = 1.0d0
call print_centers(P1,P2,R)
P1 = (/0.1234d0, 0.9876d0/)
P2 = (/0.1234d0, 0.9876d0/)
R = 2.0d0
call prin... |
Convert this C++ block to Fortran, preserving its control flow and logic. | #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... |
program circles
implicit none
double precision :: P1(2), P2(2), R
P1 = (/0.1234d0, 0.9876d0/)
P2 = (/0.8765d0,0.2345d0/)
R = 2.0d0
call print_centers(P1,P2,R)
P1 = (/0.0d0, 2.0d0/)
P2 = (/0.0d0,0.0d0/)
R = 1.0d0
call print_centers(P1,P2,R)
P1 = (/0.1234d0, 0.9876d0/)
P2 = (/0.1234d0, 0.9876d0/)
R = 2.0d0
call prin... |
Convert the following code from C++ to Fortran, ensuring the logic remains intact. | #include <iostream>
#include <fstream>
#include <string>
#include <tuple>
#include <vector>
#include <stdexcept>
#include <boost/regex.hpp>
struct Claim {
Claim(const std::string& name) : name_(name), pro_(0), against_(0), propats_(), againstpats_() {
}
void add_pro(const std::string... |
program cia
implicit none
character (len=256) :: s
integer :: ie, ei, cie, cei
integer :: ios
data ie, ei, cie, cei/4*0/
do while (.true.)
read(5,*,iostat = ios)s
if (0 .ne. ios) then
exit
endif
call lower_case(s)
cie = cie + occurrences(s, 'cie')
cei = cei + occu... |
Produce a functionally identical Fortran code for the snippet given in C++. | #include <iostream>
#include <fstream>
#include <string>
#include <tuple>
#include <vector>
#include <stdexcept>
#include <boost/regex.hpp>
struct Claim {
Claim(const std::string& name) : name_(name), pro_(0), against_(0), propats_(), againstpats_() {
}
void add_pro(const std::string... |
program cia
implicit none
character (len=256) :: s
integer :: ie, ei, cie, cei
integer :: ios
data ie, ei, cie, cei/4*0/
do while (.true.)
read(5,*,iostat = ios)s
if (0 .ne. ios) then
exit
endif
call lower_case(s)
cie = cie + occurrences(s, 'cie')
cei = cei + occu... |
Transform the following C++ implementation into Fortran, maintaining the same output and logic. | #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 abelian_sandpile_m
implicit none
private
public :: pile
type :: pile
integer, allocatable :: grid(:,:)
integer :: n(2)
contains
procedure :: init
procedure :: run
procedure, private :: process_node
procedure, private :: inside
end type
contai... |
Can you help me rewrite this code in Fortran instead of C++, keeping it the same logically? | #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 abelian_sandpile_m
implicit none
private
public :: pile
type :: pile
integer, allocatable :: grid(:,:)
integer :: n(2)
contains
procedure :: init
procedure :: run
procedure, private :: process_node
procedure, private :: inside
end type
contai... |
Can you help me rewrite this code in Fortran instead of C++, keeping it the same logically? | #include <iostream>
#include <string>
#include <cctype>
#include <cstdint>
typedef std::uint64_t integer;
const char* small[] = {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen"... | MODULE FOUR_IS_MAGIC
IMPLICIT NONE
CHARACTER(8), DIMENSION(20) :: SMALL_NUMS
CHARACTER(7), DIMENSION(8) :: TENS
CHARACTER(7) :: HUNDRED
CHARACTER(8) :: THOUSAND
CHARACTER(8) :: MILLION
CHARACTER(8) :: BILLION
CHARACTER(9) :: TRILLION
CHARACTER(11) :: QUADRILLION
CHARACTER(11) :: ... |
Convert this C++ block to Fortran, preserving its control flow and logic. | #include <iostream>
#include <string>
#include <sstream>
#include <valarray>
const std::string input {
"................................"
".#########.......########......."
".###...####.....####..####......"
".###....###.....###....###......"
".###...####.....###............."
".#########......###............."
".###.#... | A(2:N - 1) = (A(1:N - 2) + A(2:N - 1) + A(3:N))/3
|
Translate this program into Fortran but keep the logic exactly as in C++. | #include <iostream>
#include <string>
#include <time.h>
using namespace std;
namespace
{
void placeRandomly(char* p, char c)
{
int loc = rand() % 8;
if (!p[loc])
p[loc] = c;
else
placeRandomly(p, c);
}
int placeFirst(char* p, char c, int loc = 0)
{
while (p[loc]) ++loc;
p[loc] = ... | program chess960
implicit none
integer, pointer :: a,b,c,d,e,f,g,h
integer, target :: p(8)
a => p(1)
b => p(2)
c => p(3)
d => p(4)
e => p(5)
f => p(6)
g => p(7)
h => p(8)
king: do a=2,7
r1: do b=1,a-1 ... |
Port the provided C++ code into Fortran while preserving the original functionality. | #include <cstdint>
#include <iostream>
#include <string>
using integer = uint64_t;
integer divisor_sum(integer n) {
integer total = 1, power = 2;
for (; n % 2 == 0; power *= 2, n /= 2)
total += power;
for (integer p = 3; p * p <= n; p += 2) {
integer sum = 1;
for (power ... | MODULE FACTORSTUFF
Concocted by R.N.McLean, MMXV.
c INTEGER*4 I4LIMIT
c PARAMETER (I4LIMIT = 2147483647)
INTEGER*8 TOOBIG
PARAMETER (TOOBIG = 2**47)
INTEGER LOTS
PARAMETER (LOTS = 10000)
INTEGER*8 KNOWNSUM(LOTS)
CONTAINS
INTEGER*8 FUNCTION ... |
Preserve the algorithm and functionality while converting the code from C++ to Fortran. | #include <cstdint>
#include <iostream>
#include <string>
using integer = uint64_t;
integer divisor_sum(integer n) {
integer total = 1, power = 2;
for (; n % 2 == 0; power *= 2, n /= 2)
total += power;
for (integer p = 3; p * p <= n; p += 2) {
integer sum = 1;
for (power ... | MODULE FACTORSTUFF
Concocted by R.N.McLean, MMXV.
c INTEGER*4 I4LIMIT
c PARAMETER (I4LIMIT = 2147483647)
INTEGER*8 TOOBIG
PARAMETER (TOOBIG = 2**47)
INTEGER LOTS
PARAMETER (LOTS = 10000)
INTEGER*8 KNOWNSUM(LOTS)
CONTAINS
INTEGER*8 FUNCTION ... |
Port the following code from C++ to Fortran with equivalent syntax and logic. | #include <iostream>
bool isPrime(uint64_t n) {
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
uint64_t test = 5;
while (test * test < n) {
if (n % test == 0) return false;
test += 2;
if (n % test == 0) return false;
test += 4;... | program mersenne
use iso_fortran_env, only: output_unit, INT64
implicit none
integer, parameter :: l=INT64
integer(kind=l) :: base
integer :: pow
base = 2
do pow = 1, 32
if (is_prime(base-1)) then
write(output_unit,'(A2,x,I0,x,A3)') "2^", pow, "- 1"
... |
Generate a Fortran translation of this C++ snippet without changing its computational steps. | #include <iostream>
bool isPrime(uint64_t n) {
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
uint64_t test = 5;
while (test * test < n) {
if (n % test == 0) return false;
test += 2;
if (n % test == 0) return false;
test += 4;... | program mersenne
use iso_fortran_env, only: output_unit, INT64
implicit none
integer, parameter :: l=INT64
integer(kind=l) :: base
integer :: pow
base = 2
do pow = 1, 32
if (is_prime(base-1)) then
write(output_unit,'(A2,x,I0,x,A3)') "2^", pow, "- 1"
... |
Ensure the translated Fortran code behaves exactly like the original C++ snippet. | #include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include <vector>
template <typename T>
size_t indexOf(const std::vector<T> &v, const T &k) {
auto it = std::find(v.cbegin(), v.cend(), k);
if (it != v.cend()) {
return it - v.cbegin();
}
return -1;
}... |
PROGRAM POOKA
IMPLICIT NONE
INTEGER , PARAMETER :: NVARS = 25
REAL :: f1
REAL :: f2
INTEGER :: hits
INTEGER :: s
INTEGER :: TAXICAB
hits = 0
s = 0
f1 = SECOND()
DO WHILE ( hits<NVARS )
s = s + 1
hits = hits + TA... |
Please provide an equivalent version of this C++ code in Fortran. | #include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <sstream>
using namespace std;
#if 1
typedef unsigned long usingle;
typedef unsigned long long udouble;
const int word_len = 32;
#else
typedef unsigned short usingle;
typedef unsigned long udouble;
const int word_len = 16;
#endif
... | MODULE LAIROTCAF
CONTAINS
INTEGER*8 FUNCTION FACT(N)
INTEGER N
INTEGER I
FACT = 1
DO I = 2,N
FACT = FACT*I
IF (FACT.LE.0) STOP "Factorial: Overflow
END DO
END FUNCTION FACT
INTEGER*8 FUNCTION LFAC... |
Convert the following code from C++ to Fortran, ensuring the logic remains intact. | #include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <sstream>
using namespace std;
#if 1
typedef unsigned long usingle;
typedef unsigned long long udouble;
const int word_len = 32;
#else
typedef unsigned short usingle;
typedef unsigned long udouble;
const int word_len = 16;
#endif
... | MODULE LAIROTCAF
CONTAINS
INTEGER*8 FUNCTION FACT(N)
INTEGER N
INTEGER I
FACT = 1
DO I = 2,N
FACT = FACT*I
IF (FACT.LE.0) STOP "Factorial: Overflow
END DO
END FUNCTION FACT
INTEGER*8 FUNCTION LFAC... |
Can you help me rewrite this code in Fortran instead of C++, keeping it the same logically? | #include <cstdint>
#include <iomanip>
#include <iostream>
uint64_t digit_sum(uint64_t n, uint64_t sum) {
++sum;
while (n > 0 && n % 10 == 0) {
sum -= 9;
n /= 10;
}
return sum;
}
inline bool divisible(uint64_t n, uint64_t d) {
if ((d & 1) == 0 && (n & 1) == 1)
return false... | program nivengaps
implicit none
integer*8 prev /1/, gap /0/, sum /0/
integer*8 nividx /0/, niven /1/
integer gapidx /1/
character*13 idxfmt
character*14 nivfmt
write (*,*) 'Gap no Gap Niven index Niven number '
write (*,*) '------ --- ... |
Please provide an equivalent version of this C++ code in Fortran. | #include <iostream>
#include <iomanip>
using namespace std;
class ormConverter
{
public:
ormConverter() : AR( 0.7112f ), CE( 0.01f ), DI( 0.0254f ), FU( 0.3048f ), KI( 1000.0f ), LI( 0.00254f ), ME( 1.0f ),
MI( 7467.6f ), PI( 0.1778f ), SA( 2.1336f ), TO( 0.000254f ), VE( 0.04445f ), VR( 1066.8f ) {}
... | PROGRAM RUS
IMPLICIT NONE
REAL, PARAMETER:: E_m = 1.
REAL, PARAMETER:: E_mm = 1.E-3
REAL, PARAMETER:: E_km = 1.E+3
REAL, PARAMETER:: E_cm = 1.E-2
REAL, PARAMETER:: E_arshin = 71.12 * E_cm
REAL, PARAMETER:: E_fut = 3./7. * E_arshin
REAL, PARAMETER:: E_piad = 1./4. * E_arshin
REAL, PARAMETER:: E_vershok = 1./16.... |
Generate a Fortran translation of this C++ snippet without changing its computational steps. | #include <complex>
#include <math.h>
#include <iostream>
template<class Type>
struct Precision
{
public:
static Type GetEps()
{
return eps;
}
static void SetEps(Type e)
{
eps = e;
}
private:
static Type eps;
};
template<class Type> Type Precision<Type>::eps = static_cast<Type>(1E-7);
template<class DigT... | MODULE ZERMELO
CONTAINS
LOGICAL FUNCTION ISINTEGRAL(X)
REAL*8 X
INTEGER*8 N
IF (ISNAN(X)) THEN
ISINTEGRAL = .FALSE.
ELSE
N = KIDINT(X)
ISINTEGRAL = N .EQ. X
END IF
END FUNCTION ISINTEGRAL
... |
Produce a functionally identical Fortran code for the snippet given in C++. | #include <fstream>
#include <iostream>
#include <numeric>
#include <unistd.h>
#include <vector>
std::vector<size_t> get_cpu_times() {
std::ifstream proc_stat("/proc/stat");
proc_stat.ignore(5, ' ');
std::vector<size_t> times;
for (size_t time; proc_stat >> time; times.push_back(time));
return time... | Program CPUusage
implicit none
integer :: ios, i
integer :: oldidle, oldsum, sumtimes = 0
real :: percent = 0.
character(len = 4) lineID
integer, dimension(9) :: times = 0
write(*, *) 'CPU Usage'
write(*, *) 'Press Ctrl<C> to end'
do while (.true.)
open(unit = 7, file = '/p... |
Rewrite this program in Fortran while keeping its functionality equivalent to the C++ version. | #include <iostream>
template <typename T>
auto typeString(const T&) {
return typeid(T).name();
}
class C {};
struct S {};
int main() {
std::cout << typeString(1) << '\n';
std::cout << typeString(1L) << '\n';
std::cout << typeString(1.0f) << '\n';
std::cout << typeString(1.0) << '\n';
std::cou... | program input_type_detection_demo
implicit none
type text_block_t
character(len = 10000), allocatable :: lines(:)
end type text_block_t
type(text_block_t) :: text_block
integer :: i
call print_text ('Print me.')
allocate (text_block%lines(1:10))
do i = 1, 10
write (text_block%lines(i), '("... |
Write the same algorithm in Fortran as shown in this C++ implementation. | #include <gmpxx.h>
#include <algorithm>
#include <cassert>
#include <functional>
#include <iostream>
#include <vector>
using big_int = mpz_class;
const unsigned int small_primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23,
29, 31, 37, 41, 43, 47, 53, 59, 61,
... | USE PRIMEBAG
Calculates the largest "left-truncatable" digit sequence that is a prime number, in various bases.
INTEGER LBASE,MANY,ENUFF
PARAMETER (LBASE = 13, MANY = 66666, ENUFF = 66)
INTEGER NS,START(LBASE)
INTEGER NH,LH
INTEGER N,HORDEN(MANY)
INTEGER*1 HORDED(ENUFF,M... |
Port the following code from C++ to Fortran with equivalent syntax and logic. | #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::... | program solve_24
use helpers
implicit none
real :: vector(4), reals(4), p, q, r, s
integer :: numbers(4), n, i, j, k, a, b, c, d
character, parameter :: ops(4) = (/ '+', '-', '*', '/' /)
logical :: last
real,parameter :: eps = epsilon(1.0)
do n=1,12
c... |
Change the following C++ code into Fortran without altering its purpose. | #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::... | program solve_24
use helpers
implicit none
real :: vector(4), reals(4), p, q, r, s
integer :: numbers(4), n, i, j, k, a, b, c, d
character, parameter :: ops(4) = (/ '+', '-', '*', '/' /)
logical :: last
real,parameter :: eps = epsilon(1.0)
do n=1,12
c... |
Change the following C++ code into Fortran without altering its purpose. | #include <iostream>
#include <list>
int main ()
{
std::list<int> numbers {1, 5, 7, 0, 3, 2};
numbers.insert(numbers.begin(), 9);
numbers.insert(numbers.end(), 4);
auto it = std::next(numbers.begin(), numbers.size() / 2);
numbers.insert(it, 6);
for(const auto& i: numbers)
std::cout <... | module dlist
implicit none
type node
type(node), pointer :: next => null()
type(node), pointer :: prev => null()
integer :: data
end type node
type dll
type(node), pointer :: head => null()
type(node), pointer :: tail => null()
integer :: num_nodes = 0
end type dll
public ::... |
Produce a functionally identical Fortran code for the snippet given in C++. | #include <iostream>
struct SpecialVariables
{
int i = 0;
SpecialVariables& operator++()
{
this->i++;
return *this;
}
};
int main()
{
SpecialVariables sv;
auto sv2 = ++sv;
std::cout << " sv :" << sv.i << "\n sv2:" << sv2.i << "\n... | INQUIRE(FILE = FILENAME(1:L),EXIST = EXIST,
1 ERR = 666,IOSTAT = IOSTAT)
IF (EXIST) THEN
...etc.
|
Generate a Fortran translation of this C++ snippet without changing its computational steps. | #include <cstdint>
#include <iostream>
#include <sstream>
#include <gmpxx.h>
typedef mpz_class integer;
bool is_probably_prime(const integer& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;
}
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
... | PROGRAM PRIMORIALP
USE PRIMEBAG
USE BIGNUMBERS
TYPE(BIGNUM) B
INTEGER MAXF
PARAMETER (MAXF = 18000000)
INTEGER I
INTEGER FU,FD
INTEGER NHIT,HIT(666)
CHARACTER*4 WOT
CHARACTER*66 ALINE
REAL T0,T1
MSG = 6
WRITE (MSG,... |
Write the same algorithm in Fortran as shown in this C++ implementation. | #include <gmpxx.h>
#include <chrono>
using namespace std;
using namespace chrono;
void agm(mpf_class& rop1, mpf_class& rop2, const mpf_class& op1,
const mpf_class& op2)
{
rop1 = (op1 + op2) / 2;
rop2 = op1 * op2;
mpf_sqrt(rop2.get_mpf_t(), rop2.get_mpf_t());
}
int main(void)
{
auto st = ste... | program CalcPi
use iso_fortran_env, only: rf => real128
implicit none
real(rf) :: a,g,s,old_pi,new_pi
real(rf) :: a1,g1,s1
integer :: k,k1,i
old_pi = 0.0_rf;
a = 1.0_rf; g = 1.0_rf/sqrt(2.0_rf); s = 0.0_rf; k = 0
do i=1,100
call approx_pi_step(a,g,s,k,a1,g1,s1,k1)
... |
Port the provided C++ code into Fortran while preserving the original functionality. | #include <gmpxx.h>
#include <chrono>
using namespace std;
using namespace chrono;
void agm(mpf_class& rop1, mpf_class& rop2, const mpf_class& op1,
const mpf_class& op2)
{
rop1 = (op1 + op2) / 2;
rop2 = op1 * op2;
mpf_sqrt(rop2.get_mpf_t(), rop2.get_mpf_t());
}
int main(void)
{
auto st = ste... | program CalcPi
use iso_fortran_env, only: rf => real128
implicit none
real(rf) :: a,g,s,old_pi,new_pi
real(rf) :: a1,g1,s1
integer :: k,k1,i
old_pi = 0.0_rf;
a = 1.0_rf; g = 1.0_rf/sqrt(2.0_rf); s = 0.0_rf; k = 0
do i=1,100
call approx_pi_step(a,g,s,k,a1,g1,s1,k1)
... |
Generate a Fortran translation of this C++ snippet without changing its computational steps. | using System;
class Program {
static int l;
static int[] gp(int n) {
var c = new bool[n]; var r = new int[(int)(1.28 * n)];
l = 0; r[l++] = 2; r[l++] = 3; int j, d, lim = (int)Math.Sqrt(n);
for (int i = 9; i < n; i += 6) c[i] = true;
for (j = 5, d = 4; j < lim; j += (d = 6 - ... | B.DIGIT(I) = MOD(D,BIGBASE)
C = D/BIGBASE
|
Port the following code from C++ to Fortran with equivalent syntax and logic. | #include <iostream>
#include <iomanip>
#include <cmath>
namespace Rosetta {
template <int N>
class GaussLegendreQuadrature {
public:
enum {eDEGREE = N};
template <typename Function>
double integrate(double a, double b, Function f) {
double p = (b - a) / 2... |
program gauss
implicit none
integer, parameter :: p = 16
integer :: n = 10, k
real(kind=p), allocatable :: r(:,:)
real(kind=p) :: z, a, b, exact
do n = 1,20
a = -3; b = 3
r = gaussquad(n)
z = (b-a)/2*dot_product(r(2,:),exp((a+b)/2+r(1,:)*(b-a)/2))
exact = exp(3.0_p)-exp... |
Rewrite the snippet below in Fortran so it works the same as the original C++ code. | #include <iostream>
#include <string>
#include <random>
int main()
{
std::random_device rd;
std::uniform_int_distribution<int> dist(1, 10);
std::mt19937 mt(rd());
std::cout << "Random Number (hardware): " << dist(rd) << std::endl;
std::cout << "Mersenne twister (hardware seeded): " << dist(mt... | program rosetta_random
implicit none
integer, parameter :: rdp = kind(1.d0)
real(rdp) :: num
integer, allocatable :: seed(:)
integer :: un,n, istat
call random_seed(size = n)
allocate(seed(n))
open(newunit=un, file="/dev/urandom", access="stream", &
form="unformatted", action="read", s... |
Write a version of this C++ function in Fortran with identical behavior. | #include <iostream>
#include <string>
#include <random>
int main()
{
std::random_device rd;
std::uniform_int_distribution<int> dist(1, 10);
std::mt19937 mt(rd());
std::cout << "Random Number (hardware): " << dist(rd) << std::endl;
std::cout << "Mersenne twister (hardware seeded): " << dist(mt... | program rosetta_random
implicit none
integer, parameter :: rdp = kind(1.d0)
real(rdp) :: num
integer, allocatable :: seed(:)
integer :: un,n, istat
call random_seed(size = n)
allocate(seed(n))
open(newunit=un, file="/dev/urandom", access="stream", &
form="unformatted", action="read", s... |
Write the same algorithm in Fortran as shown in this C++ implementation. | #include <windows.h>
#include <ctime>
#include <string>
#include <iostream>
const int BMP_SIZE = 600;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
... | PROGRAM CHAOS
IMPLICIT NONE
REAL, DIMENSION(3):: KA, KN
REAL, DIMENSION(3):: DA, DB, DC
INTEGER:: I, Z
INTEGER, PARAMETER:: UT = 17
DA = (/ 0., 0., 0. /)
DB = (/ 600., 0., 0. /)
DC = (/ 500., 0., 400. /)
KA = (/ 500., 0., 100. /)
OPEN (UNIT = UT, FILE = 'aus.csv')
DO I=1, 1000000
Z = ZAHL()... |
Please provide an equivalent version of this C++ code in Fortran. | #include <windows.h>
#include <ctime>
#include <string>
#include <iostream>
const int BMP_SIZE = 600;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
... | PROGRAM CHAOS
IMPLICIT NONE
REAL, DIMENSION(3):: KA, KN
REAL, DIMENSION(3):: DA, DB, DC
INTEGER:: I, Z
INTEGER, PARAMETER:: UT = 17
DA = (/ 0., 0., 0. /)
DB = (/ 600., 0., 0. /)
DC = (/ 500., 0., 400. /)
KA = (/ 500., 0., 100. /)
OPEN (UNIT = UT, FILE = 'aus.csv')
DO I=1, 1000000
Z = ZAHL()... |
Keep all operations the same but rewrite the snippet in Fortran. | #include <iostream>
#include <cmath>
#include <cassert>
using namespace std;
#define PI 3.14159265359
class Vector
{
public:
Vector(double ix, double iy, char mode)
{
if(mode=='a')
{
x=ix*cos(iy);
y=ix*sin(iy);
}
else
{
x=ix;
... | MODULE ROSETTA_VECTOR
IMPLICIT NONE
TYPE VECTOR
REAL :: X, Y
END TYPE VECTOR
INTERFACE OPERATOR(+)
MODULE PROCEDURE VECTOR_ADD
END INTERFACE
INTERFACE OPERATOR(-)
MODULE PROCEDURE VECTOR_SUB
END INTERFACE
INTERFACE OPERATOR(/)
MODULE PROCEDURE VECTOR_DIV... |
Convert this C++ snippet to Fortran and keep its semantics consistent. | #include <vector>
#include <iostream>
#include <cmath>
#include <utility>
#include <map>
#include <iomanip>
bool isPrime( int i ) {
int stop = std::sqrt( static_cast<double>( i ) ) ;
for ( int d = 2 ; d <= stop ; d++ )
if ( i % d == 0 )
return false ;
return true ;
}
class Compare {
public :
Compa... | PROGRAM INHERIT
USE PRIMEBAG
INTEGER MBASE,P0,NHIC
PARAMETER (MBASE = 13, P0 = 2, NHIC = 100000000)
INTEGER N(0:MBASE - 1,0:MBASE - 1,2:MBASE)
INTEGER I,B,D1,D2
INTEGER P,PP
MSG = 6
WRITE (MSG,1) MBASE,P0,NHIC
1 FORMAT ("Working in base 2 to ",I0," co... |
Can you help me rewrite this code in Fortran instead of C++, keeping it the same logically? | #include <random>
#include <map>
#include <string>
#include <iostream>
#include <cmath>
#include <iomanip>
int main( ) {
std::random_device myseed ;
std::mt19937 engine ( myseed( ) ) ;
std::normal_distribution<> normDistri ( 2 , 3 ) ;
std::map<int , int> normalFreq ;
int sum = 0 ;
double mean = 0.0 ... | program Normal_Distribution
implicit none
integer, parameter :: i64 = selected_int_kind(18)
integer, parameter :: r64 = selected_real_kind(15)
integer(i64), parameter :: samples = 1000000_i64
real(r64) :: mean, stddev
real(r64) :: sumn = 0, sumnsq = 0
integer(i64) :: n = 0
integer(i64) :: bin(-50:50) ... |
Write the same code in Fortran as shown below in C++. | #include <iostream>
struct link
{
link* next;
int data;
link(int newItem, link* head)
: next{head}, data{newItem}{}
};
void PrintList(link* head)
{
if(!head) return;
std::cout << head->data << " ";
PrintList(head->next);
}
link* RemoveItem(int valueToRemove, link*&head)
{
for(link... | MODULE SIMPLELINKEDLIST
CONTAINS
SUBROUTINE LLREMOVE(LINK,X)
INTEGER LINK(0:)
INTEGER X
INTEGER IT
IT = 0
DO WHILE(LINK(IT).GT.0)
IF (LINK(IT).EQ.X) THEN
LINK(IT) = LINK(LINK(IT))
RETURN
... |
Preserve the algorithm and functionality while converting the code from C++ to Fortran. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns, scalar_type val... |
SUBROUTINE GJINV (A, LDA, N, B, LDB, IERR)
IMPLICIT NONE
INTEGER LDA, N, LDB, IERR
REAL A(LDA,N), B(LDB,N)
REAL EPS
PARAMETER (EPS = 1.1920929E-07)
INTEGER I, J, K, P
REAL F, TOL
IF ... |
Convert this C++ snippet to Fortran and keep its semantics consistent. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns, scalar_type val... |
SUBROUTINE GJINV (A, LDA, N, B, LDB, IERR)
IMPLICIT NONE
INTEGER LDA, N, LDB, IERR
REAL A(LDA,N), B(LDB,N)
REAL EPS
PARAMETER (EPS = 1.1920929E-07)
INTEGER I, J, K, P
REAL F, TOL
IF ... |
Convert this Go block to BBC_Basic, preserving its control flow and logic. |
package main
import "fmt"
func hailstone(n int, recycle []int) []int {
s := append(recycle[:0], n)
for n > 1 {
if n&1 == 0 {
n = n / 2
} else {
n = 3*n + 1
}
s = append(s, n)
}
return s
}
func libMain() {
seq := hailstone(27, nil)
fm... | seqlen% = FNhailstone(27)
PRINT "Sequence length for 27 is "; seqlen%
maxlen% = 0
FOR number% = 2 TO 100000
seqlen% = FNhailstone(number%)
IF seqlen% > maxlen% THEN
maxlen% = seqlen%
maxnum% = number%
ENDIF
NEXT
PRINT "The number with the l... |
Translate the given Go code snippet into BBC_Basic without altering its behavior. |
package main
import "fmt"
func hailstone(n int, recycle []int) []int {
s := append(recycle[:0], n)
for n > 1 {
if n&1 == 0 {
n = n / 2
} else {
n = 3*n + 1
}
s = append(s, n)
}
return s
}
func libMain() {
seq := hailstone(27, nil)
fm... | seqlen% = FNhailstone(27)
PRINT "Sequence length for 27 is "; seqlen%
maxlen% = 0
FOR number% = 2 TO 100000
seqlen% = FNhailstone(number%)
IF seqlen% > maxlen% THEN
maxlen% = seqlen%
maxnum% = number%
ENDIF
NEXT
PRINT "The number with the l... |
Port the provided Go code into BBC_Basic while preserving the original functionality. | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
)
func main() {
rect := image.Rect(0, 0, 320, 240)
img := image.NewRGBA(rect)
green := color.RGBA{0, 255, 0, 255}
draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src)
red := color.RGBA{255, 0, 0, ... | VDU 23, 22, 320; 240; 8, 8, 8, 0, 18, 0, 1, 25, 69, 100; 100;
|
Rewrite the snippet below in BBC_Basic so it works the same as the original Go code. | package main
import "github.com/fogleman/gg"
var colors = [8]string{
"000000",
"FF0000",
"00FF00",
"0000FF",
"FF00FF",
"00FFFF",
"FFFF00",
"FFFFFF",
}
func drawBars(dc *gg.Context) {
w := float64(dc.Width() / len(colors))
h := float64(dc.Height())
for i := range co... | SW_MAXIMIZE = 3
SYS "ShowWindow", @hwnd%, SW_MAXIMIZE
VDU 26
W% = @vdu%!208 / 4
H% = @vdu%!212 * 2
COLOUR 1,9
COLOUR 2,10
COLOUR 3,12
COLOUR 4,13
COLOUR 5,14
COLOUR 6,11
COLOUR 7,15
FOR C% = 0 TO 7
GCOL C%
... |
Change the programming language of this snippet from Go to BBC_Basic without modifying what it does. | package main
import (
"hash/fnv"
"log"
"math/rand"
"os"
"time"
)
var ph = []string{"Aristotle", "Kant", "Spinoza", "Marx", "Russell"}
const hunger = 3
const think = time.Second / 100
const eat = time.Second / 100
var fmt = log.New(os.Stdout, "", 0)
var done = make(chan bo... | INSTALL @lib$+"TIMERLIB"
nSeats% = 5
DIM Name$(nSeats%-1), Fork%(nSeats%-1), tID%(nSeats%-1), Leftie%(nSeats%-1)
Name$() = "Aristotle", "Kant", "Spinoza", "Marx", "Russell"
Fork%() = TRUE :
Leftie%(RND(nSeats%)-1) = TRUE :
tID%(0) = FN_ontimer(10, PROCphi... |
Maintain the same structure and functionality when rewriting this code in BBC_Basic. | package main
import "fmt"
func foo() int {
fmt.Println("let's foo...")
defer func() {
if e := recover(); e != nil {
fmt.Println("Recovered from", e)
}
}()
var a []int
a[12] = 0
fmt.Println("there's no point in going on.")
panic("never reached")
panic(fmt.Scan)
}
func main() {
foo()
fmt.Println("gla... | ON ERROR PROCerror(ERR, REPORT$) : END
ERROR 100, "User-generated exception"
END
DEF PROCerror(er%, rpt$)
PRINT "Exception occurred"
PRINT "Error number was " ; er%
PRINT "Error string was " rpt$
ENDPROC
|
Generate an equivalent BBC_Basic version of this Go code. | package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().Unix())
n := make([]rune, 4)
for i := range n {
n[i] = rune(rand.Intn(9) + '1')
}
fmt.Printf("Your numbers: %c\n", n)
fmt.Print("Enter RPN: ")
var expr string
fmt.Scan(&ex... |
DIM digits%(4), check%(4)
FOR choice% = 1 TO 4
digits%(choice%) = RND(9)
NEXT choice%
PRINT "Enter an equation (using all of, and only, the single digits ";
FOR index% = 1 TO 4
PRINT ; digits%(index%) ;
IF index%<>4 PRINT " " ;
NEXT
... |
Preserve the algorithm and functionality while converting the code from Go to BBC_Basic. | package main
func main() {
s := "immutable"
s[0] = 'a'
}
| DEF FNconst = 2.71828182845905
PRINT FNconst
FNconst = 1.234 :
|
Produce a functionally identical BBC_Basic code for the snippet given in Go. | package main
import(
"fmt"
"unsafe"
"reflect"
)
func pointer() {
fmt.Printf("Pointer:\n")
var i int
p := &i
fmt.Printf("Before:\n\t%v: %v, %v\n", p, *p, i)
*p = 3
fmt.Printf("After:\n\t%v: %v, %v\n", p, *p, i)
}
func slice() {
fmt.Printf("Slice:\n")
var a [10]byte
var h reflect.Sl... |
anInteger% = 12345678
PRINT "Original value =", anInteger%
address% = ^anInteger%
PRINT "Hexadecimal address = ";~address%
!address% = 87654321
PRINT "New value =", anInteger%
anInteger% = 55555555
... |
Produce a language-to-language conversion: from Go to BBC_Basic, same semantics. | package main
import "fmt"
var m map[int]int
func initMap() {
m = make(map[int]int)
m[1] = 1
m[2] = 1
}
func q(n int) (r int) {
if r = m[n]; r == 0 {
r = q(n-q(n-1)) + q(n-q(n-2))
m[n] = r
}
return
}
func main() {
initMap()
for n := 1; n <= 10; n++ {
show... | PRINT "First 10 terms of Q = " ;
FOR i% = 1 TO 10 : PRINT ;FNq(i%, c%) " "; : NEXT : PRINT
PRINT "1000th term = " ; FNq(1000, c%)
PRINT "100000th term = " ; FNq(100000, c%)
PRINT "Term is less than preceding term " ; c% " times"
END
DEF FNq(n%, RETURN c%)
LOCAL i%,... |
Port the provided Go code into BBC_Basic while preserving the original functionality. | package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Count("the three truths", "th"))
fmt.Println(strings.Count("ababababab", "abab"))
}
| tst$ = "the three truths"
sub$ = "th"
PRINT ; FNcountSubstring(tst$, sub$) " """ sub$ """ in """ tst$ """"
tst$ = "ababababab"
sub$ = "abab"
PRINT ; FNcountSubstring(tst$, sub$) " """ sub$ """ in """ tst$ """"
END
DEF FNcountSubstring(A$, B$)
LOCAL I%, N%
... |
Transform the following Go implementation into BBC_Basic, maintaining the same output and logic. | package main
import (
"github.com/gotk3/gotk3/gtk"
"log"
"math/rand"
"strconv"
"time"
)
func validateInput(window *gtk.Window, str1, str2 string) bool {
n, err := strconv.ParseFloat(str2, 64)
if len(str1) == 0 || err != nil || n != 75000 {
dialog := gtk.MessageDialogNew(
... | INSTALL @lib$+"WINLIB2"
INSTALL @lib$+"WINLIB5"
ES_NUMBER = 8192
form% = FN_newdialog("Rosetta Code", 100, 100, 100, 64, 8, 1000)
PROC_static(form%, "String:", 100, 8, 8, 30, 14, 0)
PROC_editbox(form%, "Example", 101, 40, 6, 52, 14, 0)
PROC_static(form%, "Number:", 102, ... |
Transform the following Go implementation into BBC_Basic, maintaining the same output and logic. | package main
import "fmt"
type expr struct {
x, y, z float64
c float64
}
func addExpr(a, b expr) expr {
return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}
}
func subExpr(a, b expr) expr {
return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}
}
func mulExpr(a expr, c flo... | INSTALL @lib$ + "ARRAYLIB"
DIM matrix(10,10), vector(10)
matrix() = \ a, b, c, d, e, f, g, h, x, y, z
\ 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
\ 1, 0,-1, 0, 0, ... |
Can you help me rewrite this code in BBC_Basic instead of Go, keeping it the same logically? | package main
import "fmt"
type expr struct {
x, y, z float64
c float64
}
func addExpr(a, b expr) expr {
return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}
}
func subExpr(a, b expr) expr {
return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}
}
func mulExpr(a expr, c flo... | INSTALL @lib$ + "ARRAYLIB"
DIM matrix(10,10), vector(10)
matrix() = \ a, b, c, d, e, f, g, h, x, y, z
\ 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
\ 1, 0,-1, 0, 0, ... |
Port the provided Go code into BBC_Basic while preserving the original functionality. | package main
import (
"log"
gc "code.google.com/p/goncurses"
)
func main() {
_, err := gc.Init()
if err != nil {
log.Fatal("init:", err)
}
defer gc.End()
gc.FlushInput()
}
| *FX 15,1
|
Write a version of this Go function in BBC_Basic with identical behavior. | package main
import (
"math"
"raster"
)
const (
width = 400
height = 300
depth = 8
angle = 12
length = 50
frac = .8
)
func main() {
g := raster.NewGrmap(width, height)
ftree(g, width/2, height*9/10, length, 0, depth)
g.Bitmap().WritePpmFile("ftree.ppm")
}
func ... | Spread = 25
Scale = 0.76
SizeX% = 400
SizeY% = 300
Depth% = 10
|
Convert this Go block to BBC_Basic, preserving its control flow and logic. | package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
const rps = "rps"
var msg = []string{
"Rock breaks scissors",
"Paper covers rock",
"Scissors cut paper",
}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println("Rock Paper Scissors")
fmt.Println("Enter r, p, or ... | PRINT"Welcome to the game of rock-paper-scissors"
PRINT "Each player guesses one of these three, and reveals it at the same time."
PRINT "Rock blunts scissors, which cut paper, which wraps stone."
PRINT "If both players choose the same, it is a draw!"
PRINT "When you've had enough, choose Q."
DIM rps%(2),g$(3)
g$()="ro... |
Change the following Go code into BBC_Basic without altering its purpose. | package config
import (
"errors"
"io"
"fmt"
"bytes"
"strings"
"io/ioutil"
)
var (
ENONE = errors.New("Requested value does not exist")
EBADTYPE = errors.New("Requested type and actual type do not match")
EBADVAL = errors.New("Value and type do not match")
)
type varError struct {
err error
n string
... | BOOL = 1
NAME = 2
ARRAY = 3
optfile$ = "options.cfg"
fullname$ = FNoption(optfile$, "FULLNAME", NAME)
favouritefruit$ = FNoption(optfile$, "FAVOURITEFRUIT", NAME)
needspeeling% = FNoption(optfile$, "NEEDSPEELING", BOOL)
seeds
!^otherfamily$() = FNoptio... |
Produce a language-to-language conversion: from Go to BBC_Basic, same semantics. | package dogs
import "fmt"
var dog = "Salt"
var Dog = "Pepper"
var DOG = "Mustard"
func PackageSees() map[*string]int {
fmt.Println("Package sees:", dog, Dog, DOG)
return map[*string]int{&dog: 1, &Dog: 1, &DOG: 1}
}
| dog$ = "Benjamin"
Dog$ = "Samba"
DOG$ = "Bernie"
PRINT "The three dogs are " dog$ ", " Dog$ " and " DOG$ "."
|
Rewrite this program in BBC_Basic while keeping its functionality equivalent to the Go version. | package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
stoogesort(a)
fmt.Println("after: ", a)
fmt.Println("nyuk nyuk nyuk")
}
func stoogesort(a []int) {
last := len(a) - 1
if a[last] < a[0] {
a[0], a[last] = a[last], a[0]
... | DIM test%(9)
test%() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1
PROCstoogesort(test%(), 0, DIM(test%(),1))
FOR i% = 0 TO 9
PRINT test%(i%) ;
NEXT
PRINT
END
DEF PROCstoogesort(l%(), i%, j%)
LOCAL t%
IF l%(j%) < l%(i%) SWAP l%(i%), l%(j%)
IF j% -... |
Please provide an equivalent version of this Go code in BBC_Basic. | import (
"fmt"
"os"
)
if err := os.Truncate("filename", newSize); err != nil {
fmt.Println(err)
}
| DEF PROCtruncate(file$, size%)
LOCAL file%
file% = OPENUP(file$)
IF file%=0 ERROR 100, "Could not open file"
EXT#file% = size%
CLOSE #file%
ENDPROC
|
Keep all operations the same but rewrite the snippet in BBC_Basic. | import (
"fmt"
"os"
)
if err := os.Truncate("filename", newSize); err != nil {
fmt.Println(err)
}
| DEF PROCtruncate(file$, size%)
LOCAL file%
file% = OPENUP(file$)
IF file%=0 ERROR 100, "Could not open file"
EXT#file% = size%
CLOSE #file%
ENDPROC
|
Port the following code from Go to BBC_Basic with equivalent syntax and logic. | package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 {
for i := inc; i < len(a); i++ {
j, temp := i, a[i]
for ; j >= inc && a[j-inc] > temp; j -= inc {
... | DIM test(9)
test() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1
PROCshellsort(test(), 10)
FOR i% = 0 TO 9
PRINT test(i%) ;
NEXT
PRINT
END
DEF PROCshellsort(a(), n%)
LOCAL h%, i%, j%, k
h% = n%
WHILE h%
IF h% = 2 h% = 1 ELSE h% DIV= 2.2
... |
Preserve the algorithm and functionality while converting the code from Go to BBC_Basic. | package main
import "fmt"
func main() {
h := []float64{-8, -9, -3, -1, -6, 7}
f := []float64{-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1}
g := []float64{24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,
96, 31, 55, 36, 29, -43, -7}
fmt.Println(h)
fmt.Println(deconv(... | *FLOAT 64
DIM h(5), f(15), g(20)
h() = -8,-9,-3,-1,-6,7
f() = -3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1
g() = 24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7
PROCdeconv(g(), f(), x())
PRINT "deconv(g,f) = " FNprintarray(x())
x() -= h() : IF SUM... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.