Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Ensure the translated BBC_Basic code behaves exactly like the original Go snippet.
package main import ( "bufio" "errors" "fmt" "io" "os" ) func main() { if line, err := rsl("input.txt", 7); err == nil { fmt.Println("7th line:") fmt.Println(line) } else { fmt.Println("rsl:", err) } } func rsl(fn string, n int) (string, error) { if n < 1 { return "", fmt.Errorf("invalid request: li...
filepath$ = @lib$ + "..\licence.txt" requiredline% = 7 file% = OPENIN(filepath$) IF file%=0 ERROR 100, "File could not be opened" FOR i% = 1 TO requiredline% IF EOF#file% ERROR 100, "File contains too few lines" INPUT #file%, text$ NEXT CLOSE #file% ...
Transform the following Go implementation into BBC_Basic, maintaining the same output and logic.
package main import ( "bufio" "errors" "fmt" "io" "os" ) func main() { if line, err := rsl("input.txt", 7); err == nil { fmt.Println("7th line:") fmt.Println(line) } else { fmt.Println("rsl:", err) } } func rsl(fn string, n int) (string, error) { if n < 1 { return "", fmt.Errorf("invalid request: li...
filepath$ = @lib$ + "..\licence.txt" requiredline% = 7 file% = OPENIN(filepath$) IF file%=0 ERROR 100, "File could not be opened" FOR i% = 1 TO requiredline% IF EOF#file% ERROR 100, "File contains too few lines" INPUT #file%, text$ NEXT CLOSE #file% ...
Write a version of this Go function in BBC_Basic with identical behavior.
package main import ( "fmt" "net/url" ) func main() { fmt.Println(url.QueryEscape("http: }
PRINT FNurlencode("http://foo bar/") END DEF FNurlencode(url$) LOCAL c%, i% WHILE i% < LEN(url$) i% += 1 c% = ASCMID$(url$, i%) IF c%<&30 OR c%>&7A OR c%>&39 AND c%<&41 OR c%>&5A AND c%<&61 THEN url$ = LEFT$(url$,i%-1) + "%" + RIGHT$("0"+STR$~c%,2) ...
Convert this Go snippet to BBC_Basic and keep its semantics consistent.
package main import ( "fmt" "net/url" ) func main() { fmt.Println(url.QueryEscape("http: }
PRINT FNurlencode("http://foo bar/") END DEF FNurlencode(url$) LOCAL c%, i% WHILE i% < LEN(url$) i% += 1 c% = ASCMID$(url$, i%) IF c%<&30 OR c%>&7A OR c%>&39 AND c%<&41 OR c%>&5A AND c%<&61 THEN url$ = LEFT$(url$,i%-1) + "%" + RIGHT$("0"+STR$~c%,2) ...
Port the following code from Go to BBC_Basic with equivalent syntax and logic.
package main import "fmt" type matrix [][]float64 func zero(n int) matrix { r := make([][]float64, n) a := make([]float64, n*n) for i := range r { r[i] = a[n*i : n*(i+1)] } return r } func eye(n int) matrix { r := zero(n) for i := range r { r[i][i] = 1 } ...
DIM A1(2,2) A1() = 1, 3, 5, 2, 4, 7, 1, 1, 0 PROCLUdecomposition(A1(), L1(), U1(), P1()) PRINT "L1:" ' FNshowmatrix(L1()) PRINT "U1:" ' FNshowmatrix(U1()) PRINT "P1:" ' FNshowmatrix(P1()) DIM A2(3,3) A2() = 11, 9, 24, 2, 1, 5, 2, 6, 3, 17, 18, 1, 2, 5, 7, 1 P...
Please provide an equivalent version of this Go code in BBC_Basic.
type cell string type spec struct { less func(cell, cell) bool column int reverse bool } func newSpec() (s spec) { return } t.sort(newSpec()) s := newSpec s.reverse = true t.sort(s)
DIM table$(100,100) PROCsort_default(table$()) PROCsort_options(table$(), TRUE, 1, FALSE) END DEF PROCsort_options(table$(), ordering%, column%, reverse%) DEF PROCsort_default(table$()) : LOCAL ordering%, column%, reverse% ENDPROC
Change the following Go code into BBC_Basic without altering its purpose.
package main import ( "fmt" "math/rand" "time" ) type rateStateS struct { lastFlush time.Time period time.Duration tickCount int } func ticRate(pRate *rateStateS) { pRate.tickCount++ now := time.Now() if now.Sub(pRate.lastFlush) >= pRate.period { tps := 0. ...
PRINT "Method 1: Calculate reciprocal of elapsed time:" FOR trial% = 1 TO 3 start% = TIME PROCtasktomeasure finish% = TIME PRINT "Rate = "; 100 / (finish%-start%) " per second" NEXT trial% PRINT '"Method 2: Count completed tasks in one second:" FOR tr...
Rewrite this program in BBC_Basic while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "time" ) func main() { var bpm = 72.0 var bpb = 4 d := time.Duration(float64(time.Minute) / bpm) fmt.Println("Delay:", d) t := time.NewTicker(d) i := 1 for _ = range t.C { i-- if i == 0 { i = bpb fmt.Printf("\nTICK ") } else { fmt.Printf("tick ") } } }
BeatPattern$ = "HLLL" Tempo% = 100 *font Arial,36 REPEAT FOR beat% = 1 TO LEN(BeatPattern$) IF MID$(BeatPattern$, beat%, 1) = "H" THEN SOUND 1,-15,148,1 ELSE SOUND 1,-15,100,1 ENDIF VDU 30 COLOUR 2 ...
Generate a BBC_Basic translation of this Go snippet without changing its computational steps.
package main import ( "github.com/fogleman/gg" "log" "os/exec" "runtime" ) var palette = [2]string{ "FFFFFF", "000000", } func pinstripe(dc *gg.Context) { w := dc.Width() h := dc.Height() / 7 for b := 1; b <= 11; b++ { for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 { ...
PD_RETURNDC = 256 _LOGPIXELSY = 90 DIM pd{lStructSize%, hwndOwner%, hDevMode%, hDevNames%, \ \ hdc%, flags%, nFromPage{l&,h&}, nToPage{l&,h&}, \ \ nMinPage{l&,h&}, nMaxPage{l&,h&}, nCopies{l&,h&}, \ \ hInstance%, lCustData%, lpfnPrintHook%, lpfnSetupHook%, \ ...
Write the same code in BBC_Basic as shown below in Go.
package main import ( "fmt" "sync" "time" ) var value int var m sync.Mutex var wg sync.WaitGroup func slowInc() { m.Lock() v := value time.Sleep(1e8) value = v+1 m.Unlock() wg.Done() } func main() { wg.Add(2) go slowInc() go slowInc() wg.Wait() fmt.Println(val...
SYS "CreateMutex", 0, 0, 0 TO hMutex% REPEAT SYS "WaitForSingleObject", hMutex%, 1 TO res% UNTIL res% = 0 SYS "ReleaseMutex", hMutex% SYS "CloseHandle", hMutex%
Produce a functionally identical BBC_Basic code for the snippet given in Go.
package main import ( "fmt" "strconv" ) func main() { var maxLen int var seqMaxLen [][]string for n := 1; n < 1e6; n++ { switch s := seq(n); { case len(s) == maxLen: seqMaxLen = append(seqMaxLen, s) case len(s) > maxLen: maxLen = len(s) s...
*FLOAT64 DIM list$(30) maxiter% = 0 maxseed% = 0 FOR seed% = 0 TO 999999 list$(0) = STR$(seed%) iter% = 0 REPEAT list$(iter%+1) = FNseq(list$(iter%)) IF VALlist$(iter%+1) <= VALlist$(iter%) THEN FOR try% = iter% TO 0 STEP -1 ...
Ensure the translated BBC_Basic code behaves exactly like the original Go snippet.
package main import ( "fmt" "strconv" "strings" ) func sdn(n int64) bool { if n >= 1e10 { return false } s := strconv.FormatInt(n, 10) for d, p := range s { if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) { return false } } return true } fu...
FOR N = 1 TO 5E7 IF FNselfdescribing(N) PRINT N NEXT END DEF FNselfdescribing(N%) LOCAL D%(), I%, L%, O% DIM D%(9) O% = N% L% = LOG(N%) WHILE N% I% = N% MOD 10 D%(I%) += 10^(L%-I%) N% DIV=10 ENDWHILE = O% = SUM(D%()...
Transform the following Go implementation into BBC_Basic, maintaining the same output and logic.
package main import ( "fmt" "unsafe" ) func main() { myVar := 3.14 myPointer := &myVar fmt.Println("Address:", myPointer, &myVar) fmt.Printf("Address: %p %p\n", myPointer, &myVar) var addr64 int64 var addr32 int32 ptr := unsafe.Pointer(myPointer) if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) { addr64 = ...
y% = ^x% x% = !y%
Transform the following Go implementation into BBC_Basic, maintaining the same output and logic.
package main import ( "bufio" "fmt" "log" "math/rand" "os" "os/exec" "strconv" "strings" "text/template" "time" "unicode" "golang.org/x/crypto/ssh/terminal" ) const maxPoints = 2048 const ( fieldSizeX = 4 fieldSizeY = 4 ) const tilesAtStart = 2 const probFor2 = 0.9 type button int const ( _ button =...
SIZE = 4 : MAX = SIZE-1 Won% = FALSE : Lost% = FALSE @% = 5 DIM Board(MAX,MAX),Stuck% 3 PROCBreed PROCPrint REPEAT Direction = GET-135 IF Direction > 0 AND Direction < 5 THEN Moved% = FALSE PROCShift PROCMerge PROCShi...
Write the same algorithm in BBC_Basic as shown in this Go implementation.
package main import ( "bytes" "fmt" "math/rand" "time" ) type maze struct { c2 [][]byte h2 [][]byte v2 [][]byte } func newMaze(rows, cols int) *maze { c := make([]byte, rows*cols) h := bytes.Repeat([]byte{'-'}, rows*cols) v := bytes.Repeat([]byte{'|'}, rows...
MazeWidth% = 11 MazeHeight% = 9 MazeCell% = 50 VDU 23,22,MazeWidth%*MazeCell%/2+3;MazeHeight%*MazeCell%/2+3;8,16,16,128 VDU 23,23,3;0;0;0; : OFF PROCgeneratemaze(Maze&(), MazeWidth%, MazeHeight%, MazeCell%) PROCsolvemaze(Path{()}, Maze&(), 0, MazeHeight%-1, MazeWi...
Port the provided Go code into BBC_Basic while preserving the original functionality.
package main import "fmt" func main() { for { fmt.Printf("SPAM\n") } }
REPEAT PRINT "SPAM" UNTIL FALSE
Rewrite the snippet below in BBC_Basic so it works the same as the original Go code.
package main import ( "fmt" "math" "bytes" "encoding/binary" ) type testCase struct { hashCode string string } var testCases = []testCase{ {"d41d8cd98f00b204e9800998ecf8427e", ""}, {"0cc175b9c0f1b6a831c399e269772661", "a"}, {"900150983cd24fb0d6963f7d28e17f72", "abc"}, {"f96b69...
PRINT FN_MD5("") PRINT FN_MD5("a") PRINT FN_MD5("abc") PRINT FN_MD5("message digest") PRINT FN_MD5("abcdefghijklmnopqrstuvwxyz") PRINT FN_MD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") PRINT FN_MD5(STRING$(8,"1234567890")) END DEF FN_MD...
Translate this program into BBC_Basic but keep the logic exactly as in Go.
package main import ( "github.com/fogleman/gg" "log" "os/exec" "runtime" ) var palette = [8]string{ "000000", "FF0000", "00FF00", "0000FF", "FF00FF", "00FFFF", "FFFF00", "FFFFFF", } func pinstripe(dc *gg.Context) { w := dc.Width() h := dc.Height() / 7...
PD_RETURNDC = 256 _LOGPIXELSY = 90 DIM pd{lStructSize%, hwndOwner%, hDevMode%, hDevNames%, \ \ hdc%, flags%, nFromPage{l&,h&}, nToPage{l&,h&}, \ \ nMinPage{l&,h&}, nMaxPage{l&,h&}, nCopies{l&,h&}, \ \ hInstance%, lCustData%, lpfnPrintHook%, lpfnSetupHook%, \ ...
Generate a BBC_Basic translation of this Go snippet without changing its computational steps.
func multiply(a, b float64) float64 { return a * b }
PRINT FNmultiply(6,7) END DEF FNmultiply(a,b) = a * b
Convert the following code from Go to BBC_Basic, ensuring the logic remains intact.
package main import ( "fmt" "os" "golang.org/x/crypto/ssh/terminal" ) func main() { w, h, err := terminal.GetSize(int(os.Stdout.Fd())) if err != nil { fmt.Println(err) return } fmt.Println(h, w) }
dx% = @vdu.tr%-@vdu.tl% : dy% = @vdu.tb%-@vdu.tt% :
Port the following code from Go to BBC_Basic with equivalent syntax and logic.
package main import "C" import "fmt" import "unsafe" func main() { d := C.XOpenDisplay(nil) f7, f6 := C.CString("F7"), C.CString("F6") defer C.free(unsafe.Pointer(f7)) defer C.free(unsafe.Pointer(f6)) if d != nil { C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))), ...
*KEY 1 |!|A *KEY 2 |!|B REPEAT key% = INKEY(1) CASE key% OF WHEN &81: PROCmethod1 WHEN &82: PROCmethod2 ENDCASE UNTIL FALSE END DEF PROCmethod1 PRINT "You pressed F1" ENDPROC DEF PROCmethod2 PRINT "You ...
Generate an equivalent BBC_Basic version of this Go code.
package main import "fmt" func main() { bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++ ++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>> >+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++. <+++++++.--------.<<<<<+.<+++.---.`) } func bf(dLen int, is string) { ds := make([]byt...
bf$ = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>->+>>+[<]<-]>>.>" + \ \ ">---.+++++++..+++.>.<<-.>.+++.------.--------.>+.>++.+++." PROCbrainfuck(bf$) END DEF PROCbrainfuck(b$) LOCAL B%, K%, M%, P% DIM M% LOCAL 65535 B% = 1 : K% = 0 : P% = 0 : ...
Change the following Go code into BBC_Basic without altering its purpose.
package main import "fmt" func main() { bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++ ++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>> >+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++. <+++++++.--------.<<<<<+.<+++.---.`) } func bf(dLen int, is string) { ds := make([]byt...
bf$ = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>->+>>+[<]<-]>>.>" + \ \ ">---.+++++++..+++.>.<<-.>.+++.------.--------.>+.>++.+++." PROCbrainfuck(bf$) END DEF PROCbrainfuck(b$) LOCAL B%, K%, M%, P% DIM M% LOCAL 65535 B% = 1 : K% = 0 : P% = 0 : ...
Rewrite the snippet below in BBC_Basic so it works the same as the original Go code.
package cards import ( "math/rand" ) type Suit uint8 const ( Spade Suit = 3 Heart Suit = 2 Diamond Suit = 1 Club Suit = 0 ) func (s Suit) String() string { const suites = "CDHS" return suites[s : s+1] } type Rank uint8 const ( Ace Rank = 1 Two Rank = 2 Three Rank = 3 Four Rank = 4 Fiv...
DIM Deck{ncards%, card&(51)}, Suit$(3), Rank$(12) Suit$() = "Clubs", "Diamonds", "Hearts", "Spades" Rank$() = "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", \ \ "Eight", "Nine", "Ten", "Jack", "Queen", "King" PRINT "Creating a new deck..." PROCnewdeck(deck1{}) ...
Write the same algorithm in BBC_Basic as shown in this Go implementation.
package main import ( "fmt" "os" "strings" ) func main() { lang := strings.ToUpper(os.Getenv("LANG")) if strings.Contains(lang, "UTF") { fmt.Printf("This terminal supports unicode and U+25b3 is : %c\n", '\u25b3') } else { fmt.Println("This terminal does not support unicode") ...
VDU 23,22,640;512;8,16,16,128+8 : *FONT Arial Unicode MS,36 PRINT CHR$(&E2)+CHR$(&96)+CHR$(&B3)
Write a version of this Go function in BBC_Basic with identical behavior.
package main import ( "fmt" "os" "strings" ) func main() { lang := strings.ToUpper(os.Getenv("LANG")) if strings.Contains(lang, "UTF") { fmt.Printf("This terminal supports unicode and U+25b3 is : %c\n", '\u25b3') } else { fmt.Println("This terminal does not support unicode") ...
VDU 23,22,640;512;8,16,16,128+8 : *FONT Arial Unicode MS,36 PRINT CHR$(&E2)+CHR$(&96)+CHR$(&B3)
Port the provided Go code into BBC_Basic while preserving the original functionality.
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) if len(a) > 1 && !recurse(len(a) - 1) { panic("sorted permutation not found!") } fmt.Println("after: ", a) } func recurse(last int) bool { ...
DIM test(9) test() = 4, 65, 2, 31, 0, 99, 2, 83, 782, 1 perms% = 0 WHILE NOT FNsorted(test()) perms% += 1 PROCnextperm(test()) ENDWHILE PRINT ;perms% " permutations required to sort "; DIM(test(),1)+1 " items." END DEF PROCnextperm(a()) ...
Write the same code in BBC_Basic as shown below in Go.
package main import ( "fmt" "go/ast" "go/parser" "go/token" "io/ioutil" "os" "sort" ) func main() { if len(os.Args) != 2 { fmt.Println("usage ff <go source filename>") return } src, err := ioutil.ReadFile(os.Args[1]) if err != nil { fmt.Println(err) ...
INSTALL @lib$+"SORTLIB" Sort% = FN_sortinit(1,0) : Valid$ = "0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_`abcdefghijklmnopqrstuvwxyz" DIM func$(1000), cnt%(1000) nFunc% = 0 file% = OPENIN("*.bbc") WHILE NOT EOF#file% ll% = BGET#file% no% = BGET#file% + ...
Change the following Go code into BBC_Basic without altering its purpose.
package main import ( "fmt" "time" ) func main() { var year int var t time.Time var lastDay = [12]int { 31,29,31,30,31,30,31,31,30,31,30,31 } for { fmt.Print("Please select a year: ") _, err := fmt.Scanf("%d", &year) if err != nil { fmt.Println(err) continue } else { break } } fmt.Prin...
INSTALL @lib$+"DATELIB" INPUT "What year to calculate (YYYY)? " Year% PRINT '"Last Sundays in ";Year%;" are on:" FOR Month%=1 TO 12 PRINT Year% "-" RIGHT$("0"+STR$Month%,2) "-";FN_dim(Month%,Year%)-FN_dow(FN_mjd(FN_dim(Month%,Year%),Month%,Year%)) NEXT END
Produce a language-to-language conversion: from Go to BBC_Basic, same semantics.
package main import ( "fmt" "time" ) func main() { var year int var t time.Time var lastDay = [12]int { 31,29,31,30,31,30,31,31,30,31,30,31 } for { fmt.Print("Please select a year: ") _, err := fmt.Scanf("%d", &year) if err != nil { fmt.Println(err) continue } else { break } } fmt.Prin...
INSTALL @lib$+"DATELIB" INPUT "What year to calculate (YYYY)? " Year% PRINT '"Last Sundays in ";Year%;" are on:" FOR Month%=1 TO 12 PRINT Year% "-" RIGHT$("0"+STR$Month%,2) "-";FN_dim(Month%,Year%)-FN_dow(FN_mjd(FN_dim(Month%,Year%),Month%,Year%)) NEXT END
Produce a functionally identical BBC_Basic code for the snippet given in Go.
var i int var u rune for i, u = range "voilà" { fmt.Println(i, u) }
VDU 23,22,640;512;8,16,16,128+8 : *FONT Times New Roman, 20 PRINT "Arabic:" arabic1$ = "هنا مثال يمكنك من الكتابة من اليمين" arabic2$ = "الى اليسار باللغة العربية" VDU 23,16,2;0;0;0;13 : PRINT FNarabic(arabic1$) ' FNarabic(arabic2$) VDU 23,16,0;0;0;...
Keep all operations the same but rewrite the snippet in BBC_Basic.
package permute func Iter(p []int) func() int { f := pf(len(p)) return func() int { return f(p) } } func pf(n int) func([]int) int { sign := 1 switch n { case 0, 1: return func([]int) (s int) { s = sign sign = 0 return } defa...
PROCperms(3) PRINT PROCperms(4) END DEF PROCperms(n%) LOCAL p%(), i%, k%, s% DIM p%(n%) FOR i% = 1 TO n% p%(i%) = -i% NEXT s% = 1 REPEAT PRINT "Perm: [ "; FOR i% = 1 TO n% PRINT ;ABSp%(i%) " "; NEXT ...
Write the same code in BBC_Basic as shown below in Go.
package main import ( "bitbucket.org/binet/go-eval/pkg/eval" "fmt" "go/parser" "go/token" ) func main() { squareExpr := "x*x" fset := token.NewFileSet() squareAst, err := parser.ParseExpr(squareExpr) if err != nil { fmt.Println(err) return } w :=...
expression$ = "x^2 - 7" one = FN_eval_with_x(expression$, 1.2) two = FN_eval_with_x(expression$, 3.4) PRINT two - one END DEF FN_eval_with_x(expr$, x) = EVAL(expr$)
Rewrite the snippet below in BBC_Basic so it works the same as the original Go code.
package main import ( "bitbucket.org/binet/go-eval/pkg/eval" "fmt" "go/parser" "go/token" ) func main() { squareExpr := "x*x" fset := token.NewFileSet() squareAst, err := parser.ParseExpr(squareExpr) if err != nil { fmt.Println(err) return } w :=...
expression$ = "x^2 - 7" one = FN_eval_with_x(expression$, 1.2) two = FN_eval_with_x(expression$, 3.4) PRINT two - one END DEF FN_eval_with_x(expr$, x) = EVAL(expr$)
Produce a language-to-language conversion: from Go to BBC_Basic, same semantics.
package main import ( "fmt" "bitbucket.org/binet/go-eval/pkg/eval" "go/token" ) func main() { w := eval.NewWorld(); fset := token.NewFileSet(); code, err := w.Compile(fset, "1 + 2") if err != nil { fmt.Println("Compile error"); return } val, err := code.Run(); if err != nil { fmt.Println("Run time er...
expr$ = "PI^2 + 1" PRINT EVAL(expr$)
Maintain the same structure and functionality when rewriting this code in BBC_Basic.
package main import ( "fmt" "bitbucket.org/binet/go-eval/pkg/eval" "go/token" ) func main() { w := eval.NewWorld(); fset := token.NewFileSet(); code, err := w.Compile(fset, "1 + 2") if err != nil { fmt.Println("Compile error"); return } val, err := code.Run(); if err != nil { fmt.Println("Run time er...
expr$ = "PI^2 + 1" PRINT EVAL(expr$)
Write the same code in BBC_Basic as shown below in Go.
package main import ( "github.com/gotk3/gotk3/gtk" "log" "time" ) func check(err error, msg string) { if err != nil { log.Fatal(msg, err) } } func main() { gtk.Init(nil) window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL) check(err, "Unable to create window:") window.SetRes...
SWP_NOMOVE = 2 SWP_NOZORDER = 4 SW_MAXIMIZE = 3 SW_MINIMIZE = 6 SW_RESTORE = 9 SW_HIDE = 0 SW_SHOW = 5 myWindowHandle% = @hwnd% PRINT "Hiding the window in two seconds..." WAIT 200 SYS "ShowWindow", myWindowHandle%, SW_HIDE WAI...
Generate a BBC_Basic translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math/rand" "time" ) const boxW = 41 const boxH = 37 const pinsBaseW = 19 const nMaxBalls = 55 const centerH = pinsBaseW + (boxW-pinsBaseW*2+1)/2 - 1 const ( empty = ' ' ball = 'o' wall = '|' corner = '+' floor = '-' pin = '.' ) ...
maxBalls% = 10 DIM ballX%(maxBalls%), ballY%(maxBalls%) VDU 23,22,180;400;8,16,16,128 ORIGIN 180,0 OFF GCOL 9 FOR row% = 1 TO 7 FOR col% = 1 TO row% CIRCLE FILL 40*col% - 20*row% - 20, 800 - 40*row%, 12 NEXT NEXT row% ...
Translate the given Go code snippet into BBC_Basic without altering its behavior.
package main import ( "fmt" "github.com/go-vgo/robotgo" ) func main() { x, y := robotgo.GetMousePos() color := robotgo.GetPixelColor(x, y) fmt.Printf("Color of pixel at (%d, %d) is 0x%s\n", x, y, color) }
palette_index% = POINT(x%, y%) RGB24b_colour% = TINT(x%, y%)
Keep all operations the same but rewrite the snippet in BBC_Basic.
package main import ( "bufio" "fmt" "log" "os" "os/exec" "strconv" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { scanner := bufio.NewScanner(os.Stdin) name := "" for name == "" { fmt.Print("Enter output file name (without extens...
wavfile$ = @dir$ + "capture.wav" bitspersample% = 16 channels% = 2 samplespersec% = 44100 alignment% = bitspersample% * channels% / 8 bytespersec% = alignment% * samplespersec% params$ = " bitspersample " + STR$(bitspersample%) + \ \ " channels " + STR$(channe...
Port the following code from Go to BBC_Basic with equivalent syntax and logic.
package main import ( "log" "os" "os/exec" ) func main() { args := []string{ "-m", "-v", "0.75", "a.wav", "-v", "0.25", "b.wav", "-d", "trim", "4", "6", "repeat", "5", } cmd := exec.Command("sox", args...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr ...
SND_LOOP = 8 SND_ASYNC = 1 SND_FILENAME = &20000 PRINT "Playing a MIDI file..." *PLAY C:\windows\media\canyon.mid WAIT 300 PRINT "Playing the Windows TADA sound quietly..." wave$ = "\windows\media\tada.wav" volume% = 10000 SYS "waveOutSetVolume",...
Change the programming language of this snippet from Go to BBC_Basic without modifying what it does.
package main import "fmt" import "math/rand" func main(){ var a1,a2,a3,y,match,j,k int var inp string y=1 for y==1{ fmt.Println("Enter your sequence:") fmt.Scanln(&inp) var Ai [3] int var user [3] int for j=0;j<3;j++{ if(inp[j]==104){ user[j]=1 }else{ user[j]=0 } } for k=0;k<3;k++{ Ai[k]=rand.Intn(2) } for user[0]==Ai[...
PRINT "*** Penney's Game ***" REPEAT PRINT ' "Heads you pick first, tails I pick first." PRINT "And it is... "; WAIT 100 ht% = RND(0 - TIME) AND 1 IF ht% THEN PRINT "heads!" PROC_player_chooses(player$) computer$ = FN_optimal(player$) PRINT "I choose "; computer$; "." ELSE PRINT "tails!...
Convert the following code from Go to BBC_Basic, ensuring the logic remains intact.
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "os" ) func main() { const order = 8 const width = 1 << order const margin = 10 bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin) im := image.NewGray(bounds) gBlack := color....
order% = 8 size% = 2^order% VDU 23,22,size%;size%;8,8,16,128 FOR Y% = 0 TO size%-1 FOR X% = 0 TO size%-1 IF (X% AND Y%)=0 PLOT X%*2,Y%*2 NEXT NEXT Y%
Can you help me rewrite this code in BBC_Basic instead of Go, keeping it the same logically?
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "os" ) func main() { const order = 8 const width = 1 << order const margin = 10 bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin) im := image.NewGray(bounds) gBlack := color....
order% = 8 size% = 2^order% VDU 23,22,size%;size%;8,8,16,128 FOR Y% = 0 TO size%-1 FOR X% = 0 TO size%-1 IF (X% AND Y%)=0 PLOT X%*2,Y%*2 NEXT NEXT Y%
Keep all operations the same but rewrite the snippet in BBC_Basic.
package raster import "math" func ipart(x float64) float64 { return math.Floor(x) } func round(x float64) float64 { return ipart(x + .5) } func fpart(x float64) float64 { return x - ipart(x) } func rfpart(x float64) float64 { return 1 - fpart(x) } func (g *Grmap) AaLine(x1, y1, x2, y2 float64) { ...
PROCdrawAntiAliasedLine(100, 100, 600, 400, 0, 0, 0) END DEF PROCdrawAntiAliasedLine(x1, y1, x2, y2, r%, g%, b%) LOCAL dx, dy, xend, yend, grad, yf, xgap, ix1%, iy1%, ix2%, iy2%, x% dx = x2 - x1 dy = y2 - y1 IF ABS(dx) < ABS(dy) THEN SWAP x1, y1 SW...
Produce a functionally identical BBC_Basic code for the snippet given in Go.
package main import ( "fmt" "os/exec" ) func main() { command := "EventCreate" args := []string{"/T", "INFORMATION", "/ID", "123", "/L", "APPLICATION", "/SO", "Go", "/D", "\"Rosetta Code Example\""} cmd := exec.Command(command, args...) err := cmd.Run() if err != nil { fmt....
INSTALL @lib$+"COMLIB" PROC_cominitlcid(1033) WshShell% = FN_createobject("WScript.Shell") PROC_callmethod(WshShell%, "LogEvent(0, ""Test from BBC BASIC"")") PROC_releaseobject(WshShell%) PROC_comexit
Change the following Go code into BBC_Basic without altering its purpose.
package main import "fmt" import "C" func main() { code := []byte{ 0x55, 0x48, 0x89, 0xe5, 0x89, 0x7d, 0xfc, 0x89, 0x75, 0xf8, 0x8b, 0x75, 0xfc, 0x03, 0x75, 0xf8, 0x89, 0x75, 0xf4, 0x8b, 0x45, 0xf4, 0x5d, 0xc3, } le := len(code) buf := C.mmap(nil, C.size_t(le), C.PROT...
SYS "GlobalAlloc",0,9 TO code% P%=code% [OPT 0 mov EAX, [ESP+4] add EAX, [ESP+8] ret ] SYS code%,7,12 TO result% PRINT result% SYS "GlobalFree",code% END
Port the provided Go code into BBC_Basic while preserving the original functionality.
package main import ( "fmt" "github.com/nsf/termbox-go" "github.com/simulatedsimian/joystick" "log" "os" "strconv" "time" ) func printAt(x, y int, s string) { for _, r := range s { termbox.SetCell(x, y, r, termbox.ColorDefault, termbox.ColorDefault) x++ } } func re...
VDU 23,22,512;512;8,16,16,0 VDU 5 GCOL 4,15 REPEAT B% = ADVAL(0) X% = ADVAL(1) / 64 Y% = 1023 - ADVAL(2) / 64 PROCjoy(B%,X%,Y%) WAIT 4 PROCjoy(B%,X%,Y%) UNTIL FALSE END DEF PROCjoy(B%,X%,Y%) LOCAL I% LINE...
Transform the following Go implementation into BBC_Basic, maintaining the same output and logic.
package main import ( "fmt" "math/big" ) func main() { fmt.Print("!0 through !10: 0") one := big.NewInt(1) n := big.NewInt(1) f := big.NewInt(1) l := big.NewInt(1) next := func() { f.Mul(f, n); l.Add(l, f); n.Add(n, one) } for ; ; next() { fmt.Print(" ", l) if n.Int...
INSTALL @lib$+"BB4WMAPMLIB" : PROCMAPM_Init : MAPM_Dec%=200 Result$="0" : A$="1" FOR I%=0 TO 10000 IF I% Result$=FNMAPM_Add(Result$,A$) : A$=FNMAPM_Multiply(A$,STR$I%) IF I% < 111 IF I% MOD 10 = 0 OR I% < 11 PRINT "!";I% " = " FNMAPM_FormatDec(Result$,0) IF I% > 999 IF I...
Produce a language-to-language conversion: from Go to BBC_Basic, same semantics.
package main import ( "fmt" "math/big" ) func main() { fmt.Print("!0 through !10: 0") one := big.NewInt(1) n := big.NewInt(1) f := big.NewInt(1) l := big.NewInt(1) next := func() { f.Mul(f, n); l.Add(l, f); n.Add(n, one) } for ; ; next() { fmt.Print(" ", l) if n.Int...
INSTALL @lib$+"BB4WMAPMLIB" : PROCMAPM_Init : MAPM_Dec%=200 Result$="0" : A$="1" FOR I%=0 TO 10000 IF I% Result$=FNMAPM_Add(Result$,A$) : A$=FNMAPM_Multiply(A$,STR$I%) IF I% < 111 IF I% MOD 10 = 0 OR I% < 11 PRINT "!";I% " = " FNMAPM_FormatDec(Result$,0) IF I% > 999 IF I...
Produce a functionally identical BBC_Basic code for the snippet given in Go.
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { units := []string{ "tochka", "liniya", "dyuim", "vershok", "piad", "fut", "arshin", "sazhen", "versta", "milia", "centimeter", "meter", "kilometer", } convs := []float32{ 0.025...
@% = &90E PROColdrus(1, "meter") PRINT PROColdrus(10, "arshin") END : DEF PROColdrus(length, unit$) LOCAL units$(), values(), unit%, i% DIM units$(12) DIM values(12) units$() = "kilometer", "meter", "centimeter", "milia", "versta", "sazhen", "arshin", "fut", "piad", "vershok", "diuym", "liniya", "tochka" values() = 10...
Preserve the algorithm and functionality while converting the code from Go to BBC_Basic.
package main import ( "fmt" "time" ) func main() { fmt.Print("\033[?1049h\033[H") fmt.Println("Alternate screen buffer\n") s := "s" for i := 5; i > 0; i-- { if i == 1 { s = "" } fmt.Printf("\rgoing back in %d second%s...", i, s) time.Sleep(time.Secon...
PRINT "This is the original screen" OSCLI "GSAVE """ + @tmp$ + "bbcsave""" WAIT 200 CLS PRINT "This is the new screen, following a CLS" WAIT 200 OSCLI "DISPLAY """ + @tmp$ + "bbcsave"""
Please provide an equivalent version of this Go code in BBC_Basic.
package main import ( "fmt" "math/big" ) var smallPrimes = [...]int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} const maxStack = 128 var ( tens, values [maxStack]big.Int bigTemp, answer = new(big.Int), new(big.Int) base, seenDepth int ) func addDigit(i int) { for d := 1; d < base; d++ { ...
HIMEM = PAGE + 3000000 INSTALL @lib$+"HIMELIB" PROC_himeinit("HIMEkey") DIM old$(20000), new$(20000) h1% = 1 : h2% = 2 : h3% = 3 : h4% = 4 FOR base% = 3 TO 17 PRINT "Base "; base% " : " FN_largest_left_truncated_prime(base%) NEXT END DEF...
Change the programming language of this snippet from Go to BBC_Basic without modifying what it does.
package main import ( "go/build" "log" "path/filepath" "github.com/unixpickle/gospeech" "github.com/unixpickle/wav" ) const pkgPath = "github.com/unixpickle/gospeech" const input = "This is an example of speech synthesis." func main() { p, err := build.Import(pkgPath, ".", build.FindOnly) ...
SPF_ASYNC = 1 ON ERROR SYS `CoUninitialize` : PRINT 'REPORT$ : END ON CLOSE SYS `CoUninitialize` : QUIT SYS "LoadLibrary","OLE32.DLL" TO O% SYS "GetProcAddress",O%,"CoInitialize" TO `CoInitialize` SYS "GetProcAddress",O%,"CoUninitialize" TO `CoUninitialize` SYS "GetProcA...
Write a version of this Go function in BBC_Basic with identical behavior.
package main import ( "log" "math/rand" "testing" "time" "github.com/gonum/plot" "github.com/gonum/plot/plotter" "github.com/gonum/plot/plotutil" "github.com/gonum/plot/vg" ) func bubblesort(a []int) { for itemCount := len(a) - 1; ; itemCount-- { hasChanged := false ...
HIMEM = PAGE + 2000000 INSTALL @lib$+"SORTLIB" INSTALL @lib$+"TIMERLIB" Sort% = FN_sortinit(0,0) Timer% = FN_ontimer(1000, PROCtimer, 1) PRINT "Array size:", 1000, 10000, 100000 @% = &2020A FOR patt% = 1 TO 4 CASE patt% OF WHEN 1: PRINT '"D...
Generate a BBC_Basic translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math/rand" "time" ) const ( op_num = iota op_add op_sub op_mul op_div ) type frac struct { num, denom int } type Expr struct { op int left, right *Expr value frac } var n_cards = 4 var goal = 24 var digit_range = 9 func (x *Expr) String() string { if x.op...
PROCsolve24("1234") PROCsolve24("6789") PROCsolve24("1127") PROCsolve24("5566") END DEF PROCsolve24(s$) LOCAL F%, I%, J%, K%, L%, P%, T%, X$, o$(), p$(), t$() DIM o$(4), p$(24,4), t$(11) o$() = "", "+", "-", "*", "/" RESTORE FOR T% = 1 TO 11 ...
Port the provided Go code into BBC_Basic while preserving the original functionality.
package main import ( "fmt" "math/rand" "time" ) const ( op_num = iota op_add op_sub op_mul op_div ) type frac struct { num, denom int } type Expr struct { op int left, right *Expr value frac } var n_cards = 4 var goal = 24 var digit_range = 9 func (x *Expr) String() string { if x.op...
PROCsolve24("1234") PROCsolve24("6789") PROCsolve24("1127") PROCsolve24("5566") END DEF PROCsolve24(s$) LOCAL F%, I%, J%, K%, L%, P%, T%, X$, o$(), p$(), t$() DIM o$(4), p$(24,4), t$(11) o$() = "", "+", "-", "*", "/" RESTORE FOR T% = 1 TO 11 ...
Generate a BBC_Basic translation of this Go snippet without changing its computational steps.
package main import "fmt" type sBox [8][16]byte type gost struct { k87, k65, k43, k21 [256]byte enc []byte } func newGost(s *sBox) *gost { var g gost for i := range g.k87 { g.k87[i] = s[7][i>>4]<<4 | s[6][i&15] g.k65[i] = s[5][i>>4]<<4 | s[4][i&15] g.k43[i] = s...
DIM table&(7,15), test%(1) table&() = 4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3, \ \ 14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9, \ \ 5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11, \ \ 7, 13, 10, 1, 0, ...
Can you help me rewrite this code in BBC_Basic instead of Go, keeping it the same logically?
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "math" "os" ) func hough(im image.Image, ntx, mry int) draw.Image { nimx := im.Bounds().Max.X mimy := im.Bounds().Max.Y him := image.NewGray(image.Rect(0, 0, ntx, mry)) draw.Draw(him, him.Bounds(), ...
Width% = 320 Height% = 240 VDU 23,22,Width%;Height%;8,16,16,128 *DISPLAY Pentagon.bmp OFF DIM hist%(Width%-1, Height%-1) rs = 2 * SQR(Width%^2 + Height%^2) / Height% : ts = PI / Width% : h% = Height% / 2 FOR y% = 0 TO Heigh...
Write a version of this Go function in BBC_Basic with identical behavior.
package main import "fmt" const jobs = 12 type environment struct{ seq, cnt int } var ( env [jobs]environment seq, cnt *int ) func hail() { fmt.Printf("% 4d", *seq) if *seq == 1 { return } (*cnt)++ if *seq&1 != 0 { *seq = 3*(*seq) + 1 } else { *seq /= 2 ...
DIM @environ$(12) @% = 4 : FOR E% = 1 TO 12 PROCsetenvironment(@environ$(E%)) seq% = E% cnt% = 0 @environ$(E%) = FNgetenvironment NEXT REPEAT T% = 0 FOR E% = 1 TO 12 PROCsetenvironment(@environ$(E%)) ...
Write the same code in BBC_Basic as shown below in Go.
package main import ( "fmt" "log" "os/exec" "time" ) func main() { out, err := exec.Command("xrandr", "-q").Output() if err != nil { log.Fatal(err) } fmt.Println(string(out)) time.Sleep(3 * time.Second) err = exec.Command("xrandr", "-s", "1024x768").Run() ...
10 MODE 1:
Generate a BBC_Basic translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "log" "os/exec" "time" ) func main() { out, err := exec.Command("xrandr", "-q").Output() if err != nil { log.Fatal(err) } fmt.Println(string(out)) time.Sleep(3 * time.Second) err = exec.Command("xrandr", "-s", "1024x768").Run() ...
10 MODE 1:
Please provide an equivalent version of this Go code in BBC_Basic.
package main import "C" import "fmt" func main() { for i := 0; i < 80*25; i++ { fmt.Print("A") } fmt.Println() conOut := C.GetStdHandle(C.STD_OUTPUT_HANDLE) info := C.CONSOLE_SCREEN_BUFFER_INFO{} pos := C.COORD{} C.GetConsoleScreenBufferInfo(conOut, &info) pos.X = info.srWin...
PRINT TAB(2,5) "Here" char$ = GET$(2,5) PRINT ''"Character at column 3 row 6 was " char$
Ensure the translated BBC_Basic code behaves exactly like the original Go snippet.
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) var ( gregorianStr = []string{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"} gregorian = []int{31, 28, 31, 30, 31, 30, 31, 3...
: DIM gregorian$(11) DIM gregorian%(11) DIM republican$(11) DIM sansculottides$(5) gregorian$() = "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" gregorian%() = 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 republican$() = "Vendemiaire", "Bruma...
Port the provided PHP code into Mathematica while preserving the original functionality.
#!/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...
isLegal[n_List, x_String] := Quiet[Check[ With[{h = ToExpression[x, StandardForm, HoldForm]}, If[Cases[Level[h, {2, \[Infinity]}, Hold, Heads -> True], Except[_Integer | Plus | _Plus | Times | _Times | Power | Power[_, -1]]] === {} && Sort[Level[h /. Power[q_, -1] -> q, {-1}] /. ...
Preserve the algorithm and functionality while converting the code from PHP to Mathematica.
define("PI", 3.14159265358); define("MSG", "Hello World");
Tau = 2*Pi;Protect[Tau] {"Tau"} Tau = 2 ->Set::wrsym: Symbol Tau is Protected.
Produce a functionally identical Mathematica code for the snippet given in PHP.
<?php echo substr_count("the three truths", "th"), PHP_EOL; // prints "3" echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
StringPosition["the three truths","th",Overlaps->False]//Length 3 StringPosition["ababababab","abab",Overlaps->False]//Length 2
Convert this PHP block to Mathematica, preserving its control flow and logic.
<?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)...
fractalTree[ pt : {_, _}, \[Theta]orient_: \[Pi]/2, \[Theta]sep_: \[Pi]/9, depth_Integer: 9] := Module[{pt2}, If[depth == 0, Return[]]; pt2 = pt + {Cos[\[Theta]orient], Sin[\[Theta]orient]}*depth; DeleteCases[ Flatten@{ Line[{pt, pt2}], fractalTree[pt2, \[Theta]orient - \[Theta]sep, \[Theta]sep,...
Preserve the algorithm and functionality while converting the code from PHP to Mathematica.
<?php echo "<h1>" . "Choose: ROCK - PAPER - SCISSORS" . "</h1>"; echo "<h2>"; echo ""; $player = strtoupper( $_GET["moves"] ); $wins = [ 'ROCK' => 'SCISSORS', 'PAPER' => 'ROCK', 'SCISSORS' => 'PAPER' ]; $a_i = array_rand($wins); echo "<br>"; echo "Player chooses " . "<i style=\"color:blue\">" . $player ....
DynamicModule[{record, play, text = "\nRock-paper-scissors\n", choices = {"Rock", "Paper", "Scissors"}}, Evaluate[record /@ choices] = {1, 1, 1}; play[x_] := Module[{y = RandomChoice[record /@ choices -> RotateLeft@choices]}, record[x]++; text = "Your Choice:" <> x <> "\nComputer's Choice:" <> y <> "\...
Convert this PHP snippet to Mathematica and keep its semantics consistent.
<?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] . '[]...
ClearAll[CreateVar, ImportConfig]; CreateVar[x_, y_String: "True"] := Module[{}, If[StringFreeQ[y, ","] , ToExpression[x <> "=" <> y] , ToExpression[x <> "={" <> StringJoin@Riffle[StringSplit[y, ","], ","] <> "}"] ] ] ImportConfig[configfile_String] := Module[{data}, data=Import[configfile,"List...
Change the programming language of this snippet from PHP to Mathematica without modifying what it does.
<?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"; "The three dogs are named "<> dog <>", "<> Dog <>" and "<> DOG -> "The three dogs are named Benjamin, Samba and Bernie"
Maintain the same structure and functionality when rewriting this code in Mathematica.
$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 ...
ClearAll[ct, FunctionMatchQ, ValidFunctionQ, ProcessString] ct = "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 ...
Translate this program into Mathematica but keep the logic exactly as in PHP.
$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 ...
ClearAll[ct, FunctionMatchQ, ValidFunctionQ, ProcessString] ct = "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 ...
Rewrite the snippet below in Mathematica so it works the same as the original PHP code.
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[lst_, I_, J_] := Module[{i = I, j = J, list = lst}, If[list[[j]] < list[[i]], list[[{i,j}]] = list[[{j,i}]];] If[(j-i) > 1, t = Round[(j-i+1)/3]; list=stoogeSort[list,i,j-t]; list=stoogeSort[list,i+t,j]; list=stoogeSort[list,i,j-t];]; list ]
Generate an equivalent Mathematica version of this PHP code.
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...
shellSort[ lst_ ] := Module[ {list = lst, incr, temp, i, j}, incr = Round[Length[list]/2]; While[incr > 0, For[i = incr + 1, i <= Length[list], i++, temp = list[[i]]; j = i; While[(j >= (incr + 1)) && (list[[j - incr]] > temp) , list[[j]] = list[[j - incr]]; j = j-incr; ]; list[[j]] = temp;]; ...
Write a version of this PHP function in Mathematica with identical behavior.
<?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...
If[# != EndOfFile , Print[#]]& @ ReadList["file", String, 7]
Produce a functionally identical Mathematica code for the snippet given in PHP.
<?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...
If[# != EndOfFile , Print[#]]& @ ReadList["file", String, 7]
Transform the following PHP implementation into Mathematica, maintaining the same output and logic.
<?php $s = 'http://foo/bar/'; $s = rawurlencode($s); ?>
URLEncoding[url_] := StringReplace[url, x : Except[ Join[CharacterRange["0", "9"], CharacterRange["a", "z"], CharacterRange["A", "Z"]]] :> StringJoin[("%" ~~ #) & /@ IntegerString[ToCharacterCode[x, "UTF8"], 16]]]
Translate this program into Mathematica but keep the logic exactly as in PHP.
<?php $s = 'http://foo/bar/'; $s = rawurlencode($s); ?>
URLEncoding[url_] := StringReplace[url, x : Except[ Join[CharacterRange["0", "9"], CharacterRange["a", "z"], CharacterRange["A", "Z"]]] :> StringJoin[("%" ~~ #) & /@ IntegerString[ToCharacterCode[x, "UTF8"], 16]]]
Keep all operations the same but rewrite the snippet in Mathematica.
<?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 = ...
numbers=RandomReal[{-2,6},11] tpk[numbers_,overflowVal_]:=Module[{revNumbers}, revNumbers=Reverse[numbers]; f[x_]:=Abs[x]^0.5+5 x^3; Do[ If[f[i]>overflowVal, Print["f[",i,"]= Overflow"] , Print["f[",i,"]= ",f[i]] ] , {i,revNumbers} ] ] tpk[numbers,400]
Transform the following PHP implementation into Mathematica, maintaining the same output and logic.
<?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;...
isSelfDescribing[n_Integer] := (RotateRight[DigitCount[n]] == PadRight[IntegerDigits[n], 10])
Translate the given PHP code snippet into Mathematica without altering its behavior.
<?php foreach(file("unixdict.txt") as $w) echo (strstr($w, "the") && strlen(trim($w)) > 11) ? $w : "";
dict = Once[Import["https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt"]]; dict //= StringSplit[#, "\n"] &; dict //= Select[StringLength /* GreaterThan[11]]; Select[dict, StringContainsQ["the"]]
Maintain the same structure and functionality when rewriting this code in Mathematica.
$address = <<<END 1, High Street, $town_name, West Midlands. WM4 5HD. END;
Print["Mathematica is an interesing language, with its strings being multiline by\ default when not back\ s\\ashed!"];
Change the following PHP code into Mathematica without altering its purpose.
$address = <<<END 1, High Street, $town_name, West Midlands. WM4 5HD. END;
Print["Mathematica is an interesing language, with its strings being multiline by\ default when not back\ s\\ashed!"];
Write the same algorithm in Mathematica as shown in this PHP implementation.
<?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...
SetOptions[InputNotebook[],NotebookEventActions->{ "LeftArrowKeyDown":>(stat=Coalesce[stat];AddNew[]), "RightArrowKeyDown":>(stat=Reverse/@Coalesce[Reverse/@stat];AddNew[]), "UpArrowKeyDown":>(stat=Coalesce[stat\[Transpose]]\[Transpose];AddNew[]), "DownArrowKeyDown":>(stat=(Reverse/@(Coalesce[Reverse/@(stat\[Transpose]...
Produce a language-to-language conversion: from PHP to Mathematica, same semantics.
<?php $db = new SQLite3(':memory:'); $db->exec(" CREATE TABLE address ( addrID INTEGER PRIMARY KEY AUTOINCREMENT, addrStreet TEXT NOT NULL, addrCity TEXT NOT NULL, addrState TEXT NOT NULL, addrZIP TEXT NOT NULL ) "); ?>
TableCreation="CREATE TABLE address ( addrID INTEGER PRIMARY KEY AUTOINCREMENT, addrStreet TEXT NOT NULL, addrCity TEXT NOT NULL, addrState TEXT NOT NULL, addrZIP TEXT NOT NULL )"; Needs["DatabaseLink`"] conn=OpenSQLConnection[ JDBC[ "mysql","databases:1234/conn_test"], "Username" -> "test"] SQLExecute[ conn, Tab...
Produce a language-to-language conversion: from PHP to Mathematica, same semantics.
<?php $a = array(); array_push($a, 0); $used = array(); array_push($used, 0); $used1000 = array(); array_push($used1000, 0); $foundDup = false; $n = 1; while($n <= 15 || !$foundDup || count($used1000) < 1001) { $next = $a[$n - 1] - $n; if ($next < 1 || in_array($next, $used)) { $next += 2 * $n; } $alreadyUsed...
ClearAll[f] f[s_List] := Block[{a = s[[-1]], len = Length@s}, Append[s, If[a > len && ! MemberQ[s, a - len], a - len, a + len]]]; g = Nest[f, {0}, 70] g = Nest[f, {0}, 70]; Take[g, 15] p = Select[Tally[g], Last /* EqualTo[2]][[All, 1]] p = Flatten[Position[g, #]] & /@ p; TakeSmallestBy[p, Last, 1][[1]]
Generate a Mathematica translation of this PHP snippet without changing its computational steps.
<?php $a = array(); array_push($a, 0); $used = array(); array_push($used, 0); $used1000 = array(); array_push($used1000, 0); $foundDup = false; $n = 1; while($n <= 15 || !$foundDup || count($used1000) < 1001) { $next = $a[$n - 1] - $n; if ($next < 1 || in_array($next, $used)) { $next += 2 * $n; } $alreadyUsed...
ClearAll[f] f[s_List] := Block[{a = s[[-1]], len = Length@s}, Append[s, If[a > len && ! MemberQ[s, a - len], a - len, a + len]]]; g = Nest[f, {0}, 70] g = Nest[f, {0}, 70]; Take[g, 15] p = Select[Tally[g], Last /* EqualTo[2]][[All, 1]] p = Flatten[Position[g, #]] & /@ p; TakeSmallestBy[p, Last, 1][[1]]
Keep all operations the same but rewrite the snippet in Mathematica.
<?php function Y($f) { $g = function($w) use($f) { return $f(function() use($w) { return call_user_func_array($w($w), func_get_args()); }); }; return $g($g); } $fibonacci = Y(function($f) { return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); }; }); echo $fibonacci(10), "...
Y = Function[f, #[#] &[Function[g, f[g[g][##] &]]]]; factorial = Y[Function[f, If[# < 1, 1, # f[# - 1]] &]]; fibonacci = Y[Function[f, If[# < 2, #, f[# - 1] + f[# - 2]] &]];
Generate a Mathematica translation of this PHP snippet without changing its computational steps.
<?php function columns($arr) { if (count($arr) == 0) return array(); else if (count($arr) == 1) return array_chunk($arr[0], 1); array_unshift($arr, NULL); $transpose = call_user_func_array('array_map', $arr); return array_map('array_filter', $transpose); } function beadsort($arr) ...
beadsort[ a ] := Module[ { m, sorted, s ,t }, sorted = a; m = Max[a]; t=ConstantArray[0, {m,m} ]; If[ Min[a] < 0, Print["can't sort"]]; For[ i = 1, i < Length[a], i++, t[[i,1;;a[[i]]]]=1 ] For[ i = 1 ,i <= m, i++, s = Total[t[[;;,i]]]; t[[ ;; , i]] = 0; t[[1 ;; s , i]] = 1; ] For[ i=1,i<=Length[a],i++, sorted[[i]] ...
Can you help me rewrite this code in Mathematica instead of PHP, keeping it the same logically?
class Card { protected static $suits = array( '♠', '♥', '♦', '♣' ); protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' ); protected $suit; protected $suitOrder; protected $pip; protected $pipOrder; protected $order; public function __c...
MakeDeck[] := Tuples[{{"Ace ", 2, 3 , 4 , 5, 6 , 7 , 8 , 9 , 10, "Jack" , "Queen", "King"}, {♦ , ♣, ♥ , ♠}}] DeckShuffle[deck_] := RandomSample[deck, Length@deck] DealFromDeck[] := (Print@First@deck; deck = deck[[2 ;; All]];)
Transform the following PHP implementation into Mathematica, maintaining the same output and logic.
<?php class Foo { public function __clone() { $this->child = clone $this->child; } } $object = new Foo; $object->some_value = 1; $object->child = new stdClass; $object->child->some_value = 1; $deepcopy = clone $object; $deepcopy->some_value++; $deepcopy->child->some_value++; echo "Object contains...
a = {"foo", \[Pi], {<| "deep" -> {# + 1 &, {{"Mathematica"}, {{"is"}, {"a"}}, {{{"cool"}}}, \ {{"programming"}, {"language!"}}}}|>}}; b = a; a[[2]] -= 3; a[[3, 1, 1, 1]] = #^2 &; Print[a]; Print[b];
Preserve the algorithm and functionality while converting the code from PHP to Mathematica.
<?php class Foo { public function __clone() { $this->child = clone $this->child; } } $object = new Foo; $object->some_value = 1; $object->child = new stdClass; $object->child->some_value = 1; $deepcopy = clone $object; $deepcopy->some_value++; $deepcopy->child->some_value++; echo "Object contains...
a = {"foo", \[Pi], {<| "deep" -> {# + 1 &, {{"Mathematica"}, {{"is"}, {"a"}}, {{{"cool"}}}, \ {{"programming"}, {"language!"}}}}|>}}; b = a; a[[2]] -= 3; a[[3, 1, 1, 1]] = #^2 &; Print[a]; Print[b];
Rewrite the snippet below in Mathematica so it works the same as the original PHP code.
function inOrder($arr){ for($i=0;$i<count($arr);$i++){ if(isset($arr[$i+1])){ if($arr[$i] > $arr[$i+1]){ return false; } } } return true; } function permute($items, $perms = array( )) { if (empty($items)) { if(inOrder($perms)){ return $perms; } } else { for ($i = count($items) ...
PermutationSort[x_List] := NestWhile[RandomSample, x, Not[OrderedQ[#]] &]
Port the following code from PHP to Mathematica with equivalent syntax and logic.
<?php function meaning_of_life() { return 42; } function main($args) { echo "Main: The meaning of life is " . meaning_of_life() . "\n"; } if (preg_match("/scriptedmain/", $_SERVER["SCRIPT_NAME"])) { main($argv); } ?>
#!/usr/bin/env MathKernel -script MeaningOfLife[] = 42 ScriptName[] = Piecewise[ { {"Interpreted", Position[$CommandLine, "-script", 1] == {}} }, $CommandLine[[Position[$CommandLine, "-script", 1][[1,1]] + 1]] ] Program = ScriptName[]; If[StringMatchQ[Program, ".*scriptedmain.*"], Print["Main: The meaning of ...
Maintain the same structure and functionality when rewriting this code in Mathematica.
<?php function meaning_of_life() { return 42; } function main($args) { echo "Main: The meaning of life is " . meaning_of_life() . "\n"; } if (preg_match("/scriptedmain/", $_SERVER["SCRIPT_NAME"])) { main($argv); } ?>
#!/usr/bin/env MathKernel -script MeaningOfLife[] = 42 ScriptName[] = Piecewise[ { {"Interpreted", Position[$CommandLine, "-script", 1] == {}} }, $CommandLine[[Position[$CommandLine, "-script", 1][[1,1]] + 1]] ] Program = ScriptName[]; If[StringMatchQ[Program, ".*scriptedmain.*"], Print["Main: The meaning of ...
Ensure the translated Mathematica code behaves exactly like the original PHP snippet.
<?php function printLastSundayOfAllMonth($year) { $months = array( 'January', 'February', 'March', 'April', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); foreach ($months as $month) { echo $month . ': ' . date('Y-m-d', strtotime('last sunday of ' . $month ...
LastSundays[year_] := Table[Last@ DayRange[{year, i}, DatePlus[{year, i}, {{1, "Month"}, {-1, "Day"}}], Sunday], {i, 12}] LastSundays[2013]
Keep all operations the same but rewrite the snippet in Mathematica.
<?php function printLastSundayOfAllMonth($year) { $months = array( 'January', 'February', 'March', 'April', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); foreach ($months as $month) { echo $month . ': ' . date('Y-m-d', strtotime('last sunday of ' . $month ...
LastSundays[year_] := Table[Last@ DayRange[{year, i}, DatePlus[{year, i}, {{1, "Month"}, {-1, "Day"}}], Sunday], {i, 12}] LastSundays[2013]
Transform the following PHP implementation into Mathematica, maintaining the same output and logic.
<?php $attributesTotal = 0; $count = 0; while($attributesTotal < 75 || $count < 2) { $attributes = []; foreach(range(0, 5) as $attribute) { $rolls = []; foreach(range(0, 3) as $roll) { $rolls[] = rand(1, 6); } sort($rolls); array_shift...
valid = False; While[! valid, try = Map[Total[TakeLargest[#, 3]] &, RandomInteger[{1, 6}, {6, 4}]]; If[Total[try] > 75 && Count[try, _?(GreaterEqualThan[15])] >= 2, valid = True; ] ] {Total[try], try}
Change the following PHP code into Mathematica without altering its purpose.
<?php class Node { public $val; public $back = NULL; } function lis($n) { $pileTops = array(); foreach ($n as $x) { $low = 0; $high = count($pileTops)-1; while ($low <= $high) { $mid = (int)(($low + $high) / 2); if ($pileTops[$mid]->val >= $x) $...
LongestAscendingSequence/@{{3,2,6,4,5,1},{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15}}