Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Produce a functionally identical Delphi code for the snippet given in Java.
import java.util.Arrays; public class CircleSort { public static void main(String[] args) { circleSort(new int[]{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1}); } public static void circleSort(int[] arr) { if (arr.length > 0) do { System.out.println(Arrays.toS...
program Sorting_Algorithms; uses System.SysUtils; function CircleSort(a: TArray<Integer>; lo, hi, swaps: Integer): Integer; begin if lo = hi then exit(swaps); var high := hi; var low := lo; var mid := (hi - lo) div 2; while lo < hi do begin if a[lo] > a[hi] then begin var tmp := a[...
Translate the given Java code snippet into Delphi without altering its behavior.
public static Color getColorAt(int x, int y){ return new Robot().getPixelColor(x, y); }
program ScreenPixel; uses Windows, SysUtils, Graphics; function GetPixelColourAsColor(const PixelCoords: TPoint): TColor; var dc: HDC; begin dc := GetDC(0); Result := GetPixel(dc,PixelCoords.X,PixelCoords.Y); end; function GetPixelColourAsString(const PixelCoords: TPoint): string; var r,g,b:...
Write the same code in Delphi as shown below in Java.
import java.util.Objects; public class Circles { private static class Point { private final double x, y; public Point(Double x, Double y) { this.x = x; this.y = y; } public double distanceFrom(Point other) { double dx = x - other.x; ...
program Circles_of_given_radius_through_two_points; uses System.SysUtils, System.Types, System.Math; const Cases: array[0..9] of TPointF = (( x: 0.1234; y: 0.9876 ), ( x: 0.8765; y: 0.2345 ), ( x: 0.0000; y: 2.0000 ), ( x: 0.0000; y: 0.0000 ), ( x: 0.1234; y: ...
Produce a functionally identical Delphi code for the snippet given in Java.
import java.util.Objects; public class Circles { private static class Point { private final double x, y; public Point(Double x, Double y) { this.x = x; this.y = y; } public double distanceFrom(Point other) { double dx = x - other.x; ...
program Circles_of_given_radius_through_two_points; uses System.SysUtils, System.Types, System.Math; const Cases: array[0..9] of TPointF = (( x: 0.1234; y: 0.9876 ), ( x: 0.8765; y: 0.2345 ), ( x: 0.0000; y: 2.0000 ), ( x: 0.0000; y: 0.0000 ), ( x: 0.1234; y: ...
Convert this Java block to Delphi, preserving its control flow and logic.
import java.awt.*; import javax.swing.*; public class FibonacciWordFractal extends JPanel { String wordFractal; FibonacciWordFractal(int n) { setPreferredSize(new Dimension(450, 620)); setBackground(Color.white); wordFractal = wordFractal(n); } public String wordFractal(int n)...
program Fibonacci_word; uses System.SysUtils, Vcl.Graphics; function GetWordFractal(n: Integer): string; var f1, f2, tmp: string; i: Integer; begin case n of 0: Result := ''; 1: Result := '1'; else begin f1 := '1'; f2 := '0'; for i := n - 2 downto 1 do b...
Change the following Java code into Delphi without altering its purpose.
import processing.sound.*; float[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25}; SinOsc sine; size(500,500); sine = new SinOsc(this); for(int i=0;i<frequencies.length;i++){ sine.freq(frequencies[i]); sine.play(); delay(500); }
program Musical_scale; uses Winapi.Windows; var notes: TArray<Double> = [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]; begin for var note in notes do Beep(Round(note), 500); readln; end.
Produce a language-to-language conversion: from Java to Delphi, same semantics.
import processing.sound.*; float[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25}; SinOsc sine; size(500,500); sine = new SinOsc(this); for(int i=0;i<frequencies.length;i++){ sine.freq(frequencies[i]); sine.play(); delay(500); }
program Musical_scale; uses Winapi.Windows; var notes: TArray<Double> = [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]; begin for var note in notes do Beep(Round(note), 500); readln; end.
Transform the following Java implementation into Delphi, maintaining the same output and logic.
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.swing.JFrame; public class Voronoi extends JFrame { st...
uses System.Generics.Collections; procedure TForm1.Voronoi; const p = 3; cells = 100; size = 1000; var aCanvas : TCanvas; px, py: array of integer; color: array of Tcolor; Img: TBitmap; lastColor:Integer; auxList: TList<TPoint>; poligonlist : TDictionary<integer,TList<TPoint>>; pointarray : ...
Can you help me rewrite this code in Delphi instead of Java, keeping it the same logically?
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.swing.JFrame; public class Voronoi extends JFrame { st...
uses System.Generics.Collections; procedure TForm1.Voronoi; const p = 3; cells = 100; size = 1000; var aCanvas : TCanvas; px, py: array of integer; color: array of Tcolor; Img: TBitmap; lastColor:Integer; auxList: TList<TPoint>; poligonlist : TDictionary<integer,TList<TPoint>>; pointarray : ...
Convert this Java snippet to Delphi and keep its semantics consistent.
import java.text.DecimalFormat; public class AnglesNormalizationAndConversion { public static void main(String[] args) { DecimalFormat formatAngle = new DecimalFormat("######0.000000"); DecimalFormat formatConv = new DecimalFormat("###0.0000"); System.out.printf(" ...
program normalization_and_conversion; uses System.SysUtils, System.Math; function d2d(d: double): double; begin result := FMod(d, 360); end; function g2g(g: double): double; begin result := FMod(g, 400); end; function m2m(m: double): double; begin result := FMod(m, 6400); end; function r2r(r: double): ...
Can you help me rewrite this code in Delphi instead of Java, keeping it the same logically?
import java.io.StringReader; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; public class XMLPars...
program XMLXPath; uses ActiveX, MSXML; const XML = '<inventory title="OmniCorp Store #45x10^3">' + ' <section name="health">' + ' <item upc="123456789" stock="12">' + ' <name>Invisibility Cream</name>' + ' <price>14.50</price>' + ' <description>Makes you invisible</descr...
Translate the given Java code snippet into Delphi without altering its behavior.
import java.io.*; import java.util.*; import java.util.regex.*; public class UpdateConfig { public static void main(String[] args) { if (args[0] == null) { System.out.println("filename required"); } else if (readConfig(args[0])) { enableOption("seedsremoved"); ...
program uConfigFile; uses System.SysUtils, uSettings; const FileName = 'uConf.txt'; var Settings: TSettings; procedure show(key: string; value: string); begin writeln(format('%14s = %s', [key, value])); end; begin Settings := TSettings.Create; Settings.LoadFromFile(FileName); Settings['NEEDSPEELI...
Maintain the same structure and functionality when rewriting this code in Delphi.
import java.io.BufferedReader; import java.io.FileReader; public class IbeforeE { public static void main(String[] args) { IbeforeE now=new IbeforeE(); String wordlist="unixdict.txt"; if(now.isPlausibleRule(wordlist)) System.out.println("Rule is plausible."); else System.out.println("Rule is not plaus...
program I_before_E_except_after_C; uses System.SysUtils, System.IOUtils; function IsOppPlausibleWord(w: string): Boolean; begin if ((not w.Contains('c')) and (w.Contains('ei'))) then exit(True); if (w.Contains('cie')) then exit(True); exit(false); end; function IsPlausibleWord(w: string): Boolean; ...
Change the programming language of this snippet from Java to Delphi without modifying what it does.
import java.io.BufferedReader; import java.io.FileReader; public class IbeforeE { public static void main(String[] args) { IbeforeE now=new IbeforeE(); String wordlist="unixdict.txt"; if(now.isPlausibleRule(wordlist)) System.out.println("Rule is plausible."); else System.out.println("Rule is not plaus...
program I_before_E_except_after_C; uses System.SysUtils, System.IOUtils; function IsOppPlausibleWord(w: string): Boolean; begin if ((not w.Contains('c')) and (w.Contains('ei'))) then exit(True); if (w.Contains('cie')) then exit(True); exit(false); end; function IsPlausibleWord(w: string): Boolean; ...
Port the provided Java code into Delphi while preserving the original functionality.
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class AbelianSandpile { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { Frame frame = new Frame(); frame.setVisible(true); ...
program Abelian_sandpile_model; uses System.SysUtils, Vcl.Graphics, System.Classes; type TGrid = array of array of Integer; function Iterate(var Grid: TGrid): Boolean; var changed: Boolean; i: Integer; j: Integer; val: Integer; Alength: Integer; begin Alength := length(Grid); changed := Fal...
Ensure the translated Delphi code behaves exactly like the original Java snippet.
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class AbelianSandpile { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { Frame frame = new Frame(); frame.setVisible(true); ...
program Abelian_sandpile_model; uses System.SysUtils, Vcl.Graphics, System.Classes; type TGrid = array of array of Integer; function Iterate(var Grid: TGrid): Boolean; var changed: Boolean; i: Integer; j: Integer; val: Integer; Alength: Integer; begin Alength := length(Grid); changed := Fal...
Keep all operations the same but rewrite the snippet in Delphi.
import java.math.BigInteger; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class NextHighestIntFromDigits { public static void main(String[] args) { for ( String s : new String[] {"0", ...
program Next_highest_int_from_digits; uses System.SysUtils, System.Generics.Collections; function StrToBytes(str: AnsiString): TArray<byte>; begin SetLength(result, Length(str)); Move(Pointer(str)^, Pointer(result)^, Length(str)); end; function BytesToStr(bytes: TArray<byte>): AnsiString; begin SetLength...
Rewrite the snippet below in Delphi so it works the same as the original Java code.
import java.math.BigInteger; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class NextHighestIntFromDigits { public static void main(String[] args) { for ( String s : new String[] {"0", ...
program Next_highest_int_from_digits; uses System.SysUtils, System.Generics.Collections; function StrToBytes(str: AnsiString): TArray<byte>; begin SetLength(result, Length(str)); Move(Pointer(str)^, Pointer(result)^, Length(str)); end; function BytesToStr(bytes: TArray<byte>): AnsiString; begin SetLength...
Keep all operations the same but rewrite the snippet in Delphi.
public class FourIsMagic { public static void main(String[] args) { for ( long n : new long[] {6, 60, 89, 300, 670, 2000, 2467, 20000, 24500,200000, 230000, 246571, 2300000, 2465712, 20000000, 24657123, 230000000, 245000000, -246570000, 123456789712345l, 8777777777777777777L, Long.MAX_VALUE}) { ...
program Four_is_magic; uses System.SysUtils; const smallies: array[1..19] of string = ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'); tens: array[2..9] of string = (...
Convert the following code from Java to Delphi, ensuring the logic remains intact.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Locale; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; public class WriteToWindowsEventLog { public static void main(String[] args) throws IOException...
program WriteToEventLog; uses Windows; procedure WriteLog(aMsg: string); var lHandle: THandle; lMessagePtr: Pointer; begin lMessagePtr := PChar(aMsg); lHandle := RegisterEventSource(nil, 'Logger'); if lHandle > 0 then begin try ReportEvent(lHandle, 4 , 0, 0, nil, 1, 0, @lMessagePtr, nil); ...
Change the following Java code into Delphi without altering its purpose.
import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; public class ChemicalCalculator { private static final Map<String, Double> atomicMass = new HashMap<>(); static { atomicMass.put("H", 1.008); atomicMass.put("He", 4.002602); atomicMas...
program ChemicalCalculator; uses System.SysUtils, System.Generics.Collections; type TAtomicMass = class(TDictionary<string, Double>) public constructor Create(Keys: array of string; Values: array of Double); overload; end; constructor TAtomicMass.Create(Keys: array of string; Values: array of D...
Port the following code from Java to Delphi with equivalent syntax and logic.
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class FixCodeTags { public static void main(String[] args) { String sourcefile=args[0]; String convertedfile=args[1]; convert(sourcefile,convertedfile); } static String[] languages = {"abap", "a...
program Fix_code_tags; uses Winapi.Windows, System.SysUtils, System.Classes, System.RegularExpressions; const LANGS: array of string = ['abap', 'actionscript', 'actionscript3', 'ada', 'apache', 'applescript', 'apt_sources', 'asm', 'asp', 'autoit', 'avisynth', 'bash', 'basic4gl', 'bf', 'blitzbasic'...
Convert the following code from Java to Delphi, ensuring the logic remains intact.
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 = ...
ValueByte : Byte := 2; ValueWord : Word := ValueByte; ValueDWord : DWord := ValueWord; ValueUint64 : Uint64 := ValueWord;
Change the following Java code into Delphi without altering its purpose.
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 = ...
ValueByte : Byte := 2; ValueWord : Word := ValueByte; ValueDWord : DWord := ValueWord; ValueUint64 : Uint64 := ValueWord;
Convert this Java block to Delphi, 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 Strange_primes; uses System.SysUtils; function IsPrime(n: Integer): Boolean; begin if n < 2 then exit(false); if n mod 2 = 0 then exit(n = 2); if n mod 3 = 0 then exit(n = 3); var d := 5; while d * d <= n do begin if n mod d = 0 then exit(false); inc(d, 2); i...
Translate the given Java code snippet into Delphi without altering its behavior.
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 Strange_primes; uses System.SysUtils; function IsPrime(n: Integer): Boolean; begin if n < 2 then exit(false); if n mod 2 = 0 then exit(n = 2); if n mod 3 = 0 then exit(n = 3); var d := 5; while d * d <= n do begin if n mod d = 0 then exit(false); inc(d, 2); i...
Convert this Java block to Delphi, 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; ...
program Strange_plus_numbers; uses System.SysUtils; function IsPrime(n: Integer): Boolean; begin Result := n in [2, 3, 5, 7, 11, 13, 17]; end; begin var count := 0; var d: TArray<Integer>; writeln('Strange plus numbers in the open interval (100, 500) are:'); for var i := 101 to 499 do begin d := ...
Convert this Java snippet to Delphi and keep its semantics consistent.
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; ...
program Strange_plus_numbers; uses System.SysUtils; function IsPrime(n: Integer): Boolean; begin Result := n in [2, 3, 5, 7, 11, 13, 17]; end; begin var count := 0; var d: TArray<Integer>; writeln('Strange plus numbers in the open interval (100, 500) are:'); for var i := 101 to 499 do begin d := ...
Generate a Delphi translation of this Java snippet without changing its computational steps.
public class OldRussianMeasures { final static String[] keys = {"tochka", "liniya", "centimeter", "diuym", "vershok", "piad", "fut", "arshin", "meter", "sazhen", "kilometer", "versta", "milia"}; final static double[] values = {0.000254, 0.00254, 0.01,0.0254, 0.04445, 0.1778, 0.3048, 0....
program Old_Russian_measure_of_length; uses System.SysUtils; const units: array[0..12] of string = ('tochka', 'liniya', 'dyuim', 'vershok', 'piad', 'fut', 'arshin', 'sazhen', 'versta', 'milia', 'centimeter', 'meter', 'kilometer'); convs: array[0..12] of double = (0.0254, 0.254, 2.54, 4.445, 17.78, 30....
Maintain the same structure and functionality when rewriting this code in Delphi.
import static java.util.stream.IntStream.rangeClosed; public class Test { final static int nMax = 12; static char[] superperm; static int pos; static int[] count = new int[nMax]; static int factSum(int n) { return rangeClosed(1, n) .map(m -> rangeClosed(1, m).reduce(1, (a,...
program Superpermutation_minimisation; uses System.SysUtils; const Max = 12; var super: ansistring; pos: Integer; cnt: TArray<Integer>; function factSum(n: Integer): Uint64; begin var s: Uint64 := 0; var f := 1; var x := 0; while x < n do begin inc(x); f := f * x; inc(s, f); end...
Change the programming language of this snippet from Java to Delphi without modifying what it does.
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; ...
uses math, ucomplex; function isInteger(x: float; const fuzziness: float = 0.0): Boolean; function fuzzyInteger: Boolean; begin x := x mod 1.0; result := (x <= fuzziness) or (x >= 1.0 - fuzziness); end; begin result := not isInfinite(x) and not isNan(x) and fuzzyInteger; end; functi...
Ensure the translated Delphi code behaves exactly like the original Java snippet.
import com.sun.javafx.application.PlatformImpl; import java.io.File; import java.util.Scanner; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; public class AudioAlarm { public static void main(String[] ...
program AudioAlarm; uses System.SysUtils, Bass; procedure Wait(sec: Cardinal; verbose: Boolean = False); begin while sec > 0 do begin if verbose then Writeln(sec); Sleep(1000); dec(sec); end; end; function QueryMp3File: string; begin while True do begin Writeln('Enter name of ...
Preserve the algorithm and functionality while converting the code from Java to Delphi.
import java.util.LinkedList; public class DoublyLinkedList { public static void main(String[] args) { LinkedList<String> list = new LinkedList<String>(); list.addFirst("Add First"); list.addLast("Add Last 1"); list.addLast("Add Last 2"); list.addLast("Add Last 1"); ...
program Doubly_linked; uses System.SysUtils, boost.LinkedList; var List: TLinkedList<string>; Head, Tail,Current: TLinkedListNode<string>; Value:string; begin List := TLinkedList<string>.Create; List.AddFirst('.AddFirst() adds at the head.'); List.AddLast('.AddLast() adds at the tail.'); Head :=...
Rewrite this program in Delphi while keeping its functionality equivalent to the Java version.
import java.util.Objects; import java.util.function.Predicate; public class RealNumberSet { public enum RangeType { CLOSED, BOTH_OPEN, LEFT_OPEN, RIGHT_OPEN, } public static class RealSet { private Double low; private Double high; private Predicate<D...
program Set_of_real_numbers; uses System.SysUtils; type TSet = TFunc<Double, boolean>; function Union(a, b: TSet): TSet; begin Result := function(x: double): boolean begin Result := a(x) or b(x); end; end; function Inter(a, b: TSet): TSet; begin Result := function(x: double): boolean...
Produce a language-to-language conversion: from Java to Delphi, same semantics.
import java.util.Objects; import java.util.function.Predicate; public class RealNumberSet { public enum RangeType { CLOSED, BOTH_OPEN, LEFT_OPEN, RIGHT_OPEN, } public static class RealSet { private Double low; private Double high; private Predicate<D...
program Set_of_real_numbers; uses System.SysUtils; type TSet = TFunc<Double, boolean>; function Union(a, b: TSet): TSet; begin Result := function(x: double): boolean begin Result := a(x) or b(x); end; end; function Inter(a, b: TSet): TSet; begin Result := function(x: double): boolean...
Maintain the same structure and functionality when rewriting this code in Delphi.
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Vector; public class RTextonyms { private static fin...
program Textonyms; uses System.SysUtils, System.Classes, System.Generics.Collections, System.Character; const TEXTONYM_MAP = '22233344455566677778889999'; type TextonymsChecker = class private Total, Elements, Textonyms, MaxFound: Integer; MaxStrings: TList<string>; Values: TDictionary<st...
Transform the following Java implementation into Delphi, maintaining the same output and logic.
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 Calculate_Pi; uses System.SysUtils, Velthuis.BigIntegers, System.Diagnostics; function IntSqRoot(value, guess: BigInteger): BigInteger; var term: BigInteger; begin while True do begin term := value div guess; if (BigInteger.Abs(term - guess) <= 1) then break; guess := (guess + ...
Transform the following Java implementation into Delphi, maintaining the same output and logic.
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 Calculate_Pi; uses System.SysUtils, Velthuis.BigIntegers, System.Diagnostics; function IntSqRoot(value, guess: BigInteger): BigInteger; var term: BigInteger; begin while True do begin term := value div guess; if (BigInteger.Abs(term - guess) <= 1) then break; guess := (guess + ...
Convert this Java snippet to Delphi 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; const Order = 5; Epsilon = 1E-12; var Roots : array[0..Order-1] of double; Weight : array[0..Order-1] of double; LegCoef : array [0..Order,0..Order] of double; function F(X:double) : double; begin Result := Exp(X); end; procedure PrepCoef; var I, N : integer; begin for I:=...
Port the provided Java code into Delphi while preserving the original functionality.
import java.util.*; public class CutRectangle { private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; public static void main(String[] args) { cutRectangle(2, 2); cutRectangle(4, 3); } static void cutRectangle(int w, int h) { if (w % 2 == 1 && h % 2 == 1) ...
program Cut_a_rectangle; uses System.SysUtils; var grid: array of byte; w, h, len: Integer; cnt: UInt64; next: array of Integer; dir: array of array of Integer = [[0, -1], [-1, 0], [0, 1], [1, 0]]; procedure walk(y, x: Integer); var i, t: Integer; begin if (y = 0) or (y = h) or (x = 0) or (x = w) t...
Produce a language-to-language conversion: from Java to Delphi, same semantics.
import java.util.*; public class CutRectangle { private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; public static void main(String[] args) { cutRectangle(2, 2); cutRectangle(4, 3); } static void cutRectangle(int w, int h) { if (w % 2 == 1 && h % 2 == 1) ...
program Cut_a_rectangle; uses System.SysUtils; var grid: array of byte; w, h, len: Integer; cnt: UInt64; next: array of Integer; dir: array of array of Integer = [[0, -1], [-1, 0], [0, 1], [1, 0]]; procedure walk(y, x: Integer); var i, t: Integer; begin if (y = 0) or (y = h) or (x = 0) or (x = w) t...
Write the same algorithm in Delphi as shown in this Java implementation.
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 = ...
unit main; interface uses Winapi.Windows, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.ExtCtrls, System.Generics.Collections; type TColoredPoint = record P: TPoint; Index: Integer; constructor Create(PX, PY: Integer; ColorIndex: Integer); end; TForm1 = class(TForm) procedure FormCreate(Sen...
Write the same code in Delphi as shown below in Java.
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 = ...
unit main; interface uses Winapi.Windows, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.ExtCtrls, System.Generics.Collections; type TColoredPoint = record P: TPoint; Index: Integer; constructor Create(PX, PY: Integer; ColorIndex: Integer); end; TForm1 = class(TForm) procedure FormCreate(Sen...
Translate the given Java code snippet into Delphi without altering its behavior.
import java.math.BigInteger; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; public class PierpontPrimes { public static void main(String[] args) { NumberFormat nf = NumberFormat.getNumberInstance(); display("First 50 Pierpont primes of the first kind:", pierpontP...
program Pierpont_primes; uses System.SysUtils, System.Math, System.StrUtils, System.Generics.Collections, System.Generics.Defaults, Velthuis.BigIntegers, Velthuis.BigIntegers.Primes; function Pierpont(ulim, vlim: Integer; first: boolean): TArray<BigInteger>; begin var p: BigInteger := 0; var p2: B...
Ensure the translated Delphi 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 N_smooth_numbers; uses System.SysUtils, System.Generics.Collections, Velthuis.BigIntegers; var primes: TList<BigInteger>; smallPrimes: TList<Integer>; function IsPrime(value: BigInteger): Boolean; var v: BigInteger; begin if value < 2 then exit(False); for v in [2, 3, 5, 7, 11, 13, 17...
Produce a language-to-language conversion: from Java to Delphi, same semantics.
import java.util.Locale; public class Test { public static void main(String[] args) { System.out.println(new Vec2(5, 7).add(new Vec2(2, 3))); System.out.println(new Vec2(5, 7).sub(new Vec2(2, 3))); System.out.println(new Vec2(5, 7).mult(11)); System.out.println(new Vec2(5, 7).div(2...
program Vector; uses System.Math.Vectors, SysUtils; procedure VectorToString(v: TVector); begin WriteLn(Format('(%.1f + i%.1f)', [v.X, v.Y])); end; var a, b: TVector; begin a := TVector.Create(5, 7); b := TVector.Create(2, 3); VectorToString(a + b); VectorToString(a - b); VectorToString(a * 11...
Write the same algorithm in Delphi as shown in this Java implementation.
import java.util.Objects; public class PrintDebugStatement { private static void printDebug(String message) { Objects.requireNonNull(message); RuntimeException exception = new RuntimeException(); StackTraceElement[] stackTrace = exception.getStackTrace(); Sta...
program DebugApp; uses winapi.windows, System.sysutils; function Add(x, y: Integer): Integer; begin Result := x + y; OutputDebugString(PChar(format('%d + %d = %d', [x, y, result]))); end; begin writeln(Add(2, 7)); readln; end.
Preserve the algorithm and functionality while converting the code from Java to Delphi.
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 Finite_state_machine; type TState = (stReady, stWaiting, stDispense, stRefunding, stExit); var state: TState = stReady; procedure fsm(); var line: string; option: char; begin Writeln('Please enter your option when prompted'); Writeln('(any characters after the first will be ignored)'#10); sta...
Convert this Java snippet to Delphi and keep its semantics consistent.
import java.io.File; import java.util.*; import java.util.regex.*; public class CommatizingNumbers { public static void main(String[] args) throws Exception { commatize("pi=3.14159265358979323846264338327950288419716939937510582" + "097494459231", 6, 5, " "); commatize("The author...
program Commatizing_numbers; uses System.SysUtils, System.RegularExpressions, system.StrUtils; const PATTERN = '(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)'; TESTS: array[0..13] of string = ('123456789.123456789', '.123456789', '57256.1D-4', 'pi=3.1415926535897932384626433832795028841971693993751058209749445...
Change the following Java code into Delphi without altering its purpose.
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 KosarajuApp; uses System.SysUtils; type TKosaraju = TArray<TArray<Integer>>; var g: TKosaraju; procedure Init(); begin SetLength(g, 8); g[0] := [1]; g[1] := [2]; g[2] := [0]; g[3] := [1, 2, 4]; g[4] := [3, 5]; g[5] := [2, 6]; g[6] := [5]; g[7] := [4, 6, 7]; end; procedure Println(ve...
Generate a Delphi translation of this Java snippet without changing its computational steps.
import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class WordBreak { public static void main(String[] args) { List<String> dict = Arrays.asList("a", "aa", "b", "ab", "aab"); for ( String testString : Arrays.asList...
program Word_break_problem; uses System.SysUtils, System.Generics.Collections; type TDict = TDictionary<string, boolean>; TPrefix = record length: integer; broken: TArray<string>; constructor Create(len: integer; b: TArray<string>); end; const TESTS: TArray<string> = ['abcd', 'abbc', 'abcb...
Convert this Java snippet to Delphi and keep its semantics consistent.
import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; public class DecimalToBinary { public static void main(String[] args) { for ( String s : new String[] {"23.34375", ".1", "3.1415926535897932"} ) { String binary = decimalToBinary(new BigDecimal(s)); ...
program FloatToBinTest; uses System.SysUtils, Math; function IntToBin(value: Int64): string; var i, bit: Integer; begin Result := ''; for i := 63 downto 0 do begin bit := (value shr i) and 1; if (bit = 0) and Result.IsEmpty then Continue; Result := Result + bit.ToString end; end; ...
Translate the given Java code snippet into Delphi without altering its behavior.
import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; public class DecimalToBinary { public static void main(String[] args) { for ( String s : new String[] {"23.34375", ".1", "3.1415926535897932"} ) { String binary = decimalToBinary(new BigDecimal(s)); ...
program FloatToBinTest; uses System.SysUtils, Math; function IntToBin(value: Int64): string; var i, bit: Integer; begin Result := ''; for i := 63 downto 0 do begin bit := (value shr i) and 1; if (bit = 0) and Result.IsEmpty then Continue; Result := Result + bit.ToString end; end; ...
Convert the following code from Java to Delphi, ensuring the logic remains intact.
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; function SHA256(const Input: TArray<Byte>; Len: Integer = -1): TArray<Byte>; var Hasher: TDCP_sha256; l: Integer; begin if Len < 0 then l := length(Input) else l := Len; Hasher := TDCP_sha256.Create(nil); try ...
Port the following code from Java to Delphi with equivalent syntax and logic.
import java.math.BigInteger; public class PartitionFunction { public static void main(String[] args) { long start = System.currentTimeMillis(); BigInteger result = partitions(6666); long end = System.currentTimeMillis(); System.out.println("P(6666) = " + result); System.out....
program Partition_function_P; uses System.SysUtils, Velthuis.BigIntegers, System.Diagnostics; var p: TArray<BigInteger>; pd: TArray<Integer>; function PartiDiffDiff(n: Integer): Integer; begin if n and 1 = 1 then exit((n + 1) div 2); Result := n + 1; end; function partDiff(n: Integer): Integer; ...
Produce a language-to-language conversion: from Java to Delphi, same semantics.
import java.util.function.IntBinaryOperator; public class Nimber { public static void main(String[] args) { printTable(15, '+', (x, y) -> nimSum(x, y)); System.out.println(); printTable(15, '*', (x, y) -> nimProduct(x, y)); System.out.println(); int a = 21508, b = 42689; ...
program Nimber_arithmetic; uses System.SysUtils, System.Math; Type TFnop = record fn: TFunc<Cardinal, Cardinal, Cardinal>; op: string; end; function hpo2(n: Cardinal): Cardinal; begin Result := n and (-n) end; function lhpo2(n: Cardinal): Cardinal; var m: Cardinal; begin Result := 0; m :=...
Convert this Java snippet to Delphi and keep its semantics consistent.
import java.util.Arrays; public class Test { public static void main(String[] args) { int[] N = {1, -12, 0, -42}; int[] D = {1, -3}; System.out.printf("%s / %s = %s", Arrays.toString(N), Arrays.toString(D), Arrays.deepToString(extendedSynthe...
program Polynomial_synthetic_division; uses System.SysUtils, Velthuis.BigRationals; type TPollynomy = record public Terms: TArray<BigRational>; class operator Divide(a, b: TPollynomy): TArray<TPollynomy>; constructor Create(Terms: TArray<BigRational>); function ToString: string; end; co...
Generate an equivalent Delphi version of this Java code.
import java.util.Arrays; public class Test { public static void main(String[] args) { int[] N = {1, -12, 0, -42}; int[] D = {1, -3}; System.out.printf("%s / %s = %s", Arrays.toString(N), Arrays.toString(D), Arrays.deepToString(extendedSynthe...
program Polynomial_synthetic_division; uses System.SysUtils, Velthuis.BigRationals; type TPollynomy = record public Terms: TArray<BigRational>; class operator Divide(a, b: TPollynomy): TArray<TPollynomy>; constructor Create(Terms: TArray<BigRational>); function ToString: string; end; co...
Can you help me rewrite this code in Delphi instead of Java, keeping it the same logically?
import java.awt.*; import javax.swing.*; public class ColorWheel { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { ColorWheelFrame frame = new ColorWheelFrame(); frame.setVisible(true); } ...
program Color_wheel; uses Winapi.Windows, System.SysUtils, Vcl.Graphics, System.Math, Vcl.Imaging.pngimage; const TAU = 2 * PI; function HSBtoColor(hue, sat, bri: Double): TColor; var f, h: Double; u, p, q, t: Byte; begin u := Trunc(bri * 255 + 0.5); if sat = 0 then Exit(rgb(u, u, u)); h...
Change the following Java code into Delphi without altering its purpose.
public class MainApp { public static void main(String[] args) { int countOfPrimes = 0; final int targetCountOfPrimes = 10; long f = 1; while (countOfPrimes < targetCountOfPrimes) { long factorialNum = getFactorial(f); boolean primePlus = isPrime(factorialNum +...
function IsPrime(N: int64): boolean; var I,Stop: integer; begin if (N = 2) or (N=3) then Result:=true else if (n <= 1) or ((n mod 2) = 0) or ((n mod 3) = 0) then Result:= false else begin I:=5; Stop:=Trunc(sqrt(N*1.0)); Result:=False; while I<=Stop do begin if ((N mod I) = 0) or ((N mod (i + 2)) = 0) then exi...
Produce a language-to-language conversion: from Java to Delphi, same semantics.
import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Scanner; public class textCompletionConcept { public static int correct = 0; public static ArrayList<String> listed = new ArrayList<>(); public static void main(String[]args) ...
program Text_Completion; uses System.SysUtils, System.Classes, System.Math, System.Generics.Collections; type TSujestions = TDictionary<Integer, string>; function Levenshtein(s, t: string): integer; var d: array of array of integer; i, j, cost: integer; begin SetLength(d, Length(s) + 1); for i ...
Rewrite this program in Delphi while keeping its functionality equivalent to the Java version.
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}; ...
unit main; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.ExtCtrls, System.UITypes; type TTrainer = class inputs: TArray<Double>; answer: Integer; constructor Create(x, y: Double; a: Integer); end; TForm1 = class(TForm) tmr1: TTimer; procedure FormCreate(S...
Translate this program into Haskell but keep the logic exactly as in C.
#include<stdlib.h> #include<stdio.h> typedef struct{ int rows,cols; int** dataSet; }matrix; matrix readMatrix(char* dataFile){ FILE* fp = fopen(dataFile,"r"); matrix rosetta; int i,j; fscanf(fp,"%d%d",&rosetta.rows,&rosetta.cols); rosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*)); for(i=0;i<ros...
matrixTriangle :: Bool -> [[a]] -> Either String [[a]] matrixTriangle upper matrix | upper = go drop id | otherwise = go take pred where go f g | isSquare matrix = (Right . snd) $ foldr (\xs (n, rows) -> (pred n, f n xs : rows)) (g $ length matrix, []) ...
Preserve the algorithm and functionality while converting the code from C to Haskell.
#include<graphics.h> #include<stdlib.h> #include<stdio.h> #include<time.h> typedef struct{ double x,y; }point; void pythagorasTree(point a,point b,int times){ point c,d,e; c.x = b.x - (a.y - b.y); c.y = b.y - (b.x - a.x); d.x = a.x - (a.y - b.y); d.y = a.y - (b.x - a.x); e.x = d.x + ( b.x - a.x - (a...
mkBranches :: [(Float,Float)] -> [[(Float,Float)]] mkBranches [a, b, c, d] = let d = 0.5 <*> (b <+> (-1 <*> a)) l1 = d <+> orth d l2 = orth l1 in [ [a <+> l2, b <+> (2 <*> l2), a <+> l1, a] , [a ...
Transform the following C implementation into Haskell, maintaining the same output and logic.
#include <stdio.h> #include <string.h> int repstr(char *str) { if (!str) return 0; size_t sl = strlen(str) / 2; while (sl > 0) { if (strstr(str, str + sl) == str) return sl; --sl; } return 0; } int main(void) { char *strs[] = { "1001110011", "1110111011", "0010010...
import Data.List (inits, maximumBy) import Data.Maybe (fromMaybe) repstring :: String -> Maybe String repstring [] = Nothing repstring [_] = Nothing repstring xs | any (`notElem` "01") xs = Nothing | otherwise = longest xs where lxs = length xs lq2 = lxs `quot` 2 subrepeat x = (...
Convert the following code from C to Haskell, ensuring the logic remains intact.
#include<windows.h> #include<string.h> #include<stdio.h> #define MAXORDER 25 int main(int argC, char* argV[]) { char str[MAXORDER],commandString[1000],*startPath; long int* fileSizeLog = (long int*)calloc(sizeof(long int),MAXORDER),max; int i,j,len; double scale; FILE* fp; if(argC==1) printf("Usage : %s <fol...
import Control.Concurrent (forkIO, setNumCapabilities) import Control.Concurrent.Chan (Chan, newChan, readChan, writeChan, writeList2Chan) import Control.Exception (IOException, catch) import Control.Monad ...
Transform the following C implementation into Haskell, maintaining the same output and logic.
#include <stdio.h> #include <string.h> typedef struct { char v[16]; } deck; typedef unsigned int uint; uint n, d, best[16]; void tryswaps(deck *a, uint f, uint s) { # define A a->v # define B b.v if (d > best[n]) best[n] = d; while (1) { if ((A[s] == s || (A[s] == -1 && !(f & 1U << s))) && (d + best[s] >= bes...
import Data.List (permutations) topswops :: Int -> Int topswops n = maximum $ map tops $ permutations [1 .. n] where tops (1:_) = 0 tops xa@(x:_) = 1 + tops reordered where reordered = reverse (take x xa) ++ drop x xa main = mapM_ (putStrLn . ((++) <$> show <*> (":\t" ++) . show . topswops))...
Rewrite this program in Haskell while keeping its functionality equivalent to the C version.
#include <stdio.h> #define MAX 15 int count_divisors(int n) { int i, count = 0; for (i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; } int main() { int i, next = 1; pr...
import Text.Printf (printf) sequence_A069654 :: [(Int,Int)] sequence_A069654 = go 1 $ (,) <*> countDivisors <$> [1..] where go t ((n,c):xs) | c == t = (t,n):go (succ t) xs | otherwise = go t xs countDivisors n = foldr f 0 [1..floor $ sqrt $ realToFrac n] where f x r | n `mod` ...
Keep all operations the same but rewrite the snippet in Haskell.
#include <stdio.h> int main() { int max = 0, i = 0, sixes, nines, twenties; loopstart: while (i < 100) { for (sixes = 0; sixes*6 < i; sixes++) { if (sixes*6 == i) { i++; goto loopstart; } for (nines = 0; nines*9 < i; nines++) { ...
import Data.Set (Set, fromList, member) mcNuggets :: Set Int mcNuggets = let size = enumFromTo 0 . quot 100 in fromList $ size 6 >>= \x -> size 9 >>= \y -> size 20 >>= \z -> [ v | let v = sum ...
Write the same algorithm in Haskell as shown in this C implementation.
#include <stdio.h> int main(int argc, char const *argv[]) { for (char c = 0x41; c < 0x5b; c ++) putchar(c); putchar('\n'); for (char c = 0x61; c < 0x7b; c ++) putchar(c); putchar('\n'); return 0; }
main = do putStrLn $ "Lower: " ++ ['a'..'z'] putStrLn $ "Upper: " ++ ['A'..'Z']
Generate an equivalent Haskell version of this C code.
#include<graphics.h> #include<stdio.h> #include<math.h> #define pi M_PI int main(){ double a,b,n,i,incr = 0.0001; printf("Enter major and minor axes of the SuperEllipse : "); scanf("%lf%lf",&a,&b); printf("Enter n : "); scanf("%lf",&n); initwindow(500,500,"Superellipse"); for(i=0;i<2*pi;i+=incr){ p...
import Reflex import Reflex.Dom import Data.Text (Text, pack, unpack) import Data.Map (Map, fromList, empty) import Text.Read (readMaybe) width = 600 height = 500 type Point = (Float,Float) type Segment = (Point,Point) data Ellipse = Ellipse {a :: Float, b :: Float, n :: Float} toFloat :: Text -> Maybe Float toFl...
Keep all operations the same but rewrite the snippet in Haskell.
HANDLE hMutex = CreateMutex(NULL, FALSE, NULL);
takeMVar :: MVar a -> IO a putMVar :: MVar a -> a -> IO () tryTakeMVar :: MVar a -> IO (Maybe a) tryPutMVar :: MVar a -> a -> IO Bool
Rewrite the snippet below in Haskell so it works the same as the original C code.
#include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #define TRUE 1 #define FALSE 0 #define max(a, b) ((a) > (b) ? (a) : (b)) #define min(a, b) ((a) < (b) ? (a) : (b)) double jaro(const char *str1, const char *str2) { int str1_len = strlen(str1); int str2_len = strlen(str2)...
import Data.List (elemIndex, intercalate, sortOn) import Data.Maybe (mapMaybe) import Text.Printf (printf) jaro :: Ord a => [a] -> [a] -> Float jaro x y | 0 == m = 0 | otherwise = (1 / 3) * ( (m / s1) + (m / s2) + ((m - t) / m)) where f = fromIntegral . length [m, t] = [f, fromIntegral ...
Ensure the translated Haskell code behaves exactly like the original C snippet.
#include <stdio.h> #include <ctype.h> static int owp(int odd) { int ch, ret; ch = getc(stdin); if (!odd) { putc(ch, stdout); if (ch == EOF || ch == '.') return EOF; if (ispunct(ch)) return 0; ...
import System.IO (BufferMode(..), getContents, hSetBuffering, stdin, stdout) import Data.Char (isAlpha) split :: String -> (String, String) split = span isAlpha parse :: String -> String parse [] = [] parse l = let (a, w) = split l (b, x) = splitAt 1 w (c, y) = split x (d, z) = splitAt 1 y ...
Can you help me rewrite this code in Haskell instead of C, keeping it the same logically?
#include <math.h> #include <stdint.h> #include <stdio.h> const uint64_t N = 6364136223846793005; static uint64_t state = 0x853c49e6748fea9b; static uint64_t inc = 0xda3e39cb94b95bdb; uint32_t pcg32_int() { uint64_t old = state; state = old * N + inc; uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 2...
import Data.Bits import Data.Word import System.Random import Data.List data PCGen = PCGen !Word64 !Word64 mkPCGen state sequence = let n = 6364136223846793005 :: Word64 inc = (sequence `shiftL` 1) .|. 1 :: Word64 in PCGen ((inc + state)*n + inc) inc instance RandomGen PCGen where next (PCGen stat...
Convert this C snippet to Haskell and keep its semantics consistent.
#include <stdio.h> unsigned int lpd(unsigned int n) { if (n<=1) return 1; int i; for (i=n-1; i>0; i--) if (n%i == 0) return i; } int main() { int i; for (i=1; i<=100; i++) { printf("%3d", lpd(i)); if (i % 10 == 0) printf("\n"); } return 0; }
import Data.List.Split (chunksOf) import Text.Printf (printf) lpd :: Int -> Int lpd 1 = 1 lpd n = head [x | x <- [n -1, n -2 .. 1], n `mod` x == 0] main :: IO () main = (putStr . unlines . map concat . chunksOf 10) $ printf "%3d" . lpd <$> [1 .. 100]
Change the programming language of this snippet from C to Haskell without modifying what it does.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct rec_t rec_t; struct rec_t { int depth; rec_t * p[10]; }; rec_t root = {0, {0}}; #define USE_POOL_ALLOC #ifdef USE_POOL_ALLOC rec_t *tail = 0, *head = 0; #define POOL_SIZE (1 << 20) inline rec_t *new_rec() { if (head == tail) { head = cal...
import Data.Set (Set, member, insert, empty) import Data.List (group, sort) step :: String -> String step = concatMap (\list -> show (length list) ++ [head list]) . group . sort findCycle :: (Ord a) => [a] -> [a] findCycle = aux empty where aux set (x : xs) | x `member` set = [] | otherwise = x : aux (insert x s...
Convert the following code from C to Haskell, ensuring the logic remains intact.
#include<graphics.h> #include<stdlib.h> #include<stdio.h> #include<math.h> #define pi M_PI typedef struct{ double x,y; }point; void kochCurve(point p1,point p2,int times){ point p3,p4,p5; double theta = pi/3; if(times>0){ p3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3}; p5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p...
import Data.Bifunctor (bimap) import Text.Printf (printf) kochSnowflake :: Int -> (Float, Float) -> (Float, Float) -> [(Float, Float)] kochSnowflake n a b = concat $ zipWith (kochCurve n) points (xs <> [x]) where points@(x : xs) = [a, equilateralApex a b, b] kochCurve :: Int -> (Float, Float)...
Convert the following code from C to Haskell, ensuring the logic remains intact.
#include <math.h> #include <stdint.h> #include <stdio.h> static uint64_t state; static const uint64_t STATE_MAGIC = 0x2545F4914F6CDD1D; void seed(uint64_t num) { state = num; } uint32_t next_int() { uint64_t x; uint32_t answer; x = state; x = x ^ (x >> 12); x = x ^ (x << 25); x = x ^ (x ...
import Data.Bits import Data.Word import System.Random import Data.List newtype XorShift = XorShift Word64 instance RandomGen XorShift where next (XorShift state) = (out newState, XorShift newState) where newState = (\z -> z `xor` (z `shiftR` 27)) . (\z -> z `xor` (z `shiftL` 25)) . ...
Write a version of this C function in Haskell with identical behavior.
#include <stdio.h> int riseEqFall(int num) { int rdigit = num % 10; int netHeight = 0; while (num /= 10) { netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit); rdigit = num % 10; } return netHeight == 0; } int nextNum() { static int num = 0; do {num++;} while (!ris...
import Data.Char pairs :: [a] -> [(a,a)] pairs (a:b:as) = (a,b):pairs (b:as) pairs _ = [] riseEqFall :: Int -> Bool riseEqFall n = rel (>) digitPairs == rel (<) digitPairs where rel r = sum . map (fromEnum . uncurry r) digitPairs = pairs $ map digitToInt $ show n a296712 :: [Int] a296712 = [n |...
Translate the given C code snippet into Haskell without altering its behavior.
#include <math.h> #include <stdio.h> #include <stdint.h> int64_t mod(int64_t x, int64_t y) { int64_t m = x % y; if (m < 0) { if (y < 0) { return m - y; } else { return m + y; } } return m; } const static int64_t a1[3] = { 0, 1403580, -810728 }; const s...
import Data.List randoms :: Int -> [Int] randoms seed = unfoldr go ([seed,0,0],[seed,0,0]) where go (x1,x2) = let x1i = sum (zipWith (*) x1 a1) `mod` m1 x2i = sum (zipWith (*) x2 a2) `mod` m2 in Just $ ((x1i - x2i) `mod` m1, (x1i:init x1, x2i:init x2)) a1 = [0, 1403580, -810728] ...
Rewrite this program in Haskell while keeping its functionality equivalent to the C version.
#include <stdio.h> inline int self_desc(unsigned long long xx) { register unsigned int d, x; unsigned char cnt[10] = {0}, dig[10] = {0}; for (d = 0; xx > ~0U; xx /= 10) cnt[ dig[d++] = xx % 10 ]++; for (x = xx; x; x /= 10) cnt[ dig[d++] = x % 10 ]++; while(d-- && dig[x++] == cnt[d]); return d == -1; ...
import Data.Char count :: Int -> [Int] -> Int count x = length . filter (x ==) isSelfDescribing :: Integer -> Bool isSelfDescribing n = nu == f where nu = digitToInt <$> show n f = (`count` nu) <$> [0 .. length nu - 1] main :: IO () main = do print $ isSelfDescribing <$> [1210, 2020, 21200, 32110...
Produce a language-to-language conversion: from C to Haskell, same semantics.
#include <stdio.h> #include <stdbool.h> bool three_3s(const int *items, size_t len) { int threes = 0; while (len--) if (*items++ == 3) if (threes<3) threes++; else return false; else if (threes != 0 && threes != 3) return false; return true; } void...
import Data.Bifunctor (bimap) import Data.List (span) nnPeers :: Int -> [Int] -> Bool nnPeers n xs = let p x = n == x in uncurry (&&) $ bimap (p . length) (not . any p) (span p $ dropWhile (not . p) xs) main :: IO () main = putStrLn $ unlines $ fmap (\xs...
Ensure the translated Haskell code behaves exactly like the original C snippet.
#include <stdio.h> #define SIZE 256 int check(char *word) { int e = 0, ok = 1; for(; *word && ok; word++) { switch(*word) { case 'a': case 'i': case 'o': case 'u': ok = 0; break; case 'e': e++; } } return ok && e > 3; } ...
import System.IO main = withFile "unixdict.txt" ReadMode $ \h -> do words <- fmap lines $ hGetContents h putStrLn $ unlines $ filter valid words valid w = not (any (`elem` "aiou") w) && length (filter (=='e') w) > 3
Write the same algorithm in Haskell as shown in this C implementation.
#include <stdio.h> int min(int a, int b) { if (a < b) return a; return b; } int main() { int n; int numbers1[5] = {5, 45, 23, 21, 67}; int numbers2[5] = {43, 22, 78, 46, 38}; int numbers3[5] = {9, 98, 12, 98, 53}; int numbers[5] = {}; for (n = 0; n < 5; ++n) { numbers[n] = min...
import Data.List (transpose) numbers1, numbers2, numbers3 :: [Integer] numbers1 = [5, 45, 23, 21, 67] numbers2 = [43, 22, 78, 46, 38] numbers3 = [9, 98, 12, 98, 53] main :: IO () main = print $ minimum <$> transpose [numbers1, numbers2, numbers3]
Write the same code in Haskell as shown below in C.
#include <stdio.h> void mosaicMatrix(unsigned int n) { int i, j; for (i = 0; i < n; ++i) { for (j = 0; j < n; ++j) { if ((i + j) % 2 == 0) { printf("%s ", "1"); } else { printf("%s ", "0"); } } printf("\n"); } } in...
import Data.Matrix (Matrix, matrix) mosaic :: Int -> Matrix Int mosaic n = matrix n n ((`rem` 2) . succ . uncurry (+)) main :: IO () main = mapM_ (print . mosaic) [7, 8]
Maintain the same structure and functionality when rewriting this code in Haskell.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_WORD_SIZE 80 bool is_vowel(char ch) { switch (ch) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U': return true; } return false; } bo...
import Control.Monad (join) import Data.Bifunctor (bimap) import Data.List.Split (chunksOf) isLongAlternator :: String -> Bool isLongAlternator s = 9 < length s && all alternating (zip s $ tail s) alternating :: (Char, Char) -> Bool alternating = uncurry (/=) . join bimap isVowel isVowel :: Char -> Bool isVo...
Produce a functionally identical Haskell code for the snippet given in C.
#include<stdlib.h> #include<stdio.h> #define LEN 100 int main() { char **list; int num, i; scanf("%d",&num); list = (char**)malloc(num*sizeof(char*)); for(i=0;i<num;i++) { list[i] = (char*)malloc(LEN*sizeof(char)); fflush(stdin); fgets(list[i],LEN,stdin); } printf("\n"); for(i=0;i<...
import Control.Monad main = do number <- getLine input <- replicateM (read number) getLine mapM_ putStrLn input
Write the same algorithm in Haskell as shown in this C implementation.
#include <stdio.h> int divisible(int n) { int p = 1; int c, d; for (c=n; c; c /= 10) { d = c % 10; if (!d || n % d) return 0; p *= d; } return n % p; } int main() { int n, c=0; for (n=1; n<1000; n++) { if (divisible(n)) { printf("%...
import Data.List.Split (chunksOf) import Text.Printf divisible :: Int -> Bool divisible = divdgt <*> dgt where dgt = map (read . pure) . show divdgt x d = notElem 0 d && 0 /= x `mod` product d && all ((0 ==) . mod x) d numbers :: [Int] numbers = filter divisible [1 ..] main :: IO () m...
Generate an equivalent Haskell version of this C code.
#define PI 3.14159265358979323846 #define ABS(x) (x<0?-x:x) double arc_length(double radius, double angle1, double angle2) { return (360 - ABS(angle2 - angle1)) * PI / 180 * radius; } void main() { printf("%.7f\n",arc_length(10, 10, 120)); }
arcLength radius angle1 angle2 = (360.0 - (abs $ angle1 - angle2)) * pi * radius / 180.0 main = putStrLn $ "arcLength 10.0 10.0 120.0 = " ++ show (arcLength 10.0 10.0 120.0)
Please provide an equivalent version of this C code in Haskell.
#include <stdio.h> void lshift(int *l, size_t n) { int i, f; if (n < 2) return; f = l[0]; for (i = 0; i < n-1; ++i) l[i] = l[i+1]; l[n-1] = f; } int main() { int l[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int i; size_t n = 9; printf("Original list  : "); for (i = 0; i < n; ++i) pri...
rotated :: Int -> [a] -> [a] rotated n = ( (<*>) take . flip (drop . mod n) . cycle ) <*> length main :: IO () main = let xs = [1 .. 9] in putStrLn ("Initial list: " <> show xs <> "\n") >> putStrLn "Rotated 3 or 30 positions to the left:" >> print (rotated 3 xs) >> p...
Translate this program into Haskell but keep the logic exactly as in C.
#include <stdio.h> #define LIMIT 100000 int digitset(int num, int base) { int set; for (set = 0; num; num /= base) set |= 1 << num % base; return set; } int main() { int i, c = 0; for (i = 0; i < LIMIT; i++) if (digitset(i,10) == digitset(i,16)) printf("%6d%c", i, ++c%1...
import qualified Data.Set as S import Numeric (showHex) sameDigitSet :: (Integral a, Show a) => a -> [(a, String)] sameDigitSet n = [ (n, h) | let h = showHex n "", S.fromList h == S.fromList (show n) ] main = do print ("decimal", "hex") mapM_ print $ [0 .. 100000] >>= sameDigitSet
Write a version of this C function in Haskell with identical behavior.
#include <stdio.h> void specialMatrix(unsigned int n) { int i, j; for (i = 0; i < n; ++i) { for (j = 0; j < n; ++j) { if (i == j || i + j == n - 1) { printf("%d ", 1); } else { printf("%d ", 0); } } printf("\n"); } ...
twoDiagonalMatrix :: Int -> [[Int]] twoDiagonalMatrix n = flip (fmap . go) xs <$> xs where xs = [1 .. n] go x y | y == x = 1 | y == succ (subtract x n) = 1 | otherwise = 0 main :: IO () main = mapM_ putStrLn $ unlines . fmap (((' ' :) . show) =<<) . twoDiagonalMatrix <$...
Rewrite this program in Haskell while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <string.h> int main() { char word[128]; FILE *f = fopen("unixdict.txt","r"); if (!f) { fprintf(stderr, "Cannot open unixdict.txt\n"); return -1; } while (!feof(f)) { fgets(word, sizeof(word), f); if (strlen(word) > 12 && ...
import System.IO (readFile) import Data.List (isInfixOf) main = do txt <- readFile "unixdict.txt" let res = [ w | w <- lines txt, isInfixOf "the" w, length w > 11 ] putStrLn $ show (length res) ++ " words were found:" mapM_ putStrLn res
Change the following C code into Haskell without altering its purpose.
#include <stdio.h> void hollowMatrix(unsigned int n) { int i, j; for (i = 0; i < n; ++i) { for (j = 0; j < n; ++j) { if (i == 0 || i == n - 1 || j == 0 || j == n - 1) { printf("%d ", 1); } else { printf("%d ", 0); } } p...
import Data.List (intercalate, intersperse) import Data.List.Split (chunksOf) import System.Environment (getArgs) square :: Int -> String square n = intercalate "\n" $ map (intersperse ' ') $ chunksOf n sq where sq = [sqChar r c | r <- [0..n-1], c <- [0..n-1]] sqChar r c = if isBorder r c then '1' else '0'...
Convert the following code from C to Haskell, ensuring the logic remains intact.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct node_t { char *elem; int length; struct node_t *next; } node; node *make_node(char *s) { node *t = malloc(sizeof(node)); t->elem = s; t->length = strlen(s); t->next = NULL; return t; } void append_node(node *hea...
import Data.List (transpose) longestCommonSuffix :: [String] -> String longestCommonSuffix = foldr (flip (<>) . return . head) [] . takeWhile (all =<< (==) . head) . transpose . fmap reverse main :: IO () main = mapM_ (putStrLn . longestCommonSuffix) [ [ "Sunday" , "Monday" , "Tuesday" ...
Translate this program into Haskell but keep the logic exactly as in C.
#include <stdio.h> #include <stdlib.h> #include <math.h> int compare(const void *a, const void *b) { int ia = *(int*)a; int ib = *(int*)b; return (ia>ib) - (ia<ib); } int main() { int pows[16]; int a, b, i=0; for (a=2; a<=5; a++) for (b=2; b<=5; b++) pows[i++] = pow(a,...
import qualified Data.Set as S distinctPowerNumbers :: Int -> Int -> [Int] distinctPowerNumbers a b = (S.elems . S.fromList) $ (fmap (^) >>= (<*>)) [a .. b] main :: IO () main = print $ distinctPowerNumbers 2 5
Translate this program into Haskell but keep the logic exactly as in C.
#include <stdio.h> #include <string.h> char *uniques(char *str[], char *buf) { static unsigned counts[256]; unsigned i; char *s, *o = buf; memset(counts, 0, 256 * sizeof(unsigned)); for (; *str; str++) for (s = *str; *s; s++) counts[(unsigned) *s]++; for (i=0; i<25...
import Data.List (group, sort) uniques :: [String] -> String uniques ks = [c | (c : cs) <- (group . sort . concat) ks, null cs] main :: IO () main = putStrLn $ uniques [ "133252abcdeeffd", "a6789798st", "yxcdfgxcyz" ]
Can you help me rewrite this code in Haskell instead of C, keeping it the same logically?
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <termios.h> #include <time.h> #include <unistd.h> #define D_INVALID -1 #define D_UP 1 #define D_DOWN 2 #define D_RIGHT 3 #define D_LEFT 4 const long values[] = { 0, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048 }; const char *c...
import System.IO import Data.List import Data.Maybe import Control.Monad import Data.Random import Data.Random.Distribution.Categorical import System.Console.ANSI import Control.Lens prob4 :: Double prob4 = 0.1 type Position = [[Int]] combine, shift :: [Int]->[Int] combine (x:y:l) | x==y = (2*x) : combine l combi...
Convert the following code from C to Haskell, ensuring the logic remains intact.
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <locale.h> bool isPrime(int n) { if (n < 2) return false; if (n%2 == 0) return n == 2; if (n%3 == 0) return n == 3; int d = 5; while (d*d <= n) { if (n%d == 0) return false; d += 2; if (n%d == 0) return fal...
import Control.Applicative import Data.List ( sort ) import Data.List.Split ( chunksOf ) isPrime :: Int -> Bool isPrime n |n == 2 = True |n == 1 = False |otherwise = null $ filter (\i -> mod n i == 0 ) [2 .. root] where root :: Int root = floor $ sqrt $ fromIntegral n solution :: [Int] solut...