Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write a version of this REXX function in C with identical behavior. |
green = 00ff00
parse arg oFN width height color .
if oFN=='' | oFN=="," then oFN='IMAGE'
if width=='' | width=="," then width= 20
if height=='' | height=="," then height= 20
if color=='' | color=="," then color= green
oFID= oFN'.PPM'
@. = x2c(color)
$ = '9'x
# = 255
call charout oFID, , 1
call charout oFID,'P6'width || $ || height || $ || # || $
_=
do j =1 for width
do k=1 for height; _= _ || @.j.k
end
end
call charout oFID, _
call charout oFID
| #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;
}
|
Ensure the translated C# code behaves exactly like the original REXX snippet. |
green = 00ff00
parse arg oFN width height color .
if oFN=='' | oFN=="," then oFN='IMAGE'
if width=='' | width=="," then width= 20
if height=='' | height=="," then height= 20
if color=='' | color=="," then color= green
oFID= oFN'.PPM'
@. = x2c(color)
$ = '9'x
# = 255
call charout oFID, , 1
call charout oFID,'P6'width || $ || height || $ || # || $
_=
do j =1 for width
do k=1 for height; _= _ || @.j.k
end
end
call charout oFID, _
call charout oFID
| 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();
}
}
|
Change the following REXX code into C++ without altering its purpose. |
green = 00ff00
parse arg oFN width height color .
if oFN=='' | oFN=="," then oFN='IMAGE'
if width=='' | width=="," then width= 20
if height=='' | height=="," then height= 20
if color=='' | color=="," then color= green
oFID= oFN'.PPM'
@. = x2c(color)
$ = '9'x
# = 255
call charout oFID, , 1
call charout oFID,'P6'width || $ || height || $ || # || $
_=
do j =1 for width
do k=1 for height; _= _ || @.j.k
end
end
call charout oFID, _
call charout oFID
| #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);
}
|
Preserve the algorithm and functionality while converting the code from REXX to Java. |
green = 00ff00
parse arg oFN width height color .
if oFN=='' | oFN=="," then oFN='IMAGE'
if width=='' | width=="," then width= 20
if height=='' | height=="," then height= 20
if color=='' | color=="," then color= green
oFID= oFN'.PPM'
@. = x2c(color)
$ = '9'x
# = 255
call charout oFID, , 1
call charout oFID,'P6'width || $ || height || $ || # || $
_=
do j =1 for width
do k=1 for height; _= _ || @.j.k
end
end
call charout oFID, _
call charout oFID
| 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());
}
}
}
}
}
|
Translate this program into Python but keep the logic exactly as in REXX. |
green = 00ff00
parse arg oFN width height color .
if oFN=='' | oFN=="," then oFN='IMAGE'
if width=='' | width=="," then width= 20
if height=='' | height=="," then height= 20
if color=='' | color=="," then color= green
oFID= oFN'.PPM'
@. = x2c(color)
$ = '9'x
# = 255
call charout oFID, , 1
call charout oFID,'P6'width || $ || height || $ || # || $
_=
do j =1 for width
do k=1 for height; _= _ || @.j.k
end
end
call charout oFID, _
call charout oFID
|
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()
|
Change the following REXX code into VB without altering its purpose. |
green = 00ff00
parse arg oFN width height color .
if oFN=='' | oFN=="," then oFN='IMAGE'
if width=='' | width=="," then width= 20
if height=='' | height=="," then height= 20
if color=='' | color=="," then color= green
oFID= oFN'.PPM'
@. = x2c(color)
$ = '9'x
# = 255
call charout oFID, , 1
call charout oFID,'P6'width || $ || height || $ || # || $
_=
do j =1 for width
do k=1 for height; _= _ || @.j.k
end
end
call charout oFID, _
call charout oFID
| 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 a version of this REXX function in Go with identical behavior. |
green = 00ff00
parse arg oFN width height color .
if oFN=='' | oFN=="," then oFN='IMAGE'
if width=='' | width=="," then width= 20
if height=='' | height=="," then height= 20
if color=='' | color=="," then color= green
oFID= oFN'.PPM'
@. = x2c(color)
$ = '9'x
# = 255
call charout oFID, , 1
call charout oFID,'P6'width || $ || height || $ || # || $
_=
do j =1 for width
do k=1 for height; _= _ || @.j.k
end
end
call charout oFID, _
call charout oFID
| 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()
}
|
Can you help me rewrite this code in C instead of Ruby, keeping it the same logically? | class RGBColour
def values
[@red, @green, @blue]
end
end
class Pixmap
def save(filename)
File.open(filename, 'w') do |f|
f.puts "P6", "
f.binmode
@height.times do |y|
@width.times do |x|
f.print @data[x][y].values.pack('C3')
end
end
end
end
alias_method :write, :save
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;
}
|
Translate the given Ruby code snippet into C# without altering its behavior. | class RGBColour
def values
[@red, @green, @blue]
end
end
class Pixmap
def save(filename)
File.open(filename, 'w') do |f|
f.puts "P6", "
f.binmode
@height.times do |y|
@width.times do |x|
f.print @data[x][y].values.pack('C3')
end
end
end
end
alias_method :write, :save
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();
}
}
|
Write a version of this Ruby function in C++ with identical behavior. | class RGBColour
def values
[@red, @green, @blue]
end
end
class Pixmap
def save(filename)
File.open(filename, 'w') do |f|
f.puts "P6", "
f.binmode
@height.times do |y|
@width.times do |x|
f.print @data[x][y].values.pack('C3')
end
end
end
end
alias_method :write, :save
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);
}
|
Write a version of this Ruby function in Java with identical behavior. | class RGBColour
def values
[@red, @green, @blue]
end
end
class Pixmap
def save(filename)
File.open(filename, 'w') do |f|
f.puts "P6", "
f.binmode
@height.times do |y|
@width.times do |x|
f.print @data[x][y].values.pack('C3')
end
end
end
end
alias_method :write, :save
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());
}
}
}
}
}
|
Keep all operations the same but rewrite the snippet in Python. | class RGBColour
def values
[@red, @green, @blue]
end
end
class Pixmap
def save(filename)
File.open(filename, 'w') do |f|
f.puts "P6", "
f.binmode
@height.times do |y|
@width.times do |x|
f.print @data[x][y].values.pack('C3')
end
end
end
end
alias_method :write, :save
end
|
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()
|
Write a version of this Ruby function in VB with identical behavior. | class RGBColour
def values
[@red, @green, @blue]
end
end
class Pixmap
def save(filename)
File.open(filename, 'w') do |f|
f.puts "P6", "
f.binmode
@height.times do |y|
@width.times do |x|
f.print @data[x][y].values.pack('C3')
end
end
end
end
alias_method :write, :save
end
| 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 Ruby code. | class RGBColour
def values
[@red, @green, @blue]
end
end
class Pixmap
def save(filename)
File.open(filename, 'w') do |f|
f.puts "P6", "
f.binmode
@height.times do |y|
@width.times do |x|
f.print @data[x][y].values.pack('C3')
end
end
end
end
alias_method :write, :save
end
| 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()
}
|
Change the programming language of this snippet from Scala to C without modifying what it does. |
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
import java.io.FileOutputStream
class BasicBitmapStorage(width: Int, height: Int) {
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
fun fill(c: Color) {
val g = image.graphics
g.color = c
g.fillRect(0, 0, image.width, image.height)
}
fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())
fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))
}
fun main(args: Array<String>) {
val width = 640
val height = 640
val bbs = BasicBitmapStorage(width, height)
for (y in 0 until height) {
for (x in 0 until width) {
val c = Color(x % 256, y % 256, (x * y) % 256)
bbs.setPixel(x, y, c)
}
}
val fos = FileOutputStream("output.ppm")
val buffer = ByteArray(width * 3)
fos.use {
val header = "P6\n$width $height\n255\n".toByteArray()
with (it) {
write(header)
for (y in 0 until height) {
for (x in 0 until width) {
val c = bbs.getPixel(x, y)
buffer[x * 3] = c.red.toByte()
buffer[x * 3 + 1] = c.green.toByte()
buffer[x * 3 + 2] = c.blue.toByte()
}
write(buffer)
}
}
}
}
| #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;
}
|
Can you help me rewrite this code in C# instead of Scala, keeping it the same logically? |
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
import java.io.FileOutputStream
class BasicBitmapStorage(width: Int, height: Int) {
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
fun fill(c: Color) {
val g = image.graphics
g.color = c
g.fillRect(0, 0, image.width, image.height)
}
fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())
fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))
}
fun main(args: Array<String>) {
val width = 640
val height = 640
val bbs = BasicBitmapStorage(width, height)
for (y in 0 until height) {
for (x in 0 until width) {
val c = Color(x % 256, y % 256, (x * y) % 256)
bbs.setPixel(x, y, c)
}
}
val fos = FileOutputStream("output.ppm")
val buffer = ByteArray(width * 3)
fos.use {
val header = "P6\n$width $height\n255\n".toByteArray()
with (it) {
write(header)
for (y in 0 until height) {
for (x in 0 until width) {
val c = bbs.getPixel(x, y)
buffer[x * 3] = c.red.toByte()
buffer[x * 3 + 1] = c.green.toByte()
buffer[x * 3 + 2] = c.blue.toByte()
}
write(buffer)
}
}
}
}
| 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();
}
}
|
Translate this program into C++ but keep the logic exactly as in Scala. |
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
import java.io.FileOutputStream
class BasicBitmapStorage(width: Int, height: Int) {
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
fun fill(c: Color) {
val g = image.graphics
g.color = c
g.fillRect(0, 0, image.width, image.height)
}
fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())
fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))
}
fun main(args: Array<String>) {
val width = 640
val height = 640
val bbs = BasicBitmapStorage(width, height)
for (y in 0 until height) {
for (x in 0 until width) {
val c = Color(x % 256, y % 256, (x * y) % 256)
bbs.setPixel(x, y, c)
}
}
val fos = FileOutputStream("output.ppm")
val buffer = ByteArray(width * 3)
fos.use {
val header = "P6\n$width $height\n255\n".toByteArray()
with (it) {
write(header)
for (y in 0 until height) {
for (x in 0 until width) {
val c = bbs.getPixel(x, y)
buffer[x * 3] = c.red.toByte()
buffer[x * 3 + 1] = c.green.toByte()
buffer[x * 3 + 2] = c.blue.toByte()
}
write(buffer)
}
}
}
}
| #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);
}
|
Please provide an equivalent version of this Scala code in Java. |
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
import java.io.FileOutputStream
class BasicBitmapStorage(width: Int, height: Int) {
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
fun fill(c: Color) {
val g = image.graphics
g.color = c
g.fillRect(0, 0, image.width, image.height)
}
fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())
fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))
}
fun main(args: Array<String>) {
val width = 640
val height = 640
val bbs = BasicBitmapStorage(width, height)
for (y in 0 until height) {
for (x in 0 until width) {
val c = Color(x % 256, y % 256, (x * y) % 256)
bbs.setPixel(x, y, c)
}
}
val fos = FileOutputStream("output.ppm")
val buffer = ByteArray(width * 3)
fos.use {
val header = "P6\n$width $height\n255\n".toByteArray()
with (it) {
write(header)
for (y in 0 until height) {
for (x in 0 until width) {
val c = bbs.getPixel(x, y)
buffer[x * 3] = c.red.toByte()
buffer[x * 3 + 1] = c.green.toByte()
buffer[x * 3 + 2] = c.blue.toByte()
}
write(buffer)
}
}
}
}
| 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());
}
}
}
}
}
|
Translate the given Scala code snippet into Python without altering its behavior. |
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
import java.io.FileOutputStream
class BasicBitmapStorage(width: Int, height: Int) {
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
fun fill(c: Color) {
val g = image.graphics
g.color = c
g.fillRect(0, 0, image.width, image.height)
}
fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())
fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))
}
fun main(args: Array<String>) {
val width = 640
val height = 640
val bbs = BasicBitmapStorage(width, height)
for (y in 0 until height) {
for (x in 0 until width) {
val c = Color(x % 256, y % 256, (x * y) % 256)
bbs.setPixel(x, y, c)
}
}
val fos = FileOutputStream("output.ppm")
val buffer = ByteArray(width * 3)
fos.use {
val header = "P6\n$width $height\n255\n".toByteArray()
with (it) {
write(header)
for (y in 0 until height) {
for (x in 0 until width) {
val c = bbs.getPixel(x, y)
buffer[x * 3] = c.red.toByte()
buffer[x * 3 + 1] = c.green.toByte()
buffer[x * 3 + 2] = c.blue.toByte()
}
write(buffer)
}
}
}
}
|
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 Scala code snippet into VB without altering its behavior. |
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
import java.io.FileOutputStream
class BasicBitmapStorage(width: Int, height: Int) {
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
fun fill(c: Color) {
val g = image.graphics
g.color = c
g.fillRect(0, 0, image.width, image.height)
}
fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())
fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))
}
fun main(args: Array<String>) {
val width = 640
val height = 640
val bbs = BasicBitmapStorage(width, height)
for (y in 0 until height) {
for (x in 0 until width) {
val c = Color(x % 256, y % 256, (x * y) % 256)
bbs.setPixel(x, y, c)
}
}
val fos = FileOutputStream("output.ppm")
val buffer = ByteArray(width * 3)
fos.use {
val header = "P6\n$width $height\n255\n".toByteArray()
with (it) {
write(header)
for (y in 0 until height) {
for (x in 0 until width) {
val c = bbs.getPixel(x, y)
buffer[x * 3] = c.red.toByte()
buffer[x * 3 + 1] = c.green.toByte()
buffer[x * 3 + 2] = c.blue.toByte()
}
write(buffer)
}
}
}
}
| 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
|
Transform the following Scala implementation into Go, maintaining the same output and logic. |
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
import java.io.FileOutputStream
class BasicBitmapStorage(width: Int, height: Int) {
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
fun fill(c: Color) {
val g = image.graphics
g.color = c
g.fillRect(0, 0, image.width, image.height)
}
fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())
fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))
}
fun main(args: Array<String>) {
val width = 640
val height = 640
val bbs = BasicBitmapStorage(width, height)
for (y in 0 until height) {
for (x in 0 until width) {
val c = Color(x % 256, y % 256, (x * y) % 256)
bbs.setPixel(x, y, c)
}
}
val fos = FileOutputStream("output.ppm")
val buffer = ByteArray(width * 3)
fos.use {
val header = "P6\n$width $height\n255\n".toByteArray()
with (it) {
write(header)
for (y in 0 until height) {
for (x in 0 until width) {
val c = bbs.getPixel(x, y)
buffer[x * 3] = c.red.toByte()
buffer[x * 3 + 1] = c.green.toByte()
buffer[x * 3 + 2] = c.blue.toByte()
}
write(buffer)
}
}
}
}
| 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()
}
|
Ensure the translated C code behaves exactly like the original Tcl snippet. | package require Tk
proc output_ppm {image filename} {
$image write $filename -format ppm
}
set img [newImage 150 150]
fill $img red
setPixel $img green 40 40
output_ppm $img filename.ppm
set fh [open filename.ppm]
puts [gets $fh] ;
puts [gets $fh] ;
puts [gets $fh] ;
binary scan [read $fh 3] c3 pixel
foreach colour $pixel {puts [expr {$colour & 0xff}]} ;
close $fh
| #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;
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Tcl version. | package require Tk
proc output_ppm {image filename} {
$image write $filename -format ppm
}
set img [newImage 150 150]
fill $img red
setPixel $img green 40 40
output_ppm $img filename.ppm
set fh [open filename.ppm]
puts [gets $fh] ;
puts [gets $fh] ;
puts [gets $fh] ;
binary scan [read $fh 3] c3 pixel
foreach colour $pixel {puts [expr {$colour & 0xff}]} ;
close $fh
| 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();
}
}
|
Change the following Tcl code into C++ without altering its purpose. | package require Tk
proc output_ppm {image filename} {
$image write $filename -format ppm
}
set img [newImage 150 150]
fill $img red
setPixel $img green 40 40
output_ppm $img filename.ppm
set fh [open filename.ppm]
puts [gets $fh] ;
puts [gets $fh] ;
puts [gets $fh] ;
binary scan [read $fh 3] c3 pixel
foreach colour $pixel {puts [expr {$colour & 0xff}]} ;
close $fh
| #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);
}
|
Preserve the algorithm and functionality while converting the code from Tcl to Java. | package require Tk
proc output_ppm {image filename} {
$image write $filename -format ppm
}
set img [newImage 150 150]
fill $img red
setPixel $img green 40 40
output_ppm $img filename.ppm
set fh [open filename.ppm]
puts [gets $fh] ;
puts [gets $fh] ;
puts [gets $fh] ;
binary scan [read $fh 3] c3 pixel
foreach colour $pixel {puts [expr {$colour & 0xff}]} ;
close $fh
| 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());
}
}
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. | package require Tk
proc output_ppm {image filename} {
$image write $filename -format ppm
}
set img [newImage 150 150]
fill $img red
setPixel $img green 40 40
output_ppm $img filename.ppm
set fh [open filename.ppm]
puts [gets $fh] ;
puts [gets $fh] ;
puts [gets $fh] ;
binary scan [read $fh 3] c3 pixel
foreach colour $pixel {puts [expr {$colour & 0xff}]} ;
close $fh
|
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()
|
Write the same code in VB as shown below in Tcl. | package require Tk
proc output_ppm {image filename} {
$image write $filename -format ppm
}
set img [newImage 150 150]
fill $img red
setPixel $img green 40 40
output_ppm $img filename.ppm
set fh [open filename.ppm]
puts [gets $fh] ;
puts [gets $fh] ;
puts [gets $fh] ;
binary scan [read $fh 3] c3 pixel
foreach colour $pixel {puts [expr {$colour & 0xff}]} ;
close $fh
| 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 Tcl. | package require Tk
proc output_ppm {image filename} {
$image write $filename -format ppm
}
set img [newImage 150 150]
fill $img red
setPixel $img green 40 40
output_ppm $img filename.ppm
set fh [open filename.ppm]
puts [gets $fh] ;
puts [gets $fh] ;
puts [gets $fh] ;
binary scan [read $fh 3] c3 pixel
foreach colour $pixel {puts [expr {$colour & 0xff}]} ;
close $fh
| 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()
}
|
Translate this program into PHP but keep the logic exactly as in Rust. | use std::path::Path;
use std::io::Write;
use std::fs::File;
pub struct RGB {
r: u8,
g: u8,
b: u8,
}
pub struct PPM {
height: u32,
width: u32,
data: Vec<u8>,
}
impl PPM {
pub fn new(height: u32, width: u32) -> PPM {
let size = 3 * height * width;
let buffer = vec![0; size as usize];
PPM { height: height, width: width, data: buffer }
}
fn buffer_size(&self) -> u32 {
3 * self.height * self.width
}
fn get_offset(&self, x: u32, y: u32) -> Option<usize> {
let offset = (y * self.width * 3) + (x * 3);
if offset < self.buffer_size() {
Some(offset as usize)
} else {
None
}
}
pub fn get_pixel(&self, x: u32, y: u32) -> Option<RGB> {
match self.get_offset(x, y) {
Some(offset) => {
let r = self.data[offset];
let g = self.data[offset + 1];
let b = self.data[offset + 2];
Some(RGB {r: r, g: g, b: b})
},
None => None
}
}
pub fn set_pixel(&mut self, x: u32, y: u32, color: RGB) -> bool {
match self.get_offset(x, y) {
Some(offset) => {
self.data[offset] = color.r;
self.data[offset + 1] = color.g;
self.data[offset + 2] = color.b;
true
},
None => false
}
}
pub fn write_file(&self, filename: &str) -> std::io::Result<()> {
let path = Path::new(filename);
let mut file = File::create(&path)?;
let header = format!("P6 {} {} 255\n", self.width, self.height);
file.write(header.as_bytes())?;
file.write(&self.data)?;
Ok(())
}
}
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Change the following Ada code into PHP without altering its purpose. | 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;
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Maintain the same structure and functionality when rewriting this code in PHP. | 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
}
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Produce a language-to-language conversion: from AWK to PHP, same semantics. |
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);
}
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Translate this program into PHP but keep the logic exactly as 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%
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Convert the following code from Common_Lisp to PHP, 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)
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Maintain the same structure and functionality when rewriting this code in PHP. | 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.
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Change the programming language of this snippet from Erlang to PHP without modifying what it does. | -module(ppm).
-export([ppm/1, write/2]).
-define(WHITESPACE, <<10>>).
-define(SPACE, <<32>>).
-record(bitmap, {
pixels = nil,
shape = {0, 0}
}).
ppm(Bitmap) ->
{Width, Height} = Bitmap#bitmap.shape,
Pixels = ppm_pixels(Bitmap),
Maxval = 255,
list_to_binary([
header(), width_and_height(Width, Height), maxval(Maxval), Pixels]).
write(Bitmap, Filename) ->
Ppm = ppm(Bitmap),
{ok, File} = file:open(Filename, [binary, write]),
file:write(File, Ppm),
file:close(File).
header() ->
[<<"P6">>, ?WHITESPACE].
width_and_height(Width, Height) ->
[encode_decimal(Width), ?SPACE, encode_decimal(Height), ?WHITESPACE].
maxval(Maxval) ->
[encode_decimal(Maxval), ?WHITESPACE].
ppm_pixels(Bitmap) ->
array:to_list(Bitmap#bitmap.pixels).
encode_decimal(Number) ->
integer_to_list(Number).
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Convert this Forth snippet to PHP and keep its semantics consistent. | : write-ppm { bmp fid -- }
s" P6" fid write-line throw
bmp bdim swap
0 <# bl hold #s #> fid write-file throw
0 <# #s #> fid write-line throw
s" 255" fid write-line throw
bmp bdata bmp bdim * pixels
bounds do
i 3 fid write-file throw
pixel +loop ;
s" red.ppm" w/o create-file throw
test over write-ppm
close-file throw
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Convert the following code from Fortran to PHP, ensuring the logic remains intact. | program main
use rgbimage_m
implicit none
integer :: nx, ny, i, j, k
type(rgbimage) :: im
nx = 400
ny = 300
call im%init(nx, ny)
do i = 1, nx
do j = 1, ny
call im%set_pixel(i, j, [(nint(rand()*255), k=1,3)])
end do
end do
call im%write('fig.ppm')
end program
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Please provide an equivalent version of this Haskell code in PHP. |
module Bitmap.Netpbm(readNetpbm, writeNetpbm) where
import Bitmap
import Data.Char
import System.IO
import Control.Monad
import Control.Monad.ST
import Data.Array.ST
nil :: a
nil = undefined
readNetpbm :: forall c. Color c => FilePath -> IO (Image RealWorld c)
readNetpbm path = do
let die = fail "readNetpbm: bad format"
ppm <- readFile path
let (s, rest) = splitAt 2 ppm
unless (s == magicNumber) die
let getNum :: String -> IO (Int, String)
getNum ppm = do
let (s, rest) = span isDigit $ skipBlanks ppm
when (null s) die
return (read s, rest)
(width, rest) <- getNum rest
(height, rest) <- getNum rest
(_, c : rest) <-
if getMaxval then getNum rest else return (nil, rest)
unless (isSpace c) die
i <- stToIO $ listImage width height $
fromNetpbm $ map fromEnum rest
return i
where skipBlanks =
dropWhile isSpace .
until ((/= '#') . head) (tail . dropWhile (/= '\n')) .
dropWhile isSpace
magicNumber = netpbmMagicNumber (nil :: c)
getMaxval = not $ null $ netpbmMaxval (nil :: c)
writeNetpbm :: forall c. Color c => FilePath -> Image RealWorld c -> IO ()
writeNetpbm path i = withFile path WriteMode $ \h -> do
(width, height) <- stToIO $ dimensions i
let w = hPutStrLn h
w $ magicNumber
w $ show width ++ " " ++ show height
unless (null maxval) (w maxval)
stToIO (getPixels i) >>= hPutStr h . toNetpbm
where magicNumber = netpbmMagicNumber (nil :: c)
maxval = netpbmMaxval (nil :: c)
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Write the same algorithm in PHP as shown in this J implementation. | require 'files'
writeppm=:dyad define
header=. 'P6',LF,(":1 0{$x),LF,'255',LF
(header,,x{a.) fwrite y
)
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Produce a language-to-language conversion: from Julia to PHP, same semantics. | using Images, FileIO
h, w = 50, 70
img = zeros(RGB{N0f8}, h, w)
img[10:40, 5:35] = colorant"skyblue"
for i in 26:50, j in (i-25):40
img[i, j] = colorant"sienna1"
end
save("data/bitmapWrite.ppm", img)
save("data/bitmapWrite.png", img)
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Change the programming language of this snippet from Lua to PHP without modifying what it does. |
local array_fill = function(vbegin, vend, value)
local t = {}
for i=vbegin, vend do
t[i] = value
end
return t
end
Bitmap = {}
Bitmap.__index = Bitmap
function Bitmap.new(width, height)
local self = {}
setmetatable(self, Bitmap)
local white = array_fill(0, width, {255, 255, 255})
self.data = array_fill(0, height, white)
self.width = width
self.height = height
return self
end
function Bitmap:writeRawPixel(file, c)
local dt
dt = string.format("%c", c)
file:write(dt)
end
function Bitmap:writeComment(fh, ...)
local strings = {...}
local str = ""
local result
for _, s in pairs(strings) do
str = str .. tostring(s)
end
result = string.format("# %s\n", str)
fh:write(result)
end
function Bitmap:writeP6(filename)
local fh = io.open(filename, 'w')
if not fh then
error(string.format("failed to open %q for writing", filename))
else
fh:write(string.format("P6 %d %d 255\n", self.width, self.height))
self:writeComment(fh, "automatically generated at ", os.date())
for _, row in pairs(self.data) do
for _, pixel in pairs(row) do
self:writeRawPixel(fh, pixel[1])
self:writeRawPixel(fh, pixel[2])
self:writeRawPixel(fh, pixel[3])
end
end
end
end
function Bitmap:fill(x, y, width, height, color)
width = (width == nil) and self.width or width
height = (height == nil) and self.height or height
width = width + x
height = height + y
for i=y, height do
for j=x, width do
self:setPixel(j, i, color)
end
end
end
function Bitmap:setPixel(x, y, color)
if x >= self.width then
return false
elseif x < 0 then
return false
elseif y >= self.height then
return false
elseif y < 0 then
return false
end
self.data[y][x] = color
return true
end
function example_colorful_stripes()
local w = 260*2
local h = 260*2
local b = Bitmap.new(w, h)
b:setPixel(0, 15, {255,68,0})
for i=1, w do
for j=1, h do
b:setPixel(i, j, {
(i + j * 8) % 256,
(j + (255 * i)) % 256,
(i * j) % 256
}
);
end
end
return b
end
example_colorful_stripes():writeP6('p6.ppm')
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Port the following code from Mathematica to PHP with equivalent syntax and logic. | Export["file.ppm",image,"PPM"]
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Produce a functionally identical PHP code for the snippet given in MATLAB. | R=[255,0,0;255,255,0];
G=[0,255,0;255,255,0];
B=[0,0,255;0,0,0];
r = R'; r(:);
g = R'; g(:);
b = R'; b(:);
fid=fopen('p6.ppm','w');
fprintf(fid,'P6\n
fwrite(fid,[r,g,b]','uint8');
fclose(fid);
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Preserve the algorithm and functionality while converting the code from Nim to PHP. | import bitmap
import streams
proc writePPM*(img: Image, stream: Stream) =
stream.writeLine("P6 ", $img.w, " ", $img.h, " 255")
for x, y in img.indices:
stream.write(chr(img[x, y].r))
stream.write(chr(img[x, y].g))
stream.write(chr(img[x, y].b))
proc writePPM*(img: Image; filename: string) =
var file = openFileStream(filename, fmWrite)
img.writePPM(file)
file.close()
when isMainModule:
var image = newImage(100, 50)
image.fill(color(255, 0, 0))
for row in 10..20:
for col in 0..<image.w:
image[col, row] = color(0, 255, 0)
for row in 30..40:
for col in 0..<image.w:
image[col, row] = color(0, 0, 255)
image.writePPM("output.ppm")
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Change the following OCaml code into PHP without altering its purpose. | let output_ppm ~oc ~img:(_, r_channel, g_channel, b_channel) =
let width = Bigarray.Array2.dim1 r_channel
and height = Bigarray.Array2.dim2 r_channel in
Printf.fprintf oc "P6\n%d %d\n255\n" width height;
for y = 0 to pred height do
for x = 0 to pred width do
output_char oc (char_of_int r_channel.{x,y});
output_char oc (char_of_int g_channel.{x,y});
output_char oc (char_of_int b_channel.{x,y});
done;
done;
output_char oc '\n';
flush oc;
;;
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Write the same code in PHP as shown below in Perl. | use Imager;
$image = Imager->new(xsize => 200, ysize => 200);
$image->box(filled => 1, color => red);
$image->box(filled => 1, color => black,
xmin => 50, ymin => 50,
xmax => 150, ymax => 150);
$image->write(file => 'bitmap.ppm') or die $image->errstr;
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Keep all operations the same but rewrite the snippet in PHP. |
library(pixmap)
pixmap::write.pnm
write.pnm(theimage, filename)
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Please provide an equivalent version of this Racket code in PHP. |
(define (bitmap->ppm bitmap output-port)
(define height (send bitmap get-height))
(define width (send bitmap get-width))
(define buffer (make-bytes (* width height 4)))
(send bitmap get-argb-pixels 0 0 width height buffer)
(parameterize ([current-output-port output-port])
(printf "P3\n~a ~a\n255" width height)
(for ([i (* width height)])
(define pixel-position (* 4 i))
(when (= (modulo i width) 0) (printf "\n"))
(printf "~s ~s ~s "
(bytes-ref buffer (+ pixel-position 1))
(bytes-ref buffer (+ pixel-position 2))
(bytes-ref buffer (+ pixel-position 3))))))
(call-with-output-file "image.ppm" #:exists 'replace #:mode 'text
(lambda (out)
(bitmap->ppm bm out)))
(define (bitmap->ppm bitmap output-port)
(define height (send bitmap get-height))
(define width (send bitmap get-width))
(define buffer (make-bytes (* width height 4)))
(send bitmap get-argb-pixels 0 0 width height buffer)
(parameterize ([current-output-port output-port])
(printf "P6\n~a ~a\n255\n" width height)
(for ([i (* width height)])
(define pixel-position (* 4 i))
(write-byte (bytes-ref buffer (+ pixel-position 1)))
(write-byte (bytes-ref buffer (+ pixel-position 2)))
(write-byte (bytes-ref buffer (+ pixel-position 3))))))
(call-with-output-file "image.ppm" #:exists 'replace #:mode 'binary
(lambda (out)
(bitmap->ppm bm out)))
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Generate an equivalent PHP version of this REXX code. |
green = 00ff00
parse arg oFN width height color .
if oFN=='' | oFN=="," then oFN='IMAGE'
if width=='' | width=="," then width= 20
if height=='' | height=="," then height= 20
if color=='' | color=="," then color= green
oFID= oFN'.PPM'
@. = x2c(color)
$ = '9'x
# = 255
call charout oFID, , 1
call charout oFID,'P6'width || $ || height || $ || # || $
_=
do j =1 for width
do k=1 for height; _= _ || @.j.k
end
end
call charout oFID, _
call charout oFID
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Transform the following Ruby implementation into PHP, maintaining the same output and logic. | class RGBColour
def values
[@red, @green, @blue]
end
end
class Pixmap
def save(filename)
File.open(filename, 'w') do |f|
f.puts "P6", "
f.binmode
@height.times do |y|
@width.times do |x|
f.print @data[x][y].values.pack('C3')
end
end
end
end
alias_method :write, :save
end
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Ensure the translated PHP code behaves exactly like the original Scala snippet. |
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
import java.io.FileOutputStream
class BasicBitmapStorage(width: Int, height: Int) {
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
fun fill(c: Color) {
val g = image.graphics
g.color = c
g.fillRect(0, 0, image.width, image.height)
}
fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())
fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))
}
fun main(args: Array<String>) {
val width = 640
val height = 640
val bbs = BasicBitmapStorage(width, height)
for (y in 0 until height) {
for (x in 0 until width) {
val c = Color(x % 256, y % 256, (x * y) % 256)
bbs.setPixel(x, y, c)
}
}
val fos = FileOutputStream("output.ppm")
val buffer = ByteArray(width * 3)
fos.use {
val header = "P6\n$width $height\n255\n".toByteArray()
with (it) {
write(header)
for (y in 0 until height) {
for (x in 0 until width) {
val c = bbs.getPixel(x, y)
buffer[x * 3] = c.red.toByte()
buffer[x * 3 + 1] = c.green.toByte()
buffer[x * 3 + 2] = c.blue.toByte()
}
write(buffer)
}
}
}
}
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Rewrite the snippet below in PHP so it works the same as the original Tcl code. | package require Tk
proc output_ppm {image filename} {
$image write $filename -format ppm
}
set img [newImage 150 150]
fill $img red
setPixel $img green 40 40
output_ppm $img filename.ppm
set fh [open filename.ppm]
puts [gets $fh] ;
puts [gets $fh] ;
puts [gets $fh] ;
binary scan [read $fh 3] c3 pixel
foreach colour $pixel {puts [expr {$colour & 0xff}]} ;
close $fh
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Write a version of this C function in Rust with identical behavior. | #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;
}
| use std::path::Path;
use std::io::Write;
use std::fs::File;
pub struct RGB {
r: u8,
g: u8,
b: u8,
}
pub struct PPM {
height: u32,
width: u32,
data: Vec<u8>,
}
impl PPM {
pub fn new(height: u32, width: u32) -> PPM {
let size = 3 * height * width;
let buffer = vec![0; size as usize];
PPM { height: height, width: width, data: buffer }
}
fn buffer_size(&self) -> u32 {
3 * self.height * self.width
}
fn get_offset(&self, x: u32, y: u32) -> Option<usize> {
let offset = (y * self.width * 3) + (x * 3);
if offset < self.buffer_size() {
Some(offset as usize)
} else {
None
}
}
pub fn get_pixel(&self, x: u32, y: u32) -> Option<RGB> {
match self.get_offset(x, y) {
Some(offset) => {
let r = self.data[offset];
let g = self.data[offset + 1];
let b = self.data[offset + 2];
Some(RGB {r: r, g: g, b: b})
},
None => None
}
}
pub fn set_pixel(&mut self, x: u32, y: u32, color: RGB) -> bool {
match self.get_offset(x, y) {
Some(offset) => {
self.data[offset] = color.r;
self.data[offset + 1] = color.g;
self.data[offset + 2] = color.b;
true
},
None => false
}
}
pub fn write_file(&self, filename: &str) -> std::io::Result<()> {
let path = Path::new(filename);
let mut file = File::create(&path)?;
let header = format!("P6 {} {} 255\n", self.width, self.height);
file.write(header.as_bytes())?;
file.write(&self.data)?;
Ok(())
}
}
|
Please provide an equivalent version of this C# code in Rust. | 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();
}
}
| use std::path::Path;
use std::io::Write;
use std::fs::File;
pub struct RGB {
r: u8,
g: u8,
b: u8,
}
pub struct PPM {
height: u32,
width: u32,
data: Vec<u8>,
}
impl PPM {
pub fn new(height: u32, width: u32) -> PPM {
let size = 3 * height * width;
let buffer = vec![0; size as usize];
PPM { height: height, width: width, data: buffer }
}
fn buffer_size(&self) -> u32 {
3 * self.height * self.width
}
fn get_offset(&self, x: u32, y: u32) -> Option<usize> {
let offset = (y * self.width * 3) + (x * 3);
if offset < self.buffer_size() {
Some(offset as usize)
} else {
None
}
}
pub fn get_pixel(&self, x: u32, y: u32) -> Option<RGB> {
match self.get_offset(x, y) {
Some(offset) => {
let r = self.data[offset];
let g = self.data[offset + 1];
let b = self.data[offset + 2];
Some(RGB {r: r, g: g, b: b})
},
None => None
}
}
pub fn set_pixel(&mut self, x: u32, y: u32, color: RGB) -> bool {
match self.get_offset(x, y) {
Some(offset) => {
self.data[offset] = color.r;
self.data[offset + 1] = color.g;
self.data[offset + 2] = color.b;
true
},
None => false
}
}
pub fn write_file(&self, filename: &str) -> std::io::Result<()> {
let path = Path::new(filename);
let mut file = File::create(&path)?;
let header = format!("P6 {} {} 255\n", self.width, self.height);
file.write(header.as_bytes())?;
file.write(&self.data)?;
Ok(())
}
}
|
Rewrite this program in Rust while keeping its functionality equivalent to the Java version. | 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());
}
}
}
}
}
| use std::path::Path;
use std::io::Write;
use std::fs::File;
pub struct RGB {
r: u8,
g: u8,
b: u8,
}
pub struct PPM {
height: u32,
width: u32,
data: Vec<u8>,
}
impl PPM {
pub fn new(height: u32, width: u32) -> PPM {
let size = 3 * height * width;
let buffer = vec![0; size as usize];
PPM { height: height, width: width, data: buffer }
}
fn buffer_size(&self) -> u32 {
3 * self.height * self.width
}
fn get_offset(&self, x: u32, y: u32) -> Option<usize> {
let offset = (y * self.width * 3) + (x * 3);
if offset < self.buffer_size() {
Some(offset as usize)
} else {
None
}
}
pub fn get_pixel(&self, x: u32, y: u32) -> Option<RGB> {
match self.get_offset(x, y) {
Some(offset) => {
let r = self.data[offset];
let g = self.data[offset + 1];
let b = self.data[offset + 2];
Some(RGB {r: r, g: g, b: b})
},
None => None
}
}
pub fn set_pixel(&mut self, x: u32, y: u32, color: RGB) -> bool {
match self.get_offset(x, y) {
Some(offset) => {
self.data[offset] = color.r;
self.data[offset + 1] = color.g;
self.data[offset + 2] = color.b;
true
},
None => false
}
}
pub fn write_file(&self, filename: &str) -> std::io::Result<()> {
let path = Path::new(filename);
let mut file = File::create(&path)?;
let header = format!("P6 {} {} 255\n", self.width, self.height);
file.write(header.as_bytes())?;
file.write(&self.data)?;
Ok(())
}
}
|
Preserve the algorithm and functionality while converting the code from Rust to Python. | use std::path::Path;
use std::io::Write;
use std::fs::File;
pub struct RGB {
r: u8,
g: u8,
b: u8,
}
pub struct PPM {
height: u32,
width: u32,
data: Vec<u8>,
}
impl PPM {
pub fn new(height: u32, width: u32) -> PPM {
let size = 3 * height * width;
let buffer = vec![0; size as usize];
PPM { height: height, width: width, data: buffer }
}
fn buffer_size(&self) -> u32 {
3 * self.height * self.width
}
fn get_offset(&self, x: u32, y: u32) -> Option<usize> {
let offset = (y * self.width * 3) + (x * 3);
if offset < self.buffer_size() {
Some(offset as usize)
} else {
None
}
}
pub fn get_pixel(&self, x: u32, y: u32) -> Option<RGB> {
match self.get_offset(x, y) {
Some(offset) => {
let r = self.data[offset];
let g = self.data[offset + 1];
let b = self.data[offset + 2];
Some(RGB {r: r, g: g, b: b})
},
None => None
}
}
pub fn set_pixel(&mut self, x: u32, y: u32, color: RGB) -> bool {
match self.get_offset(x, y) {
Some(offset) => {
self.data[offset] = color.r;
self.data[offset + 1] = color.g;
self.data[offset + 2] = color.b;
true
},
None => false
}
}
pub fn write_file(&self, filename: &str) -> std::io::Result<()> {
let path = Path::new(filename);
let mut file = File::create(&path)?;
let header = format!("P6 {} {} 255\n", self.width, self.height);
file.write(header.as_bytes())?;
file.write(&self.data)?;
Ok(())
}
}
|
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()
|
Produce a language-to-language conversion: from Rust to VB, same semantics. | use std::path::Path;
use std::io::Write;
use std::fs::File;
pub struct RGB {
r: u8,
g: u8,
b: u8,
}
pub struct PPM {
height: u32,
width: u32,
data: Vec<u8>,
}
impl PPM {
pub fn new(height: u32, width: u32) -> PPM {
let size = 3 * height * width;
let buffer = vec![0; size as usize];
PPM { height: height, width: width, data: buffer }
}
fn buffer_size(&self) -> u32 {
3 * self.height * self.width
}
fn get_offset(&self, x: u32, y: u32) -> Option<usize> {
let offset = (y * self.width * 3) + (x * 3);
if offset < self.buffer_size() {
Some(offset as usize)
} else {
None
}
}
pub fn get_pixel(&self, x: u32, y: u32) -> Option<RGB> {
match self.get_offset(x, y) {
Some(offset) => {
let r = self.data[offset];
let g = self.data[offset + 1];
let b = self.data[offset + 2];
Some(RGB {r: r, g: g, b: b})
},
None => None
}
}
pub fn set_pixel(&mut self, x: u32, y: u32, color: RGB) -> bool {
match self.get_offset(x, y) {
Some(offset) => {
self.data[offset] = color.r;
self.data[offset + 1] = color.g;
self.data[offset + 2] = color.b;
true
},
None => false
}
}
pub fn write_file(&self, filename: &str) -> std::io::Result<()> {
let path = Path::new(filename);
let mut file = File::create(&path)?;
let header = format!("P6 {} {} 255\n", self.width, self.height);
file.write(header.as_bytes())?;
file.write(&self.data)?;
Ok(())
}
}
| 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
|
Generate an equivalent Rust version of this C++ code. | #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;
}
| use std::path::Path;
use std::io::Write;
use std::fs::File;
pub struct RGB {
r: u8,
g: u8,
b: u8,
}
pub struct PPM {
height: u32,
width: u32,
data: Vec<u8>,
}
impl PPM {
pub fn new(height: u32, width: u32) -> PPM {
let size = 3 * height * width;
let buffer = vec![0; size as usize];
PPM { height: height, width: width, data: buffer }
}
fn buffer_size(&self) -> u32 {
3 * self.height * self.width
}
fn get_offset(&self, x: u32, y: u32) -> Option<usize> {
let offset = (y * self.width * 3) + (x * 3);
if offset < self.buffer_size() {
Some(offset as usize)
} else {
None
}
}
pub fn get_pixel(&self, x: u32, y: u32) -> Option<RGB> {
match self.get_offset(x, y) {
Some(offset) => {
let r = self.data[offset];
let g = self.data[offset + 1];
let b = self.data[offset + 2];
Some(RGB {r: r, g: g, b: b})
},
None => None
}
}
pub fn set_pixel(&mut self, x: u32, y: u32, color: RGB) -> bool {
match self.get_offset(x, y) {
Some(offset) => {
self.data[offset] = color.r;
self.data[offset + 1] = color.g;
self.data[offset + 2] = color.b;
true
},
None => false
}
}
pub fn write_file(&self, filename: &str) -> std::io::Result<()> {
let path = Path::new(filename);
let mut file = File::create(&path)?;
let header = format!("P6 {} {} 255\n", self.width, self.height);
file.write(header.as_bytes())?;
file.write(&self.data)?;
Ok(())
}
}
|
Write the same code in Rust as shown below in Go. | 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()
}
| use std::path::Path;
use std::io::Write;
use std::fs::File;
pub struct RGB {
r: u8,
g: u8,
b: u8,
}
pub struct PPM {
height: u32,
width: u32,
data: Vec<u8>,
}
impl PPM {
pub fn new(height: u32, width: u32) -> PPM {
let size = 3 * height * width;
let buffer = vec![0; size as usize];
PPM { height: height, width: width, data: buffer }
}
fn buffer_size(&self) -> u32 {
3 * self.height * self.width
}
fn get_offset(&self, x: u32, y: u32) -> Option<usize> {
let offset = (y * self.width * 3) + (x * 3);
if offset < self.buffer_size() {
Some(offset as usize)
} else {
None
}
}
pub fn get_pixel(&self, x: u32, y: u32) -> Option<RGB> {
match self.get_offset(x, y) {
Some(offset) => {
let r = self.data[offset];
let g = self.data[offset + 1];
let b = self.data[offset + 2];
Some(RGB {r: r, g: g, b: b})
},
None => None
}
}
pub fn set_pixel(&mut self, x: u32, y: u32, color: RGB) -> bool {
match self.get_offset(x, y) {
Some(offset) => {
self.data[offset] = color.r;
self.data[offset + 1] = color.g;
self.data[offset + 2] = color.b;
true
},
None => false
}
}
pub fn write_file(&self, filename: &str) -> std::io::Result<()> {
let path = Path::new(filename);
let mut file = File::create(&path)?;
let header = format!("P6 {} {} 255\n", self.width, self.height);
file.write(header.as_bytes())?;
file.write(&self.data)?;
Ok(())
}
}
|
Convert the following code from Ada to C#, ensuring the logic remains intact. | with Ada.Text_Io;
with Ada.Float_Text_Io;
with Ada.Integer_Text_Io;
procedure Two_Dimensional_Arrays is
type Matrix_Type is array(Positive range <>, Positive range <>) of Float;
Dim_1 : Positive;
Dim_2 : Positive;
begin
Ada.Integer_Text_Io.Get(Item => Dim_1);
Ada.Integer_Text_Io.Get(Item => Dim_2);
declare
Matrix : Matrix_Type(1..Dim_1, 1..Dim_2);
begin
Matrix(1, Dim_2) := 3.14159;
Ada.Float_Text_Io.Put(Item => Matrix(1, Dim_2), Fore => 1, Aft => 5, Exp => 0);
Ada.Text_Io.New_Line;
end;
end Two_Dimensional_Arrays;
| class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter two integers. Space delimited please: ");
string s = Console.ReadLine();
int[,] myArray=new int[(int)s[0],(int)s[2]];
myArray[0, 0] = 2;
Console.WriteLine(myArray[0, 0]);
Console.ReadLine();
}
}
|
Change the programming language of this snippet from Ada to C without modifying what it does. | with Ada.Text_Io;
with Ada.Float_Text_Io;
with Ada.Integer_Text_Io;
procedure Two_Dimensional_Arrays is
type Matrix_Type is array(Positive range <>, Positive range <>) of Float;
Dim_1 : Positive;
Dim_2 : Positive;
begin
Ada.Integer_Text_Io.Get(Item => Dim_1);
Ada.Integer_Text_Io.Get(Item => Dim_2);
declare
Matrix : Matrix_Type(1..Dim_1, 1..Dim_2);
begin
Matrix(1, Dim_2) := 3.14159;
Ada.Float_Text_Io.Put(Item => Matrix(1, Dim_2), Fore => 1, Aft => 5, Exp => 0);
Ada.Text_Io.New_Line;
end;
end Two_Dimensional_Arrays;
| #include <stdio.h>
int main(int argc, char **argv) {
int user1 = 0, user2 = 0;
printf("Enter two integers. Space delimited, please: ");
scanf("%d %d",&user1, &user2);
int array[user1][user2];
array[user1/2][user2/2] = user1 + user2;
printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]);
return 0;
}
|
Please provide an equivalent version of this Ada code in C++. | with Ada.Text_Io;
with Ada.Float_Text_Io;
with Ada.Integer_Text_Io;
procedure Two_Dimensional_Arrays is
type Matrix_Type is array(Positive range <>, Positive range <>) of Float;
Dim_1 : Positive;
Dim_2 : Positive;
begin
Ada.Integer_Text_Io.Get(Item => Dim_1);
Ada.Integer_Text_Io.Get(Item => Dim_2);
declare
Matrix : Matrix_Type(1..Dim_1, 1..Dim_2);
begin
Matrix(1, Dim_2) := 3.14159;
Ada.Float_Text_Io.Put(Item => Matrix(1, Dim_2), Fore => 1, Aft => 5, Exp => 0);
Ada.Text_Io.New_Line;
end;
end Two_Dimensional_Arrays;
| #include <iostream>
int main()
{
int dim1, dim2;
std::cin >> dim1 >> dim2;
double* array_data = new double[dim1*dim2];
double** array = new double*[dim1];
for (int i = 0; i < dim1; ++i)
array[i] = array_data + dim2*i;
array[0][0] = 3.5;
std::cout << array[0][0] << std::endl;
delete[] array;
delete[] array_data;
return 0;
}
|
Rewrite the snippet below in Go so it works the same as the original Ada code. | with Ada.Text_Io;
with Ada.Float_Text_Io;
with Ada.Integer_Text_Io;
procedure Two_Dimensional_Arrays is
type Matrix_Type is array(Positive range <>, Positive range <>) of Float;
Dim_1 : Positive;
Dim_2 : Positive;
begin
Ada.Integer_Text_Io.Get(Item => Dim_1);
Ada.Integer_Text_Io.Get(Item => Dim_2);
declare
Matrix : Matrix_Type(1..Dim_1, 1..Dim_2);
begin
Matrix(1, Dim_2) := 3.14159;
Ada.Float_Text_Io.Put(Item => Matrix(1, Dim_2), Fore => 1, Aft => 5, Exp => 0);
Ada.Text_Io.New_Line;
end;
end Two_Dimensional_Arrays;
| package main
import "fmt"
func main() {
var row, col int
fmt.Print("enter rows cols: ")
fmt.Scan(&row, &col)
a := make([][]int, row)
for i := range a {
a[i] = make([]int, col)
}
fmt.Println("a[0][0] =", a[0][0])
a[row-1][col-1] = 7
fmt.Printf("a[%d][%d] = %d\n", row-1, col-1, a[row-1][col-1])
a = nil
}
|
Rewrite the snippet below in Java so it works the same as the original Ada code. | with Ada.Text_Io;
with Ada.Float_Text_Io;
with Ada.Integer_Text_Io;
procedure Two_Dimensional_Arrays is
type Matrix_Type is array(Positive range <>, Positive range <>) of Float;
Dim_1 : Positive;
Dim_2 : Positive;
begin
Ada.Integer_Text_Io.Get(Item => Dim_1);
Ada.Integer_Text_Io.Get(Item => Dim_2);
declare
Matrix : Matrix_Type(1..Dim_1, 1..Dim_2);
begin
Matrix(1, Dim_2) := 3.14159;
Ada.Float_Text_Io.Put(Item => Matrix(1, Dim_2), Fore => 1, Aft => 5, Exp => 0);
Ada.Text_Io.New_Line;
end;
end Two_Dimensional_Arrays;
| import java.util.Scanner;
public class twoDimArray {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int nbr1 = in.nextInt();
int nbr2 = in.nextInt();
double[][] array = new double[nbr1][nbr2];
array[0][0] = 42.0;
System.out.println("The number at place [0 0] is " + array[0][0]);
}
}
|
Produce a language-to-language conversion: from Ada to Python, same semantics. | with Ada.Text_Io;
with Ada.Float_Text_Io;
with Ada.Integer_Text_Io;
procedure Two_Dimensional_Arrays is
type Matrix_Type is array(Positive range <>, Positive range <>) of Float;
Dim_1 : Positive;
Dim_2 : Positive;
begin
Ada.Integer_Text_Io.Get(Item => Dim_1);
Ada.Integer_Text_Io.Get(Item => Dim_2);
declare
Matrix : Matrix_Type(1..Dim_1, 1..Dim_2);
begin
Matrix(1, Dim_2) := 3.14159;
Ada.Float_Text_Io.Put(Item => Matrix(1, Dim_2), Fore => 1, Aft => 5, Exp => 0);
Ada.Text_Io.New_Line;
end;
end Two_Dimensional_Arrays;
| width = int(raw_input("Width of myarray: "))
height = int(raw_input("Height of Array: "))
myarray = [[0] * width for i in range(height)]
myarray[0][0] = 3.5
print (myarray[0][0])
|
Generate an equivalent VB version of this Ada code. | with Ada.Text_Io;
with Ada.Float_Text_Io;
with Ada.Integer_Text_Io;
procedure Two_Dimensional_Arrays is
type Matrix_Type is array(Positive range <>, Positive range <>) of Float;
Dim_1 : Positive;
Dim_2 : Positive;
begin
Ada.Integer_Text_Io.Get(Item => Dim_1);
Ada.Integer_Text_Io.Get(Item => Dim_2);
declare
Matrix : Matrix_Type(1..Dim_1, 1..Dim_2);
begin
Matrix(1, Dim_2) := 3.14159;
Ada.Float_Text_Io.Put(Item => Matrix(1, Dim_2), Fore => 1, Aft => 5, Exp => 0);
Ada.Text_Io.New_Line;
end;
end Two_Dimensional_Arrays;
| Module Program
Sub Main()
Console.WriteLine("Enter two space-delimited integers:")
Dim input = Console.ReadLine().Split()
Dim rows = Integer.Parse(input(0))
Dim cols = Integer.Parse(input(1))
Dim arr(rows - 1, cols - 1) As Integer
arr(0, 0) = 2
Console.WriteLine(arr(0, 0))
End Sub
End Module
|
Rewrite the snippet below in C so it works the same as the original Arturo code. | width: to :integer input "give me the array's width: "
height: to :integer input "give me the array's height: "
arr: array.of: @[width height] 0
x: random 0 dec width
y: random 0 dec height
arr\[x]\[y]: 123
print ["item at [" x "," y "] =" arr\[x]\[y]]
| #include <stdio.h>
int main(int argc, char **argv) {
int user1 = 0, user2 = 0;
printf("Enter two integers. Space delimited, please: ");
scanf("%d %d",&user1, &user2);
int array[user1][user2];
array[user1/2][user2/2] = user1 + user2;
printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]);
return 0;
}
|
Please provide an equivalent version of this Arturo code in C#. | width: to :integer input "give me the array's width: "
height: to :integer input "give me the array's height: "
arr: array.of: @[width height] 0
x: random 0 dec width
y: random 0 dec height
arr\[x]\[y]: 123
print ["item at [" x "," y "] =" arr\[x]\[y]]
| class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter two integers. Space delimited please: ");
string s = Console.ReadLine();
int[,] myArray=new int[(int)s[0],(int)s[2]];
myArray[0, 0] = 2;
Console.WriteLine(myArray[0, 0]);
Console.ReadLine();
}
}
|
Preserve the algorithm and functionality while converting the code from Arturo to C++. | width: to :integer input "give me the array's width: "
height: to :integer input "give me the array's height: "
arr: array.of: @[width height] 0
x: random 0 dec width
y: random 0 dec height
arr\[x]\[y]: 123
print ["item at [" x "," y "] =" arr\[x]\[y]]
| #include <iostream>
int main()
{
int dim1, dim2;
std::cin >> dim1 >> dim2;
double* array_data = new double[dim1*dim2];
double** array = new double*[dim1];
for (int i = 0; i < dim1; ++i)
array[i] = array_data + dim2*i;
array[0][0] = 3.5;
std::cout << array[0][0] << std::endl;
delete[] array;
delete[] array_data;
return 0;
}
|
Ensure the translated Java code behaves exactly like the original Arturo snippet. | width: to :integer input "give me the array's width: "
height: to :integer input "give me the array's height: "
arr: array.of: @[width height] 0
x: random 0 dec width
y: random 0 dec height
arr\[x]\[y]: 123
print ["item at [" x "," y "] =" arr\[x]\[y]]
| import java.util.Scanner;
public class twoDimArray {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int nbr1 = in.nextInt();
int nbr2 = in.nextInt();
double[][] array = new double[nbr1][nbr2];
array[0][0] = 42.0;
System.out.println("The number at place [0 0] is " + array[0][0]);
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. | width: to :integer input "give me the array's width: "
height: to :integer input "give me the array's height: "
arr: array.of: @[width height] 0
x: random 0 dec width
y: random 0 dec height
arr\[x]\[y]: 123
print ["item at [" x "," y "] =" arr\[x]\[y]]
| width = int(raw_input("Width of myarray: "))
height = int(raw_input("Height of Array: "))
myarray = [[0] * width for i in range(height)]
myarray[0][0] = 3.5
print (myarray[0][0])
|
Generate an equivalent VB version of this Arturo code. | width: to :integer input "give me the array's width: "
height: to :integer input "give me the array's height: "
arr: array.of: @[width height] 0
x: random 0 dec width
y: random 0 dec height
arr\[x]\[y]: 123
print ["item at [" x "," y "] =" arr\[x]\[y]]
| Module Program
Sub Main()
Console.WriteLine("Enter two space-delimited integers:")
Dim input = Console.ReadLine().Split()
Dim rows = Integer.Parse(input(0))
Dim cols = Integer.Parse(input(1))
Dim arr(rows - 1, cols - 1) As Integer
arr(0, 0) = 2
Console.WriteLine(arr(0, 0))
End Sub
End Module
|
Rewrite this program in Go while keeping its functionality equivalent to the Arturo version. | width: to :integer input "give me the array's width: "
height: to :integer input "give me the array's height: "
arr: array.of: @[width height] 0
x: random 0 dec width
y: random 0 dec height
arr\[x]\[y]: 123
print ["item at [" x "," y "] =" arr\[x]\[y]]
| package main
import "fmt"
func main() {
var row, col int
fmt.Print("enter rows cols: ")
fmt.Scan(&row, &col)
a := make([][]int, row)
for i := range a {
a[i] = make([]int, col)
}
fmt.Println("a[0][0] =", a[0][0])
a[row-1][col-1] = 7
fmt.Printf("a[%d][%d] = %d\n", row-1, col-1, a[row-1][col-1])
a = nil
}
|
Ensure the translated C code behaves exactly like the original AutoHotKey snippet. | Array := []
InputBox, data,, Enter two integers separated by a Space:`n(ex. 5 7)
StringSplit, i, data, %A_Space%
Array[i1,i2] := "that element"
MsgBox, % "Array[" i1 "," i2 "] = " Array[i1,i2]
| #include <stdio.h>
int main(int argc, char **argv) {
int user1 = 0, user2 = 0;
printf("Enter two integers. Space delimited, please: ");
scanf("%d %d",&user1, &user2);
int array[user1][user2];
array[user1/2][user2/2] = user1 + user2;
printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C#. | Array := []
InputBox, data,, Enter two integers separated by a Space:`n(ex. 5 7)
StringSplit, i, data, %A_Space%
Array[i1,i2] := "that element"
MsgBox, % "Array[" i1 "," i2 "] = " Array[i1,i2]
| class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter two integers. Space delimited please: ");
string s = Console.ReadLine();
int[,] myArray=new int[(int)s[0],(int)s[2]];
myArray[0, 0] = 2;
Console.WriteLine(myArray[0, 0]);
Console.ReadLine();
}
}
|
Port the provided AutoHotKey code into C++ while preserving the original functionality. | Array := []
InputBox, data,, Enter two integers separated by a Space:`n(ex. 5 7)
StringSplit, i, data, %A_Space%
Array[i1,i2] := "that element"
MsgBox, % "Array[" i1 "," i2 "] = " Array[i1,i2]
| #include <iostream>
int main()
{
int dim1, dim2;
std::cin >> dim1 >> dim2;
double* array_data = new double[dim1*dim2];
double** array = new double*[dim1];
for (int i = 0; i < dim1; ++i)
array[i] = array_data + dim2*i;
array[0][0] = 3.5;
std::cout << array[0][0] << std::endl;
delete[] array;
delete[] array_data;
return 0;
}
|
Generate an equivalent Java version of this AutoHotKey code. | Array := []
InputBox, data,, Enter two integers separated by a Space:`n(ex. 5 7)
StringSplit, i, data, %A_Space%
Array[i1,i2] := "that element"
MsgBox, % "Array[" i1 "," i2 "] = " Array[i1,i2]
| import java.util.Scanner;
public class twoDimArray {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int nbr1 = in.nextInt();
int nbr2 = in.nextInt();
double[][] array = new double[nbr1][nbr2];
array[0][0] = 42.0;
System.out.println("The number at place [0 0] is " + array[0][0]);
}
}
|
Translate the given AutoHotKey code snippet into Python without altering its behavior. | Array := []
InputBox, data,, Enter two integers separated by a Space:`n(ex. 5 7)
StringSplit, i, data, %A_Space%
Array[i1,i2] := "that element"
MsgBox, % "Array[" i1 "," i2 "] = " Array[i1,i2]
| width = int(raw_input("Width of myarray: "))
height = int(raw_input("Height of Array: "))
myarray = [[0] * width for i in range(height)]
myarray[0][0] = 3.5
print (myarray[0][0])
|
Port the following code from AutoHotKey to VB with equivalent syntax and logic. | Array := []
InputBox, data,, Enter two integers separated by a Space:`n(ex. 5 7)
StringSplit, i, data, %A_Space%
Array[i1,i2] := "that element"
MsgBox, % "Array[" i1 "," i2 "] = " Array[i1,i2]
| Module Program
Sub Main()
Console.WriteLine("Enter two space-delimited integers:")
Dim input = Console.ReadLine().Split()
Dim rows = Integer.Parse(input(0))
Dim cols = Integer.Parse(input(1))
Dim arr(rows - 1, cols - 1) As Integer
arr(0, 0) = 2
Console.WriteLine(arr(0, 0))
End Sub
End Module
|
Generate a Go translation of this AutoHotKey snippet without changing its computational steps. | Array := []
InputBox, data,, Enter two integers separated by a Space:`n(ex. 5 7)
StringSplit, i, data, %A_Space%
Array[i1,i2] := "that element"
MsgBox, % "Array[" i1 "," i2 "] = " Array[i1,i2]
| package main
import "fmt"
func main() {
var row, col int
fmt.Print("enter rows cols: ")
fmt.Scan(&row, &col)
a := make([][]int, row)
for i := range a {
a[i] = make([]int, col)
}
fmt.Println("a[0][0] =", a[0][0])
a[row-1][col-1] = 7
fmt.Printf("a[%d][%d] = %d\n", row-1, col-1, a[row-1][col-1])
a = nil
}
|
Can you help me rewrite this code in C instead of AWK, keeping it the same logically? | /[0-9]+ [0-9]+/ {
for(i=0; i < $1; i++) {
for(j=0; j < $2; j++) {
arr[i, j] = i*j
}
}
for (comb in arr) {
split(comb, idx, SUBSEP)
print idx[1] "," idx[2] "->" arr[idx[1], idx[2]]
}
}
| #include <stdio.h>
int main(int argc, char **argv) {
int user1 = 0, user2 = 0;
printf("Enter two integers. Space delimited, please: ");
scanf("%d %d",&user1, &user2);
int array[user1][user2];
array[user1/2][user2/2] = user1 + user2;
printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]);
return 0;
}
|
Produce a functionally identical C# code for the snippet given in AWK. | /[0-9]+ [0-9]+/ {
for(i=0; i < $1; i++) {
for(j=0; j < $2; j++) {
arr[i, j] = i*j
}
}
for (comb in arr) {
split(comb, idx, SUBSEP)
print idx[1] "," idx[2] "->" arr[idx[1], idx[2]]
}
}
| class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter two integers. Space delimited please: ");
string s = Console.ReadLine();
int[,] myArray=new int[(int)s[0],(int)s[2]];
myArray[0, 0] = 2;
Console.WriteLine(myArray[0, 0]);
Console.ReadLine();
}
}
|
Convert this AWK block to C++, preserving its control flow and logic. | /[0-9]+ [0-9]+/ {
for(i=0; i < $1; i++) {
for(j=0; j < $2; j++) {
arr[i, j] = i*j
}
}
for (comb in arr) {
split(comb, idx, SUBSEP)
print idx[1] "," idx[2] "->" arr[idx[1], idx[2]]
}
}
| #include <iostream>
int main()
{
int dim1, dim2;
std::cin >> dim1 >> dim2;
double* array_data = new double[dim1*dim2];
double** array = new double*[dim1];
for (int i = 0; i < dim1; ++i)
array[i] = array_data + dim2*i;
array[0][0] = 3.5;
std::cout << array[0][0] << std::endl;
delete[] array;
delete[] array_data;
return 0;
}
|
Generate a Java translation of this AWK snippet without changing its computational steps. | /[0-9]+ [0-9]+/ {
for(i=0; i < $1; i++) {
for(j=0; j < $2; j++) {
arr[i, j] = i*j
}
}
for (comb in arr) {
split(comb, idx, SUBSEP)
print idx[1] "," idx[2] "->" arr[idx[1], idx[2]]
}
}
| import java.util.Scanner;
public class twoDimArray {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int nbr1 = in.nextInt();
int nbr2 = in.nextInt();
double[][] array = new double[nbr1][nbr2];
array[0][0] = 42.0;
System.out.println("The number at place [0 0] is " + array[0][0]);
}
}
|
Produce a functionally identical Python code for the snippet given in AWK. | /[0-9]+ [0-9]+/ {
for(i=0; i < $1; i++) {
for(j=0; j < $2; j++) {
arr[i, j] = i*j
}
}
for (comb in arr) {
split(comb, idx, SUBSEP)
print idx[1] "," idx[2] "->" arr[idx[1], idx[2]]
}
}
| width = int(raw_input("Width of myarray: "))
height = int(raw_input("Height of Array: "))
myarray = [[0] * width for i in range(height)]
myarray[0][0] = 3.5
print (myarray[0][0])
|
Change the following AWK code into VB without altering its purpose. | /[0-9]+ [0-9]+/ {
for(i=0; i < $1; i++) {
for(j=0; j < $2; j++) {
arr[i, j] = i*j
}
}
for (comb in arr) {
split(comb, idx, SUBSEP)
print idx[1] "," idx[2] "->" arr[idx[1], idx[2]]
}
}
| Module Program
Sub Main()
Console.WriteLine("Enter two space-delimited integers:")
Dim input = Console.ReadLine().Split()
Dim rows = Integer.Parse(input(0))
Dim cols = Integer.Parse(input(1))
Dim arr(rows - 1, cols - 1) As Integer
arr(0, 0) = 2
Console.WriteLine(arr(0, 0))
End Sub
End Module
|
Preserve the algorithm and functionality while converting the code from AWK to Go. | /[0-9]+ [0-9]+/ {
for(i=0; i < $1; i++) {
for(j=0; j < $2; j++) {
arr[i, j] = i*j
}
}
for (comb in arr) {
split(comb, idx, SUBSEP)
print idx[1] "," idx[2] "->" arr[idx[1], idx[2]]
}
}
| package main
import "fmt"
func main() {
var row, col int
fmt.Print("enter rows cols: ")
fmt.Scan(&row, &col)
a := make([][]int, row)
for i := range a {
a[i] = make([]int, col)
}
fmt.Println("a[0][0] =", a[0][0])
a[row-1][col-1] = 7
fmt.Printf("a[%d][%d] = %d\n", row-1, col-1, a[row-1][col-1])
a = nil
}
|
Write the same algorithm in C as shown in this BBC_Basic implementation. | INPUT "Enter array dimensions separated by a comma: " a%, b%
DIM array(a%, b%)
array(1, 1) = PI
PRINT array(1, 1)
| #include <stdio.h>
int main(int argc, char **argv) {
int user1 = 0, user2 = 0;
printf("Enter two integers. Space delimited, please: ");
scanf("%d %d",&user1, &user2);
int array[user1][user2];
array[user1/2][user2/2] = user1 + user2;
printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]);
return 0;
}
|
Write the same code in C# as shown below in BBC_Basic. | INPUT "Enter array dimensions separated by a comma: " a%, b%
DIM array(a%, b%)
array(1, 1) = PI
PRINT array(1, 1)
| class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter two integers. Space delimited please: ");
string s = Console.ReadLine();
int[,] myArray=new int[(int)s[0],(int)s[2]];
myArray[0, 0] = 2;
Console.WriteLine(myArray[0, 0]);
Console.ReadLine();
}
}
|
Please provide an equivalent version of this BBC_Basic code in C++. | INPUT "Enter array dimensions separated by a comma: " a%, b%
DIM array(a%, b%)
array(1, 1) = PI
PRINT array(1, 1)
| #include <iostream>
int main()
{
int dim1, dim2;
std::cin >> dim1 >> dim2;
double* array_data = new double[dim1*dim2];
double** array = new double*[dim1];
for (int i = 0; i < dim1; ++i)
array[i] = array_data + dim2*i;
array[0][0] = 3.5;
std::cout << array[0][0] << std::endl;
delete[] array;
delete[] array_data;
return 0;
}
|
Generate a Java translation of this BBC_Basic snippet without changing its computational steps. | INPUT "Enter array dimensions separated by a comma: " a%, b%
DIM array(a%, b%)
array(1, 1) = PI
PRINT array(1, 1)
| import java.util.Scanner;
public class twoDimArray {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int nbr1 = in.nextInt();
int nbr2 = in.nextInt();
double[][] array = new double[nbr1][nbr2];
array[0][0] = 42.0;
System.out.println("The number at place [0 0] is " + array[0][0]);
}
}
|
Preserve the algorithm and functionality while converting the code from BBC_Basic to Python. | INPUT "Enter array dimensions separated by a comma: " a%, b%
DIM array(a%, b%)
array(1, 1) = PI
PRINT array(1, 1)
| width = int(raw_input("Width of myarray: "))
height = int(raw_input("Height of Array: "))
myarray = [[0] * width for i in range(height)]
myarray[0][0] = 3.5
print (myarray[0][0])
|
Write the same algorithm in VB as shown in this BBC_Basic implementation. | INPUT "Enter array dimensions separated by a comma: " a%, b%
DIM array(a%, b%)
array(1, 1) = PI
PRINT array(1, 1)
| Module Program
Sub Main()
Console.WriteLine("Enter two space-delimited integers:")
Dim input = Console.ReadLine().Split()
Dim rows = Integer.Parse(input(0))
Dim cols = Integer.Parse(input(1))
Dim arr(rows - 1, cols - 1) As Integer
arr(0, 0) = 2
Console.WriteLine(arr(0, 0))
End Sub
End Module
|
Convert this BBC_Basic block to Go, preserving its control flow and logic. | INPUT "Enter array dimensions separated by a comma: " a%, b%
DIM array(a%, b%)
array(1, 1) = PI
PRINT array(1, 1)
| package main
import "fmt"
func main() {
var row, col int
fmt.Print("enter rows cols: ")
fmt.Scan(&row, &col)
a := make([][]int, row)
for i := range a {
a[i] = make([]int, col)
}
fmt.Println("a[0][0] =", a[0][0])
a[row-1][col-1] = 7
fmt.Printf("a[%d][%d] = %d\n", row-1, col-1, a[row-1][col-1])
a = nil
}
|
Convert this Clojure block to C, preserving its control flow and logic. | (let [rows (Integer/parseInt (read-line))
cols (Integer/parseInt (read-line))
a (to-array-2d (repeat rows (repeat cols nil)))]
(aset a 0 0 12)
(println "Element at 0,0:" (aget a 0 0)))
| #include <stdio.h>
int main(int argc, char **argv) {
int user1 = 0, user2 = 0;
printf("Enter two integers. Space delimited, please: ");
scanf("%d %d",&user1, &user2);
int array[user1][user2];
array[user1/2][user2/2] = user1 + user2;
printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]);
return 0;
}
|
Port the provided Clojure code into C# while preserving the original functionality. | (let [rows (Integer/parseInt (read-line))
cols (Integer/parseInt (read-line))
a (to-array-2d (repeat rows (repeat cols nil)))]
(aset a 0 0 12)
(println "Element at 0,0:" (aget a 0 0)))
| class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter two integers. Space delimited please: ");
string s = Console.ReadLine();
int[,] myArray=new int[(int)s[0],(int)s[2]];
myArray[0, 0] = 2;
Console.WriteLine(myArray[0, 0]);
Console.ReadLine();
}
}
|
Please provide an equivalent version of this Clojure code in C++. | (let [rows (Integer/parseInt (read-line))
cols (Integer/parseInt (read-line))
a (to-array-2d (repeat rows (repeat cols nil)))]
(aset a 0 0 12)
(println "Element at 0,0:" (aget a 0 0)))
| #include <iostream>
int main()
{
int dim1, dim2;
std::cin >> dim1 >> dim2;
double* array_data = new double[dim1*dim2];
double** array = new double*[dim1];
for (int i = 0; i < dim1; ++i)
array[i] = array_data + dim2*i;
array[0][0] = 3.5;
std::cout << array[0][0] << std::endl;
delete[] array;
delete[] array_data;
return 0;
}
|
Translate this program into Java but keep the logic exactly as in Clojure. | (let [rows (Integer/parseInt (read-line))
cols (Integer/parseInt (read-line))
a (to-array-2d (repeat rows (repeat cols nil)))]
(aset a 0 0 12)
(println "Element at 0,0:" (aget a 0 0)))
| import java.util.Scanner;
public class twoDimArray {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int nbr1 = in.nextInt();
int nbr2 = in.nextInt();
double[][] array = new double[nbr1][nbr2];
array[0][0] = 42.0;
System.out.println("The number at place [0 0] is " + array[0][0]);
}
}
|
Convert this Clojure block to Python, preserving its control flow and logic. | (let [rows (Integer/parseInt (read-line))
cols (Integer/parseInt (read-line))
a (to-array-2d (repeat rows (repeat cols nil)))]
(aset a 0 0 12)
(println "Element at 0,0:" (aget a 0 0)))
| width = int(raw_input("Width of myarray: "))
height = int(raw_input("Height of Array: "))
myarray = [[0] * width for i in range(height)]
myarray[0][0] = 3.5
print (myarray[0][0])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.