Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Generate a Pascal translation of this Java snippet without changing its computational steps. | public class ImplicitTypeConversion{
public static void main(String...args){
System.out.println( "Primitive conversions" );
byte by = -1;
short sh = by;
int in = sh;
long lo = in;
System.out.println( "byte value -1 to 3 integral types: " + lo );
float fl = ... | program implicitTypeConversion;
var
i: integer;
r: real;
begin
i := 42;
r := i
end.
|
Preserve the algorithm and functionality while converting the code from Java to Pascal. | import java.util.ArrayList;
import java.util.List;
public class SexyPrimes {
public static void main(String[] args) {
sieve();
int pairs = 0;
List<String> pairList = new ArrayList<>();
int triples = 0;
List<String> tripleList = new ArrayList<>();
int quadruplets = 0... | program SexyPrimes;
uses
SysUtils
,windows
const
ctext: array[0..5] of string = ('Primes',
'sexy prime pairs',
'sexy prime triplets',
'sexy prime quadruplets',
'sexy prime quintuplet',
'sexy prime sextuplet');
primeLmt = 1000 * 1000 + 35;
type
sxPrtpl = record
spCnt,
splast5Id... |
Change the following Java code into Pascal without altering its purpose. | import java.util.PriorityQueue;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
class CubeSum implements Comparable<CubeSum> {
public long x, y, value;
public CubeSum(long x, long y) {
this.x = x;
this.y = y;
this.value = x*x*x + y*y*y;
}
public String toString() {
return St... | program taxiCabNo;
uses
sysutils;
type
tPot3 = Uint32;
tPot3Sol = record
p3Sum : tPot3;
i1,j1,
i2,j2 : Word;
end;
tpPot3 = ^tPot3;
tpPot3Sol = ^tPot3Sol;
var
pot3 : array[0..1190] of tPot3;
AllSol : array[0..3000] of tpot3Sol;
AllSolHigh :... |
Keep all operations the same but rewrite the snippet in Pascal. | public class StrongAndWeakPrimes {
private static int MAX = 10_000_000 + 1000;
private static boolean[] primes = new boolean[MAX];
public static void main(String[] args) {
sieve();
System.out.println("First 36 strong primes:");
displayStrongPrimes(36);
for ( int n :... | program WeakPrim;
const
PrimeLimit = 1000*1000*1000;
type
tLimit = 0..(PrimeLimit-1) DIV 2;
tPrimCnt = 0..51*1000*1000;
tWeakStrong = record
strong,
balanced,
weak : NativeUint;
end;
var
primes: array [tLimit] of byte;
delta... |
Ensure the translated Pascal code behaves exactly like the original Java snippet. | import java.util.*;
public class StrangeUniquePrimeTriplets {
public static void main(String[] args) {
strangeUniquePrimeTriplets(30, true);
strangeUniquePrimeTriplets(1000, false);
}
private static void strangeUniquePrimeTriplets(int limit, boolean verbose) {
boolean[] sieve = pri... | program PrimeTriplets;
const
MAXZAHL = 100000;
MAXSUM = 3*MAXZAHL;
CountOfPrimes = trunc(MAXZAHL/(ln(MAXZAHL)-1.08))+100;
type
tChkprimes = array[0..MAXSUM] of byte;
var
Chkprimes:tChkprimes;
primes : array[0..CountOfPrimes]of Uint32;
count,primeCount:NativeInt;
procedure Init... |
Convert this Java block to Pascal, preserving its control flow and logic. | import java.util.*;
public class StrangeUniquePrimeTriplets {
public static void main(String[] args) {
strangeUniquePrimeTriplets(30, true);
strangeUniquePrimeTriplets(1000, false);
}
private static void strangeUniquePrimeTriplets(int limit, boolean verbose) {
boolean[] sieve = pri... | program PrimeTriplets;
const
MAXZAHL = 100000;
MAXSUM = 3*MAXZAHL;
CountOfPrimes = trunc(MAXZAHL/(ln(MAXZAHL)-1.08))+100;
type
tChkprimes = array[0..MAXSUM] of byte;
var
Chkprimes:tChkprimes;
primes : array[0..CountOfPrimes]of Uint32;
count,primeCount:NativeInt;
procedure Init... |
Convert this Java block to Pascal, preserving its control flow and logic. | public class Strange {
private static final boolean[] p = {
false, false, true, true, false,
true, false, true, false, false,
false, true, false, true, false,
false, false, true, false
};
public static boolean isstrange(long n) {
if (n < 10) return false;
... | begin % find numbers where the sum of the first 2 digits is prime and also %
% the sum of the second 2 digits is prime %
% considers numbers n where 100 < n < 500 %
logical procedure isSmallPrime ( integer value n ); n = 2 or ( odd( n ) and n n... |
Convert this Java block to Pascal, preserving its control flow and logic. | public class Strange {
private static final boolean[] p = {
false, false, true, true, false,
true, false, true, false, false,
false, true, false, true, false,
false, false, true, false
};
public static boolean isstrange(long n) {
if (n < 10) return false;
... | begin % find numbers where the sum of the first 2 digits is prime and also %
% the sum of the second 2 digits is prime %
% considers numbers n where 100 < n < 500 %
logical procedure isSmallPrime ( integer value n ); n = 2 or ( odd( n ) and n n... |
Rewrite the snippet below in Pascal so it works the same as the original Java code. | public class SmarandachePrimeDigitalSequence {
public static void main(String[] args) {
long s = getNextSmarandache(7);
System.out.printf("First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 ");
for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) {
if ( isP... | program Smarandache;
uses
sysutils,primsieve;
const
Digits : array[0..3] of Uint32 = (2,3,5,7);
var
i,j,pot10,DgtLimit,n,DgtCnt,v,cnt,LastPrime,Limit : NativeUint;
procedure Check(n:NativeUint);
var
p : NativeUint;
Begin
p := LastPrime;
while p< n do
p := nextprime;
if p = n then
begin
inc(cnt... |
Keep all operations the same but rewrite the snippet in Pascal. | import java.util.ArrayList;
import java.util.List;
public class SquareFree
{
private static List<Long> sieve(long limit) {
List<Long> primes = new ArrayList<Long>();
primes.add(2L);
boolean[] c = new boolean[(int)limit + 1];
long p = 3;
for (;;) {
long ... | program SquareFree;
const
BigLimit = 10*1000*1000*1000;
TRILLION = 1000*1000*1000*1000;
primeLmt = trunc(sqrt(TRILLION+150));
var
primes : array of byte;
sieve : array of byte;
procedure initPrimes;
var
i,lmt,dp :NativeInt;
Begin
setlength(primes,80000);
setlength(sieve,primeLmt);
sie... |
Write a version of this Java function in Pascal with identical behavior. | public class SelfNumbers {
private static final int MC = 103 * 1000 * 10000 + 11 * 9 + 1;
private static final boolean[] SV = new boolean[MC + 1];
private static void sieve() {
int[] dS = new int[10_000];
for (int a = 9, i = 9999; a >= 0; a--) {
for (int b = 9; b >= 0; b--) {
... | program selfnumb;
uses
sysutils;
const
MAXCOUNT =103*10000*10000+11*9+ 1;
type
tDigitSum9999 = array[0..9999] of Uint8;
tpDigitSum9999 = ^tDigitSum9999;
var
DigitSum9999 : tDigitSum9999;
sieve : array of boolean;
procedure dosieve;
var
pSieve : pBoolean;
pDigitSum :tpDigitSum9999;
n,c,b,a,... |
Generate a Pascal translation of this Java snippet without changing its computational steps. | public class NivenNumberGaps {
public static void main(String[] args) {
long prevGap = 0;
long prevN = 1;
long index = 0;
System.out.println("Gap Gap Index Starting Niven");
for ( long n = 2 ; n < 20_000_000_000l ; n++ ) {
if ( isNiven(n) ) {
... | program NivenGaps;
uses
sysutils,
strutils;
const
base = 10;
type
tNum = Uint64;
const
cntbasedigits = ((trunc(ln(High(tNum))/ln(base))+1) DIV 8 +1) *8;
type
tSumDigit = record
sdDigits : array[0..cntbasedigits-1] of byte;
sdNumber,
sdNivCoun... |
Change the following Java code into Pascal without altering its purpose. | import java.util.ArrayList;
import java.util.List;
public class PythagoreanQuadruples {
public static void main(String[] args) {
long d = 2200;
System.out.printf("Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n", d, getPythagoreanQuadruples(d));
... | program pythQuad;
const
MaxFactor =2200;
limit = MaxFactor*MaxFactor;
type
tIdx = NativeUint;
tSum = NativeUint;
var
check : array[0..MaxFactor] of boolean;
checkCnt : LongWord;
procedure Find2(s:tSum;idx:tSum);
var
s1 : tSum;
d : tSum;
begin
d := trunc(sqrt(s+idx*idx));
For idx := idx to M... |
Port the following code from Java to Pascal with equivalent syntax and logic. | import java.math.BigDecimal;
import java.util.List;
public class TestIntegerness {
private static boolean isLong(double d) {
return isLong(d, 0.0);
}
private static boolean isLong(double d, double tolerance) {
return (d - Math.floor(d)) <= tolerance || (Math.ceil(d) - d) <= tolerance;
... | program integerness(output);
function isRealIntegral(protected x: complex): Boolean;
begin
isRealIntegral := (im(x) = 0.0) and_then
(abs(re(x)) <= maxInt * 1.0) and_then
(trunc(re(x)) * 1.0 = re(x))
end;
function isIntegral(protected x: real): Boolean;
begin
isIntegral := isRealIntegral(cmplx(x * 1.0, 0.0... |
Preserve the algorithm and functionality while converting the code from Java to Pascal. | public class UlamNumbers {
public static void main(String[] args) {
long start = System.currentTimeMillis();
for (int n = 1; n <= 100000; n *= 10) {
System.out.printf("Ulam(%d) = %d\n", n, ulam(n));
}
long finish = System.currentTimeMillis();
System.out.printf("El... | program UlamNumbers;
uses
sysutils;
const
maxUlam = 100000;
Limit = 1351223+4000;
type
tCheck = Uint16;
tpCheck = pUint16;
var
Ulams : array of Uint32;
Check0 : array of tCheck;
Ulam_idx :NativeInt;
procedure init;
begin
setlength(Ulams,maxUlam);
Ulams[0] := 1;
Ulams[1] := 2;
Ulam_idx... |
Please provide an equivalent version of this Java code in Pascal. | public class TypeDetection {
private static void showType(Object a) {
if (a instanceof Integer) {
System.out.printf("'%s' is an integer\n", a);
} else if (a instanceof Double) {
System.out.printf("'%s' is a double\n", a);
} else if (a instanceof Character) {
... | program typedetectiondemo (input, output);
type
sourcetype = record case kind : (builtintext, filetext) of
builtintext : (i : integer);
filetext : (f : file of char);
end;
var
source : sourcetype;
input : file of char;
c : char;
procedure printt... |
Rewrite this program in Pascal while keeping its functionality equivalent to the Java version. | public class SafePrimes {
public static void main(String... args) {
int SIEVE_SIZE = 10_000_000;
boolean[] isComposite = new boolean[SIEVE_SIZE];
isComposite[0] = true;
isComposite[1] = true;
for (int n = 2; n < SIEVE_SIZE; n++) {
if (isComposite... | program Sophie;
uses
mp_prime,sysutils;
var
pS0,pS1:TSieve;
procedure SafeOrNoSavePrimeOut(totCnt:NativeInt;CntSafe:boolean);
var
cnt,pr,pSG,testPr : NativeUint;
begin
prime_sieve_reset(pS0,1);
prime_sieve_reset(pS1,1);
cnt := 0;
testPr := prime_sieve_next(pS1);
IF CntSafe then
Begin
writel... |
Maintain the same structure and functionality when rewriting this code in Pascal. | import java.util.function.Predicate;
public class PermutationsWithRepetitions {
public static void main(String[] args) {
char[] chars = {'a', 'b', 'c', 'd'};
permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);
}
static void permute(char[] a, int k, Predicate<int[]> decid... | program PermuWithRep;
uses
sysutils;
type
tPermData = record
mdTup_n,
mdTup_k:NativeInt;
mdTup :array of integer;
end;
function InitTuple(k,n:nativeInt):tPermData;
begin
with result do
Begin
IF k> 0 then
Begin
mdTup... |
Can you help me rewrite this code in Pascal instead of Java, keeping it the same logically? | import java.util.function.Predicate;
public class PermutationsWithRepetitions {
public static void main(String[] args) {
char[] chars = {'a', 'b', 'c', 'd'};
permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);
}
static void permute(char[] a, int k, Predicate<int[]> decid... | program PermuWithRep;
uses
sysutils;
type
tPermData = record
mdTup_n,
mdTup_k:NativeInt;
mdTup :array of integer;
end;
function InitTuple(k,n:nativeInt):tPermData;
begin
with result do
Begin
IF k> 0 then
Begin
mdTup... |
Write the same code in Pascal as shown below in Java. | import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
public class TruthTable {
public static void main( final String... args ) {
System.out.println( new Tru... | program TruthTables;
const
StackSize = 80;
type
TVariable = record
Name: Char;
Value: Boolean;
end;
TStackOfBool = record
Top: Integer;
Elements: array [0 .. StackSize - 1] of Boolean;
end;
var
Expression: string;
Variables: array [0 .. 23] of TVariable;
VariablesLength: Integer;
i:... |
Generate an equivalent Pascal version of this Java code. | import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
public class TruthTable {
public static void main( final String... args ) {
System.out.println( new Tru... | program TruthTables;
const
StackSize = 80;
type
TVariable = record
Name: Char;
Value: Boolean;
end;
TStackOfBool = record
Top: Integer;
Elements: array [0 .. StackSize - 1] of Boolean;
end;
var
Expression: string;
Variables: array [0 .. 23] of TVariable;
VariablesLength: Integer;
i:... |
Transform the following Java implementation into Pascal, maintaining the same output and logic. | import java.math.BigInteger;
public class SuperDNumbers {
public static void main(String[] args) {
for ( int i = 2 ; i <= 9 ; i++ ) {
superD(i, 10);
}
}
private static final void superD(int d, int max) {
long start = System.currentTimeMillis();
String test ... | program Super_D;
uses
sysutils,gmp;
var
s :ansistring;
s_comp : ansistring;
test : mpz_t;
i,j,dgt,cnt : NativeUint;
Begin
mpz_init(test);
for dgt := 2 to 9 do
Begin
i := dgt;
For j := 2 to dgt do
i := i*10+dgt;
s_comp := IntToStr(i);
writeln('Finding ',s_comp,' in ',dgt,'*i*... |
Port the provided Java code into Pascal while preserving the original functionality. | import java.math.BigInteger;
public class SuperDNumbers {
public static void main(String[] args) {
for ( int i = 2 ; i <= 9 ; i++ ) {
superD(i, 10);
}
}
private static final void superD(int d, int max) {
long start = System.currentTimeMillis();
String test ... | program Super_D;
uses
sysutils,gmp;
var
s :ansistring;
s_comp : ansistring;
test : mpz_t;
i,j,dgt,cnt : NativeUint;
Begin
mpz_init(test);
for dgt := 2 to 9 do
Begin
i := dgt;
For j := 2 to dgt do
i := i*10+dgt;
s_comp := IntToStr(i);
writeln('Finding ',s_comp,' in ',dgt,'*i*... |
Rewrite the snippet below in Pascal so it works the same as the original Java code. | import java.lang.reflect.Method;
class Example {
public int foo(int x) {
return 42 + x;
}
}
public class Main {
public static void main(String[] args) throws Exception {
Object example = new Example();
String name = "foo";
Class<?> clazz = example.getClass();
Method meth = clazz.getMethod(na... | program Test;
uses
SysUtils;
type
TProc = procedure of object;
TMyObj = class
strict private
FName: string;
public
constructor Create(const aName: string);
property Name: string read FName;
published
procedure Foo;
procedure Bar;
end;
constructor TMyObj.Create(const aName: string... |
Convert the following code from Java to Pascal, ensuring the logic remains intact. | import java.util.Arrays;
public class SpecialVariables {
public static void main(String[] args) {
System.out.println(Arrays.toString(args));
System.out.println(SpecialVariables.class);
System.out.println(System.getenv());
... | program foo(input, output);
begin
end.
|
Preserve the algorithm and functionality while converting the code from Java to Pascal. | import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Objects;
public class Calculate_Pi {
private static final MathContext con1024 = new MathContext(1024);
private static final BigDecimal bigTwo = new BigDecimal(2);
private static final BigDecimal bigFour = new BigDecimal(4);
pr... | program AgmForPi;
uses
SysUtils, Math, GMP;
const
MIN_DIGITS = 32;
MAX_DIGITS = 1000000;
var
Digits: Cardinal = 256;
procedure ReadInput;
var
UserDigits: Cardinal;
begin
if (ParamCount > 0) and TryStrToDWord(ParamStr(1), UserDigits) then
Digits := Min(MAX_DIGITS, Max(UserDigits, MIN_DIGITS));
f_se... |
Generate a Pascal translation of this Java snippet without changing its computational steps. | import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Objects;
public class Calculate_Pi {
private static final MathContext con1024 = new MathContext(1024);
private static final BigDecimal bigTwo = new BigDecimal(2);
private static final BigDecimal bigFour = new BigDecimal(4);
pr... | program AgmForPi;
uses
SysUtils, Math, GMP;
const
MIN_DIGITS = 32;
MAX_DIGITS = 1000000;
var
Digits: Cardinal = 256;
procedure ReadInput;
var
UserDigits: Cardinal;
begin
if (ParamCount > 0) and TryStrToDWord(ParamStr(1), UserDigits) then
Digits := Min(MAX_DIGITS, Max(UserDigits, MIN_DIGITS));
f_se... |
Port the provided Java code into Pascal while preserving the original functionality. | import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class WindowExample {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
public void run() {
createAndShow();
}
};
SwingUtilities.invokeLater(runnable);
}
static void createAndShow() {
... | program xshowwindow;
uses
xlib, x, ctypes;
procedure ModalShowX11Window(AMsg: string);
var
d: PDisplay;
w: TWindow;
e: TXEvent;
msg: PChar;
s: cint;
begin
msg := PChar(AMsg);
d := XOpenDisplay(nil);
if (d = nil) then
begin
WriteLn('[ModalShowX11Window] Cannot open display');
exit;
... |
Generate an equivalent Pascal version of this Java code. | import java.math.BigInteger;
public class PrimorialNumbers {
final static int sieveLimit = 1300_000;
static boolean[] notPrime = sieve(sieveLimit);
public static void main(String[] args) {
for (int i = 0; i < 10; i++)
System.out.printf("primorial(%d): %d%n", i, primorial(i));
... |
uses
sysutils,mp_types,mp_base,mp_prime,mp_numth;
var
x: mp_int;
t0,t1: TDateTime;
s: AnsiString;
var
i,cnt : NativeInt;
ctx :TPrimeContext;
begin
mp_init(x);
cnt := 1;
i := 2;
FindFirstPrime32(i,ctx);
i := 10;
t0 := time;
repeat
repeat
FindNextPrime32(ctx);
inc(cnt);
until ... |
Convert this Java snippet to Pascal and keep its semantics consistent. | import static java.lang.Math.*;
import java.util.function.Function;
public class Test {
final static int N = 5;
static double[] lroots = new double[N];
static double[] weight = new double[N];
static double[][] lcoef = new double[N + 1][N + 1];
static void legeCoef() {
lcoef[0][0] = lcoef[... | program Legendre(output);
const Order = 5;
Order1 = Order - 1;
Epsilon = 1E-12;
Pi = 3.1415926;
var Roots : array[0..Order1] of real;
Weight : array[0..Order1] of real;
LegCoef : array [0..Order,0..Order] of real;
I : integer;
function F(X:real) : real;
begin
F := Exp(X);
en... |
Generate a Pascal translation of this Java snippet without changing its computational steps. | public class CubanPrimes {
private static int MAX = 1_400_000;
private static boolean[] primes = new boolean[MAX];
public static void main(String[] args) {
preCompute();
cubanPrime(200, true);
for ( int i = 1 ; i <= 5 ; i++ ) {
int max = (int) Math.pow(10, i);
... | program CubanPrimes;
uses
primTrial;
const
COLUMNCOUNT = 10*10;
procedure FormOut(Cuban:Uint64;ColSize:Uint32);
var
s : String;
pI,pJ :pChar;
i,j : NativeInt;
Begin
str(Cuban,s);
i := length(s);
If i>3 then
Begin
j := i+ (i-1) div 3;
setlength(s,j);
pI := @s[i];
pJ := ... |
Keep all operations the same but rewrite the snippet in Pascal. | import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class ChaosGame extends JPanel {
static class ColoredPoint extends Point {
int colorIndex;
ColoredPoint(int x, int y, int idx) {
super(x, y);
colorIndex = ... | program ChaosGame;
uses
Graph, windows, math;
Function PointOfCircle(Angle: SmallInt; Radius: integer): TPoint;
var Ia: Double;
begin
Ia:=DegToRad(-Angle);
result.x:=round(cos(Ia)*Radius);
result.y:=round(sin(Ia)*Radius);
end;
var
GraphDev,GraphMode: smallint;
Triangle: array[0..2] of Tpoint;
Tr... |
Rewrite this program in Pascal while keeping its functionality equivalent to the Java version. | import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class ChaosGame extends JPanel {
static class ColoredPoint extends Point {
int colorIndex;
ColoredPoint(int x, int y, int idx) {
super(x, y);
colorIndex = ... | program ChaosGame;
uses
Graph, windows, math;
Function PointOfCircle(Angle: SmallInt; Radius: integer): TPoint;
var Ia: Double;
begin
Ia:=DegToRad(-Angle);
result.x:=round(cos(Ia)*Radius);
result.y:=round(sin(Ia)*Radius);
end;
var
GraphDev,GraphMode: smallint;
Triangle: array[0..2] of Tpoint;
Tr... |
Port the provided Java code into Pascal while preserving the original functionality. |
public final class ImprovedNoise {
static public double noise(double x, double y, double z) {
int X = (int)Math.floor(x) & 255,
Y = (int)Math.floor(y) & 255,
Z = (int)Math.floor(z) & 255;
x -= Math.floor(x);
y... | program perlinNoise;
uses
sysutils;
type
float64 = double;
const
p : array[0..255] of byte = (
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,
140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,
247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11,... |
Generate an equivalent Pascal version of this Java code. | import java.math.BigInteger;
import java.util.*;
public class Lychrel {
static Map<BigInteger, Tuple> cache = new HashMap<>();
static class Tuple {
final Boolean flag;
final BigInteger bi;
Tuple(boolean f, BigInteger b) {
flag = f;
bi = b;
}
}
... | program p196;
uses
SysUtils,classes;
const
cMAXNUM = 100*1000*1000;
cMaxCycle = 1500;
cChkDigit = 10;
MaxLen = 256;
cMaxDigit = MAXLEN-1;
type
TDigit = byte;
tpDigit =^TDigit;
tDigitArr = array[0..0] of tDigit;
tpDigitArr = ^tDigitArr;
TNumber = record
... |
Keep all operations the same but rewrite the snippet in Pascal. | import java.math.BigInteger;
import java.util.*;
public class Lychrel {
static Map<BigInteger, Tuple> cache = new HashMap<>();
static class Tuple {
final Boolean flag;
final BigInteger bi;
Tuple(boolean f, BigInteger b) {
flag = f;
bi = b;
}
}
... | program p196;
uses
SysUtils,classes;
const
cMAXNUM = 100*1000*1000;
cMaxCycle = 1500;
cChkDigit = 10;
MaxLen = 256;
cMaxDigit = MAXLEN-1;
type
TDigit = byte;
tpDigit =^TDigit;
tDigitArr = array[0..0] of tDigit;
tpDigitArr = ^tDigitArr;
TNumber = record
... |
Maintain the same structure and functionality when rewriting this code in Pascal. | public class FirstPowerOfTwo {
public static void main(String[] args) {
runTest(12, 1);
runTest(12, 2);
runTest(123, 45);
runTest(123, 12345);
runTest(123, 678910);
}
private static void runTest(int l, int n) {
System.out.printf("p(%d, %d) = %,d%n", l, n... | program Power2FirstDigits;
uses
sysutils,
strUtils;
const
ld10 :double = ln(2)/ln(10);
ld10 = 0.30102999566398119521373889472449;
function Numb2USA(const S: string): string;
var
i, NA: Integer;
begin
i := Length(S);
Result := S;
NA := 0;
while (i > 0) do
begin
if ((Length(Result) - i + ... |
Transform the following Java implementation into Pascal, maintaining the same output and logic. | public class FirstPowerOfTwo {
public static void main(String[] args) {
runTest(12, 1);
runTest(12, 2);
runTest(123, 45);
runTest(123, 12345);
runTest(123, 678910);
}
private static void runTest(int l, int n) {
System.out.printf("p(%d, %d) = %,d%n", l, n... | program Power2FirstDigits;
uses
sysutils,
strUtils;
const
ld10 :double = ln(2)/ln(10);
ld10 = 0.30102999566398119521373889472449;
function Numb2USA(const S: string): string;
var
i, NA: Integer;
begin
i := Length(S);
Result := S;
NA := 0;
while (i > 0) do
begin
if ((Length(Result) - i + ... |
Ensure the translated Pascal code behaves exactly like the original Java snippet. | import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class NSmoothNumbers {
public static void main(String[] args) {
System.out.printf("show the first 25 n-smooth numbers for n = 2 through n = 29%n");
int max = 25;
List<BigInteger> primes = new ArrayList<>... | program nSmoothNumbers(output);
const
primeCount = 538;
cardinalMax = 3888;
type
cardinal = 0..cardinalMax;
cardinals = set of cardinal;
cardinalPositive = 1..cardinalMax;
natural = 1..maxInt;
primeIndex = 1..primeCount;
list = array[primeIndex] of cardinal;
var
prime: list;
function primeFactoriz... |
Please provide an equivalent version of this Java code in Pascal. | import java.util.ArrayList;
import java.util.List;
public class BWT {
private static final String STX = "\u0002";
private static final String ETX = "\u0003";
private static String bwt(String s) {
if (s.contains(STX) || s.contains(ETX)) {
throw new IllegalArgumentException("String canno... | program BurrowsWheeler;
uses SysUtils;
const STR_BASE = 1;
type TComparison = -1..1;
procedure Encode( const input : string;
out encoded : string;
out index : integer);
var
n : integer;
perm : array of integer;
i, j, k : integer;
incr, v : integer;
... |
Change the programming language of this snippet from Java to Pascal without modifying what it does. | import java.util.ArrayList;
import java.util.List;
public class BWT {
private static final String STX = "\u0002";
private static final String ETX = "\u0003";
private static String bwt(String s) {
if (s.contains(STX) || s.contains(ETX)) {
throw new IllegalArgumentException("String canno... | program BurrowsWheeler;
uses SysUtils;
const STR_BASE = 1;
type TComparison = -1..1;
procedure Encode( const input : string;
out encoded : string;
out index : integer);
var
n : integer;
perm : array of integer;
i, j, k : integer;
incr, v : integer;
... |
Write a version of this Java function in Pascal with identical behavior. | import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Arrays;
import java.util.stream.LongStream;
public class FaulhabersTriangle {
private static final MathContext MC = new MathContext(256);
private static long gcd(long a, long b) {
if (b == 0) {
return a;
}
... | program FaulhaberTriangle;
uses uIntX, uEnums,
SysUtils;
function RationalToString( num, den : TIntX;
minWidth : integer) : string;
var
num1, den1, divisor : TIntX;
w : integer;
begin
divisor := TIntX.GCD( num, den);
num1 := TIntx.Divide( num, divisor, uEnums.dmClassic);
... |
Change the following Java code into Pascal without altering its purpose. | import java.math.BigInteger;
import java.util.Arrays;
class Test {
final static int nMax = 250;
final static int nBranches = 4;
static BigInteger[] rooted = new BigInteger[nMax + 1];
static BigInteger[] unrooted = new BigInteger[nMax + 1];
static BigInteger[] c = new BigInteger[nBranches];
st... | Program Paraffins;
uses
gmp;
const
max_n = 500;
branch = 4;
var
rooted, unrooted: array [0 .. max_n-1] of mpz_t;
c: array [0 .. branch-1] of mpz_t;
cnt, tmp: mpz_t;
n: integer;
fmt: pchar;
sum: integer;
procedure tree(br, n, l: integer; sum: integer; cnt: mpz_t);
var
b, m: integer;
begin... |
Transform the following Java implementation into Pascal, maintaining the same output and logic. | import java.math.BigInteger;
import java.util.Arrays;
class Test {
final static int nMax = 250;
final static int nBranches = 4;
static BigInteger[] rooted = new BigInteger[nMax + 1];
static BigInteger[] unrooted = new BigInteger[nMax + 1];
static BigInteger[] c = new BigInteger[nBranches];
st... | Program Paraffins;
uses
gmp;
const
max_n = 500;
branch = 4;
var
rooted, unrooted: array [0 .. max_n-1] of mpz_t;
c: array [0 .. branch-1] of mpz_t;
cnt, tmp: mpz_t;
n: integer;
fmt: pchar;
sum: integer;
procedure tree(br, n, l: integer; sum: integer; cnt: mpz_t);
var
b, m: integer;
begin... |
Preserve the algorithm and functionality while converting the code from Java to Pascal. | import java.util.Arrays;
import java.util.stream.IntStream;
public class FaulhabersFormula {
private static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
private static class Frac implements Comparable<Frac> {
private long num;
... | program Faulhaber;
uses SysUtils;
type TRational = record
Num, Den : integer;
end;
const
ZERO : TRational = ( Num: 0; Den : 1);
HALF : TRational = ( Num: 1; Den : 2);
function Rational( const a, b : integer) : TRational;
var
t, x, y : integer;
begin
if b <= 0 then raise SysUtils.Exc... |
Rewrite this program in Pascal while keeping its functionality equivalent to the Java version. | public class PrimeConspiracy {
public static void main(String[] args) {
final int limit = 1000_000;
final int sieveLimit = 15_500_000;
int[][] buckets = new int[10][10];
int prevDigit = 2;
boolean[] notPrime = sieve(sieveLimit);
for (int n = 3, primeCount = 1; prim... | program primCons;
const
PrimeLimit = 2038074748 DIV 2;
type
tLimit = 0..PrimeLimit;
tCntTransition = array[0..9,0..9] of NativeInt;
tCntTransRec = record
CTR_CntTrans:tCntTransition;
CTR_primCnt,
CTR_Limit : NativeInt;
end;
tCntTr... |
Generate an equivalent Pascal version of this Java code. | import static java.lang.Math.*;
import static java.util.Arrays.stream;
import java.util.Locale;
import java.util.function.DoubleSupplier;
import static java.util.stream.Collectors.joining;
import java.util.stream.DoubleStream;
import static java.util.stream.IntStream.range;
public class Test implements DoubleSupplier ... | Program Example40;
Uses Math;
type
tTestData = extended;
ttstfunc = function (mean, sd: tTestData): tTestData;
tExArray = Array of tTestData;
tSolution = record
SolExArr : tExArray;
SollowVal,
SolHighVal,
SolMean,
SolStdDiv... |
Ensure the translated Pascal code behaves exactly like the original Java snippet. | import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class MinimumNumberOnlyZeroAndOne {
public static void main(String[] args) {
for ( int n : getTestCases() ) {
BigInteger result = getA004290(n);
System.out.printf("A004290(%d) = %s = %s * %s%n"... | program B10_num;
uses
sysutils,gmp;
const
Limit = 256*256*8;
B10_4 = 10*10*10*10;
B10_5 = 10*B10_4;
B10_9 = B10_5*B10_4;
HexB10 : array[0..15] of NativeUint = (0000,0001,0010,0011,0100,0101,0110,0111,
1000,1001,1010,1011,1100,1101,1110,1111);
va... |
Maintain the same structure and functionality when rewriting this code in Pascal. | import java.util.*;
public class FiniteStateMachine {
private enum State {
Ready(true, "Deposit", "Quit"),
Waiting(true, "Select", "Refund"),
Dispensing(true, "Remove"),
Refunding(false, "Refunding"),
Exiting(false, "Quiting");
State(boolean exp, String... in) {
... |
program fsm1.pas;
uses sysutils;
type
state = (Null,Ready,Waiting,Refund,Dispense,Stop);
event = (Epsilon := 1,Deposit,Select,Cancel,Remove,Quit,Error);
Item = record
Name : string[12];
Stock: shortint;
price: currency;
end;
var
amountPaid, itemPrice , changeDue: currency;
I,J ... |
Produce a functionally identical Pascal code for the snippet given in Java. | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.IntConsumer;
import java.util.stream.Collectors;
public class Kosaraju {
static class Recursive<I> {
I func;
}
... | program Kosaraju_SCC;
type
TDigraph = array of array of Integer;
procedure PrintComponents(const g: TDigraph);
var
Visited: array of Boolean = nil;
RevPostOrder: array of Integer = nil;
gr: TDigraph = nil;
Counter, Next: Integer;
FirstItem: Boolean;
procedure Dfs1(aNode: Integer);
begin
Visited... |
Maintain the same structure and functionality when rewriting this code in Pascal. | import java.io.*;
import java.security.*;
import java.util.*;
public class SHA256MerkleTree {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("missing file argument");
System.exit(1);
}
try (InputStream in = new BufferedInputStream... | program SHA256_Merkle_tree;
uses
System.SysUtils,
System.Classes,
DCPsha256;
type
TmyByte = TArray<Byte>;
TmyHashes = TArray<TArray<byte>>;
uses
SysUtils,
Classes,
DCPsha256;
type
TmyByte = array of byte;
TmyHashes = array of TmyByte;
function SHA256(const Input: TmyByte; ... |
Write the same algorithm in Pascal as shown in this Java implementation. | import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class Perceptron extends JPanel {
class Trainer {
double[] inputs;
int answer;
Trainer(double x, double y, int a) {
inputs = new double[]{x, y, 1};
... | program Perceptron;
function targetOutput( a, b : integer ) : integer;
begin
if a * 2 + 1 < b then
targetOutput := 1
else
targetOutput := -1
end;
procedure showTargetOutput;
var x, y : integer;
begin
for y := 10 downto -9 do
begin
for x := -9 to 10 do
if targetOu... |
Generate a Pascal translation of this Java snippet without changing its computational steps. | import java.util.*;
public class PermutedMultiples {
public static void main(String[] args) {
for (int p = 100; ; p *= 10) {
int max = (p * 10) / 6;
for (int n = p + 2; n <= max; n += 3) {
if (sameDigits(n)) {
System.out.printf(" n = %d\n", n);
... | program euler52;
uses
sysutils;
const
BaseConvDgt :array[0..35] of char = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
MAXBASE = 12;
type
TUsedDigits = array[0..MAXBASE-1] of byte;
tDigitsInUse = set of 0..MAXBASE-1;
var
UsedDigits :tUsedDigits;
gblMaxDepth,
steps,
base,maxmul : NativeIn... |
Write the same algorithm in Pascal as shown in this Java implementation. | import java.util.*;
public class PermutedMultiples {
public static void main(String[] args) {
for (int p = 100; ; p *= 10) {
int max = (p * 10) / 6;
for (int n = p + 2; n <= max; n += 3) {
if (sameDigits(n)) {
System.out.printf(" n = %d\n", n);
... | program euler52;
uses
sysutils;
const
BaseConvDgt :array[0..35] of char = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
MAXBASE = 12;
type
TUsedDigits = array[0..MAXBASE-1] of byte;
tDigitsInUse = set of 0..MAXBASE-1;
var
UsedDigits :tUsedDigits;
gblMaxDepth,
steps,
base,maxmul : NativeIn... |
Produce a language-to-language conversion: from Java to Pascal, same semantics. | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PalindromicGapfulNumbers {
public static void main(String[] args) {
System.out.println("First 20 palindromic gapful numbers ending in:");
displayMap(getPalindromicGapfulEnding(20, 20));
... | program PalinGap;
type
tLimits = record
LoLmt,HiLmt:Uint64;
end;
const
base = 10;
var
delta : Array[0..9] of Uint64;
deltaBase: Array[0..9] of Uint64;
deltaMod : Array[0..9] of Uint32;
deltaModBase : Array[0..9] of Uint32;
IdxCnt : Array[0..9] of Uint32;
... |
Transform the following Java implementation into Pascal, maintaining the same output and logic. | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PalindromicGapfulNumbers {
public static void main(String[] args) {
System.out.println("First 20 palindromic gapful numbers ending in:");
displayMap(getPalindromicGapfulEnding(20, 20));
... | program PalinGap;
type
tLimits = record
LoLmt,HiLmt:Uint64;
end;
const
base = 10;
var
delta : Array[0..9] of Uint64;
deltaBase: Array[0..9] of Uint64;
deltaMod : Array[0..9] of Uint32;
deltaModBase : Array[0..9] of Uint32;
IdxCnt : Array[0..9] of Uint32;
... |
Rewrite the snippet below in Pascal so it works the same as the original Java code. | public class PrimeTriangle {
public static void main(String[] args) {
long start = System.currentTimeMillis();
for (int i = 2; i <= 20; ++i) {
int[] a = new int[i];
for (int j = 0; j < i; ++j)
a[j] = j + 1;
if (findRow(a, 0, i))
pri... | program PrimePyramid;
const
MAX = 21;
cMaxAlign32 = (((MAX-1)DIV 32)+1)*32-1;
type
tPrimeRange = set of 0..127;
var
SetOfPrimes :tPrimeRange =[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,
53,59,61,67,71,73,79,83,89,97,101,103,107,
109,113,127];
S... |
Produce a language-to-language conversion: from Java to Pascal, same semantics. | import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
public class SphenicNumbers {
public static void main(String[] args) {
final int limit = 1000000;
final int imax = limit / 6;
boolean[] sieve = primeSieve(imax + 1);
boolean[] sphenic = new boolean[limit + 1... | program sphenic;
const
Limit= 1000*1000;
type
tPrimesSieve = array of boolean;
tElement = Uint32;
tarrElement = array of tElement;
tpPrimes = pBoolean;
var
PrimeSieve : tPrimesSieve;
primes : tarrElement;
sphenics : tarrElement;
procedure ClearAll;
begin
setlength(sphenics,0);
setlength(... |
Translate this program into Pascal but keep the logic exactly as in Java. | import java.util.HashMap;
import java.util.Map;
public class PrimeGaps {
private Map<Integer, Integer> gapStarts = new HashMap<>();
private int lastPrime;
private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000);
public static void main(String[] args) {
final int limit = 100000... | program primesieve;
uses
sysutils;
const
smlPrimes :array [0..10] of Byte = (2,3,5,7,11,13,17,19,23,29,31);
maxPreSievePrime = 17;
sieveSize = 1 shl 15;
type
tSievePrim = record
svdeltaPrime:word;
svSivOfs:word;
svSivNum:LongWord;
... |
Convert the following code from Java to Pascal, ensuring the logic remains intact. | public class ColorfulNumbers {
private int count[] = new int[8];
private boolean used[] = new boolean[10];
private int largest = 0;
public static void main(String[] args) {
System.out.printf("Colorful numbers less than 100:\n");
for (int n = 0, count = 0; n < 100; ++n) {
if ... |
uses
sysutils;
const
EightFak = 1*2*3*4*5*6*7*8;
type
tDgt = Int8;
tpDgt = pInt8;
tDgtfield = array[0..7] of tdgt;
tpDgtfield = ^tDgtfield;
tPermfield = tDgtfield;
tAllPermDigits = array[0..EightFak] of tDgtfield;
tMarkNotColorful = array[0..EightFak-1] of byte;
tDat = Uin... |
Produce a functionally identical Pascal code for the snippet given in Java. | public class ColorfulNumbers {
private int count[] = new int[8];
private boolean used[] = new boolean[10];
private int largest = 0;
public static void main(String[] args) {
System.out.printf("Colorful numbers less than 100:\n");
for (int n = 0, count = 0; n < 100; ++n) {
if ... |
uses
sysutils;
const
EightFak = 1*2*3*4*5*6*7*8;
type
tDgt = Int8;
tpDgt = pInt8;
tDgtfield = array[0..7] of tdgt;
tpDgtfield = ^tDgtfield;
tPermfield = tDgtfield;
tAllPermDigits = array[0..EightFak] of tDgtfield;
tMarkNotColorful = array[0..EightFak-1] of byte;
tDat = Uin... |
Convert this Java snippet to Pascal and keep its semantics consistent. | import java.util.*;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
public class TopologicalSort2 {
public static void main(String[] args) {
String s = "top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1,"
+ "des1a,des1b,des1c,des1a1,des1a2,des... | program TopLevel;
uses
SysUtils, Generics.Collections;
type
TAdjList = class
InList,
OutList: THashSet<string>;
constructor Create;
destructor Destroy; override;
end;
TDigraph = class(TObjectDictionary<string, TAdjList>)
procedure AddNode(const s: string);
procedu... |
Can you help me rewrite this code in Pascal instead of Java, keeping it the same logically? | import java.util.*;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
public class TopologicalSort2 {
public static void main(String[] args) {
String s = "top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1,"
+ "des1a,des1b,des1c,des1a1,des1a2,des... | program TopLevel;
uses
SysUtils, Generics.Collections;
type
TAdjList = class
InList,
OutList: THashSet<string>;
constructor Create;
destructor Destroy; override;
end;
TDigraph = class(TObjectDictionary<string, TAdjList>)
procedure AddNode(const s: string);
procedu... |
Convert this Java snippet to Pascal and keep its semantics consistent. | public class PanBaseNonPrimes {
public static void main(String[] args) {
System.out.printf("First 50 prime pan-base composites:\n");
int count = 0;
for (long n = 2; count < 50; ++n) {
if (isPanBaseNonPrime(n)) {
++count;
System.out.printf("%3d%c", ... | program PanBaseNonPrime;
type
tDgts = 0..31;
tUsedDgts = set of tDgts;
tDecDigits = packed record
decdgts :array[0..20] of byte;
decmaxIdx :byte;
decmaxDgt :byte;
decUsedDgt :tUsedDgts;
end;
const
MAXLIMIT = 2500;... |
Port the provided Java code into Pascal while preserving the original functionality. | import java.util.*;
public class PracticalNumbers {
public static void main(String[] args) {
final int from = 1;
final int to = 333;
List<Integer> practical = new ArrayList<>();
for (int i = from; i <= to; ++i) {
if (isPractical(i))
practical.add(i);
... | program practicalnumbers;
uses
sysutils
,Windows
;
const
LOW_DIVS = 0;
HIGH_DIVS = 2048 - 1;
type
tdivs = record
DivsVal: array[LOW_DIVS..HIGH_DIVS] of Uint32;
DivsMaxIdx, DivsNum, DivsSumProp: NativeUInt;
end;
var
Divs: tDivs;
HasSum: array of byte;
procedure GetDivisors(va... |
Preserve the algorithm and functionality while converting the code from VB to Common_Lisp. | Sub foo1()
err.raise(vbObjectError + 1050)
End Sub
Sub foo2()
Error vbObjectError + 1051
End Sub
| (define-condition unexpected-odd-number (error)
((number :reader number :initarg :number))
(:report (lambda (condition stream)
(format stream "Unexpected odd number: ~w."
(number condition)))))
(defun get-number (&aux (n (random 100)))
(if (not (oddp n)) n
(error 'unexpected... |
Transform the following VB implementation into Common_Lisp, maintaining the same output and logic. | Sub Rosetta_24game()
Dim Digit(4) As Integer, i As Integer, iDigitCount As Integer
Dim stUserExpression As String
Dim stFailMessage As String, stFailDigits As String
Dim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean
Dim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant
G... | (define-condition choose-digits () ())
(define-condition bad-equation (error) ())
(defun 24-game ()
(let (chosen-digits)
(labels ((prompt ()
(format t "Chosen digits: ~{~D~^, ~}~%~
Enter expression (or `bye' to quit, `!' to choose new digits): "
cho... |
Change the programming language of this snippet from VB to Common_Lisp without modifying what it does. | Sub Rosetta_24game()
Dim Digit(4) As Integer, i As Integer, iDigitCount As Integer
Dim stUserExpression As String
Dim stFailMessage As String, stFailDigits As String
Dim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean
Dim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant
G... | (define-condition choose-digits () ())
(define-condition bad-equation (error) ())
(defun 24-game ()
(let (chosen-digits)
(labels ((prompt ()
(format t "Chosen digits: ~{~D~^, ~}~%~
Enter expression (or `bye' to quit, `!' to choose new digits): "
cho... |
Port the provided VB code into Common_Lisp while preserving the original functionality. | Public Q(100000) As Long
Public Sub HofstadterQ()
Dim n As Long, smaller As Long
Q(1) = 1
Q(2) = 1
For n = 3 To 100000
Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))
If Q(n) < Q(n - 1) Then smaller = smaller + 1
Next n
Debug.Print "First ten terms:"
For i = 1 To 10
Debug.Pr... | (defparameter *mm* (make-hash-table :test #'equal))
(defmacro defun-memoize (f (&rest args) &body body)
(defmacro hash () `(gethash (cons ',f (list ,@args)) *mm*))
(let ((h (gensym)))
`(defun ,f (,@args)
(let ((,h (hash)))
(if ,h ,h
(setf (hash) (progn ,@body)))))))
(defun-memoize q (n)
(if (... |
Change the programming language of this snippet from VB to Common_Lisp without modifying what it does. | Public Q(100000) As Long
Public Sub HofstadterQ()
Dim n As Long, smaller As Long
Q(1) = 1
Q(2) = 1
For n = 3 To 100000
Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))
If Q(n) < Q(n - 1) Then smaller = smaller + 1
Next n
Debug.Print "First ten terms:"
For i = 1 To 10
Debug.Pr... | (defparameter *mm* (make-hash-table :test #'equal))
(defmacro defun-memoize (f (&rest args) &body body)
(defmacro hash () `(gethash (cons ',f (list ,@args)) *mm*))
(let ((h (gensym)))
`(defun ,f (,@args)
(let ((,h (hash)))
(if ,h ,h
(setf (hash) (progn ,@body)))))))
(defun-memoize q (n)
(if (... |
Keep all operations the same but rewrite the snippet in Common_Lisp. | Public Sub Main()
Print countSubstring("the three truths", "th")
Print countSubstring("ababababab", "abab")
Print countSubString("zzzzzzzzzzzzzzz", "z")
End
Function countSubstring(s As String, search As String) As Integer
If s = "" Or search = "" Then Return 0
Dim count As Integer = 0, length As ... | (defun count-sub (str pat)
(loop with z = 0 with s = 0 while s do
(when (setf s (search pat str :start2 s))
(incf z) (incf s (length pat)))
finally (return z)))
(count-sub "ababa" "ab")
(count-sub "ababa" "aba")
|
Translate this program into Common_Lisp but keep the logic exactly as in VB. | max_sieve = 1e7
dim isprime(max_sieve)
//set up sieve
for i = 3 to max_sieve step 2
isprime(i) = 1
next i
isprime(2) = 1
for i = 3 to sqrt(max_sieve) step 2
if isprime(i) = 1 then
for j = i * i to max_sieve step i * 2
isprime(j) = 0
next j
fi
next i
for i = 2 to 61
carmichael3(i)
next i
end
s... | (ns example
(:gen-class))
(defn prime? [n]
" Prime number test (using Java) "
(.isProbablePrime (biginteger n) 16))
(defn carmichael [p1]
" Triplets of Carmichael primes, with first element prime p1 "
(if (prime? p1)
(into [] (for [h3 (range 2 p1)
:let [g (+ h3 p1)]
d (range 1 g)
... |
Translate this program into Common_Lisp but keep the logic exactly as in VB. | Sub BenfordLaw()
Dim BenResult(1 To 9) As Long
BENref = "30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%"
For Each c In Selection.Cells
If InStr(1, "-0123456789", Left(c, 1)) > 0 Then
For i = 1 To 9
If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For
Next
End If
Next
Total= ... | (ns example
(:gen-class))
(defn abs [x]
(if (> x 0)
x
(- x)))
(defn calc-benford-stats [digits]
" Frequencies of digits in data "
(let [y (frequencies digits)
tot (reduce + (vals y))]
[y tot]))
(defn show-benford-stats [v]
" Prints in percent the actual, Benford expected, and differenc... |
Write the same code in Common_Lisp as shown below in VB. | Sub BenfordLaw()
Dim BenResult(1 To 9) As Long
BENref = "30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%"
For Each c In Selection.Cells
If InStr(1, "-0123456789", Left(c, 1)) > 0 Then
For i = 1 To 9
If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For
Next
End If
Next
Total= ... | (ns example
(:gen-class))
(defn abs [x]
(if (> x 0)
x
(- x)))
(defn calc-benford-stats [digits]
" Frequencies of digits in data "
(let [y (frequencies digits)
tot (reduce + (vals y))]
[y tot]))
(defn show-benford-stats [v]
" Prints in percent the actual, Benford expected, and differenc... |
Produce a language-to-language conversion: from VB to Common_Lisp, same semantics. | type TSettings extends QObject
FullName as string
FavouriteFruit as string
NeedSpelling as integer
SeedsRemoved as integer
OtherFamily as QStringlist
Constructor
FullName = ""
FavouriteFruit = ""
NeedSpelling = 0
SeedsRemoved = 0
OtherFamily.clear
... | (ql:quickload :parser-combinators)
(defpackage :read-config
(:use :cl :parser-combinators))
(in-package :read-config)
(defun trim-space (string)
(string-trim '(#\space #\tab) string))
(defun any-but1? (except)
(named-seq? (<- res (many1? (except? (item) except)))
(coerce res 'string)))
(defun v... |
Write a version of this VB function in Common_Lisp with identical behavior. | Public Sub case_sensitivity()
Dim DOG As String
DOG = "Benjamin"
DOG = "Samba"
DOG = "Bernie"
Debug.Print "There is just one dog named " & DOG
End Sub
| CL-USER> (let* ((dog "Benjamin") (Dog "Samba") (DOG "Bernie"))
(format nil "There is just one dog named ~a." dog))
"There is just one dog named Bernie."
|
Generate a Common_Lisp translation of this VB snippet without changing its computational steps. | Sub arrShellSort(ByVal arrData As Variant)
Dim lngHold, lngGap As Long
Dim lngCount, lngMin, lngMax As Long
Dim varItem As Variant
lngMin = LBound(arrData)
lngMax = UBound(arrData)
lngGap = lngMin
Do While (lngGap < lngMax)
lngGap = 3 * lngGap + 1
Loop
Do While (lngGap > 1)
lngGap = lngGap ... | (defun gap-insertion-sort (array predicate gap)
(let ((length (length array)))
(if (< length 2) array
(do ((i 1 (1+ i))) ((eql i length) array)
(do ((x (aref array i))
(j i (- j gap)))
((or (< (- j gap) 0)
(not (funcall predicate x (aref array (1- j)))))
... |
Change the following VB code into Common_Lisp without altering its purpose. | Function read_line(filepath,n)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(filepath,1)
arrLines = Split(objFile.ReadAll,vbCrLf)
If UBound(arrLines) >= n-1 Then
If arrLines(n-1) <> "" Then
read_line = arrLines(n-1)
Else
read_line = "Line " & n & " is null."
E... | (defun read-nth-line (file n &aux (line-number 0))
"Read the nth line from a text file. The first line has the number 1"
(assert (> n 0) (n))
(with-open-file (stream file)
(loop for line = (read-line stream nil nil)
if (and (null line) (< line-number n))
do (error "file ~a is too short, ... |
Port the provided VB code into Common_Lisp while preserving the original functionality. | Function read_line(filepath,n)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(filepath,1)
arrLines = Split(objFile.ReadAll,vbCrLf)
If UBound(arrLines) >= n-1 Then
If arrLines(n-1) <> "" Then
read_line = arrLines(n-1)
Else
read_line = "Line " & n & " is null."
E... | (defun read-nth-line (file n &aux (line-number 0))
"Read the nth line from a text file. The first line has the number 1"
(assert (> n 0) (n))
(with-open-file (stream file)
(loop for line = (read-line stream nil nil)
if (and (null line) (< line-number n))
do (error "file ~a is too short, ... |
Please provide an equivalent version of this VB code in Common_Lisp. | Dim URL As String = "http://foo bar/"
URL = EncodeURLComponent(URL)
Print(URL)
| (defun needs-encoding-p (char)
(not (digit-char-p char 36)))
(defun encode-char (char)
(format nil "%~2,'0X" (char-code char)))
(defun url-encode (url)
(apply #'concatenate 'string
(map 'list (lambda (char)
(if (needs-encoding-p char)
(encode-char char)
... |
Preserve the algorithm and functionality while converting the code from VB to Common_Lisp. | Dim URL As String = "http://foo bar/"
URL = EncodeURLComponent(URL)
Print(URL)
| (defun needs-encoding-p (char)
(not (digit-char-p char 36)))
(defun encode-char (char)
(format nil "%~2,'0X" (char-code char)))
(defun url-encode (url)
(apply #'concatenate 'string
(map 'list (lambda (char)
(if (needs-encoding-p char)
(encode-char char)
... |
Convert this VB block to Common_Lisp, preserving its control flow and logic. | Option Base 1
Private Function pivotize(m As Variant) As Variant
Dim n As Integer: n = UBound(m)
Dim im() As Double
ReDim im(n, n)
For i = 1 To n
For j = 1 To n
im(i, j) = 0
Next j
im(i, i) = 1
Next i
For i = 1 To n
mx = Abs(m(i, i))
row_ = i
... |
(defun eye (n)
(let ((I (make-array `(,n ,n) :initial-element 0)))
(loop for j from 0 to (- n 1) do
(setf (aref I j j) 1))
I))
(defun swap-rows (A l k)
(let* ((n (cadr (array-dimensions A)))
(row (make-array n :initial-element 0)))
(loop for j from 0 to (- n 1) do
(setf (... |
Change the programming language of this snippet from VB to Common_Lisp without modifying what it does. | Private Sub optional_parameters(theRange As String, _
Optional ordering As Integer = 0, _
Optional column As Integer = 1, _
Optional reverse As Integer = 1)
ActiveSheet.Sort.SortFields.Clear
ActiveSheet.Sort.SortFields.Add _
Key:=Range(theRange).Columns(column), _
SortOn:... | (defun sort-table (table &key (ordering #'string<)
(column 0)
reverse)
(sort table (if reverse
(complement ordering)
ordering)
:key (lambda (row) (elt row column))))
|
Convert this VB snippet to Common_Lisp and keep its semantics consistent. | dim s(10)
print "Enter 11 numbers."
for i = 0 to 10
print i +1;
input " => "; s(i)
next i
print
for i = 10 to 0 step -1
print "f("; s(i); ") = ";
r = f(s(i))
if r > 400 then
print "-=< overflow >=-"
else
print r
end if
next i
end
function f(n)
f = sqr(abs(n)) + 5 * n * n * n
end function
| (defun read-numbers ()
(princ "Enter 11 numbers (space-separated): ")
(let ((numbers '()))
(dotimes (i 11 numbers)
(push (read) numbers))))
(defun trabb-pardo-knuth (func overflowp)
(let ((S (read-numbers)))
(format T "~{~a~%~}"
(substitute-if "Overflow!" overflowp (mapcar func S)))))
... |
Rewrite this program in Common_Lisp while keeping its functionality equivalent to the VB version. | Function rep_string(s)
max_len = Int(Len(s)/2)
tmp = ""
If max_len = 0 Then
rep_string = "No Repeating String"
Exit Function
End If
For i = 1 To max_len
If InStr(i+1,s,tmp & Mid(s,i,1))Then
tmp = tmp & Mid(s,i,1)
Else
Exit For
End If
Next
Do While Len(tmp) > 0
If Mid(s,Len(tmp)+1,Len(tmp)) = tm... | (defn rep-string [s]
(let [len (count s)
first-half (subs s 0 (/ len 2))
test-group (take-while seq (iterate butlast first-half))
test-reptd (map (comp #(take len %) cycle) test-group)]
(some #(= (seq s) %) test-reptd)))
|
Maintain the same structure and functionality when rewriting this code in Common_Lisp. | for j = asc("a") to asc("z")
print chr(j);
next j
print
for j= asc("A") to Asc("Z")
print chr(j);
next j
end
| (flet ((do-case (converter)
(loop for radix from 10 to 35
for char = (funcall converter (digit-char radix 36)) do
(format t "~&~8D #\\~24A ~S"
(char-code char) (char-name char) char))))
(format t "~&
(do-case #'char-downc... |
Convert this VB block to Common_Lisp, preserving its control flow and logic. | Option Explicit
Function JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double
Dim dummyChar, match1, match2 As String
Dim i, f, t, j, m, l, s1, s2, limit As Integer
i = 1
Do
dummyChar = Chr(i)
i = i + 1
Loop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0
s1 = Len(t... | (let ()
(defun jaro (s1 s2)
(let (mw mflags1 mflags2 fn-reset-mflags fn-reset-all-mflags fn-cnt-trans)
(setq mflags1 (make-vector (length s1) nil))
(setq mflags2 (make-vector (length s2) nil))
(setq mw (1- (/ (max (length s1) (length s2)) 2)))
(setq fn-reset-mflags
(lambda (idx)
... |
Change the following VB code into Common_Lisp without altering its purpose. | Private Function OddWordFirst(W As String) As String
Dim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String
count = 1
Do
flag = Not flag
l = FindNextPunct(i, W) - count + 1
If flag Then
temp = temp & ExtractWord(W, count, l)
Else
temp = temp & R... | (defun odd-word (s)
(let ((stream (make-string-input-stream s)))
(loop for forwardp = t then (not forwardp)
while (if forwardp
(forward stream)
(funcall (backward stream)))) ))
(defun forward (stream)
(let ((ch (read-char stream)))
(write-char ch)
(if (... |
Maintain the same structure and functionality when rewriting this code in Common_Lisp. | Function IsSelfDescribing(n)
IsSelfDescribing = False
Set digit = CreateObject("Scripting.Dictionary")
For i = 1 To Len(n)
k = Mid(n,i,1)
If digit.Exists(k) Then
digit.Item(k) = digit.Item(k) + 1
Else
digit.Add k,1
End If
Next
c = 0
For j = 0 To Len(n)-1
l = Mid(n,j+1,1)
If digit.Exists(CStr(j)... | (defun to-ascii (str) (mapcar #'char-code (coerce str 'list)))
(defun to-digits (n)
(mapcar #'(lambda(v) (- v 48)) (to-ascii (princ-to-string n))))
(defun count-digits (n)
(do
((counts (make-array '(10) :initial-contents '(0 0 0 0 0 0 0 0 0 0)))
(curlist (to-digits n) (cdr curlist)))
((null cu... |
Convert the following code from VB to Common_Lisp, ensuring the logic remains intact. | Sub Main_Contain()
Dim ListeWords() As String, Book As String, i As Long, out() As String, count As Integer
Book = Read_File("C:\Users\" & Environ("Username") & "\Desktop\unixdict.txt")
ListeWords = Split(Book, vbNewLine)
For i = LBound(ListeWords) To UBound(ListeWords)
If Len(ListeWords(i)) > 11 Th... | (defun print-words-containing-substring (str len path)
(with-open-file (s path :direction :input)
(do ((line (read-line s nil :eof) (read-line s nil :eof)))
((eql line :eof)) (when (and (> (length line) len)
(search str line))
(format t "~a~... |
Convert this VB block to Common_Lisp, preserving its control flow and logic. | Dim TheAddress as long
Dim SecVar as byte
Dim MyVar as byte
MyVar = 10
TheAddress = varptr(MyVar)
MEMSET(TheAddress, 102, SizeOf(byte))
showmessage "MyVar = " + str$(MyVar)
MEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))
showmessage "SecVar = " + str$(SecVar)
|
(defun swap (ref-left ref-right)
(with-refs ((l ref-left) (r ref-right))
(psetf l r r l)))
(defvar *x* 42)
(defvar *y* 0)
(swap (ref *x*) (ref *y*))
|
Generate an equivalent Common_Lisp version of this VB code. | Do
Debug.Print "SPAM"
Loop
| (defun spam ()
(declare (xargs :mode :program))
(if nil
nil
(prog2$ (cw "SPAM~%")
(spam))))
|
Rewrite the snippet below in Common_Lisp so it works the same as the original VB code. | Module Module1
Sub Main()
Dim bufferHeight = Console.BufferHeight
Dim bufferWidth = Console.BufferWidth
Dim windowHeight = Console.WindowHeight
Dim windowWidth = Console.WindowWidth
Console.Write("Buffer Height: ")
Console.WriteLine(bufferHeight)
Console.Wri... | (defun screen-dimensions ()
(with-screen (scr :input-blocking t :input-echoing nil :cursor-visible nil)
(let ((width (width scr))
(height (height scr)))
(format scr "The current terminal screen is ~A lines high, ~A columns wide.~%~%" height width)
(refresh scr)
(get-char scr... |
Write a version of this VB function in Common_Lisp with identical behavior. | Module Module1
Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,)
Dim length = a.GetLength(0) - 1
Dim result(length - 1, length - 1) As Double
For i = 1 To length
For j = 1 To length
If i < x AndAlso j < y Then
result(i - ... | (defun determinant (rows &optional (skip-cols nil))
(let* ((result 0) (sgn -1))
(dotimes (col (length (car rows)) result)
(unless (member col skip-cols)
(if (null (cdr rows))
(return-from determinant (elt (car rows) col))
(incf result (* (setq sgn (- sgn)) (elt (car rows) col) (d... |
Rewrite this program in Common_Lisp while keeping its functionality equivalent to the VB version. | Module Module1
Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,)
Dim length = a.GetLength(0) - 1
Dim result(length - 1, length - 1) As Double
For i = 1 To length
For j = 1 To length
If i < x AndAlso j < y Then
result(i - ... | (defun determinant (rows &optional (skip-cols nil))
(let* ((result 0) (sgn -1))
(dotimes (col (length (car rows)) result)
(unless (member col skip-cols)
(if (null (cdr rows))
(return-from determinant (elt (car rows) col))
(incf result (* (setq sgn (- sgn)) (elt (car rows) col) (d... |
Write the same code in Common_Lisp as shown below in VB. | Private Function call_fn(f As String, n As Long) As Long
call_fn = Application.Run(f, f, n)
End Function
Private Function Y(f As String) As String
Y = f
End Function
Private Function fac(self As String, n As Long) As Long
If n > 1 Then
fac = n * call_fn(self, n - 1)
Else
fac = 1
... | (defn Y [f]
((fn [x] (x x))
(fn [x]
(f (fn [& args]
(apply (x x) args))))))
(def fac
(fn [f]
(fn [n]
(if (zero? n) 1 (* n (f (dec n)))))))
(def fib
(fn [f]
(fn [n]
(condp = n
0 0
1 1
(+ (f (dec n))
(f (dec (de... |
Generate an equivalent Common_Lisp version of this VB code. |
Dim fact()
nn1=9 : nn2=12
lim=1499999
ReDim fact(nn2)
fact(0)=1
For i=1 To nn2
fact(i)=fact(i-1)*i
Next
For base=nn1 To nn2
list=""
For i=1 To lim
s=0
t=i
Do While t<>0
d=t Mod base
s=s+fact(d)
t=t\base
Loop
If s=i Then list=list &" "& i
Next
Wscript.Echo "the factori... | (defparameter *bases* '(9 10 11 12))
(defparameter *limit* 1500000)
(defun ! (n) (apply #'* (loop for i from 2 to n collect i)))
(defparameter *digit-factorials* (mapcar #'! (loop for i from 0 to (1- (apply #'max *bases*)) collect i)))
(defun fact (n) (nth n *digit-factorials*))
(defun digit-value (digit)
(let ((... |
Produce a functionally identical Common_Lisp code for the snippet given in VB. |
Dim fact()
nn1=9 : nn2=12
lim=1499999
ReDim fact(nn2)
fact(0)=1
For i=1 To nn2
fact(i)=fact(i-1)*i
Next
For base=nn1 To nn2
list=""
For i=1 To lim
s=0
t=i
Do While t<>0
d=t Mod base
s=s+fact(d)
t=t\base
Loop
If s=i Then list=list &" "& i
Next
Wscript.Echo "the factori... | (defparameter *bases* '(9 10 11 12))
(defparameter *limit* 1500000)
(defun ! (n) (apply #'* (loop for i from 2 to n collect i)))
(defparameter *digit-factorials* (mapcar #'! (loop for i from 0 to (1- (apply #'max *bases*)) collect i)))
(defun fact (n) (nth n *digit-factorials*))
(defun digit-value (digit)
(let ((... |
Produce a functionally identical Common_Lisp code for the snippet given in VB. | Option Base 1
Private Function sq_add(arr As Variant, x As Double) As Variant
Dim res() As Variant
ReDim res(UBound(arr))
For i = 1 To UBound(arr)
res(i) = arr(i) + x
Next i
sq_add = res
End Function
Private Function beadsort(ByVal a As Variant) As Variant
Dim poles() As Variant
Re... | (defun transpose (remain &optional (ret '()))
(if (null remain)
ret
(transpose (remove-if #'null (mapcar #'cdr remain))
(append ret (list (mapcar #'car remain))))))
(defun bead-sort (xs)
(mapcar #'length (transpose (transpose (mapcar (lambda (x) (make-list x :initial-element 1)) xs)))))
(be... |
Rewrite the snippet below in Common_Lisp so it works the same as the original VB code. | Module Module1
Sub Print(ls As List(Of Integer))
Dim iter = ls.GetEnumerator
Console.Write("[")
If iter.MoveNext Then
Console.Write(iter.Current)
End If
While iter.MoveNext
Console.Write(", ")
Console.Write(iter.Current)
End While
... |
(defmacro kaprekar-number-filter (n &optional (base 10))
`(= (mod ,n (1- ,base)) (mod (* ,n ,n) (1- ,base))))
(defun test (&key (start 1) (stop 10000) (base 10) (collect t))
(let ((count 0)
(nums))
(loop for i from start to stop do
(when (kaprekar-number-filter i base)
(if collect (push i nums))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.