Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Rewrite this program in C++ while keeping its functionality equivalent to the REXX version.
Numeric Digits 20 names='w x y z' M=' 2 -1 5 1', ' 3 2 2 -6', ' 1 3 3 -1', ' 5 -2 -3 3' v=' -3', '-32', '-47', ' 49' Call mk_mat(m) Do j=1 To dim ol='' Do i=1 To dim ol=ol format(a.i.j,6) End ol=ol format(word(v,j),6) Say ol End Say copies('-',35) d=det(m) Do k=1 To dim Do j=1 To dim Do i=1 To dim If i=k Then b.i.j=word(v,j) Else b.i.j=a.i.j End End Call show_b d.k=det(mk_str()) Say word(names,k) '=' d.k/d End Exit mk_mat: Procedure Expose a. dim Parse Arg list dim=sqrt(words(list)) k=0 Do j=1 To dim Do i=1 To dim k=k+1 a.i.j=word(list,k) End End Return mk_str: Procedure Expose b. dim str='' Do j=1 To dim Do i=1 To dim str=str b.i.j End End Return str show_b: Procedure Expose b. dim do j=1 To dim ol='' Do i=1 To dim ol=ol format(b.i.j,6) end Call dbg ol end Return det: Procedure Parse Arg list n=words(list) call dbg 'det:' list do dim=1 To 10 If dim**2=n Then Leave End call dbg 'dim='dim If dim=2 Then Do det=word(list,1)*word(list,4)-word(list,2)*word(list,3) call dbg 'det=>'det Return det End k=0 Do j=1 To dim Do i=1 To dim k=k+1 a.i.j=word(list,k) End End Do j=1 To dim ol=j Do i=1 To dim ol=ol format(a.i.j,6) End call dbg ol End det=0 Do i=1 To dim ol='' Do j=2 To dim Do ii=1 To dim If ii<>i Then ol=ol a.ii.j End End call dbg 'i='i 'ol='ol If i//2 Then det=det+a.i.1*det(ol) Else det=det-a.i.1*det(ol) End Call dbg 'det=>>>'det Return det sqrt: Procedure * EXEC to calculate the square root of a = 2 with high precision **********************************************************************/ Parse Arg x,prec If prec<9 Then prec=9 prec1=2*prec eps=10**(-prec1) k = 1 Numeric Digits 3 r0= x r = 1 Do i=1 By 1 Until r=r0 | (abs(r*r-x)<eps) r0 = r r = (r + x/r) / 2 k = min(prec1,2*k) Numeric Digits (k + 5) End Numeric Digits prec r=r+0 Return r dbg: Return
#include <algorithm> #include <iostream> #include <vector> class SubMatrix { const std::vector<std::vector<double>> *source; std::vector<double> replaceColumn; const SubMatrix *prev; size_t sz; int colIndex = -1; public: SubMatrix(const std::vector<std::vector<double>> &src, const std::vector<double> &rc) : source(&src), replaceColumn(rc), prev(nullptr), colIndex(-1) { sz = replaceColumn.size(); } SubMatrix(const SubMatrix &p) : source(nullptr), prev(&p), colIndex(-1) { sz = p.size() - 1; } SubMatrix(const SubMatrix &p, int deletedColumnIndex) : source(nullptr), prev(&p), colIndex(deletedColumnIndex) { sz = p.size() - 1; } int columnIndex() const { return colIndex; } void columnIndex(int index) { colIndex = index; } size_t size() const { return sz; } double index(int row, int col) const { if (source != nullptr) { if (col == colIndex) { return replaceColumn[row]; } else { return (*source)[row][col]; } } else { if (col < colIndex) { return prev->index(row + 1, col); } else { return prev->index(row + 1, col + 1); } } } double det() const { if (sz == 1) { return index(0, 0); } if (sz == 2) { return index(0, 0) * index(1, 1) - index(0, 1) * index(1, 0); } SubMatrix m(*this); double det = 0.0; int sign = 1; for (size_t c = 0; c < sz; ++c) { m.columnIndex(c); double d = m.det(); det += index(0, c) * d * sign; sign = -sign; } return det; } }; std::vector<double> solve(SubMatrix &matrix) { double det = matrix.det(); if (det == 0.0) { throw std::runtime_error("The determinant is zero."); } std::vector<double> answer(matrix.size()); for (int i = 0; i < matrix.size(); ++i) { matrix.columnIndex(i); answer[i] = matrix.det() / det; } return answer; } std::vector<double> solveCramer(const std::vector<std::vector<double>> &equations) { int size = equations.size(); if (std::any_of( equations.cbegin(), equations.cend(), [size](const std::vector<double> &a) { return a.size() != size + 1; } )) { throw std::runtime_error("Each equation must have the expected size."); } std::vector<std::vector<double>> matrix(size); std::vector<double> column(size); for (int r = 0; r < size; ++r) { column[r] = equations[r][size]; matrix[r].resize(size); for (int c = 0; c < size; ++c) { matrix[r][c] = equations[r][c]; } } SubMatrix sm(matrix, column); return solve(sm); } template<typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it++; } while (it != end) { os << ", " << *it++; } return os << ']'; } int main() { std::vector<std::vector<double>> equations = { { 2, -1, 5, 1, -3}, { 3, 2, 2, -6, -32}, { 1, 3, 3, -1, -47}, { 5, -2, -3, 3, 49}, }; auto solution = solveCramer(equations); std::cout << solution << '\n'; return 0; }
Maintain the same structure and functionality when rewriting this code in Java.
Numeric Digits 20 names='w x y z' M=' 2 -1 5 1', ' 3 2 2 -6', ' 1 3 3 -1', ' 5 -2 -3 3' v=' -3', '-32', '-47', ' 49' Call mk_mat(m) Do j=1 To dim ol='' Do i=1 To dim ol=ol format(a.i.j,6) End ol=ol format(word(v,j),6) Say ol End Say copies('-',35) d=det(m) Do k=1 To dim Do j=1 To dim Do i=1 To dim If i=k Then b.i.j=word(v,j) Else b.i.j=a.i.j End End Call show_b d.k=det(mk_str()) Say word(names,k) '=' d.k/d End Exit mk_mat: Procedure Expose a. dim Parse Arg list dim=sqrt(words(list)) k=0 Do j=1 To dim Do i=1 To dim k=k+1 a.i.j=word(list,k) End End Return mk_str: Procedure Expose b. dim str='' Do j=1 To dim Do i=1 To dim str=str b.i.j End End Return str show_b: Procedure Expose b. dim do j=1 To dim ol='' Do i=1 To dim ol=ol format(b.i.j,6) end Call dbg ol end Return det: Procedure Parse Arg list n=words(list) call dbg 'det:' list do dim=1 To 10 If dim**2=n Then Leave End call dbg 'dim='dim If dim=2 Then Do det=word(list,1)*word(list,4)-word(list,2)*word(list,3) call dbg 'det=>'det Return det End k=0 Do j=1 To dim Do i=1 To dim k=k+1 a.i.j=word(list,k) End End Do j=1 To dim ol=j Do i=1 To dim ol=ol format(a.i.j,6) End call dbg ol End det=0 Do i=1 To dim ol='' Do j=2 To dim Do ii=1 To dim If ii<>i Then ol=ol a.ii.j End End call dbg 'i='i 'ol='ol If i//2 Then det=det+a.i.1*det(ol) Else det=det-a.i.1*det(ol) End Call dbg 'det=>>>'det Return det sqrt: Procedure * EXEC to calculate the square root of a = 2 with high precision **********************************************************************/ Parse Arg x,prec If prec<9 Then prec=9 prec1=2*prec eps=10**(-prec1) k = 1 Numeric Digits 3 r0= x r = 1 Do i=1 By 1 Until r=r0 | (abs(r*r-x)<eps) r0 = r r = (r + x/r) / 2 k = min(prec1,2*k) Numeric Digits (k + 5) End Numeric Digits prec r=r+0 Return r dbg: Return
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CramersRule { public static void main(String[] args) { Matrix mat = new Matrix(Arrays.asList(2d, -1d, 5d, 1d), Arrays.asList(3d, 2d, 2d, -6d), Arrays.asList(1d, 3d, 3d, -1d), Arrays.asList(5d, -2d, -3d, 3d)); List<Double> b = Arrays.asList(-3d, -32d, -47d, 49d); System.out.println("Solution = " + cramersRule(mat, b)); } private static List<Double> cramersRule(Matrix matrix, List<Double> b) { double denominator = matrix.determinant(); List<Double> result = new ArrayList<>(); for ( int i = 0 ; i < b.size() ; i++ ) { result.add(matrix.replaceColumn(b, i).determinant() / denominator); } return result; } private static class Matrix { private List<List<Double>> matrix; @Override public String toString() { return matrix.toString(); } @SafeVarargs public Matrix(List<Double> ... lists) { matrix = new ArrayList<>(); for ( List<Double> list : lists) { matrix.add(list); } } public Matrix(List<List<Double>> mat) { matrix = mat; } public double determinant() { if ( matrix.size() == 1 ) { return get(0, 0); } if ( matrix.size() == 2 ) { return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0); } double sum = 0; double sign = 1; for ( int i = 0 ; i < matrix.size() ; i++ ) { sum += sign * get(0, i) * coFactor(0, i).determinant(); sign *= -1; } return sum; } private Matrix coFactor(int row, int col) { List<List<Double>> mat = new ArrayList<>(); for ( int i = 0 ; i < matrix.size() ; i++ ) { if ( i == row ) { continue; } List<Double> list = new ArrayList<>(); for ( int j = 0 ; j < matrix.size() ; j++ ) { if ( j == col ) { continue; } list.add(get(i, j)); } mat.add(list); } return new Matrix(mat); } private Matrix replaceColumn(List<Double> b, int column) { List<List<Double>> mat = new ArrayList<>(); for ( int row = 0 ; row < matrix.size() ; row++ ) { List<Double> list = new ArrayList<>(); for ( int col = 0 ; col < matrix.size() ; col++ ) { double value = get(row, col); if ( col == column ) { value = b.get(row); } list.add(value); } mat.add(list); } return new Matrix(mat); } private double get(int row, int col) { return matrix.get(row).get(col); } } }
Port the following code from REXX to Python with equivalent syntax and logic.
Numeric Digits 20 names='w x y z' M=' 2 -1 5 1', ' 3 2 2 -6', ' 1 3 3 -1', ' 5 -2 -3 3' v=' -3', '-32', '-47', ' 49' Call mk_mat(m) Do j=1 To dim ol='' Do i=1 To dim ol=ol format(a.i.j,6) End ol=ol format(word(v,j),6) Say ol End Say copies('-',35) d=det(m) Do k=1 To dim Do j=1 To dim Do i=1 To dim If i=k Then b.i.j=word(v,j) Else b.i.j=a.i.j End End Call show_b d.k=det(mk_str()) Say word(names,k) '=' d.k/d End Exit mk_mat: Procedure Expose a. dim Parse Arg list dim=sqrt(words(list)) k=0 Do j=1 To dim Do i=1 To dim k=k+1 a.i.j=word(list,k) End End Return mk_str: Procedure Expose b. dim str='' Do j=1 To dim Do i=1 To dim str=str b.i.j End End Return str show_b: Procedure Expose b. dim do j=1 To dim ol='' Do i=1 To dim ol=ol format(b.i.j,6) end Call dbg ol end Return det: Procedure Parse Arg list n=words(list) call dbg 'det:' list do dim=1 To 10 If dim**2=n Then Leave End call dbg 'dim='dim If dim=2 Then Do det=word(list,1)*word(list,4)-word(list,2)*word(list,3) call dbg 'det=>'det Return det End k=0 Do j=1 To dim Do i=1 To dim k=k+1 a.i.j=word(list,k) End End Do j=1 To dim ol=j Do i=1 To dim ol=ol format(a.i.j,6) End call dbg ol End det=0 Do i=1 To dim ol='' Do j=2 To dim Do ii=1 To dim If ii<>i Then ol=ol a.ii.j End End call dbg 'i='i 'ol='ol If i//2 Then det=det+a.i.1*det(ol) Else det=det-a.i.1*det(ol) End Call dbg 'det=>>>'det Return det sqrt: Procedure * EXEC to calculate the square root of a = 2 with high precision **********************************************************************/ Parse Arg x,prec If prec<9 Then prec=9 prec1=2*prec eps=10**(-prec1) k = 1 Numeric Digits 3 r0= x r = 1 Do i=1 By 1 Until r=r0 | (abs(r*r-x)<eps) r0 = r r = (r + x/r) / 2 k = min(prec1,2*k) Numeric Digits (k + 5) End Numeric Digits prec r=r+0 Return r dbg: Return
def det(m,n): if n==1: return m[0][0] z=0 for r in range(n): k=m[:] del k[r] z+=m[r][0]*(-1)**r*det([p[1:]for p in k],n-1) return z w=len(t) d=det(h,w) if d==0:r=[] else:r=[det([r[0:i]+[s]+r[i+1:]for r,s in zip(h,t)],w)/d for i in range(w)] print(r)
Translate the given REXX code snippet into VB without altering its behavior.
Numeric Digits 20 names='w x y z' M=' 2 -1 5 1', ' 3 2 2 -6', ' 1 3 3 -1', ' 5 -2 -3 3' v=' -3', '-32', '-47', ' 49' Call mk_mat(m) Do j=1 To dim ol='' Do i=1 To dim ol=ol format(a.i.j,6) End ol=ol format(word(v,j),6) Say ol End Say copies('-',35) d=det(m) Do k=1 To dim Do j=1 To dim Do i=1 To dim If i=k Then b.i.j=word(v,j) Else b.i.j=a.i.j End End Call show_b d.k=det(mk_str()) Say word(names,k) '=' d.k/d End Exit mk_mat: Procedure Expose a. dim Parse Arg list dim=sqrt(words(list)) k=0 Do j=1 To dim Do i=1 To dim k=k+1 a.i.j=word(list,k) End End Return mk_str: Procedure Expose b. dim str='' Do j=1 To dim Do i=1 To dim str=str b.i.j End End Return str show_b: Procedure Expose b. dim do j=1 To dim ol='' Do i=1 To dim ol=ol format(b.i.j,6) end Call dbg ol end Return det: Procedure Parse Arg list n=words(list) call dbg 'det:' list do dim=1 To 10 If dim**2=n Then Leave End call dbg 'dim='dim If dim=2 Then Do det=word(list,1)*word(list,4)-word(list,2)*word(list,3) call dbg 'det=>'det Return det End k=0 Do j=1 To dim Do i=1 To dim k=k+1 a.i.j=word(list,k) End End Do j=1 To dim ol=j Do i=1 To dim ol=ol format(a.i.j,6) End call dbg ol End det=0 Do i=1 To dim ol='' Do j=2 To dim Do ii=1 To dim If ii<>i Then ol=ol a.ii.j End End call dbg 'i='i 'ol='ol If i//2 Then det=det+a.i.1*det(ol) Else det=det-a.i.1*det(ol) End Call dbg 'det=>>>'det Return det sqrt: Procedure * EXEC to calculate the square root of a = 2 with high precision **********************************************************************/ Parse Arg x,prec If prec<9 Then prec=9 prec1=2*prec eps=10**(-prec1) k = 1 Numeric Digits 3 r0= x r = 1 Do i=1 By 1 Until r=r0 | (abs(r*r-x)<eps) r0 = r r = (r + x/r) / 2 k = min(prec1,2*k) Numeric Digits (k + 5) End Numeric Digits prec r=r+0 Return r dbg: Return
Imports System.Runtime.CompilerServices Imports System.Linq.Enumerable Module Module1 <Extension()> Function DelimitWith(Of T)(source As IEnumerable(Of T), Optional seperator As String = " ") As String Return String.Join(seperator, source) End Function Private Class SubMatrix Private ReadOnly source As Integer(,) Private ReadOnly prev As SubMatrix Private ReadOnly replaceColumn As Integer() Public Sub New(source As Integer(,), replaceColumn As Integer()) Me.source = source Me.replaceColumn = replaceColumn prev = Nothing ColumnIndex = -1 Size = replaceColumn.Length End Sub Public Sub New(prev As SubMatrix, Optional deletedColumnIndex As Integer = -1) source = Nothing replaceColumn = Nothing Me.prev = prev ColumnIndex = deletedColumnIndex Size = prev.Size - 1 End Sub Public Property ColumnIndex As Integer Public ReadOnly Property Size As Integer Default Public ReadOnly Property Index(row As Integer, column As Integer) As Integer Get If Not IsNothing(source) Then Return If(column = ColumnIndex, replaceColumn(row), source(row, column)) Else Return prev(row + 1, If(column < ColumnIndex, column, column + 1)) End If End Get End Property Public Function Det() As Integer If Size = 1 Then Return Me(0, 0) If Size = 2 Then Return Me(0, 0) * Me(1, 1) - Me(0, 1) * Me(1, 0) Dim m As New SubMatrix(Me) Dim detVal = 0 Dim sign = 1 For c = 0 To Size - 1 m.ColumnIndex = c Dim d = m.Det() detVal += Me(0, c) * d * sign sign = -sign Next Return detVal End Function Public Sub Print() For r = 0 To Size - 1 Dim rl = r Console.WriteLine(Range(0, Size).Select(Function(c) Me(rl, c)).DelimitWith(", ")) Next Console.WriteLine() End Sub End Class Private Function Solve(matrix As SubMatrix) As Integer() Dim det = matrix.Det() If det = 0 Then Throw New ArgumentException("The determinant is zero.") Dim answer(matrix.Size - 1) As Integer For i = 0 To matrix.Size - 1 matrix.ColumnIndex = i answer(i) = matrix.Det() / det Next Return answer End Function Public Function SolveCramer(equations As Integer()()) As Integer() Dim size = equations.Length If equations.Any(Function(eq) eq.Length <> size + 1) Then Throw New ArgumentException($"Each equation must have {size + 1} terms.") Dim matrix(size - 1, size - 1) As Integer Dim column(size - 1) As Integer For r = 0 To size - 1 column(r) = equations(r)(size) For c = 0 To size - 1 matrix(r, c) = equations(r)(c) Next Next Return Solve(New SubMatrix(matrix, column)) End Function Sub Main() Dim equations = { ({2, -1, 5, 1, -3}), ({3, 2, 2, -6, -32}), ({1, 3, 3, -1, -47}), ({5, -2, -3, 3, 49}) } Dim solution = SolveCramer(equations) Console.WriteLine(solution.DelimitWith(", ")) End Sub End Module
Preserve the algorithm and functionality while converting the code from REXX to Go.
Numeric Digits 20 names='w x y z' M=' 2 -1 5 1', ' 3 2 2 -6', ' 1 3 3 -1', ' 5 -2 -3 3' v=' -3', '-32', '-47', ' 49' Call mk_mat(m) Do j=1 To dim ol='' Do i=1 To dim ol=ol format(a.i.j,6) End ol=ol format(word(v,j),6) Say ol End Say copies('-',35) d=det(m) Do k=1 To dim Do j=1 To dim Do i=1 To dim If i=k Then b.i.j=word(v,j) Else b.i.j=a.i.j End End Call show_b d.k=det(mk_str()) Say word(names,k) '=' d.k/d End Exit mk_mat: Procedure Expose a. dim Parse Arg list dim=sqrt(words(list)) k=0 Do j=1 To dim Do i=1 To dim k=k+1 a.i.j=word(list,k) End End Return mk_str: Procedure Expose b. dim str='' Do j=1 To dim Do i=1 To dim str=str b.i.j End End Return str show_b: Procedure Expose b. dim do j=1 To dim ol='' Do i=1 To dim ol=ol format(b.i.j,6) end Call dbg ol end Return det: Procedure Parse Arg list n=words(list) call dbg 'det:' list do dim=1 To 10 If dim**2=n Then Leave End call dbg 'dim='dim If dim=2 Then Do det=word(list,1)*word(list,4)-word(list,2)*word(list,3) call dbg 'det=>'det Return det End k=0 Do j=1 To dim Do i=1 To dim k=k+1 a.i.j=word(list,k) End End Do j=1 To dim ol=j Do i=1 To dim ol=ol format(a.i.j,6) End call dbg ol End det=0 Do i=1 To dim ol='' Do j=2 To dim Do ii=1 To dim If ii<>i Then ol=ol a.ii.j End End call dbg 'i='i 'ol='ol If i//2 Then det=det+a.i.1*det(ol) Else det=det-a.i.1*det(ol) End Call dbg 'det=>>>'det Return det sqrt: Procedure * EXEC to calculate the square root of a = 2 with high precision **********************************************************************/ Parse Arg x,prec If prec<9 Then prec=9 prec1=2*prec eps=10**(-prec1) k = 1 Numeric Digits 3 r0= x r = 1 Do i=1 By 1 Until r=r0 | (abs(r*r-x)<eps) r0 = r r = (r + x/r) / 2 k = min(prec1,2*k) Numeric Digits (k + 5) End Numeric Digits prec r=r+0 Return r dbg: Return
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) var m = mat.NewDense(4, 4, []float64{ 2, -1, 5, 1, 3, 2, 2, -6, 1, 3, 3, -1, 5, -2, -3, 3, }) var v = []float64{-3, -32, -47, 49} func main() { x := make([]float64, len(v)) b := make([]float64, len(v)) d := mat.Det(m) for c := range v { mat.Col(b, c, m) m.SetCol(c, v) x[c] = mat.Det(m) / d m.SetCol(c, b) } fmt.Println(x) }
Rewrite this program in C while keeping its functionality equivalent to the Ruby version.
require 'matrix' def cramers_rule(a, terms) raise ArgumentError, " Matrix not square" unless a.square? cols = a.to_a.transpose cols.each_index.map do |i| c = cols.dup c[i] = terms Matrix.columns(c).det / a.det end end matrix = Matrix[ [2, -1, 5, 1], [3, 2, 2, -6], [1, 3, 3, -1], [5, -2, -3, 3], ] vector = [-3, -32, -47, 49] puts cramers_rule(matrix, vector)
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct { int n; double **elems; } SquareMatrix; SquareMatrix init_square_matrix(int n, double elems[n][n]) { SquareMatrix A = { .n = n, .elems = malloc(n * sizeof(double *)) }; for(int i = 0; i < n; ++i) { A.elems[i] = malloc(n * sizeof(double)); for(int j = 0; j < n; ++j) A.elems[i][j] = elems[i][j]; } return A; } SquareMatrix copy_square_matrix(SquareMatrix src) { SquareMatrix dest; dest.n = src.n; dest.elems = malloc(dest.n * sizeof(double *)); for(int i = 0; i < dest.n; ++i) { dest.elems[i] = malloc(dest.n * sizeof(double)); for(int j = 0; j < dest.n; ++j) dest.elems[i][j] = src.elems[i][j]; } return dest; } double det(SquareMatrix A) { double det = 1; for(int j = 0; j < A.n; ++j) { int i_max = j; for(int i = j; i < A.n; ++i) if(A.elems[i][j] > A.elems[i_max][j]) i_max = i; if(i_max != j) { for(int k = 0; k < A.n; ++k) { double tmp = A.elems[i_max][k]; A.elems[i_max][k] = A.elems[j][k]; A.elems[j][k] = tmp; } det *= -1; } if(abs(A.elems[j][j]) < 1e-12) { puts("Singular matrix!"); return NAN; } for(int i = j + 1; i < A.n; ++i) { double mult = -A.elems[i][j] / A.elems[j][j]; for(int k = 0; k < A.n; ++k) A.elems[i][k] += mult * A.elems[j][k]; } } for(int i = 0; i < A.n; ++i) det *= A.elems[i][i]; return det; } void deinit_square_matrix(SquareMatrix A) { for(int i = 0; i < A.n; ++i) free(A.elems[i]); free(A.elems); } double cramer_solve(SquareMatrix A, double det_A, double *b, int var) { SquareMatrix tmp = copy_square_matrix(A); for(int i = 0; i < tmp.n; ++i) tmp.elems[i][var] = b[i]; double det_tmp = det(tmp); deinit_square_matrix(tmp); return det_tmp / det_A; } int main(int argc, char **argv) { #define N 4 double elems[N][N] = { { 2, -1, 5, 1}, { 3, 2, 2, -6}, { 1, 3, 3, -1}, { 5, -2, -3, 3} }; SquareMatrix A = init_square_matrix(N, elems); SquareMatrix tmp = copy_square_matrix(A); int det_A = det(tmp); deinit_square_matrix(tmp); double b[] = {-3, -32, -47, 49}; for(int i = 0; i < N; ++i) printf("%7.3lf\n", cramer_solve(A, det_A, b, i)); deinit_square_matrix(A); return EXIT_SUCCESS; }
Port the provided Ruby code into C# while preserving the original functionality.
require 'matrix' def cramers_rule(a, terms) raise ArgumentError, " Matrix not square" unless a.square? cols = a.to_a.transpose cols.each_index.map do |i| c = cols.dup c[i] = terms Matrix.columns(c).det / a.det end end matrix = Matrix[ [2, -1, 5, 1], [3, 2, 2, -6], [1, 3, 3, -1], [5, -2, -3, 3], ] vector = [-3, -32, -47, 49] puts cramers_rule(matrix, vector)
using System; using System.Collections.Generic; using static System.Linq.Enumerable; public static class CramersRule { public static void Main() { var equations = new [] { new [] { 2, -1, 5, 1, -3 }, new [] { 3, 2, 2, -6, -32 }, new [] { 1, 3, 3, -1, -47 }, new [] { 5, -2, -3, 3, 49 } }; var solution = SolveCramer(equations); Console.WriteLine(solution.DelimitWith(", ")); } public static int[] SolveCramer(int[][] equations) { int size = equations.Length; if (equations.Any(eq => eq.Length != size + 1)) throw new ArgumentException($"Each equation must have {size+1} terms."); int[,] matrix = new int[size, size]; int[] column = new int[size]; for (int r = 0; r < size; r++) { column[r] = equations[r][size]; for (int c = 0; c < size; c++) { matrix[r, c] = equations[r][c]; } } return Solve(new SubMatrix(matrix, column)); } private static int[] Solve(SubMatrix matrix) { int det = matrix.Det(); if (det == 0) throw new ArgumentException("The determinant is zero."); int[] answer = new int[matrix.Size]; for (int i = 0; i < matrix.Size; i++) { matrix.ColumnIndex = i; answer[i] = matrix.Det() / det; } return answer; } static string DelimitWith<T>(this IEnumerable<T> source, string separator = " ") => string.Join(separator ?? " ", source ?? Empty<T>()); private class SubMatrix { private int[,] source; private SubMatrix prev; private int[] replaceColumn; public SubMatrix(int[,] source, int[] replaceColumn) { this.source = source; this.replaceColumn = replaceColumn; this.prev = null; this.ColumnIndex = -1; Size = replaceColumn.Length; } private SubMatrix(SubMatrix prev, int deletedColumnIndex = -1) { this.source = null; this.prev = prev; this.ColumnIndex = deletedColumnIndex; Size = prev.Size - 1; } public int ColumnIndex { get; set; } public int Size { get; } public int this[int row, int column] { get { if (source != null) return column == ColumnIndex ? replaceColumn[row] : source[row, column]; return prev[row + 1, column < ColumnIndex ? column : column + 1]; } } public int Det() { if (Size == 1) return this[0, 0]; if (Size == 2) return this[0, 0] * this[1, 1] - this[0, 1] * this[1, 0]; SubMatrix m = new SubMatrix(this); int det = 0; int sign = 1; for (int c = 0; c < Size; c++) { m.ColumnIndex = c; int d = m.Det(); det += this[0, c] * d * sign; sign = -sign; } return det; } public void Print() { for (int r = 0; r < Size; r++) { Console.WriteLine(Range(0, Size).Select(c => this[r, c]).DelimitWith(", ")); } Console.WriteLine(); } } }
Produce a functionally identical C++ code for the snippet given in Ruby.
require 'matrix' def cramers_rule(a, terms) raise ArgumentError, " Matrix not square" unless a.square? cols = a.to_a.transpose cols.each_index.map do |i| c = cols.dup c[i] = terms Matrix.columns(c).det / a.det end end matrix = Matrix[ [2, -1, 5, 1], [3, 2, 2, -6], [1, 3, 3, -1], [5, -2, -3, 3], ] vector = [-3, -32, -47, 49] puts cramers_rule(matrix, vector)
#include <algorithm> #include <iostream> #include <vector> class SubMatrix { const std::vector<std::vector<double>> *source; std::vector<double> replaceColumn; const SubMatrix *prev; size_t sz; int colIndex = -1; public: SubMatrix(const std::vector<std::vector<double>> &src, const std::vector<double> &rc) : source(&src), replaceColumn(rc), prev(nullptr), colIndex(-1) { sz = replaceColumn.size(); } SubMatrix(const SubMatrix &p) : source(nullptr), prev(&p), colIndex(-1) { sz = p.size() - 1; } SubMatrix(const SubMatrix &p, int deletedColumnIndex) : source(nullptr), prev(&p), colIndex(deletedColumnIndex) { sz = p.size() - 1; } int columnIndex() const { return colIndex; } void columnIndex(int index) { colIndex = index; } size_t size() const { return sz; } double index(int row, int col) const { if (source != nullptr) { if (col == colIndex) { return replaceColumn[row]; } else { return (*source)[row][col]; } } else { if (col < colIndex) { return prev->index(row + 1, col); } else { return prev->index(row + 1, col + 1); } } } double det() const { if (sz == 1) { return index(0, 0); } if (sz == 2) { return index(0, 0) * index(1, 1) - index(0, 1) * index(1, 0); } SubMatrix m(*this); double det = 0.0; int sign = 1; for (size_t c = 0; c < sz; ++c) { m.columnIndex(c); double d = m.det(); det += index(0, c) * d * sign; sign = -sign; } return det; } }; std::vector<double> solve(SubMatrix &matrix) { double det = matrix.det(); if (det == 0.0) { throw std::runtime_error("The determinant is zero."); } std::vector<double> answer(matrix.size()); for (int i = 0; i < matrix.size(); ++i) { matrix.columnIndex(i); answer[i] = matrix.det() / det; } return answer; } std::vector<double> solveCramer(const std::vector<std::vector<double>> &equations) { int size = equations.size(); if (std::any_of( equations.cbegin(), equations.cend(), [size](const std::vector<double> &a) { return a.size() != size + 1; } )) { throw std::runtime_error("Each equation must have the expected size."); } std::vector<std::vector<double>> matrix(size); std::vector<double> column(size); for (int r = 0; r < size; ++r) { column[r] = equations[r][size]; matrix[r].resize(size); for (int c = 0; c < size; ++c) { matrix[r][c] = equations[r][c]; } } SubMatrix sm(matrix, column); return solve(sm); } template<typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it++; } while (it != end) { os << ", " << *it++; } return os << ']'; } int main() { std::vector<std::vector<double>> equations = { { 2, -1, 5, 1, -3}, { 3, 2, 2, -6, -32}, { 1, 3, 3, -1, -47}, { 5, -2, -3, 3, 49}, }; auto solution = solveCramer(equations); std::cout << solution << '\n'; return 0; }
Translate the given Ruby code snippet into Java without altering its behavior.
require 'matrix' def cramers_rule(a, terms) raise ArgumentError, " Matrix not square" unless a.square? cols = a.to_a.transpose cols.each_index.map do |i| c = cols.dup c[i] = terms Matrix.columns(c).det / a.det end end matrix = Matrix[ [2, -1, 5, 1], [3, 2, 2, -6], [1, 3, 3, -1], [5, -2, -3, 3], ] vector = [-3, -32, -47, 49] puts cramers_rule(matrix, vector)
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CramersRule { public static void main(String[] args) { Matrix mat = new Matrix(Arrays.asList(2d, -1d, 5d, 1d), Arrays.asList(3d, 2d, 2d, -6d), Arrays.asList(1d, 3d, 3d, -1d), Arrays.asList(5d, -2d, -3d, 3d)); List<Double> b = Arrays.asList(-3d, -32d, -47d, 49d); System.out.println("Solution = " + cramersRule(mat, b)); } private static List<Double> cramersRule(Matrix matrix, List<Double> b) { double denominator = matrix.determinant(); List<Double> result = new ArrayList<>(); for ( int i = 0 ; i < b.size() ; i++ ) { result.add(matrix.replaceColumn(b, i).determinant() / denominator); } return result; } private static class Matrix { private List<List<Double>> matrix; @Override public String toString() { return matrix.toString(); } @SafeVarargs public Matrix(List<Double> ... lists) { matrix = new ArrayList<>(); for ( List<Double> list : lists) { matrix.add(list); } } public Matrix(List<List<Double>> mat) { matrix = mat; } public double determinant() { if ( matrix.size() == 1 ) { return get(0, 0); } if ( matrix.size() == 2 ) { return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0); } double sum = 0; double sign = 1; for ( int i = 0 ; i < matrix.size() ; i++ ) { sum += sign * get(0, i) * coFactor(0, i).determinant(); sign *= -1; } return sum; } private Matrix coFactor(int row, int col) { List<List<Double>> mat = new ArrayList<>(); for ( int i = 0 ; i < matrix.size() ; i++ ) { if ( i == row ) { continue; } List<Double> list = new ArrayList<>(); for ( int j = 0 ; j < matrix.size() ; j++ ) { if ( j == col ) { continue; } list.add(get(i, j)); } mat.add(list); } return new Matrix(mat); } private Matrix replaceColumn(List<Double> b, int column) { List<List<Double>> mat = new ArrayList<>(); for ( int row = 0 ; row < matrix.size() ; row++ ) { List<Double> list = new ArrayList<>(); for ( int col = 0 ; col < matrix.size() ; col++ ) { double value = get(row, col); if ( col == column ) { value = b.get(row); } list.add(value); } mat.add(list); } return new Matrix(mat); } private double get(int row, int col) { return matrix.get(row).get(col); } } }
Preserve the algorithm and functionality while converting the code from Ruby to Python.
require 'matrix' def cramers_rule(a, terms) raise ArgumentError, " Matrix not square" unless a.square? cols = a.to_a.transpose cols.each_index.map do |i| c = cols.dup c[i] = terms Matrix.columns(c).det / a.det end end matrix = Matrix[ [2, -1, 5, 1], [3, 2, 2, -6], [1, 3, 3, -1], [5, -2, -3, 3], ] vector = [-3, -32, -47, 49] puts cramers_rule(matrix, vector)
def det(m,n): if n==1: return m[0][0] z=0 for r in range(n): k=m[:] del k[r] z+=m[r][0]*(-1)**r*det([p[1:]for p in k],n-1) return z w=len(t) d=det(h,w) if d==0:r=[] else:r=[det([r[0:i]+[s]+r[i+1:]for r,s in zip(h,t)],w)/d for i in range(w)] print(r)
Write the same code in VB as shown below in Ruby.
require 'matrix' def cramers_rule(a, terms) raise ArgumentError, " Matrix not square" unless a.square? cols = a.to_a.transpose cols.each_index.map do |i| c = cols.dup c[i] = terms Matrix.columns(c).det / a.det end end matrix = Matrix[ [2, -1, 5, 1], [3, 2, 2, -6], [1, 3, 3, -1], [5, -2, -3, 3], ] vector = [-3, -32, -47, 49] puts cramers_rule(matrix, vector)
Imports System.Runtime.CompilerServices Imports System.Linq.Enumerable Module Module1 <Extension()> Function DelimitWith(Of T)(source As IEnumerable(Of T), Optional seperator As String = " ") As String Return String.Join(seperator, source) End Function Private Class SubMatrix Private ReadOnly source As Integer(,) Private ReadOnly prev As SubMatrix Private ReadOnly replaceColumn As Integer() Public Sub New(source As Integer(,), replaceColumn As Integer()) Me.source = source Me.replaceColumn = replaceColumn prev = Nothing ColumnIndex = -1 Size = replaceColumn.Length End Sub Public Sub New(prev As SubMatrix, Optional deletedColumnIndex As Integer = -1) source = Nothing replaceColumn = Nothing Me.prev = prev ColumnIndex = deletedColumnIndex Size = prev.Size - 1 End Sub Public Property ColumnIndex As Integer Public ReadOnly Property Size As Integer Default Public ReadOnly Property Index(row As Integer, column As Integer) As Integer Get If Not IsNothing(source) Then Return If(column = ColumnIndex, replaceColumn(row), source(row, column)) Else Return prev(row + 1, If(column < ColumnIndex, column, column + 1)) End If End Get End Property Public Function Det() As Integer If Size = 1 Then Return Me(0, 0) If Size = 2 Then Return Me(0, 0) * Me(1, 1) - Me(0, 1) * Me(1, 0) Dim m As New SubMatrix(Me) Dim detVal = 0 Dim sign = 1 For c = 0 To Size - 1 m.ColumnIndex = c Dim d = m.Det() detVal += Me(0, c) * d * sign sign = -sign Next Return detVal End Function Public Sub Print() For r = 0 To Size - 1 Dim rl = r Console.WriteLine(Range(0, Size).Select(Function(c) Me(rl, c)).DelimitWith(", ")) Next Console.WriteLine() End Sub End Class Private Function Solve(matrix As SubMatrix) As Integer() Dim det = matrix.Det() If det = 0 Then Throw New ArgumentException("The determinant is zero.") Dim answer(matrix.Size - 1) As Integer For i = 0 To matrix.Size - 1 matrix.ColumnIndex = i answer(i) = matrix.Det() / det Next Return answer End Function Public Function SolveCramer(equations As Integer()()) As Integer() Dim size = equations.Length If equations.Any(Function(eq) eq.Length <> size + 1) Then Throw New ArgumentException($"Each equation must have {size + 1} terms.") Dim matrix(size - 1, size - 1) As Integer Dim column(size - 1) As Integer For r = 0 To size - 1 column(r) = equations(r)(size) For c = 0 To size - 1 matrix(r, c) = equations(r)(c) Next Next Return Solve(New SubMatrix(matrix, column)) End Function Sub Main() Dim equations = { ({2, -1, 5, 1, -3}), ({3, 2, 2, -6, -32}), ({1, 3, 3, -1, -47}), ({5, -2, -3, 3, 49}) } Dim solution = SolveCramer(equations) Console.WriteLine(solution.DelimitWith(", ")) End Sub End Module
Ensure the translated Go code behaves exactly like the original Ruby snippet.
require 'matrix' def cramers_rule(a, terms) raise ArgumentError, " Matrix not square" unless a.square? cols = a.to_a.transpose cols.each_index.map do |i| c = cols.dup c[i] = terms Matrix.columns(c).det / a.det end end matrix = Matrix[ [2, -1, 5, 1], [3, 2, 2, -6], [1, 3, 3, -1], [5, -2, -3, 3], ] vector = [-3, -32, -47, 49] puts cramers_rule(matrix, vector)
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) var m = mat.NewDense(4, 4, []float64{ 2, -1, 5, 1, 3, 2, 2, -6, 1, 3, 3, -1, 5, -2, -3, 3, }) var v = []float64{-3, -32, -47, 49} func main() { x := make([]float64, len(v)) b := make([]float64, len(v)) d := mat.Det(m) for c := range v { mat.Col(b, c, m) m.SetCol(c, v) x[c] = mat.Det(m) / d m.SetCol(c, b) } fmt.Println(x) }
Transform the following Scala implementation into C, maintaining the same output and logic.
typealias Vector = DoubleArray typealias Matrix = Array<Vector> fun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> { val p = IntArray(n) { it } val q = IntArray(n) { it } val d = IntArray(n) { -1 } var sign = 1 val perms = mutableListOf<IntArray>() val signs = mutableListOf<Int>() fun permute(k: Int) { if (k >= n) { perms.add(p.copyOf()) signs.add(sign) sign *= -1 return } permute(k + 1) for (i in 0 until k) { val z = p[q[k] + d[k]] p[q[k]] = z p[q[k] + d[k]] = k q[z] = q[k] q[k] += d[k] permute(k + 1) } d[k] *= -1 } permute(0) return perms to signs } fun determinant(m: Matrix): Double { val (sigmas, signs) = johnsonTrotter(m.size) var sum = 0.0 for ((i, sigma) in sigmas.withIndex()) { var prod = 1.0 for ((j, s) in sigma.withIndex()) prod *= m[j][s] sum += signs[i] * prod } return sum } fun cramer(m: Matrix, d: Vector): Vector { val divisor = determinant(m) val numerators = Array(m.size) { Matrix(m.size) { m[it].copyOf() } } val v = Vector(m.size) for (i in 0 until m.size) { for (j in 0 until m.size) numerators[i][j][i] = d[j] } for (i in 0 until m.size) v[i] = determinant(numerators[i]) / divisor return v } fun main(args: Array<String>) { val m = arrayOf( doubleArrayOf(2.0, -1.0, 5.0, 1.0), doubleArrayOf(3.0, 2.0, 2.0, -6.0), doubleArrayOf(1.0, 3.0, 3.0, -1.0), doubleArrayOf(5.0, -2.0, -3.0, 3.0) ) val d = doubleArrayOf(-3.0, -32.0, -47.0, 49.0) val (w, x, y, z) = cramer(m, d) println("w = $w, x = $x, y = $y, z = $z") }
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct { int n; double **elems; } SquareMatrix; SquareMatrix init_square_matrix(int n, double elems[n][n]) { SquareMatrix A = { .n = n, .elems = malloc(n * sizeof(double *)) }; for(int i = 0; i < n; ++i) { A.elems[i] = malloc(n * sizeof(double)); for(int j = 0; j < n; ++j) A.elems[i][j] = elems[i][j]; } return A; } SquareMatrix copy_square_matrix(SquareMatrix src) { SquareMatrix dest; dest.n = src.n; dest.elems = malloc(dest.n * sizeof(double *)); for(int i = 0; i < dest.n; ++i) { dest.elems[i] = malloc(dest.n * sizeof(double)); for(int j = 0; j < dest.n; ++j) dest.elems[i][j] = src.elems[i][j]; } return dest; } double det(SquareMatrix A) { double det = 1; for(int j = 0; j < A.n; ++j) { int i_max = j; for(int i = j; i < A.n; ++i) if(A.elems[i][j] > A.elems[i_max][j]) i_max = i; if(i_max != j) { for(int k = 0; k < A.n; ++k) { double tmp = A.elems[i_max][k]; A.elems[i_max][k] = A.elems[j][k]; A.elems[j][k] = tmp; } det *= -1; } if(abs(A.elems[j][j]) < 1e-12) { puts("Singular matrix!"); return NAN; } for(int i = j + 1; i < A.n; ++i) { double mult = -A.elems[i][j] / A.elems[j][j]; for(int k = 0; k < A.n; ++k) A.elems[i][k] += mult * A.elems[j][k]; } } for(int i = 0; i < A.n; ++i) det *= A.elems[i][i]; return det; } void deinit_square_matrix(SquareMatrix A) { for(int i = 0; i < A.n; ++i) free(A.elems[i]); free(A.elems); } double cramer_solve(SquareMatrix A, double det_A, double *b, int var) { SquareMatrix tmp = copy_square_matrix(A); for(int i = 0; i < tmp.n; ++i) tmp.elems[i][var] = b[i]; double det_tmp = det(tmp); deinit_square_matrix(tmp); return det_tmp / det_A; } int main(int argc, char **argv) { #define N 4 double elems[N][N] = { { 2, -1, 5, 1}, { 3, 2, 2, -6}, { 1, 3, 3, -1}, { 5, -2, -3, 3} }; SquareMatrix A = init_square_matrix(N, elems); SquareMatrix tmp = copy_square_matrix(A); int det_A = det(tmp); deinit_square_matrix(tmp); double b[] = {-3, -32, -47, 49}; for(int i = 0; i < N; ++i) printf("%7.3lf\n", cramer_solve(A, det_A, b, i)); deinit_square_matrix(A); return EXIT_SUCCESS; }
Preserve the algorithm and functionality while converting the code from Scala to C#.
typealias Vector = DoubleArray typealias Matrix = Array<Vector> fun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> { val p = IntArray(n) { it } val q = IntArray(n) { it } val d = IntArray(n) { -1 } var sign = 1 val perms = mutableListOf<IntArray>() val signs = mutableListOf<Int>() fun permute(k: Int) { if (k >= n) { perms.add(p.copyOf()) signs.add(sign) sign *= -1 return } permute(k + 1) for (i in 0 until k) { val z = p[q[k] + d[k]] p[q[k]] = z p[q[k] + d[k]] = k q[z] = q[k] q[k] += d[k] permute(k + 1) } d[k] *= -1 } permute(0) return perms to signs } fun determinant(m: Matrix): Double { val (sigmas, signs) = johnsonTrotter(m.size) var sum = 0.0 for ((i, sigma) in sigmas.withIndex()) { var prod = 1.0 for ((j, s) in sigma.withIndex()) prod *= m[j][s] sum += signs[i] * prod } return sum } fun cramer(m: Matrix, d: Vector): Vector { val divisor = determinant(m) val numerators = Array(m.size) { Matrix(m.size) { m[it].copyOf() } } val v = Vector(m.size) for (i in 0 until m.size) { for (j in 0 until m.size) numerators[i][j][i] = d[j] } for (i in 0 until m.size) v[i] = determinant(numerators[i]) / divisor return v } fun main(args: Array<String>) { val m = arrayOf( doubleArrayOf(2.0, -1.0, 5.0, 1.0), doubleArrayOf(3.0, 2.0, 2.0, -6.0), doubleArrayOf(1.0, 3.0, 3.0, -1.0), doubleArrayOf(5.0, -2.0, -3.0, 3.0) ) val d = doubleArrayOf(-3.0, -32.0, -47.0, 49.0) val (w, x, y, z) = cramer(m, d) println("w = $w, x = $x, y = $y, z = $z") }
using System; using System.Collections.Generic; using static System.Linq.Enumerable; public static class CramersRule { public static void Main() { var equations = new [] { new [] { 2, -1, 5, 1, -3 }, new [] { 3, 2, 2, -6, -32 }, new [] { 1, 3, 3, -1, -47 }, new [] { 5, -2, -3, 3, 49 } }; var solution = SolveCramer(equations); Console.WriteLine(solution.DelimitWith(", ")); } public static int[] SolveCramer(int[][] equations) { int size = equations.Length; if (equations.Any(eq => eq.Length != size + 1)) throw new ArgumentException($"Each equation must have {size+1} terms."); int[,] matrix = new int[size, size]; int[] column = new int[size]; for (int r = 0; r < size; r++) { column[r] = equations[r][size]; for (int c = 0; c < size; c++) { matrix[r, c] = equations[r][c]; } } return Solve(new SubMatrix(matrix, column)); } private static int[] Solve(SubMatrix matrix) { int det = matrix.Det(); if (det == 0) throw new ArgumentException("The determinant is zero."); int[] answer = new int[matrix.Size]; for (int i = 0; i < matrix.Size; i++) { matrix.ColumnIndex = i; answer[i] = matrix.Det() / det; } return answer; } static string DelimitWith<T>(this IEnumerable<T> source, string separator = " ") => string.Join(separator ?? " ", source ?? Empty<T>()); private class SubMatrix { private int[,] source; private SubMatrix prev; private int[] replaceColumn; public SubMatrix(int[,] source, int[] replaceColumn) { this.source = source; this.replaceColumn = replaceColumn; this.prev = null; this.ColumnIndex = -1; Size = replaceColumn.Length; } private SubMatrix(SubMatrix prev, int deletedColumnIndex = -1) { this.source = null; this.prev = prev; this.ColumnIndex = deletedColumnIndex; Size = prev.Size - 1; } public int ColumnIndex { get; set; } public int Size { get; } public int this[int row, int column] { get { if (source != null) return column == ColumnIndex ? replaceColumn[row] : source[row, column]; return prev[row + 1, column < ColumnIndex ? column : column + 1]; } } public int Det() { if (Size == 1) return this[0, 0]; if (Size == 2) return this[0, 0] * this[1, 1] - this[0, 1] * this[1, 0]; SubMatrix m = new SubMatrix(this); int det = 0; int sign = 1; for (int c = 0; c < Size; c++) { m.ColumnIndex = c; int d = m.Det(); det += this[0, c] * d * sign; sign = -sign; } return det; } public void Print() { for (int r = 0; r < Size; r++) { Console.WriteLine(Range(0, Size).Select(c => this[r, c]).DelimitWith(", ")); } Console.WriteLine(); } } }
Port the following code from Scala to C++ with equivalent syntax and logic.
typealias Vector = DoubleArray typealias Matrix = Array<Vector> fun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> { val p = IntArray(n) { it } val q = IntArray(n) { it } val d = IntArray(n) { -1 } var sign = 1 val perms = mutableListOf<IntArray>() val signs = mutableListOf<Int>() fun permute(k: Int) { if (k >= n) { perms.add(p.copyOf()) signs.add(sign) sign *= -1 return } permute(k + 1) for (i in 0 until k) { val z = p[q[k] + d[k]] p[q[k]] = z p[q[k] + d[k]] = k q[z] = q[k] q[k] += d[k] permute(k + 1) } d[k] *= -1 } permute(0) return perms to signs } fun determinant(m: Matrix): Double { val (sigmas, signs) = johnsonTrotter(m.size) var sum = 0.0 for ((i, sigma) in sigmas.withIndex()) { var prod = 1.0 for ((j, s) in sigma.withIndex()) prod *= m[j][s] sum += signs[i] * prod } return sum } fun cramer(m: Matrix, d: Vector): Vector { val divisor = determinant(m) val numerators = Array(m.size) { Matrix(m.size) { m[it].copyOf() } } val v = Vector(m.size) for (i in 0 until m.size) { for (j in 0 until m.size) numerators[i][j][i] = d[j] } for (i in 0 until m.size) v[i] = determinant(numerators[i]) / divisor return v } fun main(args: Array<String>) { val m = arrayOf( doubleArrayOf(2.0, -1.0, 5.0, 1.0), doubleArrayOf(3.0, 2.0, 2.0, -6.0), doubleArrayOf(1.0, 3.0, 3.0, -1.0), doubleArrayOf(5.0, -2.0, -3.0, 3.0) ) val d = doubleArrayOf(-3.0, -32.0, -47.0, 49.0) val (w, x, y, z) = cramer(m, d) println("w = $w, x = $x, y = $y, z = $z") }
#include <algorithm> #include <iostream> #include <vector> class SubMatrix { const std::vector<std::vector<double>> *source; std::vector<double> replaceColumn; const SubMatrix *prev; size_t sz; int colIndex = -1; public: SubMatrix(const std::vector<std::vector<double>> &src, const std::vector<double> &rc) : source(&src), replaceColumn(rc), prev(nullptr), colIndex(-1) { sz = replaceColumn.size(); } SubMatrix(const SubMatrix &p) : source(nullptr), prev(&p), colIndex(-1) { sz = p.size() - 1; } SubMatrix(const SubMatrix &p, int deletedColumnIndex) : source(nullptr), prev(&p), colIndex(deletedColumnIndex) { sz = p.size() - 1; } int columnIndex() const { return colIndex; } void columnIndex(int index) { colIndex = index; } size_t size() const { return sz; } double index(int row, int col) const { if (source != nullptr) { if (col == colIndex) { return replaceColumn[row]; } else { return (*source)[row][col]; } } else { if (col < colIndex) { return prev->index(row + 1, col); } else { return prev->index(row + 1, col + 1); } } } double det() const { if (sz == 1) { return index(0, 0); } if (sz == 2) { return index(0, 0) * index(1, 1) - index(0, 1) * index(1, 0); } SubMatrix m(*this); double det = 0.0; int sign = 1; for (size_t c = 0; c < sz; ++c) { m.columnIndex(c); double d = m.det(); det += index(0, c) * d * sign; sign = -sign; } return det; } }; std::vector<double> solve(SubMatrix &matrix) { double det = matrix.det(); if (det == 0.0) { throw std::runtime_error("The determinant is zero."); } std::vector<double> answer(matrix.size()); for (int i = 0; i < matrix.size(); ++i) { matrix.columnIndex(i); answer[i] = matrix.det() / det; } return answer; } std::vector<double> solveCramer(const std::vector<std::vector<double>> &equations) { int size = equations.size(); if (std::any_of( equations.cbegin(), equations.cend(), [size](const std::vector<double> &a) { return a.size() != size + 1; } )) { throw std::runtime_error("Each equation must have the expected size."); } std::vector<std::vector<double>> matrix(size); std::vector<double> column(size); for (int r = 0; r < size; ++r) { column[r] = equations[r][size]; matrix[r].resize(size); for (int c = 0; c < size; ++c) { matrix[r][c] = equations[r][c]; } } SubMatrix sm(matrix, column); return solve(sm); } template<typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it++; } while (it != end) { os << ", " << *it++; } return os << ']'; } int main() { std::vector<std::vector<double>> equations = { { 2, -1, 5, 1, -3}, { 3, 2, 2, -6, -32}, { 1, 3, 3, -1, -47}, { 5, -2, -3, 3, 49}, }; auto solution = solveCramer(equations); std::cout << solution << '\n'; return 0; }
Produce a functionally identical Java code for the snippet given in Scala.
typealias Vector = DoubleArray typealias Matrix = Array<Vector> fun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> { val p = IntArray(n) { it } val q = IntArray(n) { it } val d = IntArray(n) { -1 } var sign = 1 val perms = mutableListOf<IntArray>() val signs = mutableListOf<Int>() fun permute(k: Int) { if (k >= n) { perms.add(p.copyOf()) signs.add(sign) sign *= -1 return } permute(k + 1) for (i in 0 until k) { val z = p[q[k] + d[k]] p[q[k]] = z p[q[k] + d[k]] = k q[z] = q[k] q[k] += d[k] permute(k + 1) } d[k] *= -1 } permute(0) return perms to signs } fun determinant(m: Matrix): Double { val (sigmas, signs) = johnsonTrotter(m.size) var sum = 0.0 for ((i, sigma) in sigmas.withIndex()) { var prod = 1.0 for ((j, s) in sigma.withIndex()) prod *= m[j][s] sum += signs[i] * prod } return sum } fun cramer(m: Matrix, d: Vector): Vector { val divisor = determinant(m) val numerators = Array(m.size) { Matrix(m.size) { m[it].copyOf() } } val v = Vector(m.size) for (i in 0 until m.size) { for (j in 0 until m.size) numerators[i][j][i] = d[j] } for (i in 0 until m.size) v[i] = determinant(numerators[i]) / divisor return v } fun main(args: Array<String>) { val m = arrayOf( doubleArrayOf(2.0, -1.0, 5.0, 1.0), doubleArrayOf(3.0, 2.0, 2.0, -6.0), doubleArrayOf(1.0, 3.0, 3.0, -1.0), doubleArrayOf(5.0, -2.0, -3.0, 3.0) ) val d = doubleArrayOf(-3.0, -32.0, -47.0, 49.0) val (w, x, y, z) = cramer(m, d) println("w = $w, x = $x, y = $y, z = $z") }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CramersRule { public static void main(String[] args) { Matrix mat = new Matrix(Arrays.asList(2d, -1d, 5d, 1d), Arrays.asList(3d, 2d, 2d, -6d), Arrays.asList(1d, 3d, 3d, -1d), Arrays.asList(5d, -2d, -3d, 3d)); List<Double> b = Arrays.asList(-3d, -32d, -47d, 49d); System.out.println("Solution = " + cramersRule(mat, b)); } private static List<Double> cramersRule(Matrix matrix, List<Double> b) { double denominator = matrix.determinant(); List<Double> result = new ArrayList<>(); for ( int i = 0 ; i < b.size() ; i++ ) { result.add(matrix.replaceColumn(b, i).determinant() / denominator); } return result; } private static class Matrix { private List<List<Double>> matrix; @Override public String toString() { return matrix.toString(); } @SafeVarargs public Matrix(List<Double> ... lists) { matrix = new ArrayList<>(); for ( List<Double> list : lists) { matrix.add(list); } } public Matrix(List<List<Double>> mat) { matrix = mat; } public double determinant() { if ( matrix.size() == 1 ) { return get(0, 0); } if ( matrix.size() == 2 ) { return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0); } double sum = 0; double sign = 1; for ( int i = 0 ; i < matrix.size() ; i++ ) { sum += sign * get(0, i) * coFactor(0, i).determinant(); sign *= -1; } return sum; } private Matrix coFactor(int row, int col) { List<List<Double>> mat = new ArrayList<>(); for ( int i = 0 ; i < matrix.size() ; i++ ) { if ( i == row ) { continue; } List<Double> list = new ArrayList<>(); for ( int j = 0 ; j < matrix.size() ; j++ ) { if ( j == col ) { continue; } list.add(get(i, j)); } mat.add(list); } return new Matrix(mat); } private Matrix replaceColumn(List<Double> b, int column) { List<List<Double>> mat = new ArrayList<>(); for ( int row = 0 ; row < matrix.size() ; row++ ) { List<Double> list = new ArrayList<>(); for ( int col = 0 ; col < matrix.size() ; col++ ) { double value = get(row, col); if ( col == column ) { value = b.get(row); } list.add(value); } mat.add(list); } return new Matrix(mat); } private double get(int row, int col) { return matrix.get(row).get(col); } } }
Change the following Scala code into Python without altering its purpose.
typealias Vector = DoubleArray typealias Matrix = Array<Vector> fun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> { val p = IntArray(n) { it } val q = IntArray(n) { it } val d = IntArray(n) { -1 } var sign = 1 val perms = mutableListOf<IntArray>() val signs = mutableListOf<Int>() fun permute(k: Int) { if (k >= n) { perms.add(p.copyOf()) signs.add(sign) sign *= -1 return } permute(k + 1) for (i in 0 until k) { val z = p[q[k] + d[k]] p[q[k]] = z p[q[k] + d[k]] = k q[z] = q[k] q[k] += d[k] permute(k + 1) } d[k] *= -1 } permute(0) return perms to signs } fun determinant(m: Matrix): Double { val (sigmas, signs) = johnsonTrotter(m.size) var sum = 0.0 for ((i, sigma) in sigmas.withIndex()) { var prod = 1.0 for ((j, s) in sigma.withIndex()) prod *= m[j][s] sum += signs[i] * prod } return sum } fun cramer(m: Matrix, d: Vector): Vector { val divisor = determinant(m) val numerators = Array(m.size) { Matrix(m.size) { m[it].copyOf() } } val v = Vector(m.size) for (i in 0 until m.size) { for (j in 0 until m.size) numerators[i][j][i] = d[j] } for (i in 0 until m.size) v[i] = determinant(numerators[i]) / divisor return v } fun main(args: Array<String>) { val m = arrayOf( doubleArrayOf(2.0, -1.0, 5.0, 1.0), doubleArrayOf(3.0, 2.0, 2.0, -6.0), doubleArrayOf(1.0, 3.0, 3.0, -1.0), doubleArrayOf(5.0, -2.0, -3.0, 3.0) ) val d = doubleArrayOf(-3.0, -32.0, -47.0, 49.0) val (w, x, y, z) = cramer(m, d) println("w = $w, x = $x, y = $y, z = $z") }
def det(m,n): if n==1: return m[0][0] z=0 for r in range(n): k=m[:] del k[r] z+=m[r][0]*(-1)**r*det([p[1:]for p in k],n-1) return z w=len(t) d=det(h,w) if d==0:r=[] else:r=[det([r[0:i]+[s]+r[i+1:]for r,s in zip(h,t)],w)/d for i in range(w)] print(r)
Ensure the translated VB code behaves exactly like the original Scala snippet.
typealias Vector = DoubleArray typealias Matrix = Array<Vector> fun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> { val p = IntArray(n) { it } val q = IntArray(n) { it } val d = IntArray(n) { -1 } var sign = 1 val perms = mutableListOf<IntArray>() val signs = mutableListOf<Int>() fun permute(k: Int) { if (k >= n) { perms.add(p.copyOf()) signs.add(sign) sign *= -1 return } permute(k + 1) for (i in 0 until k) { val z = p[q[k] + d[k]] p[q[k]] = z p[q[k] + d[k]] = k q[z] = q[k] q[k] += d[k] permute(k + 1) } d[k] *= -1 } permute(0) return perms to signs } fun determinant(m: Matrix): Double { val (sigmas, signs) = johnsonTrotter(m.size) var sum = 0.0 for ((i, sigma) in sigmas.withIndex()) { var prod = 1.0 for ((j, s) in sigma.withIndex()) prod *= m[j][s] sum += signs[i] * prod } return sum } fun cramer(m: Matrix, d: Vector): Vector { val divisor = determinant(m) val numerators = Array(m.size) { Matrix(m.size) { m[it].copyOf() } } val v = Vector(m.size) for (i in 0 until m.size) { for (j in 0 until m.size) numerators[i][j][i] = d[j] } for (i in 0 until m.size) v[i] = determinant(numerators[i]) / divisor return v } fun main(args: Array<String>) { val m = arrayOf( doubleArrayOf(2.0, -1.0, 5.0, 1.0), doubleArrayOf(3.0, 2.0, 2.0, -6.0), doubleArrayOf(1.0, 3.0, 3.0, -1.0), doubleArrayOf(5.0, -2.0, -3.0, 3.0) ) val d = doubleArrayOf(-3.0, -32.0, -47.0, 49.0) val (w, x, y, z) = cramer(m, d) println("w = $w, x = $x, y = $y, z = $z") }
Imports System.Runtime.CompilerServices Imports System.Linq.Enumerable Module Module1 <Extension()> Function DelimitWith(Of T)(source As IEnumerable(Of T), Optional seperator As String = " ") As String Return String.Join(seperator, source) End Function Private Class SubMatrix Private ReadOnly source As Integer(,) Private ReadOnly prev As SubMatrix Private ReadOnly replaceColumn As Integer() Public Sub New(source As Integer(,), replaceColumn As Integer()) Me.source = source Me.replaceColumn = replaceColumn prev = Nothing ColumnIndex = -1 Size = replaceColumn.Length End Sub Public Sub New(prev As SubMatrix, Optional deletedColumnIndex As Integer = -1) source = Nothing replaceColumn = Nothing Me.prev = prev ColumnIndex = deletedColumnIndex Size = prev.Size - 1 End Sub Public Property ColumnIndex As Integer Public ReadOnly Property Size As Integer Default Public ReadOnly Property Index(row As Integer, column As Integer) As Integer Get If Not IsNothing(source) Then Return If(column = ColumnIndex, replaceColumn(row), source(row, column)) Else Return prev(row + 1, If(column < ColumnIndex, column, column + 1)) End If End Get End Property Public Function Det() As Integer If Size = 1 Then Return Me(0, 0) If Size = 2 Then Return Me(0, 0) * Me(1, 1) - Me(0, 1) * Me(1, 0) Dim m As New SubMatrix(Me) Dim detVal = 0 Dim sign = 1 For c = 0 To Size - 1 m.ColumnIndex = c Dim d = m.Det() detVal += Me(0, c) * d * sign sign = -sign Next Return detVal End Function Public Sub Print() For r = 0 To Size - 1 Dim rl = r Console.WriteLine(Range(0, Size).Select(Function(c) Me(rl, c)).DelimitWith(", ")) Next Console.WriteLine() End Sub End Class Private Function Solve(matrix As SubMatrix) As Integer() Dim det = matrix.Det() If det = 0 Then Throw New ArgumentException("The determinant is zero.") Dim answer(matrix.Size - 1) As Integer For i = 0 To matrix.Size - 1 matrix.ColumnIndex = i answer(i) = matrix.Det() / det Next Return answer End Function Public Function SolveCramer(equations As Integer()()) As Integer() Dim size = equations.Length If equations.Any(Function(eq) eq.Length <> size + 1) Then Throw New ArgumentException($"Each equation must have {size + 1} terms.") Dim matrix(size - 1, size - 1) As Integer Dim column(size - 1) As Integer For r = 0 To size - 1 column(r) = equations(r)(size) For c = 0 To size - 1 matrix(r, c) = equations(r)(c) Next Next Return Solve(New SubMatrix(matrix, column)) End Function Sub Main() Dim equations = { ({2, -1, 5, 1, -3}), ({3, 2, 2, -6, -32}), ({1, 3, 3, -1, -47}), ({5, -2, -3, 3, 49}) } Dim solution = SolveCramer(equations) Console.WriteLine(solution.DelimitWith(", ")) End Sub End Module
Port the following code from Scala to Go with equivalent syntax and logic.
typealias Vector = DoubleArray typealias Matrix = Array<Vector> fun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> { val p = IntArray(n) { it } val q = IntArray(n) { it } val d = IntArray(n) { -1 } var sign = 1 val perms = mutableListOf<IntArray>() val signs = mutableListOf<Int>() fun permute(k: Int) { if (k >= n) { perms.add(p.copyOf()) signs.add(sign) sign *= -1 return } permute(k + 1) for (i in 0 until k) { val z = p[q[k] + d[k]] p[q[k]] = z p[q[k] + d[k]] = k q[z] = q[k] q[k] += d[k] permute(k + 1) } d[k] *= -1 } permute(0) return perms to signs } fun determinant(m: Matrix): Double { val (sigmas, signs) = johnsonTrotter(m.size) var sum = 0.0 for ((i, sigma) in sigmas.withIndex()) { var prod = 1.0 for ((j, s) in sigma.withIndex()) prod *= m[j][s] sum += signs[i] * prod } return sum } fun cramer(m: Matrix, d: Vector): Vector { val divisor = determinant(m) val numerators = Array(m.size) { Matrix(m.size) { m[it].copyOf() } } val v = Vector(m.size) for (i in 0 until m.size) { for (j in 0 until m.size) numerators[i][j][i] = d[j] } for (i in 0 until m.size) v[i] = determinant(numerators[i]) / divisor return v } fun main(args: Array<String>) { val m = arrayOf( doubleArrayOf(2.0, -1.0, 5.0, 1.0), doubleArrayOf(3.0, 2.0, 2.0, -6.0), doubleArrayOf(1.0, 3.0, 3.0, -1.0), doubleArrayOf(5.0, -2.0, -3.0, 3.0) ) val d = doubleArrayOf(-3.0, -32.0, -47.0, 49.0) val (w, x, y, z) = cramer(m, d) println("w = $w, x = $x, y = $y, z = $z") }
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) var m = mat.NewDense(4, 4, []float64{ 2, -1, 5, 1, 3, 2, 2, -6, 1, 3, 3, -1, 5, -2, -3, 3, }) var v = []float64{-3, -32, -47, 49} func main() { x := make([]float64, len(v)) b := make([]float64, len(v)) d := mat.Det(m) for c := range v { mat.Col(b, c, m) m.SetCol(c, v) x[c] = mat.Det(m) / d m.SetCol(c, b) } fmt.Println(x) }
Preserve the algorithm and functionality while converting the code from Tcl to C.
package require math::linearalgebra namespace path ::math::linearalgebra set A [list { 2 -1 5 1} { 3 2 2 -6} { 1 3 3 -1} { 5 -2 -3 3}] set n [llength $A] set right {-3 -32 -47 49} set detA [det $A] for {set i 0} {$i < $n} {incr i} { set tmp $A ; setcol tmp $i $right ; set detTmp [det $tmp] ; set v [expr $detTmp / $detA] ; puts [format "%0.4f" $v] ; }
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct { int n; double **elems; } SquareMatrix; SquareMatrix init_square_matrix(int n, double elems[n][n]) { SquareMatrix A = { .n = n, .elems = malloc(n * sizeof(double *)) }; for(int i = 0; i < n; ++i) { A.elems[i] = malloc(n * sizeof(double)); for(int j = 0; j < n; ++j) A.elems[i][j] = elems[i][j]; } return A; } SquareMatrix copy_square_matrix(SquareMatrix src) { SquareMatrix dest; dest.n = src.n; dest.elems = malloc(dest.n * sizeof(double *)); for(int i = 0; i < dest.n; ++i) { dest.elems[i] = malloc(dest.n * sizeof(double)); for(int j = 0; j < dest.n; ++j) dest.elems[i][j] = src.elems[i][j]; } return dest; } double det(SquareMatrix A) { double det = 1; for(int j = 0; j < A.n; ++j) { int i_max = j; for(int i = j; i < A.n; ++i) if(A.elems[i][j] > A.elems[i_max][j]) i_max = i; if(i_max != j) { for(int k = 0; k < A.n; ++k) { double tmp = A.elems[i_max][k]; A.elems[i_max][k] = A.elems[j][k]; A.elems[j][k] = tmp; } det *= -1; } if(abs(A.elems[j][j]) < 1e-12) { puts("Singular matrix!"); return NAN; } for(int i = j + 1; i < A.n; ++i) { double mult = -A.elems[i][j] / A.elems[j][j]; for(int k = 0; k < A.n; ++k) A.elems[i][k] += mult * A.elems[j][k]; } } for(int i = 0; i < A.n; ++i) det *= A.elems[i][i]; return det; } void deinit_square_matrix(SquareMatrix A) { for(int i = 0; i < A.n; ++i) free(A.elems[i]); free(A.elems); } double cramer_solve(SquareMatrix A, double det_A, double *b, int var) { SquareMatrix tmp = copy_square_matrix(A); for(int i = 0; i < tmp.n; ++i) tmp.elems[i][var] = b[i]; double det_tmp = det(tmp); deinit_square_matrix(tmp); return det_tmp / det_A; } int main(int argc, char **argv) { #define N 4 double elems[N][N] = { { 2, -1, 5, 1}, { 3, 2, 2, -6}, { 1, 3, 3, -1}, { 5, -2, -3, 3} }; SquareMatrix A = init_square_matrix(N, elems); SquareMatrix tmp = copy_square_matrix(A); int det_A = det(tmp); deinit_square_matrix(tmp); double b[] = {-3, -32, -47, 49}; for(int i = 0; i < N; ++i) printf("%7.3lf\n", cramer_solve(A, det_A, b, i)); deinit_square_matrix(A); return EXIT_SUCCESS; }
Change the following Tcl code into C# without altering its purpose.
package require math::linearalgebra namespace path ::math::linearalgebra set A [list { 2 -1 5 1} { 3 2 2 -6} { 1 3 3 -1} { 5 -2 -3 3}] set n [llength $A] set right {-3 -32 -47 49} set detA [det $A] for {set i 0} {$i < $n} {incr i} { set tmp $A ; setcol tmp $i $right ; set detTmp [det $tmp] ; set v [expr $detTmp / $detA] ; puts [format "%0.4f" $v] ; }
using System; using System.Collections.Generic; using static System.Linq.Enumerable; public static class CramersRule { public static void Main() { var equations = new [] { new [] { 2, -1, 5, 1, -3 }, new [] { 3, 2, 2, -6, -32 }, new [] { 1, 3, 3, -1, -47 }, new [] { 5, -2, -3, 3, 49 } }; var solution = SolveCramer(equations); Console.WriteLine(solution.DelimitWith(", ")); } public static int[] SolveCramer(int[][] equations) { int size = equations.Length; if (equations.Any(eq => eq.Length != size + 1)) throw new ArgumentException($"Each equation must have {size+1} terms."); int[,] matrix = new int[size, size]; int[] column = new int[size]; for (int r = 0; r < size; r++) { column[r] = equations[r][size]; for (int c = 0; c < size; c++) { matrix[r, c] = equations[r][c]; } } return Solve(new SubMatrix(matrix, column)); } private static int[] Solve(SubMatrix matrix) { int det = matrix.Det(); if (det == 0) throw new ArgumentException("The determinant is zero."); int[] answer = new int[matrix.Size]; for (int i = 0; i < matrix.Size; i++) { matrix.ColumnIndex = i; answer[i] = matrix.Det() / det; } return answer; } static string DelimitWith<T>(this IEnumerable<T> source, string separator = " ") => string.Join(separator ?? " ", source ?? Empty<T>()); private class SubMatrix { private int[,] source; private SubMatrix prev; private int[] replaceColumn; public SubMatrix(int[,] source, int[] replaceColumn) { this.source = source; this.replaceColumn = replaceColumn; this.prev = null; this.ColumnIndex = -1; Size = replaceColumn.Length; } private SubMatrix(SubMatrix prev, int deletedColumnIndex = -1) { this.source = null; this.prev = prev; this.ColumnIndex = deletedColumnIndex; Size = prev.Size - 1; } public int ColumnIndex { get; set; } public int Size { get; } public int this[int row, int column] { get { if (source != null) return column == ColumnIndex ? replaceColumn[row] : source[row, column]; return prev[row + 1, column < ColumnIndex ? column : column + 1]; } } public int Det() { if (Size == 1) return this[0, 0]; if (Size == 2) return this[0, 0] * this[1, 1] - this[0, 1] * this[1, 0]; SubMatrix m = new SubMatrix(this); int det = 0; int sign = 1; for (int c = 0; c < Size; c++) { m.ColumnIndex = c; int d = m.Det(); det += this[0, c] * d * sign; sign = -sign; } return det; } public void Print() { for (int r = 0; r < Size; r++) { Console.WriteLine(Range(0, Size).Select(c => this[r, c]).DelimitWith(", ")); } Console.WriteLine(); } } }
Translate this program into C++ but keep the logic exactly as in Tcl.
package require math::linearalgebra namespace path ::math::linearalgebra set A [list { 2 -1 5 1} { 3 2 2 -6} { 1 3 3 -1} { 5 -2 -3 3}] set n [llength $A] set right {-3 -32 -47 49} set detA [det $A] for {set i 0} {$i < $n} {incr i} { set tmp $A ; setcol tmp $i $right ; set detTmp [det $tmp] ; set v [expr $detTmp / $detA] ; puts [format "%0.4f" $v] ; }
#include <algorithm> #include <iostream> #include <vector> class SubMatrix { const std::vector<std::vector<double>> *source; std::vector<double> replaceColumn; const SubMatrix *prev; size_t sz; int colIndex = -1; public: SubMatrix(const std::vector<std::vector<double>> &src, const std::vector<double> &rc) : source(&src), replaceColumn(rc), prev(nullptr), colIndex(-1) { sz = replaceColumn.size(); } SubMatrix(const SubMatrix &p) : source(nullptr), prev(&p), colIndex(-1) { sz = p.size() - 1; } SubMatrix(const SubMatrix &p, int deletedColumnIndex) : source(nullptr), prev(&p), colIndex(deletedColumnIndex) { sz = p.size() - 1; } int columnIndex() const { return colIndex; } void columnIndex(int index) { colIndex = index; } size_t size() const { return sz; } double index(int row, int col) const { if (source != nullptr) { if (col == colIndex) { return replaceColumn[row]; } else { return (*source)[row][col]; } } else { if (col < colIndex) { return prev->index(row + 1, col); } else { return prev->index(row + 1, col + 1); } } } double det() const { if (sz == 1) { return index(0, 0); } if (sz == 2) { return index(0, 0) * index(1, 1) - index(0, 1) * index(1, 0); } SubMatrix m(*this); double det = 0.0; int sign = 1; for (size_t c = 0; c < sz; ++c) { m.columnIndex(c); double d = m.det(); det += index(0, c) * d * sign; sign = -sign; } return det; } }; std::vector<double> solve(SubMatrix &matrix) { double det = matrix.det(); if (det == 0.0) { throw std::runtime_error("The determinant is zero."); } std::vector<double> answer(matrix.size()); for (int i = 0; i < matrix.size(); ++i) { matrix.columnIndex(i); answer[i] = matrix.det() / det; } return answer; } std::vector<double> solveCramer(const std::vector<std::vector<double>> &equations) { int size = equations.size(); if (std::any_of( equations.cbegin(), equations.cend(), [size](const std::vector<double> &a) { return a.size() != size + 1; } )) { throw std::runtime_error("Each equation must have the expected size."); } std::vector<std::vector<double>> matrix(size); std::vector<double> column(size); for (int r = 0; r < size; ++r) { column[r] = equations[r][size]; matrix[r].resize(size); for (int c = 0; c < size; ++c) { matrix[r][c] = equations[r][c]; } } SubMatrix sm(matrix, column); return solve(sm); } template<typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it++; } while (it != end) { os << ", " << *it++; } return os << ']'; } int main() { std::vector<std::vector<double>> equations = { { 2, -1, 5, 1, -3}, { 3, 2, 2, -6, -32}, { 1, 3, 3, -1, -47}, { 5, -2, -3, 3, 49}, }; auto solution = solveCramer(equations); std::cout << solution << '\n'; return 0; }
Transform the following Tcl implementation into Java, maintaining the same output and logic.
package require math::linearalgebra namespace path ::math::linearalgebra set A [list { 2 -1 5 1} { 3 2 2 -6} { 1 3 3 -1} { 5 -2 -3 3}] set n [llength $A] set right {-3 -32 -47 49} set detA [det $A] for {set i 0} {$i < $n} {incr i} { set tmp $A ; setcol tmp $i $right ; set detTmp [det $tmp] ; set v [expr $detTmp / $detA] ; puts [format "%0.4f" $v] ; }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CramersRule { public static void main(String[] args) { Matrix mat = new Matrix(Arrays.asList(2d, -1d, 5d, 1d), Arrays.asList(3d, 2d, 2d, -6d), Arrays.asList(1d, 3d, 3d, -1d), Arrays.asList(5d, -2d, -3d, 3d)); List<Double> b = Arrays.asList(-3d, -32d, -47d, 49d); System.out.println("Solution = " + cramersRule(mat, b)); } private static List<Double> cramersRule(Matrix matrix, List<Double> b) { double denominator = matrix.determinant(); List<Double> result = new ArrayList<>(); for ( int i = 0 ; i < b.size() ; i++ ) { result.add(matrix.replaceColumn(b, i).determinant() / denominator); } return result; } private static class Matrix { private List<List<Double>> matrix; @Override public String toString() { return matrix.toString(); } @SafeVarargs public Matrix(List<Double> ... lists) { matrix = new ArrayList<>(); for ( List<Double> list : lists) { matrix.add(list); } } public Matrix(List<List<Double>> mat) { matrix = mat; } public double determinant() { if ( matrix.size() == 1 ) { return get(0, 0); } if ( matrix.size() == 2 ) { return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0); } double sum = 0; double sign = 1; for ( int i = 0 ; i < matrix.size() ; i++ ) { sum += sign * get(0, i) * coFactor(0, i).determinant(); sign *= -1; } return sum; } private Matrix coFactor(int row, int col) { List<List<Double>> mat = new ArrayList<>(); for ( int i = 0 ; i < matrix.size() ; i++ ) { if ( i == row ) { continue; } List<Double> list = new ArrayList<>(); for ( int j = 0 ; j < matrix.size() ; j++ ) { if ( j == col ) { continue; } list.add(get(i, j)); } mat.add(list); } return new Matrix(mat); } private Matrix replaceColumn(List<Double> b, int column) { List<List<Double>> mat = new ArrayList<>(); for ( int row = 0 ; row < matrix.size() ; row++ ) { List<Double> list = new ArrayList<>(); for ( int col = 0 ; col < matrix.size() ; col++ ) { double value = get(row, col); if ( col == column ) { value = b.get(row); } list.add(value); } mat.add(list); } return new Matrix(mat); } private double get(int row, int col) { return matrix.get(row).get(col); } } }
Write the same code in Python as shown below in Tcl.
package require math::linearalgebra namespace path ::math::linearalgebra set A [list { 2 -1 5 1} { 3 2 2 -6} { 1 3 3 -1} { 5 -2 -3 3}] set n [llength $A] set right {-3 -32 -47 49} set detA [det $A] for {set i 0} {$i < $n} {incr i} { set tmp $A ; setcol tmp $i $right ; set detTmp [det $tmp] ; set v [expr $detTmp / $detA] ; puts [format "%0.4f" $v] ; }
def det(m,n): if n==1: return m[0][0] z=0 for r in range(n): k=m[:] del k[r] z+=m[r][0]*(-1)**r*det([p[1:]for p in k],n-1) return z w=len(t) d=det(h,w) if d==0:r=[] else:r=[det([r[0:i]+[s]+r[i+1:]for r,s in zip(h,t)],w)/d for i in range(w)] print(r)
Please provide an equivalent version of this Tcl code in VB.
package require math::linearalgebra namespace path ::math::linearalgebra set A [list { 2 -1 5 1} { 3 2 2 -6} { 1 3 3 -1} { 5 -2 -3 3}] set n [llength $A] set right {-3 -32 -47 49} set detA [det $A] for {set i 0} {$i < $n} {incr i} { set tmp $A ; setcol tmp $i $right ; set detTmp [det $tmp] ; set v [expr $detTmp / $detA] ; puts [format "%0.4f" $v] ; }
Imports System.Runtime.CompilerServices Imports System.Linq.Enumerable Module Module1 <Extension()> Function DelimitWith(Of T)(source As IEnumerable(Of T), Optional seperator As String = " ") As String Return String.Join(seperator, source) End Function Private Class SubMatrix Private ReadOnly source As Integer(,) Private ReadOnly prev As SubMatrix Private ReadOnly replaceColumn As Integer() Public Sub New(source As Integer(,), replaceColumn As Integer()) Me.source = source Me.replaceColumn = replaceColumn prev = Nothing ColumnIndex = -1 Size = replaceColumn.Length End Sub Public Sub New(prev As SubMatrix, Optional deletedColumnIndex As Integer = -1) source = Nothing replaceColumn = Nothing Me.prev = prev ColumnIndex = deletedColumnIndex Size = prev.Size - 1 End Sub Public Property ColumnIndex As Integer Public ReadOnly Property Size As Integer Default Public ReadOnly Property Index(row As Integer, column As Integer) As Integer Get If Not IsNothing(source) Then Return If(column = ColumnIndex, replaceColumn(row), source(row, column)) Else Return prev(row + 1, If(column < ColumnIndex, column, column + 1)) End If End Get End Property Public Function Det() As Integer If Size = 1 Then Return Me(0, 0) If Size = 2 Then Return Me(0, 0) * Me(1, 1) - Me(0, 1) * Me(1, 0) Dim m As New SubMatrix(Me) Dim detVal = 0 Dim sign = 1 For c = 0 To Size - 1 m.ColumnIndex = c Dim d = m.Det() detVal += Me(0, c) * d * sign sign = -sign Next Return detVal End Function Public Sub Print() For r = 0 To Size - 1 Dim rl = r Console.WriteLine(Range(0, Size).Select(Function(c) Me(rl, c)).DelimitWith(", ")) Next Console.WriteLine() End Sub End Class Private Function Solve(matrix As SubMatrix) As Integer() Dim det = matrix.Det() If det = 0 Then Throw New ArgumentException("The determinant is zero.") Dim answer(matrix.Size - 1) As Integer For i = 0 To matrix.Size - 1 matrix.ColumnIndex = i answer(i) = matrix.Det() / det Next Return answer End Function Public Function SolveCramer(equations As Integer()()) As Integer() Dim size = equations.Length If equations.Any(Function(eq) eq.Length <> size + 1) Then Throw New ArgumentException($"Each equation must have {size + 1} terms.") Dim matrix(size - 1, size - 1) As Integer Dim column(size - 1) As Integer For r = 0 To size - 1 column(r) = equations(r)(size) For c = 0 To size - 1 matrix(r, c) = equations(r)(c) Next Next Return Solve(New SubMatrix(matrix, column)) End Function Sub Main() Dim equations = { ({2, -1, 5, 1, -3}), ({3, 2, 2, -6, -32}), ({1, 3, 3, -1, -47}), ({5, -2, -3, 3, 49}) } Dim solution = SolveCramer(equations) Console.WriteLine(solution.DelimitWith(", ")) End Sub End Module
Rewrite this program in Go while keeping its functionality equivalent to the Tcl version.
package require math::linearalgebra namespace path ::math::linearalgebra set A [list { 2 -1 5 1} { 3 2 2 -6} { 1 3 3 -1} { 5 -2 -3 3}] set n [llength $A] set right {-3 -32 -47 49} set detA [det $A] for {set i 0} {$i < $n} {incr i} { set tmp $A ; setcol tmp $i $right ; set detTmp [det $tmp] ; set v [expr $detTmp / $detA] ; puts [format "%0.4f" $v] ; }
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) var m = mat.NewDense(4, 4, []float64{ 2, -1, 5, 1, 3, 2, 2, -6, 1, 3, 3, -1, 5, -2, -3, 3, }) var v = []float64{-3, -32, -47, 49} func main() { x := make([]float64, len(v)) b := make([]float64, len(v)) d := mat.Det(m) for c := range v { mat.Col(b, c, m) m.SetCol(c, v) x[c] = mat.Det(m) / d m.SetCol(c, b) } fmt.Println(x) }
Maintain the same structure and functionality when rewriting this code in Rust.
#include <algorithm> #include <iostream> #include <vector> class SubMatrix { const std::vector<std::vector<double>> *source; std::vector<double> replaceColumn; const SubMatrix *prev; size_t sz; int colIndex = -1; public: SubMatrix(const std::vector<std::vector<double>> &src, const std::vector<double> &rc) : source(&src), replaceColumn(rc), prev(nullptr), colIndex(-1) { sz = replaceColumn.size(); } SubMatrix(const SubMatrix &p) : source(nullptr), prev(&p), colIndex(-1) { sz = p.size() - 1; } SubMatrix(const SubMatrix &p, int deletedColumnIndex) : source(nullptr), prev(&p), colIndex(deletedColumnIndex) { sz = p.size() - 1; } int columnIndex() const { return colIndex; } void columnIndex(int index) { colIndex = index; } size_t size() const { return sz; } double index(int row, int col) const { if (source != nullptr) { if (col == colIndex) { return replaceColumn[row]; } else { return (*source)[row][col]; } } else { if (col < colIndex) { return prev->index(row + 1, col); } else { return prev->index(row + 1, col + 1); } } } double det() const { if (sz == 1) { return index(0, 0); } if (sz == 2) { return index(0, 0) * index(1, 1) - index(0, 1) * index(1, 0); } SubMatrix m(*this); double det = 0.0; int sign = 1; for (size_t c = 0; c < sz; ++c) { m.columnIndex(c); double d = m.det(); det += index(0, c) * d * sign; sign = -sign; } return det; } }; std::vector<double> solve(SubMatrix &matrix) { double det = matrix.det(); if (det == 0.0) { throw std::runtime_error("The determinant is zero."); } std::vector<double> answer(matrix.size()); for (int i = 0; i < matrix.size(); ++i) { matrix.columnIndex(i); answer[i] = matrix.det() / det; } return answer; } std::vector<double> solveCramer(const std::vector<std::vector<double>> &equations) { int size = equations.size(); if (std::any_of( equations.cbegin(), equations.cend(), [size](const std::vector<double> &a) { return a.size() != size + 1; } )) { throw std::runtime_error("Each equation must have the expected size."); } std::vector<std::vector<double>> matrix(size); std::vector<double> column(size); for (int r = 0; r < size; ++r) { column[r] = equations[r][size]; matrix[r].resize(size); for (int c = 0; c < size; ++c) { matrix[r][c] = equations[r][c]; } } SubMatrix sm(matrix, column); return solve(sm); } template<typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it++; } while (it != end) { os << ", " << *it++; } return os << ']'; } int main() { std::vector<std::vector<double>> equations = { { 2, -1, 5, 1, -3}, { 3, 2, 2, -6, -32}, { 1, 3, 3, -1, -47}, { 5, -2, -3, 3, 49}, }; auto solution = solveCramer(equations); std::cout << solution << '\n'; return 0; }
use std::ops::{Index, IndexMut}; fn main() { let m = matrix( vec![ 2., -1., 5., 1., 3., 2., 2., -6., 1., 3., 3., -1., 5., -2., -3., 3., ], 4, ); let mm = m.solve(&vec![-3., -32., -47., 49.]); println!("{:?}", mm); } #[derive(Clone)] struct Matrix { elts: Vec<f64>, dim: usize, } impl Matrix { fn det(&self) -> f64 { match self.dim { 0 => 0., 1 => self[0][0], 2 => self[0][0] * self[1][1] - self[0][1] * self[1][0], d => { let mut acc = 0.; let mut signature = 1.; for k in 0..d { acc += signature * self[0][k] * self.comatrix(0, k).det(); signature *= -1. } acc } } } fn solve(&self, target: &Vec<f64>) -> Vec<f64> { let mut solution: Vec<f64> = vec![0.; self.dim]; let denominator = self.det(); for j in 0..self.dim { let mut mm = self.clone(); for i in 0..self.dim { mm[i][j] = target[i] } solution[j] = mm.det() / denominator } solution } fn comatrix(&self, k: usize, l: usize) -> Matrix { let mut v: Vec<f64> = vec![]; for i in 0..self.dim { for j in 0..self.dim { if i != k && j != l { v.push(self[i][j]) } } } matrix(v, self.dim - 1) } } fn matrix(elts: Vec<f64>, dim: usize) -> Matrix { assert_eq!(elts.len(), dim * dim); Matrix { elts, dim } } impl Index<usize> for Matrix { type Output = [f64]; fn index(&self, i: usize) -> &Self::Output { let m = self.dim; &self.elts[m * i..m * (i + 1)] } } impl IndexMut<usize> for Matrix { fn index_mut(&mut self, i: usize) -> &mut Self::Output { let m = self.dim; &mut self.elts[m * i..m * (i + 1)] } }
Write a version of this Java function in Rust with identical behavior.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CramersRule { public static void main(String[] args) { Matrix mat = new Matrix(Arrays.asList(2d, -1d, 5d, 1d), Arrays.asList(3d, 2d, 2d, -6d), Arrays.asList(1d, 3d, 3d, -1d), Arrays.asList(5d, -2d, -3d, 3d)); List<Double> b = Arrays.asList(-3d, -32d, -47d, 49d); System.out.println("Solution = " + cramersRule(mat, b)); } private static List<Double> cramersRule(Matrix matrix, List<Double> b) { double denominator = matrix.determinant(); List<Double> result = new ArrayList<>(); for ( int i = 0 ; i < b.size() ; i++ ) { result.add(matrix.replaceColumn(b, i).determinant() / denominator); } return result; } private static class Matrix { private List<List<Double>> matrix; @Override public String toString() { return matrix.toString(); } @SafeVarargs public Matrix(List<Double> ... lists) { matrix = new ArrayList<>(); for ( List<Double> list : lists) { matrix.add(list); } } public Matrix(List<List<Double>> mat) { matrix = mat; } public double determinant() { if ( matrix.size() == 1 ) { return get(0, 0); } if ( matrix.size() == 2 ) { return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0); } double sum = 0; double sign = 1; for ( int i = 0 ; i < matrix.size() ; i++ ) { sum += sign * get(0, i) * coFactor(0, i).determinant(); sign *= -1; } return sum; } private Matrix coFactor(int row, int col) { List<List<Double>> mat = new ArrayList<>(); for ( int i = 0 ; i < matrix.size() ; i++ ) { if ( i == row ) { continue; } List<Double> list = new ArrayList<>(); for ( int j = 0 ; j < matrix.size() ; j++ ) { if ( j == col ) { continue; } list.add(get(i, j)); } mat.add(list); } return new Matrix(mat); } private Matrix replaceColumn(List<Double> b, int column) { List<List<Double>> mat = new ArrayList<>(); for ( int row = 0 ; row < matrix.size() ; row++ ) { List<Double> list = new ArrayList<>(); for ( int col = 0 ; col < matrix.size() ; col++ ) { double value = get(row, col); if ( col == column ) { value = b.get(row); } list.add(value); } mat.add(list); } return new Matrix(mat); } private double get(int row, int col) { return matrix.get(row).get(col); } } }
use std::ops::{Index, IndexMut}; fn main() { let m = matrix( vec![ 2., -1., 5., 1., 3., 2., 2., -6., 1., 3., 3., -1., 5., -2., -3., 3., ], 4, ); let mm = m.solve(&vec![-3., -32., -47., 49.]); println!("{:?}", mm); } #[derive(Clone)] struct Matrix { elts: Vec<f64>, dim: usize, } impl Matrix { fn det(&self) -> f64 { match self.dim { 0 => 0., 1 => self[0][0], 2 => self[0][0] * self[1][1] - self[0][1] * self[1][0], d => { let mut acc = 0.; let mut signature = 1.; for k in 0..d { acc += signature * self[0][k] * self.comatrix(0, k).det(); signature *= -1. } acc } } } fn solve(&self, target: &Vec<f64>) -> Vec<f64> { let mut solution: Vec<f64> = vec![0.; self.dim]; let denominator = self.det(); for j in 0..self.dim { let mut mm = self.clone(); for i in 0..self.dim { mm[i][j] = target[i] } solution[j] = mm.det() / denominator } solution } fn comatrix(&self, k: usize, l: usize) -> Matrix { let mut v: Vec<f64> = vec![]; for i in 0..self.dim { for j in 0..self.dim { if i != k && j != l { v.push(self[i][j]) } } } matrix(v, self.dim - 1) } } fn matrix(elts: Vec<f64>, dim: usize) -> Matrix { assert_eq!(elts.len(), dim * dim); Matrix { elts, dim } } impl Index<usize> for Matrix { type Output = [f64]; fn index(&self, i: usize) -> &Self::Output { let m = self.dim; &self.elts[m * i..m * (i + 1)] } } impl IndexMut<usize> for Matrix { fn index_mut(&mut self, i: usize) -> &mut Self::Output { let m = self.dim; &mut self.elts[m * i..m * (i + 1)] } }
Write a version of this Go function in Rust with identical behavior.
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) var m = mat.NewDense(4, 4, []float64{ 2, -1, 5, 1, 3, 2, 2, -6, 1, 3, 3, -1, 5, -2, -3, 3, }) var v = []float64{-3, -32, -47, 49} func main() { x := make([]float64, len(v)) b := make([]float64, len(v)) d := mat.Det(m) for c := range v { mat.Col(b, c, m) m.SetCol(c, v) x[c] = mat.Det(m) / d m.SetCol(c, b) } fmt.Println(x) }
use std::ops::{Index, IndexMut}; fn main() { let m = matrix( vec![ 2., -1., 5., 1., 3., 2., 2., -6., 1., 3., 3., -1., 5., -2., -3., 3., ], 4, ); let mm = m.solve(&vec![-3., -32., -47., 49.]); println!("{:?}", mm); } #[derive(Clone)] struct Matrix { elts: Vec<f64>, dim: usize, } impl Matrix { fn det(&self) -> f64 { match self.dim { 0 => 0., 1 => self[0][0], 2 => self[0][0] * self[1][1] - self[0][1] * self[1][0], d => { let mut acc = 0.; let mut signature = 1.; for k in 0..d { acc += signature * self[0][k] * self.comatrix(0, k).det(); signature *= -1. } acc } } } fn solve(&self, target: &Vec<f64>) -> Vec<f64> { let mut solution: Vec<f64> = vec![0.; self.dim]; let denominator = self.det(); for j in 0..self.dim { let mut mm = self.clone(); for i in 0..self.dim { mm[i][j] = target[i] } solution[j] = mm.det() / denominator } solution } fn comatrix(&self, k: usize, l: usize) -> Matrix { let mut v: Vec<f64> = vec![]; for i in 0..self.dim { for j in 0..self.dim { if i != k && j != l { v.push(self[i][j]) } } } matrix(v, self.dim - 1) } } fn matrix(elts: Vec<f64>, dim: usize) -> Matrix { assert_eq!(elts.len(), dim * dim); Matrix { elts, dim } } impl Index<usize> for Matrix { type Output = [f64]; fn index(&self, i: usize) -> &Self::Output { let m = self.dim; &self.elts[m * i..m * (i + 1)] } } impl IndexMut<usize> for Matrix { fn index_mut(&mut self, i: usize) -> &mut Self::Output { let m = self.dim; &mut self.elts[m * i..m * (i + 1)] } }
Port the following code from Rust to Python with equivalent syntax and logic.
use std::ops::{Index, IndexMut}; fn main() { let m = matrix( vec![ 2., -1., 5., 1., 3., 2., 2., -6., 1., 3., 3., -1., 5., -2., -3., 3., ], 4, ); let mm = m.solve(&vec![-3., -32., -47., 49.]); println!("{:?}", mm); } #[derive(Clone)] struct Matrix { elts: Vec<f64>, dim: usize, } impl Matrix { fn det(&self) -> f64 { match self.dim { 0 => 0., 1 => self[0][0], 2 => self[0][0] * self[1][1] - self[0][1] * self[1][0], d => { let mut acc = 0.; let mut signature = 1.; for k in 0..d { acc += signature * self[0][k] * self.comatrix(0, k).det(); signature *= -1. } acc } } } fn solve(&self, target: &Vec<f64>) -> Vec<f64> { let mut solution: Vec<f64> = vec![0.; self.dim]; let denominator = self.det(); for j in 0..self.dim { let mut mm = self.clone(); for i in 0..self.dim { mm[i][j] = target[i] } solution[j] = mm.det() / denominator } solution } fn comatrix(&self, k: usize, l: usize) -> Matrix { let mut v: Vec<f64> = vec![]; for i in 0..self.dim { for j in 0..self.dim { if i != k && j != l { v.push(self[i][j]) } } } matrix(v, self.dim - 1) } } fn matrix(elts: Vec<f64>, dim: usize) -> Matrix { assert_eq!(elts.len(), dim * dim); Matrix { elts, dim } } impl Index<usize> for Matrix { type Output = [f64]; fn index(&self, i: usize) -> &Self::Output { let m = self.dim; &self.elts[m * i..m * (i + 1)] } } impl IndexMut<usize> for Matrix { fn index_mut(&mut self, i: usize) -> &mut Self::Output { let m = self.dim; &mut self.elts[m * i..m * (i + 1)] } }
def det(m,n): if n==1: return m[0][0] z=0 for r in range(n): k=m[:] del k[r] z+=m[r][0]*(-1)**r*det([p[1:]for p in k],n-1) return z w=len(t) d=det(h,w) if d==0:r=[] else:r=[det([r[0:i]+[s]+r[i+1:]for r,s in zip(h,t)],w)/d for i in range(w)] print(r)
Port the provided Rust code into VB while preserving the original functionality.
use std::ops::{Index, IndexMut}; fn main() { let m = matrix( vec![ 2., -1., 5., 1., 3., 2., 2., -6., 1., 3., 3., -1., 5., -2., -3., 3., ], 4, ); let mm = m.solve(&vec![-3., -32., -47., 49.]); println!("{:?}", mm); } #[derive(Clone)] struct Matrix { elts: Vec<f64>, dim: usize, } impl Matrix { fn det(&self) -> f64 { match self.dim { 0 => 0., 1 => self[0][0], 2 => self[0][0] * self[1][1] - self[0][1] * self[1][0], d => { let mut acc = 0.; let mut signature = 1.; for k in 0..d { acc += signature * self[0][k] * self.comatrix(0, k).det(); signature *= -1. } acc } } } fn solve(&self, target: &Vec<f64>) -> Vec<f64> { let mut solution: Vec<f64> = vec![0.; self.dim]; let denominator = self.det(); for j in 0..self.dim { let mut mm = self.clone(); for i in 0..self.dim { mm[i][j] = target[i] } solution[j] = mm.det() / denominator } solution } fn comatrix(&self, k: usize, l: usize) -> Matrix { let mut v: Vec<f64> = vec![]; for i in 0..self.dim { for j in 0..self.dim { if i != k && j != l { v.push(self[i][j]) } } } matrix(v, self.dim - 1) } } fn matrix(elts: Vec<f64>, dim: usize) -> Matrix { assert_eq!(elts.len(), dim * dim); Matrix { elts, dim } } impl Index<usize> for Matrix { type Output = [f64]; fn index(&self, i: usize) -> &Self::Output { let m = self.dim; &self.elts[m * i..m * (i + 1)] } } impl IndexMut<usize> for Matrix { fn index_mut(&mut self, i: usize) -> &mut Self::Output { let m = self.dim; &mut self.elts[m * i..m * (i + 1)] } }
Imports System.Runtime.CompilerServices Imports System.Linq.Enumerable Module Module1 <Extension()> Function DelimitWith(Of T)(source As IEnumerable(Of T), Optional seperator As String = " ") As String Return String.Join(seperator, source) End Function Private Class SubMatrix Private ReadOnly source As Integer(,) Private ReadOnly prev As SubMatrix Private ReadOnly replaceColumn As Integer() Public Sub New(source As Integer(,), replaceColumn As Integer()) Me.source = source Me.replaceColumn = replaceColumn prev = Nothing ColumnIndex = -1 Size = replaceColumn.Length End Sub Public Sub New(prev As SubMatrix, Optional deletedColumnIndex As Integer = -1) source = Nothing replaceColumn = Nothing Me.prev = prev ColumnIndex = deletedColumnIndex Size = prev.Size - 1 End Sub Public Property ColumnIndex As Integer Public ReadOnly Property Size As Integer Default Public ReadOnly Property Index(row As Integer, column As Integer) As Integer Get If Not IsNothing(source) Then Return If(column = ColumnIndex, replaceColumn(row), source(row, column)) Else Return prev(row + 1, If(column < ColumnIndex, column, column + 1)) End If End Get End Property Public Function Det() As Integer If Size = 1 Then Return Me(0, 0) If Size = 2 Then Return Me(0, 0) * Me(1, 1) - Me(0, 1) * Me(1, 0) Dim m As New SubMatrix(Me) Dim detVal = 0 Dim sign = 1 For c = 0 To Size - 1 m.ColumnIndex = c Dim d = m.Det() detVal += Me(0, c) * d * sign sign = -sign Next Return detVal End Function Public Sub Print() For r = 0 To Size - 1 Dim rl = r Console.WriteLine(Range(0, Size).Select(Function(c) Me(rl, c)).DelimitWith(", ")) Next Console.WriteLine() End Sub End Class Private Function Solve(matrix As SubMatrix) As Integer() Dim det = matrix.Det() If det = 0 Then Throw New ArgumentException("The determinant is zero.") Dim answer(matrix.Size - 1) As Integer For i = 0 To matrix.Size - 1 matrix.ColumnIndex = i answer(i) = matrix.Det() / det Next Return answer End Function Public Function SolveCramer(equations As Integer()()) As Integer() Dim size = equations.Length If equations.Any(Function(eq) eq.Length <> size + 1) Then Throw New ArgumentException($"Each equation must have {size + 1} terms.") Dim matrix(size - 1, size - 1) As Integer Dim column(size - 1) As Integer For r = 0 To size - 1 column(r) = equations(r)(size) For c = 0 To size - 1 matrix(r, c) = equations(r)(c) Next Next Return Solve(New SubMatrix(matrix, column)) End Function Sub Main() Dim equations = { ({2, -1, 5, 1, -3}), ({3, 2, 2, -6, -32}), ({1, 3, 3, -1, -47}), ({5, -2, -3, 3, 49}) } Dim solution = SolveCramer(equations) Console.WriteLine(solution.DelimitWith(", ")) End Sub End Module
Write a version of this C# function in Rust with identical behavior.
using System; using System.Collections.Generic; using static System.Linq.Enumerable; public static class CramersRule { public static void Main() { var equations = new [] { new [] { 2, -1, 5, 1, -3 }, new [] { 3, 2, 2, -6, -32 }, new [] { 1, 3, 3, -1, -47 }, new [] { 5, -2, -3, 3, 49 } }; var solution = SolveCramer(equations); Console.WriteLine(solution.DelimitWith(", ")); } public static int[] SolveCramer(int[][] equations) { int size = equations.Length; if (equations.Any(eq => eq.Length != size + 1)) throw new ArgumentException($"Each equation must have {size+1} terms."); int[,] matrix = new int[size, size]; int[] column = new int[size]; for (int r = 0; r < size; r++) { column[r] = equations[r][size]; for (int c = 0; c < size; c++) { matrix[r, c] = equations[r][c]; } } return Solve(new SubMatrix(matrix, column)); } private static int[] Solve(SubMatrix matrix) { int det = matrix.Det(); if (det == 0) throw new ArgumentException("The determinant is zero."); int[] answer = new int[matrix.Size]; for (int i = 0; i < matrix.Size; i++) { matrix.ColumnIndex = i; answer[i] = matrix.Det() / det; } return answer; } static string DelimitWith<T>(this IEnumerable<T> source, string separator = " ") => string.Join(separator ?? " ", source ?? Empty<T>()); private class SubMatrix { private int[,] source; private SubMatrix prev; private int[] replaceColumn; public SubMatrix(int[,] source, int[] replaceColumn) { this.source = source; this.replaceColumn = replaceColumn; this.prev = null; this.ColumnIndex = -1; Size = replaceColumn.Length; } private SubMatrix(SubMatrix prev, int deletedColumnIndex = -1) { this.source = null; this.prev = prev; this.ColumnIndex = deletedColumnIndex; Size = prev.Size - 1; } public int ColumnIndex { get; set; } public int Size { get; } public int this[int row, int column] { get { if (source != null) return column == ColumnIndex ? replaceColumn[row] : source[row, column]; return prev[row + 1, column < ColumnIndex ? column : column + 1]; } } public int Det() { if (Size == 1) return this[0, 0]; if (Size == 2) return this[0, 0] * this[1, 1] - this[0, 1] * this[1, 0]; SubMatrix m = new SubMatrix(this); int det = 0; int sign = 1; for (int c = 0; c < Size; c++) { m.ColumnIndex = c; int d = m.Det(); det += this[0, c] * d * sign; sign = -sign; } return det; } public void Print() { for (int r = 0; r < Size; r++) { Console.WriteLine(Range(0, Size).Select(c => this[r, c]).DelimitWith(", ")); } Console.WriteLine(); } } }
use std::ops::{Index, IndexMut}; fn main() { let m = matrix( vec![ 2., -1., 5., 1., 3., 2., 2., -6., 1., 3., 3., -1., 5., -2., -3., 3., ], 4, ); let mm = m.solve(&vec![-3., -32., -47., 49.]); println!("{:?}", mm); } #[derive(Clone)] struct Matrix { elts: Vec<f64>, dim: usize, } impl Matrix { fn det(&self) -> f64 { match self.dim { 0 => 0., 1 => self[0][0], 2 => self[0][0] * self[1][1] - self[0][1] * self[1][0], d => { let mut acc = 0.; let mut signature = 1.; for k in 0..d { acc += signature * self[0][k] * self.comatrix(0, k).det(); signature *= -1. } acc } } } fn solve(&self, target: &Vec<f64>) -> Vec<f64> { let mut solution: Vec<f64> = vec![0.; self.dim]; let denominator = self.det(); for j in 0..self.dim { let mut mm = self.clone(); for i in 0..self.dim { mm[i][j] = target[i] } solution[j] = mm.det() / denominator } solution } fn comatrix(&self, k: usize, l: usize) -> Matrix { let mut v: Vec<f64> = vec![]; for i in 0..self.dim { for j in 0..self.dim { if i != k && j != l { v.push(self[i][j]) } } } matrix(v, self.dim - 1) } } fn matrix(elts: Vec<f64>, dim: usize) -> Matrix { assert_eq!(elts.len(), dim * dim); Matrix { elts, dim } } impl Index<usize> for Matrix { type Output = [f64]; fn index(&self, i: usize) -> &Self::Output { let m = self.dim; &self.elts[m * i..m * (i + 1)] } } impl IndexMut<usize> for Matrix { fn index_mut(&mut self, i: usize) -> &mut Self::Output { let m = self.dim; &mut self.elts[m * i..m * (i + 1)] } }
Change the programming language of this snippet from C to Rust without modifying what it does.
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct { int n; double **elems; } SquareMatrix; SquareMatrix init_square_matrix(int n, double elems[n][n]) { SquareMatrix A = { .n = n, .elems = malloc(n * sizeof(double *)) }; for(int i = 0; i < n; ++i) { A.elems[i] = malloc(n * sizeof(double)); for(int j = 0; j < n; ++j) A.elems[i][j] = elems[i][j]; } return A; } SquareMatrix copy_square_matrix(SquareMatrix src) { SquareMatrix dest; dest.n = src.n; dest.elems = malloc(dest.n * sizeof(double *)); for(int i = 0; i < dest.n; ++i) { dest.elems[i] = malloc(dest.n * sizeof(double)); for(int j = 0; j < dest.n; ++j) dest.elems[i][j] = src.elems[i][j]; } return dest; } double det(SquareMatrix A) { double det = 1; for(int j = 0; j < A.n; ++j) { int i_max = j; for(int i = j; i < A.n; ++i) if(A.elems[i][j] > A.elems[i_max][j]) i_max = i; if(i_max != j) { for(int k = 0; k < A.n; ++k) { double tmp = A.elems[i_max][k]; A.elems[i_max][k] = A.elems[j][k]; A.elems[j][k] = tmp; } det *= -1; } if(abs(A.elems[j][j]) < 1e-12) { puts("Singular matrix!"); return NAN; } for(int i = j + 1; i < A.n; ++i) { double mult = -A.elems[i][j] / A.elems[j][j]; for(int k = 0; k < A.n; ++k) A.elems[i][k] += mult * A.elems[j][k]; } } for(int i = 0; i < A.n; ++i) det *= A.elems[i][i]; return det; } void deinit_square_matrix(SquareMatrix A) { for(int i = 0; i < A.n; ++i) free(A.elems[i]); free(A.elems); } double cramer_solve(SquareMatrix A, double det_A, double *b, int var) { SquareMatrix tmp = copy_square_matrix(A); for(int i = 0; i < tmp.n; ++i) tmp.elems[i][var] = b[i]; double det_tmp = det(tmp); deinit_square_matrix(tmp); return det_tmp / det_A; } int main(int argc, char **argv) { #define N 4 double elems[N][N] = { { 2, -1, 5, 1}, { 3, 2, 2, -6}, { 1, 3, 3, -1}, { 5, -2, -3, 3} }; SquareMatrix A = init_square_matrix(N, elems); SquareMatrix tmp = copy_square_matrix(A); int det_A = det(tmp); deinit_square_matrix(tmp); double b[] = {-3, -32, -47, 49}; for(int i = 0; i < N; ++i) printf("%7.3lf\n", cramer_solve(A, det_A, b, i)); deinit_square_matrix(A); return EXIT_SUCCESS; }
use std::ops::{Index, IndexMut}; fn main() { let m = matrix( vec![ 2., -1., 5., 1., 3., 2., 2., -6., 1., 3., 3., -1., 5., -2., -3., 3., ], 4, ); let mm = m.solve(&vec![-3., -32., -47., 49.]); println!("{:?}", mm); } #[derive(Clone)] struct Matrix { elts: Vec<f64>, dim: usize, } impl Matrix { fn det(&self) -> f64 { match self.dim { 0 => 0., 1 => self[0][0], 2 => self[0][0] * self[1][1] - self[0][1] * self[1][0], d => { let mut acc = 0.; let mut signature = 1.; for k in 0..d { acc += signature * self[0][k] * self.comatrix(0, k).det(); signature *= -1. } acc } } } fn solve(&self, target: &Vec<f64>) -> Vec<f64> { let mut solution: Vec<f64> = vec![0.; self.dim]; let denominator = self.det(); for j in 0..self.dim { let mut mm = self.clone(); for i in 0..self.dim { mm[i][j] = target[i] } solution[j] = mm.det() / denominator } solution } fn comatrix(&self, k: usize, l: usize) -> Matrix { let mut v: Vec<f64> = vec![]; for i in 0..self.dim { for j in 0..self.dim { if i != k && j != l { v.push(self[i][j]) } } } matrix(v, self.dim - 1) } } fn matrix(elts: Vec<f64>, dim: usize) -> Matrix { assert_eq!(elts.len(), dim * dim); Matrix { elts, dim } } impl Index<usize> for Matrix { type Output = [f64]; fn index(&self, i: usize) -> &Self::Output { let m = self.dim; &self.elts[m * i..m * (i + 1)] } } impl IndexMut<usize> for Matrix { fn index_mut(&mut self, i: usize) -> &mut Self::Output { let m = self.dim; &mut self.elts[m * i..m * (i + 1)] } }
Convert this Ada block to C#, preserving its control flow and logic.
with Ada.Long_Complex_Text_IO; use Ada.Long_Complex_Text_IO; with Ada.Numerics; use Ada.Numerics; with Ada.Numerics.Long_Complex_Types; use Ada.Numerics.Long_Complex_Types; with Ada.Numerics.Long_Complex_Elementary_Functions; use Ada.Numerics.Long_Complex_Elementary_Functions; procedure Eulers_Identity is begin Put (Exp (Pi * i) + 1.0); end Eulers_Identity;
using System; using System.Numerics; public class Program { static void Main() { Complex e = Math.E; Complex i = Complex.ImaginaryOne; Complex π = Math.PI; Console.WriteLine(Complex.Pow(e, i * π) + 1); } }
Generate a C# translation of this Ada snippet without changing its computational steps.
with Ada.Long_Complex_Text_IO; use Ada.Long_Complex_Text_IO; with Ada.Numerics; use Ada.Numerics; with Ada.Numerics.Long_Complex_Types; use Ada.Numerics.Long_Complex_Types; with Ada.Numerics.Long_Complex_Elementary_Functions; use Ada.Numerics.Long_Complex_Elementary_Functions; procedure Eulers_Identity is begin Put (Exp (Pi * i) + 1.0); end Eulers_Identity;
using System; using System.Numerics; public class Program { static void Main() { Complex e = Math.E; Complex i = Complex.ImaginaryOne; Complex π = Math.PI; Console.WriteLine(Complex.Pow(e, i * π) + 1); } }
Change the following Ada code into C without altering its purpose.
with Ada.Long_Complex_Text_IO; use Ada.Long_Complex_Text_IO; with Ada.Numerics; use Ada.Numerics; with Ada.Numerics.Long_Complex_Types; use Ada.Numerics.Long_Complex_Types; with Ada.Numerics.Long_Complex_Elementary_Functions; use Ada.Numerics.Long_Complex_Elementary_Functions; procedure Eulers_Identity is begin Put (Exp (Pi * i) + 1.0); end Eulers_Identity;
#include <stdio.h> #include <math.h> #include <complex.h> #include <wchar.h> #include <locale.h> int main() { wchar_t pi = L'\u03c0'; wchar_t ae = L'\u2245'; double complex e = cexp(M_PI * I) + 1.0; setlocale(LC_CTYPE, ""); printf("e ^ %lci + 1 = [%.16f, %.16f] %lc 0\n", pi, creal(e), cimag(e), ae); return 0; }
Rewrite the snippet below in C so it works the same as the original Ada code.
with Ada.Long_Complex_Text_IO; use Ada.Long_Complex_Text_IO; with Ada.Numerics; use Ada.Numerics; with Ada.Numerics.Long_Complex_Types; use Ada.Numerics.Long_Complex_Types; with Ada.Numerics.Long_Complex_Elementary_Functions; use Ada.Numerics.Long_Complex_Elementary_Functions; procedure Eulers_Identity is begin Put (Exp (Pi * i) + 1.0); end Eulers_Identity;
#include <stdio.h> #include <math.h> #include <complex.h> #include <wchar.h> #include <locale.h> int main() { wchar_t pi = L'\u03c0'; wchar_t ae = L'\u2245'; double complex e = cexp(M_PI * I) + 1.0; setlocale(LC_CTYPE, ""); printf("e ^ %lci + 1 = [%.16f, %.16f] %lc 0\n", pi, creal(e), cimag(e), ae); return 0; }
Change the programming language of this snippet from Ada to C++ without modifying what it does.
with Ada.Long_Complex_Text_IO; use Ada.Long_Complex_Text_IO; with Ada.Numerics; use Ada.Numerics; with Ada.Numerics.Long_Complex_Types; use Ada.Numerics.Long_Complex_Types; with Ada.Numerics.Long_Complex_Elementary_Functions; use Ada.Numerics.Long_Complex_Elementary_Functions; procedure Eulers_Identity is begin Put (Exp (Pi * i) + 1.0); end Eulers_Identity;
#include <iostream> #include <complex> int main() { std::cout << std::exp(std::complex<double>(0.0, M_PI)) + 1.0 << std::endl; return 0; }
Convert this Ada block to C++, preserving its control flow and logic.
with Ada.Long_Complex_Text_IO; use Ada.Long_Complex_Text_IO; with Ada.Numerics; use Ada.Numerics; with Ada.Numerics.Long_Complex_Types; use Ada.Numerics.Long_Complex_Types; with Ada.Numerics.Long_Complex_Elementary_Functions; use Ada.Numerics.Long_Complex_Elementary_Functions; procedure Eulers_Identity is begin Put (Exp (Pi * i) + 1.0); end Eulers_Identity;
#include <iostream> #include <complex> int main() { std::cout << std::exp(std::complex<double>(0.0, M_PI)) + 1.0 << std::endl; return 0; }
Can you help me rewrite this code in Go instead of Ada, keeping it the same logically?
with Ada.Long_Complex_Text_IO; use Ada.Long_Complex_Text_IO; with Ada.Numerics; use Ada.Numerics; with Ada.Numerics.Long_Complex_Types; use Ada.Numerics.Long_Complex_Types; with Ada.Numerics.Long_Complex_Elementary_Functions; use Ada.Numerics.Long_Complex_Elementary_Functions; procedure Eulers_Identity is begin Put (Exp (Pi * i) + 1.0); end Eulers_Identity;
package main import ( "fmt" "math" "math/cmplx" ) func main() { fmt.Println(cmplx.Exp(math.Pi * 1i) + 1.0) }
Convert the following code from Ada to Go, ensuring the logic remains intact.
with Ada.Long_Complex_Text_IO; use Ada.Long_Complex_Text_IO; with Ada.Numerics; use Ada.Numerics; with Ada.Numerics.Long_Complex_Types; use Ada.Numerics.Long_Complex_Types; with Ada.Numerics.Long_Complex_Elementary_Functions; use Ada.Numerics.Long_Complex_Elementary_Functions; procedure Eulers_Identity is begin Put (Exp (Pi * i) + 1.0); end Eulers_Identity;
package main import ( "fmt" "math" "math/cmplx" ) func main() { fmt.Println(cmplx.Exp(math.Pi * 1i) + 1.0) }
Produce a language-to-language conversion: from Ada to Java, same semantics.
with Ada.Long_Complex_Text_IO; use Ada.Long_Complex_Text_IO; with Ada.Numerics; use Ada.Numerics; with Ada.Numerics.Long_Complex_Types; use Ada.Numerics.Long_Complex_Types; with Ada.Numerics.Long_Complex_Elementary_Functions; use Ada.Numerics.Long_Complex_Elementary_Functions; procedure Eulers_Identity is begin Put (Exp (Pi * i) + 1.0); end Eulers_Identity;
public class EulerIdentity { public static void main(String[] args) { System.out.println("e ^ (i*Pi) + 1 = " + (new Complex(0, Math.PI).exp()).add(new Complex(1, 0))); } public static class Complex { private double x, y; public Complex(double re, double im) { x = re; y = im; } public Complex exp() { double exp = Math.exp(x); return new Complex(exp * Math.cos(y), exp * Math.sin(y)); } public Complex add(Complex a) { return new Complex(x + a.x, y + a.y); } @Override public String toString() { return x + " + " + y + "i"; } } }
Maintain the same structure and functionality when rewriting this code in Java.
with Ada.Long_Complex_Text_IO; use Ada.Long_Complex_Text_IO; with Ada.Numerics; use Ada.Numerics; with Ada.Numerics.Long_Complex_Types; use Ada.Numerics.Long_Complex_Types; with Ada.Numerics.Long_Complex_Elementary_Functions; use Ada.Numerics.Long_Complex_Elementary_Functions; procedure Eulers_Identity is begin Put (Exp (Pi * i) + 1.0); end Eulers_Identity;
public class EulerIdentity { public static void main(String[] args) { System.out.println("e ^ (i*Pi) + 1 = " + (new Complex(0, Math.PI).exp()).add(new Complex(1, 0))); } public static class Complex { private double x, y; public Complex(double re, double im) { x = re; y = im; } public Complex exp() { double exp = Math.exp(x); return new Complex(exp * Math.cos(y), exp * Math.sin(y)); } public Complex add(Complex a) { return new Complex(x + a.x, y + a.y); } @Override public String toString() { return x + " + " + y + "i"; } } }
Write the same code in Python as shown below in Ada.
with Ada.Long_Complex_Text_IO; use Ada.Long_Complex_Text_IO; with Ada.Numerics; use Ada.Numerics; with Ada.Numerics.Long_Complex_Types; use Ada.Numerics.Long_Complex_Types; with Ada.Numerics.Long_Complex_Elementary_Functions; use Ada.Numerics.Long_Complex_Elementary_Functions; procedure Eulers_Identity is begin Put (Exp (Pi * i) + 1.0); end Eulers_Identity;
>>> import math >>> math.e ** (math.pi * 1j) + 1 1.2246467991473532e-16j
Ensure the translated Python code behaves exactly like the original Ada snippet.
with Ada.Long_Complex_Text_IO; use Ada.Long_Complex_Text_IO; with Ada.Numerics; use Ada.Numerics; with Ada.Numerics.Long_Complex_Types; use Ada.Numerics.Long_Complex_Types; with Ada.Numerics.Long_Complex_Elementary_Functions; use Ada.Numerics.Long_Complex_Elementary_Functions; procedure Eulers_Identity is begin Put (Exp (Pi * i) + 1.0); end Eulers_Identity;
>>> import math >>> math.e ** (math.pi * 1j) + 1 1.2246467991473532e-16j
Convert the following code from Delphi to C, ensuring the logic remains intact.
program Euler_identity; uses System.VarCmplx; begin var result := VarComplexExp(Pi * VarComplexCreate(0, 1)) + 1; writeln(result); readln; end.
#include <stdio.h> #include <math.h> #include <complex.h> #include <wchar.h> #include <locale.h> int main() { wchar_t pi = L'\u03c0'; wchar_t ae = L'\u2245'; double complex e = cexp(M_PI * I) + 1.0; setlocale(LC_CTYPE, ""); printf("e ^ %lci + 1 = [%.16f, %.16f] %lc 0\n", pi, creal(e), cimag(e), ae); return 0; }
Generate an equivalent C version of this Delphi code.
program Euler_identity; uses System.VarCmplx; begin var result := VarComplexExp(Pi * VarComplexCreate(0, 1)) + 1; writeln(result); readln; end.
#include <stdio.h> #include <math.h> #include <complex.h> #include <wchar.h> #include <locale.h> int main() { wchar_t pi = L'\u03c0'; wchar_t ae = L'\u2245'; double complex e = cexp(M_PI * I) + 1.0; setlocale(LC_CTYPE, ""); printf("e ^ %lci + 1 = [%.16f, %.16f] %lc 0\n", pi, creal(e), cimag(e), ae); return 0; }
Please provide an equivalent version of this Delphi code in C#.
program Euler_identity; uses System.VarCmplx; begin var result := VarComplexExp(Pi * VarComplexCreate(0, 1)) + 1; writeln(result); readln; end.
using System; using System.Numerics; public class Program { static void Main() { Complex e = Math.E; Complex i = Complex.ImaginaryOne; Complex π = Math.PI; Console.WriteLine(Complex.Pow(e, i * π) + 1); } }
Please provide an equivalent version of this Delphi code in C#.
program Euler_identity; uses System.VarCmplx; begin var result := VarComplexExp(Pi * VarComplexCreate(0, 1)) + 1; writeln(result); readln; end.
using System; using System.Numerics; public class Program { static void Main() { Complex e = Math.E; Complex i = Complex.ImaginaryOne; Complex π = Math.PI; Console.WriteLine(Complex.Pow(e, i * π) + 1); } }
Rewrite this program in C++ while keeping its functionality equivalent to the Delphi version.
program Euler_identity; uses System.VarCmplx; begin var result := VarComplexExp(Pi * VarComplexCreate(0, 1)) + 1; writeln(result); readln; end.
#include <iostream> #include <complex> int main() { std::cout << std::exp(std::complex<double>(0.0, M_PI)) + 1.0 << std::endl; return 0; }
Produce a functionally identical C++ code for the snippet given in Delphi.
program Euler_identity; uses System.VarCmplx; begin var result := VarComplexExp(Pi * VarComplexCreate(0, 1)) + 1; writeln(result); readln; end.
#include <iostream> #include <complex> int main() { std::cout << std::exp(std::complex<double>(0.0, M_PI)) + 1.0 << std::endl; return 0; }
Produce a functionally identical Java code for the snippet given in Delphi.
program Euler_identity; uses System.VarCmplx; begin var result := VarComplexExp(Pi * VarComplexCreate(0, 1)) + 1; writeln(result); readln; end.
public class EulerIdentity { public static void main(String[] args) { System.out.println("e ^ (i*Pi) + 1 = " + (new Complex(0, Math.PI).exp()).add(new Complex(1, 0))); } public static class Complex { private double x, y; public Complex(double re, double im) { x = re; y = im; } public Complex exp() { double exp = Math.exp(x); return new Complex(exp * Math.cos(y), exp * Math.sin(y)); } public Complex add(Complex a) { return new Complex(x + a.x, y + a.y); } @Override public String toString() { return x + " + " + y + "i"; } } }
Ensure the translated Java code behaves exactly like the original Delphi snippet.
program Euler_identity; uses System.VarCmplx; begin var result := VarComplexExp(Pi * VarComplexCreate(0, 1)) + 1; writeln(result); readln; end.
public class EulerIdentity { public static void main(String[] args) { System.out.println("e ^ (i*Pi) + 1 = " + (new Complex(0, Math.PI).exp()).add(new Complex(1, 0))); } public static class Complex { private double x, y; public Complex(double re, double im) { x = re; y = im; } public Complex exp() { double exp = Math.exp(x); return new Complex(exp * Math.cos(y), exp * Math.sin(y)); } public Complex add(Complex a) { return new Complex(x + a.x, y + a.y); } @Override public String toString() { return x + " + " + y + "i"; } } }
Maintain the same structure and functionality when rewriting this code in Python.
program Euler_identity; uses System.VarCmplx; begin var result := VarComplexExp(Pi * VarComplexCreate(0, 1)) + 1; writeln(result); readln; end.
>>> import math >>> math.e ** (math.pi * 1j) + 1 1.2246467991473532e-16j
Convert the following code from Delphi to Python, ensuring the logic remains intact.
program Euler_identity; uses System.VarCmplx; begin var result := VarComplexExp(Pi * VarComplexCreate(0, 1)) + 1; writeln(result); readln; end.
>>> import math >>> math.e ** (math.pi * 1j) + 1 1.2246467991473532e-16j
Produce a language-to-language conversion: from Delphi to Go, same semantics.
program Euler_identity; uses System.VarCmplx; begin var result := VarComplexExp(Pi * VarComplexCreate(0, 1)) + 1; writeln(result); readln; end.
package main import ( "fmt" "math" "math/cmplx" ) func main() { fmt.Println(cmplx.Exp(math.Pi * 1i) + 1.0) }
Port the following code from Delphi to Go with equivalent syntax and logic.
program Euler_identity; uses System.VarCmplx; begin var result := VarComplexExp(Pi * VarComplexCreate(0, 1)) + 1; writeln(result); readln; end.
package main import ( "fmt" "math" "math/cmplx" ) func main() { fmt.Println(cmplx.Exp(math.Pi * 1i) + 1.0) }
Convert this F# block to C, preserving its control flow and logic.
printfn "-1 + 1 = %d" (-1+1)
#include <stdio.h> #include <math.h> #include <complex.h> #include <wchar.h> #include <locale.h> int main() { wchar_t pi = L'\u03c0'; wchar_t ae = L'\u2245'; double complex e = cexp(M_PI * I) + 1.0; setlocale(LC_CTYPE, ""); printf("e ^ %lci + 1 = [%.16f, %.16f] %lc 0\n", pi, creal(e), cimag(e), ae); return 0; }
Convert the following code from F# to C, ensuring the logic remains intact.
printfn "-1 + 1 = %d" (-1+1)
#include <stdio.h> #include <math.h> #include <complex.h> #include <wchar.h> #include <locale.h> int main() { wchar_t pi = L'\u03c0'; wchar_t ae = L'\u2245'; double complex e = cexp(M_PI * I) + 1.0; setlocale(LC_CTYPE, ""); printf("e ^ %lci + 1 = [%.16f, %.16f] %lc 0\n", pi, creal(e), cimag(e), ae); return 0; }
Rewrite the snippet below in C# so it works the same as the original F# code.
printfn "-1 + 1 = %d" (-1+1)
using System; using System.Numerics; public class Program { static void Main() { Complex e = Math.E; Complex i = Complex.ImaginaryOne; Complex π = Math.PI; Console.WriteLine(Complex.Pow(e, i * π) + 1); } }
Translate this program into C# but keep the logic exactly as in F#.
printfn "-1 + 1 = %d" (-1+1)
using System; using System.Numerics; public class Program { static void Main() { Complex e = Math.E; Complex i = Complex.ImaginaryOne; Complex π = Math.PI; Console.WriteLine(Complex.Pow(e, i * π) + 1); } }
Translate this program into C++ but keep the logic exactly as in F#.
printfn "-1 + 1 = %d" (-1+1)
#include <iostream> #include <complex> int main() { std::cout << std::exp(std::complex<double>(0.0, M_PI)) + 1.0 << std::endl; return 0; }
Convert this F# block to C++, preserving its control flow and logic.
printfn "-1 + 1 = %d" (-1+1)
#include <iostream> #include <complex> int main() { std::cout << std::exp(std::complex<double>(0.0, M_PI)) + 1.0 << std::endl; return 0; }
Produce a functionally identical Java code for the snippet given in F#.
printfn "-1 + 1 = %d" (-1+1)
public class EulerIdentity { public static void main(String[] args) { System.out.println("e ^ (i*Pi) + 1 = " + (new Complex(0, Math.PI).exp()).add(new Complex(1, 0))); } public static class Complex { private double x, y; public Complex(double re, double im) { x = re; y = im; } public Complex exp() { double exp = Math.exp(x); return new Complex(exp * Math.cos(y), exp * Math.sin(y)); } public Complex add(Complex a) { return new Complex(x + a.x, y + a.y); } @Override public String toString() { return x + " + " + y + "i"; } } }
Ensure the translated Java code behaves exactly like the original F# snippet.
printfn "-1 + 1 = %d" (-1+1)
public class EulerIdentity { public static void main(String[] args) { System.out.println("e ^ (i*Pi) + 1 = " + (new Complex(0, Math.PI).exp()).add(new Complex(1, 0))); } public static class Complex { private double x, y; public Complex(double re, double im) { x = re; y = im; } public Complex exp() { double exp = Math.exp(x); return new Complex(exp * Math.cos(y), exp * Math.sin(y)); } public Complex add(Complex a) { return new Complex(x + a.x, y + a.y); } @Override public String toString() { return x + " + " + y + "i"; } } }
Rewrite this program in Python while keeping its functionality equivalent to the F# version.
printfn "-1 + 1 = %d" (-1+1)
>>> import math >>> math.e ** (math.pi * 1j) + 1 1.2246467991473532e-16j
Please provide an equivalent version of this F# code in Python.
printfn "-1 + 1 = %d" (-1+1)
>>> import math >>> math.e ** (math.pi * 1j) + 1 1.2246467991473532e-16j
Port the provided F# code into Go while preserving the original functionality.
printfn "-1 + 1 = %d" (-1+1)
package main import ( "fmt" "math" "math/cmplx" ) func main() { fmt.Println(cmplx.Exp(math.Pi * 1i) + 1.0) }
Write the same algorithm in Go as shown in this F# implementation.
printfn "-1 + 1 = %d" (-1+1)
package main import ( "fmt" "math" "math/cmplx" ) func main() { fmt.Println(cmplx.Exp(math.Pi * 1i) + 1.0) }
Port the following code from Factor to C with equivalent syntax and logic.
USING: math math.constants math.functions prettyprint ; 1 e pi C{ 0 1 } * ^ + .
#include <stdio.h> #include <math.h> #include <complex.h> #include <wchar.h> #include <locale.h> int main() { wchar_t pi = L'\u03c0'; wchar_t ae = L'\u2245'; double complex e = cexp(M_PI * I) + 1.0; setlocale(LC_CTYPE, ""); printf("e ^ %lci + 1 = [%.16f, %.16f] %lc 0\n", pi, creal(e), cimag(e), ae); return 0; }
Port the following code from Factor to C with equivalent syntax and logic.
USING: math math.constants math.functions prettyprint ; 1 e pi C{ 0 1 } * ^ + .
#include <stdio.h> #include <math.h> #include <complex.h> #include <wchar.h> #include <locale.h> int main() { wchar_t pi = L'\u03c0'; wchar_t ae = L'\u2245'; double complex e = cexp(M_PI * I) + 1.0; setlocale(LC_CTYPE, ""); printf("e ^ %lci + 1 = [%.16f, %.16f] %lc 0\n", pi, creal(e), cimag(e), ae); return 0; }
Please provide an equivalent version of this Factor code in C#.
USING: math math.constants math.functions prettyprint ; 1 e pi C{ 0 1 } * ^ + .
using System; using System.Numerics; public class Program { static void Main() { Complex e = Math.E; Complex i = Complex.ImaginaryOne; Complex π = Math.PI; Console.WriteLine(Complex.Pow(e, i * π) + 1); } }
Keep all operations the same but rewrite the snippet in C#.
USING: math math.constants math.functions prettyprint ; 1 e pi C{ 0 1 } * ^ + .
using System; using System.Numerics; public class Program { static void Main() { Complex e = Math.E; Complex i = Complex.ImaginaryOne; Complex π = Math.PI; Console.WriteLine(Complex.Pow(e, i * π) + 1); } }
Write the same algorithm in C++ as shown in this Factor implementation.
USING: math math.constants math.functions prettyprint ; 1 e pi C{ 0 1 } * ^ + .
#include <iostream> #include <complex> int main() { std::cout << std::exp(std::complex<double>(0.0, M_PI)) + 1.0 << std::endl; return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
USING: math math.constants math.functions prettyprint ; 1 e pi C{ 0 1 } * ^ + .
#include <iostream> #include <complex> int main() { std::cout << std::exp(std::complex<double>(0.0, M_PI)) + 1.0 << std::endl; return 0; }
Rewrite this program in Java while keeping its functionality equivalent to the Factor version.
USING: math math.constants math.functions prettyprint ; 1 e pi C{ 0 1 } * ^ + .
public class EulerIdentity { public static void main(String[] args) { System.out.println("e ^ (i*Pi) + 1 = " + (new Complex(0, Math.PI).exp()).add(new Complex(1, 0))); } public static class Complex { private double x, y; public Complex(double re, double im) { x = re; y = im; } public Complex exp() { double exp = Math.exp(x); return new Complex(exp * Math.cos(y), exp * Math.sin(y)); } public Complex add(Complex a) { return new Complex(x + a.x, y + a.y); } @Override public String toString() { return x + " + " + y + "i"; } } }
Change the following Factor code into Java without altering its purpose.
USING: math math.constants math.functions prettyprint ; 1 e pi C{ 0 1 } * ^ + .
public class EulerIdentity { public static void main(String[] args) { System.out.println("e ^ (i*Pi) + 1 = " + (new Complex(0, Math.PI).exp()).add(new Complex(1, 0))); } public static class Complex { private double x, y; public Complex(double re, double im) { x = re; y = im; } public Complex exp() { double exp = Math.exp(x); return new Complex(exp * Math.cos(y), exp * Math.sin(y)); } public Complex add(Complex a) { return new Complex(x + a.x, y + a.y); } @Override public String toString() { return x + " + " + y + "i"; } } }
Keep all operations the same but rewrite the snippet in Python.
USING: math math.constants math.functions prettyprint ; 1 e pi C{ 0 1 } * ^ + .
>>> import math >>> math.e ** (math.pi * 1j) + 1 1.2246467991473532e-16j
Port the following code from Factor to Python with equivalent syntax and logic.
USING: math math.constants math.functions prettyprint ; 1 e pi C{ 0 1 } * ^ + .
>>> import math >>> math.e ** (math.pi * 1j) + 1 1.2246467991473532e-16j
Ensure the translated Go code behaves exactly like the original Factor snippet.
USING: math math.constants math.functions prettyprint ; 1 e pi C{ 0 1 } * ^ + .
package main import ( "fmt" "math" "math/cmplx" ) func main() { fmt.Println(cmplx.Exp(math.Pi * 1i) + 1.0) }
Convert this Factor snippet to Go and keep its semantics consistent.
USING: math math.constants math.functions prettyprint ; 1 e pi C{ 0 1 } * ^ + .
package main import ( "fmt" "math" "math/cmplx" ) func main() { fmt.Println(cmplx.Exp(math.Pi * 1i) + 1.0) }
Ensure the translated C code behaves exactly like the original Forth snippet.
." e^ + 1 = " pi fcos 1e0 f+ f. '+ emit space pi fsin fs. 'i emit cr bye
#include <stdio.h> #include <math.h> #include <complex.h> #include <wchar.h> #include <locale.h> int main() { wchar_t pi = L'\u03c0'; wchar_t ae = L'\u2245'; double complex e = cexp(M_PI * I) + 1.0; setlocale(LC_CTYPE, ""); printf("e ^ %lci + 1 = [%.16f, %.16f] %lc 0\n", pi, creal(e), cimag(e), ae); return 0; }
Write a version of this Forth function in C with identical behavior.
." e^ + 1 = " pi fcos 1e0 f+ f. '+ emit space pi fsin fs. 'i emit cr bye
#include <stdio.h> #include <math.h> #include <complex.h> #include <wchar.h> #include <locale.h> int main() { wchar_t pi = L'\u03c0'; wchar_t ae = L'\u2245'; double complex e = cexp(M_PI * I) + 1.0; setlocale(LC_CTYPE, ""); printf("e ^ %lci + 1 = [%.16f, %.16f] %lc 0\n", pi, creal(e), cimag(e), ae); return 0; }
Please provide an equivalent version of this Forth code in C#.
." e^ + 1 = " pi fcos 1e0 f+ f. '+ emit space pi fsin fs. 'i emit cr bye
using System; using System.Numerics; public class Program { static void Main() { Complex e = Math.E; Complex i = Complex.ImaginaryOne; Complex π = Math.PI; Console.WriteLine(Complex.Pow(e, i * π) + 1); } }
Port the provided Forth code into C# while preserving the original functionality.
." e^ + 1 = " pi fcos 1e0 f+ f. '+ emit space pi fsin fs. 'i emit cr bye
using System; using System.Numerics; public class Program { static void Main() { Complex e = Math.E; Complex i = Complex.ImaginaryOne; Complex π = Math.PI; Console.WriteLine(Complex.Pow(e, i * π) + 1); } }
Translate this program into C++ but keep the logic exactly as in Forth.
." e^ + 1 = " pi fcos 1e0 f+ f. '+ emit space pi fsin fs. 'i emit cr bye
#include <iostream> #include <complex> int main() { std::cout << std::exp(std::complex<double>(0.0, M_PI)) + 1.0 << std::endl; return 0; }
Port the following code from Forth to C++ with equivalent syntax and logic.
." e^ + 1 = " pi fcos 1e0 f+ f. '+ emit space pi fsin fs. 'i emit cr bye
#include <iostream> #include <complex> int main() { std::cout << std::exp(std::complex<double>(0.0, M_PI)) + 1.0 << std::endl; return 0; }
Change the following Forth code into Java without altering its purpose.
." e^ + 1 = " pi fcos 1e0 f+ f. '+ emit space pi fsin fs. 'i emit cr bye
public class EulerIdentity { public static void main(String[] args) { System.out.println("e ^ (i*Pi) + 1 = " + (new Complex(0, Math.PI).exp()).add(new Complex(1, 0))); } public static class Complex { private double x, y; public Complex(double re, double im) { x = re; y = im; } public Complex exp() { double exp = Math.exp(x); return new Complex(exp * Math.cos(y), exp * Math.sin(y)); } public Complex add(Complex a) { return new Complex(x + a.x, y + a.y); } @Override public String toString() { return x + " + " + y + "i"; } } }
Write the same algorithm in Java as shown in this Forth implementation.
." e^ + 1 = " pi fcos 1e0 f+ f. '+ emit space pi fsin fs. 'i emit cr bye
public class EulerIdentity { public static void main(String[] args) { System.out.println("e ^ (i*Pi) + 1 = " + (new Complex(0, Math.PI).exp()).add(new Complex(1, 0))); } public static class Complex { private double x, y; public Complex(double re, double im) { x = re; y = im; } public Complex exp() { double exp = Math.exp(x); return new Complex(exp * Math.cos(y), exp * Math.sin(y)); } public Complex add(Complex a) { return new Complex(x + a.x, y + a.y); } @Override public String toString() { return x + " + " + y + "i"; } } }
Write the same code in Python as shown below in Forth.
." e^ + 1 = " pi fcos 1e0 f+ f. '+ emit space pi fsin fs. 'i emit cr bye
>>> import math >>> math.e ** (math.pi * 1j) + 1 1.2246467991473532e-16j
Rewrite the snippet below in Python so it works the same as the original Forth code.
." e^ + 1 = " pi fcos 1e0 f+ f. '+ emit space pi fsin fs. 'i emit cr bye
>>> import math >>> math.e ** (math.pi * 1j) + 1 1.2246467991473532e-16j
Produce a language-to-language conversion: from Forth to Go, same semantics.
." e^ + 1 = " pi fcos 1e0 f+ f. '+ emit space pi fsin fs. 'i emit cr bye
package main import ( "fmt" "math" "math/cmplx" ) func main() { fmt.Println(cmplx.Exp(math.Pi * 1i) + 1.0) }
Please provide an equivalent version of this Forth code in Go.
." e^ + 1 = " pi fcos 1e0 f+ f. '+ emit space pi fsin fs. 'i emit cr bye
package main import ( "fmt" "math" "math/cmplx" ) func main() { fmt.Println(cmplx.Exp(math.Pi * 1i) + 1.0) }
Produce a functionally identical C# code for the snippet given in Fortran.
program euler use iso_fortran_env, only: output_unit, REAL64 implicit none integer, parameter :: d=REAL64 real(kind=d), parameter :: e=exp(1._d), pi=4._d*atan(1._d) complex(kind=d), parameter :: i=(0._d,1._d) write(output_unit,*) e**(pi*i) + 1 end program euler
using System; using System.Numerics; public class Program { static void Main() { Complex e = Math.E; Complex i = Complex.ImaginaryOne; Complex π = Math.PI; Console.WriteLine(Complex.Pow(e, i * π) + 1); } }
Write a version of this Fortran function in C# with identical behavior.
program euler use iso_fortran_env, only: output_unit, REAL64 implicit none integer, parameter :: d=REAL64 real(kind=d), parameter :: e=exp(1._d), pi=4._d*atan(1._d) complex(kind=d), parameter :: i=(0._d,1._d) write(output_unit,*) e**(pi*i) + 1 end program euler
using System; using System.Numerics; public class Program { static void Main() { Complex e = Math.E; Complex i = Complex.ImaginaryOne; Complex π = Math.PI; Console.WriteLine(Complex.Pow(e, i * π) + 1); } }
Port the following code from Fortran to C++ with equivalent syntax and logic.
program euler use iso_fortran_env, only: output_unit, REAL64 implicit none integer, parameter :: d=REAL64 real(kind=d), parameter :: e=exp(1._d), pi=4._d*atan(1._d) complex(kind=d), parameter :: i=(0._d,1._d) write(output_unit,*) e**(pi*i) + 1 end program euler
#include <iostream> #include <complex> int main() { std::cout << std::exp(std::complex<double>(0.0, M_PI)) + 1.0 << std::endl; return 0; }
Can you help me rewrite this code in C++ instead of Fortran, keeping it the same logically?
program euler use iso_fortran_env, only: output_unit, REAL64 implicit none integer, parameter :: d=REAL64 real(kind=d), parameter :: e=exp(1._d), pi=4._d*atan(1._d) complex(kind=d), parameter :: i=(0._d,1._d) write(output_unit,*) e**(pi*i) + 1 end program euler
#include <iostream> #include <complex> int main() { std::cout << std::exp(std::complex<double>(0.0, M_PI)) + 1.0 << std::endl; return 0; }
Produce a functionally identical C code for the snippet given in Fortran.
program euler use iso_fortran_env, only: output_unit, REAL64 implicit none integer, parameter :: d=REAL64 real(kind=d), parameter :: e=exp(1._d), pi=4._d*atan(1._d) complex(kind=d), parameter :: i=(0._d,1._d) write(output_unit,*) e**(pi*i) + 1 end program euler
#include <stdio.h> #include <math.h> #include <complex.h> #include <wchar.h> #include <locale.h> int main() { wchar_t pi = L'\u03c0'; wchar_t ae = L'\u2245'; double complex e = cexp(M_PI * I) + 1.0; setlocale(LC_CTYPE, ""); printf("e ^ %lci + 1 = [%.16f, %.16f] %lc 0\n", pi, creal(e), cimag(e), ae); return 0; }
Generate a C translation of this Fortran snippet without changing its computational steps.
program euler use iso_fortran_env, only: output_unit, REAL64 implicit none integer, parameter :: d=REAL64 real(kind=d), parameter :: e=exp(1._d), pi=4._d*atan(1._d) complex(kind=d), parameter :: i=(0._d,1._d) write(output_unit,*) e**(pi*i) + 1 end program euler
#include <stdio.h> #include <math.h> #include <complex.h> #include <wchar.h> #include <locale.h> int main() { wchar_t pi = L'\u03c0'; wchar_t ae = L'\u2245'; double complex e = cexp(M_PI * I) + 1.0; setlocale(LC_CTYPE, ""); printf("e ^ %lci + 1 = [%.16f, %.16f] %lc 0\n", pi, creal(e), cimag(e), ae); return 0; }
Convert the following code from Fortran to Java, ensuring the logic remains intact.
program euler use iso_fortran_env, only: output_unit, REAL64 implicit none integer, parameter :: d=REAL64 real(kind=d), parameter :: e=exp(1._d), pi=4._d*atan(1._d) complex(kind=d), parameter :: i=(0._d,1._d) write(output_unit,*) e**(pi*i) + 1 end program euler
public class EulerIdentity { public static void main(String[] args) { System.out.println("e ^ (i*Pi) + 1 = " + (new Complex(0, Math.PI).exp()).add(new Complex(1, 0))); } public static class Complex { private double x, y; public Complex(double re, double im) { x = re; y = im; } public Complex exp() { double exp = Math.exp(x); return new Complex(exp * Math.cos(y), exp * Math.sin(y)); } public Complex add(Complex a) { return new Complex(x + a.x, y + a.y); } @Override public String toString() { return x + " + " + y + "i"; } } }