Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Change the following Java code into Ada without altering its purpose.
package kronecker; public class ProductFractals { public static int[][] product(final int[][] a, final int[][] b) { final int[][] c = new int[a.length*b.length][]; for (int ix = 0; ix < c.length; ix++) { final int num_cols = a[0].length*b[0].length; c[ix] = new int[num_col...
with SDL.Video.Windows.Makers; with SDL.Video.Renderers.Makers; with SDL.Events.Events; with SDL.Events.Mice; procedure Kronecker_Fractals is Width : constant := 800; Height : constant := 800; Order : constant := 6; Window : SDL.Video.Windows.Window; Renderer : SDL.Video.Renderers.Renderer; ty...
Convert the following code from Java to Ada, ensuring the logic remains intact.
public class additivePrimes { public static void main(String[] args) { int additive_primes = 0; for (int i = 2; i < 500; i++) { if(isPrime(i) && isPrime(digitSum(i))){ additive_primes++; System.out.print(i + " "); } } System.ou...
with Ada.Text_Io; procedure Additive_Primes is Last : constant := 499; Columns : constant := 12; type Prime_List is array (2 .. Last) of Boolean; function Get_Primes return Prime_List is Prime : Prime_List := (others => True); begin for P in Prime'Range loop if Prime (P) then ...
Convert this Java block to Ada, preserving its control flow and logic.
String dog = "Benjamin"; String Dog = "Samba"; String DOG = "Bernie"; @Inject Console console; console.print($"There are three dogs named {dog}, {Dog}, and {DOG}");
with Ada.Text_IO; procedure Dogs is Dog : String := "Bernie"; begin Ada.Text_IO.Put_Line ("There is just one dog named " & DOG); end Dogs;
Write a version of this Java function in Ada with identical behavior.
public class ExtraPrimes { private static int nextPrimeDigitNumber(int n) { if (n == 0) { return 2; } switch (n % 10) { case 2: return n + 1; case 3: case 5: return n + 2; default: ret...
with Ada.Text_Io; procedure Extra_Primes is type Number is new Long_Integer range 0 .. Long_Integer'Last; package Number_Io is new Ada.Text_Io.Integer_Io (Number); function Is_Prime (A : Number) return Boolean is D : Number; begin if A < 2 then return False; end if; if A in 2 ....
Write a version of this Java function in Ada with identical behavior.
public class ExtraPrimes { private static int nextPrimeDigitNumber(int n) { if (n == 0) { return 2; } switch (n % 10) { case 2: return n + 1; case 3: case 5: return n + 2; default: ret...
with Ada.Text_Io; procedure Extra_Primes is type Number is new Long_Integer range 0 .. Long_Integer'Last; package Number_Io is new Ada.Text_Io.Integer_Io (Number); function Is_Prime (A : Number) return Boolean is D : Number; begin if A < 2 then return False; end if; if A in 2 ....
Port the provided Java code into Ada while preserving the original functionality.
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class AbbreviationsEasy { private static final Scanner input = new Scanner(System.in); private static final String COMMAND_TABLE = " Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy...
with Ada.Characters.Handling; with Ada.Containers.Indefinite_Vectors; with Ada.Strings.Fixed; with Ada.Strings.Maps.Constants; with Ada.Text_IO; procedure Abbreviations_Easy is package Command_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, ...
Translate the given Java code snippet into Ada without altering its behavior.
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class AbbreviationsEasy { private static final Scanner input = new Scanner(System.in); private static final String COMMAND_TABLE = " Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy...
with Ada.Characters.Handling; with Ada.Containers.Indefinite_Vectors; with Ada.Strings.Fixed; with Ada.Strings.Maps.Constants; with Ada.Text_IO; procedure Abbreviations_Easy is package Command_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, ...
Port the provided Java code into Ada while preserving the original functionality.
import java.util.Arrays; public class Stooge { public static void main(String[] args) { int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5}; stoogeSort(nums); System.out.println(Arrays.toString(nums)); } public static void stoogeSort(int[] L) { stoogeSort(L, 0, L.length - 1); ...
with Ada.Text_IO; procedure Stooge is type Integer_Array is array (Positive range <>) of Integer; procedure Swap (Left, Right : in out Integer) is Temp : Integer := Left; begin Left := Right; Right := Temp; end Swap; procedure Stooge_Sort (List : in out Integer_Array) is T : Natu...
Write a version of this Java function in Ada with identical behavior.
import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; public class TruncFile { public static void main(String[] args) throws IOException{ if(args.length < 2){ System.out.println("Usage: java TruncFile fileName newSize"); return; } FileChannel outChan = new F...
with Ada.Command_Line, Ada.Sequential_IO, Ada.Directories; procedure Truncate_File is type Byte is mod 256; for Byte'Size use 8; package Byte_IO is new Ada.Sequential_IO(Byte); function Arg(N: Positive) return String renames Ada.Command_Line.Argument; function Args return Natural renames Ada.Command_...
Keep all operations the same but rewrite the snippet in Ada.
import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; public class TruncFile { public static void main(String[] args) throws IOException{ if(args.length < 2){ System.out.println("Usage: java TruncFile fileName newSize"); return; } FileChannel outChan = new F...
with Ada.Command_Line, Ada.Sequential_IO, Ada.Directories; procedure Truncate_File is type Byte is mod 256; for Byte'Size use 8; package Byte_IO is new Ada.Sequential_IO(Byte); function Arg(N: Positive) return String renames Ada.Command_Line.Argument; function Args return Natural renames Ada.Command_...
Write a version of this Java function in Ada with identical behavior.
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...
generic type Element_Type is digits <>; type Index_Type is (<>); type Array_Type is array(Index_Type range <>) of Element_Type; package Shell_Sort is procedure Sort(Item : in out Array_Type); end Shell_Sort;
Convert this Java snippet to Ada and keep its semantics consistent.
import java.util.Arrays; public class Deconvolution1D { public static int[] deconv(int[] g, int[] f) { int[] h = new int[g.length - f.length + 1]; for (int n = 0; n < h.length; n++) { h[n] = g[n]; int lower = Math.max(n - f.length + 1, 0); for (int i = lower; i <...
with Ada.Text_IO; use Ada.Text_IO; procedure Main is package real_io is new Float_IO (Long_Float); use real_io; type Vector is array (Natural range <>) of Long_Float; function deconv (g, f : Vector) return Vector is len : Positive := Integer'Max ((g'Length - f'length), (f'length - g'length)...
Port the following code from Java to Ada with equivalent syntax and logic.
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...
with Ada.Text_IO; use Ada.Text_IO; procedure Rosetta_Read is File : File_Type; begin Open (File => File, Mode => In_File, Name => "rosetta_read.adb"); Set_Line (File, To => 7); declare Line_7 : constant String := Get_Line (File); begin if Line_7'Length = 0 then P...
Generate an equivalent Ada version of this Java code.
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...
with Ada.Text_IO; use Ada.Text_IO; procedure Rosetta_Read is File : File_Type; begin Open (File => File, Mode => In_File, Name => "rosetta_read.adb"); Set_Line (File, To => 7); declare Line_7 : constant String := Get_Line (File); begin if Line_7'Length = 0 then P...
Port the following code from Java to Ada with equivalent syntax and logic.
import java.io.UnsupportedEncodingException; import java.net.URLEncoder; public class Main { public static void main(String[] args) throws UnsupportedEncodingException { String normal = "http: String encoded = URLEncoder.encode(normal, "utf-8"); System.out.println(encoded); } }
with AWS.URL; with Ada.Text_IO; use Ada.Text_IO; procedure Encode is Normal : constant String := "http://foo bar/"; begin Put_Line (AWS.URL.Encode (Normal)); end Encode;
Change the following Java code into Ada without altering its purpose.
import java.io.UnsupportedEncodingException; import java.net.URLEncoder; public class Main { public static void main(String[] args) throws UnsupportedEncodingException { String normal = "http: String encoded = URLEncoder.encode(normal, "utf-8"); System.out.println(encoded); } }
with AWS.URL; with Ada.Text_IO; use Ada.Text_IO; procedure Encode is Normal : constant String := "http://foo bar/"; begin Put_Line (AWS.URL.Encode (Normal)); end Encode;
Transform the following Java implementation into Ada, maintaining the same output and logic.
import static java.util.Arrays.stream; import java.util.Locale; import static java.util.stream.IntStream.range; public class Test { static double dotProduct(double[] a, double[] b) { return range(0, a.length).mapToDouble(i -> a[i] * b[i]).sum(); } static double[][] matrixMul(double[][] A, double[...
with Ada.Numerics.Generic_Real_Arrays; generic with package Matrix is new Ada.Numerics.Generic_Real_Arrays (<>); package Decomposition is procedure Decompose (A : Matrix.Real_Matrix; P, L, U : out Matrix.Real_Matrix); end Decomposition;
Convert this Java block to Ada, preserving its control flow and logic.
import java.util.Arrays; public class SumDataType { public static void main(String[] args) { for ( ObjectStore<?> e : Arrays.asList(new ObjectStore<String>("String"), new ObjectStore<Integer>(23), new ObjectStore<Float>(new Float(3.14159))) ) { System.out.println("Object : " + e); } ...
type Ret_Val (Found : Boolean) is record case Found is when True => Position : Positive; when False => null; end case; end record;
Can you help me rewrite this code in Ada instead of Java, keeping it the same logically?
import java.util.Arrays; public class SumDataType { public static void main(String[] args) { for ( ObjectStore<?> e : Arrays.asList(new ObjectStore<String>("String"), new ObjectStore<Integer>(23), new ObjectStore<Float>(new Float(3.14159))) ) { System.out.println("Object : " + e); } ...
type Ret_Val (Found : Boolean) is record case Found is when True => Position : Positive; when False => null; end case; end record;
Write the same code in Ada 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, ...
package Tables is type Table is private; type Ordering is (Lexicographic, Psionic, ...); procedure Sort (It : in out Table; Order_By : in Ordering := Lexicographic; Column : in Positive := 1; Reverse_Ordering : in Bool...
Generate an equivalent Ada version of this Java code.
public class Approx { private double value; private double error; public Approx(){this.value = this.error = 0;} public Approx(Approx b){ this.value = b.value; this.error = b.error; } public Approx(double value, double error){ this.value = value; thi...
generic type Real is digits <>; with function Sqrt(X: Real) return Real; with function "**"(X: Real; Y: Real) return Real; package Approximation is type Number is private; function Approx(Value: Real; Sigma: Real) return Number; function "+"(X: Real) return Number; function "-"(X: Real) ...
Produce a language-to-language conversion: from Java to Ada, same semantics.
import java.util.*; import java.io.*; public class TPKA { public static void main(String... args) { double[] input = new double[11]; double userInput = 0.0; Scanner in = new Scanner(System.in); for(int i = 0; i < 11; i++) { System.out.print("Please enter a number: "); String s = in.nextLine(); try ...
with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions; procedure Trabb_Pardo_Knuth is type Real is digits 6 range -400.0 .. 400.0; package TIO renames Ada.Text_IO; package FIO is new TIO.Float_IO(Real); package Math is new Ada.Numerics.Generic_Elementary_Functions(Real); function F(X: Real) re...
Rewrite the snippet below in Ada 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...
with System; use System; with Ada.Text_IO; use Ada.Text_IO; with Ada.Calendar; use Ada.Calendar; with Ada.Unchecked_Deallocation; use Ada; with Interfaces; procedure Rate_Counter is pragma Priority (Max_Priority); package Duration_IO is new Fixed_IO (Duration); ...
Rewrite this program in Ada while keeping its functionality equivalent to the Java version.
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class EKGSequenceConvergence { public static void main(String[] args) { System.out.println("Calculate and show here the first 10 members of EKG[2], EKG[5], EKG[7], EKG[9]...
with Ada.Text_IO; with Ada.Containers.Generic_Array_Sort; procedure EKG_Sequences is type Element_Type is new Integer; type Index_Type is new Integer range 1 .. 100; subtype Show_Range is Index_Type range 1 .. 30; type Sequence is array (Index_Type range <>) of Element_Type; subtype EKG_Sequence ...
Convert this Java snippet to Ada and keep its semantics consistent.
import java.util.Random; public class Dice{ private static int roll(int nDice, int nSides){ int sum = 0; Random rand = new Random(); for(int i = 0; i < nDice; i++){ sum += rand.nextInt(nSides) + 1; } return sum; } private static int diceGame(int p1Dice, int p1Sides, int p2Dice, int p2Sides, int rolls...
with Ada.Text_IO; use Ada.Text_IO; with Ada.Numerics.Discrete_Random; procedure Main is package real_io is new Float_IO (Long_Float); use real_io; type Dice is record Faces : Positive; Num_Dice : Positive; end record; procedure Roll_Dice (The_Dice : in Dice; Count : out Natural) is ...
Rewrite the snippet below in Ada so it works the same as the original Java code.
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 ...
with Ada.Text_IO; use Ada.Text_IO; with Ada.Calendar; use Ada.Calendar; with Ada.Characters.Latin_1; procedure Main is begin Put_Line ("Hello, this is 60 BPM"); loop Ada.Text_IO.Put (Ada.Characters.Latin_1.BEL); delay 0.9; end loop; end Main;
Write the same code in Ada as shown below in Java.
public static void main(String[] args) { int[][] matrix = {{1, 3, 7, 8, 10}, {2, 4, 16, 14, 4}, {3, 1, 9, 18, 11}, {12, 14, 17, 18, 20}, {7, 1, 3, 9, 5}}; int sum = 0; for (int row = 1; row < matrix.length; row++) { ...
with Ada.Text_Io; with Ada.Numerics.Generic_Real_Arrays; procedure Sum_Below_Diagonals is type Real is new Float; package Real_Arrays is new Ada.Numerics.Generic_Real_Arrays (Real); function Sum_Below_Diagonal (M : Real_Arrays.Real_Matrix) return Real with Pre => M'Length (1) = M'Length (2) is ...
Write the same code in Ada as shown below in Java.
import java.awt.*; import java.awt.geom.Path2D; import javax.swing.*; public class PythagorasTree extends JPanel { final int depthLimit = 7; float hue = 0.15f; public PythagorasTree() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); } private void drawTree(...
with SDL.Video.Windows.Makers; with SDL.Video.Renderers.Makers; with SDL.Video.Rectangles; with SDL.Events.Events; procedure Pythagoras_Tree is Width : constant := 600; Height : constant := 600; Level : constant := 7; type Point is record X, Y : Float; end record; B1 : constant Point := (X => 250...
Produce a functionally identical Ada code for the snippet given in Java.
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 :...
with Ada.Command_Line, Ada.Text_IO, Ada.Strings.Fixed; procedure Rep_String is function Find_Largest_Rep_String(S:String) return String is L: Natural := S'Length; begin for I in reverse 1 .. L/2 loop declare use Ada.Strings.Fixed; T: String := S(S'First .. S'First + I-1); U: Str...
Preserve the algorithm and functionality while converting the code from Java to Ada.
public class Topswops { static final int maxBest = 32; static int[] best; static private void trySwaps(int[] deck, int f, int d, int n) { if (d > best[n]) best[n] = d; for (int i = n - 1; i >= 0; i--) { if (deck[i] == -1 || deck[i] == i) break; ...
with Ada.Integer_Text_IO, Generic_Perm; procedure Topswaps is function Topswaps(Size: Positive) return Natural is package Perms is new Generic_Perm(Size); P: Perms.Permutation; Done: Boolean; Max: Natural; function Swapper_Calls(P: Perms.Permutation) return Natural is Q: P...
Generate an equivalent Ada version of this Java code.
public class AntiPrimesPlus { static int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (n % i == 0) { if (i == n / i) count++; else count += 2; } } return c...
with Ada.Text_IO; procedure Show_Sequence is function Count_Divisors (N : in Natural) return Natural is Count : Natural := 0; I : Natural; begin I := 1; while I**2 <= N loop if N mod I = 0 then if I = N / I then Count := Count + 1; else...
Keep all operations the same but rewrite the snippet in Ada.
public class McNuggets { public static void main(String... args) { int[] SIZES = new int[] { 6, 9, 20 }; int MAX_TOTAL = 100; int numSizes = SIZES.length; int[] counts = new int[numSizes]; int maxFound = MAX_TOTAL + 1; boolean[] found = new boolean[maxFound]...
with Ada.Text_IO; use Ada.Text_IO; procedure McNugget is Limit : constant := 100; List : array (0 .. Limit) of Boolean := (others => False); N : Integer; begin for A in 0 .. Limit / 6 loop for B in 0 .. Limit / 9 loop for C in 0 .. Limit / 20 loop N := A...
Write a version of this Java function in Ada with identical behavior.
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...
with Ada.Text_IO; use Ada.Text_IO; procedure Main is subtype Lower is Character range 'a' .. 'z'; subtype Upper is Character range 'A' .. 'Z'; begin Put ("Lower: "); for c in Lower'range loop Put (c); end loop; New_Line; Put ("Upper: "); for c in Upper'range loop Put (c); end loo...
Convert this Java block to Ada, preserving its control flow and logic.
import java.awt.*; import java.awt.geom.Path2D; import static java.lang.Math.pow; import java.util.Hashtable; import javax.swing.*; import javax.swing.event.*; public class SuperEllipse extends JPanel implements ChangeListener { private double exp = 2.5; public SuperEllipse() { setPreferredSize(new Di...
with Ada.Numerics.Elementary_Functions; with SDL.Video.Windows.Makers; with SDL.Video.Renderers.Makers; with SDL.Events.Events; procedure Superelipse is Width : constant := 600; Height : constant := 600; A : constant := 200.0; B : constant := 200.0; N : constant := 2.5; Window : ...
Convert the following code from Java to Ada, ensuring the logic remains intact.
import java.util.concurrent.Semaphore; public class VolatileClass{ public Semaphore mutex = new Semaphore(1); public void needsToBeSynched(){ } }
protected type Mutex is entry Seize; procedure Release; private Owned : Boolean := False; end Mutex;
Keep all operations the same but rewrite the snippet in Ada.
public class JaroDistance { public static double jaro(String s, String t) { int s_len = s.length(); int t_len = t.length(); if (s_len == 0 && t_len == 0) return 1; int match_distance = Integer.max(s_len, t_len) / 2 - 1; boolean[] s_matches = new boolean[s_len]; boo...
with Ada.Text_IO; procedure Jaro_Distances is type Jaro_Measure is new Float; function Jaro_Distance (Left, Right : in String) return Jaro_Measure is Left_Matches : array (Left'Range) of Boolean := (others => False); Right_Matches : array (Right'Range) of Boolean := (others => False); ...
Convert this Java snippet to Ada and keep its semantics consistent.
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...
with Ada.Text_IO; procedure Odd_Word_Problem is use Ada.Text_IO; function Current return Character is End_Of_Line: Boolean; C: Character; begin Look_Ahead(C, End_Of_Line); if End_Of_Line then raise Constraint_Error with "end of line before the terminating '.'"; ...
Change the programming language of this snippet from Java to Ada without modifying what it does.
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 = ...
with Interfaces; use Interfaces; package random_pcg32 is function Next_Int return Unsigned_32; function Next_Float return Long_Float; procedure Seed (seed_state : Unsigned_64; seed_sequence : Unsigned_64); end random_pcg32;
Can you help me rewrite this code in Ada instead of Java, keeping it the same logically?
import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.IntStream; public class SelfReferentialSequence { static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000); public static void main(String[] args) { Seeds res = IntStream.range(0, 1000_000) ...
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Vectors; procedure SelfRef is subtype Seed is Natural range 0 .. 1_000_000; subtype Num is Natural range 0 .. 10; type NumList is array (0 .. 10) of Num; package IO is new Ada.Text_IO.Integer_IO (Natural); package DVect is new Ada.Containers.Vectors ...
Change the following Java code into Ada without altering its purpose.
int l = 300; void setup() { size(400, 400); background(0, 0, 255); stroke(255); translate(width/2.0, height/2.0); translate(-l/2.0, l*sqrt(3)/6.0); for (int i = 1; i <= 3; i++) { kcurve(0, l); rotate(radians(120)); translate(-l, 0); } } void kcurve(float x1, float x2) { float s = (x2...
with Ada.Command_Line; with Ada.Numerics.Generic_Elementary_Functions; with Ada.Text_IO; with PDF_Out; procedure Koch_Curve is package Real_Math is new Ada.Numerics.Generic_Elementary_Functions (PDF_Out.Real); use Real_Math, PDF_Out, Ada.Command_Line, Ada.Text_IO; subtype Angle_Deg is Real; type ...
Write a version of this Java function in Ada with identical behavior.
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...
with Interfaces; use Interfaces; with Ada.Text_IO; use Ada.Text_IO; procedure Main is const : constant Unsigned_64 := 16#2545_F491_4F6C_DD1D#; state : Unsigned_64 := 0; Unseeded_Error : exception; procedure seed (num : Unsigned_64) is begin state := num; end seed; function Next_I...
Change the programming language of this snippet from Java to Ada without modifying what it does.
public class EqualRisesFalls { public static void main(String[] args) { final int limit1 = 200; final int limit2 = 10000000; System.out.printf("The first %d numbers in the sequence are:\n", limit1); int n = 0; for (int count = 0; count < limit2; ) { if (equalRises...
with Ada.Text_Io; with Ada.Integer_Text_Io; procedure Equal_Rise_Fall is use Ada.Text_Io; function Has_Equal_Rise_Fall (Value : Natural) return Boolean is Rises : Natural := 0; Falls : Natural := 0; Image : constant String := Natural'Image (Value); Last : Character := Image (Image'First...
Translate this program into Ada but keep the logic exactly as in Java.
public class App { private static long mod(long x, long y) { long m = x % y; if (m < 0) { if (y < 0) { return m - y; } else { return m + y; } } return m; } public static class RNG { private ...
package MRG32KA is type I64 is range -2**63..2**63 - 1; m1 : constant I64 := 2**32 - 209; m2 : constant I64 := 2**32 - 22853; subtype state_value is I64 range 1..m1; procedure Seed (seed_state : state_value); function Next_Int return I64; function Next_Float return Long_Float; end MRG32KA;
Please provide an equivalent version of this Java code in Ada.
public class SelfDescribingNumbers{ public static boolean isSelfDescribing(int a){ String s = Integer.toString(a); for(int i = 0; i < s.length(); i++){ String s0 = s.charAt(i) + ""; int b = Integer.parseInt(s0); int count = 0; for(int j = 0; j < s.len...
with Ada.Text_IO; use Ada.Text_IO; procedure SelfDesc is subtype Desc_Int is Long_Integer range 0 .. 10**10-1; function isDesc (innum : Desc_Int) return Boolean is subtype S_Int is Natural range 0 .. 10; type S_Int_Arr is array (0 .. 9) of S_Int; ref, cnt : S_Int_Arr := (others => 0); n, ...
Change the programming language of this snippet from Java to Ada 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...
with Ada.Text_Io; with Ada.Strings.Fixed; with Ada.Containers.Indefinite_Vectors; procedure Changeable is use Ada.Text_Io, Ada.Strings.Fixed; package String_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String); F...
Maintain the same structure and functionality when rewriting this code in Ada.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.util.Objects; public class DecisionTables { private static class Pair<T, U> { private final T t; private final U u; public static <T, U> Pair<T, U> of(T t, U u) {...
generic type Condition is (<>); type Action is (<>); with function Ask_Question (Cond: Condition) return Boolean; with procedure Give_Answer (Act: Action); with procedure No_Answer; package Generic_Decision_Table is type Answers is array(Condition) of Boolean; type Rule_R is record If_Then...
Please provide an equivalent version of this Java code in Ada.
size(1000,1000); textSize(50); for(int i=0;i<10;i++){ for(int j=0;j<10;j++){ noFill(); square(i*100,j*100,100); fill(#000000); if((i+j)%2==0){ text("1",i*100+50,j*100+50); } else{ text("0",i*100+50,j*100+50); } } }
with Ada.Text_Io; use Ada.Text_Io; with Ada.Command_Line; procedure Mosaic_Matrix is type Matrix_Type is array (Positive range <>, Positive range <>) of Character; function Mosaic (Length : Natural) return Matrix_Type is begin return M : Matrix_Type (1 .. Length, 1 .. Length) do for Row in M'...
Transform the following Java implementation into Ada, maintaining the same output and logic.
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(...
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; procedure Main is Num_Lines : Integer; begin Get(Num_Lines); Skip_Line; for I in 1..Num_Lines loop Put_Line(Get_Line); end loop; end Main;
Rewrite this program in Ada while keeping its functionality equivalent to the Java version.
public static double arcLength(double r, double a1, double a2){ return (360.0 - Math.abs(a2-a1))*Math.PI/180.0 * r; }
with Ada.Text_Io; with Ada.Numerics; procedure Calculate_Arc_Length is use Ada.Text_Io; type Angle_Type is new Float range 0.0 .. 360.0; type Distance is new Float range 0.0 .. Float'Last; function Major_Arc_Length (Angle_1, Angle_2 : Angle_Type; Radius ...
Produce a language-to-language conversion: from Java to Ada, same semantics.
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...
with Ada.Text_Io; procedure Shift_Left is Shift_Count : constant := 3; type List_Type is array (Positive range <>) of Integer; procedure Put_List (List : List_Type) is use Ada.Text_Io; begin for V of List loop Put (V'Image); Put (" "); end loop; New_Line; end Put_Lis...
Keep all operations the same but rewrite the snippet in Ada.
class Vector{ private double x, y, z; public Vector(double x1,double y1,double z1){ x = x1; y = y1; z = z1; } void printVector(int x,int y){ text("( " + this.x + " ) \u00ee + ( " + this.y + " ) + \u0135 ( " + this.z + ") \u006b\u0302",x,y); } public double norm() { return Math.sq...
with Ada.Text_Io; use Ada.Text_Io; with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; procedure Rodrigues is type Vector is record X, Y, Z : Float; end record; function Image (V : in Vector) return String is ('[' & V.X'Image & ',' & V.Y'Image & ',' & V.Z'Image & ']'); ...
Keep all operations the same but rewrite the snippet in Ada.
public class AirMass { public static void main(String[] args) { System.out.println("Angle 0 m 13700 m"); System.out.println("------------------------------------"); for (double z = 0; z <= 90; z+= 5) { System.out.printf("%2.0f %11.8f %11.8f\n", ...
with Ada.Text_IO; use Ada.Text_IO; with Ada.Numerics.Generic_Elementary_Functions; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; procedure Main is subtype double is Long_Float; package double_io is new Ada.Text_IO.Float_IO (double); use double_io; package Elementary_Double is new Ada.Numerics.Generic_...
Generate an equivalent Ada version of this Java code.
package example.diagdiag; public class Program { public static void main(String[] args) { DiagonalDiagonalMatrix A = new DiagonalDiagonalMatrix(7); System.out.println(A); } } class DiagonalDiagonalMatrix { final int n; private double[][] a = null; public Matrix(int n) { ...
with Ada.Text_Io; use Ada.Text_Io; with Ada.Command_Line; procedure Matrix_With_Diagonals is type Matrix_Type is array (Positive range <>, Positive range <>) of Character; function Matrix_X (Length : Natural) return Matrix_Type is begin return M : Matrix_Type (1 .. Length, 1 .. Length) do for...
Can you help me rewrite this code in Ada instead of Java, keeping it the same logically?
size(640,480); stroke(#ffff00); ellipse(random(640),random(480),1,1);
with Ada.Numerics.Discrete_Random; with SDL.Video.Windows.Makers; with SDL.Video.Renderers.Makers; with SDL.Events.Events; procedure Draw_A_Pixel_2 is Width : constant := 640; Height : constant := 480; use SDL.C; subtype Width_Range is SDL.C.int range 0 .. Width - 1; subtype Height_Range is SDL.C...
Keep all operations the same but rewrite the snippet in Ada.
size(1000,1000); textSize(50); for(int i=0;i<10;i++){ for(int j=0;j<10;j++){ noFill(); square(i*100,j*100,100); fill(#000000); if(i==0||i==9||j==0||j==9){ text("1",i*100+50,j*100+50); } else{ text("0",i*100+50,j*100+50); } } }
with Ada.Text_Io; with Ada.Command_Line; procedure Four_Sides is type Matrix_Type is array (Natural range <>, Natural range <>) of Character; function Hollow (Length : Natural) return Matrix_Type is begin return M : Matrix_Type (1 .. Length, 1 .. Length) do for Row in M'Range(1) loop ...
Translate this program into Ada 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 = ...
with Ada.Strings.Unbounded; with Ada.Text_Io.Unbounded_IO; procedure Longest_Common_Suffix is use Ada.Text_Io; use Ada.Text_Io.Unbounded_Io; use Ada.Strings.Unbounded; subtype Ustring is Unbounded_String; function "+"(S : String) return Ustring renames To_Unbounded_String; type String_List is...
Translate the given Java code snippet into Ada without altering its behavior.
public class NumericSeparatorSyntax { public static void main(String[] args) { runTask("Underscore allowed as seperator", 1_000); runTask("Multiple consecutive underscores allowed:", 1__0_0_0); runTask("Many multiple consecutive underscores allowed:", 1________________________00); r...
with Ada.Text_IO; use Ada.Text_IO; with Ada.Float_Text_IO; use Ada.Float_Text_IO; procedure Main is type u64 is mod 2**64; pi : constant Float := 3.14159_26535_89793_23846_26433_83279_50288_41971_69399_37511; Trillion : u64 := 1_000_000_000_000; begin Put ("pi : "); Put (Ite...
Rewrite this program in Ada while keeping its functionality equivalent to the Java version.
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello world!"); } }
procedure Main is begin null; end Main;
Rewrite this program in Ada while keeping its functionality equivalent to the Java version.
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello world!"); } }
procedure Main is begin null; end Main;
Produce a functionally identical Ada code for the snippet given in Java.
public class AVLtree { private Node root; private static class Node { private int key; private int balance; private int height; private Node left; private Node right; private Node parent; Node(int key, Node parent) { this.key = key; ...
with Ada.Text_IO, Ada.Finalization, Ada.Unchecked_Deallocation; procedure Main is generic type Key_Type is private; with function "<"(a, b : Key_Type) return Boolean is <>; with function "="(a, b : Key_Type) return Boolean is <>; with function "<="(a, b : Key_Type) return Boolean is <>; ...
Can you help me rewrite this code in Ada instead of Java, keeping it the same logically?
public class AVLtree { private Node root; private static class Node { private int key; private int balance; private int height; private Node left; private Node right; private Node parent; Node(int key, Node parent) { this.key = key; ...
with Ada.Text_IO, Ada.Finalization, Ada.Unchecked_Deallocation; procedure Main is generic type Key_Type is private; with function "<"(a, b : Key_Type) return Boolean is <>; with function "="(a, b : Key_Type) return Boolean is <>; with function "<="(a, b : Key_Type) return Boolean is <>; ...
Transform the following Java implementation into Ada, maintaining the same output and logic.
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); } }
with Ada.Containers.Indefinite_Vectors, Ada.Text_IO; procedure Here_Doc is package String_Vec is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String); use type String_Vec.Vector; Document: String_Vec.Vector := String_Vec.Empty_Vector & "This is a vector of...
Ensure the translated Ada 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); } }
with Ada.Containers.Indefinite_Vectors, Ada.Text_IO; procedure Here_Doc is package String_Vec is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String); use type String_Vec.Vector; Document: String_Vec.Vector := String_Vec.Empty_Vector & "This is a vector of...
Translate this program into Ada but keep the logic exactly as in Java.
& | ^ ~ >> << >>> + - * / = %
with Ada.Text_IO; use Ada.Text_IO; procedure Test is begin Put ("Quote """ & ''' & """" & Character'Val (10)); end Test;
Preserve the algorithm and functionality while converting the code from Java to Ada.
import java.util.Scanner; public class Pigdice { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int players = 0; while(true) { System.out.println("Hello, welcome to Pig Dice the game! How many players? "); if(scan.hasNextInt()) { int nextInt = scan...
with Pig; with Ada.Text_IO; with Ada.Command_Line; procedure automatic_Pig is use Pig; type Robot is new Actor with record Bound: Natural := 20; Final_Run: Natural := 0; end record; function Roll_More(A: Robot; Self, Opponent: Player'Class) return Boolean; function Roll_More(A: R...
Change the following Java code into Ada without altering its purpose.
import java.util.Scanner; public class Pigdice { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int players = 0; while(true) { System.out.println("Hello, welcome to Pig Dice the game! How many players? "); if(scan.hasNextInt()) { int nextInt = scan...
with Pig; with Ada.Text_IO; with Ada.Command_Line; procedure automatic_Pig is use Pig; type Robot is new Actor with record Bound: Natural := 20; Final_Run: Natural := 0; end record; function Roll_More(A: Robot; Self, Opponent: Player'Class) return Boolean; function Roll_More(A: R...
Transform the following Java implementation into Ada, maintaining the same output and logic.
import java.io.*; import java.util.*; public class OddWords { public static void main(String[] args) { try { Set<String> dictionary = new TreeSet<>(); final int minLength = 5; String fileName = "unixdict.txt"; if (args.length != 0) fileName = ...
with Ada.Text_Io; with Ada.Containers.Indefinite_Ordered_Maps; procedure Odd_Words is use Ada.Text_Io; package String_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String, Element_Type => String); Filename : constant String := "unix...
Keep all operations the same but rewrite the snippet in Ada.
import java.io.*; import java.util.*; public class MazeSolver { private static String[] readLines (InputStream f) throws IOException { BufferedReader r = new BufferedReader (new InputStreamReader (f, "US-ASCII")); ArrayList<String> lines = new ArrayList<String>(); Strin...
with Ada.Text_IO; procedure Maze_Solver is X_Size: constant Natural := 45; Y_Size: constant Natural := 17; subtype X_Range is Natural range 1 .. X_Size; subtype Y_Range is Natural range 1 .. Y_Size; East: constant X_Range := 2; South: constant Y_Range := 1; X_Start: constant X_Range := 3; ...
Can you help me rewrite this code in Ada instead of Java, keeping it the same logically?
import static java.lang.Math.*; import java.util.Arrays; import java.util.function.BiFunction; public class DemingsFunnel { public static void main(String[] args) { double[] dxs = { -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0....
with Ada.Numerics.Elementary_Functions; with Ada.Text_IO; procedure Demings_Funnel is type Float_List is array (Positive range <>) of Float; Dxs : constant Float_List := (-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, ...
Change the following Java code into Ada without altering its purpose.
import static java.lang.Math.*; import java.util.Arrays; import java.util.function.BiFunction; public class DemingsFunnel { public static void main(String[] args) { double[] dxs = { -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0....
with Ada.Numerics.Elementary_Functions; with Ada.Text_IO; procedure Demings_Funnel is type Float_List is array (Positive range <>) of Float; Dxs : constant Float_List := (-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, ...
Preserve the algorithm and functionality while converting the code from Java to Ada.
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,...
package MD5 is type Int32 is mod 2 ** 32; type MD5_Hash is array (1 .. 4) of Int32; function MD5 (Input : String) return MD5_Hash; subtype MD5_String is String (1 .. 34); function To_String (Item : MD5_Hash) return MD5_String; end MD5;
Convert this Java snippet to Ada and keep its semantics consistent.
(...) int feedForward(double[] inputs) { assert inputs.length == weights.length : "weights and input length mismatch"; double sum = 0; for (int i = 0; i < weights.length; i++) { sum += inputs[i] * weights[i]; } return activate(sum); } (...)
type Nums_Array is array (Integer range <>) of Integer; procedure Sort(Arr : in out Nums_Array) with Pre => Arr'Length > 1, Post => (for all I in Arr'First .. Arr'Last -1 => Arr(I) <= Arr(I + 1));
Write the same algorithm in Ada as shown in this Java implementation.
(...) int feedForward(double[] inputs) { assert inputs.length == weights.length : "weights and input length mismatch"; double sum = 0; for (int i = 0; i < weights.length; i++) { sum += inputs[i] * weights[i]; } return activate(sum); } (...)
type Nums_Array is array (Integer range <>) of Integer; procedure Sort(Arr : in out Nums_Array) with Pre => Arr'Length > 1, Post => (for all I in Arr'First .. Arr'Last -1 => Arr(I) <= Arr(I + 1));
Port the following code from Java to Ada 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...
private with Ada.Containers.Indefinite_Vectors; generic type Item_Type (<>) is private; package History_Variables is type Variable is tagged limited private; procedure Set(V: in out Variable; Item: Item_Type); function Get(V: Variable) return Item_Type; function Defined(V: Variable) return Nat...
Produce a functionally identical Ada code for the snippet given in Java.
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 : Float) return Float;
Keep all operations the same but rewrite the snippet in AutoHotKey.
<?php $colors = array(array( 0, 0, 0), // black array(255, 0, 0), // red array( 0, 255, 0), // green array( 0, 0, 255), // blue array(255, 0, 255), // magenta array( 0, 255, 255), // cyan array(...
#SingleInstance, Force #NoEnv SetBatchLines, -1 If !pToken := Gdip_Startup() { message = ( LTrim gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system. ) MsgBox, 48, %message% ExitApp } OnExit, Exit Width := A_ScreenWidth, Height := A_ScreenHeight ...
Change the following PHP code into AutoHotKey without altering its purpose.
class MyException extends Exception { }
foo() If ErrorLevel Msgbox calling foo failed with: %ErrorLevel% foo() { If success Return Else ErrorLevel = foo_error Return }
Please provide an equivalent version of this PHP code in AutoHotKey.
#!/usr/bin/env php The 24 Game Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24. An answer of "q" will quit the game. An answer of "!" will generate a new set of four digits. Otherwi...
AutoExecute: Title := "24 Game" Gui, -MinimizeBox Gui, Add, Text, w230 vPuzzle Gui, Add, Edit, wp vAnswer Gui, Add, Button, w70, &Generate Gui, Add, Button, x+10 wp Default, &Submit Gui, Add, Button, x+10 wp, E&xit ButtonGenerate:  Loop, 4 Random, r%A_Index%, 1, 9 ...
Convert this PHP block to AutoHotKey, preserving its control flow and logic.
#!/usr/bin/env php The 24 Game Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24. An answer of "q" will quit the game. An answer of "!" will generate a new set of four digits. Otherwi...
AutoExecute: Title := "24 Game" Gui, -MinimizeBox Gui, Add, Text, w230 vPuzzle Gui, Add, Edit, wp vAnswer Gui, Add, Button, w70, &Generate Gui, Add, Button, x+10 wp Default, &Submit Gui, Add, Button, x+10 wp, E&xit ButtonGenerate:  Loop, 4 Random, r%A_Index%, 1, 9 ...
Can you help me rewrite this code in AutoHotKey instead of PHP, keeping it the same logically?
define("PI", 3.14159265358); define("MSG", "Hello World");
MyData := new FinalBox("Immutable data") MsgBox % "MyData.Data = " MyData.Data MyData.Data := "This will fail to set" MsgBox % "MyData.Data = " MyData.Data Class FinalBox { __New(FinalValue) { ObjInsert(this, "proxy",{Data:FinalValue}) } __Get(k) { return, this["proxy",k] } __Set(p*) { ...
Please provide an equivalent version of this PHP code in AutoHotKey.
<?php echo substr_count("the three truths", "th"), PHP_EOL; // prints "3" echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
MsgBox % countSubstring("the three truths","th")  MsgBox % countSubstring("ababababab","abab")   CountSubstring(fullstring, substring){ StringReplace, junk, fullstring, %substring%, , UseErrorLevel return errorlevel }
Generate an equivalent AutoHotKey version of this PHP code.
<?php header("Content-type: image/png"); $width = 512; $height = 512; $img = imagecreatetruecolor($width,$height); $bg = imagecolorallocate($img,255,255,255); imagefilledrectangle($img, 0, 0, $width, $width, $bg); $depth = 8; function drawTree($x1, $y1, $angle, $depth){ global $img; if ($depth != 0)...
#SingleInstance, Force #NoEnv SetBatchLines, -1 FileOut := A_Desktop "\MyNewFile.png" TreeColor := 0xff0066ff TrunkWidth := 10 TrunkLength := 80 Angle := 60 ImageWidth := 670 ImageHeight := 450 Branches := 13 Decrease := 0.81 Angle := (Angle * 0.01745329252) / 2 , Points := {} , Points[1, "Angle...
Translate this program into AutoHotKey but keep the logic exactly as in PHP.
<?php $conf = file_get_contents('parse-conf-file.txt'); $conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf); $conf = preg_replace_callback( '/^([a-z]+)\s*=((?=.*\,.*).*)$/mi', function ($matches) { $r = ''; foreach (explode(',', $matches[2]) AS $val) { $r .= $matches[1] . '[]...
data = %A_scriptdir%\rosettaconfig.txt comma := "," Loop, Read, %data% { if NOT (instr(A_LoopReadLine, "#") == 1 OR A_LoopReadLine == "") { if instr(A_LoopReadLine, " { parameter := RegExReplace(Substr(A_LoopReadLine,2), "^[ \s]+|[ \s]+$", "") %parameter% = "1" } else { parameter := RegEx...
Ensure the translated AutoHotKey code behaves exactly like the original PHP snippet.
<?php $dog = 'Benjamin'; $Dog = 'Samba'; $DOG = 'Bernie'; echo "There are 3 dogs named {$dog}, {$Dog} and {$DOG}\n"; function DOG() { return 'Bernie'; } echo 'There is only 1 dog named ' . dog() . "\n";
dog := "Benjamin" Dog := "Samba" DOG := "Bernie" MsgBox There is just one dog named %dOG%
Produce a language-to-language conversion: from PHP to AutoHotKey, same semantics.
$commands = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase ...
str = ( Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix M...
Translate the given PHP code snippet into AutoHotKey without altering its behavior.
$commands = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase ...
str = ( Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix M...
Transform the following PHP implementation into AutoHotKey, maintaining the same output and logic.
function stoogeSort(&$arr, $i, $j) { if($arr[$j] < $arr[$i]) { list($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]); } if(($j - $i) > 1) { $t = ($j - $i + 1) / 3; stoogesort($arr, $i, $j - $t); stoogesort($arr, $i + $t, $j); stoogesort($arr, $i, $j - $t); } }
StoogeSort(L, i:=1, j:=""){ if !j j := L.MaxIndex() if (L[j] < L[i]){ temp := L[i] L[i] := L[j] L[j] := temp } if (j - i > 1){ t := floor((j - i + 1)/3) StoogeSort(L, i, j-t) StoogeSort(L, i+t, j) StoogeSort(L, i, j-t) } return L }
Generate a AutoHotKey translation of this PHP snippet without changing its computational steps.
function shellSort($arr) { $inc = round(count($arr)/2); while($inc > 0) { for($i = $inc; $i < count($arr);$i++){ $temp = $arr[$i]; $j = $i; while($j >= $inc && $arr[$j-$inc] > $temp) { $arr[$j] = $arr[$j - $inc]; $j -= $inc; } $arr[$j] = $temp; } $inc = round($inc/2.2); } return $ar...
MsgBox % ShellSort("") MsgBox % ShellSort("xxx") MsgBox % ShellSort("3,2,1") MsgBox % ShellSort("dog,000000,xx,cat,pile,abcde,1,cat,zz,xx,z") MsgBox % ShellSort("12,11,10,9,8,4,5,6,7,3,2,1,10,13,14,15,19,17,18,16,20,10") ShellSort(var) {   StringSplit a, var, `,   inc := a0 ...
Change the programming language of this snippet from PHP to AutoHotKey without modifying what it does.
<?php $DOCROOT = $_SERVER['DOCUMENT_ROOT']; function fileLine ($lineNum, $file) { $count = 0; while (!feof($file)) { $count++; $line = fgets($file); if ($count == $lineNum) return $line; } die("Requested file has fewer than ".$lineNum." lines!"); } @ $fp = fopen("$DOC...
FileReadLine, OutputVar, filename.txt, 7 if ErrorLevel MsgBox, There was an error reading the 7th line of the file
Rewrite the snippet below in AutoHotKey so it works the same as the original PHP code.
<?php $DOCROOT = $_SERVER['DOCUMENT_ROOT']; function fileLine ($lineNum, $file) { $count = 0; while (!feof($file)) { $count++; $line = fgets($file); if ($count == $lineNum) return $line; } die("Requested file has fewer than ".$lineNum." lines!"); } @ $fp = fopen("$DOC...
FileReadLine, OutputVar, filename.txt, 7 if ErrorLevel MsgBox, There was an error reading the 7th line of the file
Convert this PHP snippet to AutoHotKey and keep its semantics consistent.
<?php $s = 'http://foo/bar/'; $s = rawurlencode($s); ?>
MsgBox, % UriEncode("http://foo bar/") UriEncode(Uri, Reserved:="!#$&'()*+,/: Unreserved := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~" VarSetCapacity(Var, StrPut(Uri, "UTF-8"), 0) StrPut(Uri, &Var, "UTF-8") While (Code := NumGet(Var, A_Index - 1, "UChar")) { If InStr(Unreserved . Re...
Preserve the algorithm and functionality while converting the code from PHP to AutoHotKey.
<?php $s = 'http://foo/bar/'; $s = rawurlencode($s); ?>
MsgBox, % UriEncode("http://foo bar/") UriEncode(Uri, Reserved:="!#$&'()*+,/: Unreserved := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~" VarSetCapacity(Var, StrPut(Uri, "UTF-8"), 0) StrPut(Uri, &Var, "UTF-8") While (Code := NumGet(Var, A_Index - 1, "UChar")) { If InStr(Unreserved . Re...
Convert the following code from PHP to AutoHotKey, ensuring the logic remains intact.
<?php function f($n) { return sqrt(abs($n)) + 5 * $n * $n * $n; } $sArray = []; echo "Enter 11 numbers.\n"; for ($i = 0; $i <= 10; $i++) { echo $i + 1, " - Enter number: "; array_push($sArray, (float)fgets(STDIN)); } echo PHP_EOL; $sArray = array_reverse($sArray); foreach ($sArray as $s) { $r = ...
seq := [1,2,3,4,5,6,7,8,9,10,11] MsgBox % result := TPK(seq, 400) return TPK(s, num){ for i, v in reverse(s) res .= v . " : " . ((x:=f(v)) > num ? "OVERFLOW" : x ) . "`n" return res } reverse(s){ Loop % s.Count() s.InsertAt(A_Index, s.pop()) return s } f(x){ return Sqrt(x) + 5* (x**...
Produce a language-to-language conversion: from PHP to AutoHotKey, same semantics.
$odd = function ($prev) use ( &$odd ) { $a = fgetc(STDIN); if (!ctype_alpha($a)) { $prev(); fwrite(STDOUT, $a); return $a != '.'; } $clos = function () use ($a , $prev) { fwrite(STDOUT, $a); $prev(); }; return $odd($clos); }; $even = function () { while (true) { $c = fgetc(STDIN); fwrite(STDOUT, $c...
str := "what,is,the loop, parse, str if (A_LoopField ~= "[[:punct:]]") res .= A_LoopField, toggle:=!toggle else res := toggle ? RegExReplace(res, ".*[[:punct:]]\K", A_LoopField ) : res A_LoopField MsgBox % res
Please provide an equivalent version of this PHP code in AutoHotKey.
<?php function is_describing($number) { foreach (str_split((int) $number) as $place => $value) { if (substr_count($number, $place) != $value) { return false; } } return true; } for ($i = 0; $i <= 50000000; $i += 10) { if (is_describing($i)) { echo $i . PHP_EOL;...
#NoEnv SetBatchlines -1 ListLines Off Process, Priority,, high MsgBox % 2020 ": " IsSelfDescribing(2020) "`n" 1337 ": " IsSelfDescribing(1337) "`n" 1210 ": " IsSelfDescribing(1210) Loop 100000000 If IsSelfDescribing(A_Index) list .= A_Index "`n" MsgBox % "Self-describing numbers < 100000000 :`n" . list Coun...
Translate the given PHP code snippet into AutoHotKey without altering its behavior.
<?php $n = 9; // the number of rows for ($i = 1; $i <= $n; $i++) { for ($j = 1; $j <= $n; $j++) { echo ($i == $j || $i == $n - $j + 1) ? ' 1' : ' 0'; } echo "\n"; }
for i, v in [8, 9] result .= "Matrix Size: " v "*" v "`n" matrix2txt(diagonalMatrix(v)) "`n" MsgBox % result return diagonalMatrix(size){ M := [] loop % size { row := A_Index loop % size M[row, A_Index] := (row = A_Index || row = size-A_Index+1) ? 1 : 0 } return M } ma...
Generate an equivalent AutoHotKey version of this PHP code.
<?php foreach(file("unixdict.txt") as $w) echo (strstr($w, "the") && strlen(trim($w)) > 11) ? $w : "";
FileRead, wList, % A_Desktop "\unixdict.txt" SubString := "the" list := ContainSubStr(wList, SubString) for i, v in list result .= i "- " v "`n" MsgBox, 262144, , % result return ContainSubStr(wList, SubString){ oRes := [] for i, w in StrSplit(wList, "`n", "`r") { if (StrLen(w) < 12 || !InStr(...
Port the provided PHP code into AutoHotKey while preserving the original functionality.
$address = <<<END 1, High Street, $town_name, West Midlands. WM4 5HD. END;
MyVar = "This is the text inside MyVar" MyVariable = ( Note that whitespace is preserved As well as newlines. The LTrim option can be present to remove left whitespace. Variable references such as %MyVar% are expanded. ) MsgBox % MyVariable
Can you help me rewrite this code in AutoHotKey instead of PHP, keeping it the same logically?
$address = <<<END 1, High Street, $town_name, West Midlands. WM4 5HD. END;
MyVar = "This is the text inside MyVar" MyVariable = ( Note that whitespace is preserved As well as newlines. The LTrim option can be present to remove left whitespace. Variable references such as %MyVar% are expanded. ) MsgBox % MyVariable
Produce a functionally identical AutoHotKey code for the snippet given in PHP.
<?php $game = new Game(); while(true) { $game->cycle(); } class Game { private $field; private $fieldSize; private $command; private $error; private $lastIndexX, $lastIndexY; private $score; private $finishScore; function __construct() { $this->field = array(); $this->fieldSize = 4; $this->finishS...
Grid := [], s := 16, w := h := S * 4.5 Gui, font, s%s% Gui, add, text, y1 loop, 4 { row := A_Index loop, 4 { col := A_Index if col = 1 Gui, add, button, v%row%_%col% xs y+1 w%w% h%h% -TabStop, % Grid[row,col] := 0 else Gui, add, button, v%row%_%col% x+1 yp w%w% h%h% -TabStop, % Grid[row,col] := 0 } }...