Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Translate this program into AutoHotKey but keep the logic exactly as in Java.
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(" ...
testAngles := [-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000] result .= "Degrees Degrees Gradians Mils Radians`n" for i, a in testAngles result .= a "`t" Deg2Deg(a) "`t" Deg2Grad(a) "`t" Deg2Mil(a) "`t" Deg2Rad(a) "`n" result .= "`nGradians Degrees Gradians Mils Radian...
Change the following Java code into AutoHotKey without altering its purpose.
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...
FileRead, inventory, xmlfile.xml RegExMatch(inventory, "<item.*?</item>", item1) MsgBox % item1 pos = 1 While, pos := RegExMatch(inventory, "<price>(.*?)</price>", price, pos + 1) MsgBox % price1 While, pos := RegExMatch(inventory, "<name>.*?</name>", name, pos + 1) names .= name . "`n" MsgBox % names
Generate a AutoHotKey translation of this Java snippet without changing its computational steps.
import java.util.*; public class RankingMethods { final static String[] input = {"44 Solomon", "42 Jason", "42 Errol", "41 Garry", "41 Bernard", "41 Barry", "39 Stephen"}; public static void main(String[] args) { int len = input.length; Map<String, int[]> map = new TreeMap<>((a, b) -...
Rank(data, opt:=1){  for index, val in StrSplit(data, "`n", "`r") { RegExMatch(val, "^(\d+)\s+(.*)", Match) if !(Match1=prev) n := index prev := Match1 Res1 .= n "`t" Match "`n" Res4 .= index "`t" Match "`n" Temp .= n ":" index " " Match "`n" } n:=0 while pos := RegExMatch(Temp, "`asm)^(\d+).*?\R(?!\...
Produce a functionally identical AutoHotKey code for the snippet given in Java.
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"); ...
data = %A_scriptdir%\rosettaconfig.txt outdata = %A_scriptdir%\rosettaconfig.tmp FileDelete, %outdata% NUMBEROFBANANAS := 1024 numberofstrawberries := 560 NEEDSPEELING = "0" FAVOURITEFRUIT := "bananas" SEEDSREMOVED = "1" BOOL0 = "0" BOOL1 = "1" NUMBER1 := 1 number0 := 0 STRINGA := "string here" parameters = bool0|bo...
Generate a AutoHotKey translation of this Java snippet without changing its computational steps.
import java.util.HashMap; import java.util.Map; import java.util.regex.*; public class StraddlingCheckerboard { final static String[] keyvals = {"H:0", "O:1", "L:2", "M:4", "E:5", "S:6", "R:8", "T:9", "A:30", "B:31", "C:32", "D:33", "F:34", "G:35", "I:36", "J:37", "K:38", "N:39", "P:70", "Q:71", "...
board := " ( ET AON RIS BCDFGHJKLM PQ/UVWXYZ. )" Text = One night-it was on the twentieth of March, 1888-I was returning StringUpper, Text, Text Text := RegExReplace(text, "[^A-Z0-9]") Num2 := InStr(board, A_Space) -1 Num3 := InStr(board, A_Space, true, Num1+1) -1 Loop Parse, Text { char := A_LoopField ...
Keep all operations the same but rewrite the snippet in AutoHotKey.
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...
WordList := URL_ToVar("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") WordList := RegExReplace(WordList, "i)cie", "", cieN) WordList := RegExReplace(WordList, "i)cei", "", ceiN) RegExReplace(WordList, "i)ie", "", ieN) RegExReplace(WordList, "i)ei", "", eiN) cei := ceiN / cieN > 2 ? "plausible" : "implausible" ...
Change the programming language of this snippet from Java to AutoHotKey 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...
WordList := URL_ToVar("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") WordList := RegExReplace(WordList, "i)cie", "", cieN) WordList := RegExReplace(WordList, "i)cei", "", ceiN) RegExReplace(WordList, "i)ie", "", ieN) RegExReplace(WordList, "i)ei", "", eiN) cei := ceiN / cieN > 2 ? "plausible" : "implausible" ...
Change the following Java code into AutoHotKey without altering its purpose.
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); ...
Size := Size2 := 10 celula := [], Deltas := ["-1,0","1,1","0,-1","0,1"], Width := Size * 2.5 Gui, font, S%Size% Gui, add, text, y1 loop, 19 { Row := A_Index loop, 19 { Col := A_Index Gui, add, button, % (Col=1 ? "xs y+1" : "x+1 yp") " v" Col "_" Row " w" Width " -TabStop" celula[Col,Row] := 0 GuiControl, hi...
Change the programming language of this snippet from Java to AutoHotKey without modifying what it does.
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); ...
Size := Size2 := 10 celula := [], Deltas := ["-1,0","1,1","0,-1","0,1"], Width := Size * 2.5 Gui, font, S%Size% Gui, add, text, y1 loop, 19 { Row := A_Index loop, 19 { Col := A_Index Gui, add, button, % (Col=1 ? "xs y+1" : "x+1 yp") " v" Col "_" Row " w" Width " -TabStop" celula[Col,Row] := 0 GuiControl, hi...
Can you help me rewrite this code in AutoHotKey instead of Java, keeping it the same logically?
import java.awt.*; import static java.lang.Math.*; import javax.swing.*; public class XiaolinWu extends JPanel { public XiaolinWu() { Dimension dim = new Dimension(640, 640); setPreferredSize(dim); setBackground(Color.white); } void plot(Graphics2D g, double x, double y, double c)...
#SingleInstance, Force #NoEnv SetBatchLines, -1 pToken := Gdip_Startup() global pBitmap := Gdip_CreateBitmap(500, 500) drawLine(100,50,400,400) Gdip_SaveBitmapToFile(pBitmap, A_ScriptDir "\linetest.png") Gdip_DisposeImage(pBitmap) Gdip_Shutdown(pToken) Run, % A_ScriptDir "\linetest.png" ExitApp plot(x, y, c) { A ...
Convert this Java snippet to AutoHotKey and keep its semantics consistent.
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", ...
Next_highest_int(num){ Arr := [] for i, v in permute(num) Arr[v] := true for n, v in Arr if found return n else if (n = num) found := true return 0 } permute(str, k:=0, l:=1){ static res:=[] r := StrLen(str) k := k ? k : r if (l = r) return SubStr(str, 1, k) i := l while (i <= r){ str := swap...
Produce a functionally identical AutoHotKey code for the snippet given in Java.
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", ...
Next_highest_int(num){ Arr := [] for i, v in permute(num) Arr[v] := true for n, v in Arr if found return n else if (n = num) found := true return 0 } permute(str, k:=0, l:=1){ static res:=[] r := StrLen(str) k := k ? k : r if (l = r) return SubStr(str, 1, k) i := l while (i <= r){ str := swap...
Convert this Java snippet to AutoHotKey and keep its semantics consistent.
import java.awt.Robot public static void type(String str){ Robot robot = new Robot(); for(char ch:str.toCharArray()){ if(Character.isUpperCase(ch)){ robot.keyPress(KeyEvent.VK_SHIFT); robot.keyPress((int)ch); robot.keyRelease((int)ch); robot.keyRelease(KeyEvent.VK_SHIFT);...
run, cmd /k WinWait, ahk_class ConsoleWindowClass controlsend, ,hello console, ahk_class ConsoleWindowClass
Can you help me rewrite this code in AutoHotKey instead of Java, keeping it the same logically?
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}) { ...
Four_is_magic(num){ nubmer := num while (num <> 4) result .= (res := spell(num)) " is " spell(num := StrLen(res)) ", " return PrettyNumber(nubmer) " " result "four is magic!" } Spell(n) {  Static p1=" thousand ",p2=" million ",p3=" billion ",p4=" trillion ",p5=" quadrillion ",p6=" quintillion " , p7=" sextill...
Rewrite this program in AutoHotKey while keeping its functionality equivalent to the Java version.
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.geom.Path2D; import static java.lang.Math.*; import java.util.Random; import javax.swing.*; public class SierpinskiPentagon extends JPanel { final double degrees072 = toRadians(72); final double scaleFactor = 1 / (2 + cos(degrees0...
W := H := 640 hw := W / 2 margin := 20 radius := hw - 2 * margin side := radius * Sin(PI := 3.141592653589793 / 5) * 2 order := 5 gdip1() drawPentagon(hw, 3*margin, side, order, 1) return drawPentagon(x, y, side, depth, colorIndex){ global G, hwnd1, hdc, Width, Height Red := "0xFFFF0000" Green ...
Keep all operations the same but rewrite the snippet in AutoHotKey.
import java.awt.Point; import java.util.*; public class ZhangSuen { final static String[] image = { " ", " ################# ############# ", " ################## ################ ", ...
FileIn := A_ScriptDir "\Zhang-Suen.txt" FileOut := A_ScriptDir "\NewFile.txt" if (!FileExist(FileIn)) { MsgBox, 48, File Not Found, % "File """ FileIn """ not found." ExitApp } S := {} N := [2,3,4,5,6,7,8,9,2] Loop, Read, % FileIn { LineNum := A_Index Loop, Parse, A_LoopReadLine S[LineNum, A_Index] := A_LoopFi...
Rewrite this program in AutoHotKey while keeping its functionality equivalent to the Java version.
import java.util.Arrays; import java.util.Collections; import java.util.List; public class Chess960{ private static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R'); public static List<Character> generateFirstRank(){ do{ Collections.shuffle(pieces); }while(!check(pieces.toString().repl...
Loop, 5 Out .= Chess960() "`n" MsgBox, % RTrim(Out, "`n") Chess960() { P := {} P[K := Rand(2, 7)] := Chr(0x2654) P[Rand(1, K - 1)] := Chr(0x2656) P[Rand(K + 1, 8)] := Chr(0x2656) Loop, 8 Remaining .= P[A_Index] ? "" : A_Index "`n" Sort, Remaining, Random N P[Bishop1 := SubStr(Remaining, 1, 1)] := Chr(0x26...
Write the same algorithm in AutoHotKey as shown in this Java implementation.
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; public class UPC { private static final int SEVEN = 7; private static final Map<String, Integer> LEFT_DIGITS = Map.of( " ...
UPC2Dec(code){ lBits :={" ## #":0," ## #":1," # ##":2," #### #":3," # ##":4," ## #":5," # ####":6," ### ##":7," ## ###":8," # ##":9} xlBits:={"# ## ":0,"# ## ":1,"## # ":2,"# #### ":3,"## # ":4,"# ## ":5,"#### # ":6,"## ### ":7,"### ## ":8,"## # ":9} rBits :={"### # ":0,"## ## ":1,...
Rewrite this program in AutoHotKey while keeping its functionality equivalent to the Java version.
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...
h := RegisterForEvents("AutoHotkey") SendWinLogEvent(h, "Test Message") DeregisterForEvents(h) SendWinLogEvent(hSource, String="", evType=0x0004, evId=0x03EA, evCat=0, pData=0) { Ptr := A_PtrSize ? "Ptr" : "UInt" LPCtSTRs := A_PtrSize ? "Ptr*" : "UInt" StringPut := A_IsUnicode ? "StrPut" : "StrPut2" VarSetCap...
Please provide an equivalent version of this Java code in AutoHotKey.
import java.util.HashMap; import java.util.Map; public class SpellingOfOrdinalNumbers { public static void main(String[] args) { for ( long test : new long[] {1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003L} ) { System.out.printf("%d = %s%n", test, toOrdinal(test)); ...
OrdinalNumber(n){ OrdinalNumber := {"one":"first", "two":"second", "three":"third", "five":"fifth", "eight":"eighth", "nine":"ninth", "twelve": "twelfth"} RegExMatch(n, "\w+$", m) return (OrdinalNumber[m] ? RegExReplace(n, "\w+$", OrdinalNumber[m]) : n "th") } Spell(n) {  Static p1=" thousand ",p2=" million ",p...
Port the provided Java code into AutoHotKey while preserving the original functionality.
import java.util.regex.Matcher; import java.util.regex.Pattern; public class ParseIPAddress { public static void main(String[] args) { String [] tests = new String[] {"192.168.0.1", "127.0.0.1", "256.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "[32e::12f]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4...
ParseIP(Address){ return InStr(A_LoopField, ".") ? IPv4(Address) : IPv6(Address) } IPv4(Address){ for i, v in StrSplit(Address, "."){ x := StrSplit(v, ":") num .= SubStr("00" . Format("{:X}", x.1), -1) port := x.2 ? x.2 : "" } return [num, port] } IPv6(Address){ for i, v in StrSplit(Address, "]") if i =...
Write the same code in AutoHotKey as shown below in Java.
import java.util.*; import java.awt.geom.*; public class LineCircleIntersection { public static void main(String[] args) { try { demo(); } catch (Exception e) { e.printStackTrace(); } } private static void demo() throws NoninvertibleTransformException { ...
data := [[[3, -5], 3, [-10, 11], [10, -9], 0] , [[3, -5], 3, [-10, 11], [-11, 12], 1] , [[3, -5], 3, [3, -2], [7, -2], 1] , [[0, 0], 4, [0, -3], [0, 6], 0] , [[0, 0], 4, [0, -3], [0, 6], 1] , [[4, 2], 5, [6, 3], [10,...
Maintain the same structure and functionality when rewriting this code in AutoHotKey.
public static int findNumOfDec(double x){ String str = String.valueOf(x); if(str.endsWith(".0")) return 0; else return (str.substring(str.indexOf('.')).length() - 1); }
for i, v in [10, "10", 12.345, "12.345", 12.3450, "12.3450"] output .= v " has " StrLen(StrSplit(v, ".").2) " decimals.`n" MsgBox % output
Rewrite the snippet below in AutoHotKey so it works the same as the original Java code.
int counter = 100; void setup(){ size(1000,1000); } void draw(){ for(int i=0;i<20;i++){ fill(counter - 5*i); rect(10 + 20*i,10 + 20*i,980 - 40*i,980 - 40*i); } counter++; if(counter > 255) counter = 100; delay(100); }
Vibrating_rectangles() OnExit, Exit return Vibrating_rectangles(){ global pToken := Gdip_Startup() colors := ["0xFFFF0000", "0xFF00FF00", "0xFF0000FF", "0xFFFFFF00", "0xFF00FFFF", "0xFFFF00FF", "0xFFC0C0C0" , "0xFF808080", "0xFF800000", "0xFF808000", "0xFF008000", "0xFF800080", "0xFF008080...
Transform the following Java implementation into AutoHotKey, maintaining the same output and logic.
import java.util.*; public class Hopido { final static String[] board = { ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0..."}; final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}}; static int[...
SolveHopido(Grid, Locked, Max, row, col, num:=1, R:="", C:=""){ if (R&&C) { Grid[R, C] := ">" num row:=R, col:=C } num++ if (num=max) return map(Grid) if locked[num] { row := StrSplit((StrSplit(locked[num], ",").1) , ":").1 col := StrSplit((StrSplit(loc...
Please provide an equivalent version of this Java code in AutoHotKey.
import java.util.*; public class Hopido { final static String[] board = { ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0..."}; final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}}; static int[...
SolveHopido(Grid, Locked, Max, row, col, num:=1, R:="", C:=""){ if (R&&C) { Grid[R, C] := ">" num row:=R, col:=C } num++ if (num=max) return map(Grid) if locked[num] { row := StrSplit((StrSplit(locked[num], ",").1) , ":").1 col := StrSplit((StrSplit(loc...
Maintain the same structure and functionality when rewriting this code in AutoHotKey.
import java.util.*; public class Numbrix { final static String[] board = { "00,00,00,00,00,00,00,00,00", "00,00,46,45,00,55,74,00,00", "00,38,00,00,43,00,00,78,00", "00,35,00,00,00,00,00,71,00", "00,00,33,00,00,00,59,00,00", "00,17,00,00,00,00,00,67,00", "00...
SolveNumbrix(Grid, Locked, Max, row, col, num:=1, R:="", C:=""){ if (R&&C) { Grid[R, C] := ">" num row:=R, col:=C } num++ if (num=max) return map(Grid) if locked[num] { row := StrSplit((StrSplit(locked[num], ",").1) , ":").1 col := StrSplit((StrSplit(l...
Convert the following code from Java to AutoHotKey, ensuring the logic remains intact.
import java.util.*; public class Numbrix { final static String[] board = { "00,00,00,00,00,00,00,00,00", "00,00,46,45,00,55,74,00,00", "00,38,00,00,43,00,00,78,00", "00,35,00,00,00,00,00,71,00", "00,00,33,00,00,00,59,00,00", "00,17,00,00,00,00,00,67,00", "00...
SolveNumbrix(Grid, Locked, Max, row, col, num:=1, R:="", C:=""){ if (R&&C) { Grid[R, C] := ">" num row:=R, col:=C } num++ if (num=max) return map(Grid) if locked[num] { row := StrSplit((StrSplit(locked[num], ",").1) , ":").1 col := StrSplit((StrSplit(l...
Can you help me rewrite this code in AutoHotKey instead of Java, keeping it the same logically?
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...
test := ["H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O" , "Uue", "C6H4O2(O)H)4", "X2O"] for i, str in test result .= str "`t`t`t> " Chemical_calculator(str) "`n" MsgBox, 262144, , % result return Chemical_calculator(str){ if (RegExReplace(str, "\(([^...
Produce a functionally identical AutoHotKey code for the snippet given in Java.
import java.util.Stack; public class ArithmeticEvaluation { public interface Expression { BigRational eval(); } public enum Parentheses {LEFT} public enum BinaryOperator { ADD('+', 1), SUB('-', 1), MUL('*', 2), DIV('/', 2); public final char symbol; ...
calcLexer := makeCalcLexer() string := "((3+4)*(7*9)+3)+4" tokens := tokenize(string, calcLexer) msgbox % printTokens(tokens) ast := expr() msgbox % printTree(ast) msgbox % expression := evalTree(ast) filedelete expression.ahk fileappend, % "msgbox % " expression, expression.ahk run, expression.ahk return expr() { ...
Convert this Java snippet to AutoHotKey and keep its semantics consistent.
import java.util.Stack; public class ArithmeticEvaluation { public interface Expression { BigRational eval(); } public enum Parentheses {LEFT} public enum BinaryOperator { ADD('+', 1), SUB('-', 1), MUL('*', 2), DIV('/', 2); public final char symbol; ...
calcLexer := makeCalcLexer() string := "((3+4)*(7*9)+3)+4" tokens := tokenize(string, calcLexer) msgbox % printTokens(tokens) ast := expr() msgbox % printTree(ast) msgbox % expression := evalTree(ast) filedelete expression.ahk fileappend, % "msgbox % " expression, expression.ahk run, expression.ahk return expr() { ...
Keep all operations the same but rewrite the snippet in AutoHotKey.
import java.io.*; public class SierpinskiCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_curve.svg"))) { SierpinskiCurve s = new SierpinskiCurve(writer); s.currentAngle = 45; s.currentX = 5; ...
SierpinskiW := 500 SierpinskiH := 500 level := 5 cx := SierpinskiW/2 cy := SierpinskiH h := cx / (2**(level+1)) Arr := [] squareCurve(level) xmin := xmax := ymin := ymax := 0 for i, point in Arr { xmin := A_Index = 1 ? point.x : xmin < point.x ? xmin : point.x xmax := point.x > xmax ? point.x : xmax ymin := A_I...
Write the same code in AutoHotKey as shown below in Java.
import java.io.*; public class SierpinskiCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_curve.svg"))) { SierpinskiCurve s = new SierpinskiCurve(writer); s.currentAngle = 45; s.currentX = 5; ...
SierpinskiW := 500 SierpinskiH := 500 level := 5 cx := SierpinskiW/2 cy := SierpinskiH h := cx / (2**(level+1)) Arr := [] squareCurve(level) xmin := xmax := ymin := ymax := 0 for i, point in Arr { xmin := A_Index = 1 ? point.x : xmin < point.x ? xmin : point.x xmax := point.x > xmax ? point.x : xmax ymin := A_I...
Rewrite this program in AutoHotKey while keeping its functionality equivalent to the Java version.
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.*; public class Backup { public static void saveWithBackup(String filename, String... data) throws IOException { Path file = Paths.get(filename).toRealPath(); File backFile = new File(filename + ".backup...
targetfile := "ahk-file" if FileExist(targetfile) FileMove, %targetfile%, %targetfile%.bak else FileAppend,, %targetfile% file := FileOpen(targetfile, "w") if !IsObject(file) { MsgBox Can't open "%FileName%" for writing. return } file.Write("This is a test string.`r`n") file.Close()
Port the provided Java code into AutoHotKey while preserving the original functionality.
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.*; public class Backup { public static void saveWithBackup(String filename, String... data) throws IOException { Path file = Paths.get(filename).toRealPath(); File backFile = new File(filename + ".backup...
targetfile := "ahk-file" if FileExist(targetfile) FileMove, %targetfile%, %targetfile%.bak else FileAppend,, %targetfile% file := FileOpen(targetfile, "w") if !IsObject(file) { MsgBox Can't open "%FileName%" for writing. return } file.Write("This is a test string.`r`n") file.Close()
Translate this program into AutoHotKey but keep the logic exactly as in Java.
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...
FileRead, text, %1% langs = ada,awk,autohotkey,etc slang = /lang slang := "<" . slang . "/>" Loop, Parse, langs, `, { tag1 = <%A_LoopField%> tag2 = </%A_LoopField%> text := RegExReplace(text, tag1, "<lang " . A_LoopField . ">") text := RegExReplace(text, tag2, slang) text := RegExReplace(text, "<code (.+?)>(...
Rewrite this program in Delphi while keeping its functionality equivalent to the Java version.
public static void shell(int[] a) { int increment = a.length / 2; while (increment > 0) { for (int i = increment; i < a.length; i++) { int j = i; int temp = a[i]; while (j >= increment && a[j - increment] > temp) { a[j] = a[j - increment]; j = j - increment; } a[j] = temp; } if (increment...
Procedure ShellSort(var buf:Array of Integer); const gaps:array[0..7] of Integer = (701, 301, 132, 57, 23, 10, 4, 1); var whichGap, i, j, n, gap, temp : Integer; begin n := high(buf); for whichGap := 0 to high(gaps) do begin gap := gaps[whichGap]; for i := gap to n do begin temp := buf[i]; ...
Write the same algorithm in Delphi as shown in this Java implementation.
package linenbr7; import java.io.*; public class LineNbr7 { public static void main(String[] args) throws Exception { File f = new File(args[0]); if (!f.isFile() || !f.canRead()) throw new IOException("can't read " + args[0]); BufferedReader br = new BufferedReader(new FileRe...
program Read_a_specific_line_from_a_file; uses System.SysUtils; function ReadLine(position: Cardinal; FileName: TFileName): string; begin Result := ''; if not FileExists(FileName) then raise Exception.Create('Error: File does not exist.'); var F: TextFile; var line: string; AssignFile(F, FileName)...
Write the same algorithm in Delphi as shown in this Java implementation.
package linenbr7; import java.io.*; public class LineNbr7 { public static void main(String[] args) throws Exception { File f = new File(args[0]); if (!f.isFile() || !f.canRead()) throw new IOException("can't read " + args[0]); BufferedReader br = new BufferedReader(new FileRe...
program Read_a_specific_line_from_a_file; uses System.SysUtils; function ReadLine(position: Cardinal; FileName: TFileName): string; begin Result := ''; if not FileExists(FileName) then raise Exception.Create('Error: File does not exist.'); var F: TextFile; var line: string; AssignFile(F, FileName)...
Write the same code in Delphi as shown below in Java.
module OptionalParameters { typedef Type<String >.Orderer as ColumnOrderer; typedef Type<String[]>.Orderer as RowOrderer; static String[][] sort(String[][] table, ColumnOrderer? orderer = Null, Int column = 0, ...
program Optional_parameters; uses System.SysUtils; type TRow = TArray<string>; TOrderingFun = TFunc<TRow, TRow, Boolean>; TTable = array of TRow; TRowHelper = record helper for TRow public procedure Swap(var other: TRow); function ToString: string; function Length: Integer; end; TTab...
Rewrite the snippet below in Delphi so it works the same as the original Java code.
import java.util.function.Consumer; public class RateCounter { public static void main(String[] args) { for (double d : benchmark(10, x -> System.out.print(""), 10)) System.out.println(d); } static double[] benchmark(int n, Consumer<Integer> f, int arg) { double[] timings = ne...
program Rate_counter; uses System.SysUtils, System.Diagnostics; var a: Integer; function TickToString(Tick: Int64): string; var ns, us, ms, s, t: Cardinal; begin Result := ''; ns := (Tick mod 10) * 100; if ns > 0 then Result := format(' %dns', [ns]); t := Tick div 10; us := t mod 1000; if ...
Generate a Delphi translation of this Java snippet without changing its computational steps.
class Metronome{ double bpm; int measure, counter; public Metronome(double bpm, int measure){ this.bpm = bpm; this.measure = measure; } public void start(){ while(true){ try { Thread.sleep((long)(1000*(60.0/bpm))); }catch(InterruptedException e) { e.printStackTrace(); } counter++; if ...
program Metronome; uses Winapi.Windows, System.SysUtils; procedure StartMetronome(bpm: double; measure: Integer); var counter: Integer; begin counter := 0; while True do begin Sleep(Trunc(1000 * (60.0 / bpm))); inc(counter); if counter mod measure = 0 then writeln('TICK') else ...
Write a version of this Java function in Delphi with identical behavior.
public class RepString { static final String[] input = {"1001110011", "1110111011", "0010010010", "1010101010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1", "0100101"}; public static void main(String[] args) { for (String s : input) System.out.printf("%s :...
program Rep_string; uses System.SysUtils; const m = '1001110011'#10 + '1110111011'#10 + '0010010010'#10 + '1010101010'#10 + '1111111111'#10 + '0100101101'#10 + '0100100'#10 + '101'#10 + '11'#10 + '00'#10 + '1'; function Rep(s: st...
Port the provided Java code into Delphi while preserving the original functionality.
import java.util.stream.IntStream; public class Letters { public static void main(String[] args) throws Exception { System.out.print("Upper case: "); IntStream.rangeClosed(0, 0x10FFFF) .filter(Character::isUpperCase) .limit(72) .forEach(n -> System...
program Idiomatically_determine_all_the_lowercase_and_uppercase_letters; uses System.SysUtils, System.Character; begin var count := 0; Write('Upper case: '); for var i := 0 to $10FFFF do if char(i).IsUpper then begin write(char(i)); inc(count); if count >= 72 then Break; ...
Change the programming language of this snippet from Java to Delphi without modifying what it does.
import java.util.concurrent.Semaphore; public class VolatileClass{ public Semaphore mutex = new Semaphore(1); public void needsToBeSynched(){ } }
unit main; interface uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms, System.SyncObjs, Vcl.StdCtrls; type TForm1 = class(TForm) mmo1: TMemo; btn1: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btn1Click(Sender...
Keep all operations the same but rewrite the snippet in Delphi.
public class OddWord { interface CharHandler { CharHandler handle(char c) throws Exception; } final CharHandler fwd = new CharHandler() { public CharHandler handle(char c) { System.out.print(c); return (Character.isLetter(c) ? fwd : rev); } }; class Reverser extends Thread implements Ch...
program Odd_word_problem; uses System.SysUtils, System.Console, System.Character; function doChar(isOdd: boolean; f: TProc = nil): Boolean; begin var c: char := Console.ReadKey(True).KeyChar; if not isOdd then Write(c); if c.IsLetter then exit(doChar(isOdd, procedure begin ...
Preserve the algorithm and functionality while converting the code from Java to Delphi.
public class PCG32 { private static final long N = 6364136223846793005L; private long state = 0x853c49e6748fea9bL; private long inc = 0xda3e39cb94b95bdbL; public void seed(long seedState, long seedSequence) { state = 0; inc = (seedSequence << 1) | 1; nextInt(); state = ...
program PCG32_test; uses System.SysUtils, Velthuis.BigIntegers, System.Generics.Collections; type TPCG32 = class public FState: BigInteger; FInc: BigInteger; mask64: BigInteger; mask32: BigInteger; k: BigInteger; constructor Create(seedState, seedSequence: BigInteger); overload; ...
Preserve the algorithm and functionality while converting the code from Java to Delphi.
public class XorShiftStar { private static final long MAGIC = Long.parseUnsignedLong("2545F4914F6CDD1D", 16); private long state; public void seed(long num) { state = num; } public int nextInt() { long x; int answer; x = state; x = x ^ (x >>> 12); x...
program Xorshift_star; uses System.SysUtils, System.Math; type TXorshiftStar = record private state: uint64; const k = $2545F4914F6CDD1D; public constructor Create(aState: uint64); procedure Seed(aState: uint64); function NextInt: uint32; function NextFloat: Extended; end; ...
Change the programming language of this snippet from Java to Delphi without modifying what it does.
import java.io.*; import java.util.*; public class ChangeableWords { public static void main(String[] args) { try { final String fileName = "unixdict.txt"; List<String> dictionary = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader(fileNam...
var Dict: TStringList; procedure DoChangeWords(Memo: TMemo); var I,J,K,Inx,Cnt: integer; var S: string; procedure Display(OldStr,NewStr: string); begin Inc(Cnt); Memo.Lines.Add(IntToStr(Cnt)+': '+OldStr+' '+NewStr); end; begin Cnt:=0; for I:=0 to Dict.Count-1 do begin if Length(Dict[I])>=12 then beg...
Change the programming language of this snippet from Java to Delphi without modifying what it does.
import java.util.Scanner; public class Main { public static void doStuff(String word){ System.out.println(word); } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = Integer.parseInt(in.nextLine()); for(int i=0; i<n; i++){ String word = in.nextLine(); doStuff(...
program Output_for_Lines_of_Text; uses System.SysUtils; function QueryIntNumber(): Integer; var val: string; begin Result := 0; repeat Writeln('Digite a number(Enter to confirm):'); Readln(val); if not TryStrToInt(val, Result) then begin Writeln('"', val, '" is not a valid number.'); ...
Write the same algorithm in Delphi as shown in this Java implementation.
public static double arcLength(double r, double a1, double a2){ return (360.0 - Math.abs(a2-a1))*Math.PI/180.0 * r; }
program Length_of_an_arc; uses System.SysUtils; function arc_length(radius, angle1, angle2: Double): Double; begin Result := (360 - abs(angle2 - angle1)) * PI / 180 * radius; end; begin Writeln(Format('%.7f', [arc_length(10, 10, 120)])); Readln; end.
Produce a functionally identical Delphi code for the snippet given in Java.
import java.util.List; import java.util.Arrays; import java.util.Collections; public class RotateLeft { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); System.out.println("original: " + list); Collections.rotate(list, -3); Syst...
program Shift_list_elements_to_left_by_3; uses System.SysUtils, Boost.Int; var List: TArray<Integer>; begin List := [1, 2, 3, 4, 5, 6, 7, 8, 9]; writeln('Original list  :', list.ToString); List.shift(3); writeln('Shifted left by 3 :', list.ToString); Readln; end.
Ensure the translated Delphi code behaves exactly like the original Java snippet.
size(640,480); stroke(#ffff00); ellipse(random(640),random(480),1,1);
program Draw_a_pixel2; uses Windows, Messages, SysUtils; const WIN_WIDTH = 640; WIN_HEIGHT = 480; var Msg: TMSG; LWndClass: TWndClass; hMainHandle: HWND; procedure Paint(Handle: hWnd); forward; procedure ReleaseResources; begin PostQuitMessage(0); end; function WindowProc(hWnd, Msg: Longint; w...
Translate this program into Delphi but keep the logic exactly as in Java.
import java.util.List; public class App { private static String lcs(List<String> a) { var le = a.size(); if (le == 0) { return ""; } if (le == 1) { return a.get(0); } var le0 = a.get(0).length(); var minLen = le0; for (int i = ...
program Longest_common_suffix; uses System.SysUtils, Types; type TStringDynArrayHelper = record helper for TStringDynArray private class function Compare(const s: string; a: TStringDynArray; subSize: integer): Boolean; public function Reverse(value: string): string; function LongestSuffi...
Change the programming language of this snippet from Java to Delphi without modifying what it does.
package rosettacode.heredoc; public class MainApp { public static void main(String[] args) { String hereDoc = """ This is a multiline string. It includes all of this text, but on separate lines in the code. """; System.out.println(hereDoc); } }
PrintLn("This is a multiline ""string"" sample");
Ensure the translated Delphi code behaves exactly like the original Java snippet.
package rosettacode.heredoc; public class MainApp { public static void main(String[] args) { String hereDoc = """ This is a multiline string. It includes all of this text, but on separate lines in the code. """; System.out.println(hereDoc); } }
PrintLn("This is a multiline ""string"" sample");
Translate the given Java code snippet into Delphi without altering its behavior.
class MD5 { private static final int INIT_A = 0x67452301; private static final int INIT_B = (int)0xEFCDAB89L; private static final int INIT_C = (int)0x98BADCFEL; private static final int INIT_D = 0x10325476; private static final int[] SHIFT_AMTS = { 7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23,...
program MD5Implementation; uses System.SysUtils, System.Classes; type TTestCase = record hashCode: string; _: string; end; var testCases: array[0..6] of TTestCase = (( hashCode: 'D41D8CD98F00B204E9800998ECF8427E'; _: '' ), ( hashCode: '0CC175B9C0F1B6A831C399E269772661'; _: 'a' ...
Port the following code from Java to Delphi with equivalent syntax and logic.
public class HistoryVariable { private Object value; public HistoryVariable(Object v) { value = v; } public void update(Object v) { value = v; } public Object undo() { return value; } @Override public String toString() { return valu...
program History_variables; uses System.SysUtils; type THistoryVarType = record value: variant; timestamp: TDateTime; function ToString: string; end; THistoryVar = record Fvalue: variant; FHistory: TArray<THistoryVarType>; private procedure SetValue(const Value: Variant); funct...
Rewrite the snippet below in Delphi so it works the same as the original Java code.
module MultiplyExample { static <Value extends Number> Value multiply(Value n1, Value n2) { return n1 * n2; } void run() { (Int i1, Int i2) = (7, 3); Int i3 = multiply(i1, i2); (Double d1, Double d2) = (2.7182818, 3.1415); Double d3 = multiply...
function multiply(a, b: integer): integer; begin result := a * b; end;
Preserve the algorithm and functionality while converting the code from Java to Delphi.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class SuccessivePrimeDifferences { private static Integer[] sieve(int limit) { List<Integer> primes = new ArrayList<>(); primes.add(2); boolean[] c = new boolean[limit + 1]; int p = 3; ...
program Successive_prime_differences; uses System.SysUtils, System.Generics.Collections; function IsPrime(a: UInt64): Boolean; var d: UInt64; begin if (a < 2) then exit(False); if (a mod 2) = 0 then exit(a = 2); if (a mod 3) = 0 then exit(a = 3); d := 5; while (d * d <= a) do be...
Port the following code from Java to Delphi with equivalent syntax and logic.
public class NthPrime { public static void main(String[] args) { System.out.printf("The 10,001st prime is %,d.\n", nthPrime(10001)); } private static int nthPrime(int n) { assert n > 0; PrimeGenerator primeGen = new PrimeGenerator(10000, 100000); int prime = primeGen.nextPri...
function IsPrime(N: integer): 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)); Result:=False; while I<=Stop do begin if ((N mod I) = ...
Transform the following Java implementation into Delphi, maintaining the same output and logic.
public class NthPrime { public static void main(String[] args) { System.out.printf("The 10,001st prime is %,d.\n", nthPrime(10001)); } private static int nthPrime(int n) { assert n > 0; PrimeGenerator primeGen = new PrimeGenerator(10000, 100000); int prime = primeGen.nextPri...
function IsPrime(N: integer): 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)); Result:=False; while I<=Stop do begin if ((N mod I) = ...
Ensure the translated Delphi code behaves exactly like the original Java snippet.
public class LynchBell { static String s = ""; public static void main(String args[]) { int i = 98764321; boolean isUnique = true; boolean canBeDivided = true; while (i>0) { s = String.valueOf(i); isUnique = uniqueDigits(i); ...
program Largest_number_divisible_by_its_digits; uses System.SysUtils; type TSetAnsiChar = set of AnsiChar; function DivByAll(num: Integer; digits: TSetAnsiChar): Boolean; var offset: byte; begin offset := ord('0'); for var d in digits do begin if (num mod (ord(d) - offset)) <> 0 then exit(fal...
Port the provided Java code into Delphi while preserving the original functionality.
public class LynchBell { static String s = ""; public static void main(String args[]) { int i = 98764321; boolean isUnique = true; boolean canBeDivided = true; while (i>0) { s = String.valueOf(i); isUnique = uniqueDigits(i); ...
program Largest_number_divisible_by_its_digits; uses System.SysUtils; type TSetAnsiChar = set of AnsiChar; function DivByAll(num: Integer; digits: TSetAnsiChar): Boolean; var offset: byte; begin offset := ord('0'); for var d in digits do begin if (num mod (ord(d) - offset)) <> 0 then exit(fal...
Convert this Java block to Delphi, preserving its control flow and logic.
import java.util.Scanner; public class MatrixArithmetic { public static double[][] minor(double[][] a, int x, int y){ int length = a.length-1; double[][] result = new double[length][length]; for(int i=0;i<length;i++) for(int j=0;j<length;j++){ if(i<x && j<y){ result[i][j] = a[i][j]; }else if(i>=x && j...
program Determinant_and_permanent; uses System.SysUtils; type TMatrix = TArray<TArray<Double>>; function Minor(a: TMatrix; x, y: Integer): TMatrix; begin var len := Length(a) - 1; SetLength(result, len, len); for var i := 0 to len - 1 do begin for var j := 0 to len - 1 do begin if ((i < x...
Translate the given Java code snippet into Delphi without altering its behavior.
import java.util.Scanner; public class MatrixArithmetic { public static double[][] minor(double[][] a, int x, int y){ int length = a.length-1; double[][] result = new double[length][length]; for(int i=0;i<length;i++) for(int j=0;j<length;j++){ if(i<x && j<y){ result[i][j] = a[i][j]; }else if(i>=x && j...
program Determinant_and_permanent; uses System.SysUtils; type TMatrix = TArray<TArray<Double>>; function Minor(a: TMatrix; x, y: Integer): TMatrix; begin var len := Length(a) - 1; SetLength(result, len, len); for var i := 0 to len - 1 do begin for var j := 0 to len - 1 do begin if ((i < x...
Rewrite this program in Delphi while keeping its functionality equivalent to the Java version.
import java.math.BigInteger; import java.util.Scanner; public class twinPrimes { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Search Size: "); BigInteger max = input.nextBigInteger(); int counter = 0; for(BigInteger x =...
program Primes; uses System.SysUtils; function IsPrime(a: UInt64): Boolean; var d: UInt64; begin if (a < 2) then exit(False); if (a mod 2) = 0 then exit(a = 2); if (a mod 3) = 0 then exit(a = 3); d := 5; while (d * d <= a) do begin if (a mod d = 0) then Exit(false); i...
Rewrite the snippet below in Delphi so it works the same as the original Java code.
import java.math.BigInteger; import java.util.List; public class Brazilian { private static final List<Integer> primeList = List.of( 2, 3, 5, 7, 9, 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, 131, 137, 139, 149, 151, 157, 163, 16...
program Brazilian_numbers; uses System.SysUtils; type TBrazilianNumber = record private FValue: Integer; FIsBrazilian: Boolean; FIsPrime: Boolean; class function SameDigits(a, b: Integer): Boolean; static; class function CheckIsBrazilian(a: Integer): Boolean; static; class function C...
Ensure the translated Delphi code behaves exactly like the original Java snippet.
import java.math.BigInteger; import java.util.List; public class Brazilian { private static final List<Integer> primeList = List.of( 2, 3, 5, 7, 9, 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, 131, 137, 139, 149, 151, 157, 163, 16...
program Brazilian_numbers; uses System.SysUtils; type TBrazilianNumber = record private FValue: Integer; FIsBrazilian: Boolean; FIsPrime: Boolean; class function SameDigits(a, b: Integer): Boolean; static; class function CheckIsBrazilian(a: Integer): Boolean; static; class function C...
Change the programming language of this snippet from Java to Delphi without modifying what it does.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; public class CreateFile { public static void main(String[] args) throws IOException { String os = System.getProperty("os.name"); if (os.contains("Windows")) {...
program Create_a_file_on_magnetic_tape; const FileName = 'tape.file'; FileName = '/dev/tape'; var f: TextFile; begin Assign(f, FileName); Rewrite(f); Writeln(f, 'Hello World'); close(f); end.
Rewrite this program in Delphi while keeping its functionality equivalent to the Java version.
import java.util.function.Function; public interface YCombinator { interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { } public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) { RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x)); return...
program Y; uses SysUtils; type YCombinator = class sealed class function Fix<T> (F: TFunc<TFunc<T, T>, TFunc<T, T>>): TFunc<T, T>; static; end; TRecursiveFuncWrapper<T> = record type TRecursiveFunc = reference to function (R: TRecursiveFuncWrapper<T>): TFunc<T, T>; var O: TRecursiv...
Port the following code from Java to Delphi with equivalent syntax and logic.
public class Factorion { public static void main(String [] args){ System.out.println("Base 9:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,9); if(multiplied == i){ System.out.print(i + "\t")...
program Factorions; uses System.SysUtils; begin var fact: TArray<UInt64>; SetLength(fact, 12); fact[0] := 0; for var n := 1 to 11 do fact[n] := fact[n - 1] * n; for var b := 9 to 12 do begin writeln('The factorions for base ', b, ' are:'); for var i := 1 to 1499999 do begin var...
Translate this program into Delphi but keep the logic exactly as in Java.
public class Factorion { public static void main(String [] args){ System.out.println("Base 9:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,9); if(multiplied == i){ System.out.print(i + "\t")...
program Factorions; uses System.SysUtils; begin var fact: TArray<UInt64>; SetLength(fact, 12); fact[0] := 0; for var n := 1 to 11 do fact[n] := fact[n - 1] * n; for var b := 9 to 12 do begin writeln('The factorions for base ', b, ' are:'); for var i := 1 to 1499999 do begin var...
Convert this Java snippet to Delphi and keep its semantics consistent.
public class DivisorSum { private static long divisorSum(long n) { var total = 1L; var power = 2L; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (long p = 3; p * p <= n; p += 2) { long sum = 1; for (po...
program Sum_of_divisors; uses System.SysUtils; function DivisorSum(n: Cardinal): Cardinal; var total, power, p, sum: Cardinal; begin total := 1; power := 2; while (n and 1 = 0) do begin inc(total, power); power := power shl 1; n := n shr 1; end; p := 3; while p * p <= n do b...
Produce a functionally identical Delphi code for the snippet given in Java.
public class DivisorSum { private static long divisorSum(long n) { var total = 1L; var power = 2L; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (long p = 3; p * p <= n; p += 2) { long sum = 1; for (po...
program Sum_of_divisors; uses System.SysUtils; function DivisorSum(n: Cardinal): Cardinal; var total, power, p, sum: Cardinal; begin total := 1; power := 2; while (n and 1 = 0) do begin inc(total, power); power := power shl 1; n := n shr 1; end; p := 3; while p * p <= n do b...
Convert the following code from Java to Delphi, ensuring the logic remains intact.
package keybord.macro.demo; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; class KeyboardMacroDemo { public static void main( String [] args ) { final JFrame frame = new JFrame(); String directions = "<html><b>Ctrl-S...
program Key_Bindings_test; uses System.SysUtils, Winapi.Windows, Messages, Classes; type TWindowlessApplication = class private Terminated: Boolean; F7_id: Word; F6_id: Word; WIN_A: Word; procedure HandleMessage; public Handle: THandle; constructor Create; destruct...
Translate this program into Delphi but keep the logic exactly as in Java.
public class TauFunction { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { +...
program Tau_function; uses System.SysUtils; function CountDivisors(n: Integer): Integer; begin Result := 0; var i := 1; var k := 2; if (n mod 2) = 0 then k := 1; while i * i <= n do begin if (n mod i) = 0 then begin inc(Result); var j := n div i; if j <> i then i...
Rewrite the snippet below in Delphi so it works the same as the original Java code.
public class TauFunction { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { +...
program Tau_function; uses System.SysUtils; function CountDivisors(n: Integer): Integer; begin Result := 0; var i := 1; var k := 2; if (n mod 2) = 0 then k := 1; while i * i <= n do begin if (n mod i) = 0 then begin inc(Result); var j := n div i; if j <> i then i...
Rewrite the snippet below in Delphi so it works the same as the original Java code.
import java.io.IOException; public class Interpreter { public final static int MEMORY_SIZE = 65536; private final char[] memory = new char[MEMORY_SIZE]; private int dp; private int ip; private int border; private void reset() { for (int i = 0; i < MEMORY_SIZE; i++) { mem...
program Execute_Brain; uses Winapi.Windows, System.SysUtils; const DataSize = 1024; MaxNest = 1000; function Readkey: Char; var InputRec: TInputRecord; NumRead: Cardinal; KeyMode: DWORD; StdIn: THandle; begin StdIn := GetStdHandle(STD_INPUT_HA...
Rewrite the snippet below in Delphi so it works the same as the original Java code.
import java.io.IOException; public class Interpreter { public final static int MEMORY_SIZE = 65536; private final char[] memory = new char[MEMORY_SIZE]; private int dp; private int ip; private int border; private void reset() { for (int i = 0; i < MEMORY_SIZE; i++) { mem...
program Execute_Brain; uses Winapi.Windows, System.SysUtils; const DataSize = 1024; MaxNest = 1000; function Readkey: Char; var InputRec: TInputRecord; NumRead: Cardinal; KeyMode: DWORD; StdIn: THandle; begin StdIn := GetStdHandle(STD_INPUT_HA...
Translate this program into Delphi but keep the logic exactly as in Java.
public class MertensFunction { public static void main(String[] args) { System.out.printf("First 199 terms of the merten function are as follows:%n "); for ( int n = 1 ; n < 200 ; n++ ) { System.out.printf("%2d ", mertenFunction(n)); if ( (n+1) % 20 == 0 ) { ...
program Mertens_function; uses System.SysUtils; type TMertens = record merts: TArray<Integer>; zeros, crosses: Integer; class function Mertens(_to: Integer): TMertens; static; end; class function TMertens.Mertens(_to: Integer): TMertens; var sum, zeros, crosses: Integer; begin if _to < 1 th...
Port the following code from Java to Delphi with equivalent syntax and logic.
import java.util.*; public class ErdosPrimes { public static void main(String[] args) { boolean[] sieve = primeSieve(1000000); int maxPrint = 2500; int maxCount = 7875; System.out.printf("Erd\u0151s primes less than %d:\n", maxPrint); for (int count = 0, prime = 1; count < m...
function IsPrime(N: integer): 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)); Result:=False; while I<=Stop do begin if ((N mod I) = 0) or ((N mod (i + 2)) = 0) then exit;...
Write a version of this Java function in Delphi with identical behavior.
import java.util.*; public class ErdosPrimes { public static void main(String[] args) { boolean[] sieve = primeSieve(1000000); int maxPrint = 2500; int maxCount = 7875; System.out.printf("Erd\u0151s primes less than %d:\n", maxPrint); for (int count = 0, prime = 1; count < m...
function IsPrime(N: integer): 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)); Result:=False; while I<=Stop do begin if ((N mod I) = 0) or ((N mod (i + 2)) = 0) then exit;...
Please provide an equivalent version of this Java code in Delphi.
public enum Pip { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace }
program Cards; uses SysUtils, Classes; type TPip = (pTwo, pThree, pFour, pFive, pSix, pSeven, pEight, pNine, pTen, pJack, pQueen, pKing, pAce); TSuite = (sDiamonds, sSpades, sHearts, sClubs); const cPipNames: array[TPip] of string = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'); cSui...
Ensure the translated Delphi code behaves exactly like the original Java snippet.
import java.util.ArrayList; import java.util.List; public class PerfectTotientNumbers { public static void main(String[] args) { computePhi(); int n = 20; System.out.printf("The first %d perfect totient numbers:%n%s%n", n, perfectTotient(n)); } private static final List<Intege...
program Perfect_totient_numbers; uses System.SysUtils; function totient(n: Integer): Integer; begin var tot := n; var i := 2; while i * i <= n do begin if (n mod i) = 0 then begin while (n mod i) = 0 do n := n div i; dec(tot, tot div i); end; if i = 2 then i := 1;...
Generate a Delphi translation of this Java snippet without changing its computational steps.
import java.util.ArrayList; import java.util.List; public class PerfectTotientNumbers { public static void main(String[] args) { computePhi(); int n = 20; System.out.printf("The first %d perfect totient numbers:%n%s%n", n, perfectTotient(n)); } private static final List<Intege...
program Perfect_totient_numbers; uses System.SysUtils; function totient(n: Integer): Integer; begin var tot := n; var i := 2; while i * i <= n do begin if (n mod i) = 0 then begin while (n mod i) = 0 do n := n div i; dec(tot, tot div i); end; if i = 2 then i := 1;...
Ensure the translated Delphi code behaves exactly like the original Java snippet.
import java.util.Arrays; public class TwoSum { public static void main(String[] args) { long sum = 21; int[] arr = {0, 2, 11, 19, 90}; System.out.println(Arrays.toString(twoSum(arr, sum))); } public static int[] twoSum(int[] a, long target) { int i = 0, j = a.length - 1; ...
program Two_Sum; uses System.SysUtils, System.Generics.Collections; function TwoSum(arr: TArray<Integer>; num: Integer; var i, j: integer): boolean; begin TArray.Sort<Integer>(arr); i := 0; j := Length(arr) - 1; while i < j do begin if arr[i] + arr[j] = num then exit(True); if arr[i] + ...
Port the provided Java code into Delphi while preserving the original functionality.
import java.util.Arrays; public class TwoSum { public static void main(String[] args) { long sum = 21; int[] arr = {0, 2, 11, 19, 90}; System.out.println(Arrays.toString(twoSum(arr, sum))); } public static int[] twoSum(int[] a, long target) { int i = 0, j = a.length - 1; ...
program Two_Sum; uses System.SysUtils, System.Generics.Collections; function TwoSum(arr: TArray<Integer>; num: Integer; var i, j: integer): boolean; begin TArray.Sort<Integer>(arr); i := 0; j := Length(arr) - 1; while i < j do begin if arr[i] + arr[j] = num then exit(True); if arr[i] + ...
Generate a Delphi translation of this Java snippet without changing its computational steps.
public class Tau { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; ...
program Tau_number; uses System.SysUtils; function CountDivisors(n: Integer): Integer; begin Result := 0; var i := 1; var k := 2; if (n mod 2) = 0 then k := 1; while i * i <= n do begin if (n mod i) = 0 then begin inc(Result); var j := n div i; if j <> i then inc...
Produce a functionally identical Delphi code for the snippet given in Java.
import java.math.BigInteger; public class PrimeSum { private static int digitSum(BigInteger bi) { int sum = 0; while (bi.compareTo(BigInteger.ZERO) > 0) { BigInteger[] dr = bi.divideAndRemainder(BigInteger.TEN); sum += dr[1].intValue(); bi = dr[0]; } ...
program Primes_which_sum_of_digits_is_25; uses System.SysUtils, PrimTrial; var row: Integer = 0; limit1: Integer = 25; limit2: Integer = 5000; function Sum25(n: Integer): boolean; var sum: Integer; str: string; c: char; begin sum := 0; str := n.ToString; for c in str do inc(sum, strToInt(...
Keep all operations the same but rewrite the snippet in Delphi.
import java.math.BigInteger; public class PrimeSum { private static int digitSum(BigInteger bi) { int sum = 0; while (bi.compareTo(BigInteger.ZERO) > 0) { BigInteger[] dr = bi.divideAndRemainder(BigInteger.TEN); sum += dr[1].intValue(); bi = dr[0]; } ...
program Primes_which_sum_of_digits_is_25; uses System.SysUtils, PrimTrial; var row: Integer = 0; limit1: Integer = 25; limit2: Integer = 5000; function Sum25(n: Integer): boolean; var sum: Integer; str: string; c: char; begin sum := 0; str := n.ToString; for c in str do inc(sum, strToInt(...
Convert this Java snippet to Delphi and keep its semantics consistent.
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class DeepCopy { public static void main(String[] args) { Person p1 = new Person("Clark", "Kent", new Address("1 World Center"...
program DeepCopyApp; uses System.TypInfo; type TTypeA = record value1: integer; value2: char; value3: string[10]; value4: Boolean; function DeepCopy: TTypeA; end; function TTypeA.DeepCopy: TTypeA; begin CopyRecord(@result, @self, TypeInfo(TTypeA)); end; var a, b: TTypeA; begin a...
Generate an equivalent Delphi version of this Java code.
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class DeepCopy { public static void main(String[] args) { Person p1 = new Person("Clark", "Kent", new Address("1 World Center"...
program DeepCopyApp; uses System.TypInfo; type TTypeA = record value1: integer; value2: char; value3: string[10]; value4: Boolean; function DeepCopy: TTypeA; end; function TTypeA.DeepCopy: TTypeA; begin CopyRecord(@result, @self, TypeInfo(TTypeA)); end; var a, b: TTypeA; begin a...
Convert this Java snippet to Delphi and keep its semantics consistent.
import java.util.Scanner; public class LastSunday { static final String[] months={"January","February","March","April","May","June","July","August","September","October","November","December"}; public static int[] findLastSunday(int year) { boolean isLeap = isLeapYear(year); int[] days={31,isLeap?29:28,31...
program Find_the_last_Sunday_of_each_month; uses System.SysUtils, System.DateUtils; function LastDayOfWeekOfEachMonth(AYear, ADayOfWeek: Word): TArray<TDateTime>; var month: word; daysOffset: Integer; date: TDatetime; begin if (ADayOfWeek > 7) or (ADayOfWeek < 1) then raise Exception.CreateFmt('Err...
Convert the following code from Java to Delphi, ensuring the logic remains intact.
import java.util.Scanner; public class LastSunday { static final String[] months={"January","February","March","April","May","June","July","August","September","October","November","December"}; public static int[] findLastSunday(int year) { boolean isLeap = isLeapYear(year); int[] days={31,isLeap?29:28,31...
program Find_the_last_Sunday_of_each_month; uses System.SysUtils, System.DateUtils; function LastDayOfWeekOfEachMonth(AYear, ADayOfWeek: Word): TArray<TDateTime>; var month: word; daysOffset: Integer; date: TDatetime; begin if (ADayOfWeek > 7) or (ADayOfWeek < 1) then raise Exception.CreateFmt('Err...
Convert the following code from Java to Delphi, ensuring the logic remains intact.
import java.util.ArrayList; import java.util.stream.IntStream; import java.util.stream.LongStream; public class EstheticNumbers { interface RecTriConsumer<A, B, C> { void accept(RecTriConsumer<A, B, C> f, A a, B b, C c); } private static boolean isEsthetic(long n, long b) { if (n == 0) { ...
type TIntArray = array of integer; function GetRadixString(L: Integer; Radix: Byte): string; const HexChars: array[0..15] Of char = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'); var I: integer; var S: string; var Sign: string[1]; begin Result:=''; If (L < 0) then begin S...
Maintain the same structure and functionality when rewriting this code in Delphi.
import java.util.List; import java.util.Random; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; public class Rpg { private static final Random random = new Random(); public static int genAttribute() { return random.ints(1, 6 + 1) .limit(4) ...
program RPG_Attributes_Generator; uses System.SysUtils, System.Generics.Collections; type TListOfInt = class(TList<Integer>) public function Sum: Integer; function FindAll(func: Tfunc<Integer, Boolean>): TListOfInt; function Join(const sep: string): string; end; function TListOfInt.FindAl...
Maintain the same structure and functionality when rewriting this code in Delphi.
public class Sparkline { String bars="▁▂▃▄▅▆▇█"; public static void main(String[] args) { Sparkline now=new Sparkline(); float[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1}; now.display1D(arr); System.out.println(now.getSparkline(arr)); float[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f}; ...
program Sparkline_in_unicode; function map(x, in_min, in_max, out_min, out_max: Double): Double; begin Result := ((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min); end; procedure Normalize(var Values: TArray<Double>; outMin, outMax: Double); var i: Integer; inMax, inMin, value: Double; begin...
Port the provided Java code into Delphi while preserving the original functionality.
import java.io.*; import java.util.*; public class NeighbourWords { public static void main(String[] args) { try { int minLength = 9; List<String> words = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader("unixdict.txt"))) { ...
program Words_from_neighbour_ones; uses System.SysUtils, System.Classes; function GetWords(minLength: Integer = 1): TStringList; var i: Integer; begin Result := TStringList.create; Result.LoadFromFile('Unixdict.txt'); with Result do for i := Count - 1 downto 0 do if Strings[i].Length < minLeng...
Generate an equivalent Delphi version of this Java code.
import java.io.FileReader; import java.io.IOException; import java.nio.charset.StandardCharsets; public class Main { public static void main(String[] args) throws IOException { final int endOfFile = -1; try ( FileReader reader = new FileReader("input.txt", StandardCharsets.UTF_8) ) { while (...
program Read_a_file_character_by_character_UTF8; uses System.SysUtils, System.Classes; function GetNextCharacter(StreamReader: TStreamReader): char; begin Result := chr(StreamReader.Read); end; const FileName: TFileName = 'input.txt'; begin if not FileExists(FileName) then raise Exception.Create('Er...