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/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Lua | Lua | function Transpose( m )
local res = {}
for i = 1, #m[1] do
res[i] = {}
for j = 1, #m do
res[i][j] = m[j][i]
end
end
return res
end
-- a test for Transpose(m)
mat = { { 1, 2, 3 }, { 4, 5, 6 } }
erg = Transpose( mat )
for i = 1, #erg do
for j = 1, #erg[1] do
io.write( erg[i][j] )
io.write( " " )
end
io.write( "\n" )
end |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth-first search algorithm.
Start at a random cell.
Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor:
If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell.
Related tasks
Maze solving.
| #Wren | Wren | import "random" for Random
import "os" for Process
var Rand = Random.new()
class Direction {
static n { __n }
static s { __s }
static e { __e }
static w { __w }
static init() {
__n = new_(1, 0, -1)
__s = new_(2, 0, 1)
__e = new_(4, 1, 0)
__w = new_(8, -1, 0)
__n.opposite = __s
__s.opposite = __n
__e.opposite = __w
__w.opposite = __e
}
construct new_(bit, dx, dy) {
_bit = bit
_dx = dx
_dy = dy
_opposite = null
}
bit { _bit }
dx { _dx }
dy { _dy }
opposite { _opposite }
opposite=(d) { _opposite = d }
}
Direction.init()
class MazeGenerator {
construct new(x, y) {
_x = x
_y = y
_maze = List.filled(x, null)
for (i in 0...x) _maze[i] = List.filled(y, 0)
}
between_(v, upper) { v >= 0 && v < upper }
generate(cx, cy) {
var values = [Direction.n, Direction.s, Direction.e, Direction.w]
Rand.shuffle(values)
values.each { |v|
var nx = cx + v.dx
var ny = cy + v.dy
if (between_(nx, _x) && between_(ny, _y) && _maze[nx][ny] == 0) {
_maze[cx][cy] = _maze[cx][cy] | v.bit
_maze[nx][ny] = _maze[nx][ny] | v.opposite.bit
generate(nx, ny)
}
}
}
display() {
for (i in 0..._y) {
// draw the north edge
for (j in 0..._x) System.write((_maze[j][i] & 1) == 0 ? "+---" : "+ ")
System.print("+")
// draw the west edge
for (j in 0..._x) System.write((_maze[j][i] & 8) == 0 ? "| " : " ")
System.print("|")
}
// draw the bottom line
for (j in 0..._x) System.write("+---")
System.print("+")
}
}
var args = Process.arguments
var x = (args.count >= 1) ? Num.fromString(args[0]) : 8
var y = (args.count == 2) ? Num.fromString(args[1]) : 8
var mg = MazeGenerator.new(x, y)
mg.generate(0, 0)
mg.display() |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #S-lang | S-lang | require("chksum");
print(md5sum("The quick brown fox jumped over the lazy dog's back")); |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #IDL | IDL |
PRO Mandelbrot,xRange,yRange,xPixels,yPixels,iterations
xPixelstartVec = Lindgen( xPixels) * Float(xRange[1]-xRange[0]) / $
xPixels + xRange[0]
yPixelstartVec = Lindgen( yPixels) * Float(YRANGE[1]-yrange[0])$
/ yPixels + yRange[0]
constArr = Complex( Rebin( xPixelstartVec, xPixels, yPixels),$
Rebin( Transpose(yPixelstartVec), xPixels, yPixels))
valArr = ComplexArr( xPixels, yPixels)
res = IntArr( xPixels, yPixels)
oriIndex = Lindgen( Long(xPixels) * yPixels)
FOR i = 0, iterations-1 DO BEGIN ; only one loop needed
; calculation for whole array at once
valArr = valArr^2 - constArr
whereIn = Where( Abs( valArr) LE 4.0d, COMPLEMENT=whereOut)
IF whereIn[0] EQ -1 THEN BREAK
valArr = valArr[ whereIn]
constArr = constArr[ whereIn]
IF whereOut[0] NE -1 THEN BEGIN
res[ oriIndex[ whereOut]] = i+1
oriIndex = oriIndex[ whereIn]
ENDIF
ENDFOR
tv,res ; open a window and show the result
END
Mandelbrot,[-1.,2.3],[-1.3,1.3],640,512,200
END
|
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Lua | Lua | function MatMul( m1, m2 )
if #m1[1] ~= #m2 then -- inner matrix-dimensions must agree
return nil
end
local res = {}
for i = 1, #m1 do
res[i] = {}
for j = 1, #m2[1] do
res[i][j] = 0
for k = 1, #m2 do
res[i][j] = res[i][j] + m1[i][k] * m2[k][j]
end
end
end
return res
end
-- Test for MatMul
mat1 = { { 1, 2, 3 }, { 4, 5, 6 } }
mat2 = { { 1, 2 }, { 3, 4 }, { 5, 6 } }
erg = MatMul( mat1, mat2 )
for i = 1, #erg do
for j = 1, #erg[1] do
io.write( erg[i][j] )
io.write(" ")
end
io.write("\n")
end |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Maple | Maple |
M := <<2,3>|<3,4>|<5,6>>;
M^%T;
with(LinearAlgebra):
Transpose(M);
|
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth-first search algorithm.
Start at a random cell.
Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor:
If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell.
Related tasks
Maze solving.
| #zkl | zkl |
fcn make_maze(w = 16, h = 8){
// make arrays with lists of lists (all mutable)
vis:=(w.pump(List().write,0)+1)*h + w.pump(List().write,1);
ver:=(w.pump(List().write,T(Void,"| ")) + "|")*h + T;
hor:=(w.pump(List().write,T(Void,"+---")) + "+")*(h + 1);
fcn(x,y,vis,ver,hor){
vis[y][x] = 1;
d:=L(T(x - 1, y), T(x, y + 1), T(x + 1, y), T(x, y - 1)).shuffle();
foreach xx,yy in (d){
if(vis[yy][xx]) continue;
if(xx==x) hor[y.max(yy)][x]="+ ";
if(yy==y) ver[y][x.max(xx)]=" ";
self.fcn(xx,yy,vis,ver,hor);
}
}((0).random(w),(0).random(h),vis,ver,hor);
foreach a,b in (hor.zip(ver)) { println(a.concat(),"\n",b.concat()) }
return(ver,hor);
}
make_maze(); |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #Scala | Scala | object RosettaMD5 extends App {
def MD5(s: String): String = {
// Besides "MD5", "SHA-256", and other hashes are available
val m = java.security.MessageDigest.getInstance("MD5").digest(s.getBytes("UTF-8"))
m.map("%02x".format(_)).mkString
}
assert("d41d8cd98f00b204e9800998ecf8427e" == MD5(""))
assert("0cc175b9c0f1b6a831c399e269772661" == MD5("a"))
assert("900150983cd24fb0d6963f7d28e17f72" == MD5("abc"))
assert("f96b697d7cb7938d525a2f31aaf161d0" == MD5("message digest"))
assert("c3fcd3d76192e4007dfb496cca67e13b" == MD5("abcdefghijklmnopqrstuvwxyz"))
assert("e38ca1d920c4b8b8d3946b2c72f01680" == MD5("The quick brown fox jumped over the lazy dog's back"))
assert("d174ab98d277d9f5a5611c2c9f419d9f" ==
MD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"))
assert("57edf4a22be3c955ac49da2e2107b67a" ==
MD5("12345678901234567890123456789012345678901234567890123456789012345678901234567890"))
import scala.compat.Platform.currentTime
println(s"Successfully completed without errors. [total ${currentTime - executionStart} ms]")
} |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Inform_7 | Inform 7 | "Mandelbrot"
The story headline is "A Non-Interactive Set".
Include Glimmr Drawing Commands by Erik Temple.
[Q20 fixed-point or floating-point: see definitions below]
Use floating-point math.
Finished is a room.
The graphics-window is a graphics g-window spawned by the main-window.
The position is g-placeabove.
When play begins:
let f10 be 10 as float;
now min re is ( -20 as float ) fdiv f10;
now max re is ( 6 as float ) fdiv f10;
now min im is ( -12 as float ) fdiv f10;
now max im is ( 12 as float ) fdiv f10;
now max iterations is 100;
add color g-Black to the palette;
add color g-Red to the palette;
add hex "#FFA500" to the palette;
add color g-Yellow to the palette;
add color g-Green to the palette;
add color g-Blue to the palette;
add hex "#4B0082" to the palette;
add hex "#EE82EE" to the palette;
open up the graphics-window.
Min Re is a number that varies.
Max Re is a number that varies.
Min Im is a number that varies.
Max Im is a number that varies.
Max Iterations is a number that varies.
Min X is a number that varies.
Max X is a number that varies.
Min Y is a number that varies.
Max Y is a number that varies.
The palette is a list of numbers that varies.
[vertically mirrored version]
Window-drawing rule for the graphics-window when max im is fneg min im:
clear the graphics-window;
let point be { 0, 0 };
now min X is 0 as float;
now min Y is 0 as float;
let mX be the width of the graphics-window minus 1;
let mY be the height of the graphics-window minus 1;
now max X is mX as float;
now max Y is mY as float;
let L be the column order with max mX;
repeat with X running through L:
now entry 1 in point is X;
repeat with Y running from 0 to mY / 2:
now entry 2 in point is Y;
let the scaled point be the complex number corresponding to the point;
let V be the Mandelbrot result for the scaled point;
let C be the color corresponding to V;
if C is 0, next;
draw a rectangle (C) in the graphics-window at the point with size 1 by 1;
now entry 2 in point is mY - Y;
draw a rectangle (C) in the graphics-window at the point with size 1 by 1;
yield to VM;
rule succeeds.
[slower non-mirrored version]
Window-drawing rule for the graphics-window:
clear the graphics-window;
let point be { 0, 0 };
now min X is 0 as float;
now min Y is 0 as float;
let mX be the width of the graphics-window minus 1;
let mY be the height of the graphics-window minus 1;
now max X is mX as float;
now max Y is mY as float;
let L be the column order with max mX;
repeat with X running through L:
now entry 1 in point is X;
repeat with Y running from 0 to mY:
now entry 2 in point is Y;
let the scaled point be the complex number corresponding to the point;
let V be the Mandelbrot result for the scaled point;
let C be the color corresponding to V;
if C is 0, next;
draw a rectangle (C) in the graphics-window at the point with size 1 by 1;
yield to VM;
rule succeeds.
To decide which list of numbers is column order with max (N - number):
let L be a list of numbers;
let L2 be a list of numbers;
let D be 64;
let rev be false;
while D > 0:
let X be 0;
truncate L2 to 0 entries;
while X <= N:
if D is 64 or X / D is odd, add X to L2;
increase X by D;
if rev is true:
reverse L2;
let rev be false;
otherwise:
let rev be true;
add L2 to L;
let D be D / 2;
decide on L.
To decide which list of numbers is complex number corresponding to (P - list of numbers):
let R be a list of numbers;
extend R to 2 entries;
let X be entry 1 in P as float;
let X be (max re fsub min re) fmul (X fdiv max X);
let X be X fadd min re;
let Y be entry 2 in P as float;
let Y be (max im fsub min im) fmul (Y fdiv max Y);
let Y be Y fadd min im;
now entry 1 in R is X;
now entry 2 in R is Y;
decide on R.
To decide which number is Mandelbrot result for (P - list of numbers):
let c_re be entry 1 in P;
let c_im be entry 2 in P;
let z_re be 0 as float;
let z_im be z_re;
let threshold be 4 as float;
let runs be 0;
while 1 is 1:
[ z = z * z ]
let r2 be z_re fmul z_re;
let i2 be z_im fmul z_im;
let ri be z_re fmul z_im;
let z_re be r2 fsub i2;
let z_im be ri fadd ri;
[ z = z + c ]
let z_re be z_re fadd c_re;
let z_im be z_im fadd c_im;
let norm be (z_re fmul z_re) fadd (z_im fmul z_im);
increase runs by 1;
if norm is greater than threshold, decide on runs;
if runs is max iterations, decide on 0.
To decide which number is color corresponding to (V - number):
let L be the number of entries in the palette;
let N be the remainder after dividing V by L;
decide on entry (N + 1) in the palette.
Section - Fractional numbers (for Glulx only)
To decide which number is (N - number) as float: (- (numtof({N})) -).
To decide which number is (N - number) fadd (M - number): (- (fadd({N}, {M})) -).
To decide which number is (N - number) fsub (M - number): (- (fsub({N}, {M})) -).
To decide which number is (N - number) fmul (M - number): (- (fmul({N}, {M})) -).
To decide which number is (N - number) fdiv (M - number): (- (fdiv({N}, {M})) -).
To decide which number is fneg (N - number): (- (fneg({N})) -).
To yield to VM: (- glk_select_poll(gg_event); -).
Use Q20 fixed-point math translates as (- Constant Q20_MATH; -).
Use floating-point math translates as (- Constant FLOAT_MATH; -).
Include (-
#ifdef Q20_MATH;
! Q11.20 format: 1 sign bit, 11 integer bits, 20 fraction bits
[ numtof n r; @shiftl n 20 r; return r; ];
[ fadd n m; return n+m; ];
[ fsub n m; return n-m; ];
[ fmul n m; n = n + $$1000000000; @sshiftr n 10 n; m = m + $$1000000000; @sshiftr m 10 m; return n * m; ];
[ fdiv n m; @sshiftr m 20 m; return n / m; ];
[ fneg n; return -n; ];
#endif;
#ifdef FLOAT_MATH;
[ numtof f; @"S2:400" f f; return f; ];
[ fadd n m; @"S3:416" n m n; return n; ];
[ fsub n m; @"S3:417" n m n; return n; ];
[ fmul n m; @"S3:418" n m n; return n; ];
[ fdiv n m; @"S3:419" n m n; return n; ];
[ fneg n; @bitxor n $80000000 n; return n; ];
#endif;
-). |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #M2000_Interpreter | M2000 Interpreter |
Module CheckMatMult {
\\ Matrix Multiplication
\\ we use array pointers so we pass arrays byvalue but change this by reference
\\ this can be done because always arrays passed by reference,
\\ and Read statement decide if this goes to a pointer of array or copied to a local array
\\ the first line of code for MatMul is: Read a as array, b as array
\\ interpreter insert this at function construction.
\\ if a pointer inside function change to point to a new array, the this has no reflect to the passed array.
Function MatMul(a as array, b as array) {
if dimension(a)<>2 or dimension(b)<>2 then Error "Need two 2D arrays "
let a2=dimension(a,2), b1=dimension(b,1)
if a2<>b1 then Error "Need columns of first array equal to rows of second array"
let a1=dimension(a,1), b2=dimension(b,2)
let aBase=dimension(a,1,0)-1, bBase=dimension(b,1,0)-1
let aBase1=dimension(a,2,0)-1, bBase1=dimension(b,2,0)-1
link a,b to a(), b() ' change interface for arrays
dim base 1, c(a1, b2)
for i=1 to a1 : let ia=i+abase : for j=1 to b2 : let jb=j+bBase1 : for k=1 to a2
c(i,j)+=a(ia,k+aBase1)*b(k+bBase,jb)
next k : next j : next i
\\ redim to base 0
dim base 0, c(a1, b2)
=c()
}
\\ define arrays with different base per dimension
\\ res() defined as empty array
dim a(10 to 13, 4), b(4, 2 to 5), res()
\\ numbers from ADA task
a(10,0)= 1, 1, 1, 1, 2, 4, 8, 16, 3, 9, 27, 81, 4, 16, 64, 256
b(0,2)= 4, -3, 4/3, -1/4, -13/3, 19/4, -7/3, 11/24, 3/2, -2, 7/6, -1/4, -1/6, 1/4, -1/6, 1/24
res()=MatMul(a(), b())
for i=0 to 3 :for j=0 to 3
Print res(i,j),
next j : Print : next i
}
CheckMatMult
Module CheckMatMult2 {
\\ Matrix Multiplication
\\ pass arrays by reference
\\ if we change a passed array here, to a new array then this change also the reference array.
Function MatMul(&a(),&b()) {
if dimension(a())<>2 or dimension(b())<>2 then Error "Need two 2D arrays "
let a2=dimension(a(),2), b1=dimension(b(),1)
if a2<>b1 then Error "Need columns of first array equal to rows of second array"
let a1=dimension(a(),1), b2=dimension(b(),2)
let aBase=dimension(a(),1,0)-1, bBase=dimension(b(),1,0)-1
let aBase1=dimension(a(),2,0)-1, bBase1=dimension(b(),2,0)-1
dim base 1, c(a1, b2)
for i=1 to a1 : let ia=i+abase : for j=1 to b2 : let jb=j+bBase1 : for k=1 to a2
c(i,j)+=a(ia,k+aBase1)*b(k+bBase,jb)
next k : next j : next i
\\ redim to base 0
dim base 0, c(a1, b2)
=c()
}
\\ define arrays with different base per dimension
\\ res() defined as empty array
dim a(10 to 13, 4), b(4, 2 to 5), res()
\\ numbers from ADA task
a(10,0)= 1, 1, 1, 1, 2, 4, 8, 16, 3, 9, 27, 81, 4, 16, 64, 256
b(0,2)= 4, -3, 4/3, -1/4, -13/3, 19/4, -7/3, 11/24, 3/2, -2, 7/6, -1/4, -1/6, 1/4, -1/6, 1/24
res()=MatMul(&a(), &b())
for i=0 to 3 :for j=0 to 3
Print res(i,j),
next j : Print : next i
}
CheckMatMult2
|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | originalMatrix = {{1, 1, 1, 1},
{2, 4, 8, 16},
{3, 9, 27, 81},
{4, 16, 64, 256},
{5, 25, 125, 625}}
transposedMatrix = Transpose[originalMatrix] |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "msgdigest.s7i";
const proc: main is func
begin
writeln(hex(md5("The quick brown fox jumped over the lazy dog's back")));
end func; |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #J | J | mcf=. (<: 2:)@|@(] ((*:@] + [)^:((<: 2:)@|@])^:1000) 0:) NB. 1000 iterations test |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Maple | Maple | A := <<1|2|3>,<4|5|6>>;
B := <<1,2,3>|<4,5,6>|<7,8,9>|<10,11,12>>;
A . B; |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #MATLAB | MATLAB | >> transpose([1 2;3 4])
ans =
1 3
2 4
>> [1 2;3 4].'
ans =
1 3
2 4 |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #Sidef | Sidef | var digest = frequire('Digest::MD5');
say digest.md5_hex("The quick brown fox jumped over the lazy dog's back"); |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Java | Java | import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
public class Mandelbrot extends JFrame {
private final int MAX_ITER = 570;
private final double ZOOM = 150;
private BufferedImage I;
private double zx, zy, cX, cY, tmp;
public Mandelbrot() {
super("Mandelbrot Set");
setBounds(100, 100, 800, 600);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
I = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < getHeight(); y++) {
for (int x = 0; x < getWidth(); x++) {
zx = zy = 0;
cX = (x - 400) / ZOOM;
cY = (y - 300) / ZOOM;
int iter = MAX_ITER;
while (zx * zx + zy * zy < 4 && iter > 0) {
tmp = zx * zx - zy * zy + cX;
zy = 2.0 * zx * zy + cY;
zx = tmp;
iter--;
}
I.setRGB(x, y, iter | (iter << 8));
}
}
}
@Override
public void paint(Graphics g) {
g.drawImage(I, 0, 0, this);
}
public static void main(String[] args) {
new Mandelbrot().setVisible(true);
}
} |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #MathCortex | MathCortex |
>> A = [2,3; -2,1]
2 3
-2 1
>> B = [1,2;4,2]
1 2
4 2
>> A * B
14 10
2 -2
|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Maxima | Maxima | originalMatrix : matrix([1, 1, 1, 1],
[2, 4, 8, 16],
[3, 9, 27, 81],
[4, 16, 64, 256],
[5, 25, 125, 625]);
transposedMatrix : transpose(originalMatrix); |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #Slate | Slate | 'The quick brown fox jumped over the lazy dog\'s back' md5String. "==> 'e38ca1d920c4b8b8d3946b2c72f01680'" |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #JavaScript | JavaScript | function mandelIter(cx, cy, maxIter) {
var x = 0.0;
var y = 0.0;
var xx = 0;
var yy = 0;
var xy = 0;
var i = maxIter;
while (i-- && xx + yy <= 4) {
xy = x * y;
xx = x * x;
yy = y * y;
x = xx - yy + cx;
y = xy + xy + cy;
}
return maxIter - i;
}
function mandelbrot(canvas, xmin, xmax, ymin, ymax, iterations) {
var width = canvas.width;
var height = canvas.height;
var ctx = canvas.getContext('2d');
var img = ctx.getImageData(0, 0, width, height);
var pix = img.data;
for (var ix = 0; ix < width; ++ix) {
for (var iy = 0; iy < height; ++iy) {
var x = xmin + (xmax - xmin) * ix / (width - 1);
var y = ymin + (ymax - ymin) * iy / (height - 1);
var i = mandelIter(x, y, iterations);
var ppos = 4 * (width * iy + ix);
if (i > iterations) {
pix[ppos] = 0;
pix[ppos + 1] = 0;
pix[ppos + 2] = 0;
} else {
var c = 3 * Math.log(i) / Math.log(iterations - 1.0);
if (c < 1) {
pix[ppos] = 255 * c;
pix[ppos + 1] = 0;
pix[ppos + 2] = 0;
}
else if ( c < 2 ) {
pix[ppos] = 255;
pix[ppos + 1] = 255 * (c - 1);
pix[ppos + 2] = 0;
} else {
pix[ppos] = 255;
pix[ppos + 1] = 255;
pix[ppos + 2] = 255 * (c - 2);
}
}
pix[ppos + 3] = 255;
}
}
ctx.putImageData(img, 0, 0);
}
var canvas = document.createElement('canvas');
canvas.width = 900;
canvas.height = 600;
document.body.insertBefore(canvas, document.body.childNodes[0]);
mandelbrot(canvas, -2, 1, -1, 1, 1000); |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Dot[{{a, b}, {c, d}}, {{w, x}, {y, z}}] |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #MAXScript | MAXScript | m = bigMatrix 5 4
for i in 1 to 5 do for j in 1 to 4 do m[i][j] = pow i j
m = transpose m |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Nial | Nial | |a := 2 3 reshape count 6
=1 2 3
=4 5 6 |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #Smalltalk | Smalltalk | PackageLoader fileInPackage: 'Digest' !
(MD5 hexDigestOf: 'The quick brown fox jumped over the lazy dog''s back') displayNl. |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #jq | jq | # SVG STUFF
def svg(id; width; height):
"<svg width='\(width // "100%")' height='\(height // "100%") '
id='\(id)'
xmlns='http://www.w3.org/2000/svg'>";
def pixel(x;y;r;g;b;a):
"<circle cx='\(x)' cy='\(y)' r='1' fill='rgb(\(r|floor),\(g|floor),\(b|floor))' />";
# "UNTIL"
# As soon as "condition" is true, then emit . and stop:
def do_until(condition; next):
def u: if condition then . else (next|u) end;
u;
|
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #MATLAB | MATLAB | >> A = [1 2;3 4]
A =
1 2
3 4
>> B = [5 6;7 8]
B =
5 6
7 8
>> A * B
ans =
19 22
43 50
>> mtimes(A,B)
ans =
19 22
43 50 |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Nim | Nim | proc transpose[X, Y; T](s: array[Y, array[X, T]]): array[X, array[Y, T]] =
for i in low(X)..high(X):
for j in low(Y)..high(Y):
result[i][j] = s[j][i]
let b = [[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[ 1, 0, 0, 0,42]]
let c = transpose(b)
for r in c:
for i in r:
stdout.write i, " "
echo "" |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Objeck | Objeck |
bundle Default {
class Transpose {
function : Main(args : String[]) ~ Nil {
input := [[1, 1, 1, 1]
[2, 4, 8, 16]
[3, 9, 27, 81]
[4, 16, 64, 256]
[5, 25, 125, 625]];
dim := input->Size();
output := Int->New[dim[0],dim[1]];
for(i := 0; i < dim[0]; i+=1;) {
for(j := 0; j < dim[1]; j+=1;) {
output[i,j] := input[i,j];
};
};
Print(output);
}
function : Print(matrix : Int[,]) ~ Nil {
dim := matrix->Size();
for(i := 0; i < dim[0]; i+=1;) {
for(j := 0; j < dim[1]; j+=1;) {
IO.Console->Print(matrix[i,j])->Print('\t');
};
'\n'->Print();
};
}
}
}
|
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #SQL | SQL | SELECT MD5('The quick brown fox jumped over the lazy dog\'s back') |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Julia | Julia | function mandelbrot(a)
z = 0
for i=1:50
z = z^2 + a
end
return z
end
for y=1.0:-0.05:-1.0
for x=-2.0:0.0315:0.5
abs(mandelbrot(complex(x, y))) < 2 ? print("*") : print(" ")
end
println()
end |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Maxima | Maxima | a: matrix([1, 2],
[3, 4],
[5, 6],
[7, 8])$
b: matrix([1, 2, 3],
[4, 5, 6])$
a . b;
/* matrix([ 9, 12, 15],
[19, 26, 33],
[29, 40, 51],
[39, 54, 69]) */ |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #OCaml | OCaml | open Bigarray
let transpose b =
let dim1 = Array2.dim1 b
and dim2 = Array2.dim2 b in
let kind = Array2.kind b
and layout = Array2.layout b in
let b' = Array2.create kind layout dim2 dim1 in
for i=0 to pred dim1 do
for j=0 to pred dim2 do
b'.{j,i} <- b.{i,j}
done;
done;
(b')
;;
let array2_display print newline b =
for i=0 to Array2.dim1 b - 1 do
for j=0 to Array2.dim2 b - 1 do
print b.{i,j}
done;
newline();
done;
;;
let a = Array2.of_array int c_layout [|
[| 1; 2; 3; 4 |];
[| 5; 6; 7; 8 |];
|]
array2_display (Printf.printf " %d") print_newline (transpose a) ;; |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #Suneido | Suneido | Md5('The quick brown fox jumped over the lazy dog\'s back') |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Kotlin | Kotlin | // version 1.1.2
import java.awt.Graphics
import java.awt.image.BufferedImage
import javax.swing.JFrame
class Mandelbrot: JFrame("Mandelbrot Set") {
companion object {
private const val MAX_ITER = 570
private const val ZOOM = 150.0
}
private val img: BufferedImage
init {
setBounds(100, 100, 800, 600)
isResizable = false
defaultCloseOperation = EXIT_ON_CLOSE
img = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
for (y in 0 until height) {
for (x in 0 until width) {
var zx = 0.0
var zy = 0.0
val cX = (x - 400) / ZOOM
val cY = (y - 300) / ZOOM
var iter = MAX_ITER
while (zx * zx + zy * zy < 4.0 && iter > 0) {
val tmp = zx * zx - zy * zy + cX
zy = 2.0 * zx * zy + cY
zx = tmp
iter--
}
img.setRGB(x, y, iter or (iter shl 7))
}
}
}
override fun paint(g: Graphics) {
g.drawImage(img, 0, 0, this)
}
}
fun main(args: Array<String>) {
Mandelbrot().isVisible = true
} |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Nial | Nial | |A := 4 4 reshape 1 1 1 1 2 4 8 16 3 9 27 81 4 16 64 256
=1 1 1 1
=2 4 8 16
=3 9 27 81
=4 16 64 256
|B := inverse A
|A innerproduct B
=1. 0. 8.3e-17 -2.9e-16
=1.3e-15 1. -4.4e-16 -3.3e-16
=0. 0. 1. 4.4e-16
=0. 0. 0. 1. |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Octave | Octave | a = [ 1, 1, 1, 1 ;
2, 4, 8, 16 ;
3, 9, 27, 81 ;
4, 16, 64, 256 ;
5, 25, 125, 625 ];
tranposed = a.'; % tranpose
ctransp = a'; % conjugate transpose |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #Tcl | Tcl | package require md5
puts [md5::md5 -hex "The quick brown fox jumped over the lazy dog's back"]
# ==> E38CA1D920C4B8B8D3946B2C72F01680 |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #LabVIEW | LabVIEW |
: d2c(*,*) 2 compress 'c dress ; # Make a complex number.
: iterate(c) [0 0](c) "dup * over +" steps reshape execute ;
: print_line(*) "#*+-. " "" split swap subscript "" join . "\n" . ;
75 iota 45 - 20 / # x coordinates
29 iota 14 - 10 / # y cordinates
'd2c outer # Make complex matrix.
10 'steps set # How many iterations?
iterate abs int 5 min 'print_line apply # Compute & print
|
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Nim | Nim | import strfmt
type Matrix[M, N: static[int]] = array[M, array[N, float]]
let a = [[1.0, 1.0, 1.0, 1.0],
[2.0, 4.0, 8.0, 16.0],
[3.0, 9.0, 27.0, 81.0],
[4.0, 16.0, 64.0, 256.0]]
let b = [[ 4.0, -3.0 , 4/3.0, -1/4.0],
[-13/3.0, 19/4.0, -7/3.0, 11/24.0],
[ 3/2.0, -2.0 , 7/6.0, -1/4.0],
[ -1/6.0, 1/4.0, -1/6.0, 1/24.0]]
proc `$`(m: Matrix): string =
result = "(["
for r in m:
if result.len > 2: result.add "]\n ["
for val in r: result.add val.format("8.2f")
result.add "])"
proc `*`[M, P, N](a: Matrix[M, P]; b: Matrix[P, N]): Matrix[M, N] =
for i in result.low .. result.high:
for j in result[0].low .. result[0].high:
for k in a[0].low .. a[0].high:
result[i][j] += a[i][k] * b[k][j]
echo a
echo b
echo a * b
echo b * a |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #OxygenBasic | OxygenBasic |
function Transpose(double *A,*B, sys nx,ny)
'==========================================
sys x,y
indexbase 0
for x=0 to <nx
for y=0 to <ny
B[y*nx+x]=A[x*ny+y]
next
next
end function
function MatrixShow(double*A, sys nx,ny) as string
'=================================================
sys x,y
indexbase 0
string pr="",tab=chr(9),cr=chr(13)+chr(10)
for y=0 to <ny
for x=0 to <nx
pr+=tab A[x*ny+y]
next
pr+=cr
next
return pr
end function
'====
'DEMO
'====
double A[5*4],B[4*5]
'columns x
'rows y
A <= 'y minor, x major
11,12,13,14,15,
21,22,23,24,25,
31,32,33,34,35,
41,42,43,44,45
print MatrixShow A,5,4
Transpose A,B,5,4
print MatrixShow B,4,5
|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #PARI.2FGP | PARI/GP | M~ |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #UNIX_Shell | UNIX Shell | echo -n "The quick brown fox jumped over the lazy dog's back" | md5sum |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Lang5 | Lang5 |
: d2c(*,*) 2 compress 'c dress ; # Make a complex number.
: iterate(c) [0 0](c) "dup * over +" steps reshape execute ;
: print_line(*) "#*+-. " "" split swap subscript "" join . "\n" . ;
75 iota 45 - 20 / # x coordinates
29 iota 14 - 10 / # y cordinates
'd2c outer # Make complex matrix.
10 'steps set # How many iterations?
iterate abs int 5 min 'print_line apply # Compute & print
|
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #OCaml | OCaml | let matrix_multiply x y =
let x0 = Array.length x
and y0 = Array.length y in
let y1 = if y0 = 0 then 0 else Array.length y.(0) in
let z = Array.make_matrix x0 y1 0 in
for i = 0 to x0-1 do
for j = 0 to y1-1 do
for k = 0 to y0-1 do
z.(i).(j) <- z.(i).(j) + x.(i).(k) * y.(k).(j)
done
done
done;
z |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Pascal | Pascal | Program Transpose;
const
A: array[1..3,1..5] of integer = (( 1, 2, 3, 4, 5),
( 6, 7, 8, 9, 10),
(11, 12, 13, 14, 15)
);
var
B: array[1..5,1..3] of integer;
i, j: integer;
begin
for i := low(A) to high(A) do
for j := low(A[1]) to high(A[1]) do
B[j,i] := A[i,j];
writeln ('A:');
for i := low(A) to high(A) do
begin
for j := low(A[1]) to high(A[1]) do
write (A[i,j]:3);
writeln;
end;
writeln ('B:');
for i := low(B) to high(B) do
begin
for j := low(B[1]) to high(B[1]) do
write (B[i,j]:3);
writeln;
end;
end. |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Security.Cryptography
Imports System.Text
Module MD5hash
Sub Main(args As String())
Console.WriteLine(GetMD5("Visual Basic .Net"))
End Sub
Private Function GetMD5(plainText As String) As String
Dim hash As String = ""
Using hashObject As MD5 = MD5.Create()
Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText))
Dim hashBuilder As New StringBuilder
For i As Integer = 0 To ptBytes.Length - 1
hashBuilder.Append(ptBytes(i).ToString("X2"))
Next
hash = hashBuilder.ToString
End Using
Return hash
End Function
End Module
|
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Lambdatalk | Lambdatalk |
{def mandel
{def mandel.r
{lambda {:iter :cx :cy :norm :x :y :count}
{if {> :count :iter} // then norm < 4
then o // inside the set
else {if {> :norm 4} // then iter > max
then . // outside the set
else {let { {:cx :cx} {:cy :cy} {:iter :iter}
{:X {+ {* :x :x} -{* :y :y} :cx}} // compute
{:Y {+ {* 2 :x :y} :cy}} // z = z^2+c
{:count {+ :count 1}}
} {mandel.r :iter :cx :cy
{+ {* :X :X} {* :Y :Y}} // the norm
:X :Y :count} }}}}}
{lambda {:iter :cx :cy}
{mandel.r :iter
{+ {* :cx 0.05} -1.50} // centering the set
{+ {* :cy 0.05} -0.75} // inside the frame
0 0 0 0} }}
-> mandel
We call mandel directly in the wiki page
{S.map {lambda {:i} {br} // loop on y
{S.map {{lambda {:i :j} // loop on x
{mandel 20 :i :j}} :i} // compute
{S.serie 0 30}}} // x resolution
{S.serie 0 40}} // y resolution
|
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Octave | Octave | a = zeros(4);
% prepare the matrix
% 1 1 1 1
% 2 4 8 16
% 3 9 27 81
% 4 16 64 256
for i = 1:4
for j = 1:4
a(i, j) = i^j;
endfor
endfor
b = inverse(a);
a * b |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Perl | Perl | use Math::Matrix;
$m = Math::Matrix->new(
[1, 1, 1, 1],
[2, 4, 8, 16],
[3, 9, 27, 81],
[4, 16, 64, 256],
[5, 25, 125, 625],
);
$m->transpose->print; |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #Vlang | Vlang | import crypto.md5
fn main() {
for p in [
// RFC 1321 test cases
["d41d8cd98f00b204e9800998ecf8427e", ""],
["0cc175b9c0f1b6a831c399e269772661", "a"],
["900150983cd24fb0d6963f7d28e17f72", "abc"],
["f96b697d7cb7938d525a2f31aaf161d0", "message digest"],
["c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz"],
["d174ab98d277d9f5a5611c2c9f419d9f",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"],
["57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890"],
// test case popular with other RC solutions
["e38ca1d920c4b8b8d3946b2c72f01680",
"The quick brown fox jumped over the lazy dog's back"],
] {
validate(p[0], p[1])
}
}
fn validate(check string, s string) {
sum := md5.hexhash(s)
if sum != check {
println("MD5 fail")
println(" for string, $s")
println(" expected: $check")
println(" got: $sum")
} else {
println('MD5 succeeded $s')
}
} |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Lasso | Lasso |
define mandelbrotBailout => 16
define mandelbrotMaxIterations => 1000
define mandelbrotIterate(x, y) => {
local(cr = #y - 0.5,
ci = #x,
zi = 0.0,
zr = 0.0,
i = 0,
temp, zr2, zi2)
{
++#i;
#temp = #zr * #zi
#zr2 = #zr * #zr
#zi2 = #zi * #zi
#zi2 + #zr2 > mandelbrotBailout?
return #i
#i > mandelbrotMaxIterations?
return 0
#zr = #zr2 - #zi2 + #cr
#zi = #temp + #temp + #ci
currentCapture->restart
}()
}
define mandelbrotTest() => {
local(x, y = -39.0)
{
stdout('\n')
#x = -39.0
{
mandelbrotIterate(#x / 40.0, #y / 40.0) == 0?
stdout('*')
| stdout(' ');
++#x
#x <= 39.0?
currentCapture->restart
}();
++#y
#y <= 39.0?
currentCapture->restart
}()
stdout('\n')
}
mandelbrotTest
|
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Ol | Ol | ; short version based on 'apply'
(define (matrix-multiply matrix1 matrix2)
(map
(lambda (row)
(apply map
(lambda column
(apply + (map * row column)))
matrix2))
matrix1))
|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Phix | Phix | with javascript_semantics
function matrix_transpose(sequence mat)
integer rows = length(mat),
cols = length(mat[1])
sequence res = repeat(repeat(0,rows),cols)
for r=1 to rows do
for c=1 to cols do
res[c][r] = mat[r][c]
end for
end for
return res
end function
|
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #Wren | Wren | import "/crypto" for Md5
import "/fmt" for Fmt
var strings = [
"The quick brown fox jumps over the lazy dog",
"The quick brown fox jumps over the lazy dog.",
""
]
for (s in strings) {
var digest = Md5.digest(s)
Fmt.print("$s <== '$0s'", digest, s)
} |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #LIL | LIL | #
# A mandelbrot generator that outputs a PBM file. This can be used to measure
# performance differences between LIL versions and measure performance
# bottlenecks (although keep in mind that LIL is not supposed to be a fast
# language, but a small one which depends on C for the slow parts - in a real
# program where for some reason mandelbrots are required, the code below would
# be written in C). The code is based on the mandelbrot test for the Computer
# Language Benchmarks Game at http://shootout.alioth.debian.org/
#
# In my current computer (Intel Core2Quad Q9550 @ 2.83GHz) running x86 Linux
# the results are (using the default 256x256 size):
#
# 2m3.634s - commit 1c41cdf89f4c1e039c9b3520c5229817bc6274d0 (Jan 10 2011)
#
# To test call
#
# time ./lil mandelbrot.lil > mandelbrot.pbm
#
# with an optimized version of lil (compiled with CFLAGS=-O3 make).
#
set width [expr $argv]
if not $width { set width 256 }
set height $width
set bit_num 0
set byte_acc 0
set iter 50
set limit 2.0
write "P4\n${width} ${height}\n"
for {set y 0} {$y < $height} {inc y} {
for {set x 0} {$x < $width} {inc x} {
set Zr 0.0 Zi 0.0 Tr 0.0 Ti 0.0
set Cr [expr 2.0 * $x / $width - 1.5]
set Ci [expr 2.0 * $y / $height - 1.0]
for {set i 0} {$i < $iter && $Tr + $Ti <= $limit * $limit} {inc i} {
set Zi [expr 2.0 * $Zr * $Zi + $Ci]
set Zr [expr $Tr - $Ti + $Cr]
set Tr [expr $Zr * $Zr]
set Ti [expr $Zi * $Zi]
}
set byte_acc [expr $byte_acc << 1]
if [expr $Tr + $Ti <= $limit * $limit] {
set byte_acc [expr $byte_acc | 1]
}
inc bit_num
if [expr $bit_num == 8] {
writechar $byte_acc
set byte_acc 0
set bit_num 0
} {if [expr $x == $width - 1] {
set byte_acc [expr 8 - $width % 8]
writechar $byte_acc
set byte_acc 0
set bit_num 0
}}
}
} |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #OxygenBasic | OxygenBasic |
'generic with striding pointers
'def typ float
typedef float typ
'
function MatMul(typ *r,*a,*b, int n=4) 'NxN MATRIX : N=1..
============================================================
int ystep=sizeof typ
int xstep=n*sizeof typ
int i,j,k
sys px
for i=1 to n
px=@a
for j=1 to n
r=0
for k=1 to n
r+=(a*b)
@a+=xstep
@b+=ystep
next
@r+=ystep
px+=ystep
@a=px
@b-=xstep
next
@a-=xstep
@b+=xstep
next
end function
|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #PHP | PHP |
function transpose($m) {
if (count($m) == 0) // special case: empty matrix
return array();
else if (count($m) == 1) // special case: row matrix
return array_chunk($m[0], 1);
// array_map(NULL, m[0], m[1], ..)
array_unshift($m, NULL); // the original matrix is not modified because it was passed by value
return call_user_func_array('array_map', $m);
} |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #zkl | zkl | Utils.MD5.calc("message digest"); //-->"f96b697d7cb7938d525a2f31aaf161d0"
Utils.MD5.calc("abcdefghijklmnopqrstuvwxyz"); //-->"c3fcd3d76192e4007dfb496cca67e13b" |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Logo | Logo | to mandelbrot :left :bottom :side :size
cs setpensize [1 1]
make "inc :side/:size
make "zr :left
repeat :size [
make "zr :zr + :inc
make "zi :bottom
pu
setxy repcount - :size/2 minus :size/2
pd
repeat :size [
make "zi :zi + :inc
setpencolor count.color calc :zr :zi
fd 1 ] ]
end
to count.color :count
;op (list :count :count :count)
if :count > 256 [op 0] ; black
if :count > 128 [op 7] ; white
if :count > 64 [op 5] ; magenta
if :count > 32 [op 6] ; yellow
if :count > 16 [op 4] ; red
if :count > 8 [op 2] ; green
if :count > 4 [op 1] ; blue
op 3 ; cyan
end
to calc :zr :zi [:count 0] [:az 0] [:bz 0]
if :az*:az + :bz*:bz > 4 [op :count]
if :count > 256 [op :count]
op (calc :zr :zi (:count + 1) (:zr + :az*:az - :bz*:bz) (:zi + 2*:az*:bz))
end
mandelbrot -2 -1.25 2.5 400 |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #PARI.2FGP | PARI/GP | M*N |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Picat | Picat | import util.
go =>
M = [[0.0, 0.1, 0.2, 0.3],
[0.4, 0.5, 0.6, 0.7],
[0.8, 0.9, 1.0, 1.1]],
print_matrix(M),
M2 = [[a,b,c,d,e],
[f,g,h,i,j],
[k,l,m,n,o],
[p,q,r,s,t],
[u,v,w,z,y]],
print_matrix(M2),
M3 = make_matrix(1..24,8),
print_matrix(M3),
nl.
%
% Print original matrix and its transpose
%
print_matrix(M) =>
println("Matrix:"),
foreach(Row in M) println(Row) end,
println("\nTransposed:"),
foreach(Row in M.transpose()) println(Row) end,
nl.
%
% Make a matrix of list L with Rows rows
% (and L.length div Rows columns)
%
make_matrix(L,Rows) = M =>
M = [],
Cols = L.length div Rows,
foreach(I in 1..Rows)
NewRow = new_list(Cols),
foreach(J in 1..Cols)
NewRow[J] := L[ (I-1)*Cols + J]
end,
M := M ++ [NewRow]
end. |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Lua | Lua |
local maxIterations = 250
local minX, maxX, minY, maxY = -2.5, 2.5, -2.5, 2.5
local miX, mxX, miY, mxY
function remap( x, t1, t2, s1, s2 )
local f = ( x - t1 ) / ( t2 - t1 )
local g = f * ( s2 - s1 ) + s1
return g;
end
function drawMandelbrot()
local pts, a, as, za, b, bs, zb, cnt, clr = {}
for j = 0, hei - 1 do
for i = 0, wid - 1 do
a = remap( i, 0, wid, minX, maxX )
b = remap( j, 0, hei, minY, maxY )
cnt = 0; za = a; zb = b
while( cnt < maxIterations ) do
as = a * a - b * b; bs = 2 * a * b
a = za + as; b = zb + bs
if math.abs( a ) + math.abs( b ) > 16 then break end
cnt = cnt + 1
end
if cnt == maxIterations then clr = 0
else clr = remap( cnt, 0, maxIterations, 0, 255 )
end
pts[1] = { i, j, clr, clr, 0, 255 }
love.graphics.points( pts )
end
end
end
function startFractal()
love.graphics.setCanvas( canvas ); love.graphics.clear()
love.graphics.setColor( 255, 255, 255 )
drawMandelbrot(); love.graphics.setCanvas()
end
function love.load()
wid, hei = love.graphics.getWidth(), love.graphics.getHeight()
canvas = love.graphics.newCanvas( wid, hei )
startFractal()
end
function love.mousepressed( x, y, button, istouch )
if button == 1 then
startDrag = true; miX = x; miY = y
else
minX = -2.5; maxX = 2.5; minY = minX; maxY = maxX
startFractal()
startDrag = false
end
end
function love.mousereleased( x, y, button, istouch )
if startDrag then
local l
if x > miX then mxX = x
else l = x; mxX = miX; miX = l
end
if y > miY then mxY = y
else l = y; mxY = miY; miY = l
end
miX = remap( miX, 0, wid, minX, maxX )
mxX = remap( mxX, 0, wid, minX, maxX )
miY = remap( miY, 0, hei, minY, maxY )
mxY = remap( mxY, 0, hei, minY, maxY )
minX = miX; maxX = mxX; minY = miY; maxY = mxY
startFractal()
end
end
function love.draw()
love.graphics.draw( canvas )
end
|
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Perl | Perl | sub mmult
{
our @a; local *a = shift;
our @b; local *b = shift;
my @p = [];
my $rows = @a;
my $cols = @{ $b[0] };
my $n = @b - 1;
for (my $r = 0 ; $r < $rows ; ++$r)
{
for (my $c = 0 ; $c < $cols ; ++$c)
{
$p[$r][$c] += $a[$r][$_] * $b[$_][$c]
foreach 0 .. $n;
}
}
return [@p];
}
sub display { join("\n" => map join(" " => map(sprintf("%4d", $_), @$_)), @{+shift})."\n" }
@a =
(
[1, 2],
[3, 4]
);
@b =
(
[-3, -8, 3],
[-2, 1, 4]
);
$c = mmult(\@a,\@b);
display($c) |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #PicoLisp | PicoLisp | (de matTrans (Mat)
(apply mapcar Mat list) )
(matTrans '((1 2 3) (4 5 6))) |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #M2000_Interpreter | M2000 Interpreter |
Module Mandelbrot(x=0&,y=0&,z=1&) {
If z<1 then z=1
If z>16 then z=16
Const iXmax=32*z
Const iYmax=26*z
Def single Cx, Cy, CxMin=-2.05, CxMax=0.85, CyMin=-1.2, CyMax=1.2
Const PixelWidth=(CxMax-CxMin)/iXmax, iXm=(iXmax-1)*PixelWidth
Const PixelHeight=(CyMax-CyMin)/iYmax,Ph2=PixelHeight/2
Const Iteration=25
Const EscRadious=2.5, ER2=EscRadious**2
Def single preview
preview=iXmax*twipsX*(z/16)
Def long yp, xp, dx, dy, dx1, dy1
Let dx=twipsx*(16/z), dx1=dx-1
Let dy=twipsy*(16/z), dy1=dy-1
yp=y
For iY=0 to (iYmax-1)*PixelHeight step PixelHeight {
Cy=CyMin+iY
xp=x
if abs(Cy)<Ph2 Then Cy=0
For iX=0 to iXm Step PixelWidth {
Let Cx=CxMin+iX,Zx=0,Zy=0,Zx2=Zx**2,Zy2=Zy**2
For It=Iteration to 1 {Let Zy=2*Zx*Zy+Cy,Zx=Zx2-Zy2+Cx,Zx2=Zx**2,Zy2=Zy**2 :if Zx2+Zy2>ER2 Then exit
}
if it>13 then {it-=13} else.if it=0 then SetPixel(xp,yp,0): xp+=dx : continue
it*=10:SetPixel(xp,yp,color(it, it,255)) :xp+=dx
} : yp+=dy
}
Sub SetPixel()
move number, number: fill dx1, dy1, number
End Sub
}
Cls 1,0
sz=(1,2,4,8,16)
i=each(sz)
While i {
Mandelbrot 250*twipsx,100*twipsy, array(i)
}
|
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Phix | Phix | with javascript_semantics
function matrix_mul(sequence a, b)
integer {ha,wa,hb,wb} = apply({a,a[1],b,b[1]},length)
if wa!=hb then crash("invalid aguments") end if
sequence c = repeat(repeat(0,wb),ha)
for i=1 to ha do
for j=1 to wb do
for k=1 to wa do
c[i][j] += a[i][k]*b[k][j]
end for
end for
end for
return c
end function
ppOpt({pp_Nest,1,pp_IntFmt,"%3d",pp_FltFmt,"%3.0f",pp_IntCh,false})
constant A = { { 1, 2 },
{ 3, 4 },
{ 5, 6 },
{ 7, 8 }},
B = { { 1, 2, 3 },
{ 4, 5, 6 }}
pp(matrix_mul(A,B))
constant C = { { 1, 1, 1, 1 },
{ 2, 4, 8, 16 },
{ 3, 9, 27, 81 },
{ 4, 16, 64, 256 }},
D = { { 4, -3, 4/3, -1/ 4 },
{-13/3, 19/4, -7/3, 11/24 },
{ 3/2, -2, 7/6, -1/ 4 },
{ -1/6, 1/4, -1/6, 1/24 }}
pp(matrix_mul(C,D))
constant F = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}},
G = {{1, 0, 0},
{0, 1, 0},
{0, 0, 1}}
pp(matrix_mul(F,G))
constant H = {{1,2},
{3,4}},
I = {{5,6},
{7,8}}
pp(matrix_mul(H,I))
constant r = sqrt(2)/2,
R = {{ r,r},
{-r,r}}
pp(matrix_mul(R,R))
-- large matrix example from OI:
function row(integer i, l) return tagset(i+l,i) end function
constant J = apply(true,row,{tagset(16,0),371}),
K = apply(true,row,{tagset(371,0),16})
pp(shorten(apply(true,shorten,{matrix_mul(J,K),{""},2}),"",2))
|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #PL.2FI | PL/I | /* The short method: */
declare A(m, n) float, B (n,m) float defined (A(2sub, 1sub));
/* Any reference to B gives the transpose of matrix A. */ |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Maple | Maple | ImageTools:-Embed(Fractals[EscapeTime]:-Mandelbrot(500, -2.0-1.35*I, .7+1.35*I, output = layer1)); |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #PicoLisp | PicoLisp | (de matMul (Mat1 Mat2)
(mapcar
'((Row)
(apply mapcar Mat2
'(@ (sum * Row (rest))) ) )
Mat1 ) )
(matMul
'((1 2 3) (4 5 6))
'((6 -1) (3 2) (0 -3)) ) |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Pop11 | Pop11 | define transpose(m) -> res;
lvars bl = boundslist(m);
if length(bl) /= 4 then
throw([need_2d_array ^a])
endif;
lvars i, i0 = bl(1), i1 = bl(2);
lvars j, j0 = bl(3), j1 = bl(4);
newarray([^j0 ^j1 ^i0 ^i1], 0) -> res;
for i from i0 to i1 do
for j from j0 to j1 do
m(i, j) -> res(j, i);
endfor;
endfor;
enddefine; |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | eTime[c_, maxIter_Integer: 100] := Length@NestWhileList[#^2 + c &, 0, Abs@# <= 2 &, 1, maxIter] - 1
DistributeDefinitions[eTime];
mesh = ParallelTable[eTime[x + I*y, 1000], {y, 1.2, -1.2, -0.01}, {x, -1.72, 1, 0.01}];
ReliefPlot[mesh, Frame -> False] |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #PL.2FI | PL/I |
/* Matrix multiplication of A by B, yielding C */
MMULT: procedure (a, b, c);
declare (a, b, c)(*,*) float controlled;
declare (i, j, m, n, p) fixed binary;
if hbound(a,2) ^= hbound(b,1) then
do;
put skip list
('Matrices are incompatible for matrix multiplication');
signal error;
end;
m = hbound(a, 1); p = hbound(b, 2);
if allocation(c) > 0 then free c;
allocate c(m,p);
do i = 1 to m;
do j = 1 to p;
c(i,j) = sum(a(i,*) * b(*,j) );
end;
end;
end MMULT;
|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #PostScript | PostScript | /transpose {
[ exch {
{ {empty? exch pop} map all?} {pop exit} ift
[ exch {} {uncons {exch cons} dip exch} fold counttomark 1 roll] uncons
} loop ] {reverse} map
}. |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Mathmap | Mathmap | filter mandelbrot (gradient coloration)
c=ri:(xy/xy:[X,X]*1.5-xy:[0.5,0]);
z=ri:[0,0]; # initial value z0 = 0
# iteration of z
iter=0;
while abs(z)<2 && iter<31
do
z=z*z+c; # z(n+1) = fc(zn)
iter=iter+1
end;
coloration(iter/32) # color of pixel
end
|
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Pop11 | Pop11 | define matmul(a, b) -> c;
lvars ba = boundslist(a), bb = boundslist(b);
lvars i, i0 = ba(1), i1 = ba(2);
lvars j, j0 = bb(1), j1 = bb(2);
lvars k, k0 = bb(3), k1 = bb(4);
if length(ba) /= 4 then
throw([need_2d_array ^a])
endif;
if length(bb) /= 4 then
throw([need_2d_array ^b])
endif;
if ba(3) /= j0 or ba(4) /= j1 then
throw([dimensions_do_not_match ^a ^b]);
endif;
newarray([^i0 ^i1 ^k0 ^k1], 0) -> c;
for i from i0 to i1 do
for k from k0 to k1 do
for j from j0 to j1 do
c(i, k) + a(i, j)*b(j, k) -> c(i, k);
endfor;
endfor;
endfor;
enddefine; |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #PowerBASIC | PowerBASIC | #COMPILE EXE
#DIM ALL
#COMPILER PBCC 6
'----------------------------------------------------------------------
SUB TransposeMatrix(InitMatrix() AS DWORD, TransposedMatrix() AS DWORD)
LOCAL l1, l2, u1, u2 AS LONG
l1 = LBOUND(InitMatrix, 1)
l2 = LBOUND(InitMatrix, 2)
u1 = UBOUND(InitMatrix, 1)
u2 = UBOUND(InitMatrix, 2)
REDIM TransposedMatrix(l2 TO u2, l1 TO u1)
MAT TransposedMatrix() = TRN(InitMatrix())
END SUB
'----------------------------------------------------------------------
SUB PrintMatrix(a() AS DWORD)
LOCAL l1, l2, u1, u2, r, c AS LONG
LOCAL s AS STRING * 8
l1 = LBOUND(a(), 1)
l2 = LBOUND(a(), 2)
u1 = UBOUND(a(), 1)
u2 = UBOUND(a(), 2)
FOR r = l1 TO u1
FOR c = l2 TO u2
RSET s = STR$(a(r, c))
CON.PRINT s;
NEXT c
CON.PRINT
NEXT r
END SUB
'----------------------------------------------------------------------
SUB TranspositionDemo(BYVAL DimSize1 AS DWORD, BYVAL DimSize2 AS DWORD)
LOCAL r, c, cc AS DWORD
LOCAL a() AS DWORD
LOCAL b() AS DWORD
cc = DimSize2
DECR DimSize1
DECR DimSize2
REDIM a(0 TO DimSize1, 0 TO DimSize2)
FOR r = 0 TO DimSize1
FOR c = 0 TO DimSize2
a(r, c)= (cc * r) + c + 1
NEXT c
NEXT r
CON.PRINT "initial matrix:"
PrintMatrix a()
TransposeMatrix a(), b()
CON.PRINT "transposed matrix:"
PrintMatrix b()
END SUB
'----------------------------------------------------------------------
FUNCTION PBMAIN () AS LONG
TranspositionDemo 3, 3
TranspositionDemo 3, 7
END FUNCTION |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #MATLAB | MATLAB | function [theSet,realAxis,imaginaryAxis] = mandelbrotSet(start,gridSpacing,last,maxIteration)
%Define the escape time algorithm
function escapeTime = escapeTimeAlgorithm(z0)
escapeTime = 0;
z = 0;
while( (abs(z)<=2) && (escapeTime < maxIteration) )
z = (z + z0)^2;
escapeTime = escapeTime + 1;
end
end
%Define the imaginary axis
imaginaryAxis = (imag(start):imag(gridSpacing):imag(last));
%Define the real axis
realAxis = (real(start):real(gridSpacing):real(last));
%Construct the complex plane from the real and imaginary axes
complexPlane = meshgrid(realAxis,imaginaryAxis) + meshgrid(imaginaryAxis(end:-1:1),realAxis)'.*i;
%Apply the escape time algorithm to each point in the complex plane
theSet = arrayfun(@escapeTimeAlgorithm, complexPlane);
%Draw the set
pcolor(realAxis,imaginaryAxis,theSet);
shading flat;
end |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #PowerShell | PowerShell |
function multarrays($a, $b) {
$n,$m,$p = ($a.Count - 1), ($b.Count - 1), ($b[0].Count - 1)
if ($a[0].Count -ne $b.Count) {throw "Multiplication impossible"}
$c = @(0)*($a[0].Count)
foreach ($i in 0..$n) {
$c[$i] = foreach ($j in 0..$p) {
$sum = 0
foreach ($k in 0..$m){$sum += $a[$i][$k]*$b[$k][$j]}
$sum
}
}
$c
}
function show($a) { $a | foreach{"$_"}}
$a = @(@(1,2),@(3,4))
$b = @(@(5,6),@(7,8))
$c = @(5,6)
"`$a ="
show $a
""
"`$b ="
show $b
""
"`$c ="
$c
""
"`$a * `$b ="
show (multarrays $a $b)
" "
"`$a * `$c ="
show (multarrays $a $c)
|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #PowerShell | PowerShell |
function transpose($a) {
$arr = @()
if($a) {
$n = $a.count - 1
if(0 -lt $n) {
$m = ($a | foreach {$_.count} | measure-object -Minimum).Minimum - 1
if( 0 -le $m) {
if (0 -lt $m) {
$arr =@(0)*($m+1)
foreach($i in 0..$m) {
$arr[$i] = foreach($j in 0..$n) {@($a[$j][$i])}
}
} else {$arr = foreach($row in $a) {$row[0]}}
}
} else {$arr = $a}
}
$arr
}
function show($a) {
if($a) {
0..($a.Count - 1) | foreach{ if($a[$_]){"$($a[$_])"}else{""} }
}
}
$a = @(@(2, 0, 7, 8),@(3, 5, 9, 1),@(4, 1, 6, 3))
"`$a ="
show $a
""
"transpose `$a ="
show (transpose $a)
""
$a = @(1)
"`$a ="
show $a
""
"transpose `$a ="
show (transpose $a)
""
"`$a ="
$a = @(1,2,3)
show $a
""
"transpose `$a ="
"$(transpose $a)"
""
"`$a ="
$a = @(@(4,7,8),@(1),@(2,3))
show $a
""
"transpose `$a ="
"$(transpose $a)"
""
"`$a ="
$a = @(@(4,7,8),@(1,5,9,0),@(2,3))
show $a
""
"transpose `$a ="
show (transpose $a)
|
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Metapost | Metapost | prologues:=3;
outputtemplate:="%j-%c.svg";
outputformat:="svg";
def mandelbrot(expr maxX, maxY) =
max_iteration := 500;
color col[];
for i := 0 upto max_iteration:
t := i / max_iteration;
col[i] = (t,t,t);
endfor;
for px := 0 upto maxX:
for py := 0 upto maxY:
xz := px * 3.5 / maxX - 2.5; % (-2.5,1)
yz := py * 2 / maxY - 1; % (-1,1)
x := 0;
y := 0;
iteration := 0;
forever: exitunless ((x*x + y*y < 4) and (iteration < max_iteration));
xtemp := x*x - y*y + xz;
y := 2*x*y + yz;
x := xtemp;
iteration := iteration + 1;
endfor;
draw (px,py) withpen pencircle withcolor col[iteration];
endfor;
endfor;
enddef;
beginfig(1);
mandelbrot(200, 150);
endfig;
end |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Prolog | Prolog | % SWI-Prolog has transpose/2 in its clpfd library
:- use_module(library(clpfd)).
% N is the dot product of lists V1 and V2.
dot(V1, V2, N) :- maplist(product,V1,V2,P), sumlist(P,N).
product(N1,N2,N3) :- N3 is N1*N2.
% Matrix multiplication with matrices represented
% as lists of lists. M3 is the product of M1 and M2
mmult(M1, M2, M3) :- transpose(M2,MT), maplist(mm_helper(MT), M1, M3).
mm_helper(M2, I1, M3) :- maplist(dot(I1), M2, M3). |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Prolog | Prolog | % transposition of a rectangular matrix
% e.g. [[1,2,3,4], [5,6,7,8]]
% give [[1,5],[2,6],[3,7],[4,8]]
transpose(In, Out) :-
In = [H | T],
maplist(initdl, H, L),
work(T, In, Out).
% we use the difference list to make "quick" appends (one inference)
initdl(V, [V | X] - X).
work(Lst, [H], Out) :-
maplist(my_append_last, Lst, H, Out).
work(Lst, [H | T], Out) :-
maplist(my_append, Lst, H, Lst1),
work(Lst1, T, Out).
my_append(X-Y, C, X1-Y1) :-
append_dl(X-Y, [C | U]- U, X1-Y1).
my_append_last(X-Y, C, X1) :-
append_dl(X-Y, [C | U]- U, X1-[]).
% "quick" append
append_dl(X-Y, Y-Z, X-Z). |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #MiniScript | MiniScript | ZOOM = 100
MAX_ITER = 40
gfx.clear color.black
for y in range(0,200)
for x in range(0,300)
zx = 0
zy = 0
cx = (x - 200) / ZOOM
cy = (y - 100) / ZOOM
for iter in range(MAX_ITER)
if zx*zx + zy*zy > 4 then break
tmp = zx * zx - zy * zy + cx
zy = 2 * zx * zy + cy
zx = tmp
end for
if iter then
gfx.setPixel x, y, rgb(255-iter*6, 0, iter*6)
end if
end for
end for |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #PureBasic | PureBasic | Procedure multiplyMatrix(Array a(2), Array b(2), Array prd(2))
Protected ar = ArraySize(a()) ;#rows for matrix a
Protected ac = ArraySize(a(), 2) ;#cols for matrix a
Protected br = ArraySize(b()) ;#rows for matrix b
Protected bc = ArraySize(b(), 2) ;#cols for matrix b
If ac = br
Dim prd(ar, bc)
Protected i, j, k
For i = 0 To ar
For j = 0 To bc
For k = 0 To br ;ac
prd(i, j) = prd(i, j) + (a(i, k) * b(k, j))
Next
Next
Next
ProcedureReturn #True ;multiplication performed, product in prd()
Else
ProcedureReturn #False ;multiplication not performed, dimensions invalid
EndIf
EndProcedure |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #PureBasic | PureBasic | Procedure transposeMatrix(Array a(2), Array trans(2))
Protected rows, cols
Protected ar = ArraySize(a(), 1) ;rows in original matrix
Protected ac = ArraySize(a(), 2) ;cols in original matrix
;size the matrix receiving the transposition
Dim trans(ac, ar)
;copy the values
For rows = 0 To ar
For cols = 0 To ac
trans(cols, rows) = a(rows, cols)
Next
Next
EndProcedure
Procedure displayMatrix(Array a(2), text.s = "")
Protected i, j
Protected cols = ArraySize(a(), 2), rows = ArraySize(a(), 1)
PrintN(text + ": (" + Str(rows + 1) + ", " + Str(cols + 1) + ")")
For i = 0 To rows
For j = 0 To cols
Print(LSet(Str(a(i, j)), 4, " "))
Next
PrintN("")
Next
PrintN("")
EndProcedure
;setup a matrix of arbitrary size
Dim m(random(5), random(5))
Define rows, cols
;fill matrix with 'random' data
For rows = 0 To ArraySize(m(),1) ;ArraySize() can take a dimension as its second argument
For cols = 0 To ArraySize(m(), 2)
m(rows, cols) = random(10) - 10
Next
Next
Dim t(0,0) ;this will be resized during transposition
If OpenConsole()
displayMatrix(m(), "matrix before transposition")
transposeMatrix(m(), t())
displayMatrix(t(), "matrix after transposition")
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Modula-3 | Modula-3 | MODULE Mandelbrot EXPORTS Main;
IMPORT Wr, Stdio, Fmt, Word;
CONST m = 50;
limit2 = 4.0;
TYPE UByte = BITS 8 FOR [0..16_FF];
VAR width := 200;
height := 200;
bitnum: CARDINAL := 0;
byteacc: UByte := 0;
isOverLimit: BOOLEAN;
Zr, Zi, Cr, Ci, Tr, Ti: REAL;
BEGIN
Wr.PutText(Stdio.stdout, "P4\n" & Fmt.Int(width) & " " & Fmt.Int(height) & "\n");
FOR y := 0 TO height - 1 DO
FOR x := 0 TO width - 1 DO
Zr := 0.0; Zi := 0.0;
Cr := 2.0 * FLOAT(x) / FLOAT(width) - 1.5;
Ci := 2.0 * FLOAT(y) / FLOAT(height) - 1.0;
FOR i := 1 TO m + 1 DO
Tr := Zr*Zr - Zi*Zi + Cr;
Ti := 2.0*Zr*Zi + Ci;
Zr := Tr; Zi := Ti;
isOverLimit := Zr*Zr + Zi*Zi > limit2;
IF isOverLimit THEN EXIT; END;
END;
IF isOverLimit THEN
byteacc := Word.Xor(Word.LeftShift(byteacc, 1), 16_00);
ELSE
byteacc := Word.Xor(Word.LeftShift(byteacc, 1), 16_01);
END;
INC(bitnum);
IF bitnum = 8 THEN
Wr.PutChar(Stdio.stdout, VAL(byteacc, CHAR));
byteacc := 0;
bitnum := 0;
ELSIF x = width - 1 THEN
byteacc := Word.LeftShift(byteacc, 8 - (width MOD 8));
Wr.PutChar(Stdio.stdout, VAL(byteacc, CHAR));
byteacc := 0;
bitnum := 0
END;
Wr.Flush(Stdio.stdout);
END;
END;
END Mandelbrot. |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Python | Python | a=((1, 1, 1, 1), # matrix A #
(2, 4, 8, 16),
(3, 9, 27, 81),
(4, 16, 64, 256))
b=(( 4 , -3 , 4/3., -1/4. ), # matrix B #
(-13/3., 19/4., -7/3., 11/24.),
( 3/2., -2. , 7/6., -1/4. ),
( -1/6., 1/4., -1/6., 1/24.))
def MatrixMul( mtx_a, mtx_b):
tpos_b = zip( *mtx_b)
rtn = [[ sum( ea*eb for ea,eb in zip(a,b)) for b in tpos_b] for a in mtx_a]
return rtn
v = MatrixMul( a, b )
print 'v = ('
for r in v:
print '[',
for val in r:
print '%8.2f '%val,
print ']'
print ')'
u = MatrixMul(b,a)
print 'u = '
for r in u:
print '[',
for val in r:
print '%8.2f '%val,
print ']'
print ')' |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Python | Python | m=((1, 1, 1, 1),
(2, 4, 8, 16),
(3, 9, 27, 81),
(4, 16, 64, 256),
(5, 25,125, 625))
print(zip(*m))
# in Python 3.x, you would do:
# print(list(zip(*m))) |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #MySQL | MySQL |
-- Table to contain all the data points
CREATE TABLE points (
c_re DOUBLE,
c_im DOUBLE,
z_re DOUBLE DEFAULT 0,
z_im DOUBLE DEFAULT 0,
znew_re DOUBLE DEFAULT 0,
znew_im DOUBLE DEFAULT 0,
steps INT DEFAULT 0,
active CHAR DEFAULT 1
);
DELIMITER |
-- Iterate over all the points in the table 'points'
CREATE PROCEDURE itrt (IN n INT)
BEGIN
label: LOOP
UPDATE points
SET
znew_re=POWER(z_re,2)-POWER(z_im,2)+c_re,
znew_im=2*z_re*z_im+c_im,
steps=steps+1
WHERE active=1;
UPDATE points SET
z_re=znew_re,
z_im=znew_im,
active=IF(POWER(z_re,2)+POWER(z_im,2)>4,0,1)
WHERE active=1;
SET n = n - 1;
IF n > 0 THEN
ITERATE label;
END IF;
LEAVE label;
END LOOP label;
END|
-- Populate the table 'points'
CREATE PROCEDURE populate (
r_min DOUBLE,
r_max DOUBLE,
r_step DOUBLE,
i_min DOUBLE,
i_max DOUBLE,
i_step DOUBLE)
BEGIN
DELETE FROM points;
SET @rl = r_min;
SET @a = 0;
rloop: LOOP
SET @im = i_min;
SET @b = 0;
iloop: LOOP
INSERT INTO points (c_re, c_im)
VALUES (@rl, @im);
SET @b=@b+1;
SET @im=i_min + @b * i_step;
IF @im < i_max THEN
ITERATE iloop;
END IF;
LEAVE iloop;
END LOOP iloop;
SET @a=@a+1;
SET @rl=r_min + @a * r_step;
IF @rl < r_max THEN
ITERATE rloop;
END IF;
LEAVE rloop;
END LOOP rloop;
END|
DELIMITER ;
-- Choose size and resolution of graph
-- R_min, R_max, R_step, I_min, I_max, I_step
CALL populate( -2.5, 1.5, 0.005, -2, 2, 0.005 );
-- Calculate 50 iterations
CALL itrt( 50 );
-- Create the image (/tmp/image.ppm)
-- Note, MySQL will not over-write an existing file and you may need
-- administrator access to delete or move it
SELECT @xmax:=COUNT(c_re) INTO @xmax FROM points GROUP BY c_im LIMIT 1;
SELECT @ymax:=COUNT(c_im) INTO @ymax FROM points GROUP BY c_re LIMIT 1;
SET group_concat_max_len=11*@xmax*@ymax;
SELECT
'P3', @xmax, @ymax, 200,
GROUP_CONCAT(
CONCAT(
IF( active=1, 0, 55+MOD(steps, 200) ), ' ',
IF( active=1, 0, 55+MOD(POWER(steps,3), 200) ), ' ',
IF( active=1, 0, 55+MOD(POWER(steps,2), 200) ) )
ORDER BY c_im ASC, c_re ASC SEPARATOR ' ' )
INTO OUTFILE '/tmp/image.ppm'
FROM points;
|
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #R | R | a %*% b |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Quackery | Quackery | [ ' [ [ ] ]
over 0 peek size of
[] rot
witheach join
witheach
[ dip behead
nested join
nested join ] ] is transpose ( [ --> [ )
' [ [ 1 2 ] [ 3 4 ] [ 5 6 ] ]
dup echo cr cr
transpose dup echo cr cr
transpose echo cr |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #R | R | b <- 1:5
m <- matrix(c(b, b^2, b^3, b^4), 5, 4)
print(m)
tm <- t(m)
print(tm) |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Nim | Nim | import complex
proc inMandelbrotSet(c: Complex, maxEscapeIterations = 50): bool =
result = true; var z: Complex
for i in 0..maxEscapeIterations:
z = z * z + c
if abs2(z) > 4: return false
iterator steps(start, step: float, numPixels: int): float =
for i in 0..numPixels:
yield start + i.float * step
proc mandelbrotImage(yStart, yStep, xStart, xStep: float, height, width: int): string =
for y in steps(yStart, yStep, height):
for x in steps(xStart, xStep, width):
result.add(if complex(x, y).inMandelbrotSet: '*'
else: ' ')
result.add('\n')
echo mandelbrotImage(1.0, -0.05, -2.0, 0.0315, 40, 80) |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Racket | Racket |
#lang racket
(define (m-mult m1 m2)
(for/list ([r m1])
(for/list ([c (apply map list m2)])
(apply + (map * r c)))))
(m-mult '((1 2) (3 4)) '((5 6) (7 8)))
;; -> '((19 22) (43 50))
|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Racket | Racket |
#lang racket
(require math)
(matrix-transpose (matrix [[1 2] [3 4]]))
|
http://rosettacode.org/wiki/MAC_Vendor_Lookup | MAC Vendor Lookup | Every connected device around the world comes with a unique Media Access Control address, or a MAC address.
A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.
Task
Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.
A MAC address that does not return a valid result should return the String "N/A". An error related to the network connectivity or the API should return a null result.
Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.
{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
| #Ada | Ada | with Ada.Text_IO;
with AWS.Client;
with AWS.Response;
with AWS.Messages;
procedure MAC_Vendor is
procedure Lookup (MAC : in String) is
use AWS.Response;
use AWS.Messages;
URL : constant String := "http://api.macvendors.com/" & MAC;
Page : constant Data := AWS.Client.Get (URL);
use Ada.Text_IO;
begin
Put (MAC);
Set_Col (20);
case AWS.Response.Status_Code (Page) is
when S200 => Put_Line (Message_Body (Page));
when S404 => Put_Line ("N/A");
when others => Put_Line ("Error");
end case;
end Lookup;
begin
-- Have to throttle traffic to site
Lookup ("88:53:2E:67:07:BE"); delay 1.500;
Lookup ("D4:F4:6F:C9:EF:8D"); delay 1.500;
Lookup ("FC:FB:FB:01:FA:21"); delay 1.500;
Lookup ("4c:72:b9:56:fe:bc"); delay 1.500;
Lookup ("00-14-22-01-23-45"); delay 1.500;
Lookup ("23-45-67"); delay 1.500;
Lookup ("foobar");
end MAC_Vendor; |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #OCaml | OCaml | #load "graphics.cma";;
let mandelbrot xMin xMax yMin yMax xPixels yPixels maxIter =
let rec mandelbrotIterator z c n =
if (Complex.norm z) > 2.0 then false else
match n with
| 0 -> true
| n -> let z' = Complex.add (Complex.mul z z) c in
mandelbrotIterator z' c (n-1) in
Graphics.open_graph
(" "^(string_of_int xPixels)^"x"^(string_of_int yPixels));
let dx = (xMax -. xMin) /. (float_of_int xPixels)
and dy = (yMax -. yMin) /. (float_of_int yPixels) in
for xi = 0 to xPixels - 1 do
for yi = 0 to yPixels - 1 do
let c = {Complex.re = xMin +. (dx *. float_of_int xi);
Complex.im = yMin +. (dy *. float_of_int yi)} in
if (mandelbrotIterator Complex.zero c maxIter) then
(Graphics.set_color Graphics.white;
Graphics.plot xi yi )
else
(Graphics.set_color Graphics.black;
Graphics.plot xi yi )
done
done;;
mandelbrot (-1.5) 0.5 (-1.0) 1.0 500 500 200;; |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Raku | Raku | sub mmult(@a,@b) {
my @p;
for ^@a X ^@b[0] -> ($r, $c) {
@p[$r][$c] += @a[$r][$_] * @b[$_][$c] for ^@b;
}
@p;
}
my @a = [1, 1, 1, 1],
[2, 4, 8, 16],
[3, 9, 27, 81],
[4, 16, 64, 256];
my @b = [ 4 , -3 , 4/3, -1/4 ],
[-13/3, 19/4, -7/3, 11/24],
[ 3/2, -2 , 7/6, -1/4 ],
[ -1/6, 1/4, -1/6, 1/24];
.say for mmult(@a,@b); |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Raku | Raku | # Transposition can be done with the reduced zip meta-operator
# on list-of-lists data structures
say [Z] (<A B C D>, <E F G H>, <I J K L>);
# For native shaped arrays, a more traditional procedure of copying item-by-item
# Here the resulting matrix is also a native shaped array
my @a[3;4] =
[
[<A B C D>],
[<E F G H>],
[<I J K L>],
];
(my $n, my $m) = @a.shape;
my @b[$m;$n];
for ^$m X ^$n -> (\i, \j) {
@b[i;j] = @a[j;i];
}
say @b; |
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.