Munching squares: Difference between revisions

From Rosetta Code
Content added Content deleted
(XPL0 example)
m (→‎{{header|J}}: fix minor layout issue)
Line 179: Line 179:


=={{header|J}}==
=={{header|J}}==
<lang J> require 'viewmat'
<lang J> require 'viewmat'

viewmat ~:"1/&.#: ~ i.256</lang>
viewmat ~:"1/&.#: ~ i.256</lang>



Revision as of 01:35, 18 December 2012

Munching squares is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Render a graphical pattern where each pixel is colored by the value of 'x xor y' from a color table.

Ada

Library: GtkAda

Uses the Cairo component of GtkAda to create and save as png <lang Ada>with Cairo; use Cairo; with Cairo.Png; use Cairo.Png; with Cairo.Image_Surface; use Cairo.Image_Surface; procedure XorPattern is

  type xorable is mod 256;
  Surface : Cairo_Surface;
  Data : RGB24_Array_Access;
  Status : Cairo_Status;
  Num : Byte;

begin

  Data := new RGB24_Array(0..256*256-1);
  for x in Natural range 0..255 loop
     for y in Natural range 0..255 loop
        Num := Byte(xorable(x) xor xorable(y));
        Data(x+256*y) := RGB24_Data'(Num,0,Num);
     end loop;
  end loop;
  Surface := Create_For_Data_RGB24(Data, 256, 256);
  Status := Write_To_Png (Surface, "AdaXorPattern.png");
  pragma Assert (Status = Cairo_Status_Success);

end XorPattern;</lang> Ada Output

C

<lang c>#include <stdlib.h>

  1. include <stdio.h>
  2. include <math.h>
  3. include <string.h>

void hue_to_rgb(double hue, double sat, unsigned char *p) { double x; int c = 255 * sat; hue /= 60; x = (1 - fabs(fmod(hue, 2) - 1)) * 255;

switch((int)hue) { case 0: p[0] = c; p[1] = x; p[2] = 0; return; case 1: p[0] = x; p[1] = c; p[2] = 0; return; case 2: p[0] = 0; p[1] = c; p[2] = x; return; case 3: p[0] = 0; p[1] = x; p[2] = c; return; case 4: p[0] = x; p[1] = 0; p[2] = c; return; case 5: p[0] = c; p[1] = 0; p[2] = x; return; } }

int main(void) { const int size = 512; int i, j; unsigned char *colors = malloc(size * 3); unsigned char *pix = malloc(size * size * 3), *p; FILE *fp;

for (i = 0; i < size; i++) hue_to_rgb(i * 240. / size, i * 1. / size, colors + 3 * i);

for (i = 0, p = pix; i < size; i++) for (j = 0; j < size; j++, p += 3) memcpy(p, colors + (i ^ j) * 3, 3);

fp = fopen("xor.ppm", "wb"); fprintf(fp, "P6\n%d %d\n255\n", size, size); fwrite(pix, size * size * 3, 1, fp); fclose(fp);

return 0; }</lang> C output

C#

<lang csharp>using System.Drawing; using System.Drawing.Imaging; using System.Linq;

class XORPattern {

   static void Main()
   {
       var size = 0x100;
       var black = Color.Black.ToArgb();
       var palette = Enumerable.Range(black, size).Select(Color.FromArgb).ToArray();
       using (var image = new Bitmap(size, size))
       {
           for (var x = 0; x < size; x++)
           {
               for (var y = 0; y < size; y++)
               {
                   image.SetPixel(x, y, palette[x ^ y]);
               }
           }
           image.Save("XORPatternCSharp.png", ImageFormat.Png);
       }
   }

}</lang> Output:

XORPatternCSharp.png

D

<lang d>import std.stdio;

void main() {

   enum width = 512, height = 512;
   auto f = File("xor_pattern.ppm", "wb");
   f.writefln("P6\n%d %d\n255", width, height);
   foreach (y; 0 .. height)
       foreach (x; 0 .. width) {
           ubyte c = (x ^ y) & ubyte.max;
           f.rawWrite(cast(ubyte[3])[255 - c, c / 2, c]);
       }

}</lang>

Gnuplot

<lang gnuplot>set pm3d map set size square set isosamples 255,255 splot [0:255][0:255]-(floor(x)^floor(y))</lang>

D output

Haskell

<lang haskell>import Data.ByteString import Data.Bits

main = Data.ByteString.writeFile "out.pgm" (pack (fmap (fromIntegral . fromEnum) "P5\n256 256\n256\n" ++ [x `xor` y | x <- [0..255], y <- [0..255]])) </lang>

Go

<lang go>package main

import (

   "image"
   "image/png"
   "os"

)

func main() {

   g := image.NewGray(image.Rect(0, 0, 256, 256))
   for i := range g.Pix {
       g.Pix[i] = uint8(i>>8 ^ i)
   }
   f, _ := os.Create("xor.png")
   png.Encode(f, g)
   f.Close()

}</lang>

Icon and Unicon

512x512 bit green and red

<lang Icon>link printf

procedure main(A) #: XOR graphic

  wsize := 512
  cmax  := 32768
  wparms := ["Xmas Xor Graphic","g",sprintf("size=%d,%d",wsize),"bg=black"]
  &window := open!wparms | stop("Unable to open window")

  every y := 0 to wsize - 1 do
     every x := 0 to wsize - 1 do {
        c := cmax/wsize * iand(wsize-1,ixor(x,y))
        Fg(sprintf("%d,%d,%d",c,cmax-c,0))
        DrawPoint(x,y)
        }

 until Event() == &lpress     # wait for left button to quit
 close(&window)

end</lang>

printf.icn provides formatting

J

<lang J> require 'viewmat'

  viewmat ~:"1/&.#: ~ i.256</lang>

Java

This example will repeat the pattern if you expand the window. <lang java>import java.awt.Color; import java.awt.Graphics;

import javax.swing.JFrame; import javax.swing.JPanel;

public class XorPattern extends JFrame{

   private JPanel xorPanel;
   public XorPattern(){
       xorPanel = new JPanel(){
           @Override
           public void paint(Graphics g) {
               for(int y = 0; y < getHeight();y++){
                   for(int x = 0; x < getWidth();x++){
                       g.setColor(new Color(0, (x ^ y) % 256, 0));
                       g.drawLine(x, y, x, y);
                   }
               }
           }
       };
       add(xorPanel);
       setSize(300, 300);
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       setVisible(true);
   }
   public static void main(String[] args){
       new XorPattern();
   }

}</lang>

Liberty BASIC

<lang lb>

   nomainwin
   w =512
   '   allow for title bar and window border
   WindowWidth  =w +2
   WindowHeight =w +34
   open "XOR Pattern" for graphics_nsb_nf as #w
   #w "trapclose quit"
   #w "down"
   for x =0 to w -1
       for y =0 to w -1
           b =( x xor y) and 255
           print b
           #w "color "; 255 -b; " "; b /2; " "; b
           #w "set "; x; " "; w -y -1
           scan
       next y
   next x
   #w "flush"
   wait
   sub quit j$
   close #w
   end
   end sub

</lang> Image available at [[1]]

Mathematica

<lang Mathematica>ListDensityPlot[

Table[Table[
  FromDigits[BitXor[IntegerDigits[x, 2, 8], IntegerDigits[y, 2, 8]], 
   2], {x, 0, 255}], {y, 0, 255}]]</lang>

Output #1:

Mathematica output #1

<lang Mathematica>ArrayPlot[Array[BitXor, {511, 511}]]</lang> Output #2:

Mathematica output #2

MATLAB

<lang matlab>size = 256; [x,y] = meshgrid([0:size-1]);

c = bitxor(x,y);

colormap bone(size); image(c); axis equal;</lang> MATLAB output

OCaml

<lang ocaml>open Graphics

let () =

 open_graph "";
 resize_window 256 256;
 for y = 0 to pred (size_y()) do
   for x = 0 to pred (size_x()) do
     let v = (x lxor y) land 0xFF in
     set_color (rgb v (255 - v) 0);
     plot x y
   done;
 done;
 ignore(read_key())</lang>

Run with:

$ ocaml graphics.cma xor_pattern.ml

Output:

OCaml output

Octave

<lang Octave>size = 256; [x,y] = meshgrid([0:size-1]);

c = bitxor(x,y);

colormap(jet(size)); image(c); axis equal;</lang> Octave output

Perl

<lang perl>use GD;

my $img = new GD::Image(256, 256, 1);

for my $y(0..255) {

       for my $x(0..255) {
               my $color = $img->colorAllocate( abs(255 - $x - $y),  (255-$x) ^ $y , $x ^ (255-$y));
               $img->setPixel($x, $y, $color);
       }

}

print $img->png</lang> Perl output

PHP

<lang php>header("Content-Type: image/png");

$w = 256; $h = 256;

$im = imagecreate($w, $h)

   or die("Cannot Initialize new GD image stream");

$color = array(); for($i=0;$i<256;$i++) {

       array_push($color,imagecolorallocate($im,sin(($i)*(2*3.14/256))*128+128,$i/2,$i));

}

for($i=0;$i<$w;$i++) {

       for($j=0;$j<$h;$j++)
       {
               imagesetpixel($im,$i,$j,$color[$i^$j]);
       }

}

imagepng($im); imagedestroy($im);</lang>

PHP output

Prolog

Works with SWI-Prolog and his GUI XPCE. <lang Prolog>xor_pattern :- new(D, window('XOR Pattern')), send(D, size, size(512,512)), new(Img, image(@nil, width := 512, height := 512 , kind := pixmap)),

forall(between(0,511, I), ( forall(between(0,511, J), ( V is I xor J, R is (V * 1024) mod 65536, G is (65536 - V * 1024) mod 65536, ( V mod 2 =:= 0 -> B is (V * 4096) mod 65536  ; B is (65536 - (V * 4096)) mod 65536), send(Img, pixel(I, J, colour(@default, R, G, B))))))),

new(Bmp, bitmap(Img)), send(D, display, Bmp, point(0,0)), send(D, open). </lang>

PureBasic

<lang purebasic>#palletteSize = 128 Procedure.f XorPattern(x, y) ;compute the gradient value from the pixel values

 Protected result = x ! y
 ProcedureReturn Mod(result, #palletteSize) / #palletteSize

EndProcedure

Procedure drawPattern()

 StartDrawing(ImageOutput(0))
   DrawingMode(#PB_2DDrawing_Gradient)
   CustomGradient(@XorPattern())
   ;specify a gradient pallette from which only specific indexes will be used
   For i = 1 To #palletteSize 
     GradientColor(1 / i, i * $BACE9B) ; or alternatively use $BEEFDEAD
   Next 
   Box(0, 0, ImageWidth(0), ImageHeight(0))
 StopDrawing()

EndProcedure

If OpenWindow(0, 0, 0, 128, 128, "XOR Pattern", #PB_Window_SystemMenu)

 CreateImage(0, WindowWidth(0), WindowHeight(0))
 drawPattern()
 ImageGadget(0, 0, 0, ImageWidth(0), ImageHeight(0), ImageID(0))
 Repeat
   event = WaitWindowEvent(20)
 Until event = #PB_Event_CloseWindow

EndIf</lang> Sample display of PureBasic solution

Python

Library: PIL

<lang Python>import Image, ImageDraw

image = Image.new("RGB", (256, 256)) drawingTool = ImageDraw.Draw(image)

for x in range(256):

   for y in range(256):
       drawingTool.point((x, y), (0, x^y, 0))

del drawingTool image.save("xorpic.png", "PNG")</lang> Sample produced by the above code

Ruby

Uses Raster graphics operations/Ruby

Sample output from Ruby program

<lang ruby>load 'raster_graphics.rb'

class Pixmap

 def self.xor_pattern(width, height, rgb1, rgb2)
   # create colour table
   size = 256
   colours = Array.new(size) do |i|
     RGBColour.new(
       (rgb1.red + (rgb2.red - rgb1.red) * i / size), 
       (rgb1.green + (rgb2.green - rgb1.green) * i / size), 
       (rgb1.blue + (rgb2.blue - rgb1.blue) * i / size), 
     )
   end
   # create the image
   pixmap = new(width, height)
   pixmap.each_pixel do |x, y|
     pixmap[x,y] = colours[(x^y)%size]
   end
   pixmap
 end

end

img = Pixmap.xor_pattern(384, 384, RGBColour::RED, RGBColour::YELLOW) img.save_as_png('xorpattern.png')</lang>

Tcl

Library: Tk

<lang tcl>package require Tk

proc xorImage {img table} {

   set data {}
   set h [image height $img]
   set w [image width $img]
   for {set y 0} {$y < $h} {incr y} {

set row {} for {set x 0} {$x < $w} {incr x} { lappend row [lindex $table [expr {($x^$y) % [llength $table]}]] } lappend data $row

   }
   $img put $data

} proc inRange {i f t} {expr {$f + ($t-$f)*$i/255}} proc mkTable {rf rt gf gt bf bt} {

   for {set i 0} {$i < 256} {incr i} {

lappend tbl [format "#%02x%02x%02x" \ [inRange $i $rf $rt] [inRange $i $gf $gt] [inRange $i $bf $bt]]

   }
   return $tbl

}

set img [image create photo -width 512 -height 512] xorImage $img [mkTable 0 255 64 192 255 0] pack [label .l -image $img]</lang>

TI-83 BASIC

Due to the TI-83's 1 bit black and white display, this program uses the home screen and a gradient of characters. Since the TI-83 does not use a standard encoding, the first Sto→ to Str1 may be subjectively interpreted.


<lang ti-83b>PROGRAM:XORPATT " •.-,+-°-1+o*:πOX"→Str1

ClrHome

{0,0,0,0}→L1 {0,0,0,0)→L2

For(I,1,8,1) For(J,1,16,1) J→A I→B

If A>8 Then A-8→A 1→L1(1) Else 0→L1(1) End

If A>4 Then A-4→A 1→L1(2) Else 0→L1(2) End

If A>2 Then A-2→A 1→L1(3) Else 0→L1(3) End

If A>1 Then 1→L1(4) Else 0→L1(4) End

0→L2(1)

If B>4 Then B-4→B 1→L2(2) Else 0→L2(2) End

If B>2 Then B-2→B 1→L2(3) Else 0→L2(3) End

If B>1 Then 1→L2(4) Else 0→L2(4) End

L1≠L2→L3 8L3(1)+4L3(2)+2L3(3)+L3(4)→C Output(I,J,sub(Str1,C+1,1))

End End Pause </lang>

XPL0

<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations int X, Y; [SetVid($101); \set 640x480 graphics with 8-bit color port($3C8):= 0; \set color registers with beautiful shades for X:= 0 to 256-1 do

       [port($3C9):= X>>1;     \red
        port($3C9):= X>>3;     \green
        port($3C9):= X;        \blue
        ];

for Y:= 0 to 256-1 do \"color table" is array of 256 registers

   for X:= 0 to 256-1 do
       Point(X, Y, X|Y);       \"|" = XOR, not OR which is "!"

X:= ChIn(1); \wait for keystroke SetVid(3); \restore normal text mode ]</lang>