task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#PureBasic
PureBasic
Structure fileDataBits bitsToWrite.i bitsToRead.i outputByte.i inputByte.i EndStructure #BitsPerByte = SizeOf(Byte) * 8 #BitsPerInteger = SizeOf(Integer) * 8   Global Dim fileBitMask(8) Define i, x For i = 0 To 8 fileBitMask(i) = x x = (x << 1) + 1 Next   Global NewMap fileDataBits.fileDataBits() Procedure flushBits(fileID) If FindMapElement(fileDataBits(), Str(fileID)) If fileDataBits()\bitsToWrite > 0 WriteByte(fileID, fileDataBits()\outputByte << (#BitsPerByte - fileDataBits()\bitsToWrite)) fileDataBits()\bitsToWrite = 0 fileDataBits()\outputByte = 0 EndIf DeleteMapElement(fileDataBits()) EndIf EndProcedure   Procedure writeBits(fileID, Value.i, bitCount) Protected *fileData.fileDataBits = FindMapElement(fileDataBits(), Str(fileID)) If Not *fileData *fileData = AddMapElement(fileDataBits(), Str(fileID)) If Not *fileData: End: EndIf ;simple error check for lack of memory EndIf   Value << (#BitsPerInteger - bitCount) ;shift value so it's first bit (HSB) is in the highest position While bitCount > 0 If bitCount > #BitsPerByte - *fileData\bitsToWrite bitGroupSize = #BitsPerByte - *fileData\bitsToWrite Else bitGroupSize = bitCount EndIf   *fileData\outputByte << bitGroupSize *fileData\outputByte + (Value >> (#BitsPerInteger - bitGroupSize)) & fileBitMask(bitGroupSize) Value << bitGroupSize *fileData\bitsToWrite + bitGroupSize If *fileData\bitsToWrite = #BitsPerByte WriteByte(fileID, *fileData\outputByte) *fileData\bitsToWrite = 0 *fileData\outputByte = 0 EndIf bitCount - bitGroupSize Wend EndProcedure   Procedure.i readBits(fileID, bitCount) Protected *fileData.fileDataBits = FindMapElement(fileDataBits(), Str(fileID)) If Not *fileData *fileData = AddMapElement(fileDataBits(), Str(fileID)) If Not *fileData: End: EndIf ;simple error check for lack of memory EndIf   Protected Value.i, bitGroupSize While bitCount > 0 If *fileData\bitsToRead = 0 If Not Eof(fileID) *fileData\inputByte = ReadByte(fileID) *fileData\bitsToRead = #BitsPerByte Else flushBits(fileID) Break ;simple error check aborts if nothing left to read EndIf EndIf   If bitCount > *fileData\bitsToRead bitGroupSize = *fileData\bitsToRead Else bitGroupSize = bitCount EndIf Value << bitGroupSize Value + (*fileData\inputByte >> (#BitsPerByte - bitGroupSize)) & fileBitMask(bitGroupSize) ;shift last bit being read in byte to the lowest position *fileData\inputByte << bitGroupSize *fileData\bitsToRead - bitGroupSize bitCount - bitGroupSize Wend ProcedureReturn Value EndProcedure   ;test Define testWriteString.s, testReadString.s, fileNum, result.s testWriteString = "This is an ascii string that will be crunched, written, read and expanded." fileNum = CreateFile(#PB_Any, "BitIO_Test.dat") If fileNum For i = 1 To Len(testWriteString) writeBits(fileNum, Asc(Mid(testWriteString, i, 1)), 7) Next flushBits(fileNum) CloseFile(fileNum) EndIf   fileNum = ReadFile(#PB_Any, "BitIO_Test.dat") If fileNum For i = 1 To Len(testWriteString) testReadString + Chr(readBits(fileNum, 7)) Next flushBits(fileNum) CloseFile(fileNum) EndIf   result = "Original ascii string is " + Str(Len(testWriteString)) + " bytes." + #LF$ result + "Filesize written is " + Str(FileSize("test.xxx")) + " bytes." + #LF$ If testReadString = testWriteString result + "The expanded string is the same as the original." + #LF$ Else result + "The expanded string is not the same as the original." + #LF$ EndIf result + "Expanded string = '" + testReadString + "'"   MessageRequester("Results", result)
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Perl
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;
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Phix
Phix
-- demo\rosetta\Bitmap_write_ppm.exw constant dimx = 512, dimy = 512 constant fn = open("first.ppm","wb") -- b - binary mode sequence color printf(fn, "P6\n%d %d\n255\n", {dimx,dimy}) for y=0 to dimy-1 do for x=0 to dimx-1 do color = {remainder(x,256), -- red remainder(y,256), -- green remainder(x*y,256)} -- blue puts(fn,color) end for end for close(fn)
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Ruby
Ruby
class Pixmap # 'open' is a class method def self.open(filename) bitmap = nil File.open(filename, 'r') do |f| header = [f.gets.chomp, f.gets.chomp, f.gets.chomp] width, height = header[1].split.map {|n| n.to_i } if header[0] != 'P6' or header[2] != '255' or width < 1 or height < 1 raise StandardError, "file '#{filename}' does not start with the expected header" end f.binmode bitmap = self.new(width, height) height.times do |y| width.times do |x| # read 3 bytes red, green, blue = f.read(3).unpack('C3') bitmap[x,y] = RGBColour.new(red, green, blue) end end end bitmap end end   # create an image: a green cross on a blue background colour_bitmap = Pixmap.new(20, 30) colour_bitmap.fill(RGBColour::BLUE) colour_bitmap.height.times {|y| [9,10,11].each {|x| colour_bitmap[x,y]=RGBColour::GREEN}} colour_bitmap.width.times {|x| [14,15,16].each {|y| colour_bitmap[x,y]=RGBColour::GREEN}} colour_bitmap.save('testcross.ppm')   # then, convert to grayscale Pixmap.open('testcross.ppm').to_grayscale!.save('testgray.ppm')
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#BQN
BQN
{1?34} 34 {⟨⟩?34} ERROR
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Bracmat
Bracmat
bool? value = null
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Sidef
Sidef
func caesar(msg, key, decode=false) { decode && (key = (26 - key)); msg.gsub(/([A-Z])/i, {|c| ((c.uc.ord - 65 + key) % 26) + 65 -> chr}); };   var msg = 'THE FIVE BOXING WIZARDS JUMP QUICKLY';   var enc = caesar(msg, 10); var dec = caesar(enc, 10, true);   say "msg: #{msg}"; say "enc: #{enc}"; say "dec: #{dec}";
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input: [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance). Notes; The headings and indices can be calculated from this pseudocode: for i in 0..32 inclusive: heading = i * 11.25 case i %3: if 1: heading += 5.62; break if 2: heading -= 5.62; break end index = ( i mod 32) + 1 The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
#Action.21
Action!
INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   DEFINE PTR="CARD"   PROC InitNames(PTR ARRAY names) names(0)="N" names(1)="NbE" names(2)="NNE" names(3)="NEbN" names(4)="NE" names(5)="NEbE" names(6)="ENE" names(7)="EbN" names(8)="E" names(9)="EbS" names(10)="ESE" names(11)="SEbE" names(12)="SE" names(13)="SEbS" names(14)="SSE" names(15)="SbE" names(16)="S" names(17)="SbW" names(18)="SSW" names(19)="SWbS" names(20)="SW" names(21)="SWbW" names(22)="WSW" names(23)="WbS" names(24)="W" names(25)="WbN" names(26)="WNW" names(27)="NWbW" names(28)="NW" names(29)="NWbN" names(30)="NNW" names(31)="NbW" names(32)="N" RETURN   PROC PrintIndex(BYTE i) CHAR ARRAY s(5)   StrB(i,s) PrintF("%2S",s) RETURN   BYTE FUNC FindDot(CHAR ARRAY s) BYTE i   FOR i=1 TO s(0) DO IF s(i)='. THEN RETURN (i) FI OD RETURN (0)   PROC PrintAngle(REAL POINTER a) CHAR ARRAY s(10) BYTE pos   StrR(a,s) pos=FindDot(s) IF pos=0 THEN s(0)==+3 s(s(0)-2)='. s(s(0)-1)='0 s(s(0)-0)='0 ELSEIF pos=s(0)-1 THEN s(0)==+1 s(s(0)-0)='0 FI PrintF("%6S",s) RETURN   INT FUNC GetIndex(REAL POINTER a) REAL r32,r360,r1,r2   IntToReal(32,r32) IntToReal(360,r360) RealMult(a,r32,r1) RealDiv(r1,r360,r2) RETURN (RealToInt(r2))   PROC Main() DEFINE COUNT="33" PTR ARRAY names(COUNT) INT i,m,ind,x,y REAL ri,r11_25,r5_62,rh,r1   Put(125) PutE() ;clear the screen InitNames(names) ValR("11.25",r11_25) ValR("5.62",r5_62) FOR i=0 TO 32 DO IntToReal(i,ri) RealMult(ri,r11_25,rh) m=i MOD 3 IF m=1 THEN RealAdd(rh,r5_62,r1) RealAssign(r1,rh) ELSEIF m=2 THEN RealSub(rh,r5_62,r1) RealAssign(r1,rh) FI ind=GetIndex(rh)   IF i<16 THEN x=2 y=i+1 ELSE x=20 y=i-15 FI Position(x,y) PrintIndex(ind MOD (COUNT-1)+1) x==+3 Position(x,y) Print(names(ind)) x==+5 Position(x,y) PrintAngle(rh) OD RETURN
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height. Test task Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows: Convert image to grayscale; Compute the histogram Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance. Replace each pixel of luminance lesser than the median to black, and others to white. Use read/write ppm file, and grayscale image solutions.
#D
D
import grayscale_image;   Color findSingleChannelMedian(Color)(in Image!Color img) pure nothrow @nogc if (Color.tupleof.length == 1) // Hack. in { assert(img !is null); } body { size_t[Color.max + 1] hist; foreach (immutable c; img.image) hist[c]++;   // Slower indexes, but not significantly so. auto from = Color(0); auto to = Color(hist.length - 1);   auto left = hist[from]; auto right = hist[to];   while (from != to) if (left < right) { from++; left += hist[from]; } else { to--; right += hist[to]; }   return from; }   Image!Color binarizeInPlace(Color)(Image!Color img, in Color thresh) pure nothrow @nogc in { assert(img !is null); } body { foreach (immutable i, ref c; img.image) c = (c < thresh) ? Color.min : Color.max; return img; }   void main() { Image!RGB im; im.loadPPM6("quantum_frog.ppm"); auto img = im.rgb2grayImage(); img.binarizeInPlace(img.findSingleChannelMedian()) .savePGM("quantum_frog_bin.pgm"); }
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate. All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer. If any operation is not available in your language, note it.
#6502_Assembly
6502 Assembly
LDA #$05 STA temp ;temp equals 5 for the following
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#Action.21
Action!
INCLUDE "H6:RGBLINE.ACT" ;from task Bresenham's line algorithm INCLUDE "H6:REALMATH.ACT"   RGB black,yellow,violet,blue   TYPE IntPoint=[INT x,y]   PROC QuadraticBezier(RgbImage POINTER img IntPoint POINTER p1,p2,p3 RGB POINTER col) INT i,n=[20],prevX,prevY,nextX,nextY REAL one,two,ri,rn,rt,ra,rb,rc,tmp1,tmp2,tmp3 REAL x1,y1,x2,y2,x3,y3   IntToReal(p1.x,x1) IntToReal(p1.y,y1) IntToReal(p2.x,x2) IntToReal(p2.y,y2) IntToReal(p3.x,x3) IntToReal(p3.y,y3) IntToReal(1,one) IntToReal(2,two) IntToReal(n,rn) FOR i=0 TO n DO prevX=nextX prevY=nextY   IntToReal(i,ri) RealDiv(ri,rn,rt)  ;t=i/n   RealSub(one,rt,tmp1)  ;tmp1=1-t RealMult(tmp1,tmp1,ra)  ;a=(1-t)^2   RealMult(two,rt,tmp2)  ;tmp2=2*t RealMult(tmp2,tmp1,rb)  ;b=2*t*(1-t)   RealMult(rt,rt,rc)  ;c=t^2   RealMult(ra,x1,tmp1)  ;tmp1=a*x1 RealMult(rb,x2,tmp2)  ;tmp2=b*x2 RealAdd(tmp1,tmp2,tmp3) ;tmp3=a*x1+b*x2 RealMult(rc,x3,tmp1)  ;tmp1=c*x3 RealAdd(tmp3,tmp1,tmp2) ;tmp2=a*x1+b*x2+c*x3 nextX=Round(tmp2)   RealMult(ra,y1,tmp1)  ;tmp1=a*y1 RealMult(rb,y2,tmp2)  ;tmp2=b*y2 RealAdd(tmp1,tmp2,tmp3) ;tmp3=a*y1+b*y2 RealMult(rc,y3,tmp1)  ;tmp1=c*y3 RealAdd(tmp3,tmp1,tmp2) ;tmp2=a*y1+b*y2+c*y3 nextY=Round(tmp2)   IF i>0 THEN RgbLine(img,prevX,prevY,nextX,nextY,col) FI OD RETURN   PROC DrawImage(RgbImage POINTER img BYTE x,y) RGB POINTER ptr BYTE i,j   ptr=img.data FOR j=0 TO img.h-1 DO FOR i=0 TO img.w-1 DO IF RgbEqual(ptr,yellow) THEN Color=1 ELSEIF RgbEqual(ptr,violet) THEN Color=2 ELSEIF RgbEqual(ptr,blue) THEN Color=3 ELSE Color=0 FI Plot(x+i,y+j) ptr==+RGBSIZE OD OD RETURN   PROC Main() RgbImage img BYTE CH=$02FC,width=[70],height=[40] BYTE ARRAY ptr(8400) IntPoint p1,p2,p3   Graphics(7+16) SetColor(0,13,12) ;yellow SetColor(1,4,8)  ;violet SetColor(2,8,6)  ;blue SetColor(4,0,0)  ;black   RgbBlack(black) RgbYellow(yellow) RgbViolet(violet) RgbBlue(blue)   InitRgbImage(img,width,height,ptr) FillRgbImage(img,black)   p1.x=0 p1.y=3 p2.x=47 p2.y=39 p3.x=69 p3.y=12 RgbLine(img,p1.x,p1.y,p2.x,p2.y,blue) RgbLine(img,p2.x,p2.y,p3.x,p3.y,blue) QuadraticBezier(img,p1,p2,p3,yellow) SetRgbPixel(img,p1.x,p1.y,violet) SetRgbPixel(img,p2.x,p2.y,violet) SetRgbPixel(img,p3.x,p3.y,violet)   DrawImage(img,(160-width)/2,(96-height)/2)   DO UNTIL CH#$FF OD CH=$FF RETURN
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#ALGOL_68
ALGOL 68
# -*- coding: utf-8 -*- #   circle OF class image := ( REF IMAGE picture, POINT center, INT radius, PIXEL color )VOID: BEGIN INT f := 1 - radius, POINT ddf := (0, -2 * radius), df := (0, radius); picture [x OF center, y OF center + radius] := picture [x OF center, y OF center - radius] := picture [x OF center + radius, y OF center] := picture [x OF center - radius, y OF center] := color; WHILE x OF df < y OF df DO IF f >= 0 THEN y OF df -:= 1; y OF ddf +:= 2; f +:= y OF ddf FI; x OF df +:= 1; x OF ddf +:= 2; f +:= x OF ddf + 1; picture [x OF center + x OF df, y OF center + y OF df] := picture [x OF center - x OF df, y OF center + y OF df] := picture [x OF center + x OF df, y OF center - y OF df] := picture [x OF center - x OF df, y OF center - y OF df] := picture [x OF center + y OF df, y OF center + x OF df] := picture [x OF center - y OF df, y OF center + x OF df] := picture [x OF center + y OF df, y OF center - x OF df] := picture [x OF center - y OF df, y OF center - x OF df] := color OD END # circle #;   SKIP
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#Python
Python
class BitWriter(object): def __init__(self, f): self.accumulator = 0 self.bcount = 0 self.out = f   def __enter__(self): return self   def __exit__(self, exc_type, exc_val, exc_tb): self.flush()   def __del__(self): try: self.flush() except ValueError: # I/O operation on closed file. pass   def _writebit(self, bit): if self.bcount == 8: self.flush() if bit > 0: self.accumulator |= 1 << 7-self.bcount self.bcount += 1   def writebits(self, bits, n): while n > 0: self._writebit(bits & 1 << n-1) n -= 1   def flush(self): self.out.write(bytearray([self.accumulator])) self.accumulator = 0 self.bcount = 0     class BitReader(object): def __init__(self, f): self.input = f self.accumulator = 0 self.bcount = 0 self.read = 0   def __enter__(self): return self   def __exit__(self, exc_type, exc_val, exc_tb): pass   def _readbit(self): if not self.bcount: a = self.input.read(1) if a: self.accumulator = ord(a) self.bcount = 8 self.read = len(a) rv = (self.accumulator & (1 << self.bcount-1)) >> self.bcount-1 self.bcount -= 1 return rv   def readbits(self, n): v = 0 while n > 0: v = (v << 1) | self._readbit() n -= 1 return v   if __name__ == '__main__': import os import sys # Determine this module's name from it's file name and import it. module_name = os.path.splitext(os.path.basename(__file__))[0] bitio = __import__(module_name)   with open('bitio_test.dat', 'wb') as outfile: with bitio.BitWriter(outfile) as writer: chars = '12345abcde' for ch in chars: writer.writebits(ord(ch), 7)   with open('bitio_test.dat', 'rb') as infile: with bitio.BitReader(infile) as reader: chars = [] while True: x = reader.readbits(7) if not reader.read: # End-of-file? break chars.append(chr(x)) print(''.join(chars))  
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#PHP
PHP
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; } //Fills a rectangle, or the whole image with black by default 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');
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Rust
Rust
  parser.rs: use super::{Color, ImageFormat}; use std::str::from_utf8; use std::str::FromStr;   pub fn parse_version(input: &[u8]) -> nom::IResult<&[u8], ImageFormat> { use nom::branch::alt; use nom::bytes::complete::tag; use nom::character::complete::line_ending; use nom::combinator::map; use nom::sequence::terminated;   // starts with P3/P6 ends with a CR/LF terminated( alt(( map(tag("P3".as_bytes()), |_| ImageFormat::P3), map(tag("P6".as_bytes()), |_| ImageFormat::P6), )), line_ending, )(input) }   pub fn parse_image_attributes(input: &[u8]) -> nom::IResult<&[u8], (usize, usize, usize)> { use nom::character::complete::line_ending; use nom::character::complete::{digit1, space1}; use nom::sequence::terminated; use nom::sequence::tuple;   // 3 numbers separated by spaces ends with a CR/LF terminated(tuple((digit1, space1, digit1, space1, digit1)), line_ending)(input).map( |(next_input, result)| { ( next_input, ( usize::from_str_radix(from_utf8(result.0).unwrap(), 10).unwrap(), usize::from_str_radix(from_utf8(result.2).unwrap(), 10).unwrap(), usize::from_str_radix(from_utf8(result.4).unwrap(), 10).unwrap(), ), ) }, ) }   pub fn parse_color_binary(input: &[u8]) -> nom::IResult<&[u8], Color> { use nom::number::complete::u8 as nom_u8; use nom::sequence::tuple;   tuple((nom_u8, nom_u8, nom_u8))(input).map(|(next_input, res)| { ( next_input, Color { red: res.0, green: res.1, blue: res.2, }, ) }) }   pub fn parse_data_binary(input: &[u8]) -> nom::IResult<&[u8], Vec<Color>> { use nom::multi::many0; many0(parse_color_binary)(input) }   pub fn parse_color_ascii(input: &[u8]) -> nom::IResult<&[u8], Color> { use nom::character::complete::{digit1, space0, space1}; use nom::sequence::tuple;   tuple((digit1, space1, digit1, space1, digit1, space0))(input).map(|(next_input, res)| { ( next_input, Color { red: u8::from_str(from_utf8(res.0).unwrap()).unwrap(), green: u8::from_str(from_utf8(res.2).unwrap()).unwrap(), blue: u8::from_str(from_utf8(res.4).unwrap()).unwrap(), }, ) }) }   pub fn parse_data_ascii(input: &[u8]) -> nom::IResult<&[u8], Vec<Color>> { use nom::multi::many0; many0(parse_color_ascii)(input) }     lib.rs: extern crate nom; extern crate thiserror; mod parser;   use std::default::Default; use std::fmt; use std::io::{BufWriter, Error, Write}; use std::ops::{Index, IndexMut}; use std::{fs::File, io::Read}; use thiserror::Error;   #[derive(Copy, Clone, Default, PartialEq, Debug)] pub struct Color { pub red: u8, pub green: u8, pub blue: u8, }   #[derive(Copy, Clone, PartialEq, Debug)] pub enum ImageFormat { P3, P6, }   impl From<&str> for ImageFormat { fn from(i: &str) -> Self { match i.to_lowercase().as_str() { "p3" => ImageFormat::P3, "p6" => ImageFormat::P6, _ => unimplemented!("no other formats supported"), } } }   impl fmt::Display for ImageFormat { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { ImageFormat::P3 => { write!(f, "P3") } ImageFormat::P6 => { write!(f, "P6") } } } }   #[derive(Error, Debug)] pub enum ImageError { #[error("File not found")] FileNotFound, #[error("File not readable")] FileNotReadable, #[error("Invalid header information")] InvalidHeader, #[error("Invalid information in the data block")] InvalidData, #[error("Invalid max color information")] InvalidMaxColor, #[error("File is incomplete")] IncompleteFile, #[error("unknown data store error")] Unknown, } pub struct Image { pub format: ImageFormat, pub width: usize, pub height: usize, pub data: Vec<Color>, }   impl Image { #[must_use] pub fn new(width: usize, height: usize) -> Self { Self { format: ImageFormat::P6, width, height, data: vec![Color::default(); width * height], } }   pub fn fill(&mut self, color: Color) { for elem in &mut self.data { *elem = color; } }   /// # Errors /// /// Will return `Error` if `filename` does not exist or the user does not have /// permission to write to it, or the write operation fails. pub fn write_ppm(&self, filename: &str) -> Result<(), Error> { let file = File::create(filename)?; let mut writer = BufWriter::new(file); writeln!(&mut writer, "{}", self.format.to_string())?; writeln!(&mut writer, "{} {} 255", self.width, self.height)?; match self.format { ImageFormat::P3 => { writer.write_all( &self .data .iter() .flat_map(|color| { vec![ color.red.to_string(), color.green.to_string(), color.blue.to_string(), ] }) .collect::<Vec<String>>() .join(" ") .as_bytes(), )?; } ImageFormat::P6 => { writer.write_all( &self .data .iter() .flat_map(|color| vec![color.red, color.green, color.blue]) .collect::<Vec<u8>>(), )?; } } Ok(()) }   /// # Panics /// /// Panics if the format is not P6 or P3 PPM /// # Errors /// /// Will return `Error` if `filename` does not exist or the user does not have /// permission to read it or the read operation fails, or the file format does not /// match the specification pub fn read_ppm(filename: &str) -> Result<Image, ImageError> { let mut file = File::open(filename).map_err(|_| ImageError::FileNotFound)?; let mut data: Vec<u8> = Vec::new(); file.read_to_end(&mut data) .map_err(|_| ImageError::FileNotReadable)?;   let (i, format) = parser::parse_version(&data).map_err(|_| ImageError::InvalidHeader)?; let (i, (width, height, max_color)) = parser::parse_image_attributes(i).map_err(|_| ImageError::InvalidHeader)?;   if max_color != 255 { return Err(ImageError::InvalidMaxColor); }   let (_, data) = match format { ImageFormat::P3 => parser::parse_data_ascii(i).map_err(|_| ImageError::InvalidData)?, ImageFormat::P6 => parser::parse_data_binary(i).map_err(|_| ImageError::InvalidData)?, };   if data.len() != height * width { return Err(ImageError::IncompleteFile); };   Ok(Image { format, width, height, data, }) } }   impl Index<(usize, usize)> for Image { type Output = Color;   fn index(&self, (x, y): (usize, usize)) -> &Color { &self.data[x + y * self.width] } }   impl IndexMut<(usize, usize)> for Image { fn index_mut(&mut self, (x, y): (usize, usize)) -> &mut Color { &mut self.data[x + y * self.width] } }     use bitmap::Image;   // see read_ppm implementation in the bitmap library   pub fn main() { // read a PPM image, which was produced by the write-a-ppm-file task let image = Image::read_ppm("./test_image.ppm").unwrap();   println!("Read using nom parsing:"); println!("Format: {:?}", image.format); println!("Dimensions: {} x {}", image.height, image.width); }  
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Scala
Scala
import scala.io._ import scala.swing._ import java.io._ import java.awt.Color import javax.swing.ImageIcon   object Pixmap { private case class PpmHeader(format:String, width:Int, height:Int, maxColor:Int)   def load(filename:String):Option[RgbBitmap]={ implicit val in=new BufferedInputStream(new FileInputStream(filename)) val header=readHeader if(header.format=="P6") { val bm=new RgbBitmap(header.width, header.height); for(y <- 0 until bm.height; x <- 0 until bm.width; c=readColor) bm.setPixel(x, y, c) return Some(bm) } None }   private def readHeader(implicit in:InputStream)={ var format=readLine   var line=readLine while(line.startsWith("#")) //skip comments line=readLine   val parts=line.split("\\s") val width=parts(0).toInt val height=parts(1).toInt val maxColor=readLine.toInt   new PpmHeader(format, width, height, maxColor) }   private def readColor(implicit in:InputStream)=new Color(in.read, in.read, in.read)   private def readLine(implicit in:InputStream)={ var out="" var b=in.read while(b!=0xA){out+=b.toChar; b=in.read} out } }
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Brainf.2A.2A.2A
Brainf***
bool? value = null
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#C
C
bool? value = null
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Sinclair_ZX81_BASIC
Sinclair ZX81 BASIC
10 INPUT KEY 20 INPUT T$ 30 LET C$="" 40 FOR I=1 TO LEN T$ 50 LET L$=T$(I) 60 IF L$<"A" OR L$>"Z" THEN GOTO 100 70 LET L$=CHR$ (CODE L$+KEY) 80 IF L$>"Z" THEN LET L$=CHR$ (CODE L$-26) 90 IF L$<"A" THEN LET L$=CHR$ (CODE L$+26) 100 LET C$=C$+L$ 110 NEXT I 120 PRINT C$
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input: [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance). Notes; The headings and indices can be calculated from this pseudocode: for i in 0..32 inclusive: heading = i * 11.25 case i %3: if 1: heading += 5.62; break if 2: heading -= 5.62; break end index = ( i mod 32) + 1 The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
#Ada
Ada
with Ada.Text_IO;   procedure Box_The_Compass is   type Degrees is digits 5 range 0.00 .. 359.99; type Index_Type is mod 32;   function Long_Name(Short: String) return String is   function Char_To_Name(Char: Character) return String is begin case Char is when 'N' | 'n' => return Char & "orth"; when 'S' | 's' => return Char & "outh"; when 'E' | 'e' => return Char & "ast"; when 'W' | 'w' => return Char & "est"; when 'b' => return " by "; when '-' => return "-"; when others => raise Constraint_Error; end case; end Char_To_Name;   begin if Short'Length = 0 or else Short(Short'First)=' ' then return ""; else return Char_To_Name(Short(Short'First)) & Long_Name(Short(Short'First+1 .. Short'Last)); end if; end Long_Name;   procedure Put_Line(Angle: Degrees) is   function Index(D: Degrees) return Index_Type is begin return Index_Type(Integer(Degrees'Rounding(D/11.25)) mod 32); end Index;   I: Integer := Integer(Index(Angle))+1; package DIO is new Ada.Text_IO.Float_IO(Degrees); Abbr: constant array(Index_Type) of String(1 .. 4)  := ("N ", "Nbe ", "N-ne", "Nebn", "Ne ", "Nebe", "E-ne", "Ebn ", "E ", "Ebs ", "E-se", "Sebe", "Se ", "Sebs", "S-se", "Sbe ", "S ", "Sbw ", "S-sw", "Swbs", "Sw ", "Swbw", "W-sw", "Wbs ", "W ", "Wbn ", "W-nw", "Nwbw", "Nw ", "Nwbn", "N-nw", "Nbw ");   begin DIO.Put(Angle, Fore => 3, Aft => 2, Exp => 0); -- format "zzx.xx" Ada.Text_IO.Put(" |"); if I <= 9 then Ada.Text_IO.Put(" "); end if; Ada.Text_IO.Put_Line(" " & Integer'Image(I) & " | " & Long_Name(Abbr(Index(Angle)))); end Put_Line;   Difference: constant array(0..2) of Degrees'Base  := (0=> 0.0, 1=> +5.62, 2=> - 5.62);   begin Ada.Text_IO.Put_Line(" angle | box | compass point"); Ada.Text_IO.Put_Line(" ---------------------------------"); for I in 0 .. 32 loop Put_Line(Degrees(Degrees'Base(I) * 11.25 + Difference(I mod 3))); end loop; end Box_The_Compass;
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height. Test task Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows: Convert image to grayscale; Compute the histogram Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance. Replace each pixel of luminance lesser than the median to black, and others to white. Use read/write ppm file, and grayscale image solutions.
#FBSL
FBSL
#DEFINE WM_CLOSE 16   DIM colored = ".\LenaClr.bmp", grayscale = ".\LenaGry.bmp", blackwhite = ".\LenaBnw.bmp" DIM head, tail, r, g, b, l, m, ptr, blobsize = 54 ' sizeof BMP headers   FILEGET(FILEOPEN(colored, BINARY), FILELEN(colored)): FILECLOSE(FILEOPEN) ' fill buffer head = @FILEGET + blobsize: tail = @FILEGET + FILELEN ' get buffer bounds   ToGrayScale() ' derive grayscale image and save it to disk ToBlackAndWhite() ' ditto, black-and-white image   FBSLSETTEXT(ME, "Clr") ' display colored image FBSLTILE(ME, FBSLLOADIMAGE(colored)) RESIZE(ME, 0, 0, 136, 162): CENTER(ME): SHOW(ME)   FBSLTILE(FBSLFORM("Gry"), FBSLLOADIMAGE(grayscale)) ' ditto, grayscale RESIZE(FBSLFORM, 0, 0, 136, 162): CENTER(FBSLFORM): SHOW(FBSLFORM)   FBSLTILE(FBSLFORM("B/w"), FBSLLOADIMAGE(blackwhite)) ' ditto, black-and-white RESIZE(FBSLFORM, 0, 0, 136, 162): CENTER(FBSLFORM): SHOW(FBSLFORM)   BEGIN EVENTS ' main message loop IF CBMSG = WM_CLOSE THEN DESTROY(ME) ' click any [X] button to quit END EVENTS   SUB ToGrayScale() FOR ptr = head TO tail STEP 3 b = PEEK(ptr + 0, 1) ' Windows stores colors in BGR order g = PEEK(ptr + 1, 1) r = PEEK(ptr + 2, 1) l = 0.2126 * r + 0.7152 * g + 0.0722 * b ' derive luminance POKE(ptr + 0, CHR(l))(ptr + 1, CHR)(ptr + 2, CHR) ' set pixel to shade of gray m = m + l NEXT FILEPUT(FILEOPEN(grayscale, BINARY_NEW), FILEGET): FILECLOSE(FILEOPEN) ' save grayscale image END SUB   SUB ToBlackAndWhite() STATIC b = CHR(0), w = CHR(255) ' initialize once   m = m / (tail - head) * 3 ' derive median FOR ptr = head TO tail STEP 3 IF PEEK(ptr + 0, 1) < m THEN ' set pixel black POKE(ptr + 0, b)(ptr + 1, b)(ptr + 2, b) ELSE ' set pixel white POKE(ptr + 0, w)(ptr + 1, w)(ptr + 2, w) END IF NEXT FILEPUT(FILEOPEN(blackwhite, BINARY_NEW), FILEGET): FILECLOSE(FILEOPEN) ' save b/w image END SUB
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate. All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer. If any operation is not available in your language, note it.
#68000_Assembly
68000 Assembly
MOVE.W #$100,D0 MOVE.W #$200,D1 AND.W D0,D1
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#Ada
Ada
procedure Quadratic_Bezier ( Picture  : in out Image; P1, P2, P3 : Point; Color  : Pixel; N  : Positive := 20 ) is Points : array (0..N) of Point; begin for I in Points'Range loop declare T : constant Float := Float (I) / Float (N); A : constant Float := (1.0 - T)**2; B : constant Float := 2.0 * T * (1.0 - T); C : constant Float := T**2; begin Points (I).X := Positive (A * Float (P1.X) + B * Float (P2.X) + C * Float (P3.X)); Points (I).Y := Positive (A * Float (P1.Y) + B * Float (P2.Y) + C * Float (P3.Y)); end; end loop; for I in Points'First..Points'Last - 1 loop Line (Picture, Points (I), Points (I + 1), Color); end loop; end Quadratic_Bezier;
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#BBC_BASIC
BBC BASIC
Width% = 200 Height% = 200   REM Set window size: VDU 23,22,Width%;Height%;8,16,16,128   REM Draw quadratic Bézier curve: PROCbezierquad(10,100, 250,270, 150,20, 20, 0,0,0) END   DEF PROCbezierquad(x1,y1,x2,y2,x3,y3,n%,r%,g%,b%) LOCAL i%, t, t1, a, b, c, p{()} DIM p{(n%) x%,y%}   FOR i% = 0 TO n% t = i% / n% t1 = 1 - t a = t1^2 b = 2 * t * t1 c = t^2 p{(i%)}.x% = INT(a * x1 + b * x2 + c * x3 + 0.5) p{(i%)}.y% = INT(a * y1 + b * y2 + c * y3 + 0.5) NEXT   FOR i% = 0 TO n%-1 PROCbresenham(p{(i%)}.x%,p{(i%)}.y%,p{(i%+1)}.x%,p{(i%+1)}.y%, \ \ r%,g%,b%) NEXT ENDPROC   DEF PROCbresenham(x1%,y1%,x2%,y2%,r%,g%,b%) LOCAL dx%, dy%, sx%, sy%, e dx% = ABS(x2% - x1%) : sx% = SGN(x2% - x1%) dy% = ABS(y2% - y1%) : sy% = SGN(y2% - y1%) IF dx% < dy% e = dx% / 2 ELSE e = dy% / 2 REPEAT PROCsetpixel(x1%,y1%,r%,g%,b%) IF x1% = x2% IF y1% = y2% EXIT REPEAT IF dx% > dy% THEN x1% += sx% : e -= dy% : IF e < 0 e += dx% : y1% += sy% ELSE y1% += sy% : e -= dx% : IF e < 0 e += dy% : x1% += sx% ENDIF UNTIL FALSE ENDPROC   DEF PROCsetpixel(x%,y%,r%,g%,b%) COLOUR 1,r%,g%,b% GCOL 1 LINE x%*2,y%*2,x%*2,y%*2 ENDPROC
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#C
C
void quad_bezier( image img, unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2, unsigned int x3, unsigned int y3, color_component r, color_component g, color_component b );
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#bash
bash
#! /bin/bash # Based on https://en.wikipedia.org/wiki/Midpoint_circle_algorithm   function putpixel { echo -en "\e[$2;$1H#" }   function drawcircle { x0=$1 y0=$2 radius=$3   for y in $( seq $((y0-radius)) $((y0+radius)) ) do echo -en "\e[${y}H" for x in $( seq $((x0+radius)) ) do echo -n "-" done done   x=$((radius-1)) y=0 dx=1 dy=1 err=$((dx-(radius<<1)))   while [ $x -ge $y ] do putpixel $(( x0 + x )) $(( y0 + y )) putpixel $(( x0 + y )) $(( y0 + x )) putpixel $(( x0 - y )) $(( y0 + x )) putpixel $(( x0 - x )) $(( y0 + y )) putpixel $(( x0 - x )) $(( y0 - y )) putpixel $(( x0 - y )) $(( y0 - x )) putpixel $(( x0 + y )) $(( y0 - x )) putpixel $(( x0 + x )) $(( y0 - y ))   if [ $err -le 0 ] then ((++y)) ((err+=dy)) ((dy+=2)) fi if [ $err -gt 0 ] then ((--x)) ((dx+=2)) ((err+=dx-(radius<<1))) fi done }   clear drawcircle 13 13 11 echo -en "\e[H"  
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#Racket
Racket
  #lang racket   (require racket/fixnum)   (define (make-bit-writer file) (define o (open-output-file file #:exists 'truncate)) (define b+len (cons 0 0)) (define (write-some-bits! n len) (if (<= 8 len) (begin (write-byte (fxand n #xFF) o) (write-some-bits! (fxrshift n 8) (- len 8))) (set! b+len (cons n len)))) (define write-bits (case-lambda [(n) (if (eof-object? n) (begin (when (positive? (cdr b+len)) (write-byte (car b+len) o)) (close-output-port o)) (write-bits n (integer-length n)))] [(n nbits) (when (< nbits (integer-length n)) (error 'write-bits "integer bigger than number of bits")) (write-some-bits! (fxior (car b+len) (fxlshift n (cdr b+len))) (+ (cdr b+len) nbits))])) write-bits)   (define (make-bit-reader file) (define i (open-input-file file)) (define b+len (cons 0 0)) (define (read-some-bits wanted n len) (if (<= wanted len) (begin0 (fxand n (sub1 (expt 2 wanted))) (set! b+len (cons (fxrshift n wanted) (- len wanted)))) (read-some-bits wanted (+ n (fxlshift (read-byte i) len)) (+ len 8)))) (define (read-bits n) (if (eof-object? n) (close-input-port i) (read-some-bits n (car b+len) (cdr b+len)))) read-bits)   (define (crunch str file) (define out (make-bit-writer file)) (for ([b (in-bytes (string->bytes/utf-8 str))]) (out b 7)) (out eof))   (define (decrunch file) (define in (make-bit-reader file)) (define bs (for/list ([i (in-range (quotient (* 8 (file-size file)) 7))]) (in 7))) (in eof) (bytes->string/utf-8 (list->bytes bs)))   (define orig (string-append "This is an ascii string that will be" " crunched, written, read and expanded."))   (crunch orig "crunched.out")   (printf "Decrunched string ~aequal to original.\n" (if (equal? orig (decrunch "crunched.out")) "" "NOT "))  
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#Raku
Raku
sub encode-ascii(Str $s) { my @b = flat $s.ords».fmt("%07b")».comb; @b.push(0) until @b %% 8; # padding Buf.new: gather while @b { take reduce * *2+*, (@b.pop for ^8) } }   sub decode-ascii(Buf $b) { my @b = flat $b.list».fmt("%08b")».comb; @b.shift until @b %% 7; # remove padding @b = gather while @b { take reduce * *2+*, (@b.pop for ^7) } return [~] @b».chr; } say my $encode = encode-ascii 'STRING'; say decode-ascii $encode;
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#PicoLisp
PicoLisp
(de ppmWrite (Ppm File) (out File (prinl "P6") (prinl (length (car Ppm)) " " (length Ppm)) (prinl 255) (for Y Ppm (for X Y (apply wr X))) ) )
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#PL.2FI
PL/I
/* BITMAP FILE: write out a file in PPM format, P6 (binary). 14/5/2010 */ test: procedure options (main); declare image (0:19,0:19) bit (24); declare 1 pixel union, 2 color bit (24) aligned, 2 primaries, 3 R character (1), 3 G character (1), 3 B character (1); declare ch character (1); declare (i, j) fixed binary; declare out file record;   open file (out) title ('/IMAGE.PPM,TYPE(FIXED),RECSIZE(1)' ) OUTPUT;   ch = 'P'; write file (out) from (ch); ch = '6'; write file (out) from (ch);   call put_integer (hbound(image, 1)); call put_integer (hbound(image, 2)); call put_integer (255);   do i = 0 to hbound(image,1); do j = 0 to hbound(image, 2); color = image(i,j); write file (out) from (R); write file (out) from (G); write file (out) from (B); end; end;   put_integer: procedure (k); declare k fixed binary; declare s character (30) varying; declare i fixed binary; declare ch character (1);   s = k; s = trim(s); do i = 1 to length(s); ch = substr(s, i, 1); write file (out) from (ch); end; ch = '09'x; write file (out) from (ch); end put_integer; end test;
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "draw.s7i"; include "color.s7i";   const func PRIMITIVE_WINDOW: getPPM (in string: fileName) is func result var PRIMITIVE_WINDOW: aWindow is PRIMITIVE_WINDOW.value; local var file: ppmFile is STD_NULL; var string: line is ""; var integer: width is 0; var integer: height is 0; var integer: x is 0; var integer: y is 0; var color: pixColor is black; begin ppmFile := open(fileName, "r"); if ppmFile <> STD_NULL then if getln(ppmFile) = "P6" then repeat line := getln(ppmFile); until line = "" or line[1] <> '#'; read(ppmFile, width); readln(ppmFile, height); aWindow := newPixmap(width, height); for y range 0 to pred(height) do for x range 0 to pred(width) do pixColor.redLight  := ord(getc(ppmFile)); pixColor.greenLight := ord(getc(ppmFile)); pixColor.blueLight  := ord(getc(ppmFile)); end for; end for; end if; close(ppmFile); end if; end func;
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Tcl
Tcl
package require Tk   proc readPPM {image file} { $image read $file -format ppm }
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#C.23
C#
bool? value = null
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#C.2B.2B
C++
::Bool = False | True
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Smalltalk
Smalltalk
'THE QUICK BROWN FOX' rot:3 -> 'WKH TXLFN EURZQ IRA'
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input: [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance). Notes; The headings and indices can be calculated from this pseudocode: for i in 0..32 inclusive: heading = i * 11.25 case i %3: if 1: heading += 5.62; break if 2: heading -= 5.62; break end index = ( i mod 32) + 1 The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
#ALGOL_68
ALGOL 68
#!/usr/local/bin/a68g --script #   []STRING long by nesw = (" by ", "North", "East", "South", "West"), short by nesw = ("b", "N", "E", "S", "W");   MODE MINUTES = REAL; # minutes type # INT last minute=360*60; INT point width=last minute OVER 32;   PROC direction name = (REAL direction in minutes, []STRING locale directions)STRING: (   STRING by = locale directions[1]; []STRING nesw = locale directions[@-1];   PRIO MASK = 7; # same PRIOrity as * and / # OP MASK = (INT n, BITS lower)INT: ABS (BIN n AND NOT lower), DECAP = (STRING s)STRING: IF UPB s > 1 THEN REPR (ABS s[1]-ABS "A"+ABS "a")+s[2:] ELSE s FI;   PROC point name = (INT in point)STRING: (   INT point = in point MOD 32 # 32 points of a compass #; IF point MOD 8 = 0 THEN # name the principle point: eg. N, E, S or W # nesw[point OVER 8]   ELIF point MOD 4 = 0 THEN # name the half: eg. NE, SE, SW or NW # point name((point+8)MASK 2r1111)+DECAP point name(point MASK 2r1111 + 8)   ELIF point MOD 2 = 0 THEN # name the quarter: eg. N-NE, E-NE, E-SE, S-SE, S-SW, W-SW, W-NW or N-NW # point name((point+4)MASK 2r111)+"-"+point name(point MASK 2r111 + 4)   ELSE # Name the sixteenth point: # # eg. NbE,NEbN,NEbE,EbN,EbS,SEbE,SEbS,SbE,SbW,SWbS,SWbW,WbS,WbN,NWbW,NWbN,NbW # INT opp point = point OVER 8 + ABS NOT ODD (point OVER 2); point name((point+2)MASK 2r11)+ by +nesw(opp point MOD 4) FI ); point name(ROUND(direction in minutes/point width)) );   PROC traditional name = (MINUTES minutes)STRING: ( INT degrees = ROUND(minutes / 60); degrees=0 |"Tramontana" |: degrees=45 |"Greco or Bora" |: degrees=90 |"Levante" |: degrees=135|"Sirocco" |: degrees=180|"Ostro" |: degrees=225|"Libeccio" |: degrees=270|"Poniente or Zephyrus"|: degrees=315|"Mistral" |: degrees=360|"Tramontana" |"" );   # First generate the test set results # test:( printf($"Test:"l$); FOR i FROM 0 TO 32 DO REAL heading = i * 11.25 + CASE i MOD 3 IN +5.62, -5.62 OUT 0 ESAC; INT index = ( i MOD 32) + 1; printf(($zd" ", g23k, zzd.zzl$, index , direction name(heading*60, long by nesw), heading)) OD );   table:( OP OVER = (REAL r, INT base)INT: ENTIER ABS r OVER base, MOD = (REAL r, INT base)REAL: ( INT i = ENTIER r; i MOD base + r - i);   printf( $l"Table:"l " #|Compass point"22k"|Abbr|Traditional wind point| Lowest°′ | Middle°′ | Highest°′"l$ );   OP DEGMIN = (REAL minutes)STRUCT(INT d, REAL m): (minutes MOD last minute OVER 60, minutes MOD 60);   FOR point FROM 1 TO 32 DO REAL centre = (point-1) * point width; REAL from = centre - point width/2, to = centre + point width/2-1/120; printf(( $g(-2)"|"$, point, $g$, direction name(centre, long by nesw), $22k"|"g$, direction name(centre, short by nesw), $27k"|"g$, traditional name(centre), $50k$, $"|"g(-3)"°", dd.dd"′"$, DEGMIN from, DEGMIN centre, DEGMIN to, $l$ )) OD )
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height. Test task Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows: Convert image to grayscale; Compute the histogram Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance. Replace each pixel of luminance lesser than the median to black, and others to white. Use read/write ppm file, and grayscale image solutions.
#Forth
Forth
: histogram ( array gmp -- ) over 256 cells erase dup bdim * over bdata + swap bdata do 1 over i c@ cells + +! loop drop ;
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height. Test task Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows: Convert image to grayscale; Compute the histogram Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance. Replace each pixel of luminance lesser than the median to black, and others to white. Use read/write ppm file, and grayscale image solutions.
#Fortran
Fortran
module RCImageProcess use RCImageBasic implicit none contains   subroutine get_histogram(img, histogram) type(scimage), intent(in) :: img integer, dimension(0:255), intent(out) :: histogram   integer :: i   histogram = 0 do i = 0,255 histogram(i) = sum(img%channel, img%channel == i) end do end subroutine get_histogram   function histogram_median(histogram) integer, dimension(0:255), intent(in) :: histogram integer :: histogram_median   integer :: from, to, left, right   from = 0 to = 255 left = histogram(from) right = histogram(to) do while ( from /= to ) if ( left < right ) then from = from + 1 left = left + histogram(from) else to = to - 1 right = right + histogram(to) end if end do histogram_median = from end function histogram_median   end module RCImageProcess
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate. All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer. If any operation is not available in your language, note it.
#8051_Assembly
8051 Assembly
; bitwise AND anl a, b   ; bitwise OR orl a, b   ; bitwise XOR xrl a, b   ; bitwise NOT cpl a   ; left shift inc b rrc a loop: rlc a clr c djnz b, loop   ; right shift inc b rlc a loop: rrc a clr c djnz b, loop   ; arithmetic right shift push 20 inc b rlc a mov 20.0, c loop: rrc a mov c, 20.0 djnz b, loop pop 20   ; left rotate inc b rr a loop: rl a djnz b, loop   ; right rotate inc b rl a loop: rr a djnz b, loop
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#Commodore_Basic
Commodore Basic
  10 rem bezier curve algorihm 20 rem translated from purebasic 30 ns=25 : rem num segments 40 dim pt(ns,2) : rem points in line 50 sc=1024 : rem start of screen memory 60 sw=40  : rem screen width 70 sh=25  : rem screen height 80 pc=42  : rem plot character '*' 90 dim bp(2,1) : rem bezier curve points 100 bp(0,0)=1:bp(1,0)=70:bp(2,0)=1 110 bp(0,1)=1:bp(1,1)=8:bp(2,1)=23 120 dim pt%(ns,2) : rem individual lines in curve 130 gosub 3000 140 end 1000 rem plot line 1010 se=0 : rem 0 = steep 1 = !steep 1020 if abs(y1-y0)>abs(x1-x0) then se=1:tp=y0:y0=x0:x0=tp:tp=y1:y1=x1:x1=tp 1030 if x0>x1 then tp=x1:x1=x0:x0=tp:tp=y1:y1=y0:y0=tp 1040 dx=x1-x0 1050 dy=abs(y1-y0) 1060 er=dx/2 1070 y=y0 1080 ys=-1 1090 if y0<y1 then ys = 1 1100 for x=x0 to x1 1110 if se=1 then p0=y: p1=x:gosub 2000:goto 1130 1120 p0=x: p1=y: gosub 2000 1130 er=er-dy 1140 if er<0 then y=y+ys:er=er+dx 1150 next x 1160 return 2000 rem plot individual point 2010 rem p0 == plot point x 2020 rem p1 == plot point y 2030 sl=p0+(p1*sw) 2040 rem make sure we dont write beyond screen memory 2050 if sl<(sw*sh) then poke sc+sl,pc 2060 return 3000 rem bezier curve 3010 for i=0 to ns 3020 t=i/ns 3030 t1=1.0-t 3040 a=t1^2 3050 b=2.0*t*t1 3060 c=t^2 3070 pt(i,0)=a*bp(0,0)+b*bp(1,0)+c*bp(2,0) 3080 pt(i,1)=a*bp(0,1)+b*bp(1,1)+c*bp(2,1) 3090 next i 3100 for i=0 to ns-1 3110 x0=int(pt(i,0)) 3120 y0=int(pt(i,1)) 3130 x1=int(pt(i+1,0)) 3140 y1=int(pt(i+1,1)) 3150 gosub 1000 3160 next i 3170 return  
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#D
D
import grayscale_image, bitmap_bresenhams_line_algorithm;   struct Pt { int x, y; } // Signed.   void quadraticBezier(size_t nSegments=20, Color) (Image!Color im, in Pt p1, in Pt p2, in Pt p3, in Color color) pure nothrow @nogc if (nSegments > 0) { Pt[nSegments + 1] points = void;   foreach (immutable i, ref p; points) { immutable double t = i / double(nSegments), a = (1.0 - t) ^^ 2, b = 2.0 * t * (1.0 - t), c = t ^^ 2; p = Pt(cast(typeof(Pt.x))(a * p1.x + b * p2.x + c * p3.x), cast(typeof(Pt.y))(a * p1.y + b * p2.y + c * p3.y)); }   foreach (immutable i, immutable p; points[0 .. $ - 1]) im.drawLine(p.x, p.y, points[i + 1].x, points[i + 1].y, color); }   void main() { auto im = new Image!Gray(20, 20); im.clear(Gray.white); im.quadraticBezier(Pt(1,10), Pt(25,27), Pt(15,2), Gray.black); im.textualShow(); }
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#BASIC256
BASIC256
fastgraphics clg color red call DrawCircle(150,100,100) refresh color blue call DrawCircle(200,200,50) refresh   #Function DrawCircle #1st param = X-coord of center #2nd param = Y-coord of center #3rd param = radius Function DrawCircle(x0,y0,radius) x=radius y=0 decisionOver2=1-x   while x>=y plot( x + x0, y + y0) plot( y + x0, x + y0) plot(-x + x0, y + y0) plot(-y + x0, x + y0) plot(-x + x0, -y + y0) plot(-y + x0, -x + y0) plot( x + x0, -y + y0) plot( y + x0, -x + y0)   y++   if decisionOver2<=0 then decisionOver2+=2*y+1 else x-- decisionOver2+=2*(y-x)+1 end if end while return 0 End Function
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion   %== Initializations ==% set width=50 set height=30   set /a allowance=height+2 mode %width%,%allowance% echo Rendering...   set "outp=" for /l %%i in (1,1,%height%) do ( for /l %%j in (1,1,%width%) do ( set "c[%%i][%%j]= " ) )   %== Set the parameters for making circle ==% call :DrawCircle 20 20 10 call :DrawCircle 10 30 15   %== Output result ==% for /l %%i in (1,1,%height%) do ( for /l %%j in (1,1,%width%) do ( set "outp=!outp!!c[%%i][%%j]!" ) ) cls echo !outp! pause>nul exit /b   %== The main function ==% :DrawCircle set x0=%1 set y0=%2 set radius=%3   set x=!radius! set y=0 set /a decisionOver2 = 1 - !x!   :circle_loop if !x! geq !y! ( set /a "hor=x + x0","ver=y + y0" set "c[!hor!][!ver!]=Û" set /a "hor=y + x0","ver=x + y0" set "c[!hor!][!ver!]=Û" set /a "hor=-x + x0","ver=y + y0" set "c[!hor!][!ver!]=Û" set /a "hor=-y + x0","ver=x + y0" set "c[!hor!][!ver!]=Û" set /a "hor=-x + x0","ver=-y + y0" set "c[!hor!][!ver!]=Û" set /a "hor=-y + x0","ver=-x + y0" set "c[!hor!][!ver!]=Û" set /a "hor=x + x0","ver=-y + y0" set "c[!hor!][!ver!]=Û" set /a "hor=y + x0","ver=-x + y0" set "c[!hor!][!ver!]=Û"   set /a y+=1 if !decisionOver2! leq 0 ( set /a "decisionOver2 = !decisionOver2! + (2 * y^) + 1" ) else ( set /a x-=1 set /a "decisionOver2 = !decisionOver2! + 2 * (y - x^) + 1" ) goto circle_loop ) goto :EOF
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#Red
Red
Red [ Title: "Bitwise IO" Link: http://rosettacode.org/wiki/Bitwise_IO Source: https://github.com/vazub/rosetta-red File: "%bitwiseio.red" Rights: "Copyright (C) 2020 Vasyl Zubko. All rights reserved." License: "Blue Oak Model License - https://blueoakcouncil.org/license/1.0.0" Tabs: 4 ]   str-compress: function [ "Compressesor" str [string!] ][ buf: copy "" bit-str: enbase/base str 2 foreach [bit1 bit2 bit3 bit4 bit5 bit6 bit7 bit8] bit-str [ append buf rejoin [bit2 bit3 bit4 bit5 bit6 bit7 bit8] ] if (pad-bits: (length? buf) // 8) <> 0 [ loop (8 - pad-bits) [append buf "0"] ] debase/base buf 2 ]   str-expand: function [ "Decompressor" bin-hex [binary!] ][ bit-str: enbase/base bin-hex 2 filled: 0 buf: copy [] acc: copy "" foreach bit bit-str [ append acc bit filled: filled + 1 if filled = 7 [ append buf debase/base rejoin ["0" acc] 2 clear acc filled: 0 ] ] if (last buf) = #{00} [take/last buf] rejoin buf ]   ; DEMO in-string: "Red forever!" compressed: str-compress in-string expanded: str-expand compressed prin [ pad "Input (string): " 20 mold in-string newline newline pad "Input (bits): " 20 enbase/base in-string 2 newline pad "Compressed (bits): " 20 enbase/base compressed 2 newline newline pad "Input (hex): " 20 to-binary in-string newline pad "Compressed (hex): " 20 compressed newline newline pad "Expanded (string): " 20 mold to-string expanded ]  
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#REXX
REXX
/* REXX **************************************************************** * 01.11.2012 Walter Pachl ***********************************************************************/ s='STRING' /* Test input */ Say 's='s ol='' /* initialize target */ Do While s<>'' /* loop through input */ Parse Var s c +1 s /* pick a character */ cx=c2x(c) /* convert to hex */ cb=x2b(cx) /* convert to bits */ ol=ol||substr(cb,2) /* append to target */ End l=length(ol) /* current length */ lm=l//8 ol=ol||copies('0',8-lm) /* pad to multiple of 8 */ pd=copies(' ',l)||copies('0',8-lm) Say 'b='ol /* show target */ Say ' 'pd 'padding' r='' /* initialize result */ Do While length(ol)>6 /* loop through target */ Parse Var ol b +7 ol /* pick 7 bits */ b='0'||b /* add a leading '0' */ x=b2x(b) /* convert to hex */ r=r||x2c(x) /* convert to character */ End /* and append to result */ Say 'r='r /* show result */
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Prolog
Prolog
  :- module(bitmapIO, [ write_ppm_p6/2]).   :- use_module(library(lists)).   %write_ppm_p6(File,Bitmap) write_ppm_p6(Filename,[[X,Y],Pixels]):- open(Filename,write,Output,[encoding(octet)]), %write p6 header writeln(Output, 'P6'), atomic_list_concat([X, Y], ' ', Dimensions), writeln(Output, Dimensions), writeln(Output, '255'), %write bytes maplist(maplist(maplist(put_byte(Output))),Pixels), close(Output).  
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#PureBasic
PureBasic
Procedure SaveImageAsPPM(Image, file$, Binary = 1) ; Author Roger Rösch (Nickname Macros) IDFiIe = CreateFile(#PB_Any, file$) If IDFiIe If StartDrawing(ImageOutput(Image)) WriteStringN(IDFiIe, "P" + Str(3 + 3*Binary)) WriteStringN(IDFiIe, "#Created with PureBasic using a Function created from Macros for Rosettacode.org ") width = ImageWidth(Image) height = ImageHeight(Image) WriteStringN(IDFiIe, Str(width) + " " + Str(height)) WriteStringN(IDFiIe, "255") If Binary = 0 For y = 0 To height - 1 For x = 0 To width - 1 color = Point(x, y) WriteString(IDFiIe, Str(Red(color)) + " " + Str(Green(color)) + " " + Str(Blue(color)) + " ") Next WriteStringN(IDFiIe, "") Next Else ; Save in Binary Format For y = 0 To height - 1 For x = 0 To width - 1 color = Point(x, y) WriteByte(IDFiIe, Red(color)) WriteByte(IDFiIe, Green(color)) WriteByte(IDFiIe, Blue(color)) Next Next EndIf StopDrawing() EndIf CloseFile(IDFiIe) EndIf EndProcedure
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#UNIX_Shell
UNIX Shell
function setrgb { _.r=$1 _.g=$2 _.b=$3 } function grayscale { integer x=$(( round( 0.2126*_.r + 0.7152*_.g + 0.0722*_.b ) )) _.r=$x _.g=$x _.b=$x }
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Vedit_macro_language
Vedit macro language
// Load a PPM file // @10 = filename // On return: // #10 points to buffer containing pixel data, // #11 = width, #12 = height.   :LOAD_PPM: File_Open(@10) BOF Search("|X", ADVANCE) // skip "P6" #11 = Num_Eval(ADVANCE) // #11 = width Match("|X", ADVANCE) // skip separator #12 = Num_Eval(ADVANCE) // #12 = height Match("|X", ADVANCE) Search("|X", ADVANCE) // skip maxval (assume 255) Del_Block(0,CP) // remove the header Return
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Clean
Clean
::Bool = False | True
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Clojure
Clojure
foreach(var 1 42 ON yes True y Princess 0 OFF no False n Princess-NOTFOUND) if(var) message(STATUS "${var} is true.") else() message(STATUS "${var} is false.") endif() endforeach(var)
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#SSEM
SSEM
00101000000000100000000000000000 0. -20 to c 11001000000000010000000000000000 1. Sub. 19 10101000000001100000000000000000 2. c to 21 10101000000000100000000000000000 3. -21 to c 00000000000000110000000000000000 4. Test 10001000000000000000000000000000 5. 17 to CI 10101000000001100000000000000000 6. c to 21 10101000000000100000000000000000 7. -21 to c 01001000000000010000000000000000 8. Sub. 18 10101000000001100000000000000000 9. c to 21 10101000000000100000000000000000 10. -21 to c 00000000000001110000000000000000 11. Stop 01001000000000010000000000000000 12. Sub. 18 00000000000000110000000000000000 13. Test 00000000000001110000000000000000 14. Stop 10101000000000100000000000000000 15. -21 to c 00000000000001110000000000000000 16. Stop 11010000000000000000000000000000 17. 11 01011000000000000000000000000000 18. 26
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input: [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance). Notes; The headings and indices can be calculated from this pseudocode: for i in 0..32 inclusive: heading = i * 11.25 case i %3: if 1: heading += 5.62; break if 2: heading -= 5.62; break end index = ( i mod 32) + 1 The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
#AppleScript
AppleScript
use framework "Foundation" use scripting additions   -- BOXING THE COMPASS --------------------------------------------------------   property plstLangs : [{|name|:"English"} & ¬ {expansions:{N:"north", S:"south", E:"east", W:"west", b:" by "}} & ¬ {|N|:"N", |NNNE|:"NbE", |NNE|:"N-NE", |NNENE|:"NEbN", |NE|:"NE", |NENEE|:"NEbE"} & ¬ {|NEE|:"E-NE", |NEEE|:"EbN", |E|:"E", |EEES|:"EbS", |EES|:"E-SE", |EESES|:"SEbE"} & ¬ {|ES|:"SE", |ESESS|:"SEbS", |ESS|:"S-SE", |ESSS|:"SbE", |S|:"S", |SSSW|:"SbW"} & ¬ {|SSW|:"S-SW", |SSWSW|:"SWbS", |SW|:"SW", |SWSWW|:"SWbW", |SWW|:"W-SW"} & ¬ {|SWWW|:"WbS", |W|:"W", |WWWN|:"WbN", |WWN|:"W-NW", |WWNWN|:"NWbW"} & ¬ {|WN|:"NW", |WNWNN|:"NWbN", |WNN|:"N-NW", |WNNN|:"NbW"}, ¬ ¬ {|name|:"Chinese", |N|:"北", |NNNE|:"北微东", |NNE|:"东北偏北"} & ¬ {|NNENE|:"东北微北", |NE|:"东北", |NENEE|:"东北微东", |NEE|:"东北偏东"} & ¬ {|NEEE|:"东微北", |E|:"东", |EEES|:"东微南", |EES|:"东南偏东", |EESES|:"东南微东"} & ¬ {|ES|:"东南", |ESESS|:"东南微南", |ESS|:"东南偏南", |ESSS|:"南微东", |S|:"南"} & ¬ {|SSSW|:"南微西", |SSW|:"西南偏南", |SSWSW|:"西南微南", |SW|:"西南"} & ¬ {|SWSWW|:"西南微西", |SWW|:"西南偏西", |SWWW|:"西微南", |W|:"西"} & ¬ {|WWWN|:"西微北", |WWN|:"西北偏西", |WWNWN|:"西北微西", |WN|:"西北"} & ¬ {|WNWNN|:"西北微北", |WNN|:"西北偏北", |WNNN|:"北微西"}]   -- Scale invariant keys for points of the compass -- (allows us to look up a translation for one scale of compass (32 here) -- for use in another size of compass (8 or 16 points) -- (Also semi-serviceable as more or less legible keys without translation)   -- compassKeys :: Int -> [String] on compassKeys(intDepth) -- Simplest compass divides into two hemispheres -- with one peak of ambiguity to the left, -- and one to the right (encoded by the commas in this list): set urCompass to ["N", "S", "N"]   -- Necessity drives recursive subdivision of broader directions, shrinking -- boxes down to a workable level of precision: script subdivision on |λ|(lstCompass, N) if N ≤ 1 then lstCompass else script subKeys on |λ|(a, x, i, xs) -- Borders between N and S engender E and W. -- further subdivisions (boxes) -- concatenate their two parent keys. if i > 1 then cond(N = intDepth, ¬ a & {cond(x = "N", "W", "E")} & x, ¬ a & {item (i - 1) of xs & x} & x) else a & x end if end |λ| end script   |λ|(foldl(subKeys, {}, lstCompass), N - 1) end if end |λ| end script   tell subdivision to items 1 thru -2 of |λ|(urCompass, intDepth) end compassKeys   -- pointIndex :: Int -> Num -> String on pointIndex(power, degrees) set nBoxes to 2 ^ power set i to round (degrees + (360 / (nBoxes * 2))) ¬ mod 360 * nBoxes / 360 rounding up cond(i > 0, i, 1) end pointIndex   -- pointNames :: Int -> Int -> [String] on pointNames(precision, iBox) set k to item iBox of compassKeys(precision)   script translation on |λ|(recLang) set maybeTrans to keyValue(recLang, k) set strBrief to cond(maybeTrans is missing value, k, maybeTrans)   set recExpand to keyValue(recLang, "expansions")   if recExpand is not missing value then script expand on |λ|(c) set t to keyValue(recExpand, c) cond(t is not missing value, t, c) end |λ| end script set strName to (intercalate(cond(precision > 5, " ", ""), ¬ map(expand, characters of strBrief))) toUpper(text item 1 of strName) & text items 2 thru -1 of strName else strBrief end if end |λ| end script   map(translation, plstLangs) end pointNames   -- maxLen :: [String] -> Int on maxLen(xs) length of maximumBy(comparing(my |length|), xs) end maxLen   -- alignRight :: Int -> String -> String on alignRight(nWidth, x) justifyRight(nWidth, space, x) end alignRight   -- alignLeft :: Int -> String -> String on alignLeft(nWidth, x) justifyLeft(nWidth, space, x) end alignLeft   -- show :: asString => a -> Text on show(x) x as string end show   -- compassTable :: Int -> [Num] -> Maybe String on compassTable(precision, xs) if precision < 1 then missing value else set intPad to 2 set rightAligned to curry(alignRight) set leftAligned to curry(alignLeft) set join to curry(my intercalate)   -- INDEX COLUMN set lstIndex to map(|λ|(precision) of curry(pointIndex), xs) set lstStrIndex to map(show, lstIndex) set nIndexWidth to maxLen(lstStrIndex) set colIndex to map(|λ|(nIndexWidth + intPad) of rightAligned, lstStrIndex)   -- ANGLES COLUMN script degreeFormat on |λ|(x) set {c, m} to splitOn(".", x as string) c & "." & (text 1 thru 2 of (m & "0")) & "°" end |λ| end script set lstAngles to map(degreeFormat, xs) set nAngleWidth to maxLen(lstAngles) + intPad set colAngles to map(|λ|(nAngleWidth) of rightAligned, lstAngles)   -- NAMES COLUMNS script precisionNames on |λ|(iBox) pointNames(precision, iBox) end |λ| end script   set lstTrans to transpose(map(precisionNames, lstIndex)) set lstTransWidths to map(maxLen, lstTrans)   script spacedNames on |λ|(lstLang, i) map(|λ|((item i of lstTransWidths) + 2) of leftAligned, lstLang) end |λ| end script   set colsTrans to map(spacedNames, lstTrans)   -- TABLE intercalate(linefeed, ¬ map(|λ|("") of join, ¬ transpose({colIndex} & {colAngles} & ¬ {replicate(length of lstIndex, " ")} & colsTrans))) end if end compassTable       -- TEST ---------------------------------------------------------------------- on run set xs to [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, ¬ 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, ¬ 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, ¬ 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, ¬ 354.38]   -- If we supply other precisions, like 4 or 6, (2^n -> 16 or 64 boxes) -- the bearings will be divided amongst smaller or larger numbers of boxes, -- either using name translations retrieved by the generic hash -- or using the keys of the hash itself (combined with any expansions) -- to substitute for missing names for very finely divided boxes.   compassTable(5, xs) -- // 2^5 -> 32 boxes end run     -- GENERIC FUNCTIONS ---------------------------------------------------------   -- comparing :: (a -> b) -> (a -> a -> Ordering) on comparing(f) set mf to mReturn(f) script on |λ|(a, b) set x to mf's |λ|(a) set y to mf's |λ|(b) if x < y then -1 else if x > y then 1 else 0 end if end if end |λ| end script end comparing   -- cond :: Bool -> a -> a -> a on cond(bool, f, g) if bool then f else g end if end cond   -- curry :: (Script|Handler) -> Script on curry(f) script on |λ|(a) script on |λ|(b) |λ|(a, b) of mReturn(f) end |λ| end script end |λ| end script end curry   -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl   -- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText) set {dlm, my text item delimiters} to {my text item delimiters, strText} set strJoined to lstText as text set my text item delimiters to dlm return strJoined end intercalate   -- justifyLeft :: Int -> Char -> Text -> Text on justifyLeft(N, cFiller, strText) if N > length of strText then text 1 thru N of (strText & replicate(N, cFiller)) else strText end if end justifyLeft   -- justifyRight :: Int -> Char -> Text -> Text on justifyRight(N, cFiller, strText) if N > length of strText then text -N thru -1 of ((replicate(N, cFiller) as text) & strText) else strText end if end justifyRight   -- keyValue :: Record -> String -> Maybe String on keyValue(rec, strKey) set ca to current application set v to (ca's NSDictionary's dictionaryWithDictionary:rec)'s objectForKey:strKey if v is not missing value then item 1 of ((ca's NSArray's arrayWithObject:v) as list) else missing value end if end keyValue   -- length :: [a] -> Int on |length|(xs) length of xs end |length|   -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map   -- maximumBy :: (a -> a -> Ordering) -> [a] -> a on maximumBy(f, xs) set cmp to mReturn(f) script max on |λ|(a, b) if a is missing value or cmp's |λ|(a, b) < 0 then b else a end if end |λ| end script   foldl(max, missing value, xs) end maximumBy   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn   -- replicate :: Int -> a -> [a] on replicate(N, a) set out to {} if N < 1 then return out set dbl to {a}   repeat while (N > 1) if (N mod 2) > 0 then set out to out & dbl set N to (N div 2) set dbl to (dbl & dbl) end repeat return out & dbl end replicate   -- splitOn :: Text -> Text -> [Text] on splitOn(strDelim, strMain) set {dlm, my text item delimiters} to {my text item delimiters, strDelim} set xs to text items of strMain set my text item delimiters to dlm return xs end splitOn   -- transpose :: [[a]] -> [[a]] on transpose(xss) script column on |λ|(_, iCol) script row on |λ|(xs) item iCol of xs end |λ| end script   map(row, xss) end |λ| end script   map(column, item 1 of xss) end transpose   -- toLower :: String -> String on toLower(str) set ca to current application ((ca's NSString's stringWithString:(str))'s ¬ lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text end toLower   -- toTitle :: String -> String on toTitle(str) set ca to current application ((ca's NSString's stringWithString:(str))'s ¬ capitalizedStringWithLocale:(ca's NSLocale's currentLocale())) as text end toTitle   -- toUpper :: String -> String on toUpper(str) set ca to current application ((ca's NSString's stringWithString:(str))'s ¬ uppercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text end toUpper
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height. Test task Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows: Convert image to grayscale; Compute the histogram Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance. Replace each pixel of luminance lesser than the median to black, and others to white. Use read/write ppm file, and grayscale image solutions.
#Go
Go
package raster   import "math"   func (g *Grmap) Histogram(bins int) []int { if bins <= 0 { bins = g.cols } h := make([]int, bins) for _, p := range g.px { h[int(p)*(bins-1)/math.MaxUint16]++ } return h }   func (g *Grmap) Threshold(t uint16) { for i, p := range g.px { if p < t { g.px[i] = 0 } else { g.px[i] = math.MaxUint16 } } }
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height. Test task Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows: Convert image to grayscale; Compute the histogram Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance. Replace each pixel of luminance lesser than the median to black, and others to white. Use read/write ppm file, and grayscale image solutions.
#Haskell
Haskell
module Bitmap.BW(module Bitmap.BW) where   import Bitmap import Control.Monad.ST   newtype BW = BW Bool deriving (Eq, Ord)   instance Color BW where luminance (BW False) = 0 luminance _ = 255 black = BW False white = BW True toNetpbm [] = "" toNetpbm l = init (concatMap f line) ++ "\n" ++ toNetpbm rest where (line, rest) = splitAt 35 l f (BW False) = "1 " f _ = "0 " fromNetpbm = map f where f 1 = black f _ = white netpbmMagicNumber _ = "P1" netpbmMaxval _ = ""   toBWImage :: Color c => Image s c -> ST s (Image s BW) toBWImage = toBWImage' 128   toBWImage' :: Color c => Int -> Image s c -> ST s (Image s BW) {- The first argument gives the darkest luminance assigned to white. -} toBWImage' darkestWhite = mapImage $ f . luminance where f x | x < darkestWhite = black | otherwise = white
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate. All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer. If any operation is not available in your language, note it.
#8086_Assembly
8086 Assembly
MOV AX,0345h MOV BX,0444h AND AX,BX
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#Factor
Factor
USING: arrays kernel locals math math.functions rosettacode.raster.storage sequences ; IN: rosettacode.raster.line   ! This gives a function :: (quadratic-bezier) ( P0 P1 P2 -- bezier ) [ :> x 1 x - sq P0 n*v 2 1 x - x * * P1 n*v x sq P2 n*v v+ v+ ] ; inline   ! Same code from the cubic bezier task : t-interval ( x -- interval ) [ iota ] keep 1 - [ / ] curry map ; : points-to-lines ( seq -- seq ) dup rest [ 2array ] 2map ; : draw-lines ( {R,G,B} points image -- ) [ [ first2 ] dip draw-line ] curry with each ; :: bezier-lines ( {R,G,B} P0 P1 P2 image -- ) 100 t-interval P0 P1 P2 (quadratic-bezier) map points-to-lines {R,G,B} swap image draw-lines ;  
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#FBSL
FBSL
#DEFINE WM_LBUTTONDOWN 513 #DEFINE WM_CLOSE 16   FBSLSETTEXT(ME, "Bezier Quadratic") FBSLSETFORMCOLOR(ME, RGB(0, 255, 255)) ' Cyan: persistent background color DRAWWIDTH(5) ' Adjust point size FBSL.GETDC(ME) ' Use volatile FBSL.GETDC below to avoid extra assignments   RESIZE(ME, 0, 0, 235, 235) CENTER(ME) SHOW(ME)   DIM Height AS INTEGER FBSL.GETCLIENTRECT(ME, 0, 0, 0, Height)   BEGIN EVENTS SELECT CASE CBMSG CASE WM_LBUTTONDOWN: BezierQuad(10, 100, 250, 270, 150, 20, 20) ' Draw CASE WM_CLOSE: FBSL.RELEASEDC(ME, FBSL.GETDC) ' Clean up END SELECT END EVENTS   SUB BezierQuad(x1, y1, x2, y2, x3, y3, n) TYPE POINTAPI x AS INTEGER y AS INTEGER END TYPE   DIM t, t1, a, b, c, p[n] AS POINTAPI   FOR DIM i = 0 TO n t = i / n: t1 = 1 - t a = t1 ^ 2 b = 2 * t * t1 c = t ^ 2 p[i].x = a * x1 + b * x2 + c * x3 + 0.5 p[i].y = Height - (a * y1 + b * y2 + c * y3 + 0.5) NEXT   FOR i = 0 TO n - 1 Bresenham(p[i].x, p[i].y, p[i + 1].x, p[i + 1].y) NEXT   SUB Bresenham(x0, y0, x1, y1) DIM dx = ABS(x0 - x1), sx = SGN(x0 - x1) DIM dy = ABS(y0 - y1), sy = SGN(y0 - y1) DIM tmp, er = IIF(dx > dy, dx, -dy) / 2   WHILE NOT (x0 = x1 ANDALSO y0 = y1) PSET(FBSL.GETDC, x0, y0, &HFF) ' Red: Windows stores colors in BGR order tmp = er IF tmp > -dx THEN: er = er - dy: x0 = x0 + sx: END IF IF tmp < +dy THEN: er = er + dx: y0 = y0 + sy: END IF WEND END SUB END SUB
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#BBC_BASIC
BBC BASIC
Width% = 200 Height% = 200   REM Set window size: VDU 23,22,Width%;Height%;8,16,16,128   REM Draw circles: PROCcircle(100,100,40, 0,0,0) PROCcircle(100,100,80, 255,0,0) END   DEF PROCcircle(cx%,cy%,r%,R%,G%,B%) LOCAL f%, x%, y%, ddx%, ddy% f% = 1 - r% : y% = r% : ddy% = - 2*r% PROCsetpixel(cx%, cy%+r%, R%,G%,B%) PROCsetpixel(cx%, cy%-r%, R%,G%,B%) PROCsetpixel(cx%+r%, cy%, R%,G%,B%) PROCsetpixel(cx%-r%, cy%, R%,G%,B%) WHILE x% < y% IF f% >= 0 THEN y% -= 1 ddy% += 2 f% += ddy% ENDIF x% += 1 ddx% += 2 f% += ddx% + 1 PROCsetpixel(cx%+x%, cy%+y%, R%,G%,B%) PROCsetpixel(cx%-x%, cy%+y%, R%,G%,B%) PROCsetpixel(cx%+x%, cy%-y%, R%,G%,B%) PROCsetpixel(cx%-x%, cy%-y%, R%,G%,B%) PROCsetpixel(cx%+y%, cy%+x%, R%,G%,B%) PROCsetpixel(cx%-y%, cy%+x%, R%,G%,B%) PROCsetpixel(cx%+y%, cy%-x%, R%,G%,B%) PROCsetpixel(cx%-y%, cy%-x%, R%,G%,B%) ENDWHILE ENDPROC   DEF PROCsetpixel(x%,y%,r%,g%,b%) COLOUR 1,r%,g%,b% GCOL 1 LINE x%*2,y%*2,x%*2,y%*2 ENDPROC
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#C
C
void raster_circle( image img, unsigned int x0, unsigned int y0, unsigned int radius, color_component r, color_component g, color_component b );
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#Ruby
Ruby
def crunch(ascii) bitstring = ascii.bytes.collect {|b| "%07b" % b}.join [bitstring].pack("B*") end   def expand(binary) bitstring = binary.unpack("B*")[0] bitstring.scan(/[01]{7}/).collect {|b| b.to_i(2).chr}.join end   original = "This is an ascii string that will be crunched, written, read and expanded." puts "my ascii string is #{original.length} bytes"   filename = "crunched.out"   # write the compressed data File.open(filename, "w") do |fh| fh.binmode fh.print crunch(original) end   filesize = File.size(filename) puts "the file containing the crunched text is #{filesize} bytes"   # read and expand expanded = File.open(filename, "r") do |fh| fh.binmode expand(fh.read) end   if original == expanded puts "success" else puts "fail!" end
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Python
Python
  # String masquerading as ppm file (version P3) 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 = '# generated from Bitmap.writeppm\n' 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   # Draw something simple bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) # Write to the open 'file' handle bitmap.writeppmp3(ppmfileout) # Whats in the generated PPM file print(ppmfileout.getvalue())   ''' The print statement above produces the following output :   P3 # generated from Bitmap.writeppmp3 4 4 255 0 0 0 0 0 0 0 0 0 127 0 63 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 255 255 255 0 0 0 0 0 0 0 0 0 255 255 255 0 0 0 0 0 0   '''   # Write a P6 file ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()  
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Wren
Wren
import "graphics" for Canvas, ImageData, Color import "dome" for Window, Process import "io" for FileSystem   class Bitmap { construct new(fileName, fileName2, width, height) { Window.title = "Bitmap - read PPM file" Window.resize(width, height) Canvas.resize(width, height) _w = width _h = height _fn2 = fileName2 loadPPMFile(fileName) }   init() { toGrayScale() // display images side by side _bmp.draw(0, 0) _bmp2.draw(536, 0) // save gray scale image to file _bmp2.saveToFile(_fn2) }   loadPPMFile(fileName) { var ppm = FileSystem.load(fileName) if (ppm[0..1] != "P6") { System.print("The loaded file is not a P6 file.") Process.exit() } var lines = ppm.split("\n") if (Num.fromString(lines[2]) > 255) { System.print("The maximum color value can't exceed 255.") Process.exit() } var wh = lines[1].split(" ") var w = Num.fromString(wh[0]) var h = Num.fromString(wh[1]) _bmp = ImageData.create(fileName, w, h) var bytes = ppm.bytes var i = bytes.count - 3 * w * h for (y in 0...h) { for (x in 0...w) { var r = bytes[i] var g = bytes[i+1] var b = bytes[i+2] var c = Color.rgb(r, g, b) pset(x, y, c) i = i + 3 } } }   toGrayScale() { _bmp2 = ImageData.create("gray scale", _bmp.width, _bmp.height) for (x in 0..._bmp.width) { for (y in 0..._bmp.height) { var c1 = _bmp.pget(x, y) var lumin = (0.2126 * c1.r + 0.7152 * c1.g + 0.0722 * c1.b).floor var c2 = Color.rgb(lumin, lumin,lumin, c1.a) _bmp2.pset(x, y, c2) } } }   pset(x, y, col) { _bmp.pset(x, y, col) }   pget(x, y) { _bmp.pget(x, y) }   update() {}   draw(alpha) {} }   var Game = Bitmap.new("Lenna100.ppm", "Lenna100_gs.jpg", 1048, 512)
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#CMake
CMake
foreach(var 1 42 ON yes True y Princess 0 OFF no False n Princess-NOTFOUND) if(var) message(STATUS "${var} is true.") else() message(STATUS "${var} is false.") endif() endforeach(var)
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Stata
Stata
function caesar(s, k) { u = ascii(s) i = selectindex(u:>=65 :& u:<=90) if (length(i)>0) u[i] = mod(u[i]:+(k-65), 26):+65 i = selectindex(u:>=97 :& u:<=122) if (length(i)>0) u[i] = mod(u[i]:+(k-97), 26):+97 return(char(u)) }   caesar("layout", 20) fusion
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input: [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance). Notes; The headings and indices can be calculated from this pseudocode: for i in 0..32 inclusive: heading = i * 11.25 case i %3: if 1: heading += 5.62; break if 2: heading -= 5.62; break end index = ( i mod 32) + 1 The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
#AutoHotkey
AutoHotkey
get_Index(angle){ return Mod(floor(angle / 11.25 +0.5), 32) + 1 }   get_Abbr_From_Index(i){ static points := [ "N", "NbE", "NNE", "NEbN", "NE", "NEbE", "ENE", "EbN" ,"E", "EbS", "ESE", "SEbE", "SE", "SEbS", "SSE", "SbE" ,"S", "SbW", "SSW", "SWbS", "SW", "SWbW", "WSW", "WbS" ,"W", "WbN", "WNW", "NWbW", "NW", "NWbN", "NNW", "NbW" ] return points[i] }   Build_Name_From_Abbr(a){ Loop Parse, a { i := A_Index if ((i = 2) && (SubStr(a, i, 1) != "b") && (StrLen(a) == 3)) retval .= "-" retval .= {N: "north", S: "south", E: "east" , W: "west" , b: " by "}[A_LoopField] } return Chr(Asc(SubStr(retval, 1, 1))-32) . SubStr(retval, 2) }   ; test   headings:= [0.00, 16.87, 16.88, 33.75, 50.62, 50.63, 67.50, 84.37, 84.38, 101.25 , 118.12, 118.13, 135.00, 151.87, 151.88, 168.75, 185.62, 185.63 , 202.50, 219.37, 219.38, 236.25, 253.12, 253.13, 270.00, 286.87 , 286.88, 303.75, 320.62, 320.63, 337.50, 354.37, 354.38] For n, a in headings { i := get_Index(a) out .= SubStr(" " i, -1) " " . SubStr(Build_Name_From_Abbr(get_Abbr_From_Index(i)) . " ", 1, 24) . SubStr(" " a, -5) . "`r`n" ; } clipboard := out
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height. Test task Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows: Convert image to grayscale; Compute the histogram Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance. Replace each pixel of luminance lesser than the median to black, and others to white. Use read/write ppm file, and grayscale image solutions.
#J
J
getImgHist=: ([: /:~ ~. ,. #/.~)@, medianHist=: {."1 {~ [: (+/\ I. -:@(+/)) {:"1 toBW=: 255 * medianHist@getImgHist < toGray
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height. Test task Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows: Convert image to grayscale; Compute the histogram Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance. Replace each pixel of luminance lesser than the median to black, and others to white. Use read/write ppm file, and grayscale image solutions.
#Java
Java
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO;   public enum ImageProcessing { ;   public static void main(String[] args) throws IOException { BufferedImage img = ImageIO.read(new File("example.png"));   BufferedImage bwimg = toBlackAndWhite(img);   ImageIO.write(bwimg, "png", new File("example-bw.png")); }   private static int luminance(int rgb) { int r = (rgb >> 16) & 0xFF; int g = (rgb >> 8) & 0xFF; int b = rgb & 0xFF; return (r + b + g) / 3; }   private static BufferedImage toBlackAndWhite(BufferedImage img) { int width = img.getWidth(); int height = img.getHeight();   int[] histo = computeHistogram(img);   int median = getMedian(width * height, histo);   BufferedImage bwimg = new BufferedImage(width, height, img.getType()); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { bwimg.setRGB(x, y, luminance(img.getRGB(x, y)) >= median ? 0xFFFFFFFF : 0xFF000000); } } return bwimg; }   private static int[] computeHistogram(BufferedImage img) { int width = img.getWidth(); int height = img.getHeight();   int[] histo = new int[256]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { histo[luminance(img.getRGB(x, y))]++; } } return histo; }   private static int getMedian(int total, int[] histo) { int median = 0; int sum = 0; for (int i = 0; i < histo.length && sum + histo[i] < total / 2; i++) { sum += histo[i]; median++; } return median; } }
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate. All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer. If any operation is not available in your language, note it.
#ABAP
ABAP
  report z_bitwise_operations.   class hex_converter definition. public section. class-methods: to_binary importing hex_value type x returning value(binary_value) type string,   to_decimal importing hex_value type x returning value(decimal_value) type int4. endclass.     class hex_converter implementation. method to_binary. data(number_of_bits) = xstrlen( hex_value ) * 8.   do number_of_bits times. get bit sy-index of hex_value into data(bit).   binary_value = |{ binary_value }{ bit }|. enddo. endmethod.     method to_decimal. decimal_value = hex_value. endmethod. endclass.     class missing_bitwise_operations definition. public section. class-methods: arithmetic_shift_left importing old_value type x change_with type x exporting new_value type x,   arithmetic_shift_right importing old_value type x change_with type x exporting new_value type x,   logical_shift_left importing old_value type x change_with type x exporting new_value type x,   logical_shift_right importing old_value type x change_with type x exporting new_value type x,   rotate_left importing old_value type x change_with type x exporting new_value type x,   rotate_right importing old_value type x change_with type x exporting new_value type x. endclass.     class missing_bitwise_operations implementation. method arithmetic_shift_left. clear new_value.   new_value = old_value * 2 ** change_with. endmethod.     method arithmetic_shift_right. clear new_value.   new_value = old_value div 2 ** change_with. endmethod.     method logical_shift_left. clear new_value.   data(bits) = hex_converter=>to_binary( old_value ).   data(length_of_bit_sequence) = strlen( bits ).   bits = shift_left( val = bits places = change_with ).   while strlen( bits ) < length_of_bit_sequence. bits = |{ bits }0|. endwhile.   do strlen( bits ) times. data(index) = sy-index - 1.   data(current_bit) = bits+index(1).   if current_bit eq `1`. set bit sy-index of new_value. endif. enddo. endmethod.     method logical_shift_right. clear new_value.   data(bits) = hex_converter=>to_binary( old_value ).   data(length_of_bit_sequence) = strlen( bits ).   bits = shift_right( val = bits places = change_with ).   while strlen( bits ) < length_of_bit_sequence. bits = |0{ bits }|. endwhile.   do strlen( bits ) times. data(index) = sy-index - 1.   data(current_bit) = bits+index(1).   if current_bit eq `1`. set bit sy-index of new_value. endif. enddo. endmethod.     method rotate_left. clear new_value.   data(bits) = hex_converter=>to_binary( old_value ).   bits = shift_left( val = bits circular = change_with ).   do strlen( bits ) times. data(index) = sy-index - 1.   data(current_bit) = bits+index(1).   if current_bit eq `1`. set bit sy-index of new_value. endif. enddo. endmethod.     method rotate_right. clear new_value.   data(bits) = hex_converter=>to_binary( old_value ).   bits = shift_right( val = bits circular = change_with ).   do strlen( bits ) times. data(index) = sy-index - 1.   data(current_bit) = bits+index(1).   if current_bit eq `1`. set bit sy-index of new_value. endif. enddo. endmethod. endclass.     start-of-selection. data: a type x length 4 value 255, b type x length 4 value 2, result type x length 4.   write: |a -> { a }, { hex_converter=>to_binary( a ) }, { hex_converter=>to_decimal( a ) }|, /.   write: |b -> { b }, { hex_converter=>to_binary( b ) }, { hex_converter=>to_decimal( b ) }|, /.   result = a bit-and b. write: |a & b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.   result = a bit-or b. write: |a \| b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.   result = a bit-xor b. write: |a ^ b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.   result = bit-not a. write: |~a -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.   missing_bitwise_operations=>arithmetic_shift_left( exporting old_value = bit-not a change_with = b importing new_value = result ). write: |~a << b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.   missing_bitwise_operations=>arithmetic_shift_right( exporting old_value = bit-not a change_with = b importing new_value = result ). write: |~a >> b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.   missing_bitwise_operations=>logical_shift_left( exporting old_value = a change_with = b importing new_value = result ). write: |a <<< b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.   missing_bitwise_operations=>logical_shift_right( exporting old_value = bit-not a change_with = b importing new_value = result ). write: |~a >>> b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.   missing_bitwise_operations=>rotate_left( exporting old_value = bit-not a change_with = b importing new_value = result ). write: |~a rotl b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.   missing_bitwise_operations=>rotate_right( exporting old_value = a change_with = b importing new_value = result ). write: |a rotr b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.  
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#Fortran
Fortran
subroutine quad_bezier(img, p1, p2, p3, color) type(rgbimage), intent(inout) :: img type(point), intent(in) :: p1, p2, p3 type(rgb), intent(in) :: color   integer :: i, j real :: pts(0:N_SEG,0:1), t, a, b, c, x, y   do i = 0, N_SEG t = real(i) / real(N_SEG) a = (1.0 - t)**2.0 b = 2.0 * t * (1.0 - t) c = t**2.0 x = a * p1%x + b * p2%x + c * p3%x y = a * p1%y + b * p2%y + c * p3%y pts(i,0) = x pts(i,1) = y end do   do i = 0, N_SEG-1 j = i + 1 call draw_line(img, point(pts(i,0), pts(i,1)), & point(pts(j,0), pts(j,1)), color) end do   end subroutine quad_bezier
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#FreeBASIC
FreeBASIC
' version 01-11-2016 ' compile with: fbc -s console   ' translation from Bitmap/Bresenham's line algorithm C entry Sub Br_line(x0 As Integer, y0 As Integer, x1 As Integer, y1 As Integer, _ Col As UInteger = &HFFFFFF)   Dim As Integer dx = Abs(x1 - x0), dy = Abs(y1 - y0) Dim As Integer sx = IIf(x0 < x1, 1, -1) Dim As Integer sy = IIf(y0 < y1, 1, -1) Dim As Integer er = IIf(dx > dy, dx, -dy) \ 2, e2   Do PSet(x0, y0), col If (x0 = x1) And (y0 = y1) Then Exit Do e2 = er If e2 > -dx Then Er -= dy : x0 += sx If e2 < dy Then Er += dx : y0 += sy Loop   End Sub   ' Bitmap/Bézier curves/Quadratic BBC BASIC entry Sub bezierquad(x1 As Double, y1 As Double, x2 As Double, y2 As Double, _ x3 As Double, y3 As Double, n As ULong, col As UInteger = &HFFFFFF)   Type point_ x As Integer y As Integer End Type   Dim As ULong i Dim As Double t, t1, a, b, c, d Dim As point_ p(n)   For i = 0 To n t = i / n t1 = 1 - t a = t1 ^ 2 b = t * t1 * 2 c = t ^ 2 p(i).x = Int(a * x1 + b * x2 + c * x3 + .5) p(i).y = Int(a * y1 + b * y2 + c * y3 + .5) Next   For i = 0 To n -1 Br_line(p(i).x, p(i).y, p(i +1).x, p(i +1).y, col) Next   End Sub   ' ------=< MAIN >=------   ScreenRes 250, 250, 32 ' 0,0 in top left corner   bezierquad(10, 100, 250, 270, 150, 20, 20)     ' empty keyboard buffer While InKey <> "" : Wend Print : Print "hit any key to end program" Sleep End
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#C.23
C#
  /// <summary> /// Draws a circle. /// </summary> /// <param name="image"> /// The destination image. /// </param> /// <param name="centerX"> /// The x center position of the circle. /// </param> /// <param name="centerY"> /// The y center position of the circle. /// </param> /// <param name="radius"> /// The radius of the circle. /// </param> /// <param name="color"> /// The color to use. /// </param> public static void DrawCircle(this GenericImage image, int centerX, int centerY, int radius, Color color) { int d = (5 - radius * 4) / 4; int x = 0; int y = radius;   do { // ensure index is in range before setting (depends on your image implementation) // in this case we check if the pixel location is within the bounds of the image before setting the pixel if (centerX + x >= 0 && centerX + x <= image.Width - 1 && centerY + y >= 0 && centerY + y <= image.Height - 1) image[centerX + x, centerY + y] = color; if (centerX + x >= 0 && centerX + x <= image.Width - 1 && centerY - y >= 0 && centerY - y <= image.Height - 1) image[centerX + x, centerY - y] = color; if (centerX - x >= 0 && centerX - x <= image.Width - 1 && centerY + y >= 0 && centerY + y <= image.Height - 1) image[centerX - x, centerY + y] = color; if (centerX - x >= 0 && centerX - x <= image.Width - 1 && centerY - y >= 0 && centerY - y <= image.Height - 1) image[centerX - x, centerY - y] = color; if (centerX + y >= 0 && centerX + y <= image.Width - 1 && centerY + x >= 0 && centerY + x <= image.Height - 1) image[centerX + y, centerY + x] = color; if (centerX + y >= 0 && centerX + y <= image.Width - 1 && centerY - x >= 0 && centerY - x <= image.Height - 1) image[centerX + y, centerY - x] = color; if (centerX - y >= 0 && centerX - y <= image.Width - 1 && centerY + x >= 0 && centerY + x <= image.Height - 1) image[centerX - y, centerY + x] = color; if (centerX - y >= 0 && centerX - y <= image.Width - 1 && centerY - x >= 0 && centerY - x <= image.Height - 1) image[centerX - y, centerY - x] = color; if (d < 0) { d += 2 * x + 1; } else { d += 2 * (x - y) + 1; y--; } x++; } while (x <= y); }  
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#Rust
Rust
pub trait Codec<Input = u8> { type Output: Iterator<Item = u8>;   fn accept(&mut self, input: Input) -> Self::Output; fn finish(self) -> Self::Output; }   #[derive(Debug)] pub struct BitDiscard { buf: u16, // Use the higher byte for storing the leftovers buf_bits: u8, // How many bits are valid in the buffer valid_len: u8, // How many bits to keep from the input shift_len: u8, // Pre-computed shift of the input byte }   impl BitDiscard { pub fn new(discard: u8) -> Self { assert!(discard < 8);   BitDiscard { buf: 0, buf_bits: 0, valid_len: 8 - discard, shift_len: 8 + discard, } } }   impl Codec<u8> for BitDiscard { type Output = std::option::IntoIter<u8>;   fn accept(&mut self, input: u8) -> Self::Output { let add = ((input as u16) << self.shift_len) >> self.buf_bits; self.buf |= add; self.buf_bits += self.valid_len;   let result = if self.buf_bits >= 8 { let result = (self.buf >> 8) as u8; self.buf <<= 8; self.buf_bits -= 8; Some(result) } else { None };   result.into_iter() }   fn finish(self) -> Self::Output { let result = if self.buf_bits > 0 { Some((self.buf >> 8) as u8) } else { None };   result.into_iter() } }   #[derive(Debug)] pub struct BitExpand { buf: u16, // For storing the leftovers buf_bits: u8, // How many bits are valid in the buffer valid_len: u8, // How many bits are valid in the input shift_len: u8, // How many bits to shift when expanding }   impl BitExpand { pub fn new(expand: u8) -> Self { assert!(expand < 8);   Self { buf: 0, buf_bits: 0, valid_len: 8 - expand, shift_len: 8 + expand, } } }   impl Codec<u8> for BitExpand { type Output = BitExpandIter;   fn accept(&mut self, input: u8) -> Self::Output { let add = ((input as u16) << 8) >> self.buf_bits; self.buf |= add; self.buf_bits += 8; let buf = self.buf; let leftover = self.buf_bits % self.valid_len; let buf_bits = self.buf_bits - leftover; self.buf <<= buf_bits; self.buf_bits = leftover;   Self::Output { buf, buf_bits, shift_len: self.shift_len, valid_len: self.valid_len, } }   fn finish(self) -> Self::Output { Self::Output { buf: 0, buf_bits: 0, shift_len: 0, valid_len: self.valid_len, } } }   #[derive(Debug)] pub struct BitExpandIter { buf: u16, buf_bits: u8, valid_len: u8, shift_len: u8, }   impl Iterator for BitExpandIter { type Item = u8;   fn next(&mut self) -> Option<u8> { if self.buf_bits < self.valid_len { None } else { let result = (self.buf >> self.shift_len) as u8; self.buf <<= self.valid_len; self.buf_bits -= self.valid_len; Some(result) } } }   fn process_bytes<C: Codec>(mut codec: C, bytes: &[u8]) -> Vec<u8> { let mut result: Vec<u8> = bytes.iter().flat_map(|byte| codec.accept(*byte)).collect(); codec.finish().for_each(|byte| result.push(byte)); result }   fn print_bytes(bytes: &[u8]) { for byte in bytes { print!("{:08b} ", byte); } println!();   for byte in bytes { print!("{:02x} ", byte); } println!(); }   fn main() { let original = b"STRINGIFY!"; let discard = 1; print_bytes(&original[..]); let compressed = process_bytes(BitDiscard::new(discard), &original[..]); print_bytes(&compressed); let decompressed = process_bytes(BitExpand::new(discard), &compressed); print_bytes(&decompressed); }
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bitdata.s7i"; include "strifile.s7i";   const proc: initWriteAscii (inout file: outFile, inout integer: bitPos) is func begin outFile.bufferChar := '\0;'; bitPos := 0; end func;   const proc: writeAscii (inout file: outFile, inout integer: bitPos, in string: ascii) is func local var char: ch is ' '; begin for ch range ascii do if ch > '\127;' then raise RANGE_ERROR; else putBitsMsb(outFile, bitPos, ord(ch), 7); end if; end for; end func;   const proc: finishWriteAscii (inout file: outFile, inout integer: bitPos) is func begin write(outFile, chr(ord(outFile.bufferChar))); end func;   const proc: initReadAscii (inout file: outFile, inout integer: bitPos) is func begin bitPos := 8; end func;   const func string: readAscii (inout file: inFile, inout integer: bitPos, in integer: length) is func result var string: stri is ""; local var char: ch is ' '; begin while not eof(inFile) and length(stri) < length do ch := chr(getBitsMsb(inFile, bitPos, 7)); if inFile.bufferChar <> EOF then stri &:= ch; end if; end while; end func;   const proc: main is func local var file: aFile is STD_NULL; var integer: bitPos is 0; begin aFile := openStrifile; initWriteAscii(aFile, bitPos); writeAscii(aFile, bitPos, "Hello, Rosetta Code!"); finishWriteAscii(aFile, bitPos); seek(aFile, 1); initReadAscii(aFile, bitPos); writeln(literal(readAscii(aFile, bitPos, 100))); end func;
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#R
R
  # View the existing code in the library library(pixmap) pixmap::write.pnm   #Usage write.pnm(theimage, filename)  
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Racket
Racket
  ;P3 (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))) ;buffer for storing argb data (send bitmap get-argb-pixels 0 0 width height buffer) ;copy pixels (parameterize ([current-output-port output-port]) (printf "P3\n~a ~a\n255" width height) ;header (for ([i (* width height)]) (define pixel-position (* 4 i)) (when (= (modulo i width) 0) (printf "\n")) ;end of row (printf "~s ~s ~s " (bytes-ref buffer (+ pixel-position 1)) ;r (bytes-ref buffer (+ pixel-position 2)) ;g (bytes-ref buffer (+ pixel-position 3)))))) ;b     (call-with-output-file "image.ppm" #:exists 'replace #:mode 'text (lambda (out) (bitmap->ppm bm out)))   ; P6 (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))) ;buffer for storing argb data (send bitmap get-argb-pixels 0 0 width height buffer) ;copy pixels (parameterize ([current-output-port output-port]) (printf "P6\n~a ~a\n255\n" width height) ;header (for ([i (* width height)]) (define pixel-position (* 4 i)) (write-byte (bytes-ref buffer (+ pixel-position 1))) ; r (write-byte (bytes-ref buffer (+ pixel-position 2))) ; g (write-byte (bytes-ref buffer (+ pixel-position 3)))))) ;b   (call-with-output-file "image.ppm" #:exists 'replace #:mode 'binary (lambda (out) (bitmap->ppm bm out)))   ;or any other output port    
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   func OpenInFile; \Open for input the file typed on command line int CpuReg, Handle; char CmdTail($80); [CpuReg:= GetReg; Blit(CpuReg(11), $81, CpuReg(12), CmdTail, $7F); \get copy of command line Trap(false); \turn off error trapping Handle:= FOpen(CmdTail, 0); \open named file for input FSet(Handle, ^I); \assign file to input device 3 OpenI(3); \initialize input buffer pointers if GetErr then return false; Trap(true); return true; ];   int C, X, Y, Width, Height, Max, Lum; real Red, Green, Blue; [if not OpenInFile then [Text(0, "File not found"); exit]; if ChIn(3)#^P or ChIn(3)#^6 then [Text(0, "Not P6 PPM file"); exit]; repeat loop [C:= ChIn(3); if C # ^# then quit; repeat C:= ChIn(3) until C=$0A\EOL\; ]; until C>=^0 & C<=^9; Backup; \back up so IntIn re-reads first digit Width:= IntIn(3); \(skips any whitespace) Height:= IntIn(3); Max:= IntIn(3) + 1; \(255/15=17; 256/16=16) case of Width<= 640 & Height<=480: SetVid($112); Width<= 800 & Height<=600: SetVid($115); Width<=1024 & Height<=768: SetVid($118) other SetVid($11B); \1280x1024 for Y:= 0 to Height-1 do for X:= 0 to Width-1 do [Red  := float(ChIn(3)*256/Max) * 0.21; \convert color to grayscale Green:= float(ChIn(3)*256/Max) * 0.72; Blue := float(ChIn(3)*256/Max) * 0.07; Lum:= fix(Red) + fix(Green) + fix(Blue); Point(X, Y, Lum<<16 + Lum<<8 + Lum); ]; X:= ChIn(1); \wait for keystroke SetVid(3); \restore normal text display ]
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Yabasic
Yabasic
sub readPPM(f$) local ff, x, y, t$, dcol$, wid, hei   if f$ = "" print "No PPM file name indicate." : return false   ff = open (f$, "rb") if not ff print "File ", f$, " not found."  : return false   input #ff t$, wid, hei, dcol$   if t$ = "P6" then open window wid, hei   for x = 0 to hei - 1 for y = 0 to wid - 1 color peek(#ff), peek(#ff), peek(#ff) dot y, x next y next x   close #ff else print "File is NOT PPM P6 type." : return false end if   return true end sub
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#COBOL
COBOL
01 some-bool PIC 1 BIT.
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#CoffeeScript
CoffeeScript
  h1 = {foo: "bar"} h2 = {foo: "bar"}   true_expressions = [ true 1 h1? # because h1 is defined above not false !false [] {} 1 + 1 == 2 1 == 1 # simple value equality true or false ]   false_expressions = [ false not true undeclared_variable? 0 '' null undefined h1 == h2 # despite having same key/values 1 == "1" # different types false and true ]  
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Swift
Swift
  func usage(_ e:String) { print("error: \(e)") print("./caeser -e 19 a-secret-string") print("./caeser -d 19 tskxvjxlskljafz") }   func charIsValid(_ c:Character) -> Bool { return c.isASCII && ( c.isLowercase || 45 == c.asciiValue ) // '-' = 45 }   func charRotate(_ c:Character, _ by:Int) -> Character { var cv:UInt8! = c.asciiValue if 45 == cv { cv = 96 } // if '-', set it to 'a'-1 cv += UInt8(by) if 122 < cv { cv -= 27 } // if larget than 'z', reduce by 27 if 96 == cv { cv = 45 } // restore '-' return Character(UnicodeScalar(cv)) }   func caesar(_ enc:Bool, _ key:Int, _ word:String) -> String { let r = enc ? key : 27 - key func charRotateWithKey(_ c:Character) -> Character { return charRotate(c,r) } return String(word.map(charRotateWithKey)) }   func main() { var encrypt = true   if 4 != CommandLine.arguments.count { return usage("caesar expects exactly three arguments") }   switch ( CommandLine.arguments[1] ) { case "-e": encrypt = true case "-d": encrypt = false default: return usage("first argument must be -e (encrypt) or -d (decrypt)") }   guard let key = Int(CommandLine.arguments[2]) else { return usage("second argument not a number (must be in range 0-26)") }   if key < 0 || 26 < key { return usage("second argument not in range 0-26") }   if !CommandLine.arguments[3].allSatisfy(charIsValid) { return usage("third argument must only be lowercase ascii characters, or -") }   let ans = caesar(encrypt,key,CommandLine.arguments[3]) print("\(ans)") }   func test() { if ( Character("a") != charRotate(Character("a"),0) ) { print("Test Fail 1") } if ( Character("-") != charRotate(Character("-"),0) ) { print("Test Fail 2") } if ( Character("-") != charRotate(Character("z"),1) ) { print("Test Fail 3") } if ( Character("z") != charRotate(Character("-"),26)) { print("Test Fail 4") } if ( "ihgmkzma" != caesar(true,8,"a-zecret") ) { print("Test Fail 5") } if ( "a-zecret" != caesar(false,8,"ihgmkzma") ) { print("Test Fail 6") } }   test() main()  
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input: [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance). Notes; The headings and indices can be calculated from this pseudocode: for i in 0..32 inclusive: heading = i * 11.25 case i %3: if 1: heading += 5.62; break if 2: heading -= 5.62; break end index = ( i mod 32) + 1 The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
#AutoIt
AutoIt
  Local $avArray[33] = [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, _ 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, _ 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]   For $i = 0 To UBound($avArray) - 1 Boxing_the_compass($avArray[$i]) Next   Func Boxing_the_compass($Degree) Local $namearray[33] = ["North", "North by east", "North-northeast", "Northeast by north", "Northeast", _ "Northeast by east", "East-northeast", "East by north", "East", "East by south", "East-southeast", _ "Southeast by east", "Southeast", "Southeast by south", "South-southeast", "South by east", "South", _ "South by west", "South-southwest", "Southwest by south", "Southwest", "Southwest by west", "West-southwest", _ "West by south", "West", "West by north", "West-northwest", "Northwest by west", "Northwest", "Northwest by north", _ "North-northwest", "North by west", "North"] ConsoleWrite(StringFormat("%-2s", Mod(Floor($Degree / 11.25 + 0.5), 32)) & " : " & _ StringFormat("%-20s", $namearray[Mod(Floor($Degree / 11.25 + 0.5), 32)]) & " : " & $Degree & @CRLF) EndFunc ;==>Boxing_the_compass  
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height. Test task Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows: Convert image to grayscale; Compute the histogram Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance. Replace each pixel of luminance lesser than the median to black, and others to white. Use read/write ppm file, and grayscale image solutions.
#Julia
Julia
using Images, FileIO   ima = load("data/lenna50.jpg") imb = Gray.(ima)   medcol = median(imb) imb[imb .≤ medcol] = Gray(0.0) imb[imb .> medcol] = Gray(1.0) save("data/lennaGray.jpg", imb)
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height. Test task Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows: Convert image to grayscale; Compute the histogram Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance. Replace each pixel of luminance lesser than the median to black, and others to white. Use read/write ppm file, and grayscale image solutions.
#Kotlin
Kotlin
// version 1.2.10   import java.io.File import java.awt.image.BufferedImage import javax.imageio.ImageIO   const val BLACK = 0xff000000.toInt() const val WHITE = 0xffffffff.toInt()   fun luminance(argb: Int): Int { val red = (argb shr 16) and 0xFF val green = (argb shr 8) and 0xFF val blue = argb and 0xFF return (0.2126 * red + 0.7152 * green + 0.0722 * blue).toInt() }   val BufferedImage.histogram: IntArray get() { val lumCount = IntArray(256) for (x in 0 until width) { for (y in 0 until height) { var argb = getRGB(x, y) lumCount[luminance(argb)]++ } } return lumCount }   fun findMedian(histogram: IntArray): Int { var lSum = 0 var rSum = 0 var left = 0 var right = 255 do { if (lSum < rSum) lSum += histogram[left++] else rSum += histogram[right--] } while (left != right) return left }   fun BufferedImage.toBlackAndWhite(median: Int) { for (x in 0 until width) { for (y in 0 until height) { val argb = getRGB(x, y) val lum = luminance(argb) if (lum < median) setRGB(x, y, BLACK) else setRGB(x, y, WHITE) } } }   fun main(args: Array<String>) { val image = ImageIO.read(File("Lenna100.jpg")) val median = findMedian(image.histogram) image.toBlackAndWhite(median) val bwFile = File("Lenna_bw.jpg") ImageIO.write(image, "jpg", bwFile) }
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate. All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer. If any operation is not available in your language, note it.
#ACL2
ACL2
(defun bitwise (a b) (list (logand a b) (logior a b) (logxor a b) (lognot a) (ash a b) (ash a (- b))))
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#Go
Go
package raster   const b2Seg = 20   func (b *Bitmap) Bézier2(x1, y1, x2, y2, x3, y3 int, p Pixel) { var px, py [b2Seg + 1]int fx1, fy1 := float64(x1), float64(y1) fx2, fy2 := float64(x2), float64(y2) fx3, fy3 := float64(x3), float64(y3) for i := range px { c := float64(i) / b2Seg a := 1 - c a, b, c := a*a, 2 * c * a, c*c px[i] = int(a*fx1 + b*fx2 + c*fx3) py[i] = int(a*fy1 + b*fy2 + c*fy3) } x0, y0 := px[0], py[0] for i := 1; i <= b2Seg; i++ { x1, y1 := px[i], py[i] b.Line(x0, y0, x1, y1, p) x0, y0 = x1, y1 } }   func (b *Bitmap) Bézier2Rgb(x1, y1, x2, y2, x3, y3 int, c Rgb) { b.Bézier2(x1, y1, x2, y2, x3, y3, c.Pixel()) }
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#Haskell
Haskell
{-# LANGUAGE FlexibleInstances, TypeSynonymInstances, ViewPatterns #-}   import Bitmap import Bitmap.Line import Control.Monad import Control.Monad.ST   type Point = (Double, Double) fromPixel (Pixel (x, y)) = (toEnum x, toEnum y) toPixel (x, y) = Pixel (round x, round y)   pmap :: (Double -> Double) -> Point -> Point pmap f (x, y) = (f x, f y)   onCoordinates :: (Double -> Double -> Double) -> Point -> Point -> Point onCoordinates f (xa, ya) (xb, yb) = (f xa xb, f ya yb)   instance Num Point where (+) = onCoordinates (+) (-) = onCoordinates (-) (*) = onCoordinates (*) negate = pmap negate abs = pmap abs signum = pmap signum fromInteger i = (i', i') where i' = fromInteger i   bézier :: Color c => Image s c -> Pixel -> Pixel -> Pixel -> c -> Int -> ST s () bézier i (fromPixel -> p1) (fromPixel -> p2) (fromPixel -> p3) c samples = zipWithM_ f ts (tail ts) where ts = map (/ top) [0 .. top] where top = toEnum $ samples - 1 curvePoint t = pt (t' ^^ 2) p1 + pt (2 * t * t') p2 + pt (t ^^ 2) p3 where t' = 1 - t pt n p = pmap (*n) p f (curvePoint -> p1) (curvePoint -> p2) = line i (toPixel p1) (toPixel p2) c
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#Clojure
Clojure
(defn draw-circle [draw-function x0 y0 radius] (letfn [(put [x y m] (let [x+ (+ x0 x) x- (- x0 x) y+ (+ y0 y) y- (- y0 y) x0y+ (+ x0 y) x0y- (- x0 y) xy0+ (+ y0 x) xy0- (- y0 x)] (draw-function x+ y+) (draw-function x+ y-) (draw-function x- y+) (draw-function x- y-) (draw-function x0y+ xy0+) (draw-function x0y+ xy0-) (draw-function x0y- xy0+) (draw-function x0y- xy0-) (let [[y m] (if (pos? m) [(dec y) (- m (* 8 y))] [y m])] (when (<= x y) (put (inc x) y (+ m 4 (* 8 x)))))))] (put 0 radius (- 5 (* 4 radius)))))
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#Tcl
Tcl
package require Tcl 8.5   proc crunch {ascii} { binary scan $ascii B* bitstring # crunch: remove the extraneous leading 0 bit regsub -all {0(.{7})} $bitstring {\1} 7bitstring set padded "$7bitstring[string repeat 0 [expr {8 - [string length $7bitstring]%8}]]" return [binary format B* $padded] }   proc expand {binary} { binary scan $binary B* padded # expand the 7 bit segments with their leading 0 bit set bitstring "0[join [regexp -inline -all {.{7}} $padded] 0]" return [binary format B* $bitstring] }   proc crunch_and_write {ascii filename} { set fh [open $filename w] fconfigure $fh -translation binary puts -nonewline $fh [crunch $ascii] close $fh }   proc read_and_expand {filename} { set fh [open $filename r] fconfigure $fh -translation binary set input [read $fh [file size $filename]] close $fh return [expand $input] }   set original "This is an ascii string that will be crunched, written, read and expanded." puts "my ascii string is [string length $original] bytes"   set filename crunched.out crunch_and_write $original $filename   set filesize [file size $filename] puts "the file containing the crunched text is $filesize bytes"   set expanded [read_and_expand $filename]   if {$original eq $expanded} { puts "the expanded string is the same as the original" } else { error "not the same" }
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Raku
Raku
class Pixel { has uint8 ($.R, $.G, $.B) } class Bitmap { has UInt ($.width, $.height); has Pixel @!data;   method fill(Pixel $p) { @!data = $p.clone xx ($!width*$!height) } method pixel( $i where ^$!width, $j where ^$!height --> Pixel ) is rw { @!data[$i*$!height + $j] }   method data { @!data } }   role PPM { method P6 returns Blob { "P6\n{self.width} {self.height}\n255\n".encode('ascii') ~ Blob.new: flat map { .R, .G, .B }, self.data } }   my Bitmap $b = Bitmap.new(width => 125, height => 125) but PPM; for flat ^$b.height X ^$b.width -> $i, $j { $b.pixel($i, $j) = Pixel.new: :R($i*2), :G($j*2), :B(255-$i*2); }   $*OUT.write: $b.P6;
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#zkl
zkl
//24-bpp P6 PPM solution: image:=File("lena.ppm","rb").read(); start:=image.find("\n255\n")+5; // Get sizeof PPM header   foreach n in ([start..image.len()-1,3]){ // Transform color triplets r,g,b:=image[n,3]; // Read colors stored in RGB order l:=(0.2126*r + 0.7152*g + 0.0722*b).toInt(); // Derive luminance image[n,3]=T(l,l,l); }   File("lenaGrey.ppm","wb").write(image);
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled. To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color). Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
#Action.21
Action!
INCLUDE "H6:RGBCIRCL.ACT" ;from task Midpoint circle algorithm   RGB black,white,yellow,blue   DEFINE PTR="CARD" TYPE PointB=[BYTE px,py] TYPE Queue=[PTR qfront,qrear,qdata INT capacity]   PROC QueueInit(Queue POINTER q) DEFINE MAXSIZE="500" CARD ARRAY a(MAXSIZE)   q.qfront=0 q.qrear=0 q.capacity=MAXSIZE q.qdata=a RETURN   BYTE FUNC IsQueueEmpty(Queue POINTER q) IF q.qfront=q.qrear THEN RETURN (1) FI RETURN (0)   PROC QueuePush(Queue POINTER q PointB POINTER p) PTR rear PointB POINTER tmp   rear=q.qrear+1 IF rear=q.capacity THEN rear=0 FI IF rear=q.qfront THEN Break() FI tmp=q.qdata+q.qrear*2 tmp.px=p.px tmp.py=p.py q.qrear=rear RETURN   PROC QueuePop(Queue POINTER q PointB POINTER p) PointB POINTER tmp   IF IsQueueEmpty(q) THEN Break() FI tmp=q.qdata+q.qfront*2 p.px=tmp.px p.py=tmp.py q.qfront==+1 IF q.qfront=q.capacity THEN q.qfront=0 FI RETURN   PROC DrawImage(RgbImage POINTER img BYTE x,y) RGB POINTER p BYTE i,j   p=img.data FOR j=0 TO img.h-1 DO FOR i=0 TO img.w-1 DO IF RgbEqual(p,yellow) THEN Color=1 ELSEIF RgbEqual(p,white) THEN Color=2 ELSEIF RgbEqual(p,blue) THEN Color=3 ELSE Color=0 FI Plot(x+i,y+j) p==+RGBSIZE OD OD RETURN   PROC FloodFill(RgbImage POINTER img BYTE x0,y0 RGB POINTER col) Queue q RGB c,tmp PointB p   GetRgbPixel(img,x0,y0,c) IF RgbEqual(c,col) THEN RETURN FI p.px=x0 p.py=y0 QueueInit(q) QueuePush(q,p) WHILE IsQueueEmpty(q)=0 DO QueuePop(q,p) x0=p.px y0=p.py   GetRgbPixel(img,x0,y0,tmp) IF RgbEqual(tmp,c) THEN SetRgbPixel(img,x0,y0,col)   IF x0>0 THEN GetRgbPixel(img,x0-1,y0,tmp) IF RgbEqual(tmp,c) THEN p.px=x0-1 p.py=y0 QueuePush(q,p) FI FI IF x0<img.w-1 THEN GetRgbPixel(img,x0+1,y0,tmp) IF RgbEqual(tmp,c) THEN p.px=x0+1 p.py=y0 QueuePush(q,p) FI FI IF y0>0 THEN GetRgbPixel(img,x0,y0-1,tmp) IF RgbEqual(tmp,c) THEN p.px=x0 p.py=y0-1 QueuePush(q,p) FI FI IF y0<img.h-1 THEN GetRgbPixel(img,x0,y0+1,tmp) IF RgbEqual(tmp,c) THEN p.px=x0 p.py=y0+1 QueuePush(q,p) FI FI FI OD RETURN   PROC Main() RgbImage img BYTE CH=$02FC,size=[40] BYTE ARRAY p(4800) BYTE n INT x,y RGB POINTER col   Graphics(7+16) SetColor(0,13,12) ;yellow SetColor(1,0,14)  ;white SetColor(2,8,6)  ;blue SetColor(4,0,0)  ;black   RgbBlack(black) RgbYellow(yellow) RgbWhite(white) RgbBlue(blue)   InitRgbImage(img,size,size,p) FillRgbImage(img,black)   RgbCircle(img,size/2,size/2,size/2-1,white) RgbCircle(img,2*size/5,2*size/5,size/5,white) DrawImage(img,0,(96-size)/2)   FloodFill(img,3*size/5,3*size/5,white) DrawImage(img,size,(96-size)/2)   FloodFill(img,2*size/5,2*size/5,blue) DrawImage(img,2*size,(96-size)/2)   FloodFill(img,3*size/5,3*size/5,yellow) DrawImage(img,3*size,(96-size)/2)   DO UNTIL CH#$FF OD CH=$FF RETURN
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Common_Lisp
Common Lisp
  VAR b,c: BOOLEAN; ... b := TRUE; c := FALSE; ...  
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Component_Pascal
Component Pascal
  VAR b,c: BOOLEAN; ... b := TRUE; c := FALSE; ...  
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Tcl
Tcl
package require Tcl 8.6; # Or TclOO package for 8.5   oo::class create Caesar { variable encryptMap decryptMap constructor shift { for {set i 0} {$i < 26} {incr i} { # Play fast and loose with string/list duality for shorter code append encryptMap [format "%c %c %c %c " \ [expr {$i+65}] [expr {($i+$shift)%26+65}] \ [expr {$i+97}] [expr {($i+$shift)%26+97}]] append decryptMap [format "%c %c %c %c " \ [expr {$i+65}] [expr {($i-$shift)%26+65}] \ [expr {$i+97}] [expr {($i-$shift)%26+97}]] } }   method encrypt text { string map $encryptMap $text } method decrypt text { string map $decryptMap $text } }
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input: [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance). Notes; The headings and indices can be calculated from this pseudocode: for i in 0..32 inclusive: heading = i * 11.25 case i %3: if 1: heading += 5.62; break if 2: heading -= 5.62; break end index = ( i mod 32) + 1 The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
#AWK
AWK
#!/usr/bin/awk -f BEGIN { split("N NbE NNE NEbN NE NEbE ENE EbN E EbS ESE SEbE SE SEbS SSE SbE S SbW SSW SWbS SW SWbW WSW WbS W WbN WNW NWbW NW NWbN NNW NbW",A," "); }   function ceil(x) { y = int(x) return y < x ? y + 1 : y }   function compassbox(d) { return ceil( ( (d + 360 / 64) % 360) * 32 / 360); }   { box = compassbox($1); printf "%6.2f : %2d\t%s\n",$1,box,A[box]; }  
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height. Test task Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows: Convert image to grayscale; Compute the histogram Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance. Replace each pixel of luminance lesser than the median to black, and others to white. Use read/write ppm file, and grayscale image solutions.
#Lua
Lua
function Histogram( image ) local size_x, size_y = #image, #image[1]   local histo = {} for i = 0, 255 do histo[i] = 0 end   for i = 1, size_x do for j = 1, size_y do histo[ image[i][j] ] = histo[ image[i][j] ] + 1 end end   return histo end   function FindMedian( histogram ) local sum_l, sum_r = 0, 0 local left, right = 0, 255   repeat if sum_l < sum_r then sum_l = sum_l + histogram[left] left = left + 1 else sum_r = sum_r + histogram[right] right = right - 1 end until left == right   return left end     bitmap = Read_PPM( "inputimage.ppm" ) gray_im = ConvertToGrayscaleImage( bitmap ) histogram = Histogram( gray_im ) median = FindMedian( histogram )   for i = 1, #gray_im do for j = 1, #gray_im[1] do if gray_im[i][j] < median then gray_im[i][j] = 0 else gray_im[i][j] = 255 end end end   bitmap = ConvertToColorImage( gray_im ) Write_PPM( "outputimage.ppm", bitmap )
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate. All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer. If any operation is not available in your language, note it.
#Action.21
Action!
BYTE FUNC Not(BYTE a) RETURN (a!$FF)   PROC Main() BYTE a=[127],b=[2],res   res=a&b PrintF("%B AND %B = %B%E",a,b,res)   res=a%b PrintF("%B OR %B = %B%E",a,b,res)   res=a!b PrintF("%B XOR %B = %B%E",a,b,res)   res=Not(a) PrintF("NOT %B = %B (by %B XOR $FF)%E",a,res,a)   res=a RSH b PrintF("%B SHR %B = %B%E",a,b,res)   res=a LSH b PrintF("%B SHL %B = %B%E",a,b,res) RETURN
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#J
J
// Version 1.2.40   import java.awt.Color import java.awt.Graphics import java.awt.image.BufferedImage import kotlin.math.abs import java.io.File import javax.imageio.ImageIO   class Point(var x: Int, var y: Int)   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 drawLine(x0: Int, y0: Int, x1: Int, y1: Int, c: Color) { val dx = abs(x1 - x0) val dy = abs(y1 - y0) val sx = if (x0 < x1) 1 else -1 val sy = if (y0 < y1) 1 else -1 var xx = x0 var yy = y0 var e1 = (if (dx > dy) dx else -dy) / 2 var e2: Int while (true) { setPixel(xx, yy, c) if (xx == x1 && yy == y1) break e2 = e1 if (e2 > -dx) { e1 -= dy; xx += sx } if (e2 < dy) { e1 += dx; yy += sy } } }   fun quadraticBezier(p1: Point, p2: Point, p3: Point, clr: Color, n: Int) { val pts = List(n + 1) { Point(0, 0) } for (i in 0..n) { val t = i.toDouble() / n val u = 1.0 - t val a = u * u val b = 2.0 * t * u val c = t * t pts[i].x = (a * p1.x + b * p2.x + c * p3.x).toInt() pts[i].y = (a * p1.y + b * p2.y + c * p3.y).toInt() setPixel(pts[i].x, pts[i].y, clr) } for (i in 0 until n) { val j = i + 1 drawLine(pts[i].x, pts[i].y, pts[j].x, pts[j].y, clr) } } }   fun main(args: Array<String>) { val width = 320 val height = 320 val bbs = BasicBitmapStorage(width, height) with (bbs) { fill(Color.cyan) val p1 = Point(10, 100) val p2 = Point(250, 270) val p3 = Point(150, 20) quadraticBezier(p1, p2, p3, Color.black, 20) val qbFile = File("quadratic_bezier.jpg") ImageIO.write(image, "jpg", qbFile) } }
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#Common_Lisp
Common Lisp
(defun draw-circle (draw-function x0 y0 radius) (labels ((foo (x y) (funcall draw-function x y)) (put (x y m) (let ((x+ (+ x0 x)) (x- (- x0 x)) (y+ (+ y0 y)) (y- (- y0 y)) (x0y+ (+ x0 y)) (x0y- (- x0 y)) (xy0+ (+ y0 x)) (xy0- (- y0 x))) (foo x+ y+) (foo x+ y-) (foo x- y+) (foo x- y-) (foo x0y+ xy0+) (foo x0y+ xy0-) (foo x0y- xy0+) (foo x0y- xy0-) (multiple-value-bind (y m) (if (plusp m) (values (1- y) (- m (* 8 y))) (values y m)) (when (<= x y) (put (1+ x) y (+ m 4 (* 8 x)))))))) (put 0 radius (- 5 (* 4 radius))) (values)))