Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write a version of this Lua function in C# with identical behavior.
Matrix = {} function Matrix.new( dim_y, dim_x ) assert( dim_y and dim_x ) local matrix = {} local metatab = {} setmetatable( matrix, metatab ) metatab.__add = Matrix.Add metatab.__mul = Matrix.Mul metatab.__pow = Matrix.Pow matrix.dim_y = dim_y matrix.dim_x = dim_x matrix.data = {} for i = 1, dim_y do matrix.data[i] = {} end return matrix end function Matrix.Show( m ) for i = 1, m.dim_y do for j = 1, m.dim_x do io.write( tostring( m.data[i][j] ), " " ) end io.write( "\n" ) end end function Matrix.Add( m, n ) assert( m.dim_x == n.dim_x and m.dim_y == n.dim_y ) local r = Matrix.new( m.dim_y, m.dim_x ) for i = 1, m.dim_y do for j = 1, m.dim_x do r.data[i][j] = m.data[i][j] + n.data[i][j] end end return r end function Matrix.Mul( m, n ) assert( m.dim_x == n.dim_y ) local r = Matrix.new( m.dim_y, n.dim_x ) for i = 1, m.dim_y do for j = 1, n.dim_x do r.data[i][j] = 0 for k = 1, m.dim_x do r.data[i][j] = r.data[i][j] + m.data[i][k] * n.data[k][j] end end end return r end function Matrix.Pow( m, p ) assert( m.dim_x == m.dim_y ) local r = Matrix.new( m.dim_y, m.dim_x ) if p == 0 then for i = 1, m.dim_y do for j = 1, m.dim_x do if i == j then r.data[i][j] = 1 else r.data[i][j] = 0 end end end elseif p == 1 then for i = 1, m.dim_y do for j = 1, m.dim_x do r.data[i][j] = m.data[i][j] end end else r = m for i = 2, p do r = r * m end end return r end m = Matrix.new( 2, 2 ) m.data = { { 1, 2 }, { 3, 4 } } n = m^4; Matrix.Show( n )
using System; using System.Collections; using System.Collections.Generic; using static System.Linq.Enumerable; public static class MatrixExponentation { public static double[,] Identity(int size) { double[,] matrix = new double[size, size]; for (int i = 0; i < size; i++) matrix[i, i] = 1; return matrix; } public static double[,] Multiply(this double[,] left, double[,] right) { if (left.ColumnCount() != right.RowCount()) throw new ArgumentException(); double[,] m = new double[left.RowCount(), right.ColumnCount()]; foreach (var (row, column) in from r in Range(0, m.RowCount()) from c in Range(0, m.ColumnCount()) select (r, c)) { m[row, column] = Range(0, m.RowCount()).Sum(i => left[row, i] * right[i, column]); } return m; } public static double[,] Pow(this double[,] matrix, int exp) { if (matrix.RowCount() != matrix.ColumnCount()) throw new ArgumentException("Matrix must be square."); double[,] accumulator = Identity(matrix.RowCount()); for (int i = 0; i < exp; i++) { accumulator = accumulator.Multiply(matrix); } return accumulator; } private static int RowCount(this double[,] matrix) => matrix.GetLength(0); private static int ColumnCount(this double[,] matrix) => matrix.GetLength(1); private static void Print(this double[,] m) { foreach (var row in Rows()) { Console.WriteLine("[ " + string.Join(" ", row) + " ]"); } Console.WriteLine(); IEnumerable<IEnumerable<double>> Rows() => Range(0, m.RowCount()).Select(row => Range(0, m.ColumnCount()).Select(column => m[row, column])); } public static void Main() { var matrix = new double[,] { { 3, 2 }, { 2, 1 } }; matrix.Pow(0).Print(); matrix.Pow(1).Print(); matrix.Pow(2).Print(); matrix.Pow(3).Print(); matrix.Pow(4).Print(); matrix.Pow(50).Print(); } }
Convert this Lua block to C++, preserving its control flow and logic.
Matrix = {} function Matrix.new( dim_y, dim_x ) assert( dim_y and dim_x ) local matrix = {} local metatab = {} setmetatable( matrix, metatab ) metatab.__add = Matrix.Add metatab.__mul = Matrix.Mul metatab.__pow = Matrix.Pow matrix.dim_y = dim_y matrix.dim_x = dim_x matrix.data = {} for i = 1, dim_y do matrix.data[i] = {} end return matrix end function Matrix.Show( m ) for i = 1, m.dim_y do for j = 1, m.dim_x do io.write( tostring( m.data[i][j] ), " " ) end io.write( "\n" ) end end function Matrix.Add( m, n ) assert( m.dim_x == n.dim_x and m.dim_y == n.dim_y ) local r = Matrix.new( m.dim_y, m.dim_x ) for i = 1, m.dim_y do for j = 1, m.dim_x do r.data[i][j] = m.data[i][j] + n.data[i][j] end end return r end function Matrix.Mul( m, n ) assert( m.dim_x == n.dim_y ) local r = Matrix.new( m.dim_y, n.dim_x ) for i = 1, m.dim_y do for j = 1, n.dim_x do r.data[i][j] = 0 for k = 1, m.dim_x do r.data[i][j] = r.data[i][j] + m.data[i][k] * n.data[k][j] end end end return r end function Matrix.Pow( m, p ) assert( m.dim_x == m.dim_y ) local r = Matrix.new( m.dim_y, m.dim_x ) if p == 0 then for i = 1, m.dim_y do for j = 1, m.dim_x do if i == j then r.data[i][j] = 1 else r.data[i][j] = 0 end end end elseif p == 1 then for i = 1, m.dim_y do for j = 1, m.dim_x do r.data[i][j] = m.data[i][j] end end else r = m for i = 2, p do r = r * m end end return r end m = Matrix.new( 2, 2 ) m.data = { { 1, 2 }, { 3, 4 } } n = m^4; Matrix.Show( n )
#include <complex> #include <cmath> #include <iostream> using namespace std; template<int MSize = 3, class T = complex<double> > class SqMx { typedef T Ax[MSize][MSize]; typedef SqMx<MSize, T> Mx; private: Ax a; SqMx() { } public: SqMx(const Ax &_a) { for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) a[r][c] = _a[r][c]; } static Mx identity() { Mx m; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) m.a[r][c] = (r == c ? 1 : 0); return m; } friend ostream &operator<<(ostream& os, const Mx &p) { for (int i = 0; i < MSize; i++) { for (int j = 0; j < MSize; j++) os << p.a[i][j] << ','; os << endl; } return os; } Mx operator*(const Mx &b) { Mx d; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) { d.a[r][c] = 0; for (int k = 0; k < MSize; k++) d.a[r][c] += a[r][k] * b.a[k][c]; } return d; }
Translate the given Lua code snippet into Python without altering its behavior.
Matrix = {} function Matrix.new( dim_y, dim_x ) assert( dim_y and dim_x ) local matrix = {} local metatab = {} setmetatable( matrix, metatab ) metatab.__add = Matrix.Add metatab.__mul = Matrix.Mul metatab.__pow = Matrix.Pow matrix.dim_y = dim_y matrix.dim_x = dim_x matrix.data = {} for i = 1, dim_y do matrix.data[i] = {} end return matrix end function Matrix.Show( m ) for i = 1, m.dim_y do for j = 1, m.dim_x do io.write( tostring( m.data[i][j] ), " " ) end io.write( "\n" ) end end function Matrix.Add( m, n ) assert( m.dim_x == n.dim_x and m.dim_y == n.dim_y ) local r = Matrix.new( m.dim_y, m.dim_x ) for i = 1, m.dim_y do for j = 1, m.dim_x do r.data[i][j] = m.data[i][j] + n.data[i][j] end end return r end function Matrix.Mul( m, n ) assert( m.dim_x == n.dim_y ) local r = Matrix.new( m.dim_y, n.dim_x ) for i = 1, m.dim_y do for j = 1, n.dim_x do r.data[i][j] = 0 for k = 1, m.dim_x do r.data[i][j] = r.data[i][j] + m.data[i][k] * n.data[k][j] end end end return r end function Matrix.Pow( m, p ) assert( m.dim_x == m.dim_y ) local r = Matrix.new( m.dim_y, m.dim_x ) if p == 0 then for i = 1, m.dim_y do for j = 1, m.dim_x do if i == j then r.data[i][j] = 1 else r.data[i][j] = 0 end end end elseif p == 1 then for i = 1, m.dim_y do for j = 1, m.dim_x do r.data[i][j] = m.data[i][j] end end else r = m for i = 2, p do r = r * m end end return r end m = Matrix.new( 2, 2 ) m.data = { { 1, 2 }, { 3, 4 } } n = m^4; Matrix.Show( n )
>>> from operator import mul >>> def matrixMul(m1, m2): return map( lambda row: map( lambda *column: sum(map(mul, row, column)), *m2), m1) >>> def identity(size): size = range(size) return [[(i==j)*1 for i in size] for j in size] >>> def matrixExp(m, pow): assert pow>=0 and int(pow)==pow, "Only non-negative, integer powers allowed" accumulator = identity(len(m)) for i in range(pow): accumulator = matrixMul(accumulator, m) return accumulator >>> def printtable(data): for row in data: print ' '.join('%-5s' % ('%s' % cell) for cell in row) >>> m = [[3,2], [2,1]] >>> for i in range(5): print '\n%i:' % i printtable( matrixExp(m, i) ) 0: 1 0 0 1 1: 3 2 2 1 2: 13 8 8 5 3: 55 34 34 21 4: 233 144 144 89 >>> printtable( matrixExp(m, 10) ) 1346269 832040 832040 514229 >>>
Translate this program into VB but keep the logic exactly as in Lua.
Matrix = {} function Matrix.new( dim_y, dim_x ) assert( dim_y and dim_x ) local matrix = {} local metatab = {} setmetatable( matrix, metatab ) metatab.__add = Matrix.Add metatab.__mul = Matrix.Mul metatab.__pow = Matrix.Pow matrix.dim_y = dim_y matrix.dim_x = dim_x matrix.data = {} for i = 1, dim_y do matrix.data[i] = {} end return matrix end function Matrix.Show( m ) for i = 1, m.dim_y do for j = 1, m.dim_x do io.write( tostring( m.data[i][j] ), " " ) end io.write( "\n" ) end end function Matrix.Add( m, n ) assert( m.dim_x == n.dim_x and m.dim_y == n.dim_y ) local r = Matrix.new( m.dim_y, m.dim_x ) for i = 1, m.dim_y do for j = 1, m.dim_x do r.data[i][j] = m.data[i][j] + n.data[i][j] end end return r end function Matrix.Mul( m, n ) assert( m.dim_x == n.dim_y ) local r = Matrix.new( m.dim_y, n.dim_x ) for i = 1, m.dim_y do for j = 1, n.dim_x do r.data[i][j] = 0 for k = 1, m.dim_x do r.data[i][j] = r.data[i][j] + m.data[i][k] * n.data[k][j] end end end return r end function Matrix.Pow( m, p ) assert( m.dim_x == m.dim_y ) local r = Matrix.new( m.dim_y, m.dim_x ) if p == 0 then for i = 1, m.dim_y do for j = 1, m.dim_x do if i == j then r.data[i][j] = 1 else r.data[i][j] = 0 end end end elseif p == 1 then for i = 1, m.dim_y do for j = 1, m.dim_x do r.data[i][j] = m.data[i][j] end end else r = m for i = 2, p do r = r * m end end return r end m = Matrix.new( 2, 2 ) m.data = { { 1, 2 }, { 3, 4 } } n = m^4; Matrix.Show( n )
Option Base 1 Private Function Identity(n As Integer) As Variant Dim I() As Variant ReDim I(n, n) For j = 1 To n For k = 1 To n I(j, k) = 0 Next k Next j For j = 1 To n I(j, j) = 1 Next j Identity = I End Function Function MatrixExponentiation(ByVal x As Variant, ByVal n As Integer) As Variant If n < 0 Then x = WorksheetFunction.MInverse(x) n = -n End If If n = 0 Then MatrixExponentiation = Identity(UBound(x)) Exit Function End If Dim y() As Variant y = Identity(UBound(x)) Do While n > 1 If n Mod 2 = 0 Then x = WorksheetFunction.MMult(x, x) n = n / 2 Else y = WorksheetFunction.MMult(x, y) x = WorksheetFunction.MMult(x, x) n = (n - 1) / 2 End If Loop MatrixExponentiation = WorksheetFunction.MMult(x, y) End Function Public Sub pp(x As Variant) For i_ = 1 To UBound(x) For j_ = 1 To UBound(x) Debug.Print x(i_, j_), Next j_ Debug.Print Next i_ End Sub Public Sub main() M2 = [{3,2;2,1}] M3 = [{1,2,0;0,3,1;1,0,0}] pp MatrixExponentiation(M2, -1) Debug.Print pp MatrixExponentiation(M2, 0) Debug.Print pp MatrixExponentiation(M2, 10) Debug.Print pp MatrixExponentiation(M3, 10) End Sub
Rewrite the snippet below in Go so it works the same as the original Lua code.
Matrix = {} function Matrix.new( dim_y, dim_x ) assert( dim_y and dim_x ) local matrix = {} local metatab = {} setmetatable( matrix, metatab ) metatab.__add = Matrix.Add metatab.__mul = Matrix.Mul metatab.__pow = Matrix.Pow matrix.dim_y = dim_y matrix.dim_x = dim_x matrix.data = {} for i = 1, dim_y do matrix.data[i] = {} end return matrix end function Matrix.Show( m ) for i = 1, m.dim_y do for j = 1, m.dim_x do io.write( tostring( m.data[i][j] ), " " ) end io.write( "\n" ) end end function Matrix.Add( m, n ) assert( m.dim_x == n.dim_x and m.dim_y == n.dim_y ) local r = Matrix.new( m.dim_y, m.dim_x ) for i = 1, m.dim_y do for j = 1, m.dim_x do r.data[i][j] = m.data[i][j] + n.data[i][j] end end return r end function Matrix.Mul( m, n ) assert( m.dim_x == n.dim_y ) local r = Matrix.new( m.dim_y, n.dim_x ) for i = 1, m.dim_y do for j = 1, n.dim_x do r.data[i][j] = 0 for k = 1, m.dim_x do r.data[i][j] = r.data[i][j] + m.data[i][k] * n.data[k][j] end end end return r end function Matrix.Pow( m, p ) assert( m.dim_x == m.dim_y ) local r = Matrix.new( m.dim_y, m.dim_x ) if p == 0 then for i = 1, m.dim_y do for j = 1, m.dim_x do if i == j then r.data[i][j] = 1 else r.data[i][j] = 0 end end end elseif p == 1 then for i = 1, m.dim_y do for j = 1, m.dim_x do r.data[i][j] = m.data[i][j] end end else r = m for i = 2, p do r = r * m end end return r end m = Matrix.new( 2, 2 ) m.data = { { 1, 2 }, { 3, 4 } } n = m^4; Matrix.Show( n )
package main import "fmt" type vector = []float64 type matrix []vector func (m1 matrix) mul(m2 matrix) matrix { rows1, cols1 := len(m1), len(m1[0]) rows2, cols2 := len(m2), len(m2[0]) if cols1 != rows2 { panic("Matrices cannot be multiplied.") } result := make(matrix, rows1) for i := 0; i < rows1; i++ { result[i] = make(vector, cols2) for j := 0; j < cols2; j++ { for k := 0; k < rows2; k++ { result[i][j] += m1[i][k] * m2[k][j] } } } return result } func identityMatrix(n int) matrix { if n < 1 { panic("Size of identity matrix can't be less than 1") } ident := make(matrix, n) for i := 0; i < n; i++ { ident[i] = make(vector, n) ident[i][i] = 1 } return ident } func (m matrix) pow(n int) matrix { le := len(m) if le != len(m[0]) { panic("Not a square matrix") } switch { case n < 0: panic("Negative exponents not supported") case n == 0: return identityMatrix(le) case n == 1: return m } pow := identityMatrix(le) base := m e := n for e > 0 { if (e & 1) == 1 { pow = pow.mul(base) } e >>= 1 base = base.mul(base) } return pow } func main() { m := matrix{{3, 2}, {2, 1}} for i := 0; i <= 10; i++ { fmt.Println("** Power of", i, "**") fmt.Println(m.pow(i)) fmt.Println() } }
Change the following Mathematica code into C without altering its purpose.
a = {{3, 2}, {4, 1}}; MatrixPower[a, 0] MatrixPower[a, 1] MatrixPower[a, -1] MatrixPower[a, 4] MatrixPower[a, 1/2] MatrixPower[a, Pi]
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct squareMtxStruct { int dim; double *cells; double **m; } *SquareMtx; typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data); SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data ) { SquareMtx sm = malloc(sizeof(struct squareMtxStruct)); if (sm) { int rw; sm->dim = dim; sm->cells = malloc(dim*dim * sizeof(double)); sm->m = malloc( dim * sizeof(double *)); if ((sm->cells != NULL) && (sm->m != NULL)) { for (rw=0; rw<dim; rw++) { sm->m[rw] = sm->cells + dim*rw; fillFunc( sm->m[rw], rw, dim, ff_data ); } } else { free(sm->m); free(sm->cells); free(sm); printf("Square Matrix allocation failure\n"); return NULL; } } else { printf("Malloc failed for square matrix\n"); } return sm; } void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 ) { int col, ix; double sum; double *m0rw = m0->m[rw]; for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * m0->m[ix][col]; cells[col] = sum; } } void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] ) { SquareMtx mleft = mplcnds[0]; SquareMtx mrigt = mplcnds[1]; double sum; double *m0rw = mleft->m[rw]; int col, ix; for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * mrigt->m[ix][col]; cells[col] = sum; } } void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt) { int rw; SquareMtx mplcnds[2]; mplcnds[0] = left; mplcnds[1] = rigt; for (rw = 0; rw < left->dim; rw++) ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds); } void ffIdentity( double *cells, int rw, int dim, void *v ) { int col; for (col=0; col<dim; col++) cells[col] = 0.0; cells[rw] = 1.0; } void ffCopy(double *cells, int rw, int dim, SquareMtx m1) { int col; for (col=0; col<dim; col++) cells[col] = m1->m[rw][col]; } void FreeSquareMtx( SquareMtx m ) { free(m->m); free(m->cells); free(m); } SquareMtx SquareMtxPow( SquareMtx m0, int exp ) { SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL); SquareMtx v1 = NULL; SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0); SquareMtx base1 = NULL; SquareMtx mplcnds[2], t; while (exp) { if (exp % 2) { if (v1) MatxMul( v1, v0, base0); else { mplcnds[0] = v0; mplcnds[1] = base0; v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds); } {t = v0; v0=v1; v1 = t;} } if (base1) MatxMul( base1, base0, base0); else base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0); t = base0; base0 = base1; base1 = t; exp = exp/2; } if (base0) FreeSquareMtx(base0); if (base1) FreeSquareMtx(base1); if (v1) FreeSquareMtx(v1); return v0; } FILE *fout; void SquareMtxPrint( SquareMtx mtx, const char *mn ) { int rw, col; int d = mtx->dim; fprintf(fout, "%s dim:%d =\n", mn, mtx->dim); for (rw=0; rw<d; rw++) { fprintf(fout, " |"); for(col=0; col<d; col++) fprintf(fout, "%8.5f ",mtx->m[rw][col] ); fprintf(fout, " |\n"); } fprintf(fout, "\n"); } void fillInit( double *cells, int rw, int dim, void *data) { double theta = 3.1415926536/6.0; double c1 = cos( theta); double s1 = sin( theta); switch(rw) { case 0: cells[0]=c1; cells[1]=s1; cells[2]=0.0; break; case 1: cells[0]=-s1; cells[1]=c1; cells[2]=0; break; case 2: cells[0]=0.0; cells[1]=0.0; cells[2]=1.0; break; } } int main() { SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL); SquareMtx m1 = SquareMtxPow( m0, 5); SquareMtx m2 = SquareMtxPow( m0, 9); SquareMtx m3 = SquareMtxPow( m0, 2); fout = fopen("matrx_exp.txt", "w"); SquareMtxPrint(m0, "m0"); FreeSquareMtx(m0); SquareMtxPrint(m1, "m0^5"); FreeSquareMtx(m1); SquareMtxPrint(m2, "m0^9"); FreeSquareMtx(m2); SquareMtxPrint(m3, "m0^2"); FreeSquareMtx(m3); fclose(fout); return 0; }
Change the programming language of this snippet from Mathematica to C# without modifying what it does.
a = {{3, 2}, {4, 1}}; MatrixPower[a, 0] MatrixPower[a, 1] MatrixPower[a, -1] MatrixPower[a, 4] MatrixPower[a, 1/2] MatrixPower[a, Pi]
using System; using System.Collections; using System.Collections.Generic; using static System.Linq.Enumerable; public static class MatrixExponentation { public static double[,] Identity(int size) { double[,] matrix = new double[size, size]; for (int i = 0; i < size; i++) matrix[i, i] = 1; return matrix; } public static double[,] Multiply(this double[,] left, double[,] right) { if (left.ColumnCount() != right.RowCount()) throw new ArgumentException(); double[,] m = new double[left.RowCount(), right.ColumnCount()]; foreach (var (row, column) in from r in Range(0, m.RowCount()) from c in Range(0, m.ColumnCount()) select (r, c)) { m[row, column] = Range(0, m.RowCount()).Sum(i => left[row, i] * right[i, column]); } return m; } public static double[,] Pow(this double[,] matrix, int exp) { if (matrix.RowCount() != matrix.ColumnCount()) throw new ArgumentException("Matrix must be square."); double[,] accumulator = Identity(matrix.RowCount()); for (int i = 0; i < exp; i++) { accumulator = accumulator.Multiply(matrix); } return accumulator; } private static int RowCount(this double[,] matrix) => matrix.GetLength(0); private static int ColumnCount(this double[,] matrix) => matrix.GetLength(1); private static void Print(this double[,] m) { foreach (var row in Rows()) { Console.WriteLine("[ " + string.Join(" ", row) + " ]"); } Console.WriteLine(); IEnumerable<IEnumerable<double>> Rows() => Range(0, m.RowCount()).Select(row => Range(0, m.ColumnCount()).Select(column => m[row, column])); } public static void Main() { var matrix = new double[,] { { 3, 2 }, { 2, 1 } }; matrix.Pow(0).Print(); matrix.Pow(1).Print(); matrix.Pow(2).Print(); matrix.Pow(3).Print(); matrix.Pow(4).Print(); matrix.Pow(50).Print(); } }
Change the following Mathematica code into C++ without altering its purpose.
a = {{3, 2}, {4, 1}}; MatrixPower[a, 0] MatrixPower[a, 1] MatrixPower[a, -1] MatrixPower[a, 4] MatrixPower[a, 1/2] MatrixPower[a, Pi]
#include <complex> #include <cmath> #include <iostream> using namespace std; template<int MSize = 3, class T = complex<double> > class SqMx { typedef T Ax[MSize][MSize]; typedef SqMx<MSize, T> Mx; private: Ax a; SqMx() { } public: SqMx(const Ax &_a) { for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) a[r][c] = _a[r][c]; } static Mx identity() { Mx m; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) m.a[r][c] = (r == c ? 1 : 0); return m; } friend ostream &operator<<(ostream& os, const Mx &p) { for (int i = 0; i < MSize; i++) { for (int j = 0; j < MSize; j++) os << p.a[i][j] << ','; os << endl; } return os; } Mx operator*(const Mx &b) { Mx d; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) { d.a[r][c] = 0; for (int k = 0; k < MSize; k++) d.a[r][c] += a[r][k] * b.a[k][c]; } return d; }
Keep all operations the same but rewrite the snippet in Python.
a = {{3, 2}, {4, 1}}; MatrixPower[a, 0] MatrixPower[a, 1] MatrixPower[a, -1] MatrixPower[a, 4] MatrixPower[a, 1/2] MatrixPower[a, Pi]
>>> from operator import mul >>> def matrixMul(m1, m2): return map( lambda row: map( lambda *column: sum(map(mul, row, column)), *m2), m1) >>> def identity(size): size = range(size) return [[(i==j)*1 for i in size] for j in size] >>> def matrixExp(m, pow): assert pow>=0 and int(pow)==pow, "Only non-negative, integer powers allowed" accumulator = identity(len(m)) for i in range(pow): accumulator = matrixMul(accumulator, m) return accumulator >>> def printtable(data): for row in data: print ' '.join('%-5s' % ('%s' % cell) for cell in row) >>> m = [[3,2], [2,1]] >>> for i in range(5): print '\n%i:' % i printtable( matrixExp(m, i) ) 0: 1 0 0 1 1: 3 2 2 1 2: 13 8 8 5 3: 55 34 34 21 4: 233 144 144 89 >>> printtable( matrixExp(m, 10) ) 1346269 832040 832040 514229 >>>
Produce a functionally identical VB code for the snippet given in Mathematica.
a = {{3, 2}, {4, 1}}; MatrixPower[a, 0] MatrixPower[a, 1] MatrixPower[a, -1] MatrixPower[a, 4] MatrixPower[a, 1/2] MatrixPower[a, Pi]
Option Base 1 Private Function Identity(n As Integer) As Variant Dim I() As Variant ReDim I(n, n) For j = 1 To n For k = 1 To n I(j, k) = 0 Next k Next j For j = 1 To n I(j, j) = 1 Next j Identity = I End Function Function MatrixExponentiation(ByVal x As Variant, ByVal n As Integer) As Variant If n < 0 Then x = WorksheetFunction.MInverse(x) n = -n End If If n = 0 Then MatrixExponentiation = Identity(UBound(x)) Exit Function End If Dim y() As Variant y = Identity(UBound(x)) Do While n > 1 If n Mod 2 = 0 Then x = WorksheetFunction.MMult(x, x) n = n / 2 Else y = WorksheetFunction.MMult(x, y) x = WorksheetFunction.MMult(x, x) n = (n - 1) / 2 End If Loop MatrixExponentiation = WorksheetFunction.MMult(x, y) End Function Public Sub pp(x As Variant) For i_ = 1 To UBound(x) For j_ = 1 To UBound(x) Debug.Print x(i_, j_), Next j_ Debug.Print Next i_ End Sub Public Sub main() M2 = [{3,2;2,1}] M3 = [{1,2,0;0,3,1;1,0,0}] pp MatrixExponentiation(M2, -1) Debug.Print pp MatrixExponentiation(M2, 0) Debug.Print pp MatrixExponentiation(M2, 10) Debug.Print pp MatrixExponentiation(M3, 10) End Sub
Generate a Go translation of this Mathematica snippet without changing its computational steps.
a = {{3, 2}, {4, 1}}; MatrixPower[a, 0] MatrixPower[a, 1] MatrixPower[a, -1] MatrixPower[a, 4] MatrixPower[a, 1/2] MatrixPower[a, Pi]
package main import "fmt" type vector = []float64 type matrix []vector func (m1 matrix) mul(m2 matrix) matrix { rows1, cols1 := len(m1), len(m1[0]) rows2, cols2 := len(m2), len(m2[0]) if cols1 != rows2 { panic("Matrices cannot be multiplied.") } result := make(matrix, rows1) for i := 0; i < rows1; i++ { result[i] = make(vector, cols2) for j := 0; j < cols2; j++ { for k := 0; k < rows2; k++ { result[i][j] += m1[i][k] * m2[k][j] } } } return result } func identityMatrix(n int) matrix { if n < 1 { panic("Size of identity matrix can't be less than 1") } ident := make(matrix, n) for i := 0; i < n; i++ { ident[i] = make(vector, n) ident[i][i] = 1 } return ident } func (m matrix) pow(n int) matrix { le := len(m) if le != len(m[0]) { panic("Not a square matrix") } switch { case n < 0: panic("Negative exponents not supported") case n == 0: return identityMatrix(le) case n == 1: return m } pow := identityMatrix(le) base := m e := n for e > 0 { if (e & 1) == 1 { pow = pow.mul(base) } e >>= 1 base = base.mul(base) } return pow } func main() { m := matrix{{3, 2}, {2, 1}} for i := 0; i <= 10; i++ { fmt.Println("** Power of", i, "**") fmt.Println(m.pow(i)) fmt.Println() } }
Rewrite the snippet below in C so it works the same as the original MATLAB code.
function [output] = matrixexponentiation(matrixA, exponent) output = matrixA^(exponent);
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct squareMtxStruct { int dim; double *cells; double **m; } *SquareMtx; typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data); SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data ) { SquareMtx sm = malloc(sizeof(struct squareMtxStruct)); if (sm) { int rw; sm->dim = dim; sm->cells = malloc(dim*dim * sizeof(double)); sm->m = malloc( dim * sizeof(double *)); if ((sm->cells != NULL) && (sm->m != NULL)) { for (rw=0; rw<dim; rw++) { sm->m[rw] = sm->cells + dim*rw; fillFunc( sm->m[rw], rw, dim, ff_data ); } } else { free(sm->m); free(sm->cells); free(sm); printf("Square Matrix allocation failure\n"); return NULL; } } else { printf("Malloc failed for square matrix\n"); } return sm; } void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 ) { int col, ix; double sum; double *m0rw = m0->m[rw]; for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * m0->m[ix][col]; cells[col] = sum; } } void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] ) { SquareMtx mleft = mplcnds[0]; SquareMtx mrigt = mplcnds[1]; double sum; double *m0rw = mleft->m[rw]; int col, ix; for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * mrigt->m[ix][col]; cells[col] = sum; } } void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt) { int rw; SquareMtx mplcnds[2]; mplcnds[0] = left; mplcnds[1] = rigt; for (rw = 0; rw < left->dim; rw++) ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds); } void ffIdentity( double *cells, int rw, int dim, void *v ) { int col; for (col=0; col<dim; col++) cells[col] = 0.0; cells[rw] = 1.0; } void ffCopy(double *cells, int rw, int dim, SquareMtx m1) { int col; for (col=0; col<dim; col++) cells[col] = m1->m[rw][col]; } void FreeSquareMtx( SquareMtx m ) { free(m->m); free(m->cells); free(m); } SquareMtx SquareMtxPow( SquareMtx m0, int exp ) { SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL); SquareMtx v1 = NULL; SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0); SquareMtx base1 = NULL; SquareMtx mplcnds[2], t; while (exp) { if (exp % 2) { if (v1) MatxMul( v1, v0, base0); else { mplcnds[0] = v0; mplcnds[1] = base0; v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds); } {t = v0; v0=v1; v1 = t;} } if (base1) MatxMul( base1, base0, base0); else base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0); t = base0; base0 = base1; base1 = t; exp = exp/2; } if (base0) FreeSquareMtx(base0); if (base1) FreeSquareMtx(base1); if (v1) FreeSquareMtx(v1); return v0; } FILE *fout; void SquareMtxPrint( SquareMtx mtx, const char *mn ) { int rw, col; int d = mtx->dim; fprintf(fout, "%s dim:%d =\n", mn, mtx->dim); for (rw=0; rw<d; rw++) { fprintf(fout, " |"); for(col=0; col<d; col++) fprintf(fout, "%8.5f ",mtx->m[rw][col] ); fprintf(fout, " |\n"); } fprintf(fout, "\n"); } void fillInit( double *cells, int rw, int dim, void *data) { double theta = 3.1415926536/6.0; double c1 = cos( theta); double s1 = sin( theta); switch(rw) { case 0: cells[0]=c1; cells[1]=s1; cells[2]=0.0; break; case 1: cells[0]=-s1; cells[1]=c1; cells[2]=0; break; case 2: cells[0]=0.0; cells[1]=0.0; cells[2]=1.0; break; } } int main() { SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL); SquareMtx m1 = SquareMtxPow( m0, 5); SquareMtx m2 = SquareMtxPow( m0, 9); SquareMtx m3 = SquareMtxPow( m0, 2); fout = fopen("matrx_exp.txt", "w"); SquareMtxPrint(m0, "m0"); FreeSquareMtx(m0); SquareMtxPrint(m1, "m0^5"); FreeSquareMtx(m1); SquareMtxPrint(m2, "m0^9"); FreeSquareMtx(m2); SquareMtxPrint(m3, "m0^2"); FreeSquareMtx(m3); fclose(fout); return 0; }
Write the same algorithm in C# as shown in this MATLAB implementation.
function [output] = matrixexponentiation(matrixA, exponent) output = matrixA^(exponent);
using System; using System.Collections; using System.Collections.Generic; using static System.Linq.Enumerable; public static class MatrixExponentation { public static double[,] Identity(int size) { double[,] matrix = new double[size, size]; for (int i = 0; i < size; i++) matrix[i, i] = 1; return matrix; } public static double[,] Multiply(this double[,] left, double[,] right) { if (left.ColumnCount() != right.RowCount()) throw new ArgumentException(); double[,] m = new double[left.RowCount(), right.ColumnCount()]; foreach (var (row, column) in from r in Range(0, m.RowCount()) from c in Range(0, m.ColumnCount()) select (r, c)) { m[row, column] = Range(0, m.RowCount()).Sum(i => left[row, i] * right[i, column]); } return m; } public static double[,] Pow(this double[,] matrix, int exp) { if (matrix.RowCount() != matrix.ColumnCount()) throw new ArgumentException("Matrix must be square."); double[,] accumulator = Identity(matrix.RowCount()); for (int i = 0; i < exp; i++) { accumulator = accumulator.Multiply(matrix); } return accumulator; } private static int RowCount(this double[,] matrix) => matrix.GetLength(0); private static int ColumnCount(this double[,] matrix) => matrix.GetLength(1); private static void Print(this double[,] m) { foreach (var row in Rows()) { Console.WriteLine("[ " + string.Join(" ", row) + " ]"); } Console.WriteLine(); IEnumerable<IEnumerable<double>> Rows() => Range(0, m.RowCount()).Select(row => Range(0, m.ColumnCount()).Select(column => m[row, column])); } public static void Main() { var matrix = new double[,] { { 3, 2 }, { 2, 1 } }; matrix.Pow(0).Print(); matrix.Pow(1).Print(); matrix.Pow(2).Print(); matrix.Pow(3).Print(); matrix.Pow(4).Print(); matrix.Pow(50).Print(); } }
Port the provided MATLAB code into C++ while preserving the original functionality.
function [output] = matrixexponentiation(matrixA, exponent) output = matrixA^(exponent);
#include <complex> #include <cmath> #include <iostream> using namespace std; template<int MSize = 3, class T = complex<double> > class SqMx { typedef T Ax[MSize][MSize]; typedef SqMx<MSize, T> Mx; private: Ax a; SqMx() { } public: SqMx(const Ax &_a) { for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) a[r][c] = _a[r][c]; } static Mx identity() { Mx m; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) m.a[r][c] = (r == c ? 1 : 0); return m; } friend ostream &operator<<(ostream& os, const Mx &p) { for (int i = 0; i < MSize; i++) { for (int j = 0; j < MSize; j++) os << p.a[i][j] << ','; os << endl; } return os; } Mx operator*(const Mx &b) { Mx d; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) { d.a[r][c] = 0; for (int k = 0; k < MSize; k++) d.a[r][c] += a[r][k] * b.a[k][c]; } return d; }
Write the same code in Python as shown below in MATLAB.
function [output] = matrixexponentiation(matrixA, exponent) output = matrixA^(exponent);
>>> from operator import mul >>> def matrixMul(m1, m2): return map( lambda row: map( lambda *column: sum(map(mul, row, column)), *m2), m1) >>> def identity(size): size = range(size) return [[(i==j)*1 for i in size] for j in size] >>> def matrixExp(m, pow): assert pow>=0 and int(pow)==pow, "Only non-negative, integer powers allowed" accumulator = identity(len(m)) for i in range(pow): accumulator = matrixMul(accumulator, m) return accumulator >>> def printtable(data): for row in data: print ' '.join('%-5s' % ('%s' % cell) for cell in row) >>> m = [[3,2], [2,1]] >>> for i in range(5): print '\n%i:' % i printtable( matrixExp(m, i) ) 0: 1 0 0 1 1: 3 2 2 1 2: 13 8 8 5 3: 55 34 34 21 4: 233 144 144 89 >>> printtable( matrixExp(m, 10) ) 1346269 832040 832040 514229 >>>
Translate the given MATLAB code snippet into VB without altering its behavior.
function [output] = matrixexponentiation(matrixA, exponent) output = matrixA^(exponent);
Option Base 1 Private Function Identity(n As Integer) As Variant Dim I() As Variant ReDim I(n, n) For j = 1 To n For k = 1 To n I(j, k) = 0 Next k Next j For j = 1 To n I(j, j) = 1 Next j Identity = I End Function Function MatrixExponentiation(ByVal x As Variant, ByVal n As Integer) As Variant If n < 0 Then x = WorksheetFunction.MInverse(x) n = -n End If If n = 0 Then MatrixExponentiation = Identity(UBound(x)) Exit Function End If Dim y() As Variant y = Identity(UBound(x)) Do While n > 1 If n Mod 2 = 0 Then x = WorksheetFunction.MMult(x, x) n = n / 2 Else y = WorksheetFunction.MMult(x, y) x = WorksheetFunction.MMult(x, x) n = (n - 1) / 2 End If Loop MatrixExponentiation = WorksheetFunction.MMult(x, y) End Function Public Sub pp(x As Variant) For i_ = 1 To UBound(x) For j_ = 1 To UBound(x) Debug.Print x(i_, j_), Next j_ Debug.Print Next i_ End Sub Public Sub main() M2 = [{3,2;2,1}] M3 = [{1,2,0;0,3,1;1,0,0}] pp MatrixExponentiation(M2, -1) Debug.Print pp MatrixExponentiation(M2, 0) Debug.Print pp MatrixExponentiation(M2, 10) Debug.Print pp MatrixExponentiation(M3, 10) End Sub
Port the following code from MATLAB to Go with equivalent syntax and logic.
function [output] = matrixexponentiation(matrixA, exponent) output = matrixA^(exponent);
package main import "fmt" type vector = []float64 type matrix []vector func (m1 matrix) mul(m2 matrix) matrix { rows1, cols1 := len(m1), len(m1[0]) rows2, cols2 := len(m2), len(m2[0]) if cols1 != rows2 { panic("Matrices cannot be multiplied.") } result := make(matrix, rows1) for i := 0; i < rows1; i++ { result[i] = make(vector, cols2) for j := 0; j < cols2; j++ { for k := 0; k < rows2; k++ { result[i][j] += m1[i][k] * m2[k][j] } } } return result } func identityMatrix(n int) matrix { if n < 1 { panic("Size of identity matrix can't be less than 1") } ident := make(matrix, n) for i := 0; i < n; i++ { ident[i] = make(vector, n) ident[i][i] = 1 } return ident } func (m matrix) pow(n int) matrix { le := len(m) if le != len(m[0]) { panic("Not a square matrix") } switch { case n < 0: panic("Negative exponents not supported") case n == 0: return identityMatrix(le) case n == 1: return m } pow := identityMatrix(le) base := m e := n for e > 0 { if (e & 1) == 1 { pow = pow.mul(base) } e >>= 1 base = base.mul(base) } return pow } func main() { m := matrix{{3, 2}, {2, 1}} for i := 0; i <= 10; i++ { fmt.Println("** Power of", i, "**") fmt.Println(m.pow(i)) fmt.Println() } }
Translate the given Nim code snippet into C without altering its behavior.
import sequtils, strutils type Matrix[N: static int; T] = array[1..N, array[1..N, T]] func `*`[N, T](a, b: Matrix[N, T]): Matrix[N, T] = for i in 1..N: for j in 1..N: for k in 1..N: result[i][j] += a[i][k] * b[k][j] func identityMatrix[N; T](): Matrix[N, T] = for i in 1..N: result[i][i] = T(1) func `^`[N, T](m: Matrix[N, T]; n: Natural): Matrix[N, T] = if n == 0: return identityMatrix[N, T]() if n == 1: return m var n = n var m = m result = identityMatrix[N, T]() while n > 0: if (n and 1) != 0: result = result * m n = n shr 1 m = m * m proc `$`(m: Matrix): string = var lg = 0 for i in 1..m.N: for j in 1..m.N: lg = max(lg, len($m[i][j])) for i in 1..m.N: echo m[i].mapIt(align($it, lg)).join(" ") when isMainModule: let m1: Matrix[3, int] = [[ 3, 2, -1], [-1, 0, 5], [ 2, -1, 3]] echo m1^10 import math const C30 = sqrt(3.0) / 2 S30 = 1 / 2 let m2: Matrix[2, float] = [[C30, -S30], [S30, C30]] echo m2^12
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct squareMtxStruct { int dim; double *cells; double **m; } *SquareMtx; typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data); SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data ) { SquareMtx sm = malloc(sizeof(struct squareMtxStruct)); if (sm) { int rw; sm->dim = dim; sm->cells = malloc(dim*dim * sizeof(double)); sm->m = malloc( dim * sizeof(double *)); if ((sm->cells != NULL) && (sm->m != NULL)) { for (rw=0; rw<dim; rw++) { sm->m[rw] = sm->cells + dim*rw; fillFunc( sm->m[rw], rw, dim, ff_data ); } } else { free(sm->m); free(sm->cells); free(sm); printf("Square Matrix allocation failure\n"); return NULL; } } else { printf("Malloc failed for square matrix\n"); } return sm; } void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 ) { int col, ix; double sum; double *m0rw = m0->m[rw]; for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * m0->m[ix][col]; cells[col] = sum; } } void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] ) { SquareMtx mleft = mplcnds[0]; SquareMtx mrigt = mplcnds[1]; double sum; double *m0rw = mleft->m[rw]; int col, ix; for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * mrigt->m[ix][col]; cells[col] = sum; } } void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt) { int rw; SquareMtx mplcnds[2]; mplcnds[0] = left; mplcnds[1] = rigt; for (rw = 0; rw < left->dim; rw++) ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds); } void ffIdentity( double *cells, int rw, int dim, void *v ) { int col; for (col=0; col<dim; col++) cells[col] = 0.0; cells[rw] = 1.0; } void ffCopy(double *cells, int rw, int dim, SquareMtx m1) { int col; for (col=0; col<dim; col++) cells[col] = m1->m[rw][col]; } void FreeSquareMtx( SquareMtx m ) { free(m->m); free(m->cells); free(m); } SquareMtx SquareMtxPow( SquareMtx m0, int exp ) { SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL); SquareMtx v1 = NULL; SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0); SquareMtx base1 = NULL; SquareMtx mplcnds[2], t; while (exp) { if (exp % 2) { if (v1) MatxMul( v1, v0, base0); else { mplcnds[0] = v0; mplcnds[1] = base0; v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds); } {t = v0; v0=v1; v1 = t;} } if (base1) MatxMul( base1, base0, base0); else base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0); t = base0; base0 = base1; base1 = t; exp = exp/2; } if (base0) FreeSquareMtx(base0); if (base1) FreeSquareMtx(base1); if (v1) FreeSquareMtx(v1); return v0; } FILE *fout; void SquareMtxPrint( SquareMtx mtx, const char *mn ) { int rw, col; int d = mtx->dim; fprintf(fout, "%s dim:%d =\n", mn, mtx->dim); for (rw=0; rw<d; rw++) { fprintf(fout, " |"); for(col=0; col<d; col++) fprintf(fout, "%8.5f ",mtx->m[rw][col] ); fprintf(fout, " |\n"); } fprintf(fout, "\n"); } void fillInit( double *cells, int rw, int dim, void *data) { double theta = 3.1415926536/6.0; double c1 = cos( theta); double s1 = sin( theta); switch(rw) { case 0: cells[0]=c1; cells[1]=s1; cells[2]=0.0; break; case 1: cells[0]=-s1; cells[1]=c1; cells[2]=0; break; case 2: cells[0]=0.0; cells[1]=0.0; cells[2]=1.0; break; } } int main() { SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL); SquareMtx m1 = SquareMtxPow( m0, 5); SquareMtx m2 = SquareMtxPow( m0, 9); SquareMtx m3 = SquareMtxPow( m0, 2); fout = fopen("matrx_exp.txt", "w"); SquareMtxPrint(m0, "m0"); FreeSquareMtx(m0); SquareMtxPrint(m1, "m0^5"); FreeSquareMtx(m1); SquareMtxPrint(m2, "m0^9"); FreeSquareMtx(m2); SquareMtxPrint(m3, "m0^2"); FreeSquareMtx(m3); fclose(fout); return 0; }
Transform the following Nim implementation into C#, maintaining the same output and logic.
import sequtils, strutils type Matrix[N: static int; T] = array[1..N, array[1..N, T]] func `*`[N, T](a, b: Matrix[N, T]): Matrix[N, T] = for i in 1..N: for j in 1..N: for k in 1..N: result[i][j] += a[i][k] * b[k][j] func identityMatrix[N; T](): Matrix[N, T] = for i in 1..N: result[i][i] = T(1) func `^`[N, T](m: Matrix[N, T]; n: Natural): Matrix[N, T] = if n == 0: return identityMatrix[N, T]() if n == 1: return m var n = n var m = m result = identityMatrix[N, T]() while n > 0: if (n and 1) != 0: result = result * m n = n shr 1 m = m * m proc `$`(m: Matrix): string = var lg = 0 for i in 1..m.N: for j in 1..m.N: lg = max(lg, len($m[i][j])) for i in 1..m.N: echo m[i].mapIt(align($it, lg)).join(" ") when isMainModule: let m1: Matrix[3, int] = [[ 3, 2, -1], [-1, 0, 5], [ 2, -1, 3]] echo m1^10 import math const C30 = sqrt(3.0) / 2 S30 = 1 / 2 let m2: Matrix[2, float] = [[C30, -S30], [S30, C30]] echo m2^12
using System; using System.Collections; using System.Collections.Generic; using static System.Linq.Enumerable; public static class MatrixExponentation { public static double[,] Identity(int size) { double[,] matrix = new double[size, size]; for (int i = 0; i < size; i++) matrix[i, i] = 1; return matrix; } public static double[,] Multiply(this double[,] left, double[,] right) { if (left.ColumnCount() != right.RowCount()) throw new ArgumentException(); double[,] m = new double[left.RowCount(), right.ColumnCount()]; foreach (var (row, column) in from r in Range(0, m.RowCount()) from c in Range(0, m.ColumnCount()) select (r, c)) { m[row, column] = Range(0, m.RowCount()).Sum(i => left[row, i] * right[i, column]); } return m; } public static double[,] Pow(this double[,] matrix, int exp) { if (matrix.RowCount() != matrix.ColumnCount()) throw new ArgumentException("Matrix must be square."); double[,] accumulator = Identity(matrix.RowCount()); for (int i = 0; i < exp; i++) { accumulator = accumulator.Multiply(matrix); } return accumulator; } private static int RowCount(this double[,] matrix) => matrix.GetLength(0); private static int ColumnCount(this double[,] matrix) => matrix.GetLength(1); private static void Print(this double[,] m) { foreach (var row in Rows()) { Console.WriteLine("[ " + string.Join(" ", row) + " ]"); } Console.WriteLine(); IEnumerable<IEnumerable<double>> Rows() => Range(0, m.RowCount()).Select(row => Range(0, m.ColumnCount()).Select(column => m[row, column])); } public static void Main() { var matrix = new double[,] { { 3, 2 }, { 2, 1 } }; matrix.Pow(0).Print(); matrix.Pow(1).Print(); matrix.Pow(2).Print(); matrix.Pow(3).Print(); matrix.Pow(4).Print(); matrix.Pow(50).Print(); } }
Convert the following code from Nim to C++, ensuring the logic remains intact.
import sequtils, strutils type Matrix[N: static int; T] = array[1..N, array[1..N, T]] func `*`[N, T](a, b: Matrix[N, T]): Matrix[N, T] = for i in 1..N: for j in 1..N: for k in 1..N: result[i][j] += a[i][k] * b[k][j] func identityMatrix[N; T](): Matrix[N, T] = for i in 1..N: result[i][i] = T(1) func `^`[N, T](m: Matrix[N, T]; n: Natural): Matrix[N, T] = if n == 0: return identityMatrix[N, T]() if n == 1: return m var n = n var m = m result = identityMatrix[N, T]() while n > 0: if (n and 1) != 0: result = result * m n = n shr 1 m = m * m proc `$`(m: Matrix): string = var lg = 0 for i in 1..m.N: for j in 1..m.N: lg = max(lg, len($m[i][j])) for i in 1..m.N: echo m[i].mapIt(align($it, lg)).join(" ") when isMainModule: let m1: Matrix[3, int] = [[ 3, 2, -1], [-1, 0, 5], [ 2, -1, 3]] echo m1^10 import math const C30 = sqrt(3.0) / 2 S30 = 1 / 2 let m2: Matrix[2, float] = [[C30, -S30], [S30, C30]] echo m2^12
#include <complex> #include <cmath> #include <iostream> using namespace std; template<int MSize = 3, class T = complex<double> > class SqMx { typedef T Ax[MSize][MSize]; typedef SqMx<MSize, T> Mx; private: Ax a; SqMx() { } public: SqMx(const Ax &_a) { for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) a[r][c] = _a[r][c]; } static Mx identity() { Mx m; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) m.a[r][c] = (r == c ? 1 : 0); return m; } friend ostream &operator<<(ostream& os, const Mx &p) { for (int i = 0; i < MSize; i++) { for (int j = 0; j < MSize; j++) os << p.a[i][j] << ','; os << endl; } return os; } Mx operator*(const Mx &b) { Mx d; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) { d.a[r][c] = 0; for (int k = 0; k < MSize; k++) d.a[r][c] += a[r][k] * b.a[k][c]; } return d; }
Generate a Python translation of this Nim snippet without changing its computational steps.
import sequtils, strutils type Matrix[N: static int; T] = array[1..N, array[1..N, T]] func `*`[N, T](a, b: Matrix[N, T]): Matrix[N, T] = for i in 1..N: for j in 1..N: for k in 1..N: result[i][j] += a[i][k] * b[k][j] func identityMatrix[N; T](): Matrix[N, T] = for i in 1..N: result[i][i] = T(1) func `^`[N, T](m: Matrix[N, T]; n: Natural): Matrix[N, T] = if n == 0: return identityMatrix[N, T]() if n == 1: return m var n = n var m = m result = identityMatrix[N, T]() while n > 0: if (n and 1) != 0: result = result * m n = n shr 1 m = m * m proc `$`(m: Matrix): string = var lg = 0 for i in 1..m.N: for j in 1..m.N: lg = max(lg, len($m[i][j])) for i in 1..m.N: echo m[i].mapIt(align($it, lg)).join(" ") when isMainModule: let m1: Matrix[3, int] = [[ 3, 2, -1], [-1, 0, 5], [ 2, -1, 3]] echo m1^10 import math const C30 = sqrt(3.0) / 2 S30 = 1 / 2 let m2: Matrix[2, float] = [[C30, -S30], [S30, C30]] echo m2^12
>>> from operator import mul >>> def matrixMul(m1, m2): return map( lambda row: map( lambda *column: sum(map(mul, row, column)), *m2), m1) >>> def identity(size): size = range(size) return [[(i==j)*1 for i in size] for j in size] >>> def matrixExp(m, pow): assert pow>=0 and int(pow)==pow, "Only non-negative, integer powers allowed" accumulator = identity(len(m)) for i in range(pow): accumulator = matrixMul(accumulator, m) return accumulator >>> def printtable(data): for row in data: print ' '.join('%-5s' % ('%s' % cell) for cell in row) >>> m = [[3,2], [2,1]] >>> for i in range(5): print '\n%i:' % i printtable( matrixExp(m, i) ) 0: 1 0 0 1 1: 3 2 2 1 2: 13 8 8 5 3: 55 34 34 21 4: 233 144 144 89 >>> printtable( matrixExp(m, 10) ) 1346269 832040 832040 514229 >>>
Write the same algorithm in VB as shown in this Nim implementation.
import sequtils, strutils type Matrix[N: static int; T] = array[1..N, array[1..N, T]] func `*`[N, T](a, b: Matrix[N, T]): Matrix[N, T] = for i in 1..N: for j in 1..N: for k in 1..N: result[i][j] += a[i][k] * b[k][j] func identityMatrix[N; T](): Matrix[N, T] = for i in 1..N: result[i][i] = T(1) func `^`[N, T](m: Matrix[N, T]; n: Natural): Matrix[N, T] = if n == 0: return identityMatrix[N, T]() if n == 1: return m var n = n var m = m result = identityMatrix[N, T]() while n > 0: if (n and 1) != 0: result = result * m n = n shr 1 m = m * m proc `$`(m: Matrix): string = var lg = 0 for i in 1..m.N: for j in 1..m.N: lg = max(lg, len($m[i][j])) for i in 1..m.N: echo m[i].mapIt(align($it, lg)).join(" ") when isMainModule: let m1: Matrix[3, int] = [[ 3, 2, -1], [-1, 0, 5], [ 2, -1, 3]] echo m1^10 import math const C30 = sqrt(3.0) / 2 S30 = 1 / 2 let m2: Matrix[2, float] = [[C30, -S30], [S30, C30]] echo m2^12
Option Base 1 Private Function Identity(n As Integer) As Variant Dim I() As Variant ReDim I(n, n) For j = 1 To n For k = 1 To n I(j, k) = 0 Next k Next j For j = 1 To n I(j, j) = 1 Next j Identity = I End Function Function MatrixExponentiation(ByVal x As Variant, ByVal n As Integer) As Variant If n < 0 Then x = WorksheetFunction.MInverse(x) n = -n End If If n = 0 Then MatrixExponentiation = Identity(UBound(x)) Exit Function End If Dim y() As Variant y = Identity(UBound(x)) Do While n > 1 If n Mod 2 = 0 Then x = WorksheetFunction.MMult(x, x) n = n / 2 Else y = WorksheetFunction.MMult(x, y) x = WorksheetFunction.MMult(x, x) n = (n - 1) / 2 End If Loop MatrixExponentiation = WorksheetFunction.MMult(x, y) End Function Public Sub pp(x As Variant) For i_ = 1 To UBound(x) For j_ = 1 To UBound(x) Debug.Print x(i_, j_), Next j_ Debug.Print Next i_ End Sub Public Sub main() M2 = [{3,2;2,1}] M3 = [{1,2,0;0,3,1;1,0,0}] pp MatrixExponentiation(M2, -1) Debug.Print pp MatrixExponentiation(M2, 0) Debug.Print pp MatrixExponentiation(M2, 10) Debug.Print pp MatrixExponentiation(M3, 10) End Sub
Produce a functionally identical Go code for the snippet given in Nim.
import sequtils, strutils type Matrix[N: static int; T] = array[1..N, array[1..N, T]] func `*`[N, T](a, b: Matrix[N, T]): Matrix[N, T] = for i in 1..N: for j in 1..N: for k in 1..N: result[i][j] += a[i][k] * b[k][j] func identityMatrix[N; T](): Matrix[N, T] = for i in 1..N: result[i][i] = T(1) func `^`[N, T](m: Matrix[N, T]; n: Natural): Matrix[N, T] = if n == 0: return identityMatrix[N, T]() if n == 1: return m var n = n var m = m result = identityMatrix[N, T]() while n > 0: if (n and 1) != 0: result = result * m n = n shr 1 m = m * m proc `$`(m: Matrix): string = var lg = 0 for i in 1..m.N: for j in 1..m.N: lg = max(lg, len($m[i][j])) for i in 1..m.N: echo m[i].mapIt(align($it, lg)).join(" ") when isMainModule: let m1: Matrix[3, int] = [[ 3, 2, -1], [-1, 0, 5], [ 2, -1, 3]] echo m1^10 import math const C30 = sqrt(3.0) / 2 S30 = 1 / 2 let m2: Matrix[2, float] = [[C30, -S30], [S30, C30]] echo m2^12
package main import "fmt" type vector = []float64 type matrix []vector func (m1 matrix) mul(m2 matrix) matrix { rows1, cols1 := len(m1), len(m1[0]) rows2, cols2 := len(m2), len(m2[0]) if cols1 != rows2 { panic("Matrices cannot be multiplied.") } result := make(matrix, rows1) for i := 0; i < rows1; i++ { result[i] = make(vector, cols2) for j := 0; j < cols2; j++ { for k := 0; k < rows2; k++ { result[i][j] += m1[i][k] * m2[k][j] } } } return result } func identityMatrix(n int) matrix { if n < 1 { panic("Size of identity matrix can't be less than 1") } ident := make(matrix, n) for i := 0; i < n; i++ { ident[i] = make(vector, n) ident[i][i] = 1 } return ident } func (m matrix) pow(n int) matrix { le := len(m) if le != len(m[0]) { panic("Not a square matrix") } switch { case n < 0: panic("Negative exponents not supported") case n == 0: return identityMatrix(le) case n == 1: return m } pow := identityMatrix(le) base := m e := n for e > 0 { if (e & 1) == 1 { pow = pow.mul(base) } e >>= 1 base = base.mul(base) } return pow } func main() { m := matrix{{3, 2}, {2, 1}} for i := 0; i <= 10; i++ { fmt.Println("** Power of", i, "**") fmt.Println(m.pow(i)) fmt.Println() } }
Preserve the algorithm and functionality while converting the code from OCaml to C.
let eye n = let a = Array.make_matrix n n 0.0 in for i=0 to n-1 do a.(i).(i) <- 1.0 done; (a) ;; let dim a = Array.length a, Array.length a.(0);; let matrix p q v = if (List.length v) <> (p * q) then failwith "bad dimensions" else let a = Array.make_matrix p q (List.hd v) in let rec g i j = function | [] -> a | x::v -> a.(i).(j) <- x; if j+1 < q then g i (j+1) v else g (i+1) 0 v in g 0 0 v ;; let matmul a b = let n, p = dim a and q, r = dim b in if p <> q then failwith "bad dimensions" else let c = Array.make_matrix n r 0.0 in for i=0 to n-1 do for j=0 to r-1 do for k=0 to p-1 do c.(i).(j) <- c.(i).(j) +. a.(i).(k) *. b.(k).(j) done done done; (c) ;; let pow one mul a n = let rec g p x = function | 0 -> x | i -> g (mul p p) (if i mod 2 = 1 then mul p x else x) (i/2) in g a one n ;; pow 1 ( * ) 2 16;;
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct squareMtxStruct { int dim; double *cells; double **m; } *SquareMtx; typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data); SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data ) { SquareMtx sm = malloc(sizeof(struct squareMtxStruct)); if (sm) { int rw; sm->dim = dim; sm->cells = malloc(dim*dim * sizeof(double)); sm->m = malloc( dim * sizeof(double *)); if ((sm->cells != NULL) && (sm->m != NULL)) { for (rw=0; rw<dim; rw++) { sm->m[rw] = sm->cells + dim*rw; fillFunc( sm->m[rw], rw, dim, ff_data ); } } else { free(sm->m); free(sm->cells); free(sm); printf("Square Matrix allocation failure\n"); return NULL; } } else { printf("Malloc failed for square matrix\n"); } return sm; } void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 ) { int col, ix; double sum; double *m0rw = m0->m[rw]; for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * m0->m[ix][col]; cells[col] = sum; } } void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] ) { SquareMtx mleft = mplcnds[0]; SquareMtx mrigt = mplcnds[1]; double sum; double *m0rw = mleft->m[rw]; int col, ix; for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * mrigt->m[ix][col]; cells[col] = sum; } } void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt) { int rw; SquareMtx mplcnds[2]; mplcnds[0] = left; mplcnds[1] = rigt; for (rw = 0; rw < left->dim; rw++) ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds); } void ffIdentity( double *cells, int rw, int dim, void *v ) { int col; for (col=0; col<dim; col++) cells[col] = 0.0; cells[rw] = 1.0; } void ffCopy(double *cells, int rw, int dim, SquareMtx m1) { int col; for (col=0; col<dim; col++) cells[col] = m1->m[rw][col]; } void FreeSquareMtx( SquareMtx m ) { free(m->m); free(m->cells); free(m); } SquareMtx SquareMtxPow( SquareMtx m0, int exp ) { SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL); SquareMtx v1 = NULL; SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0); SquareMtx base1 = NULL; SquareMtx mplcnds[2], t; while (exp) { if (exp % 2) { if (v1) MatxMul( v1, v0, base0); else { mplcnds[0] = v0; mplcnds[1] = base0; v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds); } {t = v0; v0=v1; v1 = t;} } if (base1) MatxMul( base1, base0, base0); else base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0); t = base0; base0 = base1; base1 = t; exp = exp/2; } if (base0) FreeSquareMtx(base0); if (base1) FreeSquareMtx(base1); if (v1) FreeSquareMtx(v1); return v0; } FILE *fout; void SquareMtxPrint( SquareMtx mtx, const char *mn ) { int rw, col; int d = mtx->dim; fprintf(fout, "%s dim:%d =\n", mn, mtx->dim); for (rw=0; rw<d; rw++) { fprintf(fout, " |"); for(col=0; col<d; col++) fprintf(fout, "%8.5f ",mtx->m[rw][col] ); fprintf(fout, " |\n"); } fprintf(fout, "\n"); } void fillInit( double *cells, int rw, int dim, void *data) { double theta = 3.1415926536/6.0; double c1 = cos( theta); double s1 = sin( theta); switch(rw) { case 0: cells[0]=c1; cells[1]=s1; cells[2]=0.0; break; case 1: cells[0]=-s1; cells[1]=c1; cells[2]=0; break; case 2: cells[0]=0.0; cells[1]=0.0; cells[2]=1.0; break; } } int main() { SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL); SquareMtx m1 = SquareMtxPow( m0, 5); SquareMtx m2 = SquareMtxPow( m0, 9); SquareMtx m3 = SquareMtxPow( m0, 2); fout = fopen("matrx_exp.txt", "w"); SquareMtxPrint(m0, "m0"); FreeSquareMtx(m0); SquareMtxPrint(m1, "m0^5"); FreeSquareMtx(m1); SquareMtxPrint(m2, "m0^9"); FreeSquareMtx(m2); SquareMtxPrint(m3, "m0^2"); FreeSquareMtx(m3); fclose(fout); return 0; }
Port the provided OCaml code into C# while preserving the original functionality.
let eye n = let a = Array.make_matrix n n 0.0 in for i=0 to n-1 do a.(i).(i) <- 1.0 done; (a) ;; let dim a = Array.length a, Array.length a.(0);; let matrix p q v = if (List.length v) <> (p * q) then failwith "bad dimensions" else let a = Array.make_matrix p q (List.hd v) in let rec g i j = function | [] -> a | x::v -> a.(i).(j) <- x; if j+1 < q then g i (j+1) v else g (i+1) 0 v in g 0 0 v ;; let matmul a b = let n, p = dim a and q, r = dim b in if p <> q then failwith "bad dimensions" else let c = Array.make_matrix n r 0.0 in for i=0 to n-1 do for j=0 to r-1 do for k=0 to p-1 do c.(i).(j) <- c.(i).(j) +. a.(i).(k) *. b.(k).(j) done done done; (c) ;; let pow one mul a n = let rec g p x = function | 0 -> x | i -> g (mul p p) (if i mod 2 = 1 then mul p x else x) (i/2) in g a one n ;; pow 1 ( * ) 2 16;;
using System; using System.Collections; using System.Collections.Generic; using static System.Linq.Enumerable; public static class MatrixExponentation { public static double[,] Identity(int size) { double[,] matrix = new double[size, size]; for (int i = 0; i < size; i++) matrix[i, i] = 1; return matrix; } public static double[,] Multiply(this double[,] left, double[,] right) { if (left.ColumnCount() != right.RowCount()) throw new ArgumentException(); double[,] m = new double[left.RowCount(), right.ColumnCount()]; foreach (var (row, column) in from r in Range(0, m.RowCount()) from c in Range(0, m.ColumnCount()) select (r, c)) { m[row, column] = Range(0, m.RowCount()).Sum(i => left[row, i] * right[i, column]); } return m; } public static double[,] Pow(this double[,] matrix, int exp) { if (matrix.RowCount() != matrix.ColumnCount()) throw new ArgumentException("Matrix must be square."); double[,] accumulator = Identity(matrix.RowCount()); for (int i = 0; i < exp; i++) { accumulator = accumulator.Multiply(matrix); } return accumulator; } private static int RowCount(this double[,] matrix) => matrix.GetLength(0); private static int ColumnCount(this double[,] matrix) => matrix.GetLength(1); private static void Print(this double[,] m) { foreach (var row in Rows()) { Console.WriteLine("[ " + string.Join(" ", row) + " ]"); } Console.WriteLine(); IEnumerable<IEnumerable<double>> Rows() => Range(0, m.RowCount()).Select(row => Range(0, m.ColumnCount()).Select(column => m[row, column])); } public static void Main() { var matrix = new double[,] { { 3, 2 }, { 2, 1 } }; matrix.Pow(0).Print(); matrix.Pow(1).Print(); matrix.Pow(2).Print(); matrix.Pow(3).Print(); matrix.Pow(4).Print(); matrix.Pow(50).Print(); } }
Transform the following OCaml implementation into C++, maintaining the same output and logic.
let eye n = let a = Array.make_matrix n n 0.0 in for i=0 to n-1 do a.(i).(i) <- 1.0 done; (a) ;; let dim a = Array.length a, Array.length a.(0);; let matrix p q v = if (List.length v) <> (p * q) then failwith "bad dimensions" else let a = Array.make_matrix p q (List.hd v) in let rec g i j = function | [] -> a | x::v -> a.(i).(j) <- x; if j+1 < q then g i (j+1) v else g (i+1) 0 v in g 0 0 v ;; let matmul a b = let n, p = dim a and q, r = dim b in if p <> q then failwith "bad dimensions" else let c = Array.make_matrix n r 0.0 in for i=0 to n-1 do for j=0 to r-1 do for k=0 to p-1 do c.(i).(j) <- c.(i).(j) +. a.(i).(k) *. b.(k).(j) done done done; (c) ;; let pow one mul a n = let rec g p x = function | 0 -> x | i -> g (mul p p) (if i mod 2 = 1 then mul p x else x) (i/2) in g a one n ;; pow 1 ( * ) 2 16;;
#include <complex> #include <cmath> #include <iostream> using namespace std; template<int MSize = 3, class T = complex<double> > class SqMx { typedef T Ax[MSize][MSize]; typedef SqMx<MSize, T> Mx; private: Ax a; SqMx() { } public: SqMx(const Ax &_a) { for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) a[r][c] = _a[r][c]; } static Mx identity() { Mx m; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) m.a[r][c] = (r == c ? 1 : 0); return m; } friend ostream &operator<<(ostream& os, const Mx &p) { for (int i = 0; i < MSize; i++) { for (int j = 0; j < MSize; j++) os << p.a[i][j] << ','; os << endl; } return os; } Mx operator*(const Mx &b) { Mx d; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) { d.a[r][c] = 0; for (int k = 0; k < MSize; k++) d.a[r][c] += a[r][k] * b.a[k][c]; } return d; }
Translate the given OCaml code snippet into Python without altering its behavior.
let eye n = let a = Array.make_matrix n n 0.0 in for i=0 to n-1 do a.(i).(i) <- 1.0 done; (a) ;; let dim a = Array.length a, Array.length a.(0);; let matrix p q v = if (List.length v) <> (p * q) then failwith "bad dimensions" else let a = Array.make_matrix p q (List.hd v) in let rec g i j = function | [] -> a | x::v -> a.(i).(j) <- x; if j+1 < q then g i (j+1) v else g (i+1) 0 v in g 0 0 v ;; let matmul a b = let n, p = dim a and q, r = dim b in if p <> q then failwith "bad dimensions" else let c = Array.make_matrix n r 0.0 in for i=0 to n-1 do for j=0 to r-1 do for k=0 to p-1 do c.(i).(j) <- c.(i).(j) +. a.(i).(k) *. b.(k).(j) done done done; (c) ;; let pow one mul a n = let rec g p x = function | 0 -> x | i -> g (mul p p) (if i mod 2 = 1 then mul p x else x) (i/2) in g a one n ;; pow 1 ( * ) 2 16;;
>>> from operator import mul >>> def matrixMul(m1, m2): return map( lambda row: map( lambda *column: sum(map(mul, row, column)), *m2), m1) >>> def identity(size): size = range(size) return [[(i==j)*1 for i in size] for j in size] >>> def matrixExp(m, pow): assert pow>=0 and int(pow)==pow, "Only non-negative, integer powers allowed" accumulator = identity(len(m)) for i in range(pow): accumulator = matrixMul(accumulator, m) return accumulator >>> def printtable(data): for row in data: print ' '.join('%-5s' % ('%s' % cell) for cell in row) >>> m = [[3,2], [2,1]] >>> for i in range(5): print '\n%i:' % i printtable( matrixExp(m, i) ) 0: 1 0 0 1 1: 3 2 2 1 2: 13 8 8 5 3: 55 34 34 21 4: 233 144 144 89 >>> printtable( matrixExp(m, 10) ) 1346269 832040 832040 514229 >>>
Keep all operations the same but rewrite the snippet in VB.
let eye n = let a = Array.make_matrix n n 0.0 in for i=0 to n-1 do a.(i).(i) <- 1.0 done; (a) ;; let dim a = Array.length a, Array.length a.(0);; let matrix p q v = if (List.length v) <> (p * q) then failwith "bad dimensions" else let a = Array.make_matrix p q (List.hd v) in let rec g i j = function | [] -> a | x::v -> a.(i).(j) <- x; if j+1 < q then g i (j+1) v else g (i+1) 0 v in g 0 0 v ;; let matmul a b = let n, p = dim a and q, r = dim b in if p <> q then failwith "bad dimensions" else let c = Array.make_matrix n r 0.0 in for i=0 to n-1 do for j=0 to r-1 do for k=0 to p-1 do c.(i).(j) <- c.(i).(j) +. a.(i).(k) *. b.(k).(j) done done done; (c) ;; let pow one mul a n = let rec g p x = function | 0 -> x | i -> g (mul p p) (if i mod 2 = 1 then mul p x else x) (i/2) in g a one n ;; pow 1 ( * ) 2 16;;
Option Base 1 Private Function Identity(n As Integer) As Variant Dim I() As Variant ReDim I(n, n) For j = 1 To n For k = 1 To n I(j, k) = 0 Next k Next j For j = 1 To n I(j, j) = 1 Next j Identity = I End Function Function MatrixExponentiation(ByVal x As Variant, ByVal n As Integer) As Variant If n < 0 Then x = WorksheetFunction.MInverse(x) n = -n End If If n = 0 Then MatrixExponentiation = Identity(UBound(x)) Exit Function End If Dim y() As Variant y = Identity(UBound(x)) Do While n > 1 If n Mod 2 = 0 Then x = WorksheetFunction.MMult(x, x) n = n / 2 Else y = WorksheetFunction.MMult(x, y) x = WorksheetFunction.MMult(x, x) n = (n - 1) / 2 End If Loop MatrixExponentiation = WorksheetFunction.MMult(x, y) End Function Public Sub pp(x As Variant) For i_ = 1 To UBound(x) For j_ = 1 To UBound(x) Debug.Print x(i_, j_), Next j_ Debug.Print Next i_ End Sub Public Sub main() M2 = [{3,2;2,1}] M3 = [{1,2,0;0,3,1;1,0,0}] pp MatrixExponentiation(M2, -1) Debug.Print pp MatrixExponentiation(M2, 0) Debug.Print pp MatrixExponentiation(M2, 10) Debug.Print pp MatrixExponentiation(M3, 10) End Sub
Ensure the translated Go code behaves exactly like the original OCaml snippet.
let eye n = let a = Array.make_matrix n n 0.0 in for i=0 to n-1 do a.(i).(i) <- 1.0 done; (a) ;; let dim a = Array.length a, Array.length a.(0);; let matrix p q v = if (List.length v) <> (p * q) then failwith "bad dimensions" else let a = Array.make_matrix p q (List.hd v) in let rec g i j = function | [] -> a | x::v -> a.(i).(j) <- x; if j+1 < q then g i (j+1) v else g (i+1) 0 v in g 0 0 v ;; let matmul a b = let n, p = dim a and q, r = dim b in if p <> q then failwith "bad dimensions" else let c = Array.make_matrix n r 0.0 in for i=0 to n-1 do for j=0 to r-1 do for k=0 to p-1 do c.(i).(j) <- c.(i).(j) +. a.(i).(k) *. b.(k).(j) done done done; (c) ;; let pow one mul a n = let rec g p x = function | 0 -> x | i -> g (mul p p) (if i mod 2 = 1 then mul p x else x) (i/2) in g a one n ;; pow 1 ( * ) 2 16;;
package main import "fmt" type vector = []float64 type matrix []vector func (m1 matrix) mul(m2 matrix) matrix { rows1, cols1 := len(m1), len(m1[0]) rows2, cols2 := len(m2), len(m2[0]) if cols1 != rows2 { panic("Matrices cannot be multiplied.") } result := make(matrix, rows1) for i := 0; i < rows1; i++ { result[i] = make(vector, cols2) for j := 0; j < cols2; j++ { for k := 0; k < rows2; k++ { result[i][j] += m1[i][k] * m2[k][j] } } } return result } func identityMatrix(n int) matrix { if n < 1 { panic("Size of identity matrix can't be less than 1") } ident := make(matrix, n) for i := 0; i < n; i++ { ident[i] = make(vector, n) ident[i][i] = 1 } return ident } func (m matrix) pow(n int) matrix { le := len(m) if le != len(m[0]) { panic("Not a square matrix") } switch { case n < 0: panic("Negative exponents not supported") case n == 0: return identityMatrix(le) case n == 1: return m } pow := identityMatrix(le) base := m e := n for e > 0 { if (e & 1) == 1 { pow = pow.mul(base) } e >>= 1 base = base.mul(base) } return pow } func main() { m := matrix{{3, 2}, {2, 1}} for i := 0; i <= 10; i++ { fmt.Println("** Power of", i, "**") fmt.Println(m.pow(i)) fmt.Println() } }
Change the following Perl code into C without altering its purpose.
use strict; package SquareMatrix; use Carp; use overload ( '""' => \&_string, '*' => \&_mult, '*=' => \&_mult, '**' => \&_expo, '=' => \&_copy, ); sub make { my $cls = shift; my $n = @_; for (@_) { confess "Bad data @$_: matrix must be square " if @$_ != $n; } bless [ map [@$_], @_ ] } sub identity { my $self = shift; my $n = @$self - 1; my @rows = map [ (0) x $_, 1, (0) x ($n - $_) ], 0 .. $n; bless \@rows } sub zero { my $self = shift; my $n = @$self; bless [ map [ (0) x $n ], 1 .. $n ] } sub _string { "[ ".join("\n " => map join(" " => map(sprintf("%12.6g", $_), @$_)), @{+shift} )." ]\n"; } sub _mult { my ($a, $b) = @_; my $x = $a->zero; my @idx = (0 .. $ for my $j (@idx) { my @col = map($a->[$_][$j], @idx); for my $i (@idx) { my $row = $b->[$i]; $x->[$i][$j] += $row->[$_] * $col[$_] for @idx; } } $x } sub _expo { my ($self, $n) = @_; confess "matrix **: must be non-negative integer power" unless $n >= 0 && $n == int($n); my ($tmp, $out) = ($self, $self->identity); do { $out *= $tmp if $n & 1; $tmp *= $tmp; } while $n >>= 1; $out } sub _copy { bless [ map [ @$_ ], @{+shift} ] } package main; my $m = SquareMatrix->make( [1, 2, 0], [0, 3, 1], [1, 0, 0] ); print " $m = SquareMatrix->make( [ 1.0001, 0, 0, 1 ], [ 0, 1.001, 0, 0 ], [ 0, 0, 1, 0.99998 ], [ 1e-8, 0, 0, 1.0002 ]); print "\n print "\n print "\n print "\n print "\n $m->identity ** 1_000_000_000_000;
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct squareMtxStruct { int dim; double *cells; double **m; } *SquareMtx; typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data); SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data ) { SquareMtx sm = malloc(sizeof(struct squareMtxStruct)); if (sm) { int rw; sm->dim = dim; sm->cells = malloc(dim*dim * sizeof(double)); sm->m = malloc( dim * sizeof(double *)); if ((sm->cells != NULL) && (sm->m != NULL)) { for (rw=0; rw<dim; rw++) { sm->m[rw] = sm->cells + dim*rw; fillFunc( sm->m[rw], rw, dim, ff_data ); } } else { free(sm->m); free(sm->cells); free(sm); printf("Square Matrix allocation failure\n"); return NULL; } } else { printf("Malloc failed for square matrix\n"); } return sm; } void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 ) { int col, ix; double sum; double *m0rw = m0->m[rw]; for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * m0->m[ix][col]; cells[col] = sum; } } void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] ) { SquareMtx mleft = mplcnds[0]; SquareMtx mrigt = mplcnds[1]; double sum; double *m0rw = mleft->m[rw]; int col, ix; for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * mrigt->m[ix][col]; cells[col] = sum; } } void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt) { int rw; SquareMtx mplcnds[2]; mplcnds[0] = left; mplcnds[1] = rigt; for (rw = 0; rw < left->dim; rw++) ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds); } void ffIdentity( double *cells, int rw, int dim, void *v ) { int col; for (col=0; col<dim; col++) cells[col] = 0.0; cells[rw] = 1.0; } void ffCopy(double *cells, int rw, int dim, SquareMtx m1) { int col; for (col=0; col<dim; col++) cells[col] = m1->m[rw][col]; } void FreeSquareMtx( SquareMtx m ) { free(m->m); free(m->cells); free(m); } SquareMtx SquareMtxPow( SquareMtx m0, int exp ) { SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL); SquareMtx v1 = NULL; SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0); SquareMtx base1 = NULL; SquareMtx mplcnds[2], t; while (exp) { if (exp % 2) { if (v1) MatxMul( v1, v0, base0); else { mplcnds[0] = v0; mplcnds[1] = base0; v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds); } {t = v0; v0=v1; v1 = t;} } if (base1) MatxMul( base1, base0, base0); else base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0); t = base0; base0 = base1; base1 = t; exp = exp/2; } if (base0) FreeSquareMtx(base0); if (base1) FreeSquareMtx(base1); if (v1) FreeSquareMtx(v1); return v0; } FILE *fout; void SquareMtxPrint( SquareMtx mtx, const char *mn ) { int rw, col; int d = mtx->dim; fprintf(fout, "%s dim:%d =\n", mn, mtx->dim); for (rw=0; rw<d; rw++) { fprintf(fout, " |"); for(col=0; col<d; col++) fprintf(fout, "%8.5f ",mtx->m[rw][col] ); fprintf(fout, " |\n"); } fprintf(fout, "\n"); } void fillInit( double *cells, int rw, int dim, void *data) { double theta = 3.1415926536/6.0; double c1 = cos( theta); double s1 = sin( theta); switch(rw) { case 0: cells[0]=c1; cells[1]=s1; cells[2]=0.0; break; case 1: cells[0]=-s1; cells[1]=c1; cells[2]=0; break; case 2: cells[0]=0.0; cells[1]=0.0; cells[2]=1.0; break; } } int main() { SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL); SquareMtx m1 = SquareMtxPow( m0, 5); SquareMtx m2 = SquareMtxPow( m0, 9); SquareMtx m3 = SquareMtxPow( m0, 2); fout = fopen("matrx_exp.txt", "w"); SquareMtxPrint(m0, "m0"); FreeSquareMtx(m0); SquareMtxPrint(m1, "m0^5"); FreeSquareMtx(m1); SquareMtxPrint(m2, "m0^9"); FreeSquareMtx(m2); SquareMtxPrint(m3, "m0^2"); FreeSquareMtx(m3); fclose(fout); return 0; }
Port the following code from Perl to C# with equivalent syntax and logic.
use strict; package SquareMatrix; use Carp; use overload ( '""' => \&_string, '*' => \&_mult, '*=' => \&_mult, '**' => \&_expo, '=' => \&_copy, ); sub make { my $cls = shift; my $n = @_; for (@_) { confess "Bad data @$_: matrix must be square " if @$_ != $n; } bless [ map [@$_], @_ ] } sub identity { my $self = shift; my $n = @$self - 1; my @rows = map [ (0) x $_, 1, (0) x ($n - $_) ], 0 .. $n; bless \@rows } sub zero { my $self = shift; my $n = @$self; bless [ map [ (0) x $n ], 1 .. $n ] } sub _string { "[ ".join("\n " => map join(" " => map(sprintf("%12.6g", $_), @$_)), @{+shift} )." ]\n"; } sub _mult { my ($a, $b) = @_; my $x = $a->zero; my @idx = (0 .. $ for my $j (@idx) { my @col = map($a->[$_][$j], @idx); for my $i (@idx) { my $row = $b->[$i]; $x->[$i][$j] += $row->[$_] * $col[$_] for @idx; } } $x } sub _expo { my ($self, $n) = @_; confess "matrix **: must be non-negative integer power" unless $n >= 0 && $n == int($n); my ($tmp, $out) = ($self, $self->identity); do { $out *= $tmp if $n & 1; $tmp *= $tmp; } while $n >>= 1; $out } sub _copy { bless [ map [ @$_ ], @{+shift} ] } package main; my $m = SquareMatrix->make( [1, 2, 0], [0, 3, 1], [1, 0, 0] ); print " $m = SquareMatrix->make( [ 1.0001, 0, 0, 1 ], [ 0, 1.001, 0, 0 ], [ 0, 0, 1, 0.99998 ], [ 1e-8, 0, 0, 1.0002 ]); print "\n print "\n print "\n print "\n print "\n $m->identity ** 1_000_000_000_000;
using System; using System.Collections; using System.Collections.Generic; using static System.Linq.Enumerable; public static class MatrixExponentation { public static double[,] Identity(int size) { double[,] matrix = new double[size, size]; for (int i = 0; i < size; i++) matrix[i, i] = 1; return matrix; } public static double[,] Multiply(this double[,] left, double[,] right) { if (left.ColumnCount() != right.RowCount()) throw new ArgumentException(); double[,] m = new double[left.RowCount(), right.ColumnCount()]; foreach (var (row, column) in from r in Range(0, m.RowCount()) from c in Range(0, m.ColumnCount()) select (r, c)) { m[row, column] = Range(0, m.RowCount()).Sum(i => left[row, i] * right[i, column]); } return m; } public static double[,] Pow(this double[,] matrix, int exp) { if (matrix.RowCount() != matrix.ColumnCount()) throw new ArgumentException("Matrix must be square."); double[,] accumulator = Identity(matrix.RowCount()); for (int i = 0; i < exp; i++) { accumulator = accumulator.Multiply(matrix); } return accumulator; } private static int RowCount(this double[,] matrix) => matrix.GetLength(0); private static int ColumnCount(this double[,] matrix) => matrix.GetLength(1); private static void Print(this double[,] m) { foreach (var row in Rows()) { Console.WriteLine("[ " + string.Join(" ", row) + " ]"); } Console.WriteLine(); IEnumerable<IEnumerable<double>> Rows() => Range(0, m.RowCount()).Select(row => Range(0, m.ColumnCount()).Select(column => m[row, column])); } public static void Main() { var matrix = new double[,] { { 3, 2 }, { 2, 1 } }; matrix.Pow(0).Print(); matrix.Pow(1).Print(); matrix.Pow(2).Print(); matrix.Pow(3).Print(); matrix.Pow(4).Print(); matrix.Pow(50).Print(); } }
Maintain the same structure and functionality when rewriting this code in C++.
use strict; package SquareMatrix; use Carp; use overload ( '""' => \&_string, '*' => \&_mult, '*=' => \&_mult, '**' => \&_expo, '=' => \&_copy, ); sub make { my $cls = shift; my $n = @_; for (@_) { confess "Bad data @$_: matrix must be square " if @$_ != $n; } bless [ map [@$_], @_ ] } sub identity { my $self = shift; my $n = @$self - 1; my @rows = map [ (0) x $_, 1, (0) x ($n - $_) ], 0 .. $n; bless \@rows } sub zero { my $self = shift; my $n = @$self; bless [ map [ (0) x $n ], 1 .. $n ] } sub _string { "[ ".join("\n " => map join(" " => map(sprintf("%12.6g", $_), @$_)), @{+shift} )." ]\n"; } sub _mult { my ($a, $b) = @_; my $x = $a->zero; my @idx = (0 .. $ for my $j (@idx) { my @col = map($a->[$_][$j], @idx); for my $i (@idx) { my $row = $b->[$i]; $x->[$i][$j] += $row->[$_] * $col[$_] for @idx; } } $x } sub _expo { my ($self, $n) = @_; confess "matrix **: must be non-negative integer power" unless $n >= 0 && $n == int($n); my ($tmp, $out) = ($self, $self->identity); do { $out *= $tmp if $n & 1; $tmp *= $tmp; } while $n >>= 1; $out } sub _copy { bless [ map [ @$_ ], @{+shift} ] } package main; my $m = SquareMatrix->make( [1, 2, 0], [0, 3, 1], [1, 0, 0] ); print " $m = SquareMatrix->make( [ 1.0001, 0, 0, 1 ], [ 0, 1.001, 0, 0 ], [ 0, 0, 1, 0.99998 ], [ 1e-8, 0, 0, 1.0002 ]); print "\n print "\n print "\n print "\n print "\n $m->identity ** 1_000_000_000_000;
#include <complex> #include <cmath> #include <iostream> using namespace std; template<int MSize = 3, class T = complex<double> > class SqMx { typedef T Ax[MSize][MSize]; typedef SqMx<MSize, T> Mx; private: Ax a; SqMx() { } public: SqMx(const Ax &_a) { for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) a[r][c] = _a[r][c]; } static Mx identity() { Mx m; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) m.a[r][c] = (r == c ? 1 : 0); return m; } friend ostream &operator<<(ostream& os, const Mx &p) { for (int i = 0; i < MSize; i++) { for (int j = 0; j < MSize; j++) os << p.a[i][j] << ','; os << endl; } return os; } Mx operator*(const Mx &b) { Mx d; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) { d.a[r][c] = 0; for (int k = 0; k < MSize; k++) d.a[r][c] += a[r][k] * b.a[k][c]; } return d; }
Ensure the translated Python code behaves exactly like the original Perl snippet.
use strict; package SquareMatrix; use Carp; use overload ( '""' => \&_string, '*' => \&_mult, '*=' => \&_mult, '**' => \&_expo, '=' => \&_copy, ); sub make { my $cls = shift; my $n = @_; for (@_) { confess "Bad data @$_: matrix must be square " if @$_ != $n; } bless [ map [@$_], @_ ] } sub identity { my $self = shift; my $n = @$self - 1; my @rows = map [ (0) x $_, 1, (0) x ($n - $_) ], 0 .. $n; bless \@rows } sub zero { my $self = shift; my $n = @$self; bless [ map [ (0) x $n ], 1 .. $n ] } sub _string { "[ ".join("\n " => map join(" " => map(sprintf("%12.6g", $_), @$_)), @{+shift} )." ]\n"; } sub _mult { my ($a, $b) = @_; my $x = $a->zero; my @idx = (0 .. $ for my $j (@idx) { my @col = map($a->[$_][$j], @idx); for my $i (@idx) { my $row = $b->[$i]; $x->[$i][$j] += $row->[$_] * $col[$_] for @idx; } } $x } sub _expo { my ($self, $n) = @_; confess "matrix **: must be non-negative integer power" unless $n >= 0 && $n == int($n); my ($tmp, $out) = ($self, $self->identity); do { $out *= $tmp if $n & 1; $tmp *= $tmp; } while $n >>= 1; $out } sub _copy { bless [ map [ @$_ ], @{+shift} ] } package main; my $m = SquareMatrix->make( [1, 2, 0], [0, 3, 1], [1, 0, 0] ); print " $m = SquareMatrix->make( [ 1.0001, 0, 0, 1 ], [ 0, 1.001, 0, 0 ], [ 0, 0, 1, 0.99998 ], [ 1e-8, 0, 0, 1.0002 ]); print "\n print "\n print "\n print "\n print "\n $m->identity ** 1_000_000_000_000;
>>> from operator import mul >>> def matrixMul(m1, m2): return map( lambda row: map( lambda *column: sum(map(mul, row, column)), *m2), m1) >>> def identity(size): size = range(size) return [[(i==j)*1 for i in size] for j in size] >>> def matrixExp(m, pow): assert pow>=0 and int(pow)==pow, "Only non-negative, integer powers allowed" accumulator = identity(len(m)) for i in range(pow): accumulator = matrixMul(accumulator, m) return accumulator >>> def printtable(data): for row in data: print ' '.join('%-5s' % ('%s' % cell) for cell in row) >>> m = [[3,2], [2,1]] >>> for i in range(5): print '\n%i:' % i printtable( matrixExp(m, i) ) 0: 1 0 0 1 1: 3 2 2 1 2: 13 8 8 5 3: 55 34 34 21 4: 233 144 144 89 >>> printtable( matrixExp(m, 10) ) 1346269 832040 832040 514229 >>>
Convert this Perl block to VB, preserving its control flow and logic.
use strict; package SquareMatrix; use Carp; use overload ( '""' => \&_string, '*' => \&_mult, '*=' => \&_mult, '**' => \&_expo, '=' => \&_copy, ); sub make { my $cls = shift; my $n = @_; for (@_) { confess "Bad data @$_: matrix must be square " if @$_ != $n; } bless [ map [@$_], @_ ] } sub identity { my $self = shift; my $n = @$self - 1; my @rows = map [ (0) x $_, 1, (0) x ($n - $_) ], 0 .. $n; bless \@rows } sub zero { my $self = shift; my $n = @$self; bless [ map [ (0) x $n ], 1 .. $n ] } sub _string { "[ ".join("\n " => map join(" " => map(sprintf("%12.6g", $_), @$_)), @{+shift} )." ]\n"; } sub _mult { my ($a, $b) = @_; my $x = $a->zero; my @idx = (0 .. $ for my $j (@idx) { my @col = map($a->[$_][$j], @idx); for my $i (@idx) { my $row = $b->[$i]; $x->[$i][$j] += $row->[$_] * $col[$_] for @idx; } } $x } sub _expo { my ($self, $n) = @_; confess "matrix **: must be non-negative integer power" unless $n >= 0 && $n == int($n); my ($tmp, $out) = ($self, $self->identity); do { $out *= $tmp if $n & 1; $tmp *= $tmp; } while $n >>= 1; $out } sub _copy { bless [ map [ @$_ ], @{+shift} ] } package main; my $m = SquareMatrix->make( [1, 2, 0], [0, 3, 1], [1, 0, 0] ); print " $m = SquareMatrix->make( [ 1.0001, 0, 0, 1 ], [ 0, 1.001, 0, 0 ], [ 0, 0, 1, 0.99998 ], [ 1e-8, 0, 0, 1.0002 ]); print "\n print "\n print "\n print "\n print "\n $m->identity ** 1_000_000_000_000;
Option Base 1 Private Function Identity(n As Integer) As Variant Dim I() As Variant ReDim I(n, n) For j = 1 To n For k = 1 To n I(j, k) = 0 Next k Next j For j = 1 To n I(j, j) = 1 Next j Identity = I End Function Function MatrixExponentiation(ByVal x As Variant, ByVal n As Integer) As Variant If n < 0 Then x = WorksheetFunction.MInverse(x) n = -n End If If n = 0 Then MatrixExponentiation = Identity(UBound(x)) Exit Function End If Dim y() As Variant y = Identity(UBound(x)) Do While n > 1 If n Mod 2 = 0 Then x = WorksheetFunction.MMult(x, x) n = n / 2 Else y = WorksheetFunction.MMult(x, y) x = WorksheetFunction.MMult(x, x) n = (n - 1) / 2 End If Loop MatrixExponentiation = WorksheetFunction.MMult(x, y) End Function Public Sub pp(x As Variant) For i_ = 1 To UBound(x) For j_ = 1 To UBound(x) Debug.Print x(i_, j_), Next j_ Debug.Print Next i_ End Sub Public Sub main() M2 = [{3,2;2,1}] M3 = [{1,2,0;0,3,1;1,0,0}] pp MatrixExponentiation(M2, -1) Debug.Print pp MatrixExponentiation(M2, 0) Debug.Print pp MatrixExponentiation(M2, 10) Debug.Print pp MatrixExponentiation(M3, 10) End Sub
Keep all operations the same but rewrite the snippet in Go.
use strict; package SquareMatrix; use Carp; use overload ( '""' => \&_string, '*' => \&_mult, '*=' => \&_mult, '**' => \&_expo, '=' => \&_copy, ); sub make { my $cls = shift; my $n = @_; for (@_) { confess "Bad data @$_: matrix must be square " if @$_ != $n; } bless [ map [@$_], @_ ] } sub identity { my $self = shift; my $n = @$self - 1; my @rows = map [ (0) x $_, 1, (0) x ($n - $_) ], 0 .. $n; bless \@rows } sub zero { my $self = shift; my $n = @$self; bless [ map [ (0) x $n ], 1 .. $n ] } sub _string { "[ ".join("\n " => map join(" " => map(sprintf("%12.6g", $_), @$_)), @{+shift} )." ]\n"; } sub _mult { my ($a, $b) = @_; my $x = $a->zero; my @idx = (0 .. $ for my $j (@idx) { my @col = map($a->[$_][$j], @idx); for my $i (@idx) { my $row = $b->[$i]; $x->[$i][$j] += $row->[$_] * $col[$_] for @idx; } } $x } sub _expo { my ($self, $n) = @_; confess "matrix **: must be non-negative integer power" unless $n >= 0 && $n == int($n); my ($tmp, $out) = ($self, $self->identity); do { $out *= $tmp if $n & 1; $tmp *= $tmp; } while $n >>= 1; $out } sub _copy { bless [ map [ @$_ ], @{+shift} ] } package main; my $m = SquareMatrix->make( [1, 2, 0], [0, 3, 1], [1, 0, 0] ); print " $m = SquareMatrix->make( [ 1.0001, 0, 0, 1 ], [ 0, 1.001, 0, 0 ], [ 0, 0, 1, 0.99998 ], [ 1e-8, 0, 0, 1.0002 ]); print "\n print "\n print "\n print "\n print "\n $m->identity ** 1_000_000_000_000;
package main import "fmt" type vector = []float64 type matrix []vector func (m1 matrix) mul(m2 matrix) matrix { rows1, cols1 := len(m1), len(m1[0]) rows2, cols2 := len(m2), len(m2[0]) if cols1 != rows2 { panic("Matrices cannot be multiplied.") } result := make(matrix, rows1) for i := 0; i < rows1; i++ { result[i] = make(vector, cols2) for j := 0; j < cols2; j++ { for k := 0; k < rows2; k++ { result[i][j] += m1[i][k] * m2[k][j] } } } return result } func identityMatrix(n int) matrix { if n < 1 { panic("Size of identity matrix can't be less than 1") } ident := make(matrix, n) for i := 0; i < n; i++ { ident[i] = make(vector, n) ident[i][i] = 1 } return ident } func (m matrix) pow(n int) matrix { le := len(m) if le != len(m[0]) { panic("Not a square matrix") } switch { case n < 0: panic("Negative exponents not supported") case n == 0: return identityMatrix(le) case n == 1: return m } pow := identityMatrix(le) base := m e := n for e > 0 { if (e & 1) == 1 { pow = pow.mul(base) } e >>= 1 base = base.mul(base) } return pow } func main() { m := matrix{{3, 2}, {2, 1}} for i := 0; i <= 10; i++ { fmt.Println("** Power of", i, "**") fmt.Println(m.pow(i)) fmt.Println() } }
Convert this Racket snippet to C and keep its semantics consistent.
#lang racket (require math) (define a (matrix ((3 2) (2 1)))) (for ([i 11]) (printf "a^~a = ~s\n" i (matrix-expt a i))) (define (mpower M p) (cond [(= p 1) M] [(even? p) (mpower (matrix* M M) (/ p 2))] [else (matrix* M (mpower M (sub1 p)))])) (for ([i (in-range 1 11)]) (printf "a^~a = ~s\n" i (matrix-expt a i)))
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct squareMtxStruct { int dim; double *cells; double **m; } *SquareMtx; typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data); SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data ) { SquareMtx sm = malloc(sizeof(struct squareMtxStruct)); if (sm) { int rw; sm->dim = dim; sm->cells = malloc(dim*dim * sizeof(double)); sm->m = malloc( dim * sizeof(double *)); if ((sm->cells != NULL) && (sm->m != NULL)) { for (rw=0; rw<dim; rw++) { sm->m[rw] = sm->cells + dim*rw; fillFunc( sm->m[rw], rw, dim, ff_data ); } } else { free(sm->m); free(sm->cells); free(sm); printf("Square Matrix allocation failure\n"); return NULL; } } else { printf("Malloc failed for square matrix\n"); } return sm; } void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 ) { int col, ix; double sum; double *m0rw = m0->m[rw]; for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * m0->m[ix][col]; cells[col] = sum; } } void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] ) { SquareMtx mleft = mplcnds[0]; SquareMtx mrigt = mplcnds[1]; double sum; double *m0rw = mleft->m[rw]; int col, ix; for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * mrigt->m[ix][col]; cells[col] = sum; } } void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt) { int rw; SquareMtx mplcnds[2]; mplcnds[0] = left; mplcnds[1] = rigt; for (rw = 0; rw < left->dim; rw++) ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds); } void ffIdentity( double *cells, int rw, int dim, void *v ) { int col; for (col=0; col<dim; col++) cells[col] = 0.0; cells[rw] = 1.0; } void ffCopy(double *cells, int rw, int dim, SquareMtx m1) { int col; for (col=0; col<dim; col++) cells[col] = m1->m[rw][col]; } void FreeSquareMtx( SquareMtx m ) { free(m->m); free(m->cells); free(m); } SquareMtx SquareMtxPow( SquareMtx m0, int exp ) { SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL); SquareMtx v1 = NULL; SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0); SquareMtx base1 = NULL; SquareMtx mplcnds[2], t; while (exp) { if (exp % 2) { if (v1) MatxMul( v1, v0, base0); else { mplcnds[0] = v0; mplcnds[1] = base0; v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds); } {t = v0; v0=v1; v1 = t;} } if (base1) MatxMul( base1, base0, base0); else base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0); t = base0; base0 = base1; base1 = t; exp = exp/2; } if (base0) FreeSquareMtx(base0); if (base1) FreeSquareMtx(base1); if (v1) FreeSquareMtx(v1); return v0; } FILE *fout; void SquareMtxPrint( SquareMtx mtx, const char *mn ) { int rw, col; int d = mtx->dim; fprintf(fout, "%s dim:%d =\n", mn, mtx->dim); for (rw=0; rw<d; rw++) { fprintf(fout, " |"); for(col=0; col<d; col++) fprintf(fout, "%8.5f ",mtx->m[rw][col] ); fprintf(fout, " |\n"); } fprintf(fout, "\n"); } void fillInit( double *cells, int rw, int dim, void *data) { double theta = 3.1415926536/6.0; double c1 = cos( theta); double s1 = sin( theta); switch(rw) { case 0: cells[0]=c1; cells[1]=s1; cells[2]=0.0; break; case 1: cells[0]=-s1; cells[1]=c1; cells[2]=0; break; case 2: cells[0]=0.0; cells[1]=0.0; cells[2]=1.0; break; } } int main() { SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL); SquareMtx m1 = SquareMtxPow( m0, 5); SquareMtx m2 = SquareMtxPow( m0, 9); SquareMtx m3 = SquareMtxPow( m0, 2); fout = fopen("matrx_exp.txt", "w"); SquareMtxPrint(m0, "m0"); FreeSquareMtx(m0); SquareMtxPrint(m1, "m0^5"); FreeSquareMtx(m1); SquareMtxPrint(m2, "m0^9"); FreeSquareMtx(m2); SquareMtxPrint(m3, "m0^2"); FreeSquareMtx(m3); fclose(fout); return 0; }
Convert this Racket block to C#, preserving its control flow and logic.
#lang racket (require math) (define a (matrix ((3 2) (2 1)))) (for ([i 11]) (printf "a^~a = ~s\n" i (matrix-expt a i))) (define (mpower M p) (cond [(= p 1) M] [(even? p) (mpower (matrix* M M) (/ p 2))] [else (matrix* M (mpower M (sub1 p)))])) (for ([i (in-range 1 11)]) (printf "a^~a = ~s\n" i (matrix-expt a i)))
using System; using System.Collections; using System.Collections.Generic; using static System.Linq.Enumerable; public static class MatrixExponentation { public static double[,] Identity(int size) { double[,] matrix = new double[size, size]; for (int i = 0; i < size; i++) matrix[i, i] = 1; return matrix; } public static double[,] Multiply(this double[,] left, double[,] right) { if (left.ColumnCount() != right.RowCount()) throw new ArgumentException(); double[,] m = new double[left.RowCount(), right.ColumnCount()]; foreach (var (row, column) in from r in Range(0, m.RowCount()) from c in Range(0, m.ColumnCount()) select (r, c)) { m[row, column] = Range(0, m.RowCount()).Sum(i => left[row, i] * right[i, column]); } return m; } public static double[,] Pow(this double[,] matrix, int exp) { if (matrix.RowCount() != matrix.ColumnCount()) throw new ArgumentException("Matrix must be square."); double[,] accumulator = Identity(matrix.RowCount()); for (int i = 0; i < exp; i++) { accumulator = accumulator.Multiply(matrix); } return accumulator; } private static int RowCount(this double[,] matrix) => matrix.GetLength(0); private static int ColumnCount(this double[,] matrix) => matrix.GetLength(1); private static void Print(this double[,] m) { foreach (var row in Rows()) { Console.WriteLine("[ " + string.Join(" ", row) + " ]"); } Console.WriteLine(); IEnumerable<IEnumerable<double>> Rows() => Range(0, m.RowCount()).Select(row => Range(0, m.ColumnCount()).Select(column => m[row, column])); } public static void Main() { var matrix = new double[,] { { 3, 2 }, { 2, 1 } }; matrix.Pow(0).Print(); matrix.Pow(1).Print(); matrix.Pow(2).Print(); matrix.Pow(3).Print(); matrix.Pow(4).Print(); matrix.Pow(50).Print(); } }
Convert the following code from Racket to C++, ensuring the logic remains intact.
#lang racket (require math) (define a (matrix ((3 2) (2 1)))) (for ([i 11]) (printf "a^~a = ~s\n" i (matrix-expt a i))) (define (mpower M p) (cond [(= p 1) M] [(even? p) (mpower (matrix* M M) (/ p 2))] [else (matrix* M (mpower M (sub1 p)))])) (for ([i (in-range 1 11)]) (printf "a^~a = ~s\n" i (matrix-expt a i)))
#include <complex> #include <cmath> #include <iostream> using namespace std; template<int MSize = 3, class T = complex<double> > class SqMx { typedef T Ax[MSize][MSize]; typedef SqMx<MSize, T> Mx; private: Ax a; SqMx() { } public: SqMx(const Ax &_a) { for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) a[r][c] = _a[r][c]; } static Mx identity() { Mx m; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) m.a[r][c] = (r == c ? 1 : 0); return m; } friend ostream &operator<<(ostream& os, const Mx &p) { for (int i = 0; i < MSize; i++) { for (int j = 0; j < MSize; j++) os << p.a[i][j] << ','; os << endl; } return os; } Mx operator*(const Mx &b) { Mx d; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) { d.a[r][c] = 0; for (int k = 0; k < MSize; k++) d.a[r][c] += a[r][k] * b.a[k][c]; } return d; }
Keep all operations the same but rewrite the snippet in Python.
#lang racket (require math) (define a (matrix ((3 2) (2 1)))) (for ([i 11]) (printf "a^~a = ~s\n" i (matrix-expt a i))) (define (mpower M p) (cond [(= p 1) M] [(even? p) (mpower (matrix* M M) (/ p 2))] [else (matrix* M (mpower M (sub1 p)))])) (for ([i (in-range 1 11)]) (printf "a^~a = ~s\n" i (matrix-expt a i)))
>>> from operator import mul >>> def matrixMul(m1, m2): return map( lambda row: map( lambda *column: sum(map(mul, row, column)), *m2), m1) >>> def identity(size): size = range(size) return [[(i==j)*1 for i in size] for j in size] >>> def matrixExp(m, pow): assert pow>=0 and int(pow)==pow, "Only non-negative, integer powers allowed" accumulator = identity(len(m)) for i in range(pow): accumulator = matrixMul(accumulator, m) return accumulator >>> def printtable(data): for row in data: print ' '.join('%-5s' % ('%s' % cell) for cell in row) >>> m = [[3,2], [2,1]] >>> for i in range(5): print '\n%i:' % i printtable( matrixExp(m, i) ) 0: 1 0 0 1 1: 3 2 2 1 2: 13 8 8 5 3: 55 34 34 21 4: 233 144 144 89 >>> printtable( matrixExp(m, 10) ) 1346269 832040 832040 514229 >>>
Translate the given Racket code snippet into VB without altering its behavior.
#lang racket (require math) (define a (matrix ((3 2) (2 1)))) (for ([i 11]) (printf "a^~a = ~s\n" i (matrix-expt a i))) (define (mpower M p) (cond [(= p 1) M] [(even? p) (mpower (matrix* M M) (/ p 2))] [else (matrix* M (mpower M (sub1 p)))])) (for ([i (in-range 1 11)]) (printf "a^~a = ~s\n" i (matrix-expt a i)))
Option Base 1 Private Function Identity(n As Integer) As Variant Dim I() As Variant ReDim I(n, n) For j = 1 To n For k = 1 To n I(j, k) = 0 Next k Next j For j = 1 To n I(j, j) = 1 Next j Identity = I End Function Function MatrixExponentiation(ByVal x As Variant, ByVal n As Integer) As Variant If n < 0 Then x = WorksheetFunction.MInverse(x) n = -n End If If n = 0 Then MatrixExponentiation = Identity(UBound(x)) Exit Function End If Dim y() As Variant y = Identity(UBound(x)) Do While n > 1 If n Mod 2 = 0 Then x = WorksheetFunction.MMult(x, x) n = n / 2 Else y = WorksheetFunction.MMult(x, y) x = WorksheetFunction.MMult(x, x) n = (n - 1) / 2 End If Loop MatrixExponentiation = WorksheetFunction.MMult(x, y) End Function Public Sub pp(x As Variant) For i_ = 1 To UBound(x) For j_ = 1 To UBound(x) Debug.Print x(i_, j_), Next j_ Debug.Print Next i_ End Sub Public Sub main() M2 = [{3,2;2,1}] M3 = [{1,2,0;0,3,1;1,0,0}] pp MatrixExponentiation(M2, -1) Debug.Print pp MatrixExponentiation(M2, 0) Debug.Print pp MatrixExponentiation(M2, 10) Debug.Print pp MatrixExponentiation(M3, 10) End Sub
Ensure the translated Go code behaves exactly like the original Racket snippet.
#lang racket (require math) (define a (matrix ((3 2) (2 1)))) (for ([i 11]) (printf "a^~a = ~s\n" i (matrix-expt a i))) (define (mpower M p) (cond [(= p 1) M] [(even? p) (mpower (matrix* M M) (/ p 2))] [else (matrix* M (mpower M (sub1 p)))])) (for ([i (in-range 1 11)]) (printf "a^~a = ~s\n" i (matrix-expt a i)))
package main import "fmt" type vector = []float64 type matrix []vector func (m1 matrix) mul(m2 matrix) matrix { rows1, cols1 := len(m1), len(m1[0]) rows2, cols2 := len(m2), len(m2[0]) if cols1 != rows2 { panic("Matrices cannot be multiplied.") } result := make(matrix, rows1) for i := 0; i < rows1; i++ { result[i] = make(vector, cols2) for j := 0; j < cols2; j++ { for k := 0; k < rows2; k++ { result[i][j] += m1[i][k] * m2[k][j] } } } return result } func identityMatrix(n int) matrix { if n < 1 { panic("Size of identity matrix can't be less than 1") } ident := make(matrix, n) for i := 0; i < n; i++ { ident[i] = make(vector, n) ident[i][i] = 1 } return ident } func (m matrix) pow(n int) matrix { le := len(m) if le != len(m[0]) { panic("Not a square matrix") } switch { case n < 0: panic("Negative exponents not supported") case n == 0: return identityMatrix(le) case n == 1: return m } pow := identityMatrix(le) base := m e := n for e > 0 { if (e & 1) == 1 { pow = pow.mul(base) } e >>= 1 base = base.mul(base) } return pow } func main() { m := matrix{{3, 2}, {2, 1}} for i := 0; i <= 10; i++ { fmt.Println("** Power of", i, "**") fmt.Println(m.pow(i)) fmt.Println() } }
Maintain the same structure and functionality when rewriting this code in C.
class Array { method ** (Number n { .>= 0 }) { var tmp = self var out = self.len.of {|i| self.len.of {|j| i == j ? 1 : 0 }} loop { out = (out `mmul` tmp) if n.is_odd n >>= 1 || break tmp = (tmp `mmul` tmp) } return out } } var m = [[1, 2, 0], [0, 3, 1], [1, 0, 0]] for order in (0..5) { say " var t = (m ** order) say (' ', t.join("\n ")) }
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct squareMtxStruct { int dim; double *cells; double **m; } *SquareMtx; typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data); SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data ) { SquareMtx sm = malloc(sizeof(struct squareMtxStruct)); if (sm) { int rw; sm->dim = dim; sm->cells = malloc(dim*dim * sizeof(double)); sm->m = malloc( dim * sizeof(double *)); if ((sm->cells != NULL) && (sm->m != NULL)) { for (rw=0; rw<dim; rw++) { sm->m[rw] = sm->cells + dim*rw; fillFunc( sm->m[rw], rw, dim, ff_data ); } } else { free(sm->m); free(sm->cells); free(sm); printf("Square Matrix allocation failure\n"); return NULL; } } else { printf("Malloc failed for square matrix\n"); } return sm; } void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 ) { int col, ix; double sum; double *m0rw = m0->m[rw]; for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * m0->m[ix][col]; cells[col] = sum; } } void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] ) { SquareMtx mleft = mplcnds[0]; SquareMtx mrigt = mplcnds[1]; double sum; double *m0rw = mleft->m[rw]; int col, ix; for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * mrigt->m[ix][col]; cells[col] = sum; } } void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt) { int rw; SquareMtx mplcnds[2]; mplcnds[0] = left; mplcnds[1] = rigt; for (rw = 0; rw < left->dim; rw++) ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds); } void ffIdentity( double *cells, int rw, int dim, void *v ) { int col; for (col=0; col<dim; col++) cells[col] = 0.0; cells[rw] = 1.0; } void ffCopy(double *cells, int rw, int dim, SquareMtx m1) { int col; for (col=0; col<dim; col++) cells[col] = m1->m[rw][col]; } void FreeSquareMtx( SquareMtx m ) { free(m->m); free(m->cells); free(m); } SquareMtx SquareMtxPow( SquareMtx m0, int exp ) { SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL); SquareMtx v1 = NULL; SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0); SquareMtx base1 = NULL; SquareMtx mplcnds[2], t; while (exp) { if (exp % 2) { if (v1) MatxMul( v1, v0, base0); else { mplcnds[0] = v0; mplcnds[1] = base0; v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds); } {t = v0; v0=v1; v1 = t;} } if (base1) MatxMul( base1, base0, base0); else base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0); t = base0; base0 = base1; base1 = t; exp = exp/2; } if (base0) FreeSquareMtx(base0); if (base1) FreeSquareMtx(base1); if (v1) FreeSquareMtx(v1); return v0; } FILE *fout; void SquareMtxPrint( SquareMtx mtx, const char *mn ) { int rw, col; int d = mtx->dim; fprintf(fout, "%s dim:%d =\n", mn, mtx->dim); for (rw=0; rw<d; rw++) { fprintf(fout, " |"); for(col=0; col<d; col++) fprintf(fout, "%8.5f ",mtx->m[rw][col] ); fprintf(fout, " |\n"); } fprintf(fout, "\n"); } void fillInit( double *cells, int rw, int dim, void *data) { double theta = 3.1415926536/6.0; double c1 = cos( theta); double s1 = sin( theta); switch(rw) { case 0: cells[0]=c1; cells[1]=s1; cells[2]=0.0; break; case 1: cells[0]=-s1; cells[1]=c1; cells[2]=0; break; case 2: cells[0]=0.0; cells[1]=0.0; cells[2]=1.0; break; } } int main() { SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL); SquareMtx m1 = SquareMtxPow( m0, 5); SquareMtx m2 = SquareMtxPow( m0, 9); SquareMtx m3 = SquareMtxPow( m0, 2); fout = fopen("matrx_exp.txt", "w"); SquareMtxPrint(m0, "m0"); FreeSquareMtx(m0); SquareMtxPrint(m1, "m0^5"); FreeSquareMtx(m1); SquareMtxPrint(m2, "m0^9"); FreeSquareMtx(m2); SquareMtxPrint(m3, "m0^2"); FreeSquareMtx(m3); fclose(fout); return 0; }
Produce a language-to-language conversion: from Ruby to C#, same semantics.
class Array { method ** (Number n { .>= 0 }) { var tmp = self var out = self.len.of {|i| self.len.of {|j| i == j ? 1 : 0 }} loop { out = (out `mmul` tmp) if n.is_odd n >>= 1 || break tmp = (tmp `mmul` tmp) } return out } } var m = [[1, 2, 0], [0, 3, 1], [1, 0, 0]] for order in (0..5) { say " var t = (m ** order) say (' ', t.join("\n ")) }
using System; using System.Collections; using System.Collections.Generic; using static System.Linq.Enumerable; public static class MatrixExponentation { public static double[,] Identity(int size) { double[,] matrix = new double[size, size]; for (int i = 0; i < size; i++) matrix[i, i] = 1; return matrix; } public static double[,] Multiply(this double[,] left, double[,] right) { if (left.ColumnCount() != right.RowCount()) throw new ArgumentException(); double[,] m = new double[left.RowCount(), right.ColumnCount()]; foreach (var (row, column) in from r in Range(0, m.RowCount()) from c in Range(0, m.ColumnCount()) select (r, c)) { m[row, column] = Range(0, m.RowCount()).Sum(i => left[row, i] * right[i, column]); } return m; } public static double[,] Pow(this double[,] matrix, int exp) { if (matrix.RowCount() != matrix.ColumnCount()) throw new ArgumentException("Matrix must be square."); double[,] accumulator = Identity(matrix.RowCount()); for (int i = 0; i < exp; i++) { accumulator = accumulator.Multiply(matrix); } return accumulator; } private static int RowCount(this double[,] matrix) => matrix.GetLength(0); private static int ColumnCount(this double[,] matrix) => matrix.GetLength(1); private static void Print(this double[,] m) { foreach (var row in Rows()) { Console.WriteLine("[ " + string.Join(" ", row) + " ]"); } Console.WriteLine(); IEnumerable<IEnumerable<double>> Rows() => Range(0, m.RowCount()).Select(row => Range(0, m.ColumnCount()).Select(column => m[row, column])); } public static void Main() { var matrix = new double[,] { { 3, 2 }, { 2, 1 } }; matrix.Pow(0).Print(); matrix.Pow(1).Print(); matrix.Pow(2).Print(); matrix.Pow(3).Print(); matrix.Pow(4).Print(); matrix.Pow(50).Print(); } }
Please provide an equivalent version of this Ruby code in C++.
class Array { method ** (Number n { .>= 0 }) { var tmp = self var out = self.len.of {|i| self.len.of {|j| i == j ? 1 : 0 }} loop { out = (out `mmul` tmp) if n.is_odd n >>= 1 || break tmp = (tmp `mmul` tmp) } return out } } var m = [[1, 2, 0], [0, 3, 1], [1, 0, 0]] for order in (0..5) { say " var t = (m ** order) say (' ', t.join("\n ")) }
#include <complex> #include <cmath> #include <iostream> using namespace std; template<int MSize = 3, class T = complex<double> > class SqMx { typedef T Ax[MSize][MSize]; typedef SqMx<MSize, T> Mx; private: Ax a; SqMx() { } public: SqMx(const Ax &_a) { for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) a[r][c] = _a[r][c]; } static Mx identity() { Mx m; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) m.a[r][c] = (r == c ? 1 : 0); return m; } friend ostream &operator<<(ostream& os, const Mx &p) { for (int i = 0; i < MSize; i++) { for (int j = 0; j < MSize; j++) os << p.a[i][j] << ','; os << endl; } return os; } Mx operator*(const Mx &b) { Mx d; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) { d.a[r][c] = 0; for (int k = 0; k < MSize; k++) d.a[r][c] += a[r][k] * b.a[k][c]; } return d; }
Produce a functionally identical Python code for the snippet given in Ruby.
class Array { method ** (Number n { .>= 0 }) { var tmp = self var out = self.len.of {|i| self.len.of {|j| i == j ? 1 : 0 }} loop { out = (out `mmul` tmp) if n.is_odd n >>= 1 || break tmp = (tmp `mmul` tmp) } return out } } var m = [[1, 2, 0], [0, 3, 1], [1, 0, 0]] for order in (0..5) { say " var t = (m ** order) say (' ', t.join("\n ")) }
>>> from operator import mul >>> def matrixMul(m1, m2): return map( lambda row: map( lambda *column: sum(map(mul, row, column)), *m2), m1) >>> def identity(size): size = range(size) return [[(i==j)*1 for i in size] for j in size] >>> def matrixExp(m, pow): assert pow>=0 and int(pow)==pow, "Only non-negative, integer powers allowed" accumulator = identity(len(m)) for i in range(pow): accumulator = matrixMul(accumulator, m) return accumulator >>> def printtable(data): for row in data: print ' '.join('%-5s' % ('%s' % cell) for cell in row) >>> m = [[3,2], [2,1]] >>> for i in range(5): print '\n%i:' % i printtable( matrixExp(m, i) ) 0: 1 0 0 1 1: 3 2 2 1 2: 13 8 8 5 3: 55 34 34 21 4: 233 144 144 89 >>> printtable( matrixExp(m, 10) ) 1346269 832040 832040 514229 >>>
Preserve the algorithm and functionality while converting the code from Ruby to VB.
class Array { method ** (Number n { .>= 0 }) { var tmp = self var out = self.len.of {|i| self.len.of {|j| i == j ? 1 : 0 }} loop { out = (out `mmul` tmp) if n.is_odd n >>= 1 || break tmp = (tmp `mmul` tmp) } return out } } var m = [[1, 2, 0], [0, 3, 1], [1, 0, 0]] for order in (0..5) { say " var t = (m ** order) say (' ', t.join("\n ")) }
Option Base 1 Private Function Identity(n As Integer) As Variant Dim I() As Variant ReDim I(n, n) For j = 1 To n For k = 1 To n I(j, k) = 0 Next k Next j For j = 1 To n I(j, j) = 1 Next j Identity = I End Function Function MatrixExponentiation(ByVal x As Variant, ByVal n As Integer) As Variant If n < 0 Then x = WorksheetFunction.MInverse(x) n = -n End If If n = 0 Then MatrixExponentiation = Identity(UBound(x)) Exit Function End If Dim y() As Variant y = Identity(UBound(x)) Do While n > 1 If n Mod 2 = 0 Then x = WorksheetFunction.MMult(x, x) n = n / 2 Else y = WorksheetFunction.MMult(x, y) x = WorksheetFunction.MMult(x, x) n = (n - 1) / 2 End If Loop MatrixExponentiation = WorksheetFunction.MMult(x, y) End Function Public Sub pp(x As Variant) For i_ = 1 To UBound(x) For j_ = 1 To UBound(x) Debug.Print x(i_, j_), Next j_ Debug.Print Next i_ End Sub Public Sub main() M2 = [{3,2;2,1}] M3 = [{1,2,0;0,3,1;1,0,0}] pp MatrixExponentiation(M2, -1) Debug.Print pp MatrixExponentiation(M2, 0) Debug.Print pp MatrixExponentiation(M2, 10) Debug.Print pp MatrixExponentiation(M3, 10) End Sub
Generate a Go translation of this Ruby snippet without changing its computational steps.
class Array { method ** (Number n { .>= 0 }) { var tmp = self var out = self.len.of {|i| self.len.of {|j| i == j ? 1 : 0 }} loop { out = (out `mmul` tmp) if n.is_odd n >>= 1 || break tmp = (tmp `mmul` tmp) } return out } } var m = [[1, 2, 0], [0, 3, 1], [1, 0, 0]] for order in (0..5) { say " var t = (m ** order) say (' ', t.join("\n ")) }
package main import "fmt" type vector = []float64 type matrix []vector func (m1 matrix) mul(m2 matrix) matrix { rows1, cols1 := len(m1), len(m1[0]) rows2, cols2 := len(m2), len(m2[0]) if cols1 != rows2 { panic("Matrices cannot be multiplied.") } result := make(matrix, rows1) for i := 0; i < rows1; i++ { result[i] = make(vector, cols2) for j := 0; j < cols2; j++ { for k := 0; k < rows2; k++ { result[i][j] += m1[i][k] * m2[k][j] } } } return result } func identityMatrix(n int) matrix { if n < 1 { panic("Size of identity matrix can't be less than 1") } ident := make(matrix, n) for i := 0; i < n; i++ { ident[i] = make(vector, n) ident[i][i] = 1 } return ident } func (m matrix) pow(n int) matrix { le := len(m) if le != len(m[0]) { panic("Not a square matrix") } switch { case n < 0: panic("Negative exponents not supported") case n == 0: return identityMatrix(le) case n == 1: return m } pow := identityMatrix(le) base := m e := n for e > 0 { if (e & 1) == 1 { pow = pow.mul(base) } e >>= 1 base = base.mul(base) } return pow } func main() { m := matrix{{3, 2}, {2, 1}} for i := 0; i <= 10; i++ { fmt.Println("** Power of", i, "**") fmt.Println(m.pow(i)) fmt.Println() } }
Change the programming language of this snippet from Scala to C without modifying what it does.
typealias Vector = DoubleArray typealias Matrix = Array<Vector> operator fun Matrix.times(other: Matrix): Matrix { val rows1 = this.size val cols1 = this[0].size val rows2 = other.size val cols2 = other[0].size require(cols1 == rows2) val result = Matrix(rows1) { Vector(cols2) } for (i in 0 until rows1) { for (j in 0 until cols2) { for (k in 0 until rows2) { result[i][j] += this[i][k] * other[k][j] } } } return result } fun identityMatrix(n: Int): Matrix { require(n >= 1) val ident = Matrix(n) { Vector(n) } for (i in 0 until n) ident[i][i] = 1.0 return ident } infix fun Matrix.pow(n : Int): Matrix { require (n >= 0 && this.size == this[0].size) if (n == 0) return identityMatrix(this.size) if (n == 1) return this var pow = identityMatrix(this.size) var base = this var e = n while (e > 0) { if ((e and 1) == 1) pow *= base e = e shr 1 base *= base } return pow } fun printMatrix(m: Matrix, n: Int) { println("** Power of $n **") for (i in 0 until m.size) println(m[i].contentToString()) println() } fun main(args: Array<String>) { val m = arrayOf( doubleArrayOf(3.0, 2.0), doubleArrayOf(2.0, 1.0) ) for (i in 0..10) printMatrix(m pow i, i) }
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct squareMtxStruct { int dim; double *cells; double **m; } *SquareMtx; typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data); SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data ) { SquareMtx sm = malloc(sizeof(struct squareMtxStruct)); if (sm) { int rw; sm->dim = dim; sm->cells = malloc(dim*dim * sizeof(double)); sm->m = malloc( dim * sizeof(double *)); if ((sm->cells != NULL) && (sm->m != NULL)) { for (rw=0; rw<dim; rw++) { sm->m[rw] = sm->cells + dim*rw; fillFunc( sm->m[rw], rw, dim, ff_data ); } } else { free(sm->m); free(sm->cells); free(sm); printf("Square Matrix allocation failure\n"); return NULL; } } else { printf("Malloc failed for square matrix\n"); } return sm; } void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 ) { int col, ix; double sum; double *m0rw = m0->m[rw]; for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * m0->m[ix][col]; cells[col] = sum; } } void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] ) { SquareMtx mleft = mplcnds[0]; SquareMtx mrigt = mplcnds[1]; double sum; double *m0rw = mleft->m[rw]; int col, ix; for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * mrigt->m[ix][col]; cells[col] = sum; } } void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt) { int rw; SquareMtx mplcnds[2]; mplcnds[0] = left; mplcnds[1] = rigt; for (rw = 0; rw < left->dim; rw++) ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds); } void ffIdentity( double *cells, int rw, int dim, void *v ) { int col; for (col=0; col<dim; col++) cells[col] = 0.0; cells[rw] = 1.0; } void ffCopy(double *cells, int rw, int dim, SquareMtx m1) { int col; for (col=0; col<dim; col++) cells[col] = m1->m[rw][col]; } void FreeSquareMtx( SquareMtx m ) { free(m->m); free(m->cells); free(m); } SquareMtx SquareMtxPow( SquareMtx m0, int exp ) { SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL); SquareMtx v1 = NULL; SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0); SquareMtx base1 = NULL; SquareMtx mplcnds[2], t; while (exp) { if (exp % 2) { if (v1) MatxMul( v1, v0, base0); else { mplcnds[0] = v0; mplcnds[1] = base0; v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds); } {t = v0; v0=v1; v1 = t;} } if (base1) MatxMul( base1, base0, base0); else base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0); t = base0; base0 = base1; base1 = t; exp = exp/2; } if (base0) FreeSquareMtx(base0); if (base1) FreeSquareMtx(base1); if (v1) FreeSquareMtx(v1); return v0; } FILE *fout; void SquareMtxPrint( SquareMtx mtx, const char *mn ) { int rw, col; int d = mtx->dim; fprintf(fout, "%s dim:%d =\n", mn, mtx->dim); for (rw=0; rw<d; rw++) { fprintf(fout, " |"); for(col=0; col<d; col++) fprintf(fout, "%8.5f ",mtx->m[rw][col] ); fprintf(fout, " |\n"); } fprintf(fout, "\n"); } void fillInit( double *cells, int rw, int dim, void *data) { double theta = 3.1415926536/6.0; double c1 = cos( theta); double s1 = sin( theta); switch(rw) { case 0: cells[0]=c1; cells[1]=s1; cells[2]=0.0; break; case 1: cells[0]=-s1; cells[1]=c1; cells[2]=0; break; case 2: cells[0]=0.0; cells[1]=0.0; cells[2]=1.0; break; } } int main() { SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL); SquareMtx m1 = SquareMtxPow( m0, 5); SquareMtx m2 = SquareMtxPow( m0, 9); SquareMtx m3 = SquareMtxPow( m0, 2); fout = fopen("matrx_exp.txt", "w"); SquareMtxPrint(m0, "m0"); FreeSquareMtx(m0); SquareMtxPrint(m1, "m0^5"); FreeSquareMtx(m1); SquareMtxPrint(m2, "m0^9"); FreeSquareMtx(m2); SquareMtxPrint(m3, "m0^2"); FreeSquareMtx(m3); fclose(fout); return 0; }
Write the same algorithm in C# as shown in this Scala implementation.
typealias Vector = DoubleArray typealias Matrix = Array<Vector> operator fun Matrix.times(other: Matrix): Matrix { val rows1 = this.size val cols1 = this[0].size val rows2 = other.size val cols2 = other[0].size require(cols1 == rows2) val result = Matrix(rows1) { Vector(cols2) } for (i in 0 until rows1) { for (j in 0 until cols2) { for (k in 0 until rows2) { result[i][j] += this[i][k] * other[k][j] } } } return result } fun identityMatrix(n: Int): Matrix { require(n >= 1) val ident = Matrix(n) { Vector(n) } for (i in 0 until n) ident[i][i] = 1.0 return ident } infix fun Matrix.pow(n : Int): Matrix { require (n >= 0 && this.size == this[0].size) if (n == 0) return identityMatrix(this.size) if (n == 1) return this var pow = identityMatrix(this.size) var base = this var e = n while (e > 0) { if ((e and 1) == 1) pow *= base e = e shr 1 base *= base } return pow } fun printMatrix(m: Matrix, n: Int) { println("** Power of $n **") for (i in 0 until m.size) println(m[i].contentToString()) println() } fun main(args: Array<String>) { val m = arrayOf( doubleArrayOf(3.0, 2.0), doubleArrayOf(2.0, 1.0) ) for (i in 0..10) printMatrix(m pow i, i) }
using System; using System.Collections; using System.Collections.Generic; using static System.Linq.Enumerable; public static class MatrixExponentation { public static double[,] Identity(int size) { double[,] matrix = new double[size, size]; for (int i = 0; i < size; i++) matrix[i, i] = 1; return matrix; } public static double[,] Multiply(this double[,] left, double[,] right) { if (left.ColumnCount() != right.RowCount()) throw new ArgumentException(); double[,] m = new double[left.RowCount(), right.ColumnCount()]; foreach (var (row, column) in from r in Range(0, m.RowCount()) from c in Range(0, m.ColumnCount()) select (r, c)) { m[row, column] = Range(0, m.RowCount()).Sum(i => left[row, i] * right[i, column]); } return m; } public static double[,] Pow(this double[,] matrix, int exp) { if (matrix.RowCount() != matrix.ColumnCount()) throw new ArgumentException("Matrix must be square."); double[,] accumulator = Identity(matrix.RowCount()); for (int i = 0; i < exp; i++) { accumulator = accumulator.Multiply(matrix); } return accumulator; } private static int RowCount(this double[,] matrix) => matrix.GetLength(0); private static int ColumnCount(this double[,] matrix) => matrix.GetLength(1); private static void Print(this double[,] m) { foreach (var row in Rows()) { Console.WriteLine("[ " + string.Join(" ", row) + " ]"); } Console.WriteLine(); IEnumerable<IEnumerable<double>> Rows() => Range(0, m.RowCount()).Select(row => Range(0, m.ColumnCount()).Select(column => m[row, column])); } public static void Main() { var matrix = new double[,] { { 3, 2 }, { 2, 1 } }; matrix.Pow(0).Print(); matrix.Pow(1).Print(); matrix.Pow(2).Print(); matrix.Pow(3).Print(); matrix.Pow(4).Print(); matrix.Pow(50).Print(); } }
Transform the following Scala implementation into C++, maintaining the same output and logic.
typealias Vector = DoubleArray typealias Matrix = Array<Vector> operator fun Matrix.times(other: Matrix): Matrix { val rows1 = this.size val cols1 = this[0].size val rows2 = other.size val cols2 = other[0].size require(cols1 == rows2) val result = Matrix(rows1) { Vector(cols2) } for (i in 0 until rows1) { for (j in 0 until cols2) { for (k in 0 until rows2) { result[i][j] += this[i][k] * other[k][j] } } } return result } fun identityMatrix(n: Int): Matrix { require(n >= 1) val ident = Matrix(n) { Vector(n) } for (i in 0 until n) ident[i][i] = 1.0 return ident } infix fun Matrix.pow(n : Int): Matrix { require (n >= 0 && this.size == this[0].size) if (n == 0) return identityMatrix(this.size) if (n == 1) return this var pow = identityMatrix(this.size) var base = this var e = n while (e > 0) { if ((e and 1) == 1) pow *= base e = e shr 1 base *= base } return pow } fun printMatrix(m: Matrix, n: Int) { println("** Power of $n **") for (i in 0 until m.size) println(m[i].contentToString()) println() } fun main(args: Array<String>) { val m = arrayOf( doubleArrayOf(3.0, 2.0), doubleArrayOf(2.0, 1.0) ) for (i in 0..10) printMatrix(m pow i, i) }
#include <complex> #include <cmath> #include <iostream> using namespace std; template<int MSize = 3, class T = complex<double> > class SqMx { typedef T Ax[MSize][MSize]; typedef SqMx<MSize, T> Mx; private: Ax a; SqMx() { } public: SqMx(const Ax &_a) { for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) a[r][c] = _a[r][c]; } static Mx identity() { Mx m; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) m.a[r][c] = (r == c ? 1 : 0); return m; } friend ostream &operator<<(ostream& os, const Mx &p) { for (int i = 0; i < MSize; i++) { for (int j = 0; j < MSize; j++) os << p.a[i][j] << ','; os << endl; } return os; } Mx operator*(const Mx &b) { Mx d; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) { d.a[r][c] = 0; for (int k = 0; k < MSize; k++) d.a[r][c] += a[r][k] * b.a[k][c]; } return d; }
Keep all operations the same but rewrite the snippet in Python.
typealias Vector = DoubleArray typealias Matrix = Array<Vector> operator fun Matrix.times(other: Matrix): Matrix { val rows1 = this.size val cols1 = this[0].size val rows2 = other.size val cols2 = other[0].size require(cols1 == rows2) val result = Matrix(rows1) { Vector(cols2) } for (i in 0 until rows1) { for (j in 0 until cols2) { for (k in 0 until rows2) { result[i][j] += this[i][k] * other[k][j] } } } return result } fun identityMatrix(n: Int): Matrix { require(n >= 1) val ident = Matrix(n) { Vector(n) } for (i in 0 until n) ident[i][i] = 1.0 return ident } infix fun Matrix.pow(n : Int): Matrix { require (n >= 0 && this.size == this[0].size) if (n == 0) return identityMatrix(this.size) if (n == 1) return this var pow = identityMatrix(this.size) var base = this var e = n while (e > 0) { if ((e and 1) == 1) pow *= base e = e shr 1 base *= base } return pow } fun printMatrix(m: Matrix, n: Int) { println("** Power of $n **") for (i in 0 until m.size) println(m[i].contentToString()) println() } fun main(args: Array<String>) { val m = arrayOf( doubleArrayOf(3.0, 2.0), doubleArrayOf(2.0, 1.0) ) for (i in 0..10) printMatrix(m pow i, i) }
>>> from operator import mul >>> def matrixMul(m1, m2): return map( lambda row: map( lambda *column: sum(map(mul, row, column)), *m2), m1) >>> def identity(size): size = range(size) return [[(i==j)*1 for i in size] for j in size] >>> def matrixExp(m, pow): assert pow>=0 and int(pow)==pow, "Only non-negative, integer powers allowed" accumulator = identity(len(m)) for i in range(pow): accumulator = matrixMul(accumulator, m) return accumulator >>> def printtable(data): for row in data: print ' '.join('%-5s' % ('%s' % cell) for cell in row) >>> m = [[3,2], [2,1]] >>> for i in range(5): print '\n%i:' % i printtable( matrixExp(m, i) ) 0: 1 0 0 1 1: 3 2 2 1 2: 13 8 8 5 3: 55 34 34 21 4: 233 144 144 89 >>> printtable( matrixExp(m, 10) ) 1346269 832040 832040 514229 >>>
Convert this Scala block to VB, preserving its control flow and logic.
typealias Vector = DoubleArray typealias Matrix = Array<Vector> operator fun Matrix.times(other: Matrix): Matrix { val rows1 = this.size val cols1 = this[0].size val rows2 = other.size val cols2 = other[0].size require(cols1 == rows2) val result = Matrix(rows1) { Vector(cols2) } for (i in 0 until rows1) { for (j in 0 until cols2) { for (k in 0 until rows2) { result[i][j] += this[i][k] * other[k][j] } } } return result } fun identityMatrix(n: Int): Matrix { require(n >= 1) val ident = Matrix(n) { Vector(n) } for (i in 0 until n) ident[i][i] = 1.0 return ident } infix fun Matrix.pow(n : Int): Matrix { require (n >= 0 && this.size == this[0].size) if (n == 0) return identityMatrix(this.size) if (n == 1) return this var pow = identityMatrix(this.size) var base = this var e = n while (e > 0) { if ((e and 1) == 1) pow *= base e = e shr 1 base *= base } return pow } fun printMatrix(m: Matrix, n: Int) { println("** Power of $n **") for (i in 0 until m.size) println(m[i].contentToString()) println() } fun main(args: Array<String>) { val m = arrayOf( doubleArrayOf(3.0, 2.0), doubleArrayOf(2.0, 1.0) ) for (i in 0..10) printMatrix(m pow i, i) }
Option Base 1 Private Function Identity(n As Integer) As Variant Dim I() As Variant ReDim I(n, n) For j = 1 To n For k = 1 To n I(j, k) = 0 Next k Next j For j = 1 To n I(j, j) = 1 Next j Identity = I End Function Function MatrixExponentiation(ByVal x As Variant, ByVal n As Integer) As Variant If n < 0 Then x = WorksheetFunction.MInverse(x) n = -n End If If n = 0 Then MatrixExponentiation = Identity(UBound(x)) Exit Function End If Dim y() As Variant y = Identity(UBound(x)) Do While n > 1 If n Mod 2 = 0 Then x = WorksheetFunction.MMult(x, x) n = n / 2 Else y = WorksheetFunction.MMult(x, y) x = WorksheetFunction.MMult(x, x) n = (n - 1) / 2 End If Loop MatrixExponentiation = WorksheetFunction.MMult(x, y) End Function Public Sub pp(x As Variant) For i_ = 1 To UBound(x) For j_ = 1 To UBound(x) Debug.Print x(i_, j_), Next j_ Debug.Print Next i_ End Sub Public Sub main() M2 = [{3,2;2,1}] M3 = [{1,2,0;0,3,1;1,0,0}] pp MatrixExponentiation(M2, -1) Debug.Print pp MatrixExponentiation(M2, 0) Debug.Print pp MatrixExponentiation(M2, 10) Debug.Print pp MatrixExponentiation(M3, 10) End Sub
Please provide an equivalent version of this Scala code in Go.
typealias Vector = DoubleArray typealias Matrix = Array<Vector> operator fun Matrix.times(other: Matrix): Matrix { val rows1 = this.size val cols1 = this[0].size val rows2 = other.size val cols2 = other[0].size require(cols1 == rows2) val result = Matrix(rows1) { Vector(cols2) } for (i in 0 until rows1) { for (j in 0 until cols2) { for (k in 0 until rows2) { result[i][j] += this[i][k] * other[k][j] } } } return result } fun identityMatrix(n: Int): Matrix { require(n >= 1) val ident = Matrix(n) { Vector(n) } for (i in 0 until n) ident[i][i] = 1.0 return ident } infix fun Matrix.pow(n : Int): Matrix { require (n >= 0 && this.size == this[0].size) if (n == 0) return identityMatrix(this.size) if (n == 1) return this var pow = identityMatrix(this.size) var base = this var e = n while (e > 0) { if ((e and 1) == 1) pow *= base e = e shr 1 base *= base } return pow } fun printMatrix(m: Matrix, n: Int) { println("** Power of $n **") for (i in 0 until m.size) println(m[i].contentToString()) println() } fun main(args: Array<String>) { val m = arrayOf( doubleArrayOf(3.0, 2.0), doubleArrayOf(2.0, 1.0) ) for (i in 0..10) printMatrix(m pow i, i) }
package main import "fmt" type vector = []float64 type matrix []vector func (m1 matrix) mul(m2 matrix) matrix { rows1, cols1 := len(m1), len(m1[0]) rows2, cols2 := len(m2), len(m2[0]) if cols1 != rows2 { panic("Matrices cannot be multiplied.") } result := make(matrix, rows1) for i := 0; i < rows1; i++ { result[i] = make(vector, cols2) for j := 0; j < cols2; j++ { for k := 0; k < rows2; k++ { result[i][j] += m1[i][k] * m2[k][j] } } } return result } func identityMatrix(n int) matrix { if n < 1 { panic("Size of identity matrix can't be less than 1") } ident := make(matrix, n) for i := 0; i < n; i++ { ident[i] = make(vector, n) ident[i][i] = 1 } return ident } func (m matrix) pow(n int) matrix { le := len(m) if le != len(m[0]) { panic("Not a square matrix") } switch { case n < 0: panic("Negative exponents not supported") case n == 0: return identityMatrix(le) case n == 1: return m } pow := identityMatrix(le) base := m e := n for e > 0 { if (e & 1) == 1 { pow = pow.mul(base) } e >>= 1 base = base.mul(base) } return pow } func main() { m := matrix{{3, 2}, {2, 1}} for i := 0; i <= 10; i++ { fmt.Println("** Power of", i, "**") fmt.Println(m.pow(i)) fmt.Println() } }
Change the following Tcl code into C without altering its purpose.
package require Tcl 8.5 namespace path {::tcl::mathop ::tcl::mathfunc} proc matrix_exp {m pow} { if { ! [string is int -strict $pow]} { error "non-integer exponents not implemented" } if {$pow < 0} { error "negative exponents not implemented" } lassign [size $m] rows cols set temp [identity $rows] for {set n 1} {$n <= $pow} {incr n} { set temp [matrix_multiply $temp $m] } return $temp } proc identity {size} { set i [lrepeat $size [lrepeat $size 0]] for {set n 0} {$n < $size} {incr n} {lset i $n $n 1} return $i }
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct squareMtxStruct { int dim; double *cells; double **m; } *SquareMtx; typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data); SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data ) { SquareMtx sm = malloc(sizeof(struct squareMtxStruct)); if (sm) { int rw; sm->dim = dim; sm->cells = malloc(dim*dim * sizeof(double)); sm->m = malloc( dim * sizeof(double *)); if ((sm->cells != NULL) && (sm->m != NULL)) { for (rw=0; rw<dim; rw++) { sm->m[rw] = sm->cells + dim*rw; fillFunc( sm->m[rw], rw, dim, ff_data ); } } else { free(sm->m); free(sm->cells); free(sm); printf("Square Matrix allocation failure\n"); return NULL; } } else { printf("Malloc failed for square matrix\n"); } return sm; } void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 ) { int col, ix; double sum; double *m0rw = m0->m[rw]; for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * m0->m[ix][col]; cells[col] = sum; } } void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] ) { SquareMtx mleft = mplcnds[0]; SquareMtx mrigt = mplcnds[1]; double sum; double *m0rw = mleft->m[rw]; int col, ix; for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * mrigt->m[ix][col]; cells[col] = sum; } } void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt) { int rw; SquareMtx mplcnds[2]; mplcnds[0] = left; mplcnds[1] = rigt; for (rw = 0; rw < left->dim; rw++) ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds); } void ffIdentity( double *cells, int rw, int dim, void *v ) { int col; for (col=0; col<dim; col++) cells[col] = 0.0; cells[rw] = 1.0; } void ffCopy(double *cells, int rw, int dim, SquareMtx m1) { int col; for (col=0; col<dim; col++) cells[col] = m1->m[rw][col]; } void FreeSquareMtx( SquareMtx m ) { free(m->m); free(m->cells); free(m); } SquareMtx SquareMtxPow( SquareMtx m0, int exp ) { SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL); SquareMtx v1 = NULL; SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0); SquareMtx base1 = NULL; SquareMtx mplcnds[2], t; while (exp) { if (exp % 2) { if (v1) MatxMul( v1, v0, base0); else { mplcnds[0] = v0; mplcnds[1] = base0; v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds); } {t = v0; v0=v1; v1 = t;} } if (base1) MatxMul( base1, base0, base0); else base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0); t = base0; base0 = base1; base1 = t; exp = exp/2; } if (base0) FreeSquareMtx(base0); if (base1) FreeSquareMtx(base1); if (v1) FreeSquareMtx(v1); return v0; } FILE *fout; void SquareMtxPrint( SquareMtx mtx, const char *mn ) { int rw, col; int d = mtx->dim; fprintf(fout, "%s dim:%d =\n", mn, mtx->dim); for (rw=0; rw<d; rw++) { fprintf(fout, " |"); for(col=0; col<d; col++) fprintf(fout, "%8.5f ",mtx->m[rw][col] ); fprintf(fout, " |\n"); } fprintf(fout, "\n"); } void fillInit( double *cells, int rw, int dim, void *data) { double theta = 3.1415926536/6.0; double c1 = cos( theta); double s1 = sin( theta); switch(rw) { case 0: cells[0]=c1; cells[1]=s1; cells[2]=0.0; break; case 1: cells[0]=-s1; cells[1]=c1; cells[2]=0; break; case 2: cells[0]=0.0; cells[1]=0.0; cells[2]=1.0; break; } } int main() { SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL); SquareMtx m1 = SquareMtxPow( m0, 5); SquareMtx m2 = SquareMtxPow( m0, 9); SquareMtx m3 = SquareMtxPow( m0, 2); fout = fopen("matrx_exp.txt", "w"); SquareMtxPrint(m0, "m0"); FreeSquareMtx(m0); SquareMtxPrint(m1, "m0^5"); FreeSquareMtx(m1); SquareMtxPrint(m2, "m0^9"); FreeSquareMtx(m2); SquareMtxPrint(m3, "m0^2"); FreeSquareMtx(m3); fclose(fout); return 0; }
Translate the given Tcl code snippet into C# without altering its behavior.
package require Tcl 8.5 namespace path {::tcl::mathop ::tcl::mathfunc} proc matrix_exp {m pow} { if { ! [string is int -strict $pow]} { error "non-integer exponents not implemented" } if {$pow < 0} { error "negative exponents not implemented" } lassign [size $m] rows cols set temp [identity $rows] for {set n 1} {$n <= $pow} {incr n} { set temp [matrix_multiply $temp $m] } return $temp } proc identity {size} { set i [lrepeat $size [lrepeat $size 0]] for {set n 0} {$n < $size} {incr n} {lset i $n $n 1} return $i }
using System; using System.Collections; using System.Collections.Generic; using static System.Linq.Enumerable; public static class MatrixExponentation { public static double[,] Identity(int size) { double[,] matrix = new double[size, size]; for (int i = 0; i < size; i++) matrix[i, i] = 1; return matrix; } public static double[,] Multiply(this double[,] left, double[,] right) { if (left.ColumnCount() != right.RowCount()) throw new ArgumentException(); double[,] m = new double[left.RowCount(), right.ColumnCount()]; foreach (var (row, column) in from r in Range(0, m.RowCount()) from c in Range(0, m.ColumnCount()) select (r, c)) { m[row, column] = Range(0, m.RowCount()).Sum(i => left[row, i] * right[i, column]); } return m; } public static double[,] Pow(this double[,] matrix, int exp) { if (matrix.RowCount() != matrix.ColumnCount()) throw new ArgumentException("Matrix must be square."); double[,] accumulator = Identity(matrix.RowCount()); for (int i = 0; i < exp; i++) { accumulator = accumulator.Multiply(matrix); } return accumulator; } private static int RowCount(this double[,] matrix) => matrix.GetLength(0); private static int ColumnCount(this double[,] matrix) => matrix.GetLength(1); private static void Print(this double[,] m) { foreach (var row in Rows()) { Console.WriteLine("[ " + string.Join(" ", row) + " ]"); } Console.WriteLine(); IEnumerable<IEnumerable<double>> Rows() => Range(0, m.RowCount()).Select(row => Range(0, m.ColumnCount()).Select(column => m[row, column])); } public static void Main() { var matrix = new double[,] { { 3, 2 }, { 2, 1 } }; matrix.Pow(0).Print(); matrix.Pow(1).Print(); matrix.Pow(2).Print(); matrix.Pow(3).Print(); matrix.Pow(4).Print(); matrix.Pow(50).Print(); } }
Convert the following code from Tcl to C++, ensuring the logic remains intact.
package require Tcl 8.5 namespace path {::tcl::mathop ::tcl::mathfunc} proc matrix_exp {m pow} { if { ! [string is int -strict $pow]} { error "non-integer exponents not implemented" } if {$pow < 0} { error "negative exponents not implemented" } lassign [size $m] rows cols set temp [identity $rows] for {set n 1} {$n <= $pow} {incr n} { set temp [matrix_multiply $temp $m] } return $temp } proc identity {size} { set i [lrepeat $size [lrepeat $size 0]] for {set n 0} {$n < $size} {incr n} {lset i $n $n 1} return $i }
#include <complex> #include <cmath> #include <iostream> using namespace std; template<int MSize = 3, class T = complex<double> > class SqMx { typedef T Ax[MSize][MSize]; typedef SqMx<MSize, T> Mx; private: Ax a; SqMx() { } public: SqMx(const Ax &_a) { for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) a[r][c] = _a[r][c]; } static Mx identity() { Mx m; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) m.a[r][c] = (r == c ? 1 : 0); return m; } friend ostream &operator<<(ostream& os, const Mx &p) { for (int i = 0; i < MSize; i++) { for (int j = 0; j < MSize; j++) os << p.a[i][j] << ','; os << endl; } return os; } Mx operator*(const Mx &b) { Mx d; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) { d.a[r][c] = 0; for (int k = 0; k < MSize; k++) d.a[r][c] += a[r][k] * b.a[k][c]; } return d; }
Please provide an equivalent version of this Tcl code in Python.
package require Tcl 8.5 namespace path {::tcl::mathop ::tcl::mathfunc} proc matrix_exp {m pow} { if { ! [string is int -strict $pow]} { error "non-integer exponents not implemented" } if {$pow < 0} { error "negative exponents not implemented" } lassign [size $m] rows cols set temp [identity $rows] for {set n 1} {$n <= $pow} {incr n} { set temp [matrix_multiply $temp $m] } return $temp } proc identity {size} { set i [lrepeat $size [lrepeat $size 0]] for {set n 0} {$n < $size} {incr n} {lset i $n $n 1} return $i }
>>> from operator import mul >>> def matrixMul(m1, m2): return map( lambda row: map( lambda *column: sum(map(mul, row, column)), *m2), m1) >>> def identity(size): size = range(size) return [[(i==j)*1 for i in size] for j in size] >>> def matrixExp(m, pow): assert pow>=0 and int(pow)==pow, "Only non-negative, integer powers allowed" accumulator = identity(len(m)) for i in range(pow): accumulator = matrixMul(accumulator, m) return accumulator >>> def printtable(data): for row in data: print ' '.join('%-5s' % ('%s' % cell) for cell in row) >>> m = [[3,2], [2,1]] >>> for i in range(5): print '\n%i:' % i printtable( matrixExp(m, i) ) 0: 1 0 0 1 1: 3 2 2 1 2: 13 8 8 5 3: 55 34 34 21 4: 233 144 144 89 >>> printtable( matrixExp(m, 10) ) 1346269 832040 832040 514229 >>>
Produce a language-to-language conversion: from Tcl to VB, same semantics.
package require Tcl 8.5 namespace path {::tcl::mathop ::tcl::mathfunc} proc matrix_exp {m pow} { if { ! [string is int -strict $pow]} { error "non-integer exponents not implemented" } if {$pow < 0} { error "negative exponents not implemented" } lassign [size $m] rows cols set temp [identity $rows] for {set n 1} {$n <= $pow} {incr n} { set temp [matrix_multiply $temp $m] } return $temp } proc identity {size} { set i [lrepeat $size [lrepeat $size 0]] for {set n 0} {$n < $size} {incr n} {lset i $n $n 1} return $i }
Option Base 1 Private Function Identity(n As Integer) As Variant Dim I() As Variant ReDim I(n, n) For j = 1 To n For k = 1 To n I(j, k) = 0 Next k Next j For j = 1 To n I(j, j) = 1 Next j Identity = I End Function Function MatrixExponentiation(ByVal x As Variant, ByVal n As Integer) As Variant If n < 0 Then x = WorksheetFunction.MInverse(x) n = -n End If If n = 0 Then MatrixExponentiation = Identity(UBound(x)) Exit Function End If Dim y() As Variant y = Identity(UBound(x)) Do While n > 1 If n Mod 2 = 0 Then x = WorksheetFunction.MMult(x, x) n = n / 2 Else y = WorksheetFunction.MMult(x, y) x = WorksheetFunction.MMult(x, x) n = (n - 1) / 2 End If Loop MatrixExponentiation = WorksheetFunction.MMult(x, y) End Function Public Sub pp(x As Variant) For i_ = 1 To UBound(x) For j_ = 1 To UBound(x) Debug.Print x(i_, j_), Next j_ Debug.Print Next i_ End Sub Public Sub main() M2 = [{3,2;2,1}] M3 = [{1,2,0;0,3,1;1,0,0}] pp MatrixExponentiation(M2, -1) Debug.Print pp MatrixExponentiation(M2, 0) Debug.Print pp MatrixExponentiation(M2, 10) Debug.Print pp MatrixExponentiation(M3, 10) End Sub
Write the same algorithm in Go as shown in this Tcl implementation.
package require Tcl 8.5 namespace path {::tcl::mathop ::tcl::mathfunc} proc matrix_exp {m pow} { if { ! [string is int -strict $pow]} { error "non-integer exponents not implemented" } if {$pow < 0} { error "negative exponents not implemented" } lassign [size $m] rows cols set temp [identity $rows] for {set n 1} {$n <= $pow} {incr n} { set temp [matrix_multiply $temp $m] } return $temp } proc identity {size} { set i [lrepeat $size [lrepeat $size 0]] for {set n 0} {$n < $size} {incr n} {lset i $n $n 1} return $i }
package main import "fmt" type vector = []float64 type matrix []vector func (m1 matrix) mul(m2 matrix) matrix { rows1, cols1 := len(m1), len(m1[0]) rows2, cols2 := len(m2), len(m2[0]) if cols1 != rows2 { panic("Matrices cannot be multiplied.") } result := make(matrix, rows1) for i := 0; i < rows1; i++ { result[i] = make(vector, cols2) for j := 0; j < cols2; j++ { for k := 0; k < rows2; k++ { result[i][j] += m1[i][k] * m2[k][j] } } } return result } func identityMatrix(n int) matrix { if n < 1 { panic("Size of identity matrix can't be less than 1") } ident := make(matrix, n) for i := 0; i < n; i++ { ident[i] = make(vector, n) ident[i][i] = 1 } return ident } func (m matrix) pow(n int) matrix { le := len(m) if le != len(m[0]) { panic("Not a square matrix") } switch { case n < 0: panic("Negative exponents not supported") case n == 0: return identityMatrix(le) case n == 1: return m } pow := identityMatrix(le) base := m e := n for e > 0 { if (e & 1) == 1 { pow = pow.mul(base) } e >>= 1 base = base.mul(base) } return pow } func main() { m := matrix{{3, 2}, {2, 1}} for i := 0; i <= 10; i++ { fmt.Println("** Power of", i, "**") fmt.Println(m.pow(i)) fmt.Println() } }
Please provide an equivalent version of this C++ code in Rust.
#include <complex> #include <cmath> #include <iostream> using namespace std; template<int MSize = 3, class T = complex<double> > class SqMx { typedef T Ax[MSize][MSize]; typedef SqMx<MSize, T> Mx; private: Ax a; SqMx() { } public: SqMx(const Ax &_a) { for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) a[r][c] = _a[r][c]; } static Mx identity() { Mx m; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) m.a[r][c] = (r == c ? 1 : 0); return m; } friend ostream &operator<<(ostream& os, const Mx &p) { for (int i = 0; i < MSize; i++) { for (int j = 0; j < MSize; j++) os << p.a[i][j] << ','; os << endl; } return os; } Mx operator*(const Mx &b) { Mx d; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) { d.a[r][c] = 0; for (int k = 0; k < MSize; k++) d.a[r][c] += a[r][k] * b.a[k][c]; } return d; }
use std::fmt; use std::ops; const WIDTH: usize = 6; #[derive(Clone)] struct SqMat { data: Vec<Vec<i64>>, } impl fmt::Debug for SqMat { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut row = "".to_string(); for i in &self.data { for j in i { row += &format!("{:>w$} ", j, w = WIDTH); } row += &"\n"; } write!(f, "{}", row) } } impl ops::BitXor<u32> for SqMat { type Output = Self; fn bitxor(self, n: u32) -> Self::Output { let mut aux = self.data.clone(); let mut ans: SqMat = SqMat { data: vec![vec![0; aux.len()]; aux.len()], }; for i in 0..aux.len() { ans.data[i][i] = 1; } let mut b = n; while b > 0 { if b & 1 > 0 { let mut tmp = aux.clone(); for i in 0..aux.len() { for j in 0..aux.len() { tmp[i][j] = 0; for k in 0..aux.len() { tmp[i][j] += ans.data[i][k] * aux[k][j]; } } } ans.data = tmp; } b >>= 1; if b > 0 { let mut tmp = aux.clone(); for i in 0..aux.len() { for j in 0..aux.len() { tmp[i][j] = 0; for k in 0..aux.len() { tmp[i][j] += aux[i][k] * aux[k][j]; } } } aux = tmp; } } ans } } fn main() { let sm: SqMat = SqMat { data: vec![vec![1, 2, 0], vec![0, 3, 1], vec![1, 0, 0]], }; for i in 0..11 { println!("Power of {}:\n{:?}", i, sm.clone() ^ i); } }
Keep all operations the same but rewrite the snippet in Python.
use std::fmt; use std::ops; const WIDTH: usize = 6; #[derive(Clone)] struct SqMat { data: Vec<Vec<i64>>, } impl fmt::Debug for SqMat { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut row = "".to_string(); for i in &self.data { for j in i { row += &format!("{:>w$} ", j, w = WIDTH); } row += &"\n"; } write!(f, "{}", row) } } impl ops::BitXor<u32> for SqMat { type Output = Self; fn bitxor(self, n: u32) -> Self::Output { let mut aux = self.data.clone(); let mut ans: SqMat = SqMat { data: vec![vec![0; aux.len()]; aux.len()], }; for i in 0..aux.len() { ans.data[i][i] = 1; } let mut b = n; while b > 0 { if b & 1 > 0 { let mut tmp = aux.clone(); for i in 0..aux.len() { for j in 0..aux.len() { tmp[i][j] = 0; for k in 0..aux.len() { tmp[i][j] += ans.data[i][k] * aux[k][j]; } } } ans.data = tmp; } b >>= 1; if b > 0 { let mut tmp = aux.clone(); for i in 0..aux.len() { for j in 0..aux.len() { tmp[i][j] = 0; for k in 0..aux.len() { tmp[i][j] += aux[i][k] * aux[k][j]; } } } aux = tmp; } } ans } } fn main() { let sm: SqMat = SqMat { data: vec![vec![1, 2, 0], vec![0, 3, 1], vec![1, 0, 0]], }; for i in 0..11 { println!("Power of {}:\n{:?}", i, sm.clone() ^ i); } }
>>> from operator import mul >>> def matrixMul(m1, m2): return map( lambda row: map( lambda *column: sum(map(mul, row, column)), *m2), m1) >>> def identity(size): size = range(size) return [[(i==j)*1 for i in size] for j in size] >>> def matrixExp(m, pow): assert pow>=0 and int(pow)==pow, "Only non-negative, integer powers allowed" accumulator = identity(len(m)) for i in range(pow): accumulator = matrixMul(accumulator, m) return accumulator >>> def printtable(data): for row in data: print ' '.join('%-5s' % ('%s' % cell) for cell in row) >>> m = [[3,2], [2,1]] >>> for i in range(5): print '\n%i:' % i printtable( matrixExp(m, i) ) 0: 1 0 0 1 1: 3 2 2 1 2: 13 8 8 5 3: 55 34 34 21 4: 233 144 144 89 >>> printtable( matrixExp(m, 10) ) 1346269 832040 832040 514229 >>>
Translate this program into VB but keep the logic exactly as in Rust.
use std::fmt; use std::ops; const WIDTH: usize = 6; #[derive(Clone)] struct SqMat { data: Vec<Vec<i64>>, } impl fmt::Debug for SqMat { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut row = "".to_string(); for i in &self.data { for j in i { row += &format!("{:>w$} ", j, w = WIDTH); } row += &"\n"; } write!(f, "{}", row) } } impl ops::BitXor<u32> for SqMat { type Output = Self; fn bitxor(self, n: u32) -> Self::Output { let mut aux = self.data.clone(); let mut ans: SqMat = SqMat { data: vec![vec![0; aux.len()]; aux.len()], }; for i in 0..aux.len() { ans.data[i][i] = 1; } let mut b = n; while b > 0 { if b & 1 > 0 { let mut tmp = aux.clone(); for i in 0..aux.len() { for j in 0..aux.len() { tmp[i][j] = 0; for k in 0..aux.len() { tmp[i][j] += ans.data[i][k] * aux[k][j]; } } } ans.data = tmp; } b >>= 1; if b > 0 { let mut tmp = aux.clone(); for i in 0..aux.len() { for j in 0..aux.len() { tmp[i][j] = 0; for k in 0..aux.len() { tmp[i][j] += aux[i][k] * aux[k][j]; } } } aux = tmp; } } ans } } fn main() { let sm: SqMat = SqMat { data: vec![vec![1, 2, 0], vec![0, 3, 1], vec![1, 0, 0]], }; for i in 0..11 { println!("Power of {}:\n{:?}", i, sm.clone() ^ i); } }
Option Base 1 Private Function Identity(n As Integer) As Variant Dim I() As Variant ReDim I(n, n) For j = 1 To n For k = 1 To n I(j, k) = 0 Next k Next j For j = 1 To n I(j, j) = 1 Next j Identity = I End Function Function MatrixExponentiation(ByVal x As Variant, ByVal n As Integer) As Variant If n < 0 Then x = WorksheetFunction.MInverse(x) n = -n End If If n = 0 Then MatrixExponentiation = Identity(UBound(x)) Exit Function End If Dim y() As Variant y = Identity(UBound(x)) Do While n > 1 If n Mod 2 = 0 Then x = WorksheetFunction.MMult(x, x) n = n / 2 Else y = WorksheetFunction.MMult(x, y) x = WorksheetFunction.MMult(x, x) n = (n - 1) / 2 End If Loop MatrixExponentiation = WorksheetFunction.MMult(x, y) End Function Public Sub pp(x As Variant) For i_ = 1 To UBound(x) For j_ = 1 To UBound(x) Debug.Print x(i_, j_), Next j_ Debug.Print Next i_ End Sub Public Sub main() M2 = [{3,2;2,1}] M3 = [{1,2,0;0,3,1;1,0,0}] pp MatrixExponentiation(M2, -1) Debug.Print pp MatrixExponentiation(M2, 0) Debug.Print pp MatrixExponentiation(M2, 10) Debug.Print pp MatrixExponentiation(M3, 10) End Sub
Rewrite this program in Rust while keeping its functionality equivalent to the C version.
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct squareMtxStruct { int dim; double *cells; double **m; } *SquareMtx; typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data); SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data ) { SquareMtx sm = malloc(sizeof(struct squareMtxStruct)); if (sm) { int rw; sm->dim = dim; sm->cells = malloc(dim*dim * sizeof(double)); sm->m = malloc( dim * sizeof(double *)); if ((sm->cells != NULL) && (sm->m != NULL)) { for (rw=0; rw<dim; rw++) { sm->m[rw] = sm->cells + dim*rw; fillFunc( sm->m[rw], rw, dim, ff_data ); } } else { free(sm->m); free(sm->cells); free(sm); printf("Square Matrix allocation failure\n"); return NULL; } } else { printf("Malloc failed for square matrix\n"); } return sm; } void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 ) { int col, ix; double sum; double *m0rw = m0->m[rw]; for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * m0->m[ix][col]; cells[col] = sum; } } void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] ) { SquareMtx mleft = mplcnds[0]; SquareMtx mrigt = mplcnds[1]; double sum; double *m0rw = mleft->m[rw]; int col, ix; for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * mrigt->m[ix][col]; cells[col] = sum; } } void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt) { int rw; SquareMtx mplcnds[2]; mplcnds[0] = left; mplcnds[1] = rigt; for (rw = 0; rw < left->dim; rw++) ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds); } void ffIdentity( double *cells, int rw, int dim, void *v ) { int col; for (col=0; col<dim; col++) cells[col] = 0.0; cells[rw] = 1.0; } void ffCopy(double *cells, int rw, int dim, SquareMtx m1) { int col; for (col=0; col<dim; col++) cells[col] = m1->m[rw][col]; } void FreeSquareMtx( SquareMtx m ) { free(m->m); free(m->cells); free(m); } SquareMtx SquareMtxPow( SquareMtx m0, int exp ) { SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL); SquareMtx v1 = NULL; SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0); SquareMtx base1 = NULL; SquareMtx mplcnds[2], t; while (exp) { if (exp % 2) { if (v1) MatxMul( v1, v0, base0); else { mplcnds[0] = v0; mplcnds[1] = base0; v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds); } {t = v0; v0=v1; v1 = t;} } if (base1) MatxMul( base1, base0, base0); else base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0); t = base0; base0 = base1; base1 = t; exp = exp/2; } if (base0) FreeSquareMtx(base0); if (base1) FreeSquareMtx(base1); if (v1) FreeSquareMtx(v1); return v0; } FILE *fout; void SquareMtxPrint( SquareMtx mtx, const char *mn ) { int rw, col; int d = mtx->dim; fprintf(fout, "%s dim:%d =\n", mn, mtx->dim); for (rw=0; rw<d; rw++) { fprintf(fout, " |"); for(col=0; col<d; col++) fprintf(fout, "%8.5f ",mtx->m[rw][col] ); fprintf(fout, " |\n"); } fprintf(fout, "\n"); } void fillInit( double *cells, int rw, int dim, void *data) { double theta = 3.1415926536/6.0; double c1 = cos( theta); double s1 = sin( theta); switch(rw) { case 0: cells[0]=c1; cells[1]=s1; cells[2]=0.0; break; case 1: cells[0]=-s1; cells[1]=c1; cells[2]=0; break; case 2: cells[0]=0.0; cells[1]=0.0; cells[2]=1.0; break; } } int main() { SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL); SquareMtx m1 = SquareMtxPow( m0, 5); SquareMtx m2 = SquareMtxPow( m0, 9); SquareMtx m3 = SquareMtxPow( m0, 2); fout = fopen("matrx_exp.txt", "w"); SquareMtxPrint(m0, "m0"); FreeSquareMtx(m0); SquareMtxPrint(m1, "m0^5"); FreeSquareMtx(m1); SquareMtxPrint(m2, "m0^9"); FreeSquareMtx(m2); SquareMtxPrint(m3, "m0^2"); FreeSquareMtx(m3); fclose(fout); return 0; }
use std::fmt; use std::ops; const WIDTH: usize = 6; #[derive(Clone)] struct SqMat { data: Vec<Vec<i64>>, } impl fmt::Debug for SqMat { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut row = "".to_string(); for i in &self.data { for j in i { row += &format!("{:>w$} ", j, w = WIDTH); } row += &"\n"; } write!(f, "{}", row) } } impl ops::BitXor<u32> for SqMat { type Output = Self; fn bitxor(self, n: u32) -> Self::Output { let mut aux = self.data.clone(); let mut ans: SqMat = SqMat { data: vec![vec![0; aux.len()]; aux.len()], }; for i in 0..aux.len() { ans.data[i][i] = 1; } let mut b = n; while b > 0 { if b & 1 > 0 { let mut tmp = aux.clone(); for i in 0..aux.len() { for j in 0..aux.len() { tmp[i][j] = 0; for k in 0..aux.len() { tmp[i][j] += ans.data[i][k] * aux[k][j]; } } } ans.data = tmp; } b >>= 1; if b > 0 { let mut tmp = aux.clone(); for i in 0..aux.len() { for j in 0..aux.len() { tmp[i][j] = 0; for k in 0..aux.len() { tmp[i][j] += aux[i][k] * aux[k][j]; } } } aux = tmp; } } ans } } fn main() { let sm: SqMat = SqMat { data: vec![vec![1, 2, 0], vec![0, 3, 1], vec![1, 0, 0]], }; for i in 0..11 { println!("Power of {}:\n{:?}", i, sm.clone() ^ i); } }
Port the provided C# code into Rust while preserving the original functionality.
using System; using System.Collections; using System.Collections.Generic; using static System.Linq.Enumerable; public static class MatrixExponentation { public static double[,] Identity(int size) { double[,] matrix = new double[size, size]; for (int i = 0; i < size; i++) matrix[i, i] = 1; return matrix; } public static double[,] Multiply(this double[,] left, double[,] right) { if (left.ColumnCount() != right.RowCount()) throw new ArgumentException(); double[,] m = new double[left.RowCount(), right.ColumnCount()]; foreach (var (row, column) in from r in Range(0, m.RowCount()) from c in Range(0, m.ColumnCount()) select (r, c)) { m[row, column] = Range(0, m.RowCount()).Sum(i => left[row, i] * right[i, column]); } return m; } public static double[,] Pow(this double[,] matrix, int exp) { if (matrix.RowCount() != matrix.ColumnCount()) throw new ArgumentException("Matrix must be square."); double[,] accumulator = Identity(matrix.RowCount()); for (int i = 0; i < exp; i++) { accumulator = accumulator.Multiply(matrix); } return accumulator; } private static int RowCount(this double[,] matrix) => matrix.GetLength(0); private static int ColumnCount(this double[,] matrix) => matrix.GetLength(1); private static void Print(this double[,] m) { foreach (var row in Rows()) { Console.WriteLine("[ " + string.Join(" ", row) + " ]"); } Console.WriteLine(); IEnumerable<IEnumerable<double>> Rows() => Range(0, m.RowCount()).Select(row => Range(0, m.ColumnCount()).Select(column => m[row, column])); } public static void Main() { var matrix = new double[,] { { 3, 2 }, { 2, 1 } }; matrix.Pow(0).Print(); matrix.Pow(1).Print(); matrix.Pow(2).Print(); matrix.Pow(3).Print(); matrix.Pow(4).Print(); matrix.Pow(50).Print(); } }
use std::fmt; use std::ops; const WIDTH: usize = 6; #[derive(Clone)] struct SqMat { data: Vec<Vec<i64>>, } impl fmt::Debug for SqMat { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut row = "".to_string(); for i in &self.data { for j in i { row += &format!("{:>w$} ", j, w = WIDTH); } row += &"\n"; } write!(f, "{}", row) } } impl ops::BitXor<u32> for SqMat { type Output = Self; fn bitxor(self, n: u32) -> Self::Output { let mut aux = self.data.clone(); let mut ans: SqMat = SqMat { data: vec![vec![0; aux.len()]; aux.len()], }; for i in 0..aux.len() { ans.data[i][i] = 1; } let mut b = n; while b > 0 { if b & 1 > 0 { let mut tmp = aux.clone(); for i in 0..aux.len() { for j in 0..aux.len() { tmp[i][j] = 0; for k in 0..aux.len() { tmp[i][j] += ans.data[i][k] * aux[k][j]; } } } ans.data = tmp; } b >>= 1; if b > 0 { let mut tmp = aux.clone(); for i in 0..aux.len() { for j in 0..aux.len() { tmp[i][j] = 0; for k in 0..aux.len() { tmp[i][j] += aux[i][k] * aux[k][j]; } } } aux = tmp; } } ans } } fn main() { let sm: SqMat = SqMat { data: vec![vec![1, 2, 0], vec![0, 3, 1], vec![1, 0, 0]], }; for i in 0..11 { println!("Power of {}:\n{:?}", i, sm.clone() ^ i); } }
Rewrite this program in Rust while keeping its functionality equivalent to the Go version.
package main import "fmt" type vector = []float64 type matrix []vector func (m1 matrix) mul(m2 matrix) matrix { rows1, cols1 := len(m1), len(m1[0]) rows2, cols2 := len(m2), len(m2[0]) if cols1 != rows2 { panic("Matrices cannot be multiplied.") } result := make(matrix, rows1) for i := 0; i < rows1; i++ { result[i] = make(vector, cols2) for j := 0; j < cols2; j++ { for k := 0; k < rows2; k++ { result[i][j] += m1[i][k] * m2[k][j] } } } return result } func identityMatrix(n int) matrix { if n < 1 { panic("Size of identity matrix can't be less than 1") } ident := make(matrix, n) for i := 0; i < n; i++ { ident[i] = make(vector, n) ident[i][i] = 1 } return ident } func (m matrix) pow(n int) matrix { le := len(m) if le != len(m[0]) { panic("Not a square matrix") } switch { case n < 0: panic("Negative exponents not supported") case n == 0: return identityMatrix(le) case n == 1: return m } pow := identityMatrix(le) base := m e := n for e > 0 { if (e & 1) == 1 { pow = pow.mul(base) } e >>= 1 base = base.mul(base) } return pow } func main() { m := matrix{{3, 2}, {2, 1}} for i := 0; i <= 10; i++ { fmt.Println("** Power of", i, "**") fmt.Println(m.pow(i)) fmt.Println() } }
use std::fmt; use std::ops; const WIDTH: usize = 6; #[derive(Clone)] struct SqMat { data: Vec<Vec<i64>>, } impl fmt::Debug for SqMat { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut row = "".to_string(); for i in &self.data { for j in i { row += &format!("{:>w$} ", j, w = WIDTH); } row += &"\n"; } write!(f, "{}", row) } } impl ops::BitXor<u32> for SqMat { type Output = Self; fn bitxor(self, n: u32) -> Self::Output { let mut aux = self.data.clone(); let mut ans: SqMat = SqMat { data: vec![vec![0; aux.len()]; aux.len()], }; for i in 0..aux.len() { ans.data[i][i] = 1; } let mut b = n; while b > 0 { if b & 1 > 0 { let mut tmp = aux.clone(); for i in 0..aux.len() { for j in 0..aux.len() { tmp[i][j] = 0; for k in 0..aux.len() { tmp[i][j] += ans.data[i][k] * aux[k][j]; } } } ans.data = tmp; } b >>= 1; if b > 0 { let mut tmp = aux.clone(); for i in 0..aux.len() { for j in 0..aux.len() { tmp[i][j] = 0; for k in 0..aux.len() { tmp[i][j] += aux[i][k] * aux[k][j]; } } } aux = tmp; } } ans } } fn main() { let sm: SqMat = SqMat { data: vec![vec![1, 2, 0], vec![0, 3, 1], vec![1, 0, 0]], }; for i in 0..11 { println!("Power of {}:\n{:?}", i, sm.clone() ^ i); } }
Translate this program into C# but keep the logic exactly as in Ada.
with Ada.Text_Io; use Ada.Text_Io; with Ada.Unchecked_Deallocation; with Ada.Containers.Doubly_Linked_Lists; procedure Tree_Traversal is type Node; type Node_Access is access Node; type Node is record Left : Node_Access := null; Right : Node_Access := null; Data : Integer; end record; procedure Destroy_Tree(N : in out Node_Access) is procedure free is new Ada.Unchecked_Deallocation(Node, Node_Access); begin if N.Left /= null then Destroy_Tree(N.Left); end if; if N.Right /= null then Destroy_Tree(N.Right); end if; Free(N); end Destroy_Tree; function Tree(Value : Integer; Left : Node_Access; Right : Node_Access) return Node_Access is Temp : Node_Access := new Node; begin Temp.Data := Value; Temp.Left := Left; Temp.Right := Right; return Temp; end Tree; procedure Preorder(N : Node_Access) is begin Put(Integer'Image(N.Data)); if N.Left /= null then Preorder(N.Left); end if; if N.Right /= null then Preorder(N.Right); end if; end Preorder; procedure Inorder(N : Node_Access) is begin if N.Left /= null then Inorder(N.Left); end if; Put(Integer'Image(N.Data)); if N.Right /= null then Inorder(N.Right); end if; end Inorder; procedure Postorder(N : Node_Access) is begin if N.Left /= null then Postorder(N.Left); end if; if N.Right /= null then Postorder(N.Right); end if; Put(Integer'Image(N.Data)); end Postorder; procedure Levelorder(N : Node_Access) is package Queues is new Ada.Containers.Doubly_Linked_Lists(Node_Access); use Queues; Node_Queue : List; Next : Node_Access; begin Node_Queue.Append(N); while not Is_Empty(Node_Queue) loop Next := First_Element(Node_Queue); Delete_First(Node_Queue); Put(Integer'Image(Next.Data)); if Next.Left /= null then Node_Queue.Append(Next.Left); end if; if Next.Right /= null then Node_Queue.Append(Next.Right); end if; end loop; end Levelorder; N : Node_Access; begin N := Tree(1, Tree(2, Tree(4, Tree(7, null, null), null), Tree(5, null, null)), Tree(3, Tree(6, Tree(8, null, null), Tree(9, null, null)), null)); Put("preorder: "); Preorder(N); New_Line; Put("inorder: "); Inorder(N); New_Line; Put("postorder: "); Postorder(N); New_Line; Put("level order: "); Levelorder(N); New_Line; Destroy_Tree(N); end Tree_traversal;
using System; using System.Collections.Generic; using System.Linq; class Node { int Value; Node Left; Node Right; Node(int value = default(int), Node left = default(Node), Node right = default(Node)) { Value = value; Left = left; Right = right; } IEnumerable<int> Preorder() { yield return Value; if (Left != null) foreach (var value in Left.Preorder()) yield return value; if (Right != null) foreach (var value in Right.Preorder()) yield return value; } IEnumerable<int> Inorder() { if (Left != null) foreach (var value in Left.Inorder()) yield return value; yield return Value; if (Right != null) foreach (var value in Right.Inorder()) yield return value; } IEnumerable<int> Postorder() { if (Left != null) foreach (var value in Left.Postorder()) yield return value; if (Right != null) foreach (var value in Right.Postorder()) yield return value; yield return Value; } IEnumerable<int> LevelOrder() { var queue = new Queue<Node>(); queue.Enqueue(this); while (queue.Any()) { var node = queue.Dequeue(); yield return node.Value; if (node.Left != null) queue.Enqueue(node.Left); if (node.Right != null) queue.Enqueue(node.Right); } } static void Main() { var tree = new Node(1, new Node(2, new Node(4, new Node(7)), new Node(5)), new Node(3, new Node(6, new Node(8), new Node(9)))); foreach (var traversal in new Func<IEnumerable<int>>[] { tree.Preorder, tree.Inorder, tree.Postorder, tree.LevelOrder }) Console.WriteLine("{0}:\t{1}", traversal.Method.Name, string.Join(" ", traversal())); } }
Translate the given Ada code snippet into C without altering its behavior.
with Ada.Text_Io; use Ada.Text_Io; with Ada.Unchecked_Deallocation; with Ada.Containers.Doubly_Linked_Lists; procedure Tree_Traversal is type Node; type Node_Access is access Node; type Node is record Left : Node_Access := null; Right : Node_Access := null; Data : Integer; end record; procedure Destroy_Tree(N : in out Node_Access) is procedure free is new Ada.Unchecked_Deallocation(Node, Node_Access); begin if N.Left /= null then Destroy_Tree(N.Left); end if; if N.Right /= null then Destroy_Tree(N.Right); end if; Free(N); end Destroy_Tree; function Tree(Value : Integer; Left : Node_Access; Right : Node_Access) return Node_Access is Temp : Node_Access := new Node; begin Temp.Data := Value; Temp.Left := Left; Temp.Right := Right; return Temp; end Tree; procedure Preorder(N : Node_Access) is begin Put(Integer'Image(N.Data)); if N.Left /= null then Preorder(N.Left); end if; if N.Right /= null then Preorder(N.Right); end if; end Preorder; procedure Inorder(N : Node_Access) is begin if N.Left /= null then Inorder(N.Left); end if; Put(Integer'Image(N.Data)); if N.Right /= null then Inorder(N.Right); end if; end Inorder; procedure Postorder(N : Node_Access) is begin if N.Left /= null then Postorder(N.Left); end if; if N.Right /= null then Postorder(N.Right); end if; Put(Integer'Image(N.Data)); end Postorder; procedure Levelorder(N : Node_Access) is package Queues is new Ada.Containers.Doubly_Linked_Lists(Node_Access); use Queues; Node_Queue : List; Next : Node_Access; begin Node_Queue.Append(N); while not Is_Empty(Node_Queue) loop Next := First_Element(Node_Queue); Delete_First(Node_Queue); Put(Integer'Image(Next.Data)); if Next.Left /= null then Node_Queue.Append(Next.Left); end if; if Next.Right /= null then Node_Queue.Append(Next.Right); end if; end loop; end Levelorder; N : Node_Access; begin N := Tree(1, Tree(2, Tree(4, Tree(7, null, null), null), Tree(5, null, null)), Tree(3, Tree(6, Tree(8, null, null), Tree(9, null, null)), null)); Put("preorder: "); Preorder(N); New_Line; Put("inorder: "); Inorder(N); New_Line; Put("postorder: "); Postorder(N); New_Line; Put("level order: "); Levelorder(N); New_Line; Destroy_Tree(N); end Tree_traversal;
#include <stdlib.h> #include <stdio.h> typedef struct node_s { int value; struct node_s* left; struct node_s* right; } *node; node tree(int v, node l, node r) { node n = malloc(sizeof(struct node_s)); n->value = v; n->left = l; n->right = r; return n; } void destroy_tree(node n) { if (n->left) destroy_tree(n->left); if (n->right) destroy_tree(n->right); free(n); } void preorder(node n, void (*f)(int)) { f(n->value); if (n->left) preorder(n->left, f); if (n->right) preorder(n->right, f); } void inorder(node n, void (*f)(int)) { if (n->left) inorder(n->left, f); f(n->value); if (n->right) inorder(n->right, f); } void postorder(node n, void (*f)(int)) { if (n->left) postorder(n->left, f); if (n->right) postorder(n->right, f); f(n->value); } typedef struct qnode_s { struct qnode_s* next; node value; } *qnode; typedef struct { qnode begin, end; } queue; void enqueue(queue* q, node n) { qnode node = malloc(sizeof(struct qnode_s)); node->value = n; node->next = 0; if (q->end) q->end->next = node; else q->begin = node; q->end = node; } node dequeue(queue* q) { node tmp = q->begin->value; qnode second = q->begin->next; free(q->begin); q->begin = second; if (!q->begin) q->end = 0; return tmp; } int queue_empty(queue* q) { return !q->begin; } void levelorder(node n, void(*f)(int)) { queue nodequeue = {}; enqueue(&nodequeue, n); while (!queue_empty(&nodequeue)) { node next = dequeue(&nodequeue); f(next->value); if (next->left) enqueue(&nodequeue, next->left); if (next->right) enqueue(&nodequeue, next->right); } } void print(int n) { printf("%d ", n); } int main() { node n = tree(1, tree(2, tree(4, tree(7, 0, 0), 0), tree(5, 0, 0)), tree(3, tree(6, tree(8, 0, 0), tree(9, 0, 0)), 0)); printf("preorder: "); preorder(n, print); printf("\n"); printf("inorder: "); inorder(n, print); printf("\n"); printf("postorder: "); postorder(n, print); printf("\n"); printf("level-order: "); levelorder(n, print); printf("\n"); destroy_tree(n); return 0; }
Produce a language-to-language conversion: from Ada to C++, same semantics.
with Ada.Text_Io; use Ada.Text_Io; with Ada.Unchecked_Deallocation; with Ada.Containers.Doubly_Linked_Lists; procedure Tree_Traversal is type Node; type Node_Access is access Node; type Node is record Left : Node_Access := null; Right : Node_Access := null; Data : Integer; end record; procedure Destroy_Tree(N : in out Node_Access) is procedure free is new Ada.Unchecked_Deallocation(Node, Node_Access); begin if N.Left /= null then Destroy_Tree(N.Left); end if; if N.Right /= null then Destroy_Tree(N.Right); end if; Free(N); end Destroy_Tree; function Tree(Value : Integer; Left : Node_Access; Right : Node_Access) return Node_Access is Temp : Node_Access := new Node; begin Temp.Data := Value; Temp.Left := Left; Temp.Right := Right; return Temp; end Tree; procedure Preorder(N : Node_Access) is begin Put(Integer'Image(N.Data)); if N.Left /= null then Preorder(N.Left); end if; if N.Right /= null then Preorder(N.Right); end if; end Preorder; procedure Inorder(N : Node_Access) is begin if N.Left /= null then Inorder(N.Left); end if; Put(Integer'Image(N.Data)); if N.Right /= null then Inorder(N.Right); end if; end Inorder; procedure Postorder(N : Node_Access) is begin if N.Left /= null then Postorder(N.Left); end if; if N.Right /= null then Postorder(N.Right); end if; Put(Integer'Image(N.Data)); end Postorder; procedure Levelorder(N : Node_Access) is package Queues is new Ada.Containers.Doubly_Linked_Lists(Node_Access); use Queues; Node_Queue : List; Next : Node_Access; begin Node_Queue.Append(N); while not Is_Empty(Node_Queue) loop Next := First_Element(Node_Queue); Delete_First(Node_Queue); Put(Integer'Image(Next.Data)); if Next.Left /= null then Node_Queue.Append(Next.Left); end if; if Next.Right /= null then Node_Queue.Append(Next.Right); end if; end loop; end Levelorder; N : Node_Access; begin N := Tree(1, Tree(2, Tree(4, Tree(7, null, null), null), Tree(5, null, null)), Tree(3, Tree(6, Tree(8, null, null), Tree(9, null, null)), null)); Put("preorder: "); Preorder(N); New_Line; Put("inorder: "); Inorder(N); New_Line; Put("postorder: "); Postorder(N); New_Line; Put("level order: "); Levelorder(N); New_Line; Destroy_Tree(N); end Tree_traversal;
#include <boost/scoped_ptr.hpp> #include <iostream> #include <queue> template<typename T> class TreeNode { public: TreeNode(const T& n, TreeNode* left = NULL, TreeNode* right = NULL) : mValue(n), mLeft(left), mRight(right) {} T getValue() const { return mValue; } TreeNode* left() const { return mLeft.get(); } TreeNode* right() const { return mRight.get(); } void preorderTraverse() const { std::cout << " " << getValue(); if(mLeft) { mLeft->preorderTraverse(); } if(mRight) { mRight->preorderTraverse(); } } void inorderTraverse() const { if(mLeft) { mLeft->inorderTraverse(); } std::cout << " " << getValue(); if(mRight) { mRight->inorderTraverse(); } } void postorderTraverse() const { if(mLeft) { mLeft->postorderTraverse(); } if(mRight) { mRight->postorderTraverse(); } std::cout << " " << getValue(); } void levelorderTraverse() const { std::queue<const TreeNode*> q; q.push(this); while(!q.empty()) { const TreeNode* n = q.front(); q.pop(); std::cout << " " << n->getValue(); if(n->left()) { q.push(n->left()); } if(n->right()) { q.push(n->right()); } } } protected: T mValue; boost::scoped_ptr<TreeNode> mLeft; boost::scoped_ptr<TreeNode> mRight; private: TreeNode(); }; int main() { TreeNode<int> root(1, new TreeNode<int>(2, new TreeNode<int>(4, new TreeNode<int>(7)), new TreeNode<int>(5)), new TreeNode<int>(3, new TreeNode<int>(6, new TreeNode<int>(8), new TreeNode<int>(9)))); std::cout << "preorder: "; root.preorderTraverse(); std::cout << std::endl; std::cout << "inorder: "; root.inorderTraverse(); std::cout << std::endl; std::cout << "postorder: "; root.postorderTraverse(); std::cout << std::endl; std::cout << "level-order:"; root.levelorderTraverse(); std::cout << std::endl; return 0; }
Generate an equivalent Go version of this Ada code.
with Ada.Text_Io; use Ada.Text_Io; with Ada.Unchecked_Deallocation; with Ada.Containers.Doubly_Linked_Lists; procedure Tree_Traversal is type Node; type Node_Access is access Node; type Node is record Left : Node_Access := null; Right : Node_Access := null; Data : Integer; end record; procedure Destroy_Tree(N : in out Node_Access) is procedure free is new Ada.Unchecked_Deallocation(Node, Node_Access); begin if N.Left /= null then Destroy_Tree(N.Left); end if; if N.Right /= null then Destroy_Tree(N.Right); end if; Free(N); end Destroy_Tree; function Tree(Value : Integer; Left : Node_Access; Right : Node_Access) return Node_Access is Temp : Node_Access := new Node; begin Temp.Data := Value; Temp.Left := Left; Temp.Right := Right; return Temp; end Tree; procedure Preorder(N : Node_Access) is begin Put(Integer'Image(N.Data)); if N.Left /= null then Preorder(N.Left); end if; if N.Right /= null then Preorder(N.Right); end if; end Preorder; procedure Inorder(N : Node_Access) is begin if N.Left /= null then Inorder(N.Left); end if; Put(Integer'Image(N.Data)); if N.Right /= null then Inorder(N.Right); end if; end Inorder; procedure Postorder(N : Node_Access) is begin if N.Left /= null then Postorder(N.Left); end if; if N.Right /= null then Postorder(N.Right); end if; Put(Integer'Image(N.Data)); end Postorder; procedure Levelorder(N : Node_Access) is package Queues is new Ada.Containers.Doubly_Linked_Lists(Node_Access); use Queues; Node_Queue : List; Next : Node_Access; begin Node_Queue.Append(N); while not Is_Empty(Node_Queue) loop Next := First_Element(Node_Queue); Delete_First(Node_Queue); Put(Integer'Image(Next.Data)); if Next.Left /= null then Node_Queue.Append(Next.Left); end if; if Next.Right /= null then Node_Queue.Append(Next.Right); end if; end loop; end Levelorder; N : Node_Access; begin N := Tree(1, Tree(2, Tree(4, Tree(7, null, null), null), Tree(5, null, null)), Tree(3, Tree(6, Tree(8, null, null), Tree(9, null, null)), null)); Put("preorder: "); Preorder(N); New_Line; Put("inorder: "); Inorder(N); New_Line; Put("postorder: "); Postorder(N); New_Line; Put("level order: "); Levelorder(N); New_Line; Destroy_Tree(N); end Tree_traversal;
package main import "fmt" type node struct { value int left, right *node } func (n *node) iterPreorder(visit func(int)) { if n == nil { return } visit(n.value) n.left.iterPreorder(visit) n.right.iterPreorder(visit) } func (n *node) iterInorder(visit func(int)) { if n == nil { return } n.left.iterInorder(visit) visit(n.value) n.right.iterInorder(visit) } func (n *node) iterPostorder(visit func(int)) { if n == nil { return } n.left.iterPostorder(visit) n.right.iterPostorder(visit) visit(n.value) } func (n *node) iterLevelorder(visit func(int)) { if n == nil { return } for queue := []*node{n}; ; { n = queue[0] visit(n.value) copy(queue, queue[1:]) queue = queue[:len(queue)-1] if n.left != nil { queue = append(queue, n.left) } if n.right != nil { queue = append(queue, n.right) } if len(queue) == 0 { return } } } func main() { tree := &node{1, &node{2, &node{4, &node{7, nil, nil}, nil}, &node{5, nil, nil}}, &node{3, &node{6, &node{8, nil, nil}, &node{9, nil, nil}}, nil}} fmt.Print("preorder: ") tree.iterPreorder(visitor) fmt.Println() fmt.Print("inorder: ") tree.iterInorder(visitor) fmt.Println() fmt.Print("postorder: ") tree.iterPostorder(visitor) fmt.Println() fmt.Print("level-order: ") tree.iterLevelorder(visitor) fmt.Println() } func visitor(value int) { fmt.Print(value, " ") }
Keep all operations the same but rewrite the snippet in Java.
with Ada.Text_Io; use Ada.Text_Io; with Ada.Unchecked_Deallocation; with Ada.Containers.Doubly_Linked_Lists; procedure Tree_Traversal is type Node; type Node_Access is access Node; type Node is record Left : Node_Access := null; Right : Node_Access := null; Data : Integer; end record; procedure Destroy_Tree(N : in out Node_Access) is procedure free is new Ada.Unchecked_Deallocation(Node, Node_Access); begin if N.Left /= null then Destroy_Tree(N.Left); end if; if N.Right /= null then Destroy_Tree(N.Right); end if; Free(N); end Destroy_Tree; function Tree(Value : Integer; Left : Node_Access; Right : Node_Access) return Node_Access is Temp : Node_Access := new Node; begin Temp.Data := Value; Temp.Left := Left; Temp.Right := Right; return Temp; end Tree; procedure Preorder(N : Node_Access) is begin Put(Integer'Image(N.Data)); if N.Left /= null then Preorder(N.Left); end if; if N.Right /= null then Preorder(N.Right); end if; end Preorder; procedure Inorder(N : Node_Access) is begin if N.Left /= null then Inorder(N.Left); end if; Put(Integer'Image(N.Data)); if N.Right /= null then Inorder(N.Right); end if; end Inorder; procedure Postorder(N : Node_Access) is begin if N.Left /= null then Postorder(N.Left); end if; if N.Right /= null then Postorder(N.Right); end if; Put(Integer'Image(N.Data)); end Postorder; procedure Levelorder(N : Node_Access) is package Queues is new Ada.Containers.Doubly_Linked_Lists(Node_Access); use Queues; Node_Queue : List; Next : Node_Access; begin Node_Queue.Append(N); while not Is_Empty(Node_Queue) loop Next := First_Element(Node_Queue); Delete_First(Node_Queue); Put(Integer'Image(Next.Data)); if Next.Left /= null then Node_Queue.Append(Next.Left); end if; if Next.Right /= null then Node_Queue.Append(Next.Right); end if; end loop; end Levelorder; N : Node_Access; begin N := Tree(1, Tree(2, Tree(4, Tree(7, null, null), null), Tree(5, null, null)), Tree(3, Tree(6, Tree(8, null, null), Tree(9, null, null)), null)); Put("preorder: "); Preorder(N); New_Line; Put("inorder: "); Inorder(N); New_Line; Put("postorder: "); Postorder(N); New_Line; Put("level order: "); Levelorder(N); New_Line; Destroy_Tree(N); end Tree_traversal;
import java.util.*; public class TreeTraversal { static class Node<T> { T value; Node<T> left; Node<T> right; Node(T value) { this.value = value; } void visit() { System.out.print(this.value + " "); } } static enum ORDER { PREORDER, INORDER, POSTORDER, LEVEL } static <T> void traverse(Node<T> node, ORDER order) { if (node == null) { return; } switch (order) { case PREORDER: node.visit(); traverse(node.left, order); traverse(node.right, order); break; case INORDER: traverse(node.left, order); node.visit(); traverse(node.right, order); break; case POSTORDER: traverse(node.left, order); traverse(node.right, order); node.visit(); break; case LEVEL: Queue<Node<T>> queue = new LinkedList<>(); queue.add(node); while(!queue.isEmpty()){ Node<T> next = queue.remove(); next.visit(); if(next.left!=null) queue.add(next.left); if(next.right!=null) queue.add(next.right); } } } public static void main(String[] args) { Node<Integer> one = new Node<Integer>(1); Node<Integer> two = new Node<Integer>(2); Node<Integer> three = new Node<Integer>(3); Node<Integer> four = new Node<Integer>(4); Node<Integer> five = new Node<Integer>(5); Node<Integer> six = new Node<Integer>(6); Node<Integer> seven = new Node<Integer>(7); Node<Integer> eight = new Node<Integer>(8); Node<Integer> nine = new Node<Integer>(9); one.left = two; one.right = three; two.left = four; two.right = five; three.left = six; four.left = seven; six.left = eight; six.right = nine; traverse(one, ORDER.PREORDER); System.out.println(); traverse(one, ORDER.INORDER); System.out.println(); traverse(one, ORDER.POSTORDER); System.out.println(); traverse(one, ORDER.LEVEL); } }
Translate the given Ada code snippet into Python without altering its behavior.
with Ada.Text_Io; use Ada.Text_Io; with Ada.Unchecked_Deallocation; with Ada.Containers.Doubly_Linked_Lists; procedure Tree_Traversal is type Node; type Node_Access is access Node; type Node is record Left : Node_Access := null; Right : Node_Access := null; Data : Integer; end record; procedure Destroy_Tree(N : in out Node_Access) is procedure free is new Ada.Unchecked_Deallocation(Node, Node_Access); begin if N.Left /= null then Destroy_Tree(N.Left); end if; if N.Right /= null then Destroy_Tree(N.Right); end if; Free(N); end Destroy_Tree; function Tree(Value : Integer; Left : Node_Access; Right : Node_Access) return Node_Access is Temp : Node_Access := new Node; begin Temp.Data := Value; Temp.Left := Left; Temp.Right := Right; return Temp; end Tree; procedure Preorder(N : Node_Access) is begin Put(Integer'Image(N.Data)); if N.Left /= null then Preorder(N.Left); end if; if N.Right /= null then Preorder(N.Right); end if; end Preorder; procedure Inorder(N : Node_Access) is begin if N.Left /= null then Inorder(N.Left); end if; Put(Integer'Image(N.Data)); if N.Right /= null then Inorder(N.Right); end if; end Inorder; procedure Postorder(N : Node_Access) is begin if N.Left /= null then Postorder(N.Left); end if; if N.Right /= null then Postorder(N.Right); end if; Put(Integer'Image(N.Data)); end Postorder; procedure Levelorder(N : Node_Access) is package Queues is new Ada.Containers.Doubly_Linked_Lists(Node_Access); use Queues; Node_Queue : List; Next : Node_Access; begin Node_Queue.Append(N); while not Is_Empty(Node_Queue) loop Next := First_Element(Node_Queue); Delete_First(Node_Queue); Put(Integer'Image(Next.Data)); if Next.Left /= null then Node_Queue.Append(Next.Left); end if; if Next.Right /= null then Node_Queue.Append(Next.Right); end if; end loop; end Levelorder; N : Node_Access; begin N := Tree(1, Tree(2, Tree(4, Tree(7, null, null), null), Tree(5, null, null)), Tree(3, Tree(6, Tree(8, null, null), Tree(9, null, null)), null)); Put("preorder: "); Preorder(N); New_Line; Put("inorder: "); Inorder(N); New_Line; Put("postorder: "); Postorder(N); New_Line; Put("level order: "); Levelorder(N); New_Line; Destroy_Tree(N); end Tree_traversal;
from collections import namedtuple Node = namedtuple('Node', 'data, left, right') tree = Node(1, Node(2, Node(4, Node(7, None, None), None), Node(5, None, None)), Node(3, Node(6, Node(8, None, None), Node(9, None, None)), None)) def printwithspace(i): print(i, end=' ') def dfs(order, node, visitor): if node is not None: for action in order: if action == 'N': visitor(node.data) elif action == 'L': dfs(order, node.left, visitor) elif action == 'R': dfs(order, node.right, visitor) def preorder(node, visitor = printwithspace): dfs('NLR', node, visitor) def inorder(node, visitor = printwithspace): dfs('LNR', node, visitor) def postorder(node, visitor = printwithspace): dfs('LRN', node, visitor) def ls(node, more, visitor, order='TB'): "Level-based Top-to-Bottom or Bottom-to-Top tree search" if node: if more is None: more = [] more += [node.left, node.right] for action in order: if action == 'B' and more: ls(more[0], more[1:], visitor, order) elif action == 'T' and node: visitor(node.data) def levelorder(node, more=None, visitor = printwithspace): ls(node, more, visitor, 'TB') def reverse_preorder(node, visitor = printwithspace): dfs('RLN', node, visitor) def bottom_up_order(node, more=None, visitor = printwithspace, order='BT'): ls(node, more, visitor, 'BT') if __name__ == '__main__': w = 10 for traversal in [preorder, inorder, postorder, levelorder, reverse_preorder, bottom_up_order]: if traversal == reverse_preorder: w = 20 print('\nThe generalisation of function dfs allows:') if traversal == bottom_up_order: print('The generalisation of function ls allows:') print(f"{traversal.__name__:>{w}}:", end=' ') traversal(tree) print()
Generate an equivalent VB version of this Ada code.
with Ada.Text_Io; use Ada.Text_Io; with Ada.Unchecked_Deallocation; with Ada.Containers.Doubly_Linked_Lists; procedure Tree_Traversal is type Node; type Node_Access is access Node; type Node is record Left : Node_Access := null; Right : Node_Access := null; Data : Integer; end record; procedure Destroy_Tree(N : in out Node_Access) is procedure free is new Ada.Unchecked_Deallocation(Node, Node_Access); begin if N.Left /= null then Destroy_Tree(N.Left); end if; if N.Right /= null then Destroy_Tree(N.Right); end if; Free(N); end Destroy_Tree; function Tree(Value : Integer; Left : Node_Access; Right : Node_Access) return Node_Access is Temp : Node_Access := new Node; begin Temp.Data := Value; Temp.Left := Left; Temp.Right := Right; return Temp; end Tree; procedure Preorder(N : Node_Access) is begin Put(Integer'Image(N.Data)); if N.Left /= null then Preorder(N.Left); end if; if N.Right /= null then Preorder(N.Right); end if; end Preorder; procedure Inorder(N : Node_Access) is begin if N.Left /= null then Inorder(N.Left); end if; Put(Integer'Image(N.Data)); if N.Right /= null then Inorder(N.Right); end if; end Inorder; procedure Postorder(N : Node_Access) is begin if N.Left /= null then Postorder(N.Left); end if; if N.Right /= null then Postorder(N.Right); end if; Put(Integer'Image(N.Data)); end Postorder; procedure Levelorder(N : Node_Access) is package Queues is new Ada.Containers.Doubly_Linked_Lists(Node_Access); use Queues; Node_Queue : List; Next : Node_Access; begin Node_Queue.Append(N); while not Is_Empty(Node_Queue) loop Next := First_Element(Node_Queue); Delete_First(Node_Queue); Put(Integer'Image(Next.Data)); if Next.Left /= null then Node_Queue.Append(Next.Left); end if; if Next.Right /= null then Node_Queue.Append(Next.Right); end if; end loop; end Levelorder; N : Node_Access; begin N := Tree(1, Tree(2, Tree(4, Tree(7, null, null), null), Tree(5, null, null)), Tree(3, Tree(6, Tree(8, null, null), Tree(9, null, null)), null)); Put("preorder: "); Preorder(N); New_Line; Put("inorder: "); Inorder(N); New_Line; Put("postorder: "); Postorder(N); New_Line; Put("level order: "); Levelorder(N); New_Line; Destroy_Tree(N); end Tree_traversal;
Public Value As Integer Public LeftChild As TreeItem Public RightChild As TreeItem
Please provide an equivalent version of this Arturo code in C.
tree: [1 [2 [4 [7 [] []] []] [5 [] []]] [3 [6 [8 [] []] [9 [] []]] []]] tree: [1 [2 [4 [7 ] ] [5 ]] [3 [6 [8 ] [9 ]] ]] visit: func [tree [block!]][prin rejoin [first tree " "]] left: :second right: :third preorder: func [tree [block!]][ if not empty? tree [visit tree] attempt [preorder left tree] attempt [preorder right tree] ] prin "preorder: " preorder tree print "" inorder: func [tree [block!]][ attempt [inorder left tree] if not empty? tree [visit tree] attempt [inorder right tree] ] prin "inorder: " inorder tree print "" postorder: func [tree [block!]][ attempt [postorder left tree] attempt [postorder right tree] if not empty? tree [visit tree] ] prin "postorder: " postorder tree print "" queue: [] enqueue: func [tree [block!]][append/only queue tree] dequeue: func [queue [block!]][take queue] level-order: func [tree [block!]][ clear head queue queue: enqueue tree while [not empty? queue] [ tree: dequeue queue if not empty? tree [visit tree] attempt [enqueue left tree] attempt [enqueue right tree] ] ] prin "level-order: " level-order tree
#include <stdlib.h> #include <stdio.h> typedef struct node_s { int value; struct node_s* left; struct node_s* right; } *node; node tree(int v, node l, node r) { node n = malloc(sizeof(struct node_s)); n->value = v; n->left = l; n->right = r; return n; } void destroy_tree(node n) { if (n->left) destroy_tree(n->left); if (n->right) destroy_tree(n->right); free(n); } void preorder(node n, void (*f)(int)) { f(n->value); if (n->left) preorder(n->left, f); if (n->right) preorder(n->right, f); } void inorder(node n, void (*f)(int)) { if (n->left) inorder(n->left, f); f(n->value); if (n->right) inorder(n->right, f); } void postorder(node n, void (*f)(int)) { if (n->left) postorder(n->left, f); if (n->right) postorder(n->right, f); f(n->value); } typedef struct qnode_s { struct qnode_s* next; node value; } *qnode; typedef struct { qnode begin, end; } queue; void enqueue(queue* q, node n) { qnode node = malloc(sizeof(struct qnode_s)); node->value = n; node->next = 0; if (q->end) q->end->next = node; else q->begin = node; q->end = node; } node dequeue(queue* q) { node tmp = q->begin->value; qnode second = q->begin->next; free(q->begin); q->begin = second; if (!q->begin) q->end = 0; return tmp; } int queue_empty(queue* q) { return !q->begin; } void levelorder(node n, void(*f)(int)) { queue nodequeue = {}; enqueue(&nodequeue, n); while (!queue_empty(&nodequeue)) { node next = dequeue(&nodequeue); f(next->value); if (next->left) enqueue(&nodequeue, next->left); if (next->right) enqueue(&nodequeue, next->right); } } void print(int n) { printf("%d ", n); } int main() { node n = tree(1, tree(2, tree(4, tree(7, 0, 0), 0), tree(5, 0, 0)), tree(3, tree(6, tree(8, 0, 0), tree(9, 0, 0)), 0)); printf("preorder: "); preorder(n, print); printf("\n"); printf("inorder: "); inorder(n, print); printf("\n"); printf("postorder: "); postorder(n, print); printf("\n"); printf("level-order: "); levelorder(n, print); printf("\n"); destroy_tree(n); return 0; }
Write a version of this Arturo function in C# with identical behavior.
tree: [1 [2 [4 [7 [] []] []] [5 [] []]] [3 [6 [8 [] []] [9 [] []]] []]] tree: [1 [2 [4 [7 ] ] [5 ]] [3 [6 [8 ] [9 ]] ]] visit: func [tree [block!]][prin rejoin [first tree " "]] left: :second right: :third preorder: func [tree [block!]][ if not empty? tree [visit tree] attempt [preorder left tree] attempt [preorder right tree] ] prin "preorder: " preorder tree print "" inorder: func [tree [block!]][ attempt [inorder left tree] if not empty? tree [visit tree] attempt [inorder right tree] ] prin "inorder: " inorder tree print "" postorder: func [tree [block!]][ attempt [postorder left tree] attempt [postorder right tree] if not empty? tree [visit tree] ] prin "postorder: " postorder tree print "" queue: [] enqueue: func [tree [block!]][append/only queue tree] dequeue: func [queue [block!]][take queue] level-order: func [tree [block!]][ clear head queue queue: enqueue tree while [not empty? queue] [ tree: dequeue queue if not empty? tree [visit tree] attempt [enqueue left tree] attempt [enqueue right tree] ] ] prin "level-order: " level-order tree
using System; using System.Collections.Generic; using System.Linq; class Node { int Value; Node Left; Node Right; Node(int value = default(int), Node left = default(Node), Node right = default(Node)) { Value = value; Left = left; Right = right; } IEnumerable<int> Preorder() { yield return Value; if (Left != null) foreach (var value in Left.Preorder()) yield return value; if (Right != null) foreach (var value in Right.Preorder()) yield return value; } IEnumerable<int> Inorder() { if (Left != null) foreach (var value in Left.Inorder()) yield return value; yield return Value; if (Right != null) foreach (var value in Right.Inorder()) yield return value; } IEnumerable<int> Postorder() { if (Left != null) foreach (var value in Left.Postorder()) yield return value; if (Right != null) foreach (var value in Right.Postorder()) yield return value; yield return Value; } IEnumerable<int> LevelOrder() { var queue = new Queue<Node>(); queue.Enqueue(this); while (queue.Any()) { var node = queue.Dequeue(); yield return node.Value; if (node.Left != null) queue.Enqueue(node.Left); if (node.Right != null) queue.Enqueue(node.Right); } } static void Main() { var tree = new Node(1, new Node(2, new Node(4, new Node(7)), new Node(5)), new Node(3, new Node(6, new Node(8), new Node(9)))); foreach (var traversal in new Func<IEnumerable<int>>[] { tree.Preorder, tree.Inorder, tree.Postorder, tree.LevelOrder }) Console.WriteLine("{0}:\t{1}", traversal.Method.Name, string.Join(" ", traversal())); } }
Produce a functionally identical C++ code for the snippet given in Arturo.
tree: [1 [2 [4 [7 [] []] []] [5 [] []]] [3 [6 [8 [] []] [9 [] []]] []]] tree: [1 [2 [4 [7 ] ] [5 ]] [3 [6 [8 ] [9 ]] ]] visit: func [tree [block!]][prin rejoin [first tree " "]] left: :second right: :third preorder: func [tree [block!]][ if not empty? tree [visit tree] attempt [preorder left tree] attempt [preorder right tree] ] prin "preorder: " preorder tree print "" inorder: func [tree [block!]][ attempt [inorder left tree] if not empty? tree [visit tree] attempt [inorder right tree] ] prin "inorder: " inorder tree print "" postorder: func [tree [block!]][ attempt [postorder left tree] attempt [postorder right tree] if not empty? tree [visit tree] ] prin "postorder: " postorder tree print "" queue: [] enqueue: func [tree [block!]][append/only queue tree] dequeue: func [queue [block!]][take queue] level-order: func [tree [block!]][ clear head queue queue: enqueue tree while [not empty? queue] [ tree: dequeue queue if not empty? tree [visit tree] attempt [enqueue left tree] attempt [enqueue right tree] ] ] prin "level-order: " level-order tree
#include <boost/scoped_ptr.hpp> #include <iostream> #include <queue> template<typename T> class TreeNode { public: TreeNode(const T& n, TreeNode* left = NULL, TreeNode* right = NULL) : mValue(n), mLeft(left), mRight(right) {} T getValue() const { return mValue; } TreeNode* left() const { return mLeft.get(); } TreeNode* right() const { return mRight.get(); } void preorderTraverse() const { std::cout << " " << getValue(); if(mLeft) { mLeft->preorderTraverse(); } if(mRight) { mRight->preorderTraverse(); } } void inorderTraverse() const { if(mLeft) { mLeft->inorderTraverse(); } std::cout << " " << getValue(); if(mRight) { mRight->inorderTraverse(); } } void postorderTraverse() const { if(mLeft) { mLeft->postorderTraverse(); } if(mRight) { mRight->postorderTraverse(); } std::cout << " " << getValue(); } void levelorderTraverse() const { std::queue<const TreeNode*> q; q.push(this); while(!q.empty()) { const TreeNode* n = q.front(); q.pop(); std::cout << " " << n->getValue(); if(n->left()) { q.push(n->left()); } if(n->right()) { q.push(n->right()); } } } protected: T mValue; boost::scoped_ptr<TreeNode> mLeft; boost::scoped_ptr<TreeNode> mRight; private: TreeNode(); }; int main() { TreeNode<int> root(1, new TreeNode<int>(2, new TreeNode<int>(4, new TreeNode<int>(7)), new TreeNode<int>(5)), new TreeNode<int>(3, new TreeNode<int>(6, new TreeNode<int>(8), new TreeNode<int>(9)))); std::cout << "preorder: "; root.preorderTraverse(); std::cout << std::endl; std::cout << "inorder: "; root.inorderTraverse(); std::cout << std::endl; std::cout << "postorder: "; root.postorderTraverse(); std::cout << std::endl; std::cout << "level-order:"; root.levelorderTraverse(); std::cout << std::endl; return 0; }
Write the same algorithm in Java as shown in this Arturo implementation.
tree: [1 [2 [4 [7 [] []] []] [5 [] []]] [3 [6 [8 [] []] [9 [] []]] []]] tree: [1 [2 [4 [7 ] ] [5 ]] [3 [6 [8 ] [9 ]] ]] visit: func [tree [block!]][prin rejoin [first tree " "]] left: :second right: :third preorder: func [tree [block!]][ if not empty? tree [visit tree] attempt [preorder left tree] attempt [preorder right tree] ] prin "preorder: " preorder tree print "" inorder: func [tree [block!]][ attempt [inorder left tree] if not empty? tree [visit tree] attempt [inorder right tree] ] prin "inorder: " inorder tree print "" postorder: func [tree [block!]][ attempt [postorder left tree] attempt [postorder right tree] if not empty? tree [visit tree] ] prin "postorder: " postorder tree print "" queue: [] enqueue: func [tree [block!]][append/only queue tree] dequeue: func [queue [block!]][take queue] level-order: func [tree [block!]][ clear head queue queue: enqueue tree while [not empty? queue] [ tree: dequeue queue if not empty? tree [visit tree] attempt [enqueue left tree] attempt [enqueue right tree] ] ] prin "level-order: " level-order tree
import java.util.*; public class TreeTraversal { static class Node<T> { T value; Node<T> left; Node<T> right; Node(T value) { this.value = value; } void visit() { System.out.print(this.value + " "); } } static enum ORDER { PREORDER, INORDER, POSTORDER, LEVEL } static <T> void traverse(Node<T> node, ORDER order) { if (node == null) { return; } switch (order) { case PREORDER: node.visit(); traverse(node.left, order); traverse(node.right, order); break; case INORDER: traverse(node.left, order); node.visit(); traverse(node.right, order); break; case POSTORDER: traverse(node.left, order); traverse(node.right, order); node.visit(); break; case LEVEL: Queue<Node<T>> queue = new LinkedList<>(); queue.add(node); while(!queue.isEmpty()){ Node<T> next = queue.remove(); next.visit(); if(next.left!=null) queue.add(next.left); if(next.right!=null) queue.add(next.right); } } } public static void main(String[] args) { Node<Integer> one = new Node<Integer>(1); Node<Integer> two = new Node<Integer>(2); Node<Integer> three = new Node<Integer>(3); Node<Integer> four = new Node<Integer>(4); Node<Integer> five = new Node<Integer>(5); Node<Integer> six = new Node<Integer>(6); Node<Integer> seven = new Node<Integer>(7); Node<Integer> eight = new Node<Integer>(8); Node<Integer> nine = new Node<Integer>(9); one.left = two; one.right = three; two.left = four; two.right = five; three.left = six; four.left = seven; six.left = eight; six.right = nine; traverse(one, ORDER.PREORDER); System.out.println(); traverse(one, ORDER.INORDER); System.out.println(); traverse(one, ORDER.POSTORDER); System.out.println(); traverse(one, ORDER.LEVEL); } }
Maintain the same structure and functionality when rewriting this code in Python.
tree: [1 [2 [4 [7 [] []] []] [5 [] []]] [3 [6 [8 [] []] [9 [] []]] []]] tree: [1 [2 [4 [7 ] ] [5 ]] [3 [6 [8 ] [9 ]] ]] visit: func [tree [block!]][prin rejoin [first tree " "]] left: :second right: :third preorder: func [tree [block!]][ if not empty? tree [visit tree] attempt [preorder left tree] attempt [preorder right tree] ] prin "preorder: " preorder tree print "" inorder: func [tree [block!]][ attempt [inorder left tree] if not empty? tree [visit tree] attempt [inorder right tree] ] prin "inorder: " inorder tree print "" postorder: func [tree [block!]][ attempt [postorder left tree] attempt [postorder right tree] if not empty? tree [visit tree] ] prin "postorder: " postorder tree print "" queue: [] enqueue: func [tree [block!]][append/only queue tree] dequeue: func [queue [block!]][take queue] level-order: func [tree [block!]][ clear head queue queue: enqueue tree while [not empty? queue] [ tree: dequeue queue if not empty? tree [visit tree] attempt [enqueue left tree] attempt [enqueue right tree] ] ] prin "level-order: " level-order tree
from collections import namedtuple Node = namedtuple('Node', 'data, left, right') tree = Node(1, Node(2, Node(4, Node(7, None, None), None), Node(5, None, None)), Node(3, Node(6, Node(8, None, None), Node(9, None, None)), None)) def printwithspace(i): print(i, end=' ') def dfs(order, node, visitor): if node is not None: for action in order: if action == 'N': visitor(node.data) elif action == 'L': dfs(order, node.left, visitor) elif action == 'R': dfs(order, node.right, visitor) def preorder(node, visitor = printwithspace): dfs('NLR', node, visitor) def inorder(node, visitor = printwithspace): dfs('LNR', node, visitor) def postorder(node, visitor = printwithspace): dfs('LRN', node, visitor) def ls(node, more, visitor, order='TB'): "Level-based Top-to-Bottom or Bottom-to-Top tree search" if node: if more is None: more = [] more += [node.left, node.right] for action in order: if action == 'B' and more: ls(more[0], more[1:], visitor, order) elif action == 'T' and node: visitor(node.data) def levelorder(node, more=None, visitor = printwithspace): ls(node, more, visitor, 'TB') def reverse_preorder(node, visitor = printwithspace): dfs('RLN', node, visitor) def bottom_up_order(node, more=None, visitor = printwithspace, order='BT'): ls(node, more, visitor, 'BT') if __name__ == '__main__': w = 10 for traversal in [preorder, inorder, postorder, levelorder, reverse_preorder, bottom_up_order]: if traversal == reverse_preorder: w = 20 print('\nThe generalisation of function dfs allows:') if traversal == bottom_up_order: print('The generalisation of function ls allows:') print(f"{traversal.__name__:>{w}}:", end=' ') traversal(tree) print()
Write the same code in VB as shown below in Arturo.
tree: [1 [2 [4 [7 [] []] []] [5 [] []]] [3 [6 [8 [] []] [9 [] []]] []]] tree: [1 [2 [4 [7 ] ] [5 ]] [3 [6 [8 ] [9 ]] ]] visit: func [tree [block!]][prin rejoin [first tree " "]] left: :second right: :third preorder: func [tree [block!]][ if not empty? tree [visit tree] attempt [preorder left tree] attempt [preorder right tree] ] prin "preorder: " preorder tree print "" inorder: func [tree [block!]][ attempt [inorder left tree] if not empty? tree [visit tree] attempt [inorder right tree] ] prin "inorder: " inorder tree print "" postorder: func [tree [block!]][ attempt [postorder left tree] attempt [postorder right tree] if not empty? tree [visit tree] ] prin "postorder: " postorder tree print "" queue: [] enqueue: func [tree [block!]][append/only queue tree] dequeue: func [queue [block!]][take queue] level-order: func [tree [block!]][ clear head queue queue: enqueue tree while [not empty? queue] [ tree: dequeue queue if not empty? tree [visit tree] attempt [enqueue left tree] attempt [enqueue right tree] ] ] prin "level-order: " level-order tree
Public Value As Integer Public LeftChild As TreeItem Public RightChild As TreeItem
Translate the given Arturo code snippet into Go without altering its behavior.
tree: [1 [2 [4 [7 [] []] []] [5 [] []]] [3 [6 [8 [] []] [9 [] []]] []]] tree: [1 [2 [4 [7 ] ] [5 ]] [3 [6 [8 ] [9 ]] ]] visit: func [tree [block!]][prin rejoin [first tree " "]] left: :second right: :third preorder: func [tree [block!]][ if not empty? tree [visit tree] attempt [preorder left tree] attempt [preorder right tree] ] prin "preorder: " preorder tree print "" inorder: func [tree [block!]][ attempt [inorder left tree] if not empty? tree [visit tree] attempt [inorder right tree] ] prin "inorder: " inorder tree print "" postorder: func [tree [block!]][ attempt [postorder left tree] attempt [postorder right tree] if not empty? tree [visit tree] ] prin "postorder: " postorder tree print "" queue: [] enqueue: func [tree [block!]][append/only queue tree] dequeue: func [queue [block!]][take queue] level-order: func [tree [block!]][ clear head queue queue: enqueue tree while [not empty? queue] [ tree: dequeue queue if not empty? tree [visit tree] attempt [enqueue left tree] attempt [enqueue right tree] ] ] prin "level-order: " level-order tree
package main import "fmt" type node struct { value int left, right *node } func (n *node) iterPreorder(visit func(int)) { if n == nil { return } visit(n.value) n.left.iterPreorder(visit) n.right.iterPreorder(visit) } func (n *node) iterInorder(visit func(int)) { if n == nil { return } n.left.iterInorder(visit) visit(n.value) n.right.iterInorder(visit) } func (n *node) iterPostorder(visit func(int)) { if n == nil { return } n.left.iterPostorder(visit) n.right.iterPostorder(visit) visit(n.value) } func (n *node) iterLevelorder(visit func(int)) { if n == nil { return } for queue := []*node{n}; ; { n = queue[0] visit(n.value) copy(queue, queue[1:]) queue = queue[:len(queue)-1] if n.left != nil { queue = append(queue, n.left) } if n.right != nil { queue = append(queue, n.right) } if len(queue) == 0 { return } } } func main() { tree := &node{1, &node{2, &node{4, &node{7, nil, nil}, nil}, &node{5, nil, nil}}, &node{3, &node{6, &node{8, nil, nil}, &node{9, nil, nil}}, nil}} fmt.Print("preorder: ") tree.iterPreorder(visitor) fmt.Println() fmt.Print("inorder: ") tree.iterInorder(visitor) fmt.Println() fmt.Print("postorder: ") tree.iterPostorder(visitor) fmt.Println() fmt.Print("level-order: ") tree.iterLevelorder(visitor) fmt.Println() } func visitor(value int) { fmt.Print(value, " ") }
Produce a language-to-language conversion: from AutoHotKey to C, same semantics.
AddNode(Tree,1,2,3,1)  AddNode(Tree,2,4,5,2) AddNode(Tree,3,6,0,3) AddNode(Tree,4,7,0,4) AddNode(Tree,5,0,0,5) AddNode(Tree,6,8,9,6) AddNode(Tree,7,0,0,7) AddNode(Tree,8,0,0,8) AddNode(Tree,9,0,0,9) MsgBox % "Preorder: " PreOrder(Tree,1)   MsgBox % "Inorder: " InOrder(Tree,1)   MsgBox % "postorder: " PostOrder(Tree,1)  MsgBox % "levelorder: " LevOrder(Tree,1)   AddNode(ByRef Tree,Node,Left,Right,Value) { if !isobject(Tree) Tree := object() Tree[Node, "L"] := Left Tree[Node, "R"] := Right Tree[Node, "V"] := Value } PreOrder(Tree,Node) { ptree := Tree[Node, "V"] " " . ((L:=Tree[Node, "L"]) ? PreOrder(Tree,L) : "") . ((R:=Tree[Node, "R"]) ? PreOrder(Tree,R) : "") return ptree } InOrder(Tree,Node) { Return itree := ((L:=Tree[Node, "L"]) ? InOrder(Tree,L) : "") . Tree[Node, "V"] " " . ((R:=Tree[Node, "R"]) ? InOrder(Tree,R) : "") } PostOrder(Tree,Node) { Return ptree := ((L:=Tree[Node, "L"]) ? PostOrder(Tree,L) : "") . ((R:=Tree[Node, "R"]) ? PostOrder(Tree,R) : "") . Tree[Node, "V"] " " } LevOrder(Tree,Node,Lev=1) { Static   i%Lev% .= Tree[Node, "V"] " "  If (L:=Tree[Node, "L"]) LevOrder(Tree,L,Lev+1) If (R:=Tree[Node, "R"]) LevOrder(Tree,R,Lev+1) If (Lev > 1) Return While i%Lev%   t .= i%Lev%, Lev++ Return t }
#include <stdlib.h> #include <stdio.h> typedef struct node_s { int value; struct node_s* left; struct node_s* right; } *node; node tree(int v, node l, node r) { node n = malloc(sizeof(struct node_s)); n->value = v; n->left = l; n->right = r; return n; } void destroy_tree(node n) { if (n->left) destroy_tree(n->left); if (n->right) destroy_tree(n->right); free(n); } void preorder(node n, void (*f)(int)) { f(n->value); if (n->left) preorder(n->left, f); if (n->right) preorder(n->right, f); } void inorder(node n, void (*f)(int)) { if (n->left) inorder(n->left, f); f(n->value); if (n->right) inorder(n->right, f); } void postorder(node n, void (*f)(int)) { if (n->left) postorder(n->left, f); if (n->right) postorder(n->right, f); f(n->value); } typedef struct qnode_s { struct qnode_s* next; node value; } *qnode; typedef struct { qnode begin, end; } queue; void enqueue(queue* q, node n) { qnode node = malloc(sizeof(struct qnode_s)); node->value = n; node->next = 0; if (q->end) q->end->next = node; else q->begin = node; q->end = node; } node dequeue(queue* q) { node tmp = q->begin->value; qnode second = q->begin->next; free(q->begin); q->begin = second; if (!q->begin) q->end = 0; return tmp; } int queue_empty(queue* q) { return !q->begin; } void levelorder(node n, void(*f)(int)) { queue nodequeue = {}; enqueue(&nodequeue, n); while (!queue_empty(&nodequeue)) { node next = dequeue(&nodequeue); f(next->value); if (next->left) enqueue(&nodequeue, next->left); if (next->right) enqueue(&nodequeue, next->right); } } void print(int n) { printf("%d ", n); } int main() { node n = tree(1, tree(2, tree(4, tree(7, 0, 0), 0), tree(5, 0, 0)), tree(3, tree(6, tree(8, 0, 0), tree(9, 0, 0)), 0)); printf("preorder: "); preorder(n, print); printf("\n"); printf("inorder: "); inorder(n, print); printf("\n"); printf("postorder: "); postorder(n, print); printf("\n"); printf("level-order: "); levelorder(n, print); printf("\n"); destroy_tree(n); return 0; }
Please provide an equivalent version of this AutoHotKey code in C#.
AddNode(Tree,1,2,3,1)  AddNode(Tree,2,4,5,2) AddNode(Tree,3,6,0,3) AddNode(Tree,4,7,0,4) AddNode(Tree,5,0,0,5) AddNode(Tree,6,8,9,6) AddNode(Tree,7,0,0,7) AddNode(Tree,8,0,0,8) AddNode(Tree,9,0,0,9) MsgBox % "Preorder: " PreOrder(Tree,1)   MsgBox % "Inorder: " InOrder(Tree,1)   MsgBox % "postorder: " PostOrder(Tree,1)  MsgBox % "levelorder: " LevOrder(Tree,1)   AddNode(ByRef Tree,Node,Left,Right,Value) { if !isobject(Tree) Tree := object() Tree[Node, "L"] := Left Tree[Node, "R"] := Right Tree[Node, "V"] := Value } PreOrder(Tree,Node) { ptree := Tree[Node, "V"] " " . ((L:=Tree[Node, "L"]) ? PreOrder(Tree,L) : "") . ((R:=Tree[Node, "R"]) ? PreOrder(Tree,R) : "") return ptree } InOrder(Tree,Node) { Return itree := ((L:=Tree[Node, "L"]) ? InOrder(Tree,L) : "") . Tree[Node, "V"] " " . ((R:=Tree[Node, "R"]) ? InOrder(Tree,R) : "") } PostOrder(Tree,Node) { Return ptree := ((L:=Tree[Node, "L"]) ? PostOrder(Tree,L) : "") . ((R:=Tree[Node, "R"]) ? PostOrder(Tree,R) : "") . Tree[Node, "V"] " " } LevOrder(Tree,Node,Lev=1) { Static   i%Lev% .= Tree[Node, "V"] " "  If (L:=Tree[Node, "L"]) LevOrder(Tree,L,Lev+1) If (R:=Tree[Node, "R"]) LevOrder(Tree,R,Lev+1) If (Lev > 1) Return While i%Lev%   t .= i%Lev%, Lev++ Return t }
using System; using System.Collections.Generic; using System.Linq; class Node { int Value; Node Left; Node Right; Node(int value = default(int), Node left = default(Node), Node right = default(Node)) { Value = value; Left = left; Right = right; } IEnumerable<int> Preorder() { yield return Value; if (Left != null) foreach (var value in Left.Preorder()) yield return value; if (Right != null) foreach (var value in Right.Preorder()) yield return value; } IEnumerable<int> Inorder() { if (Left != null) foreach (var value in Left.Inorder()) yield return value; yield return Value; if (Right != null) foreach (var value in Right.Inorder()) yield return value; } IEnumerable<int> Postorder() { if (Left != null) foreach (var value in Left.Postorder()) yield return value; if (Right != null) foreach (var value in Right.Postorder()) yield return value; yield return Value; } IEnumerable<int> LevelOrder() { var queue = new Queue<Node>(); queue.Enqueue(this); while (queue.Any()) { var node = queue.Dequeue(); yield return node.Value; if (node.Left != null) queue.Enqueue(node.Left); if (node.Right != null) queue.Enqueue(node.Right); } } static void Main() { var tree = new Node(1, new Node(2, new Node(4, new Node(7)), new Node(5)), new Node(3, new Node(6, new Node(8), new Node(9)))); foreach (var traversal in new Func<IEnumerable<int>>[] { tree.Preorder, tree.Inorder, tree.Postorder, tree.LevelOrder }) Console.WriteLine("{0}:\t{1}", traversal.Method.Name, string.Join(" ", traversal())); } }
Port the provided AutoHotKey code into C++ while preserving the original functionality.
AddNode(Tree,1,2,3,1)  AddNode(Tree,2,4,5,2) AddNode(Tree,3,6,0,3) AddNode(Tree,4,7,0,4) AddNode(Tree,5,0,0,5) AddNode(Tree,6,8,9,6) AddNode(Tree,7,0,0,7) AddNode(Tree,8,0,0,8) AddNode(Tree,9,0,0,9) MsgBox % "Preorder: " PreOrder(Tree,1)   MsgBox % "Inorder: " InOrder(Tree,1)   MsgBox % "postorder: " PostOrder(Tree,1)  MsgBox % "levelorder: " LevOrder(Tree,1)   AddNode(ByRef Tree,Node,Left,Right,Value) { if !isobject(Tree) Tree := object() Tree[Node, "L"] := Left Tree[Node, "R"] := Right Tree[Node, "V"] := Value } PreOrder(Tree,Node) { ptree := Tree[Node, "V"] " " . ((L:=Tree[Node, "L"]) ? PreOrder(Tree,L) : "") . ((R:=Tree[Node, "R"]) ? PreOrder(Tree,R) : "") return ptree } InOrder(Tree,Node) { Return itree := ((L:=Tree[Node, "L"]) ? InOrder(Tree,L) : "") . Tree[Node, "V"] " " . ((R:=Tree[Node, "R"]) ? InOrder(Tree,R) : "") } PostOrder(Tree,Node) { Return ptree := ((L:=Tree[Node, "L"]) ? PostOrder(Tree,L) : "") . ((R:=Tree[Node, "R"]) ? PostOrder(Tree,R) : "") . Tree[Node, "V"] " " } LevOrder(Tree,Node,Lev=1) { Static   i%Lev% .= Tree[Node, "V"] " "  If (L:=Tree[Node, "L"]) LevOrder(Tree,L,Lev+1) If (R:=Tree[Node, "R"]) LevOrder(Tree,R,Lev+1) If (Lev > 1) Return While i%Lev%   t .= i%Lev%, Lev++ Return t }
#include <boost/scoped_ptr.hpp> #include <iostream> #include <queue> template<typename T> class TreeNode { public: TreeNode(const T& n, TreeNode* left = NULL, TreeNode* right = NULL) : mValue(n), mLeft(left), mRight(right) {} T getValue() const { return mValue; } TreeNode* left() const { return mLeft.get(); } TreeNode* right() const { return mRight.get(); } void preorderTraverse() const { std::cout << " " << getValue(); if(mLeft) { mLeft->preorderTraverse(); } if(mRight) { mRight->preorderTraverse(); } } void inorderTraverse() const { if(mLeft) { mLeft->inorderTraverse(); } std::cout << " " << getValue(); if(mRight) { mRight->inorderTraverse(); } } void postorderTraverse() const { if(mLeft) { mLeft->postorderTraverse(); } if(mRight) { mRight->postorderTraverse(); } std::cout << " " << getValue(); } void levelorderTraverse() const { std::queue<const TreeNode*> q; q.push(this); while(!q.empty()) { const TreeNode* n = q.front(); q.pop(); std::cout << " " << n->getValue(); if(n->left()) { q.push(n->left()); } if(n->right()) { q.push(n->right()); } } } protected: T mValue; boost::scoped_ptr<TreeNode> mLeft; boost::scoped_ptr<TreeNode> mRight; private: TreeNode(); }; int main() { TreeNode<int> root(1, new TreeNode<int>(2, new TreeNode<int>(4, new TreeNode<int>(7)), new TreeNode<int>(5)), new TreeNode<int>(3, new TreeNode<int>(6, new TreeNode<int>(8), new TreeNode<int>(9)))); std::cout << "preorder: "; root.preorderTraverse(); std::cout << std::endl; std::cout << "inorder: "; root.inorderTraverse(); std::cout << std::endl; std::cout << "postorder: "; root.postorderTraverse(); std::cout << std::endl; std::cout << "level-order:"; root.levelorderTraverse(); std::cout << std::endl; return 0; }
Convert this AutoHotKey block to Java, preserving its control flow and logic.
AddNode(Tree,1,2,3,1)  AddNode(Tree,2,4,5,2) AddNode(Tree,3,6,0,3) AddNode(Tree,4,7,0,4) AddNode(Tree,5,0,0,5) AddNode(Tree,6,8,9,6) AddNode(Tree,7,0,0,7) AddNode(Tree,8,0,0,8) AddNode(Tree,9,0,0,9) MsgBox % "Preorder: " PreOrder(Tree,1)   MsgBox % "Inorder: " InOrder(Tree,1)   MsgBox % "postorder: " PostOrder(Tree,1)  MsgBox % "levelorder: " LevOrder(Tree,1)   AddNode(ByRef Tree,Node,Left,Right,Value) { if !isobject(Tree) Tree := object() Tree[Node, "L"] := Left Tree[Node, "R"] := Right Tree[Node, "V"] := Value } PreOrder(Tree,Node) { ptree := Tree[Node, "V"] " " . ((L:=Tree[Node, "L"]) ? PreOrder(Tree,L) : "") . ((R:=Tree[Node, "R"]) ? PreOrder(Tree,R) : "") return ptree } InOrder(Tree,Node) { Return itree := ((L:=Tree[Node, "L"]) ? InOrder(Tree,L) : "") . Tree[Node, "V"] " " . ((R:=Tree[Node, "R"]) ? InOrder(Tree,R) : "") } PostOrder(Tree,Node) { Return ptree := ((L:=Tree[Node, "L"]) ? PostOrder(Tree,L) : "") . ((R:=Tree[Node, "R"]) ? PostOrder(Tree,R) : "") . Tree[Node, "V"] " " } LevOrder(Tree,Node,Lev=1) { Static   i%Lev% .= Tree[Node, "V"] " "  If (L:=Tree[Node, "L"]) LevOrder(Tree,L,Lev+1) If (R:=Tree[Node, "R"]) LevOrder(Tree,R,Lev+1) If (Lev > 1) Return While i%Lev%   t .= i%Lev%, Lev++ Return t }
import java.util.*; public class TreeTraversal { static class Node<T> { T value; Node<T> left; Node<T> right; Node(T value) { this.value = value; } void visit() { System.out.print(this.value + " "); } } static enum ORDER { PREORDER, INORDER, POSTORDER, LEVEL } static <T> void traverse(Node<T> node, ORDER order) { if (node == null) { return; } switch (order) { case PREORDER: node.visit(); traverse(node.left, order); traverse(node.right, order); break; case INORDER: traverse(node.left, order); node.visit(); traverse(node.right, order); break; case POSTORDER: traverse(node.left, order); traverse(node.right, order); node.visit(); break; case LEVEL: Queue<Node<T>> queue = new LinkedList<>(); queue.add(node); while(!queue.isEmpty()){ Node<T> next = queue.remove(); next.visit(); if(next.left!=null) queue.add(next.left); if(next.right!=null) queue.add(next.right); } } } public static void main(String[] args) { Node<Integer> one = new Node<Integer>(1); Node<Integer> two = new Node<Integer>(2); Node<Integer> three = new Node<Integer>(3); Node<Integer> four = new Node<Integer>(4); Node<Integer> five = new Node<Integer>(5); Node<Integer> six = new Node<Integer>(6); Node<Integer> seven = new Node<Integer>(7); Node<Integer> eight = new Node<Integer>(8); Node<Integer> nine = new Node<Integer>(9); one.left = two; one.right = three; two.left = four; two.right = five; three.left = six; four.left = seven; six.left = eight; six.right = nine; traverse(one, ORDER.PREORDER); System.out.println(); traverse(one, ORDER.INORDER); System.out.println(); traverse(one, ORDER.POSTORDER); System.out.println(); traverse(one, ORDER.LEVEL); } }
Convert the following code from AutoHotKey to Python, ensuring the logic remains intact.
AddNode(Tree,1,2,3,1)  AddNode(Tree,2,4,5,2) AddNode(Tree,3,6,0,3) AddNode(Tree,4,7,0,4) AddNode(Tree,5,0,0,5) AddNode(Tree,6,8,9,6) AddNode(Tree,7,0,0,7) AddNode(Tree,8,0,0,8) AddNode(Tree,9,0,0,9) MsgBox % "Preorder: " PreOrder(Tree,1)   MsgBox % "Inorder: " InOrder(Tree,1)   MsgBox % "postorder: " PostOrder(Tree,1)  MsgBox % "levelorder: " LevOrder(Tree,1)   AddNode(ByRef Tree,Node,Left,Right,Value) { if !isobject(Tree) Tree := object() Tree[Node, "L"] := Left Tree[Node, "R"] := Right Tree[Node, "V"] := Value } PreOrder(Tree,Node) { ptree := Tree[Node, "V"] " " . ((L:=Tree[Node, "L"]) ? PreOrder(Tree,L) : "") . ((R:=Tree[Node, "R"]) ? PreOrder(Tree,R) : "") return ptree } InOrder(Tree,Node) { Return itree := ((L:=Tree[Node, "L"]) ? InOrder(Tree,L) : "") . Tree[Node, "V"] " " . ((R:=Tree[Node, "R"]) ? InOrder(Tree,R) : "") } PostOrder(Tree,Node) { Return ptree := ((L:=Tree[Node, "L"]) ? PostOrder(Tree,L) : "") . ((R:=Tree[Node, "R"]) ? PostOrder(Tree,R) : "") . Tree[Node, "V"] " " } LevOrder(Tree,Node,Lev=1) { Static   i%Lev% .= Tree[Node, "V"] " "  If (L:=Tree[Node, "L"]) LevOrder(Tree,L,Lev+1) If (R:=Tree[Node, "R"]) LevOrder(Tree,R,Lev+1) If (Lev > 1) Return While i%Lev%   t .= i%Lev%, Lev++ Return t }
from collections import namedtuple Node = namedtuple('Node', 'data, left, right') tree = Node(1, Node(2, Node(4, Node(7, None, None), None), Node(5, None, None)), Node(3, Node(6, Node(8, None, None), Node(9, None, None)), None)) def printwithspace(i): print(i, end=' ') def dfs(order, node, visitor): if node is not None: for action in order: if action == 'N': visitor(node.data) elif action == 'L': dfs(order, node.left, visitor) elif action == 'R': dfs(order, node.right, visitor) def preorder(node, visitor = printwithspace): dfs('NLR', node, visitor) def inorder(node, visitor = printwithspace): dfs('LNR', node, visitor) def postorder(node, visitor = printwithspace): dfs('LRN', node, visitor) def ls(node, more, visitor, order='TB'): "Level-based Top-to-Bottom or Bottom-to-Top tree search" if node: if more is None: more = [] more += [node.left, node.right] for action in order: if action == 'B' and more: ls(more[0], more[1:], visitor, order) elif action == 'T' and node: visitor(node.data) def levelorder(node, more=None, visitor = printwithspace): ls(node, more, visitor, 'TB') def reverse_preorder(node, visitor = printwithspace): dfs('RLN', node, visitor) def bottom_up_order(node, more=None, visitor = printwithspace, order='BT'): ls(node, more, visitor, 'BT') if __name__ == '__main__': w = 10 for traversal in [preorder, inorder, postorder, levelorder, reverse_preorder, bottom_up_order]: if traversal == reverse_preorder: w = 20 print('\nThe generalisation of function dfs allows:') if traversal == bottom_up_order: print('The generalisation of function ls allows:') print(f"{traversal.__name__:>{w}}:", end=' ') traversal(tree) print()
Maintain the same structure and functionality when rewriting this code in VB.
AddNode(Tree,1,2,3,1)  AddNode(Tree,2,4,5,2) AddNode(Tree,3,6,0,3) AddNode(Tree,4,7,0,4) AddNode(Tree,5,0,0,5) AddNode(Tree,6,8,9,6) AddNode(Tree,7,0,0,7) AddNode(Tree,8,0,0,8) AddNode(Tree,9,0,0,9) MsgBox % "Preorder: " PreOrder(Tree,1)   MsgBox % "Inorder: " InOrder(Tree,1)   MsgBox % "postorder: " PostOrder(Tree,1)  MsgBox % "levelorder: " LevOrder(Tree,1)   AddNode(ByRef Tree,Node,Left,Right,Value) { if !isobject(Tree) Tree := object() Tree[Node, "L"] := Left Tree[Node, "R"] := Right Tree[Node, "V"] := Value } PreOrder(Tree,Node) { ptree := Tree[Node, "V"] " " . ((L:=Tree[Node, "L"]) ? PreOrder(Tree,L) : "") . ((R:=Tree[Node, "R"]) ? PreOrder(Tree,R) : "") return ptree } InOrder(Tree,Node) { Return itree := ((L:=Tree[Node, "L"]) ? InOrder(Tree,L) : "") . Tree[Node, "V"] " " . ((R:=Tree[Node, "R"]) ? InOrder(Tree,R) : "") } PostOrder(Tree,Node) { Return ptree := ((L:=Tree[Node, "L"]) ? PostOrder(Tree,L) : "") . ((R:=Tree[Node, "R"]) ? PostOrder(Tree,R) : "") . Tree[Node, "V"] " " } LevOrder(Tree,Node,Lev=1) { Static   i%Lev% .= Tree[Node, "V"] " "  If (L:=Tree[Node, "L"]) LevOrder(Tree,L,Lev+1) If (R:=Tree[Node, "R"]) LevOrder(Tree,R,Lev+1) If (Lev > 1) Return While i%Lev%   t .= i%Lev%, Lev++ Return t }
Public Value As Integer Public LeftChild As TreeItem Public RightChild As TreeItem
Translate the given AutoHotKey code snippet into Go without altering its behavior.
AddNode(Tree,1,2,3,1)  AddNode(Tree,2,4,5,2) AddNode(Tree,3,6,0,3) AddNode(Tree,4,7,0,4) AddNode(Tree,5,0,0,5) AddNode(Tree,6,8,9,6) AddNode(Tree,7,0,0,7) AddNode(Tree,8,0,0,8) AddNode(Tree,9,0,0,9) MsgBox % "Preorder: " PreOrder(Tree,1)   MsgBox % "Inorder: " InOrder(Tree,1)   MsgBox % "postorder: " PostOrder(Tree,1)  MsgBox % "levelorder: " LevOrder(Tree,1)   AddNode(ByRef Tree,Node,Left,Right,Value) { if !isobject(Tree) Tree := object() Tree[Node, "L"] := Left Tree[Node, "R"] := Right Tree[Node, "V"] := Value } PreOrder(Tree,Node) { ptree := Tree[Node, "V"] " " . ((L:=Tree[Node, "L"]) ? PreOrder(Tree,L) : "") . ((R:=Tree[Node, "R"]) ? PreOrder(Tree,R) : "") return ptree } InOrder(Tree,Node) { Return itree := ((L:=Tree[Node, "L"]) ? InOrder(Tree,L) : "") . Tree[Node, "V"] " " . ((R:=Tree[Node, "R"]) ? InOrder(Tree,R) : "") } PostOrder(Tree,Node) { Return ptree := ((L:=Tree[Node, "L"]) ? PostOrder(Tree,L) : "") . ((R:=Tree[Node, "R"]) ? PostOrder(Tree,R) : "") . Tree[Node, "V"] " " } LevOrder(Tree,Node,Lev=1) { Static   i%Lev% .= Tree[Node, "V"] " "  If (L:=Tree[Node, "L"]) LevOrder(Tree,L,Lev+1) If (R:=Tree[Node, "R"]) LevOrder(Tree,R,Lev+1) If (Lev > 1) Return While i%Lev%   t .= i%Lev%, Lev++ Return t }
package main import "fmt" type node struct { value int left, right *node } func (n *node) iterPreorder(visit func(int)) { if n == nil { return } visit(n.value) n.left.iterPreorder(visit) n.right.iterPreorder(visit) } func (n *node) iterInorder(visit func(int)) { if n == nil { return } n.left.iterInorder(visit) visit(n.value) n.right.iterInorder(visit) } func (n *node) iterPostorder(visit func(int)) { if n == nil { return } n.left.iterPostorder(visit) n.right.iterPostorder(visit) visit(n.value) } func (n *node) iterLevelorder(visit func(int)) { if n == nil { return } for queue := []*node{n}; ; { n = queue[0] visit(n.value) copy(queue, queue[1:]) queue = queue[:len(queue)-1] if n.left != nil { queue = append(queue, n.left) } if n.right != nil { queue = append(queue, n.right) } if len(queue) == 0 { return } } } func main() { tree := &node{1, &node{2, &node{4, &node{7, nil, nil}, nil}, &node{5, nil, nil}}, &node{3, &node{6, &node{8, nil, nil}, &node{9, nil, nil}}, nil}} fmt.Print("preorder: ") tree.iterPreorder(visitor) fmt.Println() fmt.Print("inorder: ") tree.iterInorder(visitor) fmt.Println() fmt.Print("postorder: ") tree.iterPostorder(visitor) fmt.Println() fmt.Print("level-order: ") tree.iterLevelorder(visitor) fmt.Println() } func visitor(value int) { fmt.Print(value, " ") }
Keep all operations the same but rewrite the snippet in C.
function preorder(tree, node, res, child) { if (node == "") return res[res["count"]++] = node split(tree[node], child, ",") preorder(tree,child[1],res) preorder(tree,child[2],res) } function inorder(tree, node, res, child) { if (node == "") return split(tree[node], child, ",") inorder(tree,child[1],res) res[res["count"]++] = node inorder(tree,child[2],res) } function postorder(tree, node, res, child) { if (node == "") return split(tree[node], child, ",") postorder(tree,child[1], res) postorder(tree,child[2], res) res[res["count"]++] = node } function levelorder(tree, node, res, nextnode, queue, child) { if (node == "") return queue["tail"] = 0 queue[queue["head"]++] = node while (queue["head"] - queue["tail"] >= 1) { nextnode = queue[queue["tail"]] delete queue[queue["tail"]++] res[res["count"]++] = nextnode split(tree[nextnode], child, ",") if (child[1] != "") queue[queue["head"]++] = child[1] if (child[2] != "") queue[queue["head"]++] = child[2] } delete queue } BEGIN { tree["1"] = "2,3" tree["2"] = "4,5" tree["3"] = "6," tree["4"] = "7," tree["5"] = "," tree["6"] = "8,9" tree["7"] = "," tree["8"] = "," tree["9"] = "," preorder(tree,"1",result) printf "preorder:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result inorder(tree,"1",result) printf "inorder:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result postorder(tree,"1",result) printf "postorder:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result levelorder(tree,"1",result) printf "level-order:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result }
#include <stdlib.h> #include <stdio.h> typedef struct node_s { int value; struct node_s* left; struct node_s* right; } *node; node tree(int v, node l, node r) { node n = malloc(sizeof(struct node_s)); n->value = v; n->left = l; n->right = r; return n; } void destroy_tree(node n) { if (n->left) destroy_tree(n->left); if (n->right) destroy_tree(n->right); free(n); } void preorder(node n, void (*f)(int)) { f(n->value); if (n->left) preorder(n->left, f); if (n->right) preorder(n->right, f); } void inorder(node n, void (*f)(int)) { if (n->left) inorder(n->left, f); f(n->value); if (n->right) inorder(n->right, f); } void postorder(node n, void (*f)(int)) { if (n->left) postorder(n->left, f); if (n->right) postorder(n->right, f); f(n->value); } typedef struct qnode_s { struct qnode_s* next; node value; } *qnode; typedef struct { qnode begin, end; } queue; void enqueue(queue* q, node n) { qnode node = malloc(sizeof(struct qnode_s)); node->value = n; node->next = 0; if (q->end) q->end->next = node; else q->begin = node; q->end = node; } node dequeue(queue* q) { node tmp = q->begin->value; qnode second = q->begin->next; free(q->begin); q->begin = second; if (!q->begin) q->end = 0; return tmp; } int queue_empty(queue* q) { return !q->begin; } void levelorder(node n, void(*f)(int)) { queue nodequeue = {}; enqueue(&nodequeue, n); while (!queue_empty(&nodequeue)) { node next = dequeue(&nodequeue); f(next->value); if (next->left) enqueue(&nodequeue, next->left); if (next->right) enqueue(&nodequeue, next->right); } } void print(int n) { printf("%d ", n); } int main() { node n = tree(1, tree(2, tree(4, tree(7, 0, 0), 0), tree(5, 0, 0)), tree(3, tree(6, tree(8, 0, 0), tree(9, 0, 0)), 0)); printf("preorder: "); preorder(n, print); printf("\n"); printf("inorder: "); inorder(n, print); printf("\n"); printf("postorder: "); postorder(n, print); printf("\n"); printf("level-order: "); levelorder(n, print); printf("\n"); destroy_tree(n); return 0; }
Produce a functionally identical C# code for the snippet given in AWK.
function preorder(tree, node, res, child) { if (node == "") return res[res["count"]++] = node split(tree[node], child, ",") preorder(tree,child[1],res) preorder(tree,child[2],res) } function inorder(tree, node, res, child) { if (node == "") return split(tree[node], child, ",") inorder(tree,child[1],res) res[res["count"]++] = node inorder(tree,child[2],res) } function postorder(tree, node, res, child) { if (node == "") return split(tree[node], child, ",") postorder(tree,child[1], res) postorder(tree,child[2], res) res[res["count"]++] = node } function levelorder(tree, node, res, nextnode, queue, child) { if (node == "") return queue["tail"] = 0 queue[queue["head"]++] = node while (queue["head"] - queue["tail"] >= 1) { nextnode = queue[queue["tail"]] delete queue[queue["tail"]++] res[res["count"]++] = nextnode split(tree[nextnode], child, ",") if (child[1] != "") queue[queue["head"]++] = child[1] if (child[2] != "") queue[queue["head"]++] = child[2] } delete queue } BEGIN { tree["1"] = "2,3" tree["2"] = "4,5" tree["3"] = "6," tree["4"] = "7," tree["5"] = "," tree["6"] = "8,9" tree["7"] = "," tree["8"] = "," tree["9"] = "," preorder(tree,"1",result) printf "preorder:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result inorder(tree,"1",result) printf "inorder:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result postorder(tree,"1",result) printf "postorder:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result levelorder(tree,"1",result) printf "level-order:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result }
using System; using System.Collections.Generic; using System.Linq; class Node { int Value; Node Left; Node Right; Node(int value = default(int), Node left = default(Node), Node right = default(Node)) { Value = value; Left = left; Right = right; } IEnumerable<int> Preorder() { yield return Value; if (Left != null) foreach (var value in Left.Preorder()) yield return value; if (Right != null) foreach (var value in Right.Preorder()) yield return value; } IEnumerable<int> Inorder() { if (Left != null) foreach (var value in Left.Inorder()) yield return value; yield return Value; if (Right != null) foreach (var value in Right.Inorder()) yield return value; } IEnumerable<int> Postorder() { if (Left != null) foreach (var value in Left.Postorder()) yield return value; if (Right != null) foreach (var value in Right.Postorder()) yield return value; yield return Value; } IEnumerable<int> LevelOrder() { var queue = new Queue<Node>(); queue.Enqueue(this); while (queue.Any()) { var node = queue.Dequeue(); yield return node.Value; if (node.Left != null) queue.Enqueue(node.Left); if (node.Right != null) queue.Enqueue(node.Right); } } static void Main() { var tree = new Node(1, new Node(2, new Node(4, new Node(7)), new Node(5)), new Node(3, new Node(6, new Node(8), new Node(9)))); foreach (var traversal in new Func<IEnumerable<int>>[] { tree.Preorder, tree.Inorder, tree.Postorder, tree.LevelOrder }) Console.WriteLine("{0}:\t{1}", traversal.Method.Name, string.Join(" ", traversal())); } }
Convert this AWK block to C++, preserving its control flow and logic.
function preorder(tree, node, res, child) { if (node == "") return res[res["count"]++] = node split(tree[node], child, ",") preorder(tree,child[1],res) preorder(tree,child[2],res) } function inorder(tree, node, res, child) { if (node == "") return split(tree[node], child, ",") inorder(tree,child[1],res) res[res["count"]++] = node inorder(tree,child[2],res) } function postorder(tree, node, res, child) { if (node == "") return split(tree[node], child, ",") postorder(tree,child[1], res) postorder(tree,child[2], res) res[res["count"]++] = node } function levelorder(tree, node, res, nextnode, queue, child) { if (node == "") return queue["tail"] = 0 queue[queue["head"]++] = node while (queue["head"] - queue["tail"] >= 1) { nextnode = queue[queue["tail"]] delete queue[queue["tail"]++] res[res["count"]++] = nextnode split(tree[nextnode], child, ",") if (child[1] != "") queue[queue["head"]++] = child[1] if (child[2] != "") queue[queue["head"]++] = child[2] } delete queue } BEGIN { tree["1"] = "2,3" tree["2"] = "4,5" tree["3"] = "6," tree["4"] = "7," tree["5"] = "," tree["6"] = "8,9" tree["7"] = "," tree["8"] = "," tree["9"] = "," preorder(tree,"1",result) printf "preorder:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result inorder(tree,"1",result) printf "inorder:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result postorder(tree,"1",result) printf "postorder:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result levelorder(tree,"1",result) printf "level-order:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result }
#include <boost/scoped_ptr.hpp> #include <iostream> #include <queue> template<typename T> class TreeNode { public: TreeNode(const T& n, TreeNode* left = NULL, TreeNode* right = NULL) : mValue(n), mLeft(left), mRight(right) {} T getValue() const { return mValue; } TreeNode* left() const { return mLeft.get(); } TreeNode* right() const { return mRight.get(); } void preorderTraverse() const { std::cout << " " << getValue(); if(mLeft) { mLeft->preorderTraverse(); } if(mRight) { mRight->preorderTraverse(); } } void inorderTraverse() const { if(mLeft) { mLeft->inorderTraverse(); } std::cout << " " << getValue(); if(mRight) { mRight->inorderTraverse(); } } void postorderTraverse() const { if(mLeft) { mLeft->postorderTraverse(); } if(mRight) { mRight->postorderTraverse(); } std::cout << " " << getValue(); } void levelorderTraverse() const { std::queue<const TreeNode*> q; q.push(this); while(!q.empty()) { const TreeNode* n = q.front(); q.pop(); std::cout << " " << n->getValue(); if(n->left()) { q.push(n->left()); } if(n->right()) { q.push(n->right()); } } } protected: T mValue; boost::scoped_ptr<TreeNode> mLeft; boost::scoped_ptr<TreeNode> mRight; private: TreeNode(); }; int main() { TreeNode<int> root(1, new TreeNode<int>(2, new TreeNode<int>(4, new TreeNode<int>(7)), new TreeNode<int>(5)), new TreeNode<int>(3, new TreeNode<int>(6, new TreeNode<int>(8), new TreeNode<int>(9)))); std::cout << "preorder: "; root.preorderTraverse(); std::cout << std::endl; std::cout << "inorder: "; root.inorderTraverse(); std::cout << std::endl; std::cout << "postorder: "; root.postorderTraverse(); std::cout << std::endl; std::cout << "level-order:"; root.levelorderTraverse(); std::cout << std::endl; return 0; }
Convert this AWK block to Java, preserving its control flow and logic.
function preorder(tree, node, res, child) { if (node == "") return res[res["count"]++] = node split(tree[node], child, ",") preorder(tree,child[1],res) preorder(tree,child[2],res) } function inorder(tree, node, res, child) { if (node == "") return split(tree[node], child, ",") inorder(tree,child[1],res) res[res["count"]++] = node inorder(tree,child[2],res) } function postorder(tree, node, res, child) { if (node == "") return split(tree[node], child, ",") postorder(tree,child[1], res) postorder(tree,child[2], res) res[res["count"]++] = node } function levelorder(tree, node, res, nextnode, queue, child) { if (node == "") return queue["tail"] = 0 queue[queue["head"]++] = node while (queue["head"] - queue["tail"] >= 1) { nextnode = queue[queue["tail"]] delete queue[queue["tail"]++] res[res["count"]++] = nextnode split(tree[nextnode], child, ",") if (child[1] != "") queue[queue["head"]++] = child[1] if (child[2] != "") queue[queue["head"]++] = child[2] } delete queue } BEGIN { tree["1"] = "2,3" tree["2"] = "4,5" tree["3"] = "6," tree["4"] = "7," tree["5"] = "," tree["6"] = "8,9" tree["7"] = "," tree["8"] = "," tree["9"] = "," preorder(tree,"1",result) printf "preorder:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result inorder(tree,"1",result) printf "inorder:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result postorder(tree,"1",result) printf "postorder:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result levelorder(tree,"1",result) printf "level-order:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result }
import java.util.*; public class TreeTraversal { static class Node<T> { T value; Node<T> left; Node<T> right; Node(T value) { this.value = value; } void visit() { System.out.print(this.value + " "); } } static enum ORDER { PREORDER, INORDER, POSTORDER, LEVEL } static <T> void traverse(Node<T> node, ORDER order) { if (node == null) { return; } switch (order) { case PREORDER: node.visit(); traverse(node.left, order); traverse(node.right, order); break; case INORDER: traverse(node.left, order); node.visit(); traverse(node.right, order); break; case POSTORDER: traverse(node.left, order); traverse(node.right, order); node.visit(); break; case LEVEL: Queue<Node<T>> queue = new LinkedList<>(); queue.add(node); while(!queue.isEmpty()){ Node<T> next = queue.remove(); next.visit(); if(next.left!=null) queue.add(next.left); if(next.right!=null) queue.add(next.right); } } } public static void main(String[] args) { Node<Integer> one = new Node<Integer>(1); Node<Integer> two = new Node<Integer>(2); Node<Integer> three = new Node<Integer>(3); Node<Integer> four = new Node<Integer>(4); Node<Integer> five = new Node<Integer>(5); Node<Integer> six = new Node<Integer>(6); Node<Integer> seven = new Node<Integer>(7); Node<Integer> eight = new Node<Integer>(8); Node<Integer> nine = new Node<Integer>(9); one.left = two; one.right = three; two.left = four; two.right = five; three.left = six; four.left = seven; six.left = eight; six.right = nine; traverse(one, ORDER.PREORDER); System.out.println(); traverse(one, ORDER.INORDER); System.out.println(); traverse(one, ORDER.POSTORDER); System.out.println(); traverse(one, ORDER.LEVEL); } }
Write a version of this AWK function in Python with identical behavior.
function preorder(tree, node, res, child) { if (node == "") return res[res["count"]++] = node split(tree[node], child, ",") preorder(tree,child[1],res) preorder(tree,child[2],res) } function inorder(tree, node, res, child) { if (node == "") return split(tree[node], child, ",") inorder(tree,child[1],res) res[res["count"]++] = node inorder(tree,child[2],res) } function postorder(tree, node, res, child) { if (node == "") return split(tree[node], child, ",") postorder(tree,child[1], res) postorder(tree,child[2], res) res[res["count"]++] = node } function levelorder(tree, node, res, nextnode, queue, child) { if (node == "") return queue["tail"] = 0 queue[queue["head"]++] = node while (queue["head"] - queue["tail"] >= 1) { nextnode = queue[queue["tail"]] delete queue[queue["tail"]++] res[res["count"]++] = nextnode split(tree[nextnode], child, ",") if (child[1] != "") queue[queue["head"]++] = child[1] if (child[2] != "") queue[queue["head"]++] = child[2] } delete queue } BEGIN { tree["1"] = "2,3" tree["2"] = "4,5" tree["3"] = "6," tree["4"] = "7," tree["5"] = "," tree["6"] = "8,9" tree["7"] = "," tree["8"] = "," tree["9"] = "," preorder(tree,"1",result) printf "preorder:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result inorder(tree,"1",result) printf "inorder:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result postorder(tree,"1",result) printf "postorder:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result levelorder(tree,"1",result) printf "level-order:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result }
from collections import namedtuple Node = namedtuple('Node', 'data, left, right') tree = Node(1, Node(2, Node(4, Node(7, None, None), None), Node(5, None, None)), Node(3, Node(6, Node(8, None, None), Node(9, None, None)), None)) def printwithspace(i): print(i, end=' ') def dfs(order, node, visitor): if node is not None: for action in order: if action == 'N': visitor(node.data) elif action == 'L': dfs(order, node.left, visitor) elif action == 'R': dfs(order, node.right, visitor) def preorder(node, visitor = printwithspace): dfs('NLR', node, visitor) def inorder(node, visitor = printwithspace): dfs('LNR', node, visitor) def postorder(node, visitor = printwithspace): dfs('LRN', node, visitor) def ls(node, more, visitor, order='TB'): "Level-based Top-to-Bottom or Bottom-to-Top tree search" if node: if more is None: more = [] more += [node.left, node.right] for action in order: if action == 'B' and more: ls(more[0], more[1:], visitor, order) elif action == 'T' and node: visitor(node.data) def levelorder(node, more=None, visitor = printwithspace): ls(node, more, visitor, 'TB') def reverse_preorder(node, visitor = printwithspace): dfs('RLN', node, visitor) def bottom_up_order(node, more=None, visitor = printwithspace, order='BT'): ls(node, more, visitor, 'BT') if __name__ == '__main__': w = 10 for traversal in [preorder, inorder, postorder, levelorder, reverse_preorder, bottom_up_order]: if traversal == reverse_preorder: w = 20 print('\nThe generalisation of function dfs allows:') if traversal == bottom_up_order: print('The generalisation of function ls allows:') print(f"{traversal.__name__:>{w}}:", end=' ') traversal(tree) print()
Change the programming language of this snippet from AWK to VB without modifying what it does.
function preorder(tree, node, res, child) { if (node == "") return res[res["count"]++] = node split(tree[node], child, ",") preorder(tree,child[1],res) preorder(tree,child[2],res) } function inorder(tree, node, res, child) { if (node == "") return split(tree[node], child, ",") inorder(tree,child[1],res) res[res["count"]++] = node inorder(tree,child[2],res) } function postorder(tree, node, res, child) { if (node == "") return split(tree[node], child, ",") postorder(tree,child[1], res) postorder(tree,child[2], res) res[res["count"]++] = node } function levelorder(tree, node, res, nextnode, queue, child) { if (node == "") return queue["tail"] = 0 queue[queue["head"]++] = node while (queue["head"] - queue["tail"] >= 1) { nextnode = queue[queue["tail"]] delete queue[queue["tail"]++] res[res["count"]++] = nextnode split(tree[nextnode], child, ",") if (child[1] != "") queue[queue["head"]++] = child[1] if (child[2] != "") queue[queue["head"]++] = child[2] } delete queue } BEGIN { tree["1"] = "2,3" tree["2"] = "4,5" tree["3"] = "6," tree["4"] = "7," tree["5"] = "," tree["6"] = "8,9" tree["7"] = "," tree["8"] = "," tree["9"] = "," preorder(tree,"1",result) printf "preorder:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result inorder(tree,"1",result) printf "inorder:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result postorder(tree,"1",result) printf "postorder:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result levelorder(tree,"1",result) printf "level-order:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result }
Public Value As Integer Public LeftChild As TreeItem Public RightChild As TreeItem
Preserve the algorithm and functionality while converting the code from AWK to Go.
function preorder(tree, node, res, child) { if (node == "") return res[res["count"]++] = node split(tree[node], child, ",") preorder(tree,child[1],res) preorder(tree,child[2],res) } function inorder(tree, node, res, child) { if (node == "") return split(tree[node], child, ",") inorder(tree,child[1],res) res[res["count"]++] = node inorder(tree,child[2],res) } function postorder(tree, node, res, child) { if (node == "") return split(tree[node], child, ",") postorder(tree,child[1], res) postorder(tree,child[2], res) res[res["count"]++] = node } function levelorder(tree, node, res, nextnode, queue, child) { if (node == "") return queue["tail"] = 0 queue[queue["head"]++] = node while (queue["head"] - queue["tail"] >= 1) { nextnode = queue[queue["tail"]] delete queue[queue["tail"]++] res[res["count"]++] = nextnode split(tree[nextnode], child, ",") if (child[1] != "") queue[queue["head"]++] = child[1] if (child[2] != "") queue[queue["head"]++] = child[2] } delete queue } BEGIN { tree["1"] = "2,3" tree["2"] = "4,5" tree["3"] = "6," tree["4"] = "7," tree["5"] = "," tree["6"] = "8,9" tree["7"] = "," tree["8"] = "," tree["9"] = "," preorder(tree,"1",result) printf "preorder:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result inorder(tree,"1",result) printf "inorder:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result postorder(tree,"1",result) printf "postorder:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result levelorder(tree,"1",result) printf "level-order:\t" for (n = 0; n < result["count"]; n += 1) printf result[n]" " printf "\n" delete result }
package main import "fmt" type node struct { value int left, right *node } func (n *node) iterPreorder(visit func(int)) { if n == nil { return } visit(n.value) n.left.iterPreorder(visit) n.right.iterPreorder(visit) } func (n *node) iterInorder(visit func(int)) { if n == nil { return } n.left.iterInorder(visit) visit(n.value) n.right.iterInorder(visit) } func (n *node) iterPostorder(visit func(int)) { if n == nil { return } n.left.iterPostorder(visit) n.right.iterPostorder(visit) visit(n.value) } func (n *node) iterLevelorder(visit func(int)) { if n == nil { return } for queue := []*node{n}; ; { n = queue[0] visit(n.value) copy(queue, queue[1:]) queue = queue[:len(queue)-1] if n.left != nil { queue = append(queue, n.left) } if n.right != nil { queue = append(queue, n.right) } if len(queue) == 0 { return } } } func main() { tree := &node{1, &node{2, &node{4, &node{7, nil, nil}, nil}, &node{5, nil, nil}}, &node{3, &node{6, &node{8, nil, nil}, &node{9, nil, nil}}, nil}} fmt.Print("preorder: ") tree.iterPreorder(visitor) fmt.Println() fmt.Print("inorder: ") tree.iterInorder(visitor) fmt.Println() fmt.Print("postorder: ") tree.iterPostorder(visitor) fmt.Println() fmt.Print("level-order: ") tree.iterLevelorder(visitor) fmt.Println() } func visitor(value int) { fmt.Print(value, " ") }
Change the following Clojure code into C without altering its purpose.
(defn walk [node f order] (when node (doseq [o order] (if (= o :visit) (f (:val node)) (walk (node o) f order))))) (defn preorder [node f] (walk node f [:visit :left :right])) (defn inorder [node f] (walk node f [:left :visit :right])) (defn postorder [node f] (walk node f [:left :right :visit])) (defn queue [& xs] (when (seq xs) (apply conj clojure.lang.PersistentQueue/EMPTY xs))) (defn level-order [root f] (loop [q (queue root)] (when-not (empty? q) (if-let [node (first q)] (do (f (:val node)) (recur (conj (pop q) (:left node) (:right node)))) (recur (pop q)))))) (defn vec-to-tree [t] (if (vector? t) (let [[val left right] t] {:val val :left (vec-to-tree left) :right (vec-to-tree right)}) t)) (let [tree (vec-to-tree [1 [2 [4 [7]] [5]] [3 [6 [8] [9]]]]) fs '[preorder inorder postorder level-order] pr-node #(print (format "%2d" %))] (doseq [f fs] (print (format "%-12s" (str f ":"))) ((resolve f) tree pr-node) (println)))
#include <stdlib.h> #include <stdio.h> typedef struct node_s { int value; struct node_s* left; struct node_s* right; } *node; node tree(int v, node l, node r) { node n = malloc(sizeof(struct node_s)); n->value = v; n->left = l; n->right = r; return n; } void destroy_tree(node n) { if (n->left) destroy_tree(n->left); if (n->right) destroy_tree(n->right); free(n); } void preorder(node n, void (*f)(int)) { f(n->value); if (n->left) preorder(n->left, f); if (n->right) preorder(n->right, f); } void inorder(node n, void (*f)(int)) { if (n->left) inorder(n->left, f); f(n->value); if (n->right) inorder(n->right, f); } void postorder(node n, void (*f)(int)) { if (n->left) postorder(n->left, f); if (n->right) postorder(n->right, f); f(n->value); } typedef struct qnode_s { struct qnode_s* next; node value; } *qnode; typedef struct { qnode begin, end; } queue; void enqueue(queue* q, node n) { qnode node = malloc(sizeof(struct qnode_s)); node->value = n; node->next = 0; if (q->end) q->end->next = node; else q->begin = node; q->end = node; } node dequeue(queue* q) { node tmp = q->begin->value; qnode second = q->begin->next; free(q->begin); q->begin = second; if (!q->begin) q->end = 0; return tmp; } int queue_empty(queue* q) { return !q->begin; } void levelorder(node n, void(*f)(int)) { queue nodequeue = {}; enqueue(&nodequeue, n); while (!queue_empty(&nodequeue)) { node next = dequeue(&nodequeue); f(next->value); if (next->left) enqueue(&nodequeue, next->left); if (next->right) enqueue(&nodequeue, next->right); } } void print(int n) { printf("%d ", n); } int main() { node n = tree(1, tree(2, tree(4, tree(7, 0, 0), 0), tree(5, 0, 0)), tree(3, tree(6, tree(8, 0, 0), tree(9, 0, 0)), 0)); printf("preorder: "); preorder(n, print); printf("\n"); printf("inorder: "); inorder(n, print); printf("\n"); printf("postorder: "); postorder(n, print); printf("\n"); printf("level-order: "); levelorder(n, print); printf("\n"); destroy_tree(n); return 0; }
Rewrite this program in C# while keeping its functionality equivalent to the Clojure version.
(defn walk [node f order] (when node (doseq [o order] (if (= o :visit) (f (:val node)) (walk (node o) f order))))) (defn preorder [node f] (walk node f [:visit :left :right])) (defn inorder [node f] (walk node f [:left :visit :right])) (defn postorder [node f] (walk node f [:left :right :visit])) (defn queue [& xs] (when (seq xs) (apply conj clojure.lang.PersistentQueue/EMPTY xs))) (defn level-order [root f] (loop [q (queue root)] (when-not (empty? q) (if-let [node (first q)] (do (f (:val node)) (recur (conj (pop q) (:left node) (:right node)))) (recur (pop q)))))) (defn vec-to-tree [t] (if (vector? t) (let [[val left right] t] {:val val :left (vec-to-tree left) :right (vec-to-tree right)}) t)) (let [tree (vec-to-tree [1 [2 [4 [7]] [5]] [3 [6 [8] [9]]]]) fs '[preorder inorder postorder level-order] pr-node #(print (format "%2d" %))] (doseq [f fs] (print (format "%-12s" (str f ":"))) ((resolve f) tree pr-node) (println)))
using System; using System.Collections.Generic; using System.Linq; class Node { int Value; Node Left; Node Right; Node(int value = default(int), Node left = default(Node), Node right = default(Node)) { Value = value; Left = left; Right = right; } IEnumerable<int> Preorder() { yield return Value; if (Left != null) foreach (var value in Left.Preorder()) yield return value; if (Right != null) foreach (var value in Right.Preorder()) yield return value; } IEnumerable<int> Inorder() { if (Left != null) foreach (var value in Left.Inorder()) yield return value; yield return Value; if (Right != null) foreach (var value in Right.Inorder()) yield return value; } IEnumerable<int> Postorder() { if (Left != null) foreach (var value in Left.Postorder()) yield return value; if (Right != null) foreach (var value in Right.Postorder()) yield return value; yield return Value; } IEnumerable<int> LevelOrder() { var queue = new Queue<Node>(); queue.Enqueue(this); while (queue.Any()) { var node = queue.Dequeue(); yield return node.Value; if (node.Left != null) queue.Enqueue(node.Left); if (node.Right != null) queue.Enqueue(node.Right); } } static void Main() { var tree = new Node(1, new Node(2, new Node(4, new Node(7)), new Node(5)), new Node(3, new Node(6, new Node(8), new Node(9)))); foreach (var traversal in new Func<IEnumerable<int>>[] { tree.Preorder, tree.Inorder, tree.Postorder, tree.LevelOrder }) Console.WriteLine("{0}:\t{1}", traversal.Method.Name, string.Join(" ", traversal())); } }
Write a version of this Clojure function in C++ with identical behavior.
(defn walk [node f order] (when node (doseq [o order] (if (= o :visit) (f (:val node)) (walk (node o) f order))))) (defn preorder [node f] (walk node f [:visit :left :right])) (defn inorder [node f] (walk node f [:left :visit :right])) (defn postorder [node f] (walk node f [:left :right :visit])) (defn queue [& xs] (when (seq xs) (apply conj clojure.lang.PersistentQueue/EMPTY xs))) (defn level-order [root f] (loop [q (queue root)] (when-not (empty? q) (if-let [node (first q)] (do (f (:val node)) (recur (conj (pop q) (:left node) (:right node)))) (recur (pop q)))))) (defn vec-to-tree [t] (if (vector? t) (let [[val left right] t] {:val val :left (vec-to-tree left) :right (vec-to-tree right)}) t)) (let [tree (vec-to-tree [1 [2 [4 [7]] [5]] [3 [6 [8] [9]]]]) fs '[preorder inorder postorder level-order] pr-node #(print (format "%2d" %))] (doseq [f fs] (print (format "%-12s" (str f ":"))) ((resolve f) tree pr-node) (println)))
#include <boost/scoped_ptr.hpp> #include <iostream> #include <queue> template<typename T> class TreeNode { public: TreeNode(const T& n, TreeNode* left = NULL, TreeNode* right = NULL) : mValue(n), mLeft(left), mRight(right) {} T getValue() const { return mValue; } TreeNode* left() const { return mLeft.get(); } TreeNode* right() const { return mRight.get(); } void preorderTraverse() const { std::cout << " " << getValue(); if(mLeft) { mLeft->preorderTraverse(); } if(mRight) { mRight->preorderTraverse(); } } void inorderTraverse() const { if(mLeft) { mLeft->inorderTraverse(); } std::cout << " " << getValue(); if(mRight) { mRight->inorderTraverse(); } } void postorderTraverse() const { if(mLeft) { mLeft->postorderTraverse(); } if(mRight) { mRight->postorderTraverse(); } std::cout << " " << getValue(); } void levelorderTraverse() const { std::queue<const TreeNode*> q; q.push(this); while(!q.empty()) { const TreeNode* n = q.front(); q.pop(); std::cout << " " << n->getValue(); if(n->left()) { q.push(n->left()); } if(n->right()) { q.push(n->right()); } } } protected: T mValue; boost::scoped_ptr<TreeNode> mLeft; boost::scoped_ptr<TreeNode> mRight; private: TreeNode(); }; int main() { TreeNode<int> root(1, new TreeNode<int>(2, new TreeNode<int>(4, new TreeNode<int>(7)), new TreeNode<int>(5)), new TreeNode<int>(3, new TreeNode<int>(6, new TreeNode<int>(8), new TreeNode<int>(9)))); std::cout << "preorder: "; root.preorderTraverse(); std::cout << std::endl; std::cout << "inorder: "; root.inorderTraverse(); std::cout << std::endl; std::cout << "postorder: "; root.postorderTraverse(); std::cout << std::endl; std::cout << "level-order:"; root.levelorderTraverse(); std::cout << std::endl; return 0; }
Rewrite the snippet below in Java so it works the same as the original Clojure code.
(defn walk [node f order] (when node (doseq [o order] (if (= o :visit) (f (:val node)) (walk (node o) f order))))) (defn preorder [node f] (walk node f [:visit :left :right])) (defn inorder [node f] (walk node f [:left :visit :right])) (defn postorder [node f] (walk node f [:left :right :visit])) (defn queue [& xs] (when (seq xs) (apply conj clojure.lang.PersistentQueue/EMPTY xs))) (defn level-order [root f] (loop [q (queue root)] (when-not (empty? q) (if-let [node (first q)] (do (f (:val node)) (recur (conj (pop q) (:left node) (:right node)))) (recur (pop q)))))) (defn vec-to-tree [t] (if (vector? t) (let [[val left right] t] {:val val :left (vec-to-tree left) :right (vec-to-tree right)}) t)) (let [tree (vec-to-tree [1 [2 [4 [7]] [5]] [3 [6 [8] [9]]]]) fs '[preorder inorder postorder level-order] pr-node #(print (format "%2d" %))] (doseq [f fs] (print (format "%-12s" (str f ":"))) ((resolve f) tree pr-node) (println)))
import java.util.*; public class TreeTraversal { static class Node<T> { T value; Node<T> left; Node<T> right; Node(T value) { this.value = value; } void visit() { System.out.print(this.value + " "); } } static enum ORDER { PREORDER, INORDER, POSTORDER, LEVEL } static <T> void traverse(Node<T> node, ORDER order) { if (node == null) { return; } switch (order) { case PREORDER: node.visit(); traverse(node.left, order); traverse(node.right, order); break; case INORDER: traverse(node.left, order); node.visit(); traverse(node.right, order); break; case POSTORDER: traverse(node.left, order); traverse(node.right, order); node.visit(); break; case LEVEL: Queue<Node<T>> queue = new LinkedList<>(); queue.add(node); while(!queue.isEmpty()){ Node<T> next = queue.remove(); next.visit(); if(next.left!=null) queue.add(next.left); if(next.right!=null) queue.add(next.right); } } } public static void main(String[] args) { Node<Integer> one = new Node<Integer>(1); Node<Integer> two = new Node<Integer>(2); Node<Integer> three = new Node<Integer>(3); Node<Integer> four = new Node<Integer>(4); Node<Integer> five = new Node<Integer>(5); Node<Integer> six = new Node<Integer>(6); Node<Integer> seven = new Node<Integer>(7); Node<Integer> eight = new Node<Integer>(8); Node<Integer> nine = new Node<Integer>(9); one.left = two; one.right = three; two.left = four; two.right = five; three.left = six; four.left = seven; six.left = eight; six.right = nine; traverse(one, ORDER.PREORDER); System.out.println(); traverse(one, ORDER.INORDER); System.out.println(); traverse(one, ORDER.POSTORDER); System.out.println(); traverse(one, ORDER.LEVEL); } }
Ensure the translated Python code behaves exactly like the original Clojure snippet.
(defn walk [node f order] (when node (doseq [o order] (if (= o :visit) (f (:val node)) (walk (node o) f order))))) (defn preorder [node f] (walk node f [:visit :left :right])) (defn inorder [node f] (walk node f [:left :visit :right])) (defn postorder [node f] (walk node f [:left :right :visit])) (defn queue [& xs] (when (seq xs) (apply conj clojure.lang.PersistentQueue/EMPTY xs))) (defn level-order [root f] (loop [q (queue root)] (when-not (empty? q) (if-let [node (first q)] (do (f (:val node)) (recur (conj (pop q) (:left node) (:right node)))) (recur (pop q)))))) (defn vec-to-tree [t] (if (vector? t) (let [[val left right] t] {:val val :left (vec-to-tree left) :right (vec-to-tree right)}) t)) (let [tree (vec-to-tree [1 [2 [4 [7]] [5]] [3 [6 [8] [9]]]]) fs '[preorder inorder postorder level-order] pr-node #(print (format "%2d" %))] (doseq [f fs] (print (format "%-12s" (str f ":"))) ((resolve f) tree pr-node) (println)))
from collections import namedtuple Node = namedtuple('Node', 'data, left, right') tree = Node(1, Node(2, Node(4, Node(7, None, None), None), Node(5, None, None)), Node(3, Node(6, Node(8, None, None), Node(9, None, None)), None)) def printwithspace(i): print(i, end=' ') def dfs(order, node, visitor): if node is not None: for action in order: if action == 'N': visitor(node.data) elif action == 'L': dfs(order, node.left, visitor) elif action == 'R': dfs(order, node.right, visitor) def preorder(node, visitor = printwithspace): dfs('NLR', node, visitor) def inorder(node, visitor = printwithspace): dfs('LNR', node, visitor) def postorder(node, visitor = printwithspace): dfs('LRN', node, visitor) def ls(node, more, visitor, order='TB'): "Level-based Top-to-Bottom or Bottom-to-Top tree search" if node: if more is None: more = [] more += [node.left, node.right] for action in order: if action == 'B' and more: ls(more[0], more[1:], visitor, order) elif action == 'T' and node: visitor(node.data) def levelorder(node, more=None, visitor = printwithspace): ls(node, more, visitor, 'TB') def reverse_preorder(node, visitor = printwithspace): dfs('RLN', node, visitor) def bottom_up_order(node, more=None, visitor = printwithspace, order='BT'): ls(node, more, visitor, 'BT') if __name__ == '__main__': w = 10 for traversal in [preorder, inorder, postorder, levelorder, reverse_preorder, bottom_up_order]: if traversal == reverse_preorder: w = 20 print('\nThe generalisation of function dfs allows:') if traversal == bottom_up_order: print('The generalisation of function ls allows:') print(f"{traversal.__name__:>{w}}:", end=' ') traversal(tree) print()
Convert the following code from Clojure to VB, ensuring the logic remains intact.
(defn walk [node f order] (when node (doseq [o order] (if (= o :visit) (f (:val node)) (walk (node o) f order))))) (defn preorder [node f] (walk node f [:visit :left :right])) (defn inorder [node f] (walk node f [:left :visit :right])) (defn postorder [node f] (walk node f [:left :right :visit])) (defn queue [& xs] (when (seq xs) (apply conj clojure.lang.PersistentQueue/EMPTY xs))) (defn level-order [root f] (loop [q (queue root)] (when-not (empty? q) (if-let [node (first q)] (do (f (:val node)) (recur (conj (pop q) (:left node) (:right node)))) (recur (pop q)))))) (defn vec-to-tree [t] (if (vector? t) (let [[val left right] t] {:val val :left (vec-to-tree left) :right (vec-to-tree right)}) t)) (let [tree (vec-to-tree [1 [2 [4 [7]] [5]] [3 [6 [8] [9]]]]) fs '[preorder inorder postorder level-order] pr-node #(print (format "%2d" %))] (doseq [f fs] (print (format "%-12s" (str f ":"))) ((resolve f) tree pr-node) (println)))
Public Value As Integer Public LeftChild As TreeItem Public RightChild As TreeItem
Generate an equivalent Go version of this Clojure code.
(defn walk [node f order] (when node (doseq [o order] (if (= o :visit) (f (:val node)) (walk (node o) f order))))) (defn preorder [node f] (walk node f [:visit :left :right])) (defn inorder [node f] (walk node f [:left :visit :right])) (defn postorder [node f] (walk node f [:left :right :visit])) (defn queue [& xs] (when (seq xs) (apply conj clojure.lang.PersistentQueue/EMPTY xs))) (defn level-order [root f] (loop [q (queue root)] (when-not (empty? q) (if-let [node (first q)] (do (f (:val node)) (recur (conj (pop q) (:left node) (:right node)))) (recur (pop q)))))) (defn vec-to-tree [t] (if (vector? t) (let [[val left right] t] {:val val :left (vec-to-tree left) :right (vec-to-tree right)}) t)) (let [tree (vec-to-tree [1 [2 [4 [7]] [5]] [3 [6 [8] [9]]]]) fs '[preorder inorder postorder level-order] pr-node #(print (format "%2d" %))] (doseq [f fs] (print (format "%-12s" (str f ":"))) ((resolve f) tree pr-node) (println)))
package main import "fmt" type node struct { value int left, right *node } func (n *node) iterPreorder(visit func(int)) { if n == nil { return } visit(n.value) n.left.iterPreorder(visit) n.right.iterPreorder(visit) } func (n *node) iterInorder(visit func(int)) { if n == nil { return } n.left.iterInorder(visit) visit(n.value) n.right.iterInorder(visit) } func (n *node) iterPostorder(visit func(int)) { if n == nil { return } n.left.iterPostorder(visit) n.right.iterPostorder(visit) visit(n.value) } func (n *node) iterLevelorder(visit func(int)) { if n == nil { return } for queue := []*node{n}; ; { n = queue[0] visit(n.value) copy(queue, queue[1:]) queue = queue[:len(queue)-1] if n.left != nil { queue = append(queue, n.left) } if n.right != nil { queue = append(queue, n.right) } if len(queue) == 0 { return } } } func main() { tree := &node{1, &node{2, &node{4, &node{7, nil, nil}, nil}, &node{5, nil, nil}}, &node{3, &node{6, &node{8, nil, nil}, &node{9, nil, nil}}, nil}} fmt.Print("preorder: ") tree.iterPreorder(visitor) fmt.Println() fmt.Print("inorder: ") tree.iterInorder(visitor) fmt.Println() fmt.Print("postorder: ") tree.iterPostorder(visitor) fmt.Println() fmt.Print("level-order: ") tree.iterLevelorder(visitor) fmt.Println() } func visitor(value int) { fmt.Print(value, " ") }