Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Generate an equivalent VB version of this Swift code.
func lookAndSay(_ seq: [Int]) -> [Int] { var result = [Int]() var cur = seq[0] var curRunLength = 1 for i in seq.dropFirst() { if cur == i { curRunLength += 1 } else { result.append(curRunLength) result.append(cur) curRunLength = 1 cur = i } } result.append(curRunLength) result.append(cur) return result } var seq = [1] for i in 0..<10 { print("Seq \(i): \(seq)") seq = lookAndSay(seq) }
function looksay( n ) dim i dim accum dim res dim c res = vbnullstring do if n = vbnullstring then exit do accum = 0 c = left( n,1 ) do while left( n, 1 ) = c accum = accum + 1 n = mid(n,2) loop if accum > 0 then res = res & accum & c end if loop looksay = res end function
Please provide an equivalent version of this Swift code in Go.
func lookAndSay(_ seq: [Int]) -> [Int] { var result = [Int]() var cur = seq[0] var curRunLength = 1 for i in seq.dropFirst() { if cur == i { curRunLength += 1 } else { result.append(curRunLength) result.append(cur) curRunLength = 1 cur = i } } result.append(curRunLength) result.append(cur) return result } var seq = [1] for i in 0..<10 { print("Seq \(i): \(seq)") seq = lookAndSay(seq) }
package main import ( "fmt" "strconv" ) func lss(s string) (r string) { c := s[0] nc := 1 for i := 1; i < len(s); i++ { d := s[i] if d == c { nc++ continue } r += strconv.Itoa(nc) + string(c) c = d nc = 1 } return r + strconv.Itoa(nc) + string(c) } func main() { s := "1" fmt.Println(s) for i := 0; i < 8; i++ { s = lss(s) fmt.Println(s) } }
Port the following code from Tcl to C with equivalent syntax and logic.
proc lookandsay n { set new "" while {[string length $n] > 0} { set char [string index $n 0] for {set count 1} {[string index $n $count] eq $char} {incr count} {} append new $count $char set n [string range $n $count end] } interp alias {} next_lookandsay {} lookandsay $new return $new } puts 1 ; puts [lookandsay 1] ; puts [next_lookandsay] ; puts [next_lookandsay] ; puts [next_lookandsay] ; puts [next_lookandsay] ;
#include <stdio.h> #include <stdlib.h> int main() { char *a = malloc(2), *b = 0, *x, c; int cnt, len = 1; for (sprintf(a, "1"); (b = realloc(b, len * 2 + 1)); a = b, b = x) { puts(x = a); for (len = 0, cnt = 1; (c = *a); ) { if (c == *++a) cnt++; else if (c) { len += sprintf(b + len, "%d%c", cnt, c); cnt = 1; } } } return 0; }
Change the programming language of this snippet from Tcl to C# without modifying what it does.
proc lookandsay n { set new "" while {[string length $n] > 0} { set char [string index $n 0] for {set count 1} {[string index $n $count] eq $char} {incr count} {} append new $count $char set n [string range $n $count end] } interp alias {} next_lookandsay {} lookandsay $new return $new } puts 1 ; puts [lookandsay 1] ; puts [next_lookandsay] ; puts [next_lookandsay] ; puts [next_lookandsay] ; puts [next_lookandsay] ;
using System; using System.Text; using System.Linq; class Program { static string lookandsay(string number) { StringBuilder result = new StringBuilder(); char repeat = number[0]; number = number.Substring(1, number.Length-1)+" "; int times = 1; foreach (char actual in number) { if (actual != repeat) { result.Append(Convert.ToString(times)+repeat); times = 1; repeat = actual; } else { times += 1; } } return result.ToString(); } static void Main(string[] args) { string num = "1"; foreach (int i in Enumerable.Range(1, 10)) { Console.WriteLine(num); num = lookandsay(num); } } }
Generate a C++ translation of this Tcl snippet without changing its computational steps.
proc lookandsay n { set new "" while {[string length $n] > 0} { set char [string index $n 0] for {set count 1} {[string index $n $count] eq $char} {incr count} {} append new $count $char set n [string range $n $count end] } interp alias {} next_lookandsay {} lookandsay $new return $new } puts 1 ; puts [lookandsay 1] ; puts [next_lookandsay] ; puts [next_lookandsay] ; puts [next_lookandsay] ; puts [next_lookandsay] ;
#include <iostream> #include <sstream> #include <string> std::string lookandsay(const std::string& s) { std::ostringstream r; for (std::size_t i = 0; i != s.length();) { auto new_i = s.find_first_not_of(s[i], i + 1); if (new_i == std::string::npos) new_i = s.length(); r << new_i - i << s[i]; i = new_i; } return r.str(); } int main() { std::string laf = "1"; std::cout << laf << '\n'; for (int i = 0; i < 10; ++i) { laf = lookandsay(laf); std::cout << laf << '\n'; } }
Convert the following code from Tcl to Java, ensuring the logic remains intact.
proc lookandsay n { set new "" while {[string length $n] > 0} { set char [string index $n 0] for {set count 1} {[string index $n $count] eq $char} {incr count} {} append new $count $char set n [string range $n $count end] } interp alias {} next_lookandsay {} lookandsay $new return $new } puts 1 ; puts [lookandsay 1] ; puts [next_lookandsay] ; puts [next_lookandsay] ; puts [next_lookandsay] ; puts [next_lookandsay] ;
public static String lookandsay(String number){ StringBuilder result= new StringBuilder(); char repeat= number.charAt(0); number= number.substring(1) + " "; int times= 1; for(char actual: number.toCharArray()){ if(actual != repeat){ result.append(times + "" + repeat); times= 1; repeat= actual; }else{ times+= 1; } } return result.toString(); }
Translate this program into Python but keep the logic exactly as in Tcl.
proc lookandsay n { set new "" while {[string length $n] > 0} { set char [string index $n 0] for {set count 1} {[string index $n $count] eq $char} {incr count} {} append new $count $char set n [string range $n $count end] } interp alias {} next_lookandsay {} lookandsay $new return $new } puts 1 ; puts [lookandsay 1] ; puts [next_lookandsay] ; puts [next_lookandsay] ; puts [next_lookandsay] ; puts [next_lookandsay] ;
def lookandsay(number): result = "" repeat = number[0] number = number[1:]+" " times = 1 for actual in number: if actual != repeat: result += str(times)+repeat times = 1 repeat = actual else: times += 1 return result num = "1" for i in range(10): print num num = lookandsay(num)
Write the same algorithm in VB as shown in this Tcl implementation.
proc lookandsay n { set new "" while {[string length $n] > 0} { set char [string index $n 0] for {set count 1} {[string index $n $count] eq $char} {incr count} {} append new $count $char set n [string range $n $count end] } interp alias {} next_lookandsay {} lookandsay $new return $new } puts 1 ; puts [lookandsay 1] ; puts [next_lookandsay] ; puts [next_lookandsay] ; puts [next_lookandsay] ; puts [next_lookandsay] ;
function looksay( n ) dim i dim accum dim res dim c res = vbnullstring do if n = vbnullstring then exit do accum = 0 c = left( n,1 ) do while left( n, 1 ) = c accum = accum + 1 n = mid(n,2) loop if accum > 0 then res = res & accum & c end if loop looksay = res end function
Please provide an equivalent version of this Tcl code in Go.
proc lookandsay n { set new "" while {[string length $n] > 0} { set char [string index $n 0] for {set count 1} {[string index $n $count] eq $char} {incr count} {} append new $count $char set n [string range $n $count end] } interp alias {} next_lookandsay {} lookandsay $new return $new } puts 1 ; puts [lookandsay 1] ; puts [next_lookandsay] ; puts [next_lookandsay] ; puts [next_lookandsay] ; puts [next_lookandsay] ;
package main import ( "fmt" "strconv" ) func lss(s string) (r string) { c := s[0] nc := 1 for i := 1; i < len(s); i++ { d := s[i] if d == c { nc++ continue } r += strconv.Itoa(nc) + string(c) c = d nc = 1 } return r + strconv.Itoa(nc) + string(c) } func main() { s := "1" fmt.Println(s) for i := 0; i < 8; i++ { s = lss(s) fmt.Println(s) } }
Transform the following Rust implementation into PHP, maintaining the same output and logic.
fn next_sequence(in_seq: &[i8]) -> Vec<i8> { assert!(!in_seq.is_empty()); let mut result = Vec::new(); let mut current_number = in_seq[0]; let mut current_runlength = 1; for i in &in_seq[1..] { if current_number == *i { current_runlength += 1; } else { result.push(current_runlength); result.push(current_number); current_runlength = 1; current_number = *i; } } result.push(current_runlength); result.push(current_number); result } fn main() { let mut seq = vec![1]; for i in 0..10 { println!("Sequence {}: {:?}", i, seq); seq = next_sequence(&seq); } }
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Write a version of this Ada function in PHP with identical behavior.
with Ada.Text_IO, Ada.Strings.Fixed; use Ada.Text_IO, Ada.Strings, Ada.Strings.Fixed; function "+" (S : String) return String is Item : constant Character := S (S'First); begin for Index in S'First + 1..S'Last loop if Item /= S (Index) then return Trim (Integer'Image (Index - S'First), Both) & Item & (+(S (Index..S'Last))); end if; end loop; return Trim (Integer'Image (S'Length), Both) & Item; end "+";
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Convert this Arturo block to PHP, preserving its control flow and logic.
lookAndSay: function [n][ if n=0 -> return "1" previous: lookAndSay n-1 result: new "" currentCounter: 0 currentCh: first previous loop previous 'ch [ if? currentCh <> ch [ if not? zero? currentCounter -> 'result ++ (to :string currentCounter) ++ currentCh currentCounter: 1 currentCh: ch ] else -> currentCounter: currentCounter + 1 ] 'result ++ (to :string currentCounter) ++ currentCh return result ] loop 0..10 'x [ print [x "->" lookAndSay x] ]
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Rewrite the snippet below in PHP so it works the same as the original AutoHotKey code.
AutoExecute: Gui, -MinimizeBox Gui, Add, Edit, w500 r20 vInput, 1 Gui, Add, Button, x155 w100 Default, &Calculate Gui, Add, Button, xp+110 yp wp, E&xit Gui, Show,, Look-and-Say sequence Return ButtonCalculate: Gui, Submit, NoHide GuiControl,, Input, % LookAndSay(Input) Return GuiClose: ButtonExit: ExitApp Return LookAndSay(Input) {       Loop, Parse, Input   If (A_LoopField = d)   c += 1   Else {   r .= c d   c := 1   d := A_LoopField   } Return, r c d }
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Port the provided AWK code into PHP while preserving the original functionality.
function lookandsay(a) { s = "" c = 1 p = substr(a, 1, 1) for(i=2; i <= length(a); i++) { if ( p == substr(a, i, 1) ) { c++ } else { s = s sprintf("%d%s", c, p) p = substr(a, i, 1) c = 1 } } s = s sprintf("%d%s", c, p) return s } BEGIN { b = "1" print b for(k=1; k <= 10; k++) { b = lookandsay(b) print b } }
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Ensure the translated PHP code behaves exactly like the original BBC_Basic snippet.
number$ = "1" FOR i% = 1 TO 10 number$ = FNlooksay(number$) PRINT number$ NEXT END DEF FNlooksay(n$) LOCAL i%, j%, c$, o$ i% = 1 REPEAT c$ = MID$(n$,i%,1) j% = i% + 1 WHILE MID$(n$,j%,1) = c$ j% += 1 ENDWHILE o$ += STR$(j%-i%) + c$ i% = j% UNTIL i% > LEN(n$) = o$
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Please provide an equivalent version of this Clojure code in PHP.
(defn digits-seq "Returns a seq of the digits of a number (L->R)." [n] (loop [digits (), number n] (if (zero? number) (seq digits) (recur (cons (mod number 10) digits) (quot number 10))))) (defn join-digits "Converts a digits-seq back in to a number." [ds] (reduce (fn [n d] (+ (* 10 n) d)) ds)) (defn look-and-say [n] (->> n digits-seq (partition-by identity) (mapcat (juxt count first)) join-digits))
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Translate the given Common_Lisp code snippet into PHP without altering its behavior.
(defun compress (array &key (test 'eql) &aux (l (length array))) "Compresses array by returning a list of conses each of whose car is a number of occurrences and whose cdr is the element occurring. For instance, (compress \"abb\") produces ((1 . #\a) (2 . #\b))." (if (zerop l) nil (do* ((i 1 (1+ i)) (segments (acons 1 (aref array 0) '()))) ((eql i l) (nreverse segments)) (if (funcall test (aref array i) (cdar segments)) (incf (caar segments)) (setf segments (acons 1 (aref array i) segments)))))) (defun next-look-and-say (number) (reduce #'(lambda (n pair) (+ (* 100 n) (* 10 (car pair)) (parse-integer (string (cdr pair))))) (compress (princ-to-string number)) :initial-value 0))
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Produce a language-to-language conversion: from D to PHP, same semantics.
import std.stdio, std.algorithm, std.range; enum say = (in string s) pure => s.group.map!q{ text(a[1],a[0]) }.join; void main() { "1".recurrence!((t, n) => t[n - 1].say).take(8).writeln; }
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Rewrite this program in PHP while keeping its functionality equivalent to the Elixir version.
defmodule LookAndSay do def next(n) do Enum.chunk_by(to_char_list(n), &(&1)) |> Enum.map(fn cl=[h|_] -> Enum.concat(to_char_list(length cl), [h]) end) |> Enum.concat |> List.to_integer end def sequence_from(n) do Stream.iterate n, &(next/1) end def main([start_str|_]) do {start_val,_} = Integer.parse(start_str) IO.inspect sequence_from(start_val) |> Enum.take 9 end def main([]) do main(["1"]) end end LookAndSay.main(System.argv)
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Convert the following code from Erlang to PHP, ensuring the logic remains intact.
-module(str). -export([look_and_say/1, look_and_say/2]). look_and_say([H|T]) -> lists:reverse(look_and_say(T,H,1,"")). look_and_say(_, 0) -> []; look_and_say(Start, Times) when Times > 0 -> [Start | look_and_say(look_and_say(Start), Times-1)]. look_and_say([], Current, N, Acc) -> [Current, $0+N | Acc]; look_and_say([H|T], H, N, Acc) -> look_and_say(T, H, N+1, Acc); look_and_say([H|T], Current, N, Acc) -> look_and_say(T, H, 1, [Current, $0+N | Acc]).
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Rewrite the snippet below in PHP so it works the same as the original F# code.
let rec brk p lst = match lst with | [] -> (lst, lst) | x::xs -> if p x then ([], lst) else let (ys, zs) = brk p xs (x::ys, zs) let span p lst = brk (not << p) lst let rec groupBy eq lst = match lst with | [] -> [] | x::xs -> let (ys,zs) = span (eq x) xs (x::ys)::groupBy eq zs let group lst : list<list<'a>> when 'a : equality = groupBy (=) lst
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Write a version of this Factor function in PHP with identical behavior.
: (look-and-say) ( str -- ) unclip-slice swap [ 1 ] 2dip [ 2dup = [ drop [ 1 + ] dip ] [ [ [ number>string % ] dip , 1 ] dip ] if ] each [ number>string % ] [ , ] bi* ; : look-and-say ( str -- str' ) [ (look-and-say) ] "" make ; "1" 10 [ dup print look-and-say ] times print
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Port the provided Forth code into PHP while preserving the original functionality.
create buf1 256 allot create buf2 256 allot buf1 value src buf2 value dest s" 1" src place : append-run dest count + tuck c! 1+ c! dest c@ 2 + dest c! ; : next-look-and-say 0 dest c! src 1+ c@ [char] 0 src count bounds do over i c@ = if 1+ else append-run i c@ [char] 1 then loop append-run src dest to src to dest ; : look-and-say 0 do next-look-and-say cr src count type loop ; 10 look-and-say
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Write the same algorithm in PHP as shown in this Fortran implementation.
module LookAndSay implicit none contains subroutine look_and_say(in, out) character(len=*), intent(in) :: in character(len=*), intent(out) :: out integer :: i, c character(len=1) :: x character(len=2) :: d out = "" c = 1 x = in(1:1) do i = 2, len(trim(in)) if ( x == in(i:i) ) then c = c + 1 else write(d, "(I2)") c out = trim(out) // trim(adjustl(d)) // trim(x) c = 1 x = in(i:i) end if end do write(d, "(I2)") c out = trim(out) // trim(adjustl(d)) // trim(x) end subroutine look_and_say end module LookAndSay
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Translate the given Groovy code snippet into PHP without altering its behavior.
def lookAndSay(sequence) { def encoded = new StringBuilder() (sequence.toString() =~ /(([0-9])\2*)/).each { matcher -> encoded.append(matcher[1].size()).append(matcher[2]) } encoded.toString() }
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Generate an equivalent PHP version of this Haskell code.
import Control.Monad (liftM2) import Data.List (group) lookAndSay :: Integer -> Integer lookAndSay = read . concatMap (liftM2 (++) (show . length) (take 1)) . group . show lookAndSay2 :: Integer -> Integer lookAndSay2 = read . concatMap (liftM2 (++) (show . length) (take 1)) . group . show lookAndSay3 :: Integer -> Integer lookAndSay3 n = read (concatMap describe (group (show n))) where describe run = show (length run) ++ take 1 run main = mapM_ print (iterate lookAndSay 1)
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Can you help me rewrite this code in PHP instead of Icon, keeping it the same logically?
procedure main() every 1 to 10 do write(n := nextlooknsayseq(\n | 1)) end procedure nextlooknsayseq(n) n2 := "" n ? until pos(0) do { i := tab(any(&digits)) | fail move(-1) n2 ||:= *tab(many(i)) || i } return n2 end
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Port the following code from J to PHP with equivalent syntax and logic.
las=: ,@((# , {.);.1~ 1 , 2 ~:/\ ])&.(10x&#.inv)@]^:(1+i.@[)
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Produce a language-to-language conversion: from Julia to PHP, same semantics.
function lookandsay(s::String) rst = IOBuffer() c = 1 for i in 1:length(s) if i != length(s) && s[i] == s[i+1] c += 1 else print(rst, c, s[i]) c = 1 end end String(take!(rst)) end function lookandsayseq(n::Integer) rst = Vector{String}(undef, n) rst[1] = "1" for i in 2:n rst[i] = lookandsay(rst[i-1]) end rst end println(lookandsayseq(10))
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Write a version of this Lua function in PHP with identical behavior.
function lookAndSay S put 0 into C put char 1 of S into lastChar repeat with i = 2 to length(S) add 1 to C if char i of S is lastChar then next repeat put C & lastChar after R put 0 into C put char i of S into lastChar end repeat return R & C + 1 & lastChar end lookAndSay on demoLookAndSay put 1 into x repeat 10 put x & cr after message put lookAndSay(x) into x end repeat put x after message end demoLookAndSay
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Can you help me rewrite this code in PHP instead of Mathematica, keeping it the same logically?
LookAndSay[n_Integer?Positive]:= Reverse @@@ Tally /@ Split @ IntegerDigits @ n // Flatten // FromDigits
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Generate a PHP translation of this Nim snippet without changing its computational steps.
iterator lookAndSay(n: int): string = var current = "1" yield current for round in 2..n: var ch = current[0] var count = 1 var next = "" for i in 1..current.high: if current[i] == ch: inc count else: next.add $count & ch ch = current[i] count = 1 current = next & $count & ch yield current for s in lookAndSay(12): echo s
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Write the same code in PHP as shown below in OCaml.
let rec seeAndSay = function | [], nys -> List.rev nys | x::xs, [] -> seeAndSay(xs, [x; 1]) | x::xs, y::n::nys when x=y -> seeAndSay(xs, y::1+n::nys) | x::xs, nys -> seeAndSay(xs, x::1::nys)
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Write a version of this Pascal function in PHP with identical behavior.
program LookAndSayDemo(input, output); uses SysUtils; function LookAndSay(s: string): string; var item: char; index: integer; count: integer; begin Result := ''; item := s[1]; count := 1; for index := 2 to length(s) do if item = s[index] then inc(count) else begin Result := Result + intTostr(count) + item; item := s[index]; count := 1; end; Result := Result + intTostr(count) + item; end; var number: string; begin writeln('Press RETURN to continue and ^C to stop.'); number := '1'; while not eof(input) do begin write(number); readln; number := LookAndSay(number); end; end.
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Port the following code from Perl to PHP with equivalent syntax and logic.
sub lookandsay { my $str = shift; $str =~ s/((.)\2*)/length($1) . $2/ge; return $str; } my $num = "1"; foreach (1..10) { print "$num\n"; $num = lookandsay($num); }
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Write the same code in PHP as shown below in PowerShell.
function Get-LookAndSay ($n = 1) { $re = [regex] '(.)\1*' $ret = "" foreach ($m in $re.Matches($n)) { $ret += [string] $m.Length + $m.Value[0] } return $ret } function Get-MultipleLookAndSay ($n) { if ($n -eq 0) { return @() } else { $a = 1 $a for ($i = 1; $i -lt $n; $i++) { $a = Get-LookAndSay $a $a } } }
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Convert the following code from R to PHP, ensuring the logic remains intact.
look.and.say <- function(x, return.an.int=FALSE) { xstr <- unlist(strsplit(as.character(x), "")) rlex <- rle(xstr) odds <- as.character(rlex$lengths) evens <- rlex$values newstr <- as.vector(rbind(odds, evens)) newstr <- paste(newstr, collapse="") if(return.an.int) as.integer(newstr) else newstr }
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Please provide an equivalent version of this Racket code in PHP.
#lang racket (define (encode str) (regexp-replace* #px"(.)\\1*" str (lambda (m c) (~a (string-length m) c)))) (define (look-and-say-sequence n) (reverse (for/fold ([r '("1")]) ([n n]) (cons (encode (car r)) r)))) (for-each displayln (look-and-say-sequence 10))
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Keep all operations the same but rewrite the snippet in PHP.
IDENTIFICATION DIVISION. PROGRAM-ID. LOOK-AND-SAY-SEQ. DATA DIVISION. WORKING-STORAGE SECTION. 01 SEQUENCES. 02 CUR-SEQ PIC X(80) VALUE "1". 02 CUR-CHARS REDEFINES CUR-SEQ PIC X OCCURS 80 TIMES INDEXED BY CI. 02 CUR-LENGTH PIC 99 COMP VALUE 1. 02 NEXT-SEQ PIC X(80). 02 NEXT-CHARS REDEFINES NEXT-SEQ PIC X OCCURS 80 TIMES INDEXED BY NI. 01 ALG-STATE. 02 STEP-AMOUNT PIC 99 VALUE 14. 02 ITEM-COUNT PIC 9. PROCEDURE DIVISION. LOOK-AND-SAY. DISPLAY CUR-SEQ. SET CI TO 1. SET NI TO 1. MAKE-NEXT-ENTRY. MOVE 0 TO ITEM-COUNT. IF CI IS GREATER THAN CUR-LENGTH GO TO STEP-DONE. TALLY-ITEM. ADD 1 TO ITEM-COUNT. SET CI UP BY 1. IF CI IS NOT GREATER THAN CUR-LENGTH AND CUR-CHARS(CI) IS EQUAL TO CUR-CHARS(CI - 1) GO TO TALLY-ITEM. INSERT-ENTRY. MOVE ITEM-COUNT TO NEXT-CHARS(NI). MOVE CUR-CHARS(CI - 1) TO NEXT-CHARS(NI + 1). SET NI UP BY 2. GO TO MAKE-NEXT-ENTRY. STEP-DONE. MOVE NEXT-SEQ TO CUR-SEQ. SET NI DOWN BY 1. SET CUR-LENGTH TO NI. SUBTRACT 1 FROM STEP-AMOUNT. IF STEP-AMOUNT IS NOT EQUAL TO ZERO GO TO LOOK-AND-SAY. STOP RUN.
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Change the following REXX code into PHP without altering its purpose.
parse arg N ! . if N=='' | N=="," then N= 20 if !=='' | !=="," then != 1 do j=1 for abs(N) if j\==1 then != lookNsay(!) if N<0 then say 'length['j"]:" length(!) else say '['j"]:" ! end exit 0 lookNsay: procedure; parse arg x,,$ fin = '0'x x= x || fin do k=1 by 0 y= substr(x, k, 1) if y== fin then return $ _= verify(x, y, , k) - k $= $ || _ || y k= k + _ end
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Produce a language-to-language conversion: from Ruby to PHP, same semantics.
class String def lookandsay gsub(/(.)\1*/){ |s| s.size.to_s + s[0] } end end ss = '1' 12.times { puts ss; ss = ss.to_s.lookandsay }
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Translate this program into PHP but keep the logic exactly as in Scala.
fun lookAndSay(s: String): String { val sb = StringBuilder() var digit = s[0] var count = 1 for (i in 1 until s.length) { if (s[i] == digit) count++ else { sb.append("$count$digit") digit = s[i] count = 1 } } return sb.append("$count$digit").toString() } fun main(args: Array<String>) { var las = "1" for (i in 1..15) { println(las) las = lookAndSay(las) } }
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Produce a language-to-language conversion: from Swift to PHP, same semantics.
func lookAndSay(_ seq: [Int]) -> [Int] { var result = [Int]() var cur = seq[0] var curRunLength = 1 for i in seq.dropFirst() { if cur == i { curRunLength += 1 } else { result.append(curRunLength) result.append(cur) curRunLength = 1 cur = i } } result.append(curRunLength) result.append(cur) return result } var seq = [1] for i in 0..<10 { print("Seq \(i): \(seq)") seq = lookAndSay(seq) }
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Change the programming language of this snippet from Tcl to PHP without modifying what it does.
proc lookandsay n { set new "" while {[string length $n] > 0} { set char [string index $n 0] for {set count 1} {[string index $n $count] eq $char} {incr count} {} append new $count $char set n [string range $n $count end] } interp alias {} next_lookandsay {} lookandsay $new return $new } puts 1 ; puts [lookandsay 1] ; puts [next_lookandsay] ; puts [next_lookandsay] ; puts [next_lookandsay] ; puts [next_lookandsay] ;
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Change the following C code into Rust without altering its purpose.
#include <stdio.h> #include <stdlib.h> int main() { char *a = malloc(2), *b = 0, *x, c; int cnt, len = 1; for (sprintf(a, "1"); (b = realloc(b, len * 2 + 1)); a = b, b = x) { puts(x = a); for (len = 0, cnt = 1; (c = *a); ) { if (c == *++a) cnt++; else if (c) { len += sprintf(b + len, "%d%c", cnt, c); cnt = 1; } } } return 0; }
fn next_sequence(in_seq: &[i8]) -> Vec<i8> { assert!(!in_seq.is_empty()); let mut result = Vec::new(); let mut current_number = in_seq[0]; let mut current_runlength = 1; for i in &in_seq[1..] { if current_number == *i { current_runlength += 1; } else { result.push(current_runlength); result.push(current_number); current_runlength = 1; current_number = *i; } } result.push(current_runlength); result.push(current_number); result } fn main() { let mut seq = vec![1]; for i in 0..10 { println!("Sequence {}: {:?}", i, seq); seq = next_sequence(&seq); } }
Ensure the translated Rust code behaves exactly like the original C++ snippet.
#include <iostream> #include <sstream> #include <string> std::string lookandsay(const std::string& s) { std::ostringstream r; for (std::size_t i = 0; i != s.length();) { auto new_i = s.find_first_not_of(s[i], i + 1); if (new_i == std::string::npos) new_i = s.length(); r << new_i - i << s[i]; i = new_i; } return r.str(); } int main() { std::string laf = "1"; std::cout << laf << '\n'; for (int i = 0; i < 10; ++i) { laf = lookandsay(laf); std::cout << laf << '\n'; } }
fn next_sequence(in_seq: &[i8]) -> Vec<i8> { assert!(!in_seq.is_empty()); let mut result = Vec::new(); let mut current_number = in_seq[0]; let mut current_runlength = 1; for i in &in_seq[1..] { if current_number == *i { current_runlength += 1; } else { result.push(current_runlength); result.push(current_number); current_runlength = 1; current_number = *i; } } result.push(current_runlength); result.push(current_number); result } fn main() { let mut seq = vec![1]; for i in 0..10 { println!("Sequence {}: {:?}", i, seq); seq = next_sequence(&seq); } }
Can you help me rewrite this code in Rust instead of Java, keeping it the same logically?
public static String lookandsay(String number){ StringBuilder result= new StringBuilder(); char repeat= number.charAt(0); number= number.substring(1) + " "; int times= 1; for(char actual: number.toCharArray()){ if(actual != repeat){ result.append(times + "" + repeat); times= 1; repeat= actual; }else{ times+= 1; } } return result.toString(); }
fn next_sequence(in_seq: &[i8]) -> Vec<i8> { assert!(!in_seq.is_empty()); let mut result = Vec::new(); let mut current_number = in_seq[0]; let mut current_runlength = 1; for i in &in_seq[1..] { if current_number == *i { current_runlength += 1; } else { result.push(current_runlength); result.push(current_number); current_runlength = 1; current_number = *i; } } result.push(current_runlength); result.push(current_number); result } fn main() { let mut seq = vec![1]; for i in 0..10 { println!("Sequence {}: {:?}", i, seq); seq = next_sequence(&seq); } }
Produce a language-to-language conversion: from Go to Rust, same semantics.
package main import ( "fmt" "strconv" ) func lss(s string) (r string) { c := s[0] nc := 1 for i := 1; i < len(s); i++ { d := s[i] if d == c { nc++ continue } r += strconv.Itoa(nc) + string(c) c = d nc = 1 } return r + strconv.Itoa(nc) + string(c) } func main() { s := "1" fmt.Println(s) for i := 0; i < 8; i++ { s = lss(s) fmt.Println(s) } }
fn next_sequence(in_seq: &[i8]) -> Vec<i8> { assert!(!in_seq.is_empty()); let mut result = Vec::new(); let mut current_number = in_seq[0]; let mut current_runlength = 1; for i in &in_seq[1..] { if current_number == *i { current_runlength += 1; } else { result.push(current_runlength); result.push(current_number); current_runlength = 1; current_number = *i; } } result.push(current_runlength); result.push(current_number); result } fn main() { let mut seq = vec![1]; for i in 0..10 { println!("Sequence {}: {:?}", i, seq); seq = next_sequence(&seq); } }
Ensure the translated VB code behaves exactly like the original Rust snippet.
fn next_sequence(in_seq: &[i8]) -> Vec<i8> { assert!(!in_seq.is_empty()); let mut result = Vec::new(); let mut current_number = in_seq[0]; let mut current_runlength = 1; for i in &in_seq[1..] { if current_number == *i { current_runlength += 1; } else { result.push(current_runlength); result.push(current_number); current_runlength = 1; current_number = *i; } } result.push(current_runlength); result.push(current_number); result } fn main() { let mut seq = vec![1]; for i in 0..10 { println!("Sequence {}: {:?}", i, seq); seq = next_sequence(&seq); } }
function looksay( n ) dim i dim accum dim res dim c res = vbnullstring do if n = vbnullstring then exit do accum = 0 c = left( n,1 ) do while left( n, 1 ) = c accum = accum + 1 n = mid(n,2) loop if accum > 0 then res = res & accum & c end if loop looksay = res end function
Write the same code in Rust as shown below in C#.
using System; using System.Text; using System.Linq; class Program { static string lookandsay(string number) { StringBuilder result = new StringBuilder(); char repeat = number[0]; number = number.Substring(1, number.Length-1)+" "; int times = 1; foreach (char actual in number) { if (actual != repeat) { result.Append(Convert.ToString(times)+repeat); times = 1; repeat = actual; } else { times += 1; } } return result.ToString(); } static void Main(string[] args) { string num = "1"; foreach (int i in Enumerable.Range(1, 10)) { Console.WriteLine(num); num = lookandsay(num); } } }
fn next_sequence(in_seq: &[i8]) -> Vec<i8> { assert!(!in_seq.is_empty()); let mut result = Vec::new(); let mut current_number = in_seq[0]; let mut current_runlength = 1; for i in &in_seq[1..] { if current_number == *i { current_runlength += 1; } else { result.push(current_runlength); result.push(current_number); current_runlength = 1; current_number = *i; } } result.push(current_runlength); result.push(current_number); result } fn main() { let mut seq = vec![1]; for i in 0..10 { println!("Sequence {}: {:?}", i, seq); seq = next_sequence(&seq); } }
Port the provided Rust code into Python while preserving the original functionality.
fn next_sequence(in_seq: &[i8]) -> Vec<i8> { assert!(!in_seq.is_empty()); let mut result = Vec::new(); let mut current_number = in_seq[0]; let mut current_runlength = 1; for i in &in_seq[1..] { if current_number == *i { current_runlength += 1; } else { result.push(current_runlength); result.push(current_number); current_runlength = 1; current_number = *i; } } result.push(current_runlength); result.push(current_number); result } fn main() { let mut seq = vec![1]; for i in 0..10 { println!("Sequence {}: {:?}", i, seq); seq = next_sequence(&seq); } }
def lookandsay(number): result = "" repeat = number[0] number = number[1:]+" " times = 1 for actual in number: if actual != repeat: result += str(times)+repeat times = 1 repeat = actual else: times += 1 return result num = "1" for i in range(10): print num num = lookandsay(num)
Generate a C# translation of this Ada snippet without changing its computational steps.
with Ada.Text_IO; procedure Value_Capture is protected type Fun is entry Init(Index: Natural); function Result return Natural; private N: Natural := 0; end Fun; protected body Fun is entry Init(Index: Natural) when N=0 is begin N := Index; end Init; function Result return Natural is (N*N); end Fun; A: array (1 .. 10) of Fun; begin for I in A'Range loop A(I).Init(I); end loop; for I in A'First .. A'Last-1 loop Ada.Text_IO.Put(Integer'Image(A(I).Result)); end loop; end Value_Capture;
using System; using System.Linq; class Program { static void Main() { var captor = (Func<int, Func<int>>)(number => () => number * number); var functions = Enumerable.Range(0, 10).Select(captor); foreach (var function in functions.Take(9)) { Console.WriteLine(function()); } } }
Convert this Ada snippet to C# and keep its semantics consistent.
with Ada.Text_IO; procedure Value_Capture is protected type Fun is entry Init(Index: Natural); function Result return Natural; private N: Natural := 0; end Fun; protected body Fun is entry Init(Index: Natural) when N=0 is begin N := Index; end Init; function Result return Natural is (N*N); end Fun; A: array (1 .. 10) of Fun; begin for I in A'Range loop A(I).Init(I); end loop; for I in A'First .. A'Last-1 loop Ada.Text_IO.Put(Integer'Image(A(I).Result)); end loop; end Value_Capture;
using System; using System.Linq; class Program { static void Main() { var captor = (Func<int, Func<int>>)(number => () => number * number); var functions = Enumerable.Range(0, 10).Select(captor); foreach (var function in functions.Take(9)) { Console.WriteLine(function()); } } }
Generate a C translation of this Ada snippet without changing its computational steps.
with Ada.Text_IO; procedure Value_Capture is protected type Fun is entry Init(Index: Natural); function Result return Natural; private N: Natural := 0; end Fun; protected body Fun is entry Init(Index: Natural) when N=0 is begin N := Index; end Init; function Result return Natural is (N*N); end Fun; A: array (1 .. 10) of Fun; begin for I in A'Range loop A(I).Init(I); end loop; for I in A'First .. A'Last-1 loop Ada.Text_IO.Put(Integer'Image(A(I).Result)); end loop; end Value_Capture;
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/mman.h> typedef int (*f_int)(); #define TAG 0xdeadbeef int _tmpl() { volatile int x = TAG; return x * x; } #define PROT (PROT_EXEC | PROT_WRITE) #define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS) f_int dupf(int v) { size_t len = (void*)dupf - (void*)_tmpl; f_int ret = mmap(NULL, len, PROT, FLAGS, 0, 0); char *p; if(ret == MAP_FAILED) { perror("mmap"); exit(-1); } memcpy(ret, _tmpl, len); for (p = (char*)ret; p < (char*)ret + len - sizeof(int); p++) if (*(int *)p == TAG) *(int *)p = v; return ret; } int main() { f_int funcs[10]; int i; for (i = 0; i < 10; i++) funcs[i] = dupf(i); for (i = 0; i < 9; i++) printf("func[%d]: %d\n", i, funcs[i]()); return 0; }
Please provide an equivalent version of this Ada code in C.
with Ada.Text_IO; procedure Value_Capture is protected type Fun is entry Init(Index: Natural); function Result return Natural; private N: Natural := 0; end Fun; protected body Fun is entry Init(Index: Natural) when N=0 is begin N := Index; end Init; function Result return Natural is (N*N); end Fun; A: array (1 .. 10) of Fun; begin for I in A'Range loop A(I).Init(I); end loop; for I in A'First .. A'Last-1 loop Ada.Text_IO.Put(Integer'Image(A(I).Result)); end loop; end Value_Capture;
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/mman.h> typedef int (*f_int)(); #define TAG 0xdeadbeef int _tmpl() { volatile int x = TAG; return x * x; } #define PROT (PROT_EXEC | PROT_WRITE) #define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS) f_int dupf(int v) { size_t len = (void*)dupf - (void*)_tmpl; f_int ret = mmap(NULL, len, PROT, FLAGS, 0, 0); char *p; if(ret == MAP_FAILED) { perror("mmap"); exit(-1); } memcpy(ret, _tmpl, len); for (p = (char*)ret; p < (char*)ret + len - sizeof(int); p++) if (*(int *)p == TAG) *(int *)p = v; return ret; } int main() { f_int funcs[10]; int i; for (i = 0; i < 10; i++) funcs[i] = dupf(i); for (i = 0; i < 9; i++) printf("func[%d]: %d\n", i, funcs[i]()); return 0; }
Change the programming language of this snippet from Ada to C++ without modifying what it does.
with Ada.Text_IO; procedure Value_Capture is protected type Fun is entry Init(Index: Natural); function Result return Natural; private N: Natural := 0; end Fun; protected body Fun is entry Init(Index: Natural) when N=0 is begin N := Index; end Init; function Result return Natural is (N*N); end Fun; A: array (1 .. 10) of Fun; begin for I in A'Range loop A(I).Init(I); end loop; for I in A'First .. A'Last-1 loop Ada.Text_IO.Put(Integer'Image(A(I).Result)); end loop; end Value_Capture;
#include <iostream> #include <functional> #include <vector> int main() { std::vector<std::function<int()> > funcs; for (int i = 0; i < 10; i++) funcs.push_back([=]() { return i * i; }); for ( std::function<int( )> f : funcs ) std::cout << f( ) << std::endl ; return 0; }
Produce a functionally identical C++ code for the snippet given in Ada.
with Ada.Text_IO; procedure Value_Capture is protected type Fun is entry Init(Index: Natural); function Result return Natural; private N: Natural := 0; end Fun; protected body Fun is entry Init(Index: Natural) when N=0 is begin N := Index; end Init; function Result return Natural is (N*N); end Fun; A: array (1 .. 10) of Fun; begin for I in A'Range loop A(I).Init(I); end loop; for I in A'First .. A'Last-1 loop Ada.Text_IO.Put(Integer'Image(A(I).Result)); end loop; end Value_Capture;
#include <iostream> #include <functional> #include <vector> int main() { std::vector<std::function<int()> > funcs; for (int i = 0; i < 10; i++) funcs.push_back([=]() { return i * i; }); for ( std::function<int( )> f : funcs ) std::cout << f( ) << std::endl ; return 0; }
Rewrite the snippet below in Go so it works the same as the original Ada code.
with Ada.Text_IO; procedure Value_Capture is protected type Fun is entry Init(Index: Natural); function Result return Natural; private N: Natural := 0; end Fun; protected body Fun is entry Init(Index: Natural) when N=0 is begin N := Index; end Init; function Result return Natural is (N*N); end Fun; A: array (1 .. 10) of Fun; begin for I in A'Range loop A(I).Init(I); end loop; for I in A'First .. A'Last-1 loop Ada.Text_IO.Put(Integer'Image(A(I).Result)); end loop; end Value_Capture;
package main import "fmt" func main() { fs := make([]func() int, 10) for i := range fs { i := i fs[i] = func() int { return i * i } } fmt.Println("func #0:", fs[0]()) fmt.Println("func #3:", fs[3]()) }
Convert this Ada block to Go, preserving its control flow and logic.
with Ada.Text_IO; procedure Value_Capture is protected type Fun is entry Init(Index: Natural); function Result return Natural; private N: Natural := 0; end Fun; protected body Fun is entry Init(Index: Natural) when N=0 is begin N := Index; end Init; function Result return Natural is (N*N); end Fun; A: array (1 .. 10) of Fun; begin for I in A'Range loop A(I).Init(I); end loop; for I in A'First .. A'Last-1 loop Ada.Text_IO.Put(Integer'Image(A(I).Result)); end loop; end Value_Capture;
package main import "fmt" func main() { fs := make([]func() int, 10) for i := range fs { i := i fs[i] = func() int { return i * i } } fmt.Println("func #0:", fs[0]()) fmt.Println("func #3:", fs[3]()) }
Convert the following code from Ada to Java, ensuring the logic remains intact.
with Ada.Text_IO; procedure Value_Capture is protected type Fun is entry Init(Index: Natural); function Result return Natural; private N: Natural := 0; end Fun; protected body Fun is entry Init(Index: Natural) when N=0 is begin N := Index; end Init; function Result return Natural is (N*N); end Fun; A: array (1 .. 10) of Fun; begin for I in A'Range loop A(I).Init(I); end loop; for I in A'First .. A'Last-1 loop Ada.Text_IO.Put(Integer'Image(A(I).Result)); end loop; end Value_Capture;
import java.util.function.Supplier; import java.util.ArrayList; public class ValueCapture { public static void main(String[] args) { ArrayList<Supplier<Integer>> funcs = new ArrayList<>(); for (int i = 0; i < 10; i++) { int j = i; funcs.add(() -> j * j); } Supplier<Integer> foo = funcs.get(3); System.out.println(foo.get()); } }
Change the programming language of this snippet from Ada to Java without modifying what it does.
with Ada.Text_IO; procedure Value_Capture is protected type Fun is entry Init(Index: Natural); function Result return Natural; private N: Natural := 0; end Fun; protected body Fun is entry Init(Index: Natural) when N=0 is begin N := Index; end Init; function Result return Natural is (N*N); end Fun; A: array (1 .. 10) of Fun; begin for I in A'Range loop A(I).Init(I); end loop; for I in A'First .. A'Last-1 loop Ada.Text_IO.Put(Integer'Image(A(I).Result)); end loop; end Value_Capture;
import java.util.function.Supplier; import java.util.ArrayList; public class ValueCapture { public static void main(String[] args) { ArrayList<Supplier<Integer>> funcs = new ArrayList<>(); for (int i = 0; i < 10; i++) { int j = i; funcs.add(() -> j * j); } Supplier<Integer> foo = funcs.get(3); System.out.println(foo.get()); } }
Translate the given Ada code snippet into Python without altering its behavior.
with Ada.Text_IO; procedure Value_Capture is protected type Fun is entry Init(Index: Natural); function Result return Natural; private N: Natural := 0; end Fun; protected body Fun is entry Init(Index: Natural) when N=0 is begin N := Index; end Init; function Result return Natural is (N*N); end Fun; A: array (1 .. 10) of Fun; begin for I in A'Range loop A(I).Init(I); end loop; for I in A'First .. A'Last-1 loop Ada.Text_IO.Put(Integer'Image(A(I).Result)); end loop; end Value_Capture;
funcs = [] for i in range(10): funcs.append(lambda: i * i) print funcs[3]()
Write a version of this Ada function in Python with identical behavior.
with Ada.Text_IO; procedure Value_Capture is protected type Fun is entry Init(Index: Natural); function Result return Natural; private N: Natural := 0; end Fun; protected body Fun is entry Init(Index: Natural) when N=0 is begin N := Index; end Init; function Result return Natural is (N*N); end Fun; A: array (1 .. 10) of Fun; begin for I in A'Range loop A(I).Init(I); end loop; for I in A'First .. A'Last-1 loop Ada.Text_IO.Put(Integer'Image(A(I).Result)); end loop; end Value_Capture;
funcs = [] for i in range(10): funcs.append(lambda: i * i) print funcs[3]()
Convert this Clojure snippet to C and keep its semantics consistent.
(def funcs (map #(fn [] (* % %)) (range 11))) (printf "%d\n%d\n" ((nth funcs 3)) ((nth funcs 4)))
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/mman.h> typedef int (*f_int)(); #define TAG 0xdeadbeef int _tmpl() { volatile int x = TAG; return x * x; } #define PROT (PROT_EXEC | PROT_WRITE) #define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS) f_int dupf(int v) { size_t len = (void*)dupf - (void*)_tmpl; f_int ret = mmap(NULL, len, PROT, FLAGS, 0, 0); char *p; if(ret == MAP_FAILED) { perror("mmap"); exit(-1); } memcpy(ret, _tmpl, len); for (p = (char*)ret; p < (char*)ret + len - sizeof(int); p++) if (*(int *)p == TAG) *(int *)p = v; return ret; } int main() { f_int funcs[10]; int i; for (i = 0; i < 10; i++) funcs[i] = dupf(i); for (i = 0; i < 9; i++) printf("func[%d]: %d\n", i, funcs[i]()); return 0; }
Convert the following code from Clojure to C, ensuring the logic remains intact.
(def funcs (map #(fn [] (* % %)) (range 11))) (printf "%d\n%d\n" ((nth funcs 3)) ((nth funcs 4)))
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/mman.h> typedef int (*f_int)(); #define TAG 0xdeadbeef int _tmpl() { volatile int x = TAG; return x * x; } #define PROT (PROT_EXEC | PROT_WRITE) #define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS) f_int dupf(int v) { size_t len = (void*)dupf - (void*)_tmpl; f_int ret = mmap(NULL, len, PROT, FLAGS, 0, 0); char *p; if(ret == MAP_FAILED) { perror("mmap"); exit(-1); } memcpy(ret, _tmpl, len); for (p = (char*)ret; p < (char*)ret + len - sizeof(int); p++) if (*(int *)p == TAG) *(int *)p = v; return ret; } int main() { f_int funcs[10]; int i; for (i = 0; i < 10; i++) funcs[i] = dupf(i); for (i = 0; i < 9; i++) printf("func[%d]: %d\n", i, funcs[i]()); return 0; }
Convert the following code from Clojure to C#, ensuring the logic remains intact.
(def funcs (map #(fn [] (* % %)) (range 11))) (printf "%d\n%d\n" ((nth funcs 3)) ((nth funcs 4)))
using System; using System.Linq; class Program { static void Main() { var captor = (Func<int, Func<int>>)(number => () => number * number); var functions = Enumerable.Range(0, 10).Select(captor); foreach (var function in functions.Take(9)) { Console.WriteLine(function()); } } }
Translate this program into C# but keep the logic exactly as in Clojure.
(def funcs (map #(fn [] (* % %)) (range 11))) (printf "%d\n%d\n" ((nth funcs 3)) ((nth funcs 4)))
using System; using System.Linq; class Program { static void Main() { var captor = (Func<int, Func<int>>)(number => () => number * number); var functions = Enumerable.Range(0, 10).Select(captor); foreach (var function in functions.Take(9)) { Console.WriteLine(function()); } } }
Change the programming language of this snippet from Clojure to C++ without modifying what it does.
(def funcs (map #(fn [] (* % %)) (range 11))) (printf "%d\n%d\n" ((nth funcs 3)) ((nth funcs 4)))
#include <iostream> #include <functional> #include <vector> int main() { std::vector<std::function<int()> > funcs; for (int i = 0; i < 10; i++) funcs.push_back([=]() { return i * i; }); for ( std::function<int( )> f : funcs ) std::cout << f( ) << std::endl ; return 0; }
Translate this program into C++ but keep the logic exactly as in Clojure.
(def funcs (map #(fn [] (* % %)) (range 11))) (printf "%d\n%d\n" ((nth funcs 3)) ((nth funcs 4)))
#include <iostream> #include <functional> #include <vector> int main() { std::vector<std::function<int()> > funcs; for (int i = 0; i < 10; i++) funcs.push_back([=]() { return i * i; }); for ( std::function<int( )> f : funcs ) std::cout << f( ) << std::endl ; return 0; }
Translate the given Clojure code snippet into Java without altering its behavior.
(def funcs (map #(fn [] (* % %)) (range 11))) (printf "%d\n%d\n" ((nth funcs 3)) ((nth funcs 4)))
import java.util.function.Supplier; import java.util.ArrayList; public class ValueCapture { public static void main(String[] args) { ArrayList<Supplier<Integer>> funcs = new ArrayList<>(); for (int i = 0; i < 10; i++) { int j = i; funcs.add(() -> j * j); } Supplier<Integer> foo = funcs.get(3); System.out.println(foo.get()); } }
Change the programming language of this snippet from Clojure to Java without modifying what it does.
(def funcs (map #(fn [] (* % %)) (range 11))) (printf "%d\n%d\n" ((nth funcs 3)) ((nth funcs 4)))
import java.util.function.Supplier; import java.util.ArrayList; public class ValueCapture { public static void main(String[] args) { ArrayList<Supplier<Integer>> funcs = new ArrayList<>(); for (int i = 0; i < 10; i++) { int j = i; funcs.add(() -> j * j); } Supplier<Integer> foo = funcs.get(3); System.out.println(foo.get()); } }
Write the same algorithm in Python as shown in this Clojure implementation.
(def funcs (map #(fn [] (* % %)) (range 11))) (printf "%d\n%d\n" ((nth funcs 3)) ((nth funcs 4)))
funcs = [] for i in range(10): funcs.append(lambda: i * i) print funcs[3]()
Port the following code from Clojure to Python with equivalent syntax and logic.
(def funcs (map #(fn [] (* % %)) (range 11))) (printf "%d\n%d\n" ((nth funcs 3)) ((nth funcs 4)))
funcs = [] for i in range(10): funcs.append(lambda: i * i) print funcs[3]()
Keep all operations the same but rewrite the snippet in Go.
(def funcs (map #(fn [] (* % %)) (range 11))) (printf "%d\n%d\n" ((nth funcs 3)) ((nth funcs 4)))
package main import "fmt" func main() { fs := make([]func() int, 10) for i := range fs { i := i fs[i] = func() int { return i * i } } fmt.Println("func #0:", fs[0]()) fmt.Println("func #3:", fs[3]()) }
Convert this Clojure block to Go, preserving its control flow and logic.
(def funcs (map #(fn [] (* % %)) (range 11))) (printf "%d\n%d\n" ((nth funcs 3)) ((nth funcs 4)))
package main import "fmt" func main() { fs := make([]func() int, 10) for i := range fs { i := i fs[i] = func() int { return i * i } } fmt.Println("func #0:", fs[0]()) fmt.Println("func #3:", fs[3]()) }
Produce a language-to-language conversion: from Common_Lisp to C, same semantics.
CL-USER> (defparameter alist (loop for i from 1 to 10 collect (cons i (let ((i i)) (lambda () (* i i)))))) ALIST CL-USER> (funcall (cdr (assoc 2 alist))) 4 CL-USER> (funcall (cdr (assoc 8 alist))) 64
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/mman.h> typedef int (*f_int)(); #define TAG 0xdeadbeef int _tmpl() { volatile int x = TAG; return x * x; } #define PROT (PROT_EXEC | PROT_WRITE) #define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS) f_int dupf(int v) { size_t len = (void*)dupf - (void*)_tmpl; f_int ret = mmap(NULL, len, PROT, FLAGS, 0, 0); char *p; if(ret == MAP_FAILED) { perror("mmap"); exit(-1); } memcpy(ret, _tmpl, len); for (p = (char*)ret; p < (char*)ret + len - sizeof(int); p++) if (*(int *)p == TAG) *(int *)p = v; return ret; } int main() { f_int funcs[10]; int i; for (i = 0; i < 10; i++) funcs[i] = dupf(i); for (i = 0; i < 9; i++) printf("func[%d]: %d\n", i, funcs[i]()); return 0; }
Port the provided Common_Lisp code into C while preserving the original functionality.
CL-USER> (defparameter alist (loop for i from 1 to 10 collect (cons i (let ((i i)) (lambda () (* i i)))))) ALIST CL-USER> (funcall (cdr (assoc 2 alist))) 4 CL-USER> (funcall (cdr (assoc 8 alist))) 64
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/mman.h> typedef int (*f_int)(); #define TAG 0xdeadbeef int _tmpl() { volatile int x = TAG; return x * x; } #define PROT (PROT_EXEC | PROT_WRITE) #define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS) f_int dupf(int v) { size_t len = (void*)dupf - (void*)_tmpl; f_int ret = mmap(NULL, len, PROT, FLAGS, 0, 0); char *p; if(ret == MAP_FAILED) { perror("mmap"); exit(-1); } memcpy(ret, _tmpl, len); for (p = (char*)ret; p < (char*)ret + len - sizeof(int); p++) if (*(int *)p == TAG) *(int *)p = v; return ret; } int main() { f_int funcs[10]; int i; for (i = 0; i < 10; i++) funcs[i] = dupf(i); for (i = 0; i < 9; i++) printf("func[%d]: %d\n", i, funcs[i]()); return 0; }
Rewrite this program in C# while keeping its functionality equivalent to the Common_Lisp version.
CL-USER> (defparameter alist (loop for i from 1 to 10 collect (cons i (let ((i i)) (lambda () (* i i)))))) ALIST CL-USER> (funcall (cdr (assoc 2 alist))) 4 CL-USER> (funcall (cdr (assoc 8 alist))) 64
using System; using System.Linq; class Program { static void Main() { var captor = (Func<int, Func<int>>)(number => () => number * number); var functions = Enumerable.Range(0, 10).Select(captor); foreach (var function in functions.Take(9)) { Console.WriteLine(function()); } } }
Translate this program into C# but keep the logic exactly as in Common_Lisp.
CL-USER> (defparameter alist (loop for i from 1 to 10 collect (cons i (let ((i i)) (lambda () (* i i)))))) ALIST CL-USER> (funcall (cdr (assoc 2 alist))) 4 CL-USER> (funcall (cdr (assoc 8 alist))) 64
using System; using System.Linq; class Program { static void Main() { var captor = (Func<int, Func<int>>)(number => () => number * number); var functions = Enumerable.Range(0, 10).Select(captor); foreach (var function in functions.Take(9)) { Console.WriteLine(function()); } } }
Convert this Common_Lisp block to C++, preserving its control flow and logic.
CL-USER> (defparameter alist (loop for i from 1 to 10 collect (cons i (let ((i i)) (lambda () (* i i)))))) ALIST CL-USER> (funcall (cdr (assoc 2 alist))) 4 CL-USER> (funcall (cdr (assoc 8 alist))) 64
#include <iostream> #include <functional> #include <vector> int main() { std::vector<std::function<int()> > funcs; for (int i = 0; i < 10; i++) funcs.push_back([=]() { return i * i; }); for ( std::function<int( )> f : funcs ) std::cout << f( ) << std::endl ; return 0; }
Can you help me rewrite this code in C++ instead of Common_Lisp, keeping it the same logically?
CL-USER> (defparameter alist (loop for i from 1 to 10 collect (cons i (let ((i i)) (lambda () (* i i)))))) ALIST CL-USER> (funcall (cdr (assoc 2 alist))) 4 CL-USER> (funcall (cdr (assoc 8 alist))) 64
#include <iostream> #include <functional> #include <vector> int main() { std::vector<std::function<int()> > funcs; for (int i = 0; i < 10; i++) funcs.push_back([=]() { return i * i; }); for ( std::function<int( )> f : funcs ) std::cout << f( ) << std::endl ; return 0; }
Write the same algorithm in Java as shown in this Common_Lisp implementation.
CL-USER> (defparameter alist (loop for i from 1 to 10 collect (cons i (let ((i i)) (lambda () (* i i)))))) ALIST CL-USER> (funcall (cdr (assoc 2 alist))) 4 CL-USER> (funcall (cdr (assoc 8 alist))) 64
import java.util.function.Supplier; import java.util.ArrayList; public class ValueCapture { public static void main(String[] args) { ArrayList<Supplier<Integer>> funcs = new ArrayList<>(); for (int i = 0; i < 10; i++) { int j = i; funcs.add(() -> j * j); } Supplier<Integer> foo = funcs.get(3); System.out.println(foo.get()); } }
Translate the given Common_Lisp code snippet into Java without altering its behavior.
CL-USER> (defparameter alist (loop for i from 1 to 10 collect (cons i (let ((i i)) (lambda () (* i i)))))) ALIST CL-USER> (funcall (cdr (assoc 2 alist))) 4 CL-USER> (funcall (cdr (assoc 8 alist))) 64
import java.util.function.Supplier; import java.util.ArrayList; public class ValueCapture { public static void main(String[] args) { ArrayList<Supplier<Integer>> funcs = new ArrayList<>(); for (int i = 0; i < 10; i++) { int j = i; funcs.add(() -> j * j); } Supplier<Integer> foo = funcs.get(3); System.out.println(foo.get()); } }
Convert the following code from Common_Lisp to Python, ensuring the logic remains intact.
CL-USER> (defparameter alist (loop for i from 1 to 10 collect (cons i (let ((i i)) (lambda () (* i i)))))) ALIST CL-USER> (funcall (cdr (assoc 2 alist))) 4 CL-USER> (funcall (cdr (assoc 8 alist))) 64
funcs = [] for i in range(10): funcs.append(lambda: i * i) print funcs[3]()
Translate the given Common_Lisp code snippet into Python without altering its behavior.
CL-USER> (defparameter alist (loop for i from 1 to 10 collect (cons i (let ((i i)) (lambda () (* i i)))))) ALIST CL-USER> (funcall (cdr (assoc 2 alist))) 4 CL-USER> (funcall (cdr (assoc 8 alist))) 64
funcs = [] for i in range(10): funcs.append(lambda: i * i) print funcs[3]()
Change the programming language of this snippet from Common_Lisp to Go without modifying what it does.
CL-USER> (defparameter alist (loop for i from 1 to 10 collect (cons i (let ((i i)) (lambda () (* i i)))))) ALIST CL-USER> (funcall (cdr (assoc 2 alist))) 4 CL-USER> (funcall (cdr (assoc 8 alist))) 64
package main import "fmt" func main() { fs := make([]func() int, 10) for i := range fs { i := i fs[i] = func() int { return i * i } } fmt.Println("func #0:", fs[0]()) fmt.Println("func #3:", fs[3]()) }
Change the programming language of this snippet from Common_Lisp to Go without modifying what it does.
CL-USER> (defparameter alist (loop for i from 1 to 10 collect (cons i (let ((i i)) (lambda () (* i i)))))) ALIST CL-USER> (funcall (cdr (assoc 2 alist))) 4 CL-USER> (funcall (cdr (assoc 8 alist))) 64
package main import "fmt" func main() { fs := make([]func() int, 10) for i := range fs { i := i fs[i] = func() int { return i * i } } fmt.Println("func #0:", fs[0]()) fmt.Println("func #3:", fs[3]()) }
Convert the following code from D to C, ensuring the logic remains intact.
import std.stdio; void main() { int delegate()[] funcs; foreach (i; 0 .. 10) funcs ~= (i => () => i ^^ 2)(i); writeln(funcs[3]()); }
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/mman.h> typedef int (*f_int)(); #define TAG 0xdeadbeef int _tmpl() { volatile int x = TAG; return x * x; } #define PROT (PROT_EXEC | PROT_WRITE) #define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS) f_int dupf(int v) { size_t len = (void*)dupf - (void*)_tmpl; f_int ret = mmap(NULL, len, PROT, FLAGS, 0, 0); char *p; if(ret == MAP_FAILED) { perror("mmap"); exit(-1); } memcpy(ret, _tmpl, len); for (p = (char*)ret; p < (char*)ret + len - sizeof(int); p++) if (*(int *)p == TAG) *(int *)p = v; return ret; } int main() { f_int funcs[10]; int i; for (i = 0; i < 10; i++) funcs[i] = dupf(i); for (i = 0; i < 9; i++) printf("func[%d]: %d\n", i, funcs[i]()); return 0; }
Change the programming language of this snippet from D to C without modifying what it does.
import std.stdio; void main() { int delegate()[] funcs; foreach (i; 0 .. 10) funcs ~= (i => () => i ^^ 2)(i); writeln(funcs[3]()); }
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/mman.h> typedef int (*f_int)(); #define TAG 0xdeadbeef int _tmpl() { volatile int x = TAG; return x * x; } #define PROT (PROT_EXEC | PROT_WRITE) #define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS) f_int dupf(int v) { size_t len = (void*)dupf - (void*)_tmpl; f_int ret = mmap(NULL, len, PROT, FLAGS, 0, 0); char *p; if(ret == MAP_FAILED) { perror("mmap"); exit(-1); } memcpy(ret, _tmpl, len); for (p = (char*)ret; p < (char*)ret + len - sizeof(int); p++) if (*(int *)p == TAG) *(int *)p = v; return ret; } int main() { f_int funcs[10]; int i; for (i = 0; i < 10; i++) funcs[i] = dupf(i); for (i = 0; i < 9; i++) printf("func[%d]: %d\n", i, funcs[i]()); return 0; }
Port the provided D code into C# while preserving the original functionality.
import std.stdio; void main() { int delegate()[] funcs; foreach (i; 0 .. 10) funcs ~= (i => () => i ^^ 2)(i); writeln(funcs[3]()); }
using System; using System.Linq; class Program { static void Main() { var captor = (Func<int, Func<int>>)(number => () => number * number); var functions = Enumerable.Range(0, 10).Select(captor); foreach (var function in functions.Take(9)) { Console.WriteLine(function()); } } }
Convert the following code from D to C#, ensuring the logic remains intact.
import std.stdio; void main() { int delegate()[] funcs; foreach (i; 0 .. 10) funcs ~= (i => () => i ^^ 2)(i); writeln(funcs[3]()); }
using System; using System.Linq; class Program { static void Main() { var captor = (Func<int, Func<int>>)(number => () => number * number); var functions = Enumerable.Range(0, 10).Select(captor); foreach (var function in functions.Take(9)) { Console.WriteLine(function()); } } }
Write the same algorithm in C++ as shown in this D implementation.
import std.stdio; void main() { int delegate()[] funcs; foreach (i; 0 .. 10) funcs ~= (i => () => i ^^ 2)(i); writeln(funcs[3]()); }
#include <iostream> #include <functional> #include <vector> int main() { std::vector<std::function<int()> > funcs; for (int i = 0; i < 10; i++) funcs.push_back([=]() { return i * i; }); for ( std::function<int( )> f : funcs ) std::cout << f( ) << std::endl ; return 0; }
Convert this D snippet to C++ and keep its semantics consistent.
import std.stdio; void main() { int delegate()[] funcs; foreach (i; 0 .. 10) funcs ~= (i => () => i ^^ 2)(i); writeln(funcs[3]()); }
#include <iostream> #include <functional> #include <vector> int main() { std::vector<std::function<int()> > funcs; for (int i = 0; i < 10; i++) funcs.push_back([=]() { return i * i; }); for ( std::function<int( )> f : funcs ) std::cout << f( ) << std::endl ; return 0; }
Ensure the translated Java code behaves exactly like the original D snippet.
import std.stdio; void main() { int delegate()[] funcs; foreach (i; 0 .. 10) funcs ~= (i => () => i ^^ 2)(i); writeln(funcs[3]()); }
import java.util.function.Supplier; import java.util.ArrayList; public class ValueCapture { public static void main(String[] args) { ArrayList<Supplier<Integer>> funcs = new ArrayList<>(); for (int i = 0; i < 10; i++) { int j = i; funcs.add(() -> j * j); } Supplier<Integer> foo = funcs.get(3); System.out.println(foo.get()); } }
Convert this D block to Java, preserving its control flow and logic.
import std.stdio; void main() { int delegate()[] funcs; foreach (i; 0 .. 10) funcs ~= (i => () => i ^^ 2)(i); writeln(funcs[3]()); }
import java.util.function.Supplier; import java.util.ArrayList; public class ValueCapture { public static void main(String[] args) { ArrayList<Supplier<Integer>> funcs = new ArrayList<>(); for (int i = 0; i < 10; i++) { int j = i; funcs.add(() -> j * j); } Supplier<Integer> foo = funcs.get(3); System.out.println(foo.get()); } }
Produce a language-to-language conversion: from D to Python, same semantics.
import std.stdio; void main() { int delegate()[] funcs; foreach (i; 0 .. 10) funcs ~= (i => () => i ^^ 2)(i); writeln(funcs[3]()); }
funcs = [] for i in range(10): funcs.append(lambda: i * i) print funcs[3]()
Rewrite the snippet below in Python so it works the same as the original D code.
import std.stdio; void main() { int delegate()[] funcs; foreach (i; 0 .. 10) funcs ~= (i => () => i ^^ 2)(i); writeln(funcs[3]()); }
funcs = [] for i in range(10): funcs.append(lambda: i * i) print funcs[3]()
Transform the following D implementation into Go, maintaining the same output and logic.
import std.stdio; void main() { int delegate()[] funcs; foreach (i; 0 .. 10) funcs ~= (i => () => i ^^ 2)(i); writeln(funcs[3]()); }
package main import "fmt" func main() { fs := make([]func() int, 10) for i := range fs { i := i fs[i] = func() int { return i * i } } fmt.Println("func #0:", fs[0]()) fmt.Println("func #3:", fs[3]()) }
Produce a functionally identical Go code for the snippet given in D.
import std.stdio; void main() { int delegate()[] funcs; foreach (i; 0 .. 10) funcs ~= (i => () => i ^^ 2)(i); writeln(funcs[3]()); }
package main import "fmt" func main() { fs := make([]func() int, 10) for i := range fs { i := i fs[i] = func() int { return i * i } } fmt.Println("func #0:", fs[0]()) fmt.Println("func #3:", fs[3]()) }
Translate the given Delphi code snippet into C without altering its behavior.
program Project1; type TFuncIntResult = reference to function: Integer; function CreateFunc(i: Integer): TFuncIntResult; begin Result := function: Integer begin Result := i * i; end; end; var Funcs: array[0..9] of TFuncIntResult; i: integer; begin for i := Low(Funcs) to High(Funcs) do Funcs[i] := CreateFunc(i); for i := Low(Funcs) to High(Funcs) do Writeln(Funcs[i]()); end.
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/mman.h> typedef int (*f_int)(); #define TAG 0xdeadbeef int _tmpl() { volatile int x = TAG; return x * x; } #define PROT (PROT_EXEC | PROT_WRITE) #define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS) f_int dupf(int v) { size_t len = (void*)dupf - (void*)_tmpl; f_int ret = mmap(NULL, len, PROT, FLAGS, 0, 0); char *p; if(ret == MAP_FAILED) { perror("mmap"); exit(-1); } memcpy(ret, _tmpl, len); for (p = (char*)ret; p < (char*)ret + len - sizeof(int); p++) if (*(int *)p == TAG) *(int *)p = v; return ret; } int main() { f_int funcs[10]; int i; for (i = 0; i < 10; i++) funcs[i] = dupf(i); for (i = 0; i < 9; i++) printf("func[%d]: %d\n", i, funcs[i]()); return 0; }