Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Transform the following COBOL implementation into Python, maintaining the same output and logic.
IDENTIFICATION DIVISION. PROGRAM-ID. CANTOR. DATA DIVISION. WORKING-STORAGE SECTION. 01 SETTINGS. 03 NUM-LINES PIC 9 VALUE 5. 03 FILL-CHAR PIC X VALUE '#'. 01 VARIABLES. 03 CUR-LINE. 05 CHAR PIC X OCCURS 81 TIMES. 03 WIDTH PIC 99. 03 CUR-SIZE PIC 99. 03 POS PIC 99. 03 MAXPOS PIC 99. 03 NEXTPOS PIC 99. 03 I PIC 99. PROCEDURE DIVISION. BEGIN. COMPUTE WIDTH = 3 ** (NUM-LINES - 1). PERFORM INIT. MOVE WIDTH TO CUR-SIZE. DISPLAY CUR-LINE. PERFORM DO-LINE UNTIL CUR-SIZE IS EQUAL TO 1. STOP RUN. INIT. PERFORM INIT-CHAR VARYING I FROM 1 BY 1 UNTIL I IS GREATER THAN WIDTH. INIT-CHAR. MOVE FILL-CHAR TO CHAR(I). DO-LINE. DIVIDE 3 INTO CUR-SIZE. MOVE 1 TO POS. SUBTRACT CUR-SIZE FROM WIDTH GIVING MAXPOS. PERFORM BLANK-REGIONS UNTIL POS IS GREATER THAN MAXPOS. DISPLAY CUR-LINE. BLANK-REGIONS. ADD CUR-SIZE TO POS. PERFORM BLANK-CHAR CUR-SIZE TIMES. BLANK-CHAR. MOVE SPACE TO CHAR(POS). ADD 1 TO POS.
WIDTH = 81 HEIGHT = 5 lines=[] def cantor(start, len, index): seg = len / 3 if seg == 0: return None for it in xrange(HEIGHT-index): i = index + it for jt in xrange(seg): j = start + seg + jt pos = i * WIDTH + j lines[pos] = ' ' cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) return None lines = ['*'] * (WIDTH*HEIGHT) cantor(0, WIDTH, 1) for i in xrange(HEIGHT): beg = WIDTH * i print ''.join(lines[beg : beg+WIDTH])
Write a version of this COBOL function in VB with identical behavior.
IDENTIFICATION DIVISION. PROGRAM-ID. CANTOR. DATA DIVISION. WORKING-STORAGE SECTION. 01 SETTINGS. 03 NUM-LINES PIC 9 VALUE 5. 03 FILL-CHAR PIC X VALUE '#'. 01 VARIABLES. 03 CUR-LINE. 05 CHAR PIC X OCCURS 81 TIMES. 03 WIDTH PIC 99. 03 CUR-SIZE PIC 99. 03 POS PIC 99. 03 MAXPOS PIC 99. 03 NEXTPOS PIC 99. 03 I PIC 99. PROCEDURE DIVISION. BEGIN. COMPUTE WIDTH = 3 ** (NUM-LINES - 1). PERFORM INIT. MOVE WIDTH TO CUR-SIZE. DISPLAY CUR-LINE. PERFORM DO-LINE UNTIL CUR-SIZE IS EQUAL TO 1. STOP RUN. INIT. PERFORM INIT-CHAR VARYING I FROM 1 BY 1 UNTIL I IS GREATER THAN WIDTH. INIT-CHAR. MOVE FILL-CHAR TO CHAR(I). DO-LINE. DIVIDE 3 INTO CUR-SIZE. MOVE 1 TO POS. SUBTRACT CUR-SIZE FROM WIDTH GIVING MAXPOS. PERFORM BLANK-REGIONS UNTIL POS IS GREATER THAN MAXPOS. DISPLAY CUR-LINE. BLANK-REGIONS. ADD CUR-SIZE TO POS. PERFORM BLANK-CHAR CUR-SIZE TIMES. BLANK-CHAR. MOVE SPACE TO CHAR(POS). ADD 1 TO POS.
Module Module1 Const WIDTH = 81 Const HEIGHT = 5 Dim lines(HEIGHT, WIDTH) As Char Sub Init() For i = 0 To HEIGHT - 1 For j = 0 To WIDTH - 1 lines(i, j) = "*" Next Next End Sub Sub Cantor(start As Integer, len As Integer, index As Integer) Dim seg As Integer = len / 3 If seg = 0 Then Return End If For i = index To HEIGHT - 1 For j = start + seg To start + seg * 2 - 1 lines(i, j) = " " Next Next Cantor(start, seg, index + 1) Cantor(start + seg * 2, seg, index + 1) End Sub Sub Main() Init() Cantor(0, WIDTH, 1) For i = 0 To HEIGHT - 1 For j = 0 To WIDTH - 1 Console.Write(lines(i, j)) Next Console.WriteLine() Next End Sub End Module
Please provide an equivalent version of this COBOL code in VB.
IDENTIFICATION DIVISION. PROGRAM-ID. CANTOR. DATA DIVISION. WORKING-STORAGE SECTION. 01 SETTINGS. 03 NUM-LINES PIC 9 VALUE 5. 03 FILL-CHAR PIC X VALUE '#'. 01 VARIABLES. 03 CUR-LINE. 05 CHAR PIC X OCCURS 81 TIMES. 03 WIDTH PIC 99. 03 CUR-SIZE PIC 99. 03 POS PIC 99. 03 MAXPOS PIC 99. 03 NEXTPOS PIC 99. 03 I PIC 99. PROCEDURE DIVISION. BEGIN. COMPUTE WIDTH = 3 ** (NUM-LINES - 1). PERFORM INIT. MOVE WIDTH TO CUR-SIZE. DISPLAY CUR-LINE. PERFORM DO-LINE UNTIL CUR-SIZE IS EQUAL TO 1. STOP RUN. INIT. PERFORM INIT-CHAR VARYING I FROM 1 BY 1 UNTIL I IS GREATER THAN WIDTH. INIT-CHAR. MOVE FILL-CHAR TO CHAR(I). DO-LINE. DIVIDE 3 INTO CUR-SIZE. MOVE 1 TO POS. SUBTRACT CUR-SIZE FROM WIDTH GIVING MAXPOS. PERFORM BLANK-REGIONS UNTIL POS IS GREATER THAN MAXPOS. DISPLAY CUR-LINE. BLANK-REGIONS. ADD CUR-SIZE TO POS. PERFORM BLANK-CHAR CUR-SIZE TIMES. BLANK-CHAR. MOVE SPACE TO CHAR(POS). ADD 1 TO POS.
Module Module1 Const WIDTH = 81 Const HEIGHT = 5 Dim lines(HEIGHT, WIDTH) As Char Sub Init() For i = 0 To HEIGHT - 1 For j = 0 To WIDTH - 1 lines(i, j) = "*" Next Next End Sub Sub Cantor(start As Integer, len As Integer, index As Integer) Dim seg As Integer = len / 3 If seg = 0 Then Return End If For i = index To HEIGHT - 1 For j = start + seg To start + seg * 2 - 1 lines(i, j) = " " Next Next Cantor(start, seg, index + 1) Cantor(start + seg * 2, seg, index + 1) End Sub Sub Main() Init() Cantor(0, WIDTH, 1) For i = 0 To HEIGHT - 1 For j = 0 To WIDTH - 1 Console.Write(lines(i, j)) Next Console.WriteLine() Next End Sub End Module
Change the following COBOL code into Go without altering its purpose.
IDENTIFICATION DIVISION. PROGRAM-ID. CANTOR. DATA DIVISION. WORKING-STORAGE SECTION. 01 SETTINGS. 03 NUM-LINES PIC 9 VALUE 5. 03 FILL-CHAR PIC X VALUE '#'. 01 VARIABLES. 03 CUR-LINE. 05 CHAR PIC X OCCURS 81 TIMES. 03 WIDTH PIC 99. 03 CUR-SIZE PIC 99. 03 POS PIC 99. 03 MAXPOS PIC 99. 03 NEXTPOS PIC 99. 03 I PIC 99. PROCEDURE DIVISION. BEGIN. COMPUTE WIDTH = 3 ** (NUM-LINES - 1). PERFORM INIT. MOVE WIDTH TO CUR-SIZE. DISPLAY CUR-LINE. PERFORM DO-LINE UNTIL CUR-SIZE IS EQUAL TO 1. STOP RUN. INIT. PERFORM INIT-CHAR VARYING I FROM 1 BY 1 UNTIL I IS GREATER THAN WIDTH. INIT-CHAR. MOVE FILL-CHAR TO CHAR(I). DO-LINE. DIVIDE 3 INTO CUR-SIZE. MOVE 1 TO POS. SUBTRACT CUR-SIZE FROM WIDTH GIVING MAXPOS. PERFORM BLANK-REGIONS UNTIL POS IS GREATER THAN MAXPOS. DISPLAY CUR-LINE. BLANK-REGIONS. ADD CUR-SIZE TO POS. PERFORM BLANK-CHAR CUR-SIZE TIMES. BLANK-CHAR. MOVE SPACE TO CHAR(POS). ADD 1 TO POS.
package main import "fmt" const ( width = 81 height = 5 ) var lines [height][width]byte func init() { for i := 0; i < height; i++ { for j := 0; j < width; j++ { lines[i][j] = '*' } } } func cantor(start, len, index int) { seg := len / 3 if seg == 0 { return } for i := index; i < height; i++ { for j := start + seg; j < start + 2 * seg; j++ { lines[i][j] = ' ' } } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } func main() { cantor(0, width, 1) for _, line := range lines { fmt.Println(string(line[:])) } }
Keep all operations the same but rewrite the snippet in Go.
IDENTIFICATION DIVISION. PROGRAM-ID. CANTOR. DATA DIVISION. WORKING-STORAGE SECTION. 01 SETTINGS. 03 NUM-LINES PIC 9 VALUE 5. 03 FILL-CHAR PIC X VALUE '#'. 01 VARIABLES. 03 CUR-LINE. 05 CHAR PIC X OCCURS 81 TIMES. 03 WIDTH PIC 99. 03 CUR-SIZE PIC 99. 03 POS PIC 99. 03 MAXPOS PIC 99. 03 NEXTPOS PIC 99. 03 I PIC 99. PROCEDURE DIVISION. BEGIN. COMPUTE WIDTH = 3 ** (NUM-LINES - 1). PERFORM INIT. MOVE WIDTH TO CUR-SIZE. DISPLAY CUR-LINE. PERFORM DO-LINE UNTIL CUR-SIZE IS EQUAL TO 1. STOP RUN. INIT. PERFORM INIT-CHAR VARYING I FROM 1 BY 1 UNTIL I IS GREATER THAN WIDTH. INIT-CHAR. MOVE FILL-CHAR TO CHAR(I). DO-LINE. DIVIDE 3 INTO CUR-SIZE. MOVE 1 TO POS. SUBTRACT CUR-SIZE FROM WIDTH GIVING MAXPOS. PERFORM BLANK-REGIONS UNTIL POS IS GREATER THAN MAXPOS. DISPLAY CUR-LINE. BLANK-REGIONS. ADD CUR-SIZE TO POS. PERFORM BLANK-CHAR CUR-SIZE TIMES. BLANK-CHAR. MOVE SPACE TO CHAR(POS). ADD 1 TO POS.
package main import "fmt" const ( width = 81 height = 5 ) var lines [height][width]byte func init() { for i := 0; i < height; i++ { for j := 0; j < width; j++ { lines[i][j] = '*' } } } func cantor(start, len, index int) { seg := len / 3 if seg == 0 { return } for i := index; i < height; i++ { for j := start + seg; j < start + 2 * seg; j++ { lines[i][j] = ' ' } } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } func main() { cantor(0, width, 1) for _, line := range lines { fmt.Println(string(line[:])) } }
Write the same code in C as shown below in REXX.
w= linesize() if w==0 then w= 81 do lines=0; _ = 3 ** lines if _>w then leave #=_ end w= # $= copies('â– ', #) do j=0 until #==0 if j>0 then do k=#+1 by #+# to w $= overlay( left('', #), $, k) end say $ #= # % 3 end
#include <stdio.h> #define WIDTH 81 #define HEIGHT 5 char lines[HEIGHT][WIDTH]; void init() { int i, j; for (i = 0; i < HEIGHT; ++i) { for (j = 0; j < WIDTH; ++j) lines[i][j] = '*'; } } void cantor(int start, int len, int index) { int i, j, seg = len / 3; if (seg == 0) return; for (i = index; i < HEIGHT; ++i) { for (j = start + seg; j < start + seg * 2; ++j) lines[i][j] = ' '; } cantor(start, seg, index + 1); cantor(start + seg * 2, seg, index + 1); } void print() { int i, j; for (i = 0; i < HEIGHT; ++i) { for (j = 0; j < WIDTH; ++j) printf("%c", lines[i][j]); printf("\n"); } } int main() { init(); cantor(0, WIDTH, 1); print(); return 0; }
Translate the given REXX code snippet into C without altering its behavior.
w= linesize() if w==0 then w= 81 do lines=0; _ = 3 ** lines if _>w then leave #=_ end w= # $= copies('â– ', #) do j=0 until #==0 if j>0 then do k=#+1 by #+# to w $= overlay( left('', #), $, k) end say $ #= # % 3 end
#include <stdio.h> #define WIDTH 81 #define HEIGHT 5 char lines[HEIGHT][WIDTH]; void init() { int i, j; for (i = 0; i < HEIGHT; ++i) { for (j = 0; j < WIDTH; ++j) lines[i][j] = '*'; } } void cantor(int start, int len, int index) { int i, j, seg = len / 3; if (seg == 0) return; for (i = index; i < HEIGHT; ++i) { for (j = start + seg; j < start + seg * 2; ++j) lines[i][j] = ' '; } cantor(start, seg, index + 1); cantor(start + seg * 2, seg, index + 1); } void print() { int i, j; for (i = 0; i < HEIGHT; ++i) { for (j = 0; j < WIDTH; ++j) printf("%c", lines[i][j]); printf("\n"); } } int main() { init(); cantor(0, WIDTH, 1); print(); return 0; }
Change the following REXX code into C# without altering its purpose.
w= linesize() if w==0 then w= 81 do lines=0; _ = 3 ** lines if _>w then leave #=_ end w= # $= copies('â– ', #) do j=0 until #==0 if j>0 then do k=#+1 by #+# to w $= overlay( left('', #), $, k) end say $ #= # % 3 end
using System; namespace CantorSet { class Program { const int WIDTH = 81; const int HEIGHT = 5; private static char[,] lines = new char[HEIGHT, WIDTH]; static Program() { for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { lines[i, j] = '*'; } } } private static void Cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { lines[i, j] = ' '; } } Cantor(start, seg, index + 1); Cantor(start + seg * 2, seg, index + 1); } static void Main(string[] args) { Cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { Console.Write(lines[i,j]); } Console.WriteLine(); } } } }
Convert this REXX block to C#, preserving its control flow and logic.
w= linesize() if w==0 then w= 81 do lines=0; _ = 3 ** lines if _>w then leave #=_ end w= # $= copies('â– ', #) do j=0 until #==0 if j>0 then do k=#+1 by #+# to w $= overlay( left('', #), $, k) end say $ #= # % 3 end
using System; namespace CantorSet { class Program { const int WIDTH = 81; const int HEIGHT = 5; private static char[,] lines = new char[HEIGHT, WIDTH]; static Program() { for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { lines[i, j] = '*'; } } } private static void Cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { lines[i, j] = ' '; } } Cantor(start, seg, index + 1); Cantor(start + seg * 2, seg, index + 1); } static void Main(string[] args) { Cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { Console.Write(lines[i,j]); } Console.WriteLine(); } } } }
Maintain the same structure and functionality when rewriting this code in C++.
w= linesize() if w==0 then w= 81 do lines=0; _ = 3 ** lines if _>w then leave #=_ end w= # $= copies('â– ', #) do j=0 until #==0 if j>0 then do k=#+1 by #+# to w $= overlay( left('', #), $, k) end say $ #= # % 3 end
#include <iostream> const int WIDTH = 81; const int HEIGHT = 5; char lines[WIDTH*HEIGHT]; void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { int pos = i * WIDTH + j; lines[pos] = ' '; } } cantor(start, seg, index + 1); cantor(start + 2 * seg, seg, index + 1); } int main() { for (int i = 0; i < WIDTH*HEIGHT; i++) { lines[i] = '*'; } cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT*WIDTH; i += WIDTH) { printf("%.*s\n", WIDTH, lines + i); } return 0; }
Change the programming language of this snippet from REXX to C++ without modifying what it does.
w= linesize() if w==0 then w= 81 do lines=0; _ = 3 ** lines if _>w then leave #=_ end w= # $= copies('â– ', #) do j=0 until #==0 if j>0 then do k=#+1 by #+# to w $= overlay( left('', #), $, k) end say $ #= # % 3 end
#include <iostream> const int WIDTH = 81; const int HEIGHT = 5; char lines[WIDTH*HEIGHT]; void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { int pos = i * WIDTH + j; lines[pos] = ' '; } } cantor(start, seg, index + 1); cantor(start + 2 * seg, seg, index + 1); } int main() { for (int i = 0; i < WIDTH*HEIGHT; i++) { lines[i] = '*'; } cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT*WIDTH; i += WIDTH) { printf("%.*s\n", WIDTH, lines + i); } return 0; }
Produce a language-to-language conversion: from REXX to Java, same semantics.
w= linesize() if w==0 then w= 81 do lines=0; _ = 3 ** lines if _>w then leave #=_ end w= # $= copies('â– ', #) do j=0 until #==0 if j>0 then do k=#+1 by #+# to w $= overlay( left('', #), $, k) end say $ #= # % 3 end
public class App { private static final int WIDTH = 81; private static final int HEIGHT = 5; private static char[][] lines; static { lines = new char[HEIGHT][WIDTH]; for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { lines[i][j] = '*'; } } } private static void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { lines[i][j] = ' '; } } cantor(start, seg, index + 1); cantor(start + seg * 2, seg, index + 1); } public static void main(String[] args) { cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { System.out.print(lines[i][j]); } System.out.println(); } } }
Translate the given REXX code snippet into Java without altering its behavior.
w= linesize() if w==0 then w= 81 do lines=0; _ = 3 ** lines if _>w then leave #=_ end w= # $= copies('â– ', #) do j=0 until #==0 if j>0 then do k=#+1 by #+# to w $= overlay( left('', #), $, k) end say $ #= # % 3 end
public class App { private static final int WIDTH = 81; private static final int HEIGHT = 5; private static char[][] lines; static { lines = new char[HEIGHT][WIDTH]; for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { lines[i][j] = '*'; } } } private static void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { lines[i][j] = ' '; } } cantor(start, seg, index + 1); cantor(start + seg * 2, seg, index + 1); } public static void main(String[] args) { cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { System.out.print(lines[i][j]); } System.out.println(); } } }
Write the same code in Python as shown below in REXX.
w= linesize() if w==0 then w= 81 do lines=0; _ = 3 ** lines if _>w then leave #=_ end w= # $= copies('â– ', #) do j=0 until #==0 if j>0 then do k=#+1 by #+# to w $= overlay( left('', #), $, k) end say $ #= # % 3 end
WIDTH = 81 HEIGHT = 5 lines=[] def cantor(start, len, index): seg = len / 3 if seg == 0: return None for it in xrange(HEIGHT-index): i = index + it for jt in xrange(seg): j = start + seg + jt pos = i * WIDTH + j lines[pos] = ' ' cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) return None lines = ['*'] * (WIDTH*HEIGHT) cantor(0, WIDTH, 1) for i in xrange(HEIGHT): beg = WIDTH * i print ''.join(lines[beg : beg+WIDTH])
Produce a functionally identical Python code for the snippet given in REXX.
w= linesize() if w==0 then w= 81 do lines=0; _ = 3 ** lines if _>w then leave #=_ end w= # $= copies('â– ', #) do j=0 until #==0 if j>0 then do k=#+1 by #+# to w $= overlay( left('', #), $, k) end say $ #= # % 3 end
WIDTH = 81 HEIGHT = 5 lines=[] def cantor(start, len, index): seg = len / 3 if seg == 0: return None for it in xrange(HEIGHT-index): i = index + it for jt in xrange(seg): j = start + seg + jt pos = i * WIDTH + j lines[pos] = ' ' cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) return None lines = ['*'] * (WIDTH*HEIGHT) cantor(0, WIDTH, 1) for i in xrange(HEIGHT): beg = WIDTH * i print ''.join(lines[beg : beg+WIDTH])
Can you help me rewrite this code in VB instead of REXX, keeping it the same logically?
w= linesize() if w==0 then w= 81 do lines=0; _ = 3 ** lines if _>w then leave #=_ end w= # $= copies('â– ', #) do j=0 until #==0 if j>0 then do k=#+1 by #+# to w $= overlay( left('', #), $, k) end say $ #= # % 3 end
Module Module1 Const WIDTH = 81 Const HEIGHT = 5 Dim lines(HEIGHT, WIDTH) As Char Sub Init() For i = 0 To HEIGHT - 1 For j = 0 To WIDTH - 1 lines(i, j) = "*" Next Next End Sub Sub Cantor(start As Integer, len As Integer, index As Integer) Dim seg As Integer = len / 3 If seg = 0 Then Return End If For i = index To HEIGHT - 1 For j = start + seg To start + seg * 2 - 1 lines(i, j) = " " Next Next Cantor(start, seg, index + 1) Cantor(start + seg * 2, seg, index + 1) End Sub Sub Main() Init() Cantor(0, WIDTH, 1) For i = 0 To HEIGHT - 1 For j = 0 To WIDTH - 1 Console.Write(lines(i, j)) Next Console.WriteLine() Next End Sub End Module
Generate a VB translation of this REXX snippet without changing its computational steps.
w= linesize() if w==0 then w= 81 do lines=0; _ = 3 ** lines if _>w then leave #=_ end w= # $= copies('â– ', #) do j=0 until #==0 if j>0 then do k=#+1 by #+# to w $= overlay( left('', #), $, k) end say $ #= # % 3 end
Module Module1 Const WIDTH = 81 Const HEIGHT = 5 Dim lines(HEIGHT, WIDTH) As Char Sub Init() For i = 0 To HEIGHT - 1 For j = 0 To WIDTH - 1 lines(i, j) = "*" Next Next End Sub Sub Cantor(start As Integer, len As Integer, index As Integer) Dim seg As Integer = len / 3 If seg = 0 Then Return End If For i = index To HEIGHT - 1 For j = start + seg To start + seg * 2 - 1 lines(i, j) = " " Next Next Cantor(start, seg, index + 1) Cantor(start + seg * 2, seg, index + 1) End Sub Sub Main() Init() Cantor(0, WIDTH, 1) For i = 0 To HEIGHT - 1 For j = 0 To WIDTH - 1 Console.Write(lines(i, j)) Next Console.WriteLine() Next End Sub End Module
Convert the following code from REXX to Go, ensuring the logic remains intact.
w= linesize() if w==0 then w= 81 do lines=0; _ = 3 ** lines if _>w then leave #=_ end w= # $= copies('â– ', #) do j=0 until #==0 if j>0 then do k=#+1 by #+# to w $= overlay( left('', #), $, k) end say $ #= # % 3 end
package main import "fmt" const ( width = 81 height = 5 ) var lines [height][width]byte func init() { for i := 0; i < height; i++ { for j := 0; j < width; j++ { lines[i][j] = '*' } } } func cantor(start, len, index int) { seg := len / 3 if seg == 0 { return } for i := index; i < height; i++ { for j := start + seg; j < start + 2 * seg; j++ { lines[i][j] = ' ' } } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } func main() { cantor(0, width, 1) for _, line := range lines { fmt.Println(string(line[:])) } }
Port the following code from REXX to Go with equivalent syntax and logic.
w= linesize() if w==0 then w= 81 do lines=0; _ = 3 ** lines if _>w then leave #=_ end w= # $= copies('â– ', #) do j=0 until #==0 if j>0 then do k=#+1 by #+# to w $= overlay( left('', #), $, k) end say $ #= # % 3 end
package main import "fmt" const ( width = 81 height = 5 ) var lines [height][width]byte func init() { for i := 0; i < height; i++ { for j := 0; j < width; j++ { lines[i][j] = '*' } } } func cantor(start, len, index int) { seg := len / 3 if seg == 0 { return } for i := index; i < height; i++ { for j := start + seg; j < start + 2 * seg; j++ { lines[i][j] = ' ' } } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } func main() { cantor(0, width, 1) for _, line := range lines { fmt.Println(string(line[:])) } }
Convert the following code from Ruby to C, ensuring the logic remains intact.
lines = 5 (0..lines).each do |exp| seg_size = 3**(lines-exp-1) chars = (3**exp).times.map{ |n| n.digits(3).any?(1) ? " " : "â–ˆ"} puts chars.map{ |c| c * seg_size }.join end
#include <stdio.h> #define WIDTH 81 #define HEIGHT 5 char lines[HEIGHT][WIDTH]; void init() { int i, j; for (i = 0; i < HEIGHT; ++i) { for (j = 0; j < WIDTH; ++j) lines[i][j] = '*'; } } void cantor(int start, int len, int index) { int i, j, seg = len / 3; if (seg == 0) return; for (i = index; i < HEIGHT; ++i) { for (j = start + seg; j < start + seg * 2; ++j) lines[i][j] = ' '; } cantor(start, seg, index + 1); cantor(start + seg * 2, seg, index + 1); } void print() { int i, j; for (i = 0; i < HEIGHT; ++i) { for (j = 0; j < WIDTH; ++j) printf("%c", lines[i][j]); printf("\n"); } } int main() { init(); cantor(0, WIDTH, 1); print(); return 0; }
Produce a functionally identical C code for the snippet given in Ruby.
lines = 5 (0..lines).each do |exp| seg_size = 3**(lines-exp-1) chars = (3**exp).times.map{ |n| n.digits(3).any?(1) ? " " : "â–ˆ"} puts chars.map{ |c| c * seg_size }.join end
#include <stdio.h> #define WIDTH 81 #define HEIGHT 5 char lines[HEIGHT][WIDTH]; void init() { int i, j; for (i = 0; i < HEIGHT; ++i) { for (j = 0; j < WIDTH; ++j) lines[i][j] = '*'; } } void cantor(int start, int len, int index) { int i, j, seg = len / 3; if (seg == 0) return; for (i = index; i < HEIGHT; ++i) { for (j = start + seg; j < start + seg * 2; ++j) lines[i][j] = ' '; } cantor(start, seg, index + 1); cantor(start + seg * 2, seg, index + 1); } void print() { int i, j; for (i = 0; i < HEIGHT; ++i) { for (j = 0; j < WIDTH; ++j) printf("%c", lines[i][j]); printf("\n"); } } int main() { init(); cantor(0, WIDTH, 1); print(); return 0; }
Write a version of this Ruby function in C# with identical behavior.
lines = 5 (0..lines).each do |exp| seg_size = 3**(lines-exp-1) chars = (3**exp).times.map{ |n| n.digits(3).any?(1) ? " " : "â–ˆ"} puts chars.map{ |c| c * seg_size }.join end
using System; namespace CantorSet { class Program { const int WIDTH = 81; const int HEIGHT = 5; private static char[,] lines = new char[HEIGHT, WIDTH]; static Program() { for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { lines[i, j] = '*'; } } } private static void Cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { lines[i, j] = ' '; } } Cantor(start, seg, index + 1); Cantor(start + seg * 2, seg, index + 1); } static void Main(string[] args) { Cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { Console.Write(lines[i,j]); } Console.WriteLine(); } } } }
Preserve the algorithm and functionality while converting the code from Ruby to C#.
lines = 5 (0..lines).each do |exp| seg_size = 3**(lines-exp-1) chars = (3**exp).times.map{ |n| n.digits(3).any?(1) ? " " : "â–ˆ"} puts chars.map{ |c| c * seg_size }.join end
using System; namespace CantorSet { class Program { const int WIDTH = 81; const int HEIGHT = 5; private static char[,] lines = new char[HEIGHT, WIDTH]; static Program() { for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { lines[i, j] = '*'; } } } private static void Cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { lines[i, j] = ' '; } } Cantor(start, seg, index + 1); Cantor(start + seg * 2, seg, index + 1); } static void Main(string[] args) { Cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { Console.Write(lines[i,j]); } Console.WriteLine(); } } } }
Ensure the translated C++ code behaves exactly like the original Ruby snippet.
lines = 5 (0..lines).each do |exp| seg_size = 3**(lines-exp-1) chars = (3**exp).times.map{ |n| n.digits(3).any?(1) ? " " : "â–ˆ"} puts chars.map{ |c| c * seg_size }.join end
#include <iostream> const int WIDTH = 81; const int HEIGHT = 5; char lines[WIDTH*HEIGHT]; void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { int pos = i * WIDTH + j; lines[pos] = ' '; } } cantor(start, seg, index + 1); cantor(start + 2 * seg, seg, index + 1); } int main() { for (int i = 0; i < WIDTH*HEIGHT; i++) { lines[i] = '*'; } cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT*WIDTH; i += WIDTH) { printf("%.*s\n", WIDTH, lines + i); } return 0; }
Preserve the algorithm and functionality while converting the code from Ruby to C++.
lines = 5 (0..lines).each do |exp| seg_size = 3**(lines-exp-1) chars = (3**exp).times.map{ |n| n.digits(3).any?(1) ? " " : "â–ˆ"} puts chars.map{ |c| c * seg_size }.join end
#include <iostream> const int WIDTH = 81; const int HEIGHT = 5; char lines[WIDTH*HEIGHT]; void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { int pos = i * WIDTH + j; lines[pos] = ' '; } } cantor(start, seg, index + 1); cantor(start + 2 * seg, seg, index + 1); } int main() { for (int i = 0; i < WIDTH*HEIGHT; i++) { lines[i] = '*'; } cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT*WIDTH; i += WIDTH) { printf("%.*s\n", WIDTH, lines + i); } return 0; }
Ensure the translated Java code behaves exactly like the original Ruby snippet.
lines = 5 (0..lines).each do |exp| seg_size = 3**(lines-exp-1) chars = (3**exp).times.map{ |n| n.digits(3).any?(1) ? " " : "â–ˆ"} puts chars.map{ |c| c * seg_size }.join end
public class App { private static final int WIDTH = 81; private static final int HEIGHT = 5; private static char[][] lines; static { lines = new char[HEIGHT][WIDTH]; for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { lines[i][j] = '*'; } } } private static void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { lines[i][j] = ' '; } } cantor(start, seg, index + 1); cantor(start + seg * 2, seg, index + 1); } public static void main(String[] args) { cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { System.out.print(lines[i][j]); } System.out.println(); } } }
Write the same algorithm in Java as shown in this Ruby implementation.
lines = 5 (0..lines).each do |exp| seg_size = 3**(lines-exp-1) chars = (3**exp).times.map{ |n| n.digits(3).any?(1) ? " " : "â–ˆ"} puts chars.map{ |c| c * seg_size }.join end
public class App { private static final int WIDTH = 81; private static final int HEIGHT = 5; private static char[][] lines; static { lines = new char[HEIGHT][WIDTH]; for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { lines[i][j] = '*'; } } } private static void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { lines[i][j] = ' '; } } cantor(start, seg, index + 1); cantor(start + seg * 2, seg, index + 1); } public static void main(String[] args) { cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { System.out.print(lines[i][j]); } System.out.println(); } } }
Convert this Ruby snippet to Python and keep its semantics consistent.
lines = 5 (0..lines).each do |exp| seg_size = 3**(lines-exp-1) chars = (3**exp).times.map{ |n| n.digits(3).any?(1) ? " " : "â–ˆ"} puts chars.map{ |c| c * seg_size }.join end
WIDTH = 81 HEIGHT = 5 lines=[] def cantor(start, len, index): seg = len / 3 if seg == 0: return None for it in xrange(HEIGHT-index): i = index + it for jt in xrange(seg): j = start + seg + jt pos = i * WIDTH + j lines[pos] = ' ' cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) return None lines = ['*'] * (WIDTH*HEIGHT) cantor(0, WIDTH, 1) for i in xrange(HEIGHT): beg = WIDTH * i print ''.join(lines[beg : beg+WIDTH])
Rewrite the snippet below in Python so it works the same as the original Ruby code.
lines = 5 (0..lines).each do |exp| seg_size = 3**(lines-exp-1) chars = (3**exp).times.map{ |n| n.digits(3).any?(1) ? " " : "â–ˆ"} puts chars.map{ |c| c * seg_size }.join end
WIDTH = 81 HEIGHT = 5 lines=[] def cantor(start, len, index): seg = len / 3 if seg == 0: return None for it in xrange(HEIGHT-index): i = index + it for jt in xrange(seg): j = start + seg + jt pos = i * WIDTH + j lines[pos] = ' ' cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) return None lines = ['*'] * (WIDTH*HEIGHT) cantor(0, WIDTH, 1) for i in xrange(HEIGHT): beg = WIDTH * i print ''.join(lines[beg : beg+WIDTH])
Translate this program into VB but keep the logic exactly as in Ruby.
lines = 5 (0..lines).each do |exp| seg_size = 3**(lines-exp-1) chars = (3**exp).times.map{ |n| n.digits(3).any?(1) ? " " : "â–ˆ"} puts chars.map{ |c| c * seg_size }.join end
Module Module1 Const WIDTH = 81 Const HEIGHT = 5 Dim lines(HEIGHT, WIDTH) As Char Sub Init() For i = 0 To HEIGHT - 1 For j = 0 To WIDTH - 1 lines(i, j) = "*" Next Next End Sub Sub Cantor(start As Integer, len As Integer, index As Integer) Dim seg As Integer = len / 3 If seg = 0 Then Return End If For i = index To HEIGHT - 1 For j = start + seg To start + seg * 2 - 1 lines(i, j) = " " Next Next Cantor(start, seg, index + 1) Cantor(start + seg * 2, seg, index + 1) End Sub Sub Main() Init() Cantor(0, WIDTH, 1) For i = 0 To HEIGHT - 1 For j = 0 To WIDTH - 1 Console.Write(lines(i, j)) Next Console.WriteLine() Next End Sub End Module
Write the same code in VB as shown below in Ruby.
lines = 5 (0..lines).each do |exp| seg_size = 3**(lines-exp-1) chars = (3**exp).times.map{ |n| n.digits(3).any?(1) ? " " : "â–ˆ"} puts chars.map{ |c| c * seg_size }.join end
Module Module1 Const WIDTH = 81 Const HEIGHT = 5 Dim lines(HEIGHT, WIDTH) As Char Sub Init() For i = 0 To HEIGHT - 1 For j = 0 To WIDTH - 1 lines(i, j) = "*" Next Next End Sub Sub Cantor(start As Integer, len As Integer, index As Integer) Dim seg As Integer = len / 3 If seg = 0 Then Return End If For i = index To HEIGHT - 1 For j = start + seg To start + seg * 2 - 1 lines(i, j) = " " Next Next Cantor(start, seg, index + 1) Cantor(start + seg * 2, seg, index + 1) End Sub Sub Main() Init() Cantor(0, WIDTH, 1) For i = 0 To HEIGHT - 1 For j = 0 To WIDTH - 1 Console.Write(lines(i, j)) Next Console.WriteLine() Next End Sub End Module
Convert the following code from Ruby to Go, ensuring the logic remains intact.
lines = 5 (0..lines).each do |exp| seg_size = 3**(lines-exp-1) chars = (3**exp).times.map{ |n| n.digits(3).any?(1) ? " " : "â–ˆ"} puts chars.map{ |c| c * seg_size }.join end
package main import "fmt" const ( width = 81 height = 5 ) var lines [height][width]byte func init() { for i := 0; i < height; i++ { for j := 0; j < width; j++ { lines[i][j] = '*' } } } func cantor(start, len, index int) { seg := len / 3 if seg == 0 { return } for i := index; i < height; i++ { for j := start + seg; j < start + 2 * seg; j++ { lines[i][j] = ' ' } } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } func main() { cantor(0, width, 1) for _, line := range lines { fmt.Println(string(line[:])) } }
Generate a Go translation of this Ruby snippet without changing its computational steps.
lines = 5 (0..lines).each do |exp| seg_size = 3**(lines-exp-1) chars = (3**exp).times.map{ |n| n.digits(3).any?(1) ? " " : "â–ˆ"} puts chars.map{ |c| c * seg_size }.join end
package main import "fmt" const ( width = 81 height = 5 ) var lines [height][width]byte func init() { for i := 0; i < height; i++ { for j := 0; j < width; j++ { lines[i][j] = '*' } } } func cantor(start, len, index int) { seg := len / 3 if seg == 0 { return } for i := index; i < height; i++ { for j := start + seg; j < start + 2 * seg; j++ { lines[i][j] = ' ' } } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } func main() { cantor(0, width, 1) for _, line := range lines { fmt.Println(string(line[:])) } }
Write the same algorithm in C as shown in this Scala implementation.
const val WIDTH = 81 const val HEIGHT = 5 val lines = List(HEIGHT) { CharArray(WIDTH) { '*' } } fun cantor(start: Int, len: Int, index: Int) { val seg = len / 3 if (seg == 0) return for (i in index until HEIGHT) { for (j in start + seg until start + seg * 2) lines[i][j] = ' ' } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } fun main(args: Array<String>) { cantor(0, WIDTH, 1) lines.forEach { println(it) } }
#include <stdio.h> #define WIDTH 81 #define HEIGHT 5 char lines[HEIGHT][WIDTH]; void init() { int i, j; for (i = 0; i < HEIGHT; ++i) { for (j = 0; j < WIDTH; ++j) lines[i][j] = '*'; } } void cantor(int start, int len, int index) { int i, j, seg = len / 3; if (seg == 0) return; for (i = index; i < HEIGHT; ++i) { for (j = start + seg; j < start + seg * 2; ++j) lines[i][j] = ' '; } cantor(start, seg, index + 1); cantor(start + seg * 2, seg, index + 1); } void print() { int i, j; for (i = 0; i < HEIGHT; ++i) { for (j = 0; j < WIDTH; ++j) printf("%c", lines[i][j]); printf("\n"); } } int main() { init(); cantor(0, WIDTH, 1); print(); return 0; }
Port the following code from Scala to C with equivalent syntax and logic.
const val WIDTH = 81 const val HEIGHT = 5 val lines = List(HEIGHT) { CharArray(WIDTH) { '*' } } fun cantor(start: Int, len: Int, index: Int) { val seg = len / 3 if (seg == 0) return for (i in index until HEIGHT) { for (j in start + seg until start + seg * 2) lines[i][j] = ' ' } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } fun main(args: Array<String>) { cantor(0, WIDTH, 1) lines.forEach { println(it) } }
#include <stdio.h> #define WIDTH 81 #define HEIGHT 5 char lines[HEIGHT][WIDTH]; void init() { int i, j; for (i = 0; i < HEIGHT; ++i) { for (j = 0; j < WIDTH; ++j) lines[i][j] = '*'; } } void cantor(int start, int len, int index) { int i, j, seg = len / 3; if (seg == 0) return; for (i = index; i < HEIGHT; ++i) { for (j = start + seg; j < start + seg * 2; ++j) lines[i][j] = ' '; } cantor(start, seg, index + 1); cantor(start + seg * 2, seg, index + 1); } void print() { int i, j; for (i = 0; i < HEIGHT; ++i) { for (j = 0; j < WIDTH; ++j) printf("%c", lines[i][j]); printf("\n"); } } int main() { init(); cantor(0, WIDTH, 1); print(); return 0; }
Port the following code from Scala to C# with equivalent syntax and logic.
const val WIDTH = 81 const val HEIGHT = 5 val lines = List(HEIGHT) { CharArray(WIDTH) { '*' } } fun cantor(start: Int, len: Int, index: Int) { val seg = len / 3 if (seg == 0) return for (i in index until HEIGHT) { for (j in start + seg until start + seg * 2) lines[i][j] = ' ' } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } fun main(args: Array<String>) { cantor(0, WIDTH, 1) lines.forEach { println(it) } }
using System; namespace CantorSet { class Program { const int WIDTH = 81; const int HEIGHT = 5; private static char[,] lines = new char[HEIGHT, WIDTH]; static Program() { for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { lines[i, j] = '*'; } } } private static void Cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { lines[i, j] = ' '; } } Cantor(start, seg, index + 1); Cantor(start + seg * 2, seg, index + 1); } static void Main(string[] args) { Cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { Console.Write(lines[i,j]); } Console.WriteLine(); } } } }
Write a version of this Scala function in C# with identical behavior.
const val WIDTH = 81 const val HEIGHT = 5 val lines = List(HEIGHT) { CharArray(WIDTH) { '*' } } fun cantor(start: Int, len: Int, index: Int) { val seg = len / 3 if (seg == 0) return for (i in index until HEIGHT) { for (j in start + seg until start + seg * 2) lines[i][j] = ' ' } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } fun main(args: Array<String>) { cantor(0, WIDTH, 1) lines.forEach { println(it) } }
using System; namespace CantorSet { class Program { const int WIDTH = 81; const int HEIGHT = 5; private static char[,] lines = new char[HEIGHT, WIDTH]; static Program() { for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { lines[i, j] = '*'; } } } private static void Cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { lines[i, j] = ' '; } } Cantor(start, seg, index + 1); Cantor(start + seg * 2, seg, index + 1); } static void Main(string[] args) { Cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { Console.Write(lines[i,j]); } Console.WriteLine(); } } } }
Rewrite this program in C++ while keeping its functionality equivalent to the Scala version.
const val WIDTH = 81 const val HEIGHT = 5 val lines = List(HEIGHT) { CharArray(WIDTH) { '*' } } fun cantor(start: Int, len: Int, index: Int) { val seg = len / 3 if (seg == 0) return for (i in index until HEIGHT) { for (j in start + seg until start + seg * 2) lines[i][j] = ' ' } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } fun main(args: Array<String>) { cantor(0, WIDTH, 1) lines.forEach { println(it) } }
#include <iostream> const int WIDTH = 81; const int HEIGHT = 5; char lines[WIDTH*HEIGHT]; void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { int pos = i * WIDTH + j; lines[pos] = ' '; } } cantor(start, seg, index + 1); cantor(start + 2 * seg, seg, index + 1); } int main() { for (int i = 0; i < WIDTH*HEIGHT; i++) { lines[i] = '*'; } cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT*WIDTH; i += WIDTH) { printf("%.*s\n", WIDTH, lines + i); } return 0; }
Write the same code in C++ as shown below in Scala.
const val WIDTH = 81 const val HEIGHT = 5 val lines = List(HEIGHT) { CharArray(WIDTH) { '*' } } fun cantor(start: Int, len: Int, index: Int) { val seg = len / 3 if (seg == 0) return for (i in index until HEIGHT) { for (j in start + seg until start + seg * 2) lines[i][j] = ' ' } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } fun main(args: Array<String>) { cantor(0, WIDTH, 1) lines.forEach { println(it) } }
#include <iostream> const int WIDTH = 81; const int HEIGHT = 5; char lines[WIDTH*HEIGHT]; void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { int pos = i * WIDTH + j; lines[pos] = ' '; } } cantor(start, seg, index + 1); cantor(start + 2 * seg, seg, index + 1); } int main() { for (int i = 0; i < WIDTH*HEIGHT; i++) { lines[i] = '*'; } cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT*WIDTH; i += WIDTH) { printf("%.*s\n", WIDTH, lines + i); } return 0; }
Ensure the translated Java code behaves exactly like the original Scala snippet.
const val WIDTH = 81 const val HEIGHT = 5 val lines = List(HEIGHT) { CharArray(WIDTH) { '*' } } fun cantor(start: Int, len: Int, index: Int) { val seg = len / 3 if (seg == 0) return for (i in index until HEIGHT) { for (j in start + seg until start + seg * 2) lines[i][j] = ' ' } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } fun main(args: Array<String>) { cantor(0, WIDTH, 1) lines.forEach { println(it) } }
public class App { private static final int WIDTH = 81; private static final int HEIGHT = 5; private static char[][] lines; static { lines = new char[HEIGHT][WIDTH]; for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { lines[i][j] = '*'; } } } private static void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { lines[i][j] = ' '; } } cantor(start, seg, index + 1); cantor(start + seg * 2, seg, index + 1); } public static void main(String[] args) { cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { System.out.print(lines[i][j]); } System.out.println(); } } }
Convert this Scala snippet to Java and keep its semantics consistent.
const val WIDTH = 81 const val HEIGHT = 5 val lines = List(HEIGHT) { CharArray(WIDTH) { '*' } } fun cantor(start: Int, len: Int, index: Int) { val seg = len / 3 if (seg == 0) return for (i in index until HEIGHT) { for (j in start + seg until start + seg * 2) lines[i][j] = ' ' } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } fun main(args: Array<String>) { cantor(0, WIDTH, 1) lines.forEach { println(it) } }
public class App { private static final int WIDTH = 81; private static final int HEIGHT = 5; private static char[][] lines; static { lines = new char[HEIGHT][WIDTH]; for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { lines[i][j] = '*'; } } } private static void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { lines[i][j] = ' '; } } cantor(start, seg, index + 1); cantor(start + seg * 2, seg, index + 1); } public static void main(String[] args) { cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { System.out.print(lines[i][j]); } System.out.println(); } } }
Rewrite the snippet below in Python so it works the same as the original Scala code.
const val WIDTH = 81 const val HEIGHT = 5 val lines = List(HEIGHT) { CharArray(WIDTH) { '*' } } fun cantor(start: Int, len: Int, index: Int) { val seg = len / 3 if (seg == 0) return for (i in index until HEIGHT) { for (j in start + seg until start + seg * 2) lines[i][j] = ' ' } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } fun main(args: Array<String>) { cantor(0, WIDTH, 1) lines.forEach { println(it) } }
WIDTH = 81 HEIGHT = 5 lines=[] def cantor(start, len, index): seg = len / 3 if seg == 0: return None for it in xrange(HEIGHT-index): i = index + it for jt in xrange(seg): j = start + seg + jt pos = i * WIDTH + j lines[pos] = ' ' cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) return None lines = ['*'] * (WIDTH*HEIGHT) cantor(0, WIDTH, 1) for i in xrange(HEIGHT): beg = WIDTH * i print ''.join(lines[beg : beg+WIDTH])
Translate this program into Python but keep the logic exactly as in Scala.
const val WIDTH = 81 const val HEIGHT = 5 val lines = List(HEIGHT) { CharArray(WIDTH) { '*' } } fun cantor(start: Int, len: Int, index: Int) { val seg = len / 3 if (seg == 0) return for (i in index until HEIGHT) { for (j in start + seg until start + seg * 2) lines[i][j] = ' ' } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } fun main(args: Array<String>) { cantor(0, WIDTH, 1) lines.forEach { println(it) } }
WIDTH = 81 HEIGHT = 5 lines=[] def cantor(start, len, index): seg = len / 3 if seg == 0: return None for it in xrange(HEIGHT-index): i = index + it for jt in xrange(seg): j = start + seg + jt pos = i * WIDTH + j lines[pos] = ' ' cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) return None lines = ['*'] * (WIDTH*HEIGHT) cantor(0, WIDTH, 1) for i in xrange(HEIGHT): beg = WIDTH * i print ''.join(lines[beg : beg+WIDTH])
Translate the given Scala code snippet into VB without altering its behavior.
const val WIDTH = 81 const val HEIGHT = 5 val lines = List(HEIGHT) { CharArray(WIDTH) { '*' } } fun cantor(start: Int, len: Int, index: Int) { val seg = len / 3 if (seg == 0) return for (i in index until HEIGHT) { for (j in start + seg until start + seg * 2) lines[i][j] = ' ' } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } fun main(args: Array<String>) { cantor(0, WIDTH, 1) lines.forEach { println(it) } }
Module Module1 Const WIDTH = 81 Const HEIGHT = 5 Dim lines(HEIGHT, WIDTH) As Char Sub Init() For i = 0 To HEIGHT - 1 For j = 0 To WIDTH - 1 lines(i, j) = "*" Next Next End Sub Sub Cantor(start As Integer, len As Integer, index As Integer) Dim seg As Integer = len / 3 If seg = 0 Then Return End If For i = index To HEIGHT - 1 For j = start + seg To start + seg * 2 - 1 lines(i, j) = " " Next Next Cantor(start, seg, index + 1) Cantor(start + seg * 2, seg, index + 1) End Sub Sub Main() Init() Cantor(0, WIDTH, 1) For i = 0 To HEIGHT - 1 For j = 0 To WIDTH - 1 Console.Write(lines(i, j)) Next Console.WriteLine() Next End Sub End Module
Preserve the algorithm and functionality while converting the code from Scala to VB.
const val WIDTH = 81 const val HEIGHT = 5 val lines = List(HEIGHT) { CharArray(WIDTH) { '*' } } fun cantor(start: Int, len: Int, index: Int) { val seg = len / 3 if (seg == 0) return for (i in index until HEIGHT) { for (j in start + seg until start + seg * 2) lines[i][j] = ' ' } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } fun main(args: Array<String>) { cantor(0, WIDTH, 1) lines.forEach { println(it) } }
Module Module1 Const WIDTH = 81 Const HEIGHT = 5 Dim lines(HEIGHT, WIDTH) As Char Sub Init() For i = 0 To HEIGHT - 1 For j = 0 To WIDTH - 1 lines(i, j) = "*" Next Next End Sub Sub Cantor(start As Integer, len As Integer, index As Integer) Dim seg As Integer = len / 3 If seg = 0 Then Return End If For i = index To HEIGHT - 1 For j = start + seg To start + seg * 2 - 1 lines(i, j) = " " Next Next Cantor(start, seg, index + 1) Cantor(start + seg * 2, seg, index + 1) End Sub Sub Main() Init() Cantor(0, WIDTH, 1) For i = 0 To HEIGHT - 1 For j = 0 To WIDTH - 1 Console.Write(lines(i, j)) Next Console.WriteLine() Next End Sub End Module
Port the following code from Scala to Go with equivalent syntax and logic.
const val WIDTH = 81 const val HEIGHT = 5 val lines = List(HEIGHT) { CharArray(WIDTH) { '*' } } fun cantor(start: Int, len: Int, index: Int) { val seg = len / 3 if (seg == 0) return for (i in index until HEIGHT) { for (j in start + seg until start + seg * 2) lines[i][j] = ' ' } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } fun main(args: Array<String>) { cantor(0, WIDTH, 1) lines.forEach { println(it) } }
package main import "fmt" const ( width = 81 height = 5 ) var lines [height][width]byte func init() { for i := 0; i < height; i++ { for j := 0; j < width; j++ { lines[i][j] = '*' } } } func cantor(start, len, index int) { seg := len / 3 if seg == 0 { return } for i := index; i < height; i++ { for j := start + seg; j < start + 2 * seg; j++ { lines[i][j] = ' ' } } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } func main() { cantor(0, width, 1) for _, line := range lines { fmt.Println(string(line[:])) } }
Keep all operations the same but rewrite the snippet in Go.
const val WIDTH = 81 const val HEIGHT = 5 val lines = List(HEIGHT) { CharArray(WIDTH) { '*' } } fun cantor(start: Int, len: Int, index: Int) { val seg = len / 3 if (seg == 0) return for (i in index until HEIGHT) { for (j in start + seg until start + seg * 2) lines[i][j] = ' ' } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } fun main(args: Array<String>) { cantor(0, WIDTH, 1) lines.forEach { println(it) } }
package main import "fmt" const ( width = 81 height = 5 ) var lines [height][width]byte func init() { for i := 0; i < height; i++ { for j := 0; j < width; j++ { lines[i][j] = '*' } } } func cantor(start, len, index int) { seg := len / 3 if seg == 0 { return } for i := index; i < height; i++ { for j := start + seg; j < start + 2 * seg; j++ { lines[i][j] = ' ' } } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } func main() { cantor(0, width, 1) for _, line := range lines { fmt.Println(string(line[:])) } }
Convert this C snippet to Rust and keep its semantics consistent.
#include <stdio.h> #define WIDTH 81 #define HEIGHT 5 char lines[HEIGHT][WIDTH]; void init() { int i, j; for (i = 0; i < HEIGHT; ++i) { for (j = 0; j < WIDTH; ++j) lines[i][j] = '*'; } } void cantor(int start, int len, int index) { int i, j, seg = len / 3; if (seg == 0) return; for (i = index; i < HEIGHT; ++i) { for (j = start + seg; j < start + seg * 2; ++j) lines[i][j] = ' '; } cantor(start, seg, index + 1); cantor(start + seg * 2, seg, index + 1); } void print() { int i, j; for (i = 0; i < HEIGHT; ++i) { for (j = 0; j < WIDTH; ++j) printf("%c", lines[i][j]); printf("\n"); } } int main() { init(); cantor(0, WIDTH, 1); print(); return 0; }
use convert_base::Convert; use std::fmt; struct CantorSet { cells: Vec<Vec<bool>>, } fn number_to_vec(n: usize) -> Vec<u32> { n.to_string() .chars() .rev() .map(|c| c.to_digit(10).unwrap()) .collect() } impl CantorSet { fn new(lines: usize) -> CantorSet { let mut base = Convert::new(10, 3); let mut cells: Vec<Vec<bool>> = vec![]; for line in 0..lines { let segment_size = 3_usize.pow((lines - line - 1) as u32); let segment: Vec<bool> = (0..3_usize.pow(line as u32)) .map(|n| { let output = base.convert::<u32, u32>(&number_to_vec(n)); !output.contains(&1) }) .collect(); let mut accum: Vec<bool> = Vec::with_capacity(segment.len() * segment_size); for c in segment.iter() { accum.extend(std::iter::repeat(*c).take(segment_size)) } cells.push(accum); } CantorSet { cells } } } impl fmt::Display for CantorSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for line in self.cells.iter() { for c in line { write!(f, "{}", if *c { "â–ˆ" } else { " " })? } writeln!(f)?; } Ok(()) } } fn main() { let cs = CantorSet::new(5); println!("Cantor set:"); println!("{}", cs); }
Produce a language-to-language conversion: from C to Rust, same semantics.
#include <stdio.h> #define WIDTH 81 #define HEIGHT 5 char lines[HEIGHT][WIDTH]; void init() { int i, j; for (i = 0; i < HEIGHT; ++i) { for (j = 0; j < WIDTH; ++j) lines[i][j] = '*'; } } void cantor(int start, int len, int index) { int i, j, seg = len / 3; if (seg == 0) return; for (i = index; i < HEIGHT; ++i) { for (j = start + seg; j < start + seg * 2; ++j) lines[i][j] = ' '; } cantor(start, seg, index + 1); cantor(start + seg * 2, seg, index + 1); } void print() { int i, j; for (i = 0; i < HEIGHT; ++i) { for (j = 0; j < WIDTH; ++j) printf("%c", lines[i][j]); printf("\n"); } } int main() { init(); cantor(0, WIDTH, 1); print(); return 0; }
use convert_base::Convert; use std::fmt; struct CantorSet { cells: Vec<Vec<bool>>, } fn number_to_vec(n: usize) -> Vec<u32> { n.to_string() .chars() .rev() .map(|c| c.to_digit(10).unwrap()) .collect() } impl CantorSet { fn new(lines: usize) -> CantorSet { let mut base = Convert::new(10, 3); let mut cells: Vec<Vec<bool>> = vec![]; for line in 0..lines { let segment_size = 3_usize.pow((lines - line - 1) as u32); let segment: Vec<bool> = (0..3_usize.pow(line as u32)) .map(|n| { let output = base.convert::<u32, u32>(&number_to_vec(n)); !output.contains(&1) }) .collect(); let mut accum: Vec<bool> = Vec::with_capacity(segment.len() * segment_size); for c in segment.iter() { accum.extend(std::iter::repeat(*c).take(segment_size)) } cells.push(accum); } CantorSet { cells } } } impl fmt::Display for CantorSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for line in self.cells.iter() { for c in line { write!(f, "{}", if *c { "â–ˆ" } else { " " })? } writeln!(f)?; } Ok(()) } } fn main() { let cs = CantorSet::new(5); println!("Cantor set:"); println!("{}", cs); }
Write the same algorithm in Rust as shown in this C# implementation.
using System; namespace CantorSet { class Program { const int WIDTH = 81; const int HEIGHT = 5; private static char[,] lines = new char[HEIGHT, WIDTH]; static Program() { for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { lines[i, j] = '*'; } } } private static void Cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { lines[i, j] = ' '; } } Cantor(start, seg, index + 1); Cantor(start + seg * 2, seg, index + 1); } static void Main(string[] args) { Cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { Console.Write(lines[i,j]); } Console.WriteLine(); } } } }
use convert_base::Convert; use std::fmt; struct CantorSet { cells: Vec<Vec<bool>>, } fn number_to_vec(n: usize) -> Vec<u32> { n.to_string() .chars() .rev() .map(|c| c.to_digit(10).unwrap()) .collect() } impl CantorSet { fn new(lines: usize) -> CantorSet { let mut base = Convert::new(10, 3); let mut cells: Vec<Vec<bool>> = vec![]; for line in 0..lines { let segment_size = 3_usize.pow((lines - line - 1) as u32); let segment: Vec<bool> = (0..3_usize.pow(line as u32)) .map(|n| { let output = base.convert::<u32, u32>(&number_to_vec(n)); !output.contains(&1) }) .collect(); let mut accum: Vec<bool> = Vec::with_capacity(segment.len() * segment_size); for c in segment.iter() { accum.extend(std::iter::repeat(*c).take(segment_size)) } cells.push(accum); } CantorSet { cells } } } impl fmt::Display for CantorSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for line in self.cells.iter() { for c in line { write!(f, "{}", if *c { "â–ˆ" } else { " " })? } writeln!(f)?; } Ok(()) } } fn main() { let cs = CantorSet::new(5); println!("Cantor set:"); println!("{}", cs); }
Convert this C# block to Rust, preserving its control flow and logic.
using System; namespace CantorSet { class Program { const int WIDTH = 81; const int HEIGHT = 5; private static char[,] lines = new char[HEIGHT, WIDTH]; static Program() { for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { lines[i, j] = '*'; } } } private static void Cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { lines[i, j] = ' '; } } Cantor(start, seg, index + 1); Cantor(start + seg * 2, seg, index + 1); } static void Main(string[] args) { Cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { Console.Write(lines[i,j]); } Console.WriteLine(); } } } }
use convert_base::Convert; use std::fmt; struct CantorSet { cells: Vec<Vec<bool>>, } fn number_to_vec(n: usize) -> Vec<u32> { n.to_string() .chars() .rev() .map(|c| c.to_digit(10).unwrap()) .collect() } impl CantorSet { fn new(lines: usize) -> CantorSet { let mut base = Convert::new(10, 3); let mut cells: Vec<Vec<bool>> = vec![]; for line in 0..lines { let segment_size = 3_usize.pow((lines - line - 1) as u32); let segment: Vec<bool> = (0..3_usize.pow(line as u32)) .map(|n| { let output = base.convert::<u32, u32>(&number_to_vec(n)); !output.contains(&1) }) .collect(); let mut accum: Vec<bool> = Vec::with_capacity(segment.len() * segment_size); for c in segment.iter() { accum.extend(std::iter::repeat(*c).take(segment_size)) } cells.push(accum); } CantorSet { cells } } } impl fmt::Display for CantorSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for line in self.cells.iter() { for c in line { write!(f, "{}", if *c { "â–ˆ" } else { " " })? } writeln!(f)?; } Ok(()) } } fn main() { let cs = CantorSet::new(5); println!("Cantor set:"); println!("{}", cs); }
Port the provided Java code into Rust while preserving the original functionality.
public class App { private static final int WIDTH = 81; private static final int HEIGHT = 5; private static char[][] lines; static { lines = new char[HEIGHT][WIDTH]; for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { lines[i][j] = '*'; } } } private static void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { lines[i][j] = ' '; } } cantor(start, seg, index + 1); cantor(start + seg * 2, seg, index + 1); } public static void main(String[] args) { cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { System.out.print(lines[i][j]); } System.out.println(); } } }
use convert_base::Convert; use std::fmt; struct CantorSet { cells: Vec<Vec<bool>>, } fn number_to_vec(n: usize) -> Vec<u32> { n.to_string() .chars() .rev() .map(|c| c.to_digit(10).unwrap()) .collect() } impl CantorSet { fn new(lines: usize) -> CantorSet { let mut base = Convert::new(10, 3); let mut cells: Vec<Vec<bool>> = vec![]; for line in 0..lines { let segment_size = 3_usize.pow((lines - line - 1) as u32); let segment: Vec<bool> = (0..3_usize.pow(line as u32)) .map(|n| { let output = base.convert::<u32, u32>(&number_to_vec(n)); !output.contains(&1) }) .collect(); let mut accum: Vec<bool> = Vec::with_capacity(segment.len() * segment_size); for c in segment.iter() { accum.extend(std::iter::repeat(*c).take(segment_size)) } cells.push(accum); } CantorSet { cells } } } impl fmt::Display for CantorSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for line in self.cells.iter() { for c in line { write!(f, "{}", if *c { "â–ˆ" } else { " " })? } writeln!(f)?; } Ok(()) } } fn main() { let cs = CantorSet::new(5); println!("Cantor set:"); println!("{}", cs); }
Ensure the translated Rust code behaves exactly like the original Go snippet.
package main import "fmt" const ( width = 81 height = 5 ) var lines [height][width]byte func init() { for i := 0; i < height; i++ { for j := 0; j < width; j++ { lines[i][j] = '*' } } } func cantor(start, len, index int) { seg := len / 3 if seg == 0 { return } for i := index; i < height; i++ { for j := start + seg; j < start + 2 * seg; j++ { lines[i][j] = ' ' } } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } func main() { cantor(0, width, 1) for _, line := range lines { fmt.Println(string(line[:])) } }
use convert_base::Convert; use std::fmt; struct CantorSet { cells: Vec<Vec<bool>>, } fn number_to_vec(n: usize) -> Vec<u32> { n.to_string() .chars() .rev() .map(|c| c.to_digit(10).unwrap()) .collect() } impl CantorSet { fn new(lines: usize) -> CantorSet { let mut base = Convert::new(10, 3); let mut cells: Vec<Vec<bool>> = vec![]; for line in 0..lines { let segment_size = 3_usize.pow((lines - line - 1) as u32); let segment: Vec<bool> = (0..3_usize.pow(line as u32)) .map(|n| { let output = base.convert::<u32, u32>(&number_to_vec(n)); !output.contains(&1) }) .collect(); let mut accum: Vec<bool> = Vec::with_capacity(segment.len() * segment_size); for c in segment.iter() { accum.extend(std::iter::repeat(*c).take(segment_size)) } cells.push(accum); } CantorSet { cells } } } impl fmt::Display for CantorSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for line in self.cells.iter() { for c in line { write!(f, "{}", if *c { "â–ˆ" } else { " " })? } writeln!(f)?; } Ok(()) } } fn main() { let cs = CantorSet::new(5); println!("Cantor set:"); println!("{}", cs); }
Please provide an equivalent version of this Rust code in Python.
use convert_base::Convert; use std::fmt; struct CantorSet { cells: Vec<Vec<bool>>, } fn number_to_vec(n: usize) -> Vec<u32> { n.to_string() .chars() .rev() .map(|c| c.to_digit(10).unwrap()) .collect() } impl CantorSet { fn new(lines: usize) -> CantorSet { let mut base = Convert::new(10, 3); let mut cells: Vec<Vec<bool>> = vec![]; for line in 0..lines { let segment_size = 3_usize.pow((lines - line - 1) as u32); let segment: Vec<bool> = (0..3_usize.pow(line as u32)) .map(|n| { let output = base.convert::<u32, u32>(&number_to_vec(n)); !output.contains(&1) }) .collect(); let mut accum: Vec<bool> = Vec::with_capacity(segment.len() * segment_size); for c in segment.iter() { accum.extend(std::iter::repeat(*c).take(segment_size)) } cells.push(accum); } CantorSet { cells } } } impl fmt::Display for CantorSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for line in self.cells.iter() { for c in line { write!(f, "{}", if *c { "â–ˆ" } else { " " })? } writeln!(f)?; } Ok(()) } } fn main() { let cs = CantorSet::new(5); println!("Cantor set:"); println!("{}", cs); }
WIDTH = 81 HEIGHT = 5 lines=[] def cantor(start, len, index): seg = len / 3 if seg == 0: return None for it in xrange(HEIGHT-index): i = index + it for jt in xrange(seg): j = start + seg + jt pos = i * WIDTH + j lines[pos] = ' ' cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) return None lines = ['*'] * (WIDTH*HEIGHT) cantor(0, WIDTH, 1) for i in xrange(HEIGHT): beg = WIDTH * i print ''.join(lines[beg : beg+WIDTH])
Write the same algorithm in VB as shown in this Rust implementation.
use convert_base::Convert; use std::fmt; struct CantorSet { cells: Vec<Vec<bool>>, } fn number_to_vec(n: usize) -> Vec<u32> { n.to_string() .chars() .rev() .map(|c| c.to_digit(10).unwrap()) .collect() } impl CantorSet { fn new(lines: usize) -> CantorSet { let mut base = Convert::new(10, 3); let mut cells: Vec<Vec<bool>> = vec![]; for line in 0..lines { let segment_size = 3_usize.pow((lines - line - 1) as u32); let segment: Vec<bool> = (0..3_usize.pow(line as u32)) .map(|n| { let output = base.convert::<u32, u32>(&number_to_vec(n)); !output.contains(&1) }) .collect(); let mut accum: Vec<bool> = Vec::with_capacity(segment.len() * segment_size); for c in segment.iter() { accum.extend(std::iter::repeat(*c).take(segment_size)) } cells.push(accum); } CantorSet { cells } } } impl fmt::Display for CantorSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for line in self.cells.iter() { for c in line { write!(f, "{}", if *c { "â–ˆ" } else { " " })? } writeln!(f)?; } Ok(()) } } fn main() { let cs = CantorSet::new(5); println!("Cantor set:"); println!("{}", cs); }
Module Module1 Const WIDTH = 81 Const HEIGHT = 5 Dim lines(HEIGHT, WIDTH) As Char Sub Init() For i = 0 To HEIGHT - 1 For j = 0 To WIDTH - 1 lines(i, j) = "*" Next Next End Sub Sub Cantor(start As Integer, len As Integer, index As Integer) Dim seg As Integer = len / 3 If seg = 0 Then Return End If For i = index To HEIGHT - 1 For j = start + seg To start + seg * 2 - 1 lines(i, j) = " " Next Next Cantor(start, seg, index + 1) Cantor(start + seg * 2, seg, index + 1) End Sub Sub Main() Init() Cantor(0, WIDTH, 1) For i = 0 To HEIGHT - 1 For j = 0 To WIDTH - 1 Console.Write(lines(i, j)) Next Console.WriteLine() Next End Sub End Module
Port the provided Rust code into VB while preserving the original functionality.
use convert_base::Convert; use std::fmt; struct CantorSet { cells: Vec<Vec<bool>>, } fn number_to_vec(n: usize) -> Vec<u32> { n.to_string() .chars() .rev() .map(|c| c.to_digit(10).unwrap()) .collect() } impl CantorSet { fn new(lines: usize) -> CantorSet { let mut base = Convert::new(10, 3); let mut cells: Vec<Vec<bool>> = vec![]; for line in 0..lines { let segment_size = 3_usize.pow((lines - line - 1) as u32); let segment: Vec<bool> = (0..3_usize.pow(line as u32)) .map(|n| { let output = base.convert::<u32, u32>(&number_to_vec(n)); !output.contains(&1) }) .collect(); let mut accum: Vec<bool> = Vec::with_capacity(segment.len() * segment_size); for c in segment.iter() { accum.extend(std::iter::repeat(*c).take(segment_size)) } cells.push(accum); } CantorSet { cells } } } impl fmt::Display for CantorSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for line in self.cells.iter() { for c in line { write!(f, "{}", if *c { "â–ˆ" } else { " " })? } writeln!(f)?; } Ok(()) } } fn main() { let cs = CantorSet::new(5); println!("Cantor set:"); println!("{}", cs); }
Module Module1 Const WIDTH = 81 Const HEIGHT = 5 Dim lines(HEIGHT, WIDTH) As Char Sub Init() For i = 0 To HEIGHT - 1 For j = 0 To WIDTH - 1 lines(i, j) = "*" Next Next End Sub Sub Cantor(start As Integer, len As Integer, index As Integer) Dim seg As Integer = len / 3 If seg = 0 Then Return End If For i = index To HEIGHT - 1 For j = start + seg To start + seg * 2 - 1 lines(i, j) = " " Next Next Cantor(start, seg, index + 1) Cantor(start + seg * 2, seg, index + 1) End Sub Sub Main() Init() Cantor(0, WIDTH, 1) For i = 0 To HEIGHT - 1 For j = 0 To WIDTH - 1 Console.Write(lines(i, j)) Next Console.WriteLine() Next End Sub End Module
Keep all operations the same but rewrite the snippet in Rust.
#include <iostream> const int WIDTH = 81; const int HEIGHT = 5; char lines[WIDTH*HEIGHT]; void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { int pos = i * WIDTH + j; lines[pos] = ' '; } } cantor(start, seg, index + 1); cantor(start + 2 * seg, seg, index + 1); } int main() { for (int i = 0; i < WIDTH*HEIGHT; i++) { lines[i] = '*'; } cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT*WIDTH; i += WIDTH) { printf("%.*s\n", WIDTH, lines + i); } return 0; }
use convert_base::Convert; use std::fmt; struct CantorSet { cells: Vec<Vec<bool>>, } fn number_to_vec(n: usize) -> Vec<u32> { n.to_string() .chars() .rev() .map(|c| c.to_digit(10).unwrap()) .collect() } impl CantorSet { fn new(lines: usize) -> CantorSet { let mut base = Convert::new(10, 3); let mut cells: Vec<Vec<bool>> = vec![]; for line in 0..lines { let segment_size = 3_usize.pow((lines - line - 1) as u32); let segment: Vec<bool> = (0..3_usize.pow(line as u32)) .map(|n| { let output = base.convert::<u32, u32>(&number_to_vec(n)); !output.contains(&1) }) .collect(); let mut accum: Vec<bool> = Vec::with_capacity(segment.len() * segment_size); for c in segment.iter() { accum.extend(std::iter::repeat(*c).take(segment_size)) } cells.push(accum); } CantorSet { cells } } } impl fmt::Display for CantorSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for line in self.cells.iter() { for c in line { write!(f, "{}", if *c { "â–ˆ" } else { " " })? } writeln!(f)?; } Ok(()) } } fn main() { let cs = CantorSet::new(5); println!("Cantor set:"); println!("{}", cs); }
Generate an equivalent Rust version of this Java code.
public class App { private static final int WIDTH = 81; private static final int HEIGHT = 5; private static char[][] lines; static { lines = new char[HEIGHT][WIDTH]; for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { lines[i][j] = '*'; } } } private static void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { lines[i][j] = ' '; } } cantor(start, seg, index + 1); cantor(start + seg * 2, seg, index + 1); } public static void main(String[] args) { cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { System.out.print(lines[i][j]); } System.out.println(); } } }
use convert_base::Convert; use std::fmt; struct CantorSet { cells: Vec<Vec<bool>>, } fn number_to_vec(n: usize) -> Vec<u32> { n.to_string() .chars() .rev() .map(|c| c.to_digit(10).unwrap()) .collect() } impl CantorSet { fn new(lines: usize) -> CantorSet { let mut base = Convert::new(10, 3); let mut cells: Vec<Vec<bool>> = vec![]; for line in 0..lines { let segment_size = 3_usize.pow((lines - line - 1) as u32); let segment: Vec<bool> = (0..3_usize.pow(line as u32)) .map(|n| { let output = base.convert::<u32, u32>(&number_to_vec(n)); !output.contains(&1) }) .collect(); let mut accum: Vec<bool> = Vec::with_capacity(segment.len() * segment_size); for c in segment.iter() { accum.extend(std::iter::repeat(*c).take(segment_size)) } cells.push(accum); } CantorSet { cells } } } impl fmt::Display for CantorSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for line in self.cells.iter() { for c in line { write!(f, "{}", if *c { "â–ˆ" } else { " " })? } writeln!(f)?; } Ok(()) } } fn main() { let cs = CantorSet::new(5); println!("Cantor set:"); println!("{}", cs); }
Ensure the translated Rust code behaves exactly like the original Go snippet.
package main import "fmt" const ( width = 81 height = 5 ) var lines [height][width]byte func init() { for i := 0; i < height; i++ { for j := 0; j < width; j++ { lines[i][j] = '*' } } } func cantor(start, len, index int) { seg := len / 3 if seg == 0 { return } for i := index; i < height; i++ { for j := start + seg; j < start + 2 * seg; j++ { lines[i][j] = ' ' } } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } func main() { cantor(0, width, 1) for _, line := range lines { fmt.Println(string(line[:])) } }
use convert_base::Convert; use std::fmt; struct CantorSet { cells: Vec<Vec<bool>>, } fn number_to_vec(n: usize) -> Vec<u32> { n.to_string() .chars() .rev() .map(|c| c.to_digit(10).unwrap()) .collect() } impl CantorSet { fn new(lines: usize) -> CantorSet { let mut base = Convert::new(10, 3); let mut cells: Vec<Vec<bool>> = vec![]; for line in 0..lines { let segment_size = 3_usize.pow((lines - line - 1) as u32); let segment: Vec<bool> = (0..3_usize.pow(line as u32)) .map(|n| { let output = base.convert::<u32, u32>(&number_to_vec(n)); !output.contains(&1) }) .collect(); let mut accum: Vec<bool> = Vec::with_capacity(segment.len() * segment_size); for c in segment.iter() { accum.extend(std::iter::repeat(*c).take(segment_size)) } cells.push(accum); } CantorSet { cells } } } impl fmt::Display for CantorSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for line in self.cells.iter() { for c in line { write!(f, "{}", if *c { "â–ˆ" } else { " " })? } writeln!(f)?; } Ok(()) } } fn main() { let cs = CantorSet::new(5); println!("Cantor set:"); println!("{}", cs); }
Write the same algorithm in Python as shown in this Rust implementation.
use convert_base::Convert; use std::fmt; struct CantorSet { cells: Vec<Vec<bool>>, } fn number_to_vec(n: usize) -> Vec<u32> { n.to_string() .chars() .rev() .map(|c| c.to_digit(10).unwrap()) .collect() } impl CantorSet { fn new(lines: usize) -> CantorSet { let mut base = Convert::new(10, 3); let mut cells: Vec<Vec<bool>> = vec![]; for line in 0..lines { let segment_size = 3_usize.pow((lines - line - 1) as u32); let segment: Vec<bool> = (0..3_usize.pow(line as u32)) .map(|n| { let output = base.convert::<u32, u32>(&number_to_vec(n)); !output.contains(&1) }) .collect(); let mut accum: Vec<bool> = Vec::with_capacity(segment.len() * segment_size); for c in segment.iter() { accum.extend(std::iter::repeat(*c).take(segment_size)) } cells.push(accum); } CantorSet { cells } } } impl fmt::Display for CantorSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for line in self.cells.iter() { for c in line { write!(f, "{}", if *c { "â–ˆ" } else { " " })? } writeln!(f)?; } Ok(()) } } fn main() { let cs = CantorSet::new(5); println!("Cantor set:"); println!("{}", cs); }
WIDTH = 81 HEIGHT = 5 lines=[] def cantor(start, len, index): seg = len / 3 if seg == 0: return None for it in xrange(HEIGHT-index): i = index + it for jt in xrange(seg): j = start + seg + jt pos = i * WIDTH + j lines[pos] = ' ' cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) return None lines = ['*'] * (WIDTH*HEIGHT) cantor(0, WIDTH, 1) for i in xrange(HEIGHT): beg = WIDTH * i print ''.join(lines[beg : beg+WIDTH])
Change the programming language of this snippet from C++ to Rust without modifying what it does.
#include <iostream> const int WIDTH = 81; const int HEIGHT = 5; char lines[WIDTH*HEIGHT]; void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { int pos = i * WIDTH + j; lines[pos] = ' '; } } cantor(start, seg, index + 1); cantor(start + 2 * seg, seg, index + 1); } int main() { for (int i = 0; i < WIDTH*HEIGHT; i++) { lines[i] = '*'; } cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT*WIDTH; i += WIDTH) { printf("%.*s\n", WIDTH, lines + i); } return 0; }
use convert_base::Convert; use std::fmt; struct CantorSet { cells: Vec<Vec<bool>>, } fn number_to_vec(n: usize) -> Vec<u32> { n.to_string() .chars() .rev() .map(|c| c.to_digit(10).unwrap()) .collect() } impl CantorSet { fn new(lines: usize) -> CantorSet { let mut base = Convert::new(10, 3); let mut cells: Vec<Vec<bool>> = vec![]; for line in 0..lines { let segment_size = 3_usize.pow((lines - line - 1) as u32); let segment: Vec<bool> = (0..3_usize.pow(line as u32)) .map(|n| { let output = base.convert::<u32, u32>(&number_to_vec(n)); !output.contains(&1) }) .collect(); let mut accum: Vec<bool> = Vec::with_capacity(segment.len() * segment_size); for c in segment.iter() { accum.extend(std::iter::repeat(*c).take(segment_size)) } cells.push(accum); } CantorSet { cells } } } impl fmt::Display for CantorSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for line in self.cells.iter() { for c in line { write!(f, "{}", if *c { "â–ˆ" } else { " " })? } writeln!(f)?; } Ok(()) } } fn main() { let cs = CantorSet::new(5); println!("Cantor set:"); println!("{}", cs); }
Port the following code from Ada to C# with equivalent syntax and logic.
with Ada.Characters.Latin_1; with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO; procedure Put_PPM (File : File_Type; Picture : Image) is use Ada.Characters.Latin_1; Size : constant String := Integer'Image (Picture'Length (2)) & Integer'Image (Picture'Length (1)); Buffer : String (1..Picture'Length (2) * 3); Color : Pixel; Index : Positive; begin String'Write (Stream (File), "P6" & LF); String'Write (Stream (File), Size (2..Size'Last) & LF); String'Write (Stream (File), "255" & LF); for I in Picture'Range (1) loop Index := Buffer'First; for J in Picture'Range (2) loop Color := Picture (I, J); Buffer (Index) := Character'Val (Color.R); Buffer (Index + 1) := Character'Val (Color.G); Buffer (Index + 2) := Character'Val (Color.B); Index := Index + 3; end loop; String'Write (Stream (File), Buffer); end loop; Character'Write (Stream (File), LF); end Put_PPM;
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Generate a C translation of this Ada snippet without changing its computational steps.
with Ada.Characters.Latin_1; with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO; procedure Put_PPM (File : File_Type; Picture : Image) is use Ada.Characters.Latin_1; Size : constant String := Integer'Image (Picture'Length (2)) & Integer'Image (Picture'Length (1)); Buffer : String (1..Picture'Length (2) * 3); Color : Pixel; Index : Positive; begin String'Write (Stream (File), "P6" & LF); String'Write (Stream (File), Size (2..Size'Last) & LF); String'Write (Stream (File), "255" & LF); for I in Picture'Range (1) loop Index := Buffer'First; for J in Picture'Range (2) loop Color := Picture (I, J); Buffer (Index) := Character'Val (Color.R); Buffer (Index + 1) := Character'Val (Color.G); Buffer (Index + 2) := Character'Val (Color.B); Index := Index + 3; end loop; String'Write (Stream (File), Buffer); end loop; Character'Write (Stream (File), LF); end Put_PPM;
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
Write a version of this Ada function in C++ with identical behavior.
with Ada.Characters.Latin_1; with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO; procedure Put_PPM (File : File_Type; Picture : Image) is use Ada.Characters.Latin_1; Size : constant String := Integer'Image (Picture'Length (2)) & Integer'Image (Picture'Length (1)); Buffer : String (1..Picture'Length (2) * 3); Color : Pixel; Index : Positive; begin String'Write (Stream (File), "P6" & LF); String'Write (Stream (File), Size (2..Size'Last) & LF); String'Write (Stream (File), "255" & LF); for I in Picture'Range (1) loop Index := Buffer'First; for J in Picture'Range (2) loop Color := Picture (I, J); Buffer (Index) := Character'Val (Color.R); Buffer (Index + 1) := Character'Val (Color.G); Buffer (Index + 2) := Character'Val (Color.B); Index := Index + 3; end loop; String'Write (Stream (File), Buffer); end loop; Character'Write (Stream (File), LF); end Put_PPM;
#include <fstream> #include <cstdio> int main() { constexpr auto dimx = 800u, dimy = 800u; using namespace std; ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6" << endl << dimx << ' ' << dimy << endl << "255" << endl; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << (char) (i % 256) << (char) (j % 256) << (char) ((i * j) % 256); ofs.close(); return EXIT_SUCCESS; }
Translate this program into Go but keep the logic exactly as in Ada.
with Ada.Characters.Latin_1; with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO; procedure Put_PPM (File : File_Type; Picture : Image) is use Ada.Characters.Latin_1; Size : constant String := Integer'Image (Picture'Length (2)) & Integer'Image (Picture'Length (1)); Buffer : String (1..Picture'Length (2) * 3); Color : Pixel; Index : Positive; begin String'Write (Stream (File), "P6" & LF); String'Write (Stream (File), Size (2..Size'Last) & LF); String'Write (Stream (File), "255" & LF); for I in Picture'Range (1) loop Index := Buffer'First; for J in Picture'Range (2) loop Color := Picture (I, J); Buffer (Index) := Character'Val (Color.R); Buffer (Index + 1) := Character'Val (Color.G); Buffer (Index + 2) := Character'Val (Color.B); Index := Index + 3; end loop; String'Write (Stream (File), Buffer); end loop; Character'Write (Stream (File), LF); end Put_PPM;
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
Port the following code from Ada to Java with equivalent syntax and logic.
with Ada.Characters.Latin_1; with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO; procedure Put_PPM (File : File_Type; Picture : Image) is use Ada.Characters.Latin_1; Size : constant String := Integer'Image (Picture'Length (2)) & Integer'Image (Picture'Length (1)); Buffer : String (1..Picture'Length (2) * 3); Color : Pixel; Index : Positive; begin String'Write (Stream (File), "P6" & LF); String'Write (Stream (File), Size (2..Size'Last) & LF); String'Write (Stream (File), "255" & LF); for I in Picture'Range (1) loop Index := Buffer'First; for J in Picture'Range (2) loop Color := Picture (I, J); Buffer (Index) := Character'Val (Color.R); Buffer (Index + 1) := Character'Val (Color.G); Buffer (Index + 2) := Character'Val (Color.B); Index := Index + 3; end loop; String'Write (Stream (File), Buffer); end loop; Character'Write (Stream (File), LF); end Put_PPM;
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class PPMWriter { public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException { file.delete(); try (var os = new FileOutputStream(file, true); var bw = new BufferedOutputStream(os)) { var header = String.format("P6\n%d %d\n255\n", bitmap.getWidth(), bitmap.getHeight()); bw.write(header.getBytes(StandardCharsets.US_ASCII)); for (var y = 0; y < bitmap.getHeight(); y++) { for (var x = 0; x < bitmap.getWidth(); x++) { var pixel = bitmap.getPixel(x, y); bw.write(pixel.getRed()); bw.write(pixel.getGreen()); bw.write(pixel.getBlue()); } } } } }
Convert this Ada snippet to Python and keep its semantics consistent.
with Ada.Characters.Latin_1; with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO; procedure Put_PPM (File : File_Type; Picture : Image) is use Ada.Characters.Latin_1; Size : constant String := Integer'Image (Picture'Length (2)) & Integer'Image (Picture'Length (1)); Buffer : String (1..Picture'Length (2) * 3); Color : Pixel; Index : Positive; begin String'Write (Stream (File), "P6" & LF); String'Write (Stream (File), Size (2..Size'Last) & LF); String'Write (Stream (File), "255" & LF); for I in Picture'Range (1) loop Index := Buffer'First; for J in Picture'Range (2) loop Color := Picture (I, J); Buffer (Index) := Character'Val (Color.R); Buffer (Index + 1) := Character'Val (Color.G); Buffer (Index + 2) := Character'Val (Color.B); Index := Index + 3; end loop; String'Write (Stream (File), Buffer); end loop; Character'Write (Stream (File), LF); end Put_PPM;
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Translate the given Ada code snippet into VB without altering its behavior.
with Ada.Characters.Latin_1; with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO; procedure Put_PPM (File : File_Type; Picture : Image) is use Ada.Characters.Latin_1; Size : constant String := Integer'Image (Picture'Length (2)) & Integer'Image (Picture'Length (1)); Buffer : String (1..Picture'Length (2) * 3); Color : Pixel; Index : Positive; begin String'Write (Stream (File), "P6" & LF); String'Write (Stream (File), Size (2..Size'Last) & LF); String'Write (Stream (File), "255" & LF); for I in Picture'Range (1) loop Index := Buffer'First; for J in Picture'Range (2) loop Color := Picture (I, J); Buffer (Index) := Character'Val (Color.R); Buffer (Index + 1) := Character'Val (Color.G); Buffer (Index + 2) := Character'Val (Color.B); Index := Index + 3; end loop; String'Write (Stream (File), Buffer); end loop; Character'Write (Stream (File), LF); end Put_PPM;
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
Rewrite this program in C while keeping its functionality equivalent to the AutoHotKey version.
cyan := color(0,255,255)  cyanppm := Bitmap(10, 10, cyan)  Bitmap_write_ppm3(cyanppm, "cyan.ppm") run, cyan.ppm return #include bitmap_storage.ahk   Bitmap_write_ppm3(bitmap, filename) { file := FileOpen(filename, 0x11)  file.seek(0,0)  file.write("P3`n"   . bitmap.width . " " . bitmap.height . "`n" . "255`n") loop % bitmap.height { height := A_Index loop % bitmap.width { width := A_Index color := bitmap[height, width] file.Write(color.R . " ") file.Write(color.G . " ") file.Write(color.B . " ") } file.write("`n") } file.close() return 0 }
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
Change the following AutoHotKey code into C# without altering its purpose.
cyan := color(0,255,255)  cyanppm := Bitmap(10, 10, cyan)  Bitmap_write_ppm3(cyanppm, "cyan.ppm") run, cyan.ppm return #include bitmap_storage.ahk   Bitmap_write_ppm3(bitmap, filename) { file := FileOpen(filename, 0x11)  file.seek(0,0)  file.write("P3`n"   . bitmap.width . " " . bitmap.height . "`n" . "255`n") loop % bitmap.height { height := A_Index loop % bitmap.width { width := A_Index color := bitmap[height, width] file.Write(color.R . " ") file.Write(color.G . " ") file.Write(color.B . " ") } file.write("`n") } file.close() return 0 }
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Write the same algorithm in C++ as shown in this AutoHotKey implementation.
cyan := color(0,255,255)  cyanppm := Bitmap(10, 10, cyan)  Bitmap_write_ppm3(cyanppm, "cyan.ppm") run, cyan.ppm return #include bitmap_storage.ahk   Bitmap_write_ppm3(bitmap, filename) { file := FileOpen(filename, 0x11)  file.seek(0,0)  file.write("P3`n"   . bitmap.width . " " . bitmap.height . "`n" . "255`n") loop % bitmap.height { height := A_Index loop % bitmap.width { width := A_Index color := bitmap[height, width] file.Write(color.R . " ") file.Write(color.G . " ") file.Write(color.B . " ") } file.write("`n") } file.close() return 0 }
#include <fstream> int main() { constexpr auto dimx = 800u, dimy = 800u; std::ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6\n" << dimx << ' ' << dimy << "\n255\n"; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << static_cast<char>(i % 256) << static_cast<char>(j % 256) << static_cast<char>((i * j) % 256); }
Transform the following AutoHotKey implementation into Java, maintaining the same output and logic.
cyan := color(0,255,255)  cyanppm := Bitmap(10, 10, cyan)  Bitmap_write_ppm3(cyanppm, "cyan.ppm") run, cyan.ppm return #include bitmap_storage.ahk   Bitmap_write_ppm3(bitmap, filename) { file := FileOpen(filename, 0x11)  file.seek(0,0)  file.write("P3`n"   . bitmap.width . " " . bitmap.height . "`n" . "255`n") loop % bitmap.height { height := A_Index loop % bitmap.width { width := A_Index color := bitmap[height, width] file.Write(color.R . " ") file.Write(color.G . " ") file.Write(color.B . " ") } file.write("`n") } file.close() return 0 }
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class PPMWriter { public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException { file.delete(); try (var os = new FileOutputStream(file, true); var bw = new BufferedOutputStream(os)) { var header = String.format("P6\n%d %d\n255\n", bitmap.getWidth(), bitmap.getHeight()); bw.write(header.getBytes(StandardCharsets.US_ASCII)); for (var y = 0; y < bitmap.getHeight(); y++) { for (var x = 0; x < bitmap.getWidth(); x++) { var pixel = bitmap.getPixel(x, y); bw.write(pixel.getRed()); bw.write(pixel.getGreen()); bw.write(pixel.getBlue()); } } } } }
Ensure the translated Python code behaves exactly like the original AutoHotKey snippet.
cyan := color(0,255,255)  cyanppm := Bitmap(10, 10, cyan)  Bitmap_write_ppm3(cyanppm, "cyan.ppm") run, cyan.ppm return #include bitmap_storage.ahk   Bitmap_write_ppm3(bitmap, filename) { file := FileOpen(filename, 0x11)  file.seek(0,0)  file.write("P3`n"   . bitmap.width . " " . bitmap.height . "`n" . "255`n") loop % bitmap.height { height := A_Index loop % bitmap.width { width := A_Index color := bitmap[height, width] file.Write(color.R . " ") file.Write(color.G . " ") file.Write(color.B . " ") } file.write("`n") } file.close() return 0 }
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Port the provided AutoHotKey code into VB while preserving the original functionality.
cyan := color(0,255,255)  cyanppm := Bitmap(10, 10, cyan)  Bitmap_write_ppm3(cyanppm, "cyan.ppm") run, cyan.ppm return #include bitmap_storage.ahk   Bitmap_write_ppm3(bitmap, filename) { file := FileOpen(filename, 0x11)  file.seek(0,0)  file.write("P3`n"   . bitmap.width . " " . bitmap.height . "`n" . "255`n") loop % bitmap.height { height := A_Index loop % bitmap.width { width := A_Index color := bitmap[height, width] file.Write(color.R . " ") file.Write(color.G . " ") file.Write(color.B . " ") } file.write("`n") } file.close() return 0 }
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
Translate this program into Go but keep the logic exactly as in AutoHotKey.
cyan := color(0,255,255)  cyanppm := Bitmap(10, 10, cyan)  Bitmap_write_ppm3(cyanppm, "cyan.ppm") run, cyan.ppm return #include bitmap_storage.ahk   Bitmap_write_ppm3(bitmap, filename) { file := FileOpen(filename, 0x11)  file.seek(0,0)  file.write("P3`n"   . bitmap.width . " " . bitmap.height . "`n" . "255`n") loop % bitmap.height { height := A_Index loop % bitmap.width { width := A_Index color := bitmap[height, width] file.Write(color.R . " ") file.Write(color.G . " ") file.Write(color.B . " ") } file.write("`n") } file.close() return 0 }
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
Generate a C translation of this AWK snippet without changing its computational steps.
BEGIN { split("255,0,0,255,255,0",R,","); split("0,255,0,255,255,0",G,","); split("0,0,255,0,0,0",B,","); outfile = "P3.ppm"; printf("P3\n2 3\n255\n") >outfile; for (k=1; k<=length(R); k++) { printf("%3i %3i %3i\n",R[k],G[k],B[k])>outfile } close(outfile); }
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
Change the following AWK code into C# without altering its purpose.
BEGIN { split("255,0,0,255,255,0",R,","); split("0,255,0,255,255,0",G,","); split("0,0,255,0,0,0",B,","); outfile = "P3.ppm"; printf("P3\n2 3\n255\n") >outfile; for (k=1; k<=length(R); k++) { printf("%3i %3i %3i\n",R[k],G[k],B[k])>outfile } close(outfile); }
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Can you help me rewrite this code in C++ instead of AWK, keeping it the same logically?
BEGIN { split("255,0,0,255,255,0",R,","); split("0,255,0,255,255,0",G,","); split("0,0,255,0,0,0",B,","); outfile = "P3.ppm"; printf("P3\n2 3\n255\n") >outfile; for (k=1; k<=length(R); k++) { printf("%3i %3i %3i\n",R[k],G[k],B[k])>outfile } close(outfile); }
#include <fstream> int main() { constexpr auto dimx = 800u, dimy = 800u; std::ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6\n" << dimx << ' ' << dimy << "\n255\n"; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << static_cast<char>(i % 256) << static_cast<char>(j % 256) << static_cast<char>((i * j) % 256); }
Produce a functionally identical Java code for the snippet given in AWK.
BEGIN { split("255,0,0,255,255,0",R,","); split("0,255,0,255,255,0",G,","); split("0,0,255,0,0,0",B,","); outfile = "P3.ppm"; printf("P3\n2 3\n255\n") >outfile; for (k=1; k<=length(R); k++) { printf("%3i %3i %3i\n",R[k],G[k],B[k])>outfile } close(outfile); }
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class PPMWriter { public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException { file.delete(); try (var os = new FileOutputStream(file, true); var bw = new BufferedOutputStream(os)) { var header = String.format("P6\n%d %d\n255\n", bitmap.getWidth(), bitmap.getHeight()); bw.write(header.getBytes(StandardCharsets.US_ASCII)); for (var y = 0; y < bitmap.getHeight(); y++) { for (var x = 0; x < bitmap.getWidth(); x++) { var pixel = bitmap.getPixel(x, y); bw.write(pixel.getRed()); bw.write(pixel.getGreen()); bw.write(pixel.getBlue()); } } } } }
Transform the following AWK implementation into Python, maintaining the same output and logic.
BEGIN { split("255,0,0,255,255,0",R,","); split("0,255,0,255,255,0",G,","); split("0,0,255,0,0,0",B,","); outfile = "P3.ppm"; printf("P3\n2 3\n255\n") >outfile; for (k=1; k<=length(R); k++) { printf("%3i %3i %3i\n",R[k],G[k],B[k])>outfile } close(outfile); }
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Port the provided AWK code into VB while preserving the original functionality.
BEGIN { split("255,0,0,255,255,0",R,","); split("0,255,0,255,255,0",G,","); split("0,0,255,0,0,0",B,","); outfile = "P3.ppm"; printf("P3\n2 3\n255\n") >outfile; for (k=1; k<=length(R); k++) { printf("%3i %3i %3i\n",R[k],G[k],B[k])>outfile } close(outfile); }
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
Write the same algorithm in Go as shown in this AWK implementation.
BEGIN { split("255,0,0,255,255,0",R,","); split("0,255,0,255,255,0",G,","); split("0,0,255,0,0,0",B,","); outfile = "P3.ppm"; printf("P3\n2 3\n255\n") >outfile; for (k=1; k<=length(R); k++) { printf("%3i %3i %3i\n",R[k],G[k],B[k])>outfile } close(outfile); }
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
Write the same code in C as shown below in BBC_Basic.
Width% = 200 Height% = 200 VDU 23,22,Width%;Height%;8,16,16,128 *display c:\lena f% = OPENOUT("c:\lena.ppm") IF f%=0 ERROR 100, "Failed to open output file" BPUT #f%, "P6" BPUT #f%, "# Created using BBC BASIC" BPUT #f%, STR$(Width%) + " " +STR$(Height%) BPUT #f%, "255" FOR y% = Height%-1 TO 0 STEP -1 FOR x% = 0 TO Width%-1 rgb% = FNgetpixel(x%,y%) BPUT #f%, rgb% >> 16 BPUT #f%, (rgb% >> 8) AND &FF BPUT #f%, rgb% AND &FF NEXT NEXT y% CLOSE#f% END DEF FNgetpixel(x%,y%) LOCAL col% col% = TINT(x%*2,y%*2) SWAP ?^col%,?(^col%+2) = col%
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
Maintain the same structure and functionality when rewriting this code in C#.
Width% = 200 Height% = 200 VDU 23,22,Width%;Height%;8,16,16,128 *display c:\lena f% = OPENOUT("c:\lena.ppm") IF f%=0 ERROR 100, "Failed to open output file" BPUT #f%, "P6" BPUT #f%, "# Created using BBC BASIC" BPUT #f%, STR$(Width%) + " " +STR$(Height%) BPUT #f%, "255" FOR y% = Height%-1 TO 0 STEP -1 FOR x% = 0 TO Width%-1 rgb% = FNgetpixel(x%,y%) BPUT #f%, rgb% >> 16 BPUT #f%, (rgb% >> 8) AND &FF BPUT #f%, rgb% AND &FF NEXT NEXT y% CLOSE#f% END DEF FNgetpixel(x%,y%) LOCAL col% col% = TINT(x%*2,y%*2) SWAP ?^col%,?(^col%+2) = col%
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Ensure the translated C++ code behaves exactly like the original BBC_Basic snippet.
Width% = 200 Height% = 200 VDU 23,22,Width%;Height%;8,16,16,128 *display c:\lena f% = OPENOUT("c:\lena.ppm") IF f%=0 ERROR 100, "Failed to open output file" BPUT #f%, "P6" BPUT #f%, "# Created using BBC BASIC" BPUT #f%, STR$(Width%) + " " +STR$(Height%) BPUT #f%, "255" FOR y% = Height%-1 TO 0 STEP -1 FOR x% = 0 TO Width%-1 rgb% = FNgetpixel(x%,y%) BPUT #f%, rgb% >> 16 BPUT #f%, (rgb% >> 8) AND &FF BPUT #f%, rgb% AND &FF NEXT NEXT y% CLOSE#f% END DEF FNgetpixel(x%,y%) LOCAL col% col% = TINT(x%*2,y%*2) SWAP ?^col%,?(^col%+2) = col%
#include <fstream> int main() { constexpr auto dimx = 800u, dimy = 800u; std::ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6\n" << dimx << ' ' << dimy << "\n255\n"; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << static_cast<char>(i % 256) << static_cast<char>(j % 256) << static_cast<char>((i * j) % 256); }
Change the programming language of this snippet from BBC_Basic to Java without modifying what it does.
Width% = 200 Height% = 200 VDU 23,22,Width%;Height%;8,16,16,128 *display c:\lena f% = OPENOUT("c:\lena.ppm") IF f%=0 ERROR 100, "Failed to open output file" BPUT #f%, "P6" BPUT #f%, "# Created using BBC BASIC" BPUT #f%, STR$(Width%) + " " +STR$(Height%) BPUT #f%, "255" FOR y% = Height%-1 TO 0 STEP -1 FOR x% = 0 TO Width%-1 rgb% = FNgetpixel(x%,y%) BPUT #f%, rgb% >> 16 BPUT #f%, (rgb% >> 8) AND &FF BPUT #f%, rgb% AND &FF NEXT NEXT y% CLOSE#f% END DEF FNgetpixel(x%,y%) LOCAL col% col% = TINT(x%*2,y%*2) SWAP ?^col%,?(^col%+2) = col%
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class PPMWriter { public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException { file.delete(); try (var os = new FileOutputStream(file, true); var bw = new BufferedOutputStream(os)) { var header = String.format("P6\n%d %d\n255\n", bitmap.getWidth(), bitmap.getHeight()); bw.write(header.getBytes(StandardCharsets.US_ASCII)); for (var y = 0; y < bitmap.getHeight(); y++) { for (var x = 0; x < bitmap.getWidth(); x++) { var pixel = bitmap.getPixel(x, y); bw.write(pixel.getRed()); bw.write(pixel.getGreen()); bw.write(pixel.getBlue()); } } } } }
Transform the following BBC_Basic implementation into Python, maintaining the same output and logic.
Width% = 200 Height% = 200 VDU 23,22,Width%;Height%;8,16,16,128 *display c:\lena f% = OPENOUT("c:\lena.ppm") IF f%=0 ERROR 100, "Failed to open output file" BPUT #f%, "P6" BPUT #f%, "# Created using BBC BASIC" BPUT #f%, STR$(Width%) + " " +STR$(Height%) BPUT #f%, "255" FOR y% = Height%-1 TO 0 STEP -1 FOR x% = 0 TO Width%-1 rgb% = FNgetpixel(x%,y%) BPUT #f%, rgb% >> 16 BPUT #f%, (rgb% >> 8) AND &FF BPUT #f%, rgb% AND &FF NEXT NEXT y% CLOSE#f% END DEF FNgetpixel(x%,y%) LOCAL col% col% = TINT(x%*2,y%*2) SWAP ?^col%,?(^col%+2) = col%
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Keep all operations the same but rewrite the snippet in VB.
Width% = 200 Height% = 200 VDU 23,22,Width%;Height%;8,16,16,128 *display c:\lena f% = OPENOUT("c:\lena.ppm") IF f%=0 ERROR 100, "Failed to open output file" BPUT #f%, "P6" BPUT #f%, "# Created using BBC BASIC" BPUT #f%, STR$(Width%) + " " +STR$(Height%) BPUT #f%, "255" FOR y% = Height%-1 TO 0 STEP -1 FOR x% = 0 TO Width%-1 rgb% = FNgetpixel(x%,y%) BPUT #f%, rgb% >> 16 BPUT #f%, (rgb% >> 8) AND &FF BPUT #f%, rgb% AND &FF NEXT NEXT y% CLOSE#f% END DEF FNgetpixel(x%,y%) LOCAL col% col% = TINT(x%*2,y%*2) SWAP ?^col%,?(^col%+2) = col%
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
Rewrite the snippet below in Go so it works the same as the original BBC_Basic code.
Width% = 200 Height% = 200 VDU 23,22,Width%;Height%;8,16,16,128 *display c:\lena f% = OPENOUT("c:\lena.ppm") IF f%=0 ERROR 100, "Failed to open output file" BPUT #f%, "P6" BPUT #f%, "# Created using BBC BASIC" BPUT #f%, STR$(Width%) + " " +STR$(Height%) BPUT #f%, "255" FOR y% = Height%-1 TO 0 STEP -1 FOR x% = 0 TO Width%-1 rgb% = FNgetpixel(x%,y%) BPUT #f%, rgb% >> 16 BPUT #f%, (rgb% >> 8) AND &FF BPUT #f%, rgb% AND &FF NEXT NEXT y% CLOSE#f% END DEF FNgetpixel(x%,y%) LOCAL col% col% = TINT(x%*2,y%*2) SWAP ?^col%,?(^col%+2) = col%
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
Convert the following code from Common_Lisp to C, ensuring the logic remains intact.
(defun write-rgb-buffer-to-ppm-file (filename buffer) (with-open-file (stream filename :element-type '(unsigned-byte 8) :direction :output :if-does-not-exist :create :if-exists :supersede) (let* ((dimensions (array-dimensions buffer)) (width (first dimensions)) (height (second dimensions)) (header (format nil "P6~A~D ~D~A255~A" #\newline width height #\newline #\newline))) (loop :for char :across header :do (write-byte (char-code char) stream)) (loop :for x :upfrom 0 :below width :do (loop :for y :upfrom 0 :below height :do (let ((pixel (rgb-pixel buffer x y))) (let ((red (rgb-pixel-red pixel)) (green (rgb-pixel-green pixel)) (blue (rgb-pixel-blue pixel))) (write-byte red stream) (write-byte green stream) (write-byte blue stream))))))) filename)
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
Translate this program into C# but keep the logic exactly as in Common_Lisp.
(defun write-rgb-buffer-to-ppm-file (filename buffer) (with-open-file (stream filename :element-type '(unsigned-byte 8) :direction :output :if-does-not-exist :create :if-exists :supersede) (let* ((dimensions (array-dimensions buffer)) (width (first dimensions)) (height (second dimensions)) (header (format nil "P6~A~D ~D~A255~A" #\newline width height #\newline #\newline))) (loop :for char :across header :do (write-byte (char-code char) stream)) (loop :for x :upfrom 0 :below width :do (loop :for y :upfrom 0 :below height :do (let ((pixel (rgb-pixel buffer x y))) (let ((red (rgb-pixel-red pixel)) (green (rgb-pixel-green pixel)) (blue (rgb-pixel-blue pixel))) (write-byte red stream) (write-byte green stream) (write-byte blue stream))))))) filename)
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Rewrite this program in C++ while keeping its functionality equivalent to the Common_Lisp version.
(defun write-rgb-buffer-to-ppm-file (filename buffer) (with-open-file (stream filename :element-type '(unsigned-byte 8) :direction :output :if-does-not-exist :create :if-exists :supersede) (let* ((dimensions (array-dimensions buffer)) (width (first dimensions)) (height (second dimensions)) (header (format nil "P6~A~D ~D~A255~A" #\newline width height #\newline #\newline))) (loop :for char :across header :do (write-byte (char-code char) stream)) (loop :for x :upfrom 0 :below width :do (loop :for y :upfrom 0 :below height :do (let ((pixel (rgb-pixel buffer x y))) (let ((red (rgb-pixel-red pixel)) (green (rgb-pixel-green pixel)) (blue (rgb-pixel-blue pixel))) (write-byte red stream) (write-byte green stream) (write-byte blue stream))))))) filename)
#include <fstream> int main() { constexpr auto dimx = 800u, dimy = 800u; std::ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6\n" << dimx << ' ' << dimy << "\n255\n"; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << static_cast<char>(i % 256) << static_cast<char>(j % 256) << static_cast<char>((i * j) % 256); }
Convert the following code from Common_Lisp to Java, ensuring the logic remains intact.
(defun write-rgb-buffer-to-ppm-file (filename buffer) (with-open-file (stream filename :element-type '(unsigned-byte 8) :direction :output :if-does-not-exist :create :if-exists :supersede) (let* ((dimensions (array-dimensions buffer)) (width (first dimensions)) (height (second dimensions)) (header (format nil "P6~A~D ~D~A255~A" #\newline width height #\newline #\newline))) (loop :for char :across header :do (write-byte (char-code char) stream)) (loop :for x :upfrom 0 :below width :do (loop :for y :upfrom 0 :below height :do (let ((pixel (rgb-pixel buffer x y))) (let ((red (rgb-pixel-red pixel)) (green (rgb-pixel-green pixel)) (blue (rgb-pixel-blue pixel))) (write-byte red stream) (write-byte green stream) (write-byte blue stream))))))) filename)
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class PPMWriter { public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException { file.delete(); try (var os = new FileOutputStream(file, true); var bw = new BufferedOutputStream(os)) { var header = String.format("P6\n%d %d\n255\n", bitmap.getWidth(), bitmap.getHeight()); bw.write(header.getBytes(StandardCharsets.US_ASCII)); for (var y = 0; y < bitmap.getHeight(); y++) { for (var x = 0; x < bitmap.getWidth(); x++) { var pixel = bitmap.getPixel(x, y); bw.write(pixel.getRed()); bw.write(pixel.getGreen()); bw.write(pixel.getBlue()); } } } } }
Preserve the algorithm and functionality while converting the code from Common_Lisp to Python.
(defun write-rgb-buffer-to-ppm-file (filename buffer) (with-open-file (stream filename :element-type '(unsigned-byte 8) :direction :output :if-does-not-exist :create :if-exists :supersede) (let* ((dimensions (array-dimensions buffer)) (width (first dimensions)) (height (second dimensions)) (header (format nil "P6~A~D ~D~A255~A" #\newline width height #\newline #\newline))) (loop :for char :across header :do (write-byte (char-code char) stream)) (loop :for x :upfrom 0 :below width :do (loop :for y :upfrom 0 :below height :do (let ((pixel (rgb-pixel buffer x y))) (let ((red (rgb-pixel-red pixel)) (green (rgb-pixel-green pixel)) (blue (rgb-pixel-blue pixel))) (write-byte red stream) (write-byte green stream) (write-byte blue stream))))))) filename)
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Rewrite the snippet below in VB so it works the same as the original Common_Lisp code.
(defun write-rgb-buffer-to-ppm-file (filename buffer) (with-open-file (stream filename :element-type '(unsigned-byte 8) :direction :output :if-does-not-exist :create :if-exists :supersede) (let* ((dimensions (array-dimensions buffer)) (width (first dimensions)) (height (second dimensions)) (header (format nil "P6~A~D ~D~A255~A" #\newline width height #\newline #\newline))) (loop :for char :across header :do (write-byte (char-code char) stream)) (loop :for x :upfrom 0 :below width :do (loop :for y :upfrom 0 :below height :do (let ((pixel (rgb-pixel buffer x y))) (let ((red (rgb-pixel-red pixel)) (green (rgb-pixel-green pixel)) (blue (rgb-pixel-blue pixel))) (write-byte red stream) (write-byte green stream) (write-byte blue stream))))))) filename)
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
Write the same code in Go as shown below in Common_Lisp.
(defun write-rgb-buffer-to-ppm-file (filename buffer) (with-open-file (stream filename :element-type '(unsigned-byte 8) :direction :output :if-does-not-exist :create :if-exists :supersede) (let* ((dimensions (array-dimensions buffer)) (width (first dimensions)) (height (second dimensions)) (header (format nil "P6~A~D ~D~A255~A" #\newline width height #\newline #\newline))) (loop :for char :across header :do (write-byte (char-code char) stream)) (loop :for x :upfrom 0 :below width :do (loop :for y :upfrom 0 :below height :do (let ((pixel (rgb-pixel buffer x y))) (let ((red (rgb-pixel-red pixel)) (green (rgb-pixel-green pixel)) (blue (rgb-pixel-blue pixel))) (write-byte red stream) (write-byte green stream) (write-byte blue stream))))))) filename)
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
Write the same algorithm in C as shown in this Delphi implementation.
program btm2ppm; uses System.SysUtils, System.Classes, Vcl.Graphics; type TBitmapHelper = class helper for TBitmap public procedure SaveAsPPM(FileName: TFileName); end; procedure TBitmapHelper.SaveAsPPM(FileName: TFileName); var i, j, color: Integer; Header: AnsiString; ppm: TMemoryStream; begin ppm := TMemoryStream.Create; try Header := Format('P6'#10'%d %d'#10'255'#10, [Self.Width, Self.Height]); writeln(Header); ppm.Write(Tbytes(Header), Length(Header)); for i := 0 to Self.Height - 1 do for j := 0 to Self.Width - 1 do begin color := ColorToRGB(Self.Canvas.Pixels[i, j]); ppm.Write(color, 3); end; ppm.SaveToFile(FileName); finally ppm.Free; end; end; begin with TBitmap.Create do begin LoadFromFile('Input.bmp'); SaveAsPPM('Output.ppm'); Free; end; end.
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
Convert this Delphi snippet to C# and keep its semantics consistent.
program btm2ppm; uses System.SysUtils, System.Classes, Vcl.Graphics; type TBitmapHelper = class helper for TBitmap public procedure SaveAsPPM(FileName: TFileName); end; procedure TBitmapHelper.SaveAsPPM(FileName: TFileName); var i, j, color: Integer; Header: AnsiString; ppm: TMemoryStream; begin ppm := TMemoryStream.Create; try Header := Format('P6'#10'%d %d'#10'255'#10, [Self.Width, Self.Height]); writeln(Header); ppm.Write(Tbytes(Header), Length(Header)); for i := 0 to Self.Height - 1 do for j := 0 to Self.Width - 1 do begin color := ColorToRGB(Self.Canvas.Pixels[i, j]); ppm.Write(color, 3); end; ppm.SaveToFile(FileName); finally ppm.Free; end; end; begin with TBitmap.Create do begin LoadFromFile('Input.bmp'); SaveAsPPM('Output.ppm'); Free; end; end.
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Generate an equivalent C++ version of this Delphi code.
program btm2ppm; uses System.SysUtils, System.Classes, Vcl.Graphics; type TBitmapHelper = class helper for TBitmap public procedure SaveAsPPM(FileName: TFileName); end; procedure TBitmapHelper.SaveAsPPM(FileName: TFileName); var i, j, color: Integer; Header: AnsiString; ppm: TMemoryStream; begin ppm := TMemoryStream.Create; try Header := Format('P6'#10'%d %d'#10'255'#10, [Self.Width, Self.Height]); writeln(Header); ppm.Write(Tbytes(Header), Length(Header)); for i := 0 to Self.Height - 1 do for j := 0 to Self.Width - 1 do begin color := ColorToRGB(Self.Canvas.Pixels[i, j]); ppm.Write(color, 3); end; ppm.SaveToFile(FileName); finally ppm.Free; end; end; begin with TBitmap.Create do begin LoadFromFile('Input.bmp'); SaveAsPPM('Output.ppm'); Free; end; end.
#include <fstream> int main() { constexpr auto dimx = 800u, dimy = 800u; std::ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6\n" << dimx << ' ' << dimy << "\n255\n"; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << static_cast<char>(i % 256) << static_cast<char>(j % 256) << static_cast<char>((i * j) % 256); }
Convert the following code from Delphi to Java, ensuring the logic remains intact.
program btm2ppm; uses System.SysUtils, System.Classes, Vcl.Graphics; type TBitmapHelper = class helper for TBitmap public procedure SaveAsPPM(FileName: TFileName); end; procedure TBitmapHelper.SaveAsPPM(FileName: TFileName); var i, j, color: Integer; Header: AnsiString; ppm: TMemoryStream; begin ppm := TMemoryStream.Create; try Header := Format('P6'#10'%d %d'#10'255'#10, [Self.Width, Self.Height]); writeln(Header); ppm.Write(Tbytes(Header), Length(Header)); for i := 0 to Self.Height - 1 do for j := 0 to Self.Width - 1 do begin color := ColorToRGB(Self.Canvas.Pixels[i, j]); ppm.Write(color, 3); end; ppm.SaveToFile(FileName); finally ppm.Free; end; end; begin with TBitmap.Create do begin LoadFromFile('Input.bmp'); SaveAsPPM('Output.ppm'); Free; end; end.
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class PPMWriter { public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException { file.delete(); try (var os = new FileOutputStream(file, true); var bw = new BufferedOutputStream(os)) { var header = String.format("P6\n%d %d\n255\n", bitmap.getWidth(), bitmap.getHeight()); bw.write(header.getBytes(StandardCharsets.US_ASCII)); for (var y = 0; y < bitmap.getHeight(); y++) { for (var x = 0; x < bitmap.getWidth(); x++) { var pixel = bitmap.getPixel(x, y); bw.write(pixel.getRed()); bw.write(pixel.getGreen()); bw.write(pixel.getBlue()); } } } } }