Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Can you help me rewrite this code in Rust instead of Java, keeping it the same logically? | String str = "alphaBETA";
System.out.println(str.toUpperCase());
System.out.println(str.toLowerCase());
System.out.println("äàâáçñßæεбế".toUpperCase());
System.out.println("ÄÀÂÁÇÑSSÆΕБẾ".toLowerCase());
| fn main() {
println!("{}", "jalapeño".to_uppercase());
println!("{}", "JALAPEÑO".to_lowercase());
}
|
Write a version of this Ada function in C# with identical behavior. | with Ada.Text_IO;
with Ada.Numerics.Generic_Real_Arrays;
procedure Cramers_Rules is
type Real is new Float;
package Real_Arrays is
new Ada.Numerics.Generic_Real_Arrays (Real);
use Real_Arrays;
function Solve_Cramer (M : in Real_Matrix;
V : in Real_Vector)
return Real_Vector
is
Denominator : Real;
Nom_Matrix : Real_Matrix (M'Range (1),
M'Range (2));
Numerator : Real;
Result : Real_Vector (M'Range (1));
begin
if
M'Length (2) /= V'Length or
M'Length (1) /= M'Length (2)
then
raise Constraint_Error with "Dimensions does not match";
end if;
Denominator := Determinant (M);
for Col in V'Range loop
Nom_Matrix := M;
for Row in V'Range loop
Nom_Matrix (Row, Col) := V (Row);
end loop;
Numerator := Determinant (Nom_Matrix);
Result (Col) := Numerator / Denominator;
end loop;
return Result;
end Solve_Cramer;
procedure Put (V : Real_Vector) is
use Ada.Text_IO;
package Real_IO is
new Ada.Text_IO.Float_IO (Real);
begin
Put ("[");
for E of V loop
Real_IO.Put (E, Exp => 0, Aft => 2);
Put (" ");
end loop;
Put ("]");
New_Line;
end Put;
M : constant Real_Matrix := ((2.0, -1.0, 5.0, 1.0),
(3.0, 2.0, 2.0, -6.0),
(1.0, 3.0, 3.0, -1.0),
(5.0, -2.0, -3.0, 3.0));
V : constant Real_Vector := (-3.0, -32.0, -47.0, 49.0);
R : constant Real_Vector := Solve_Cramer (M, V);
begin
Put (R);
end Cramers_Rules;
| 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();
}
}
}
|
Write the same algorithm in C as shown in this Ada implementation. | with Ada.Text_IO;
with Ada.Numerics.Generic_Real_Arrays;
procedure Cramers_Rules is
type Real is new Float;
package Real_Arrays is
new Ada.Numerics.Generic_Real_Arrays (Real);
use Real_Arrays;
function Solve_Cramer (M : in Real_Matrix;
V : in Real_Vector)
return Real_Vector
is
Denominator : Real;
Nom_Matrix : Real_Matrix (M'Range (1),
M'Range (2));
Numerator : Real;
Result : Real_Vector (M'Range (1));
begin
if
M'Length (2) /= V'Length or
M'Length (1) /= M'Length (2)
then
raise Constraint_Error with "Dimensions does not match";
end if;
Denominator := Determinant (M);
for Col in V'Range loop
Nom_Matrix := M;
for Row in V'Range loop
Nom_Matrix (Row, Col) := V (Row);
end loop;
Numerator := Determinant (Nom_Matrix);
Result (Col) := Numerator / Denominator;
end loop;
return Result;
end Solve_Cramer;
procedure Put (V : Real_Vector) is
use Ada.Text_IO;
package Real_IO is
new Ada.Text_IO.Float_IO (Real);
begin
Put ("[");
for E of V loop
Real_IO.Put (E, Exp => 0, Aft => 2);
Put (" ");
end loop;
Put ("]");
New_Line;
end Put;
M : constant Real_Matrix := ((2.0, -1.0, 5.0, 1.0),
(3.0, 2.0, 2.0, -6.0),
(1.0, 3.0, 3.0, -1.0),
(5.0, -2.0, -3.0, 3.0));
V : constant Real_Vector := (-3.0, -32.0, -47.0, 49.0);
R : constant Real_Vector := Solve_Cramer (M, V);
begin
Put (R);
end Cramers_Rules;
| #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;
}
|
Convert this Ada snippet to C++ and keep its semantics consistent. | with Ada.Text_IO;
with Ada.Numerics.Generic_Real_Arrays;
procedure Cramers_Rules is
type Real is new Float;
package Real_Arrays is
new Ada.Numerics.Generic_Real_Arrays (Real);
use Real_Arrays;
function Solve_Cramer (M : in Real_Matrix;
V : in Real_Vector)
return Real_Vector
is
Denominator : Real;
Nom_Matrix : Real_Matrix (M'Range (1),
M'Range (2));
Numerator : Real;
Result : Real_Vector (M'Range (1));
begin
if
M'Length (2) /= V'Length or
M'Length (1) /= M'Length (2)
then
raise Constraint_Error with "Dimensions does not match";
end if;
Denominator := Determinant (M);
for Col in V'Range loop
Nom_Matrix := M;
for Row in V'Range loop
Nom_Matrix (Row, Col) := V (Row);
end loop;
Numerator := Determinant (Nom_Matrix);
Result (Col) := Numerator / Denominator;
end loop;
return Result;
end Solve_Cramer;
procedure Put (V : Real_Vector) is
use Ada.Text_IO;
package Real_IO is
new Ada.Text_IO.Float_IO (Real);
begin
Put ("[");
for E of V loop
Real_IO.Put (E, Exp => 0, Aft => 2);
Put (" ");
end loop;
Put ("]");
New_Line;
end Put;
M : constant Real_Matrix := ((2.0, -1.0, 5.0, 1.0),
(3.0, 2.0, 2.0, -6.0),
(1.0, 3.0, 3.0, -1.0),
(5.0, -2.0, -3.0, 3.0));
V : constant Real_Vector := (-3.0, -32.0, -47.0, 49.0);
R : constant Real_Vector := Solve_Cramer (M, V);
begin
Put (R);
end Cramers_Rules;
| #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;
}
|
Convert this Ada snippet to Go and keep its semantics consistent. | with Ada.Text_IO;
with Ada.Numerics.Generic_Real_Arrays;
procedure Cramers_Rules is
type Real is new Float;
package Real_Arrays is
new Ada.Numerics.Generic_Real_Arrays (Real);
use Real_Arrays;
function Solve_Cramer (M : in Real_Matrix;
V : in Real_Vector)
return Real_Vector
is
Denominator : Real;
Nom_Matrix : Real_Matrix (M'Range (1),
M'Range (2));
Numerator : Real;
Result : Real_Vector (M'Range (1));
begin
if
M'Length (2) /= V'Length or
M'Length (1) /= M'Length (2)
then
raise Constraint_Error with "Dimensions does not match";
end if;
Denominator := Determinant (M);
for Col in V'Range loop
Nom_Matrix := M;
for Row in V'Range loop
Nom_Matrix (Row, Col) := V (Row);
end loop;
Numerator := Determinant (Nom_Matrix);
Result (Col) := Numerator / Denominator;
end loop;
return Result;
end Solve_Cramer;
procedure Put (V : Real_Vector) is
use Ada.Text_IO;
package Real_IO is
new Ada.Text_IO.Float_IO (Real);
begin
Put ("[");
for E of V loop
Real_IO.Put (E, Exp => 0, Aft => 2);
Put (" ");
end loop;
Put ("]");
New_Line;
end Put;
M : constant Real_Matrix := ((2.0, -1.0, 5.0, 1.0),
(3.0, 2.0, 2.0, -6.0),
(1.0, 3.0, 3.0, -1.0),
(5.0, -2.0, -3.0, 3.0));
V : constant Real_Vector := (-3.0, -32.0, -47.0, 49.0);
R : constant Real_Vector := Solve_Cramer (M, V);
begin
Put (R);
end Cramers_Rules;
| 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)
}
|
Please provide an equivalent version of this Ada code in Java. | with Ada.Text_IO;
with Ada.Numerics.Generic_Real_Arrays;
procedure Cramers_Rules is
type Real is new Float;
package Real_Arrays is
new Ada.Numerics.Generic_Real_Arrays (Real);
use Real_Arrays;
function Solve_Cramer (M : in Real_Matrix;
V : in Real_Vector)
return Real_Vector
is
Denominator : Real;
Nom_Matrix : Real_Matrix (M'Range (1),
M'Range (2));
Numerator : Real;
Result : Real_Vector (M'Range (1));
begin
if
M'Length (2) /= V'Length or
M'Length (1) /= M'Length (2)
then
raise Constraint_Error with "Dimensions does not match";
end if;
Denominator := Determinant (M);
for Col in V'Range loop
Nom_Matrix := M;
for Row in V'Range loop
Nom_Matrix (Row, Col) := V (Row);
end loop;
Numerator := Determinant (Nom_Matrix);
Result (Col) := Numerator / Denominator;
end loop;
return Result;
end Solve_Cramer;
procedure Put (V : Real_Vector) is
use Ada.Text_IO;
package Real_IO is
new Ada.Text_IO.Float_IO (Real);
begin
Put ("[");
for E of V loop
Real_IO.Put (E, Exp => 0, Aft => 2);
Put (" ");
end loop;
Put ("]");
New_Line;
end Put;
M : constant Real_Matrix := ((2.0, -1.0, 5.0, 1.0),
(3.0, 2.0, 2.0, -6.0),
(1.0, 3.0, 3.0, -1.0),
(5.0, -2.0, -3.0, 3.0));
V : constant Real_Vector := (-3.0, -32.0, -47.0, 49.0);
R : constant Real_Vector := Solve_Cramer (M, V);
begin
Put (R);
end Cramers_Rules;
| 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);
}
}
}
|
Can you help me rewrite this code in Python instead of Ada, keeping it the same logically? | with Ada.Text_IO;
with Ada.Numerics.Generic_Real_Arrays;
procedure Cramers_Rules is
type Real is new Float;
package Real_Arrays is
new Ada.Numerics.Generic_Real_Arrays (Real);
use Real_Arrays;
function Solve_Cramer (M : in Real_Matrix;
V : in Real_Vector)
return Real_Vector
is
Denominator : Real;
Nom_Matrix : Real_Matrix (M'Range (1),
M'Range (2));
Numerator : Real;
Result : Real_Vector (M'Range (1));
begin
if
M'Length (2) /= V'Length or
M'Length (1) /= M'Length (2)
then
raise Constraint_Error with "Dimensions does not match";
end if;
Denominator := Determinant (M);
for Col in V'Range loop
Nom_Matrix := M;
for Row in V'Range loop
Nom_Matrix (Row, Col) := V (Row);
end loop;
Numerator := Determinant (Nom_Matrix);
Result (Col) := Numerator / Denominator;
end loop;
return Result;
end Solve_Cramer;
procedure Put (V : Real_Vector) is
use Ada.Text_IO;
package Real_IO is
new Ada.Text_IO.Float_IO (Real);
begin
Put ("[");
for E of V loop
Real_IO.Put (E, Exp => 0, Aft => 2);
Put (" ");
end loop;
Put ("]");
New_Line;
end Put;
M : constant Real_Matrix := ((2.0, -1.0, 5.0, 1.0),
(3.0, 2.0, 2.0, -6.0),
(1.0, 3.0, 3.0, -1.0),
(5.0, -2.0, -3.0, 3.0));
V : constant Real_Vector := (-3.0, -32.0, -47.0, 49.0);
R : constant Real_Vector := Solve_Cramer (M, V);
begin
Put (R);
end Cramers_Rules;
| 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)
|
Convert this Ada snippet to VB and keep its semantics consistent. | with Ada.Text_IO;
with Ada.Numerics.Generic_Real_Arrays;
procedure Cramers_Rules is
type Real is new Float;
package Real_Arrays is
new Ada.Numerics.Generic_Real_Arrays (Real);
use Real_Arrays;
function Solve_Cramer (M : in Real_Matrix;
V : in Real_Vector)
return Real_Vector
is
Denominator : Real;
Nom_Matrix : Real_Matrix (M'Range (1),
M'Range (2));
Numerator : Real;
Result : Real_Vector (M'Range (1));
begin
if
M'Length (2) /= V'Length or
M'Length (1) /= M'Length (2)
then
raise Constraint_Error with "Dimensions does not match";
end if;
Denominator := Determinant (M);
for Col in V'Range loop
Nom_Matrix := M;
for Row in V'Range loop
Nom_Matrix (Row, Col) := V (Row);
end loop;
Numerator := Determinant (Nom_Matrix);
Result (Col) := Numerator / Denominator;
end loop;
return Result;
end Solve_Cramer;
procedure Put (V : Real_Vector) is
use Ada.Text_IO;
package Real_IO is
new Ada.Text_IO.Float_IO (Real);
begin
Put ("[");
for E of V loop
Real_IO.Put (E, Exp => 0, Aft => 2);
Put (" ");
end loop;
Put ("]");
New_Line;
end Put;
M : constant Real_Matrix := ((2.0, -1.0, 5.0, 1.0),
(3.0, 2.0, 2.0, -6.0),
(1.0, 3.0, 3.0, -1.0),
(5.0, -2.0, -3.0, 3.0));
V : constant Real_Vector := (-3.0, -32.0, -47.0, 49.0);
R : constant Real_Vector := Solve_Cramer (M, V);
begin
Put (R);
end Cramers_Rules;
| 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 Common_Lisp to C with equivalent syntax and logic. | (defun minor (m col)
(loop with dim = (1- (array-dimension m 0))
with result = (make-array (list dim dim))
for i from 1 to dim
for r = (1- i)
do (loop with c = 0
for j to dim
when (/= j col)
do (setf (aref result r c) (aref m i j))
(incf c))
finally (return result)))
(defun det (m)
(assert (= (array-rank m) 2))
(assert (= (array-dimension m 0) (array-dimension m 1)))
(let ((dim (array-dimension m 0)))
(if (= dim 1)
(aref m 0 0)
(loop for col below dim
for sign = 1 then (- sign)
sum (* sign (aref m 0 col) (det (minor m col)))))))
(defun replace-column (m col values)
(let* ((dim (array-dimension m 0))
(result (make-array (list dim dim))))
(dotimes (r dim result)
(dotimes (c dim)
(setf (aref result r c)
(if (= c col) (aref values r) (aref m r c)))))))
(defun solve (m v)
(loop with dim = (array-dimension m 0)
with det = (det m)
for col below dim
collect (/ (det (replace-column m col v)) det)))
(solve #2A((2 -1 5 1)
(3 2 2 -6)
(1 3 3 -1)
(5 -2 -3 3))
#(-3 -32 -47 49))
| #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 Common_Lisp code into C# without altering its purpose. | (defun minor (m col)
(loop with dim = (1- (array-dimension m 0))
with result = (make-array (list dim dim))
for i from 1 to dim
for r = (1- i)
do (loop with c = 0
for j to dim
when (/= j col)
do (setf (aref result r c) (aref m i j))
(incf c))
finally (return result)))
(defun det (m)
(assert (= (array-rank m) 2))
(assert (= (array-dimension m 0) (array-dimension m 1)))
(let ((dim (array-dimension m 0)))
(if (= dim 1)
(aref m 0 0)
(loop for col below dim
for sign = 1 then (- sign)
sum (* sign (aref m 0 col) (det (minor m col)))))))
(defun replace-column (m col values)
(let* ((dim (array-dimension m 0))
(result (make-array (list dim dim))))
(dotimes (r dim result)
(dotimes (c dim)
(setf (aref result r c)
(if (= c col) (aref values r) (aref m r c)))))))
(defun solve (m v)
(loop with dim = (array-dimension m 0)
with det = (det m)
for col below dim
collect (/ (det (replace-column m col v)) det)))
(solve #2A((2 -1 5 1)
(3 2 2 -6)
(1 3 3 -1)
(5 -2 -3 3))
#(-3 -32 -47 49))
| 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();
}
}
}
|
Convert this Common_Lisp snippet to C++ and keep its semantics consistent. | (defun minor (m col)
(loop with dim = (1- (array-dimension m 0))
with result = (make-array (list dim dim))
for i from 1 to dim
for r = (1- i)
do (loop with c = 0
for j to dim
when (/= j col)
do (setf (aref result r c) (aref m i j))
(incf c))
finally (return result)))
(defun det (m)
(assert (= (array-rank m) 2))
(assert (= (array-dimension m 0) (array-dimension m 1)))
(let ((dim (array-dimension m 0)))
(if (= dim 1)
(aref m 0 0)
(loop for col below dim
for sign = 1 then (- sign)
sum (* sign (aref m 0 col) (det (minor m col)))))))
(defun replace-column (m col values)
(let* ((dim (array-dimension m 0))
(result (make-array (list dim dim))))
(dotimes (r dim result)
(dotimes (c dim)
(setf (aref result r c)
(if (= c col) (aref values r) (aref m r c)))))))
(defun solve (m v)
(loop with dim = (array-dimension m 0)
with det = (det m)
for col below dim
collect (/ (det (replace-column m col v)) det)))
(solve #2A((2 -1 5 1)
(3 2 2 -6)
(1 3 3 -1)
(5 -2 -3 3))
#(-3 -32 -47 49))
| #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;
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Common_Lisp version. | (defun minor (m col)
(loop with dim = (1- (array-dimension m 0))
with result = (make-array (list dim dim))
for i from 1 to dim
for r = (1- i)
do (loop with c = 0
for j to dim
when (/= j col)
do (setf (aref result r c) (aref m i j))
(incf c))
finally (return result)))
(defun det (m)
(assert (= (array-rank m) 2))
(assert (= (array-dimension m 0) (array-dimension m 1)))
(let ((dim (array-dimension m 0)))
(if (= dim 1)
(aref m 0 0)
(loop for col below dim
for sign = 1 then (- sign)
sum (* sign (aref m 0 col) (det (minor m col)))))))
(defun replace-column (m col values)
(let* ((dim (array-dimension m 0))
(result (make-array (list dim dim))))
(dotimes (r dim result)
(dotimes (c dim)
(setf (aref result r c)
(if (= c col) (aref values r) (aref m r c)))))))
(defun solve (m v)
(loop with dim = (array-dimension m 0)
with det = (det m)
for col below dim
collect (/ (det (replace-column m col v)) det)))
(solve #2A((2 -1 5 1)
(3 2 2 -6)
(1 3 3 -1)
(5 -2 -3 3))
#(-3 -32 -47 49))
| 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 algorithm in Python as shown in this Common_Lisp implementation. | (defun minor (m col)
(loop with dim = (1- (array-dimension m 0))
with result = (make-array (list dim dim))
for i from 1 to dim
for r = (1- i)
do (loop with c = 0
for j to dim
when (/= j col)
do (setf (aref result r c) (aref m i j))
(incf c))
finally (return result)))
(defun det (m)
(assert (= (array-rank m) 2))
(assert (= (array-dimension m 0) (array-dimension m 1)))
(let ((dim (array-dimension m 0)))
(if (= dim 1)
(aref m 0 0)
(loop for col below dim
for sign = 1 then (- sign)
sum (* sign (aref m 0 col) (det (minor m col)))))))
(defun replace-column (m col values)
(let* ((dim (array-dimension m 0))
(result (make-array (list dim dim))))
(dotimes (r dim result)
(dotimes (c dim)
(setf (aref result r c)
(if (= c col) (aref values r) (aref m r c)))))))
(defun solve (m v)
(loop with dim = (array-dimension m 0)
with det = (det m)
for col below dim
collect (/ (det (replace-column m col v)) det)))
(solve #2A((2 -1 5 1)
(3 2 2 -6)
(1 3 3 -1)
(5 -2 -3 3))
#(-3 -32 -47 49))
| 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)
|
Produce a language-to-language conversion: from Common_Lisp to VB, same semantics. | (defun minor (m col)
(loop with dim = (1- (array-dimension m 0))
with result = (make-array (list dim dim))
for i from 1 to dim
for r = (1- i)
do (loop with c = 0
for j to dim
when (/= j col)
do (setf (aref result r c) (aref m i j))
(incf c))
finally (return result)))
(defun det (m)
(assert (= (array-rank m) 2))
(assert (= (array-dimension m 0) (array-dimension m 1)))
(let ((dim (array-dimension m 0)))
(if (= dim 1)
(aref m 0 0)
(loop for col below dim
for sign = 1 then (- sign)
sum (* sign (aref m 0 col) (det (minor m col)))))))
(defun replace-column (m col values)
(let* ((dim (array-dimension m 0))
(result (make-array (list dim dim))))
(dotimes (r dim result)
(dotimes (c dim)
(setf (aref result r c)
(if (= c col) (aref values r) (aref m r c)))))))
(defun solve (m v)
(loop with dim = (array-dimension m 0)
with det = (det m)
for col below dim
collect (/ (det (replace-column m col v)) det)))
(solve #2A((2 -1 5 1)
(3 2 2 -6)
(1 3 3 -1)
(5 -2 -3 3))
#(-3 -32 -47 49))
| 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
|
Generate a Go translation of this Common_Lisp snippet without changing its computational steps. | (defun minor (m col)
(loop with dim = (1- (array-dimension m 0))
with result = (make-array (list dim dim))
for i from 1 to dim
for r = (1- i)
do (loop with c = 0
for j to dim
when (/= j col)
do (setf (aref result r c) (aref m i j))
(incf c))
finally (return result)))
(defun det (m)
(assert (= (array-rank m) 2))
(assert (= (array-dimension m 0) (array-dimension m 1)))
(let ((dim (array-dimension m 0)))
(if (= dim 1)
(aref m 0 0)
(loop for col below dim
for sign = 1 then (- sign)
sum (* sign (aref m 0 col) (det (minor m col)))))))
(defun replace-column (m col values)
(let* ((dim (array-dimension m 0))
(result (make-array (list dim dim))))
(dotimes (r dim result)
(dotimes (c dim)
(setf (aref result r c)
(if (= c col) (aref values r) (aref m r c)))))))
(defun solve (m v)
(loop with dim = (array-dimension m 0)
with det = (det m)
for col below dim
collect (/ (det (replace-column m col v)) det)))
(solve #2A((2 -1 5 1)
(3 2 2 -6)
(1 3 3 -1)
(5 -2 -3 3))
#(-3 -32 -47 49))
| 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)
}
|
Please provide an equivalent version of this D code in C. | import std.array : array, uninitializedArray;
import std.range : iota;
import std.stdio : writeln;
import std.typecons : tuple;
alias vector = double[4];
alias matrix = vector[4];
auto johnsonTrotter(int n) {
auto p = iota(n).array;
auto q = iota(n).array;
auto d = uninitializedArray!(int[])(n);
d[] = -1;
auto sign = 1;
int[][] perms;
int[] signs;
void permute(int k) {
if (k >= n) {
perms ~= p.dup;
signs ~= sign;
sign *= -1;
return;
}
permute(k + 1);
foreach (i; 0..k) {
auto 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 tuple!("sigmas", "signs")(perms, signs);
}
auto determinant(matrix m) {
auto jt = johnsonTrotter(m.length);
auto sum = 0.0;
foreach (i,sigma; jt.sigmas) {
auto prod = 1.0;
foreach (j,s; sigma) {
prod *= m[j][s];
}
sum += jt.signs[i] * prod;
}
return sum;
}
auto cramer(matrix m, vector d) {
auto divisor = determinant(m);
auto numerators = uninitializedArray!(matrix[])(m.length);
foreach (i; 0..m.length) {
foreach (j; 0..m.length) {
foreach (k; 0..m.length) {
numerators[i][j][k] = m[j][k];
}
}
}
vector v;
foreach (i; 0..m.length) {
foreach (j; 0..m.length) {
numerators[i][j][i] = d[j];
}
}
foreach (i; 0..m.length) {
v[i] = determinant(numerators[i]) / divisor;
}
return v;
}
void main() {
matrix m = [
[2.0, -1.0, 5.0, 1.0],
[3.0, 2.0, 2.0, -6.0],
[1.0, 3.0, 3.0, -1.0],
[5.0, -2.0, -3.0, 3.0]
];
vector d = [-3.0, -32.0, -47.0, 49.0];
auto wxyz = cramer(m, d);
writeln("w = ", wxyz[0], ", x = ", wxyz[1], ", y = ", wxyz[2], ", z = ", wxyz[3]);
}
| #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;
}
|
Please provide an equivalent version of this D code in C#. | import std.array : array, uninitializedArray;
import std.range : iota;
import std.stdio : writeln;
import std.typecons : tuple;
alias vector = double[4];
alias matrix = vector[4];
auto johnsonTrotter(int n) {
auto p = iota(n).array;
auto q = iota(n).array;
auto d = uninitializedArray!(int[])(n);
d[] = -1;
auto sign = 1;
int[][] perms;
int[] signs;
void permute(int k) {
if (k >= n) {
perms ~= p.dup;
signs ~= sign;
sign *= -1;
return;
}
permute(k + 1);
foreach (i; 0..k) {
auto 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 tuple!("sigmas", "signs")(perms, signs);
}
auto determinant(matrix m) {
auto jt = johnsonTrotter(m.length);
auto sum = 0.0;
foreach (i,sigma; jt.sigmas) {
auto prod = 1.0;
foreach (j,s; sigma) {
prod *= m[j][s];
}
sum += jt.signs[i] * prod;
}
return sum;
}
auto cramer(matrix m, vector d) {
auto divisor = determinant(m);
auto numerators = uninitializedArray!(matrix[])(m.length);
foreach (i; 0..m.length) {
foreach (j; 0..m.length) {
foreach (k; 0..m.length) {
numerators[i][j][k] = m[j][k];
}
}
}
vector v;
foreach (i; 0..m.length) {
foreach (j; 0..m.length) {
numerators[i][j][i] = d[j];
}
}
foreach (i; 0..m.length) {
v[i] = determinant(numerators[i]) / divisor;
}
return v;
}
void main() {
matrix m = [
[2.0, -1.0, 5.0, 1.0],
[3.0, 2.0, 2.0, -6.0],
[1.0, 3.0, 3.0, -1.0],
[5.0, -2.0, -3.0, 3.0]
];
vector d = [-3.0, -32.0, -47.0, 49.0];
auto wxyz = cramer(m, d);
writeln("w = ", wxyz[0], ", x = ", wxyz[1], ", y = ", wxyz[2], ", z = ", wxyz[3]);
}
| 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();
}
}
}
|
Generate a C++ translation of this D snippet without changing its computational steps. | import std.array : array, uninitializedArray;
import std.range : iota;
import std.stdio : writeln;
import std.typecons : tuple;
alias vector = double[4];
alias matrix = vector[4];
auto johnsonTrotter(int n) {
auto p = iota(n).array;
auto q = iota(n).array;
auto d = uninitializedArray!(int[])(n);
d[] = -1;
auto sign = 1;
int[][] perms;
int[] signs;
void permute(int k) {
if (k >= n) {
perms ~= p.dup;
signs ~= sign;
sign *= -1;
return;
}
permute(k + 1);
foreach (i; 0..k) {
auto 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 tuple!("sigmas", "signs")(perms, signs);
}
auto determinant(matrix m) {
auto jt = johnsonTrotter(m.length);
auto sum = 0.0;
foreach (i,sigma; jt.sigmas) {
auto prod = 1.0;
foreach (j,s; sigma) {
prod *= m[j][s];
}
sum += jt.signs[i] * prod;
}
return sum;
}
auto cramer(matrix m, vector d) {
auto divisor = determinant(m);
auto numerators = uninitializedArray!(matrix[])(m.length);
foreach (i; 0..m.length) {
foreach (j; 0..m.length) {
foreach (k; 0..m.length) {
numerators[i][j][k] = m[j][k];
}
}
}
vector v;
foreach (i; 0..m.length) {
foreach (j; 0..m.length) {
numerators[i][j][i] = d[j];
}
}
foreach (i; 0..m.length) {
v[i] = determinant(numerators[i]) / divisor;
}
return v;
}
void main() {
matrix m = [
[2.0, -1.0, 5.0, 1.0],
[3.0, 2.0, 2.0, -6.0],
[1.0, 3.0, 3.0, -1.0],
[5.0, -2.0, -3.0, 3.0]
];
vector d = [-3.0, -32.0, -47.0, 49.0];
auto wxyz = cramer(m, d);
writeln("w = ", wxyz[0], ", x = ", wxyz[1], ", y = ", wxyz[2], ", z = ", wxyz[3]);
}
| #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;
}
|
Write the same algorithm in Java as shown in this D implementation. | import std.array : array, uninitializedArray;
import std.range : iota;
import std.stdio : writeln;
import std.typecons : tuple;
alias vector = double[4];
alias matrix = vector[4];
auto johnsonTrotter(int n) {
auto p = iota(n).array;
auto q = iota(n).array;
auto d = uninitializedArray!(int[])(n);
d[] = -1;
auto sign = 1;
int[][] perms;
int[] signs;
void permute(int k) {
if (k >= n) {
perms ~= p.dup;
signs ~= sign;
sign *= -1;
return;
}
permute(k + 1);
foreach (i; 0..k) {
auto 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 tuple!("sigmas", "signs")(perms, signs);
}
auto determinant(matrix m) {
auto jt = johnsonTrotter(m.length);
auto sum = 0.0;
foreach (i,sigma; jt.sigmas) {
auto prod = 1.0;
foreach (j,s; sigma) {
prod *= m[j][s];
}
sum += jt.signs[i] * prod;
}
return sum;
}
auto cramer(matrix m, vector d) {
auto divisor = determinant(m);
auto numerators = uninitializedArray!(matrix[])(m.length);
foreach (i; 0..m.length) {
foreach (j; 0..m.length) {
foreach (k; 0..m.length) {
numerators[i][j][k] = m[j][k];
}
}
}
vector v;
foreach (i; 0..m.length) {
foreach (j; 0..m.length) {
numerators[i][j][i] = d[j];
}
}
foreach (i; 0..m.length) {
v[i] = determinant(numerators[i]) / divisor;
}
return v;
}
void main() {
matrix m = [
[2.0, -1.0, 5.0, 1.0],
[3.0, 2.0, 2.0, -6.0],
[1.0, 3.0, 3.0, -1.0],
[5.0, -2.0, -3.0, 3.0]
];
vector d = [-3.0, -32.0, -47.0, 49.0];
auto wxyz = cramer(m, d);
writeln("w = ", wxyz[0], ", x = ", wxyz[1], ", y = ", wxyz[2], ", z = ", wxyz[3]);
}
| 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);
}
}
}
|
Transform the following D implementation into Python, maintaining the same output and logic. | import std.array : array, uninitializedArray;
import std.range : iota;
import std.stdio : writeln;
import std.typecons : tuple;
alias vector = double[4];
alias matrix = vector[4];
auto johnsonTrotter(int n) {
auto p = iota(n).array;
auto q = iota(n).array;
auto d = uninitializedArray!(int[])(n);
d[] = -1;
auto sign = 1;
int[][] perms;
int[] signs;
void permute(int k) {
if (k >= n) {
perms ~= p.dup;
signs ~= sign;
sign *= -1;
return;
}
permute(k + 1);
foreach (i; 0..k) {
auto 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 tuple!("sigmas", "signs")(perms, signs);
}
auto determinant(matrix m) {
auto jt = johnsonTrotter(m.length);
auto sum = 0.0;
foreach (i,sigma; jt.sigmas) {
auto prod = 1.0;
foreach (j,s; sigma) {
prod *= m[j][s];
}
sum += jt.signs[i] * prod;
}
return sum;
}
auto cramer(matrix m, vector d) {
auto divisor = determinant(m);
auto numerators = uninitializedArray!(matrix[])(m.length);
foreach (i; 0..m.length) {
foreach (j; 0..m.length) {
foreach (k; 0..m.length) {
numerators[i][j][k] = m[j][k];
}
}
}
vector v;
foreach (i; 0..m.length) {
foreach (j; 0..m.length) {
numerators[i][j][i] = d[j];
}
}
foreach (i; 0..m.length) {
v[i] = determinant(numerators[i]) / divisor;
}
return v;
}
void main() {
matrix m = [
[2.0, -1.0, 5.0, 1.0],
[3.0, 2.0, 2.0, -6.0],
[1.0, 3.0, 3.0, -1.0],
[5.0, -2.0, -3.0, 3.0]
];
vector d = [-3.0, -32.0, -47.0, 49.0];
auto wxyz = cramer(m, d);
writeln("w = ", wxyz[0], ", x = ", wxyz[1], ", y = ", wxyz[2], ", z = ", wxyz[3]);
}
| 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)
|
Change the following D code into VB without altering its purpose. | import std.array : array, uninitializedArray;
import std.range : iota;
import std.stdio : writeln;
import std.typecons : tuple;
alias vector = double[4];
alias matrix = vector[4];
auto johnsonTrotter(int n) {
auto p = iota(n).array;
auto q = iota(n).array;
auto d = uninitializedArray!(int[])(n);
d[] = -1;
auto sign = 1;
int[][] perms;
int[] signs;
void permute(int k) {
if (k >= n) {
perms ~= p.dup;
signs ~= sign;
sign *= -1;
return;
}
permute(k + 1);
foreach (i; 0..k) {
auto 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 tuple!("sigmas", "signs")(perms, signs);
}
auto determinant(matrix m) {
auto jt = johnsonTrotter(m.length);
auto sum = 0.0;
foreach (i,sigma; jt.sigmas) {
auto prod = 1.0;
foreach (j,s; sigma) {
prod *= m[j][s];
}
sum += jt.signs[i] * prod;
}
return sum;
}
auto cramer(matrix m, vector d) {
auto divisor = determinant(m);
auto numerators = uninitializedArray!(matrix[])(m.length);
foreach (i; 0..m.length) {
foreach (j; 0..m.length) {
foreach (k; 0..m.length) {
numerators[i][j][k] = m[j][k];
}
}
}
vector v;
foreach (i; 0..m.length) {
foreach (j; 0..m.length) {
numerators[i][j][i] = d[j];
}
}
foreach (i; 0..m.length) {
v[i] = determinant(numerators[i]) / divisor;
}
return v;
}
void main() {
matrix m = [
[2.0, -1.0, 5.0, 1.0],
[3.0, 2.0, 2.0, -6.0],
[1.0, 3.0, 3.0, -1.0],
[5.0, -2.0, -3.0, 3.0]
];
vector d = [-3.0, -32.0, -47.0, 49.0];
auto wxyz = cramer(m, d);
writeln("w = ", wxyz[0], ", x = ", wxyz[1], ", y = ", wxyz[2], ", z = ", wxyz[3]);
}
| 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 the snippet below in Go so it works the same as the original D code. | import std.array : array, uninitializedArray;
import std.range : iota;
import std.stdio : writeln;
import std.typecons : tuple;
alias vector = double[4];
alias matrix = vector[4];
auto johnsonTrotter(int n) {
auto p = iota(n).array;
auto q = iota(n).array;
auto d = uninitializedArray!(int[])(n);
d[] = -1;
auto sign = 1;
int[][] perms;
int[] signs;
void permute(int k) {
if (k >= n) {
perms ~= p.dup;
signs ~= sign;
sign *= -1;
return;
}
permute(k + 1);
foreach (i; 0..k) {
auto 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 tuple!("sigmas", "signs")(perms, signs);
}
auto determinant(matrix m) {
auto jt = johnsonTrotter(m.length);
auto sum = 0.0;
foreach (i,sigma; jt.sigmas) {
auto prod = 1.0;
foreach (j,s; sigma) {
prod *= m[j][s];
}
sum += jt.signs[i] * prod;
}
return sum;
}
auto cramer(matrix m, vector d) {
auto divisor = determinant(m);
auto numerators = uninitializedArray!(matrix[])(m.length);
foreach (i; 0..m.length) {
foreach (j; 0..m.length) {
foreach (k; 0..m.length) {
numerators[i][j][k] = m[j][k];
}
}
}
vector v;
foreach (i; 0..m.length) {
foreach (j; 0..m.length) {
numerators[i][j][i] = d[j];
}
}
foreach (i; 0..m.length) {
v[i] = determinant(numerators[i]) / divisor;
}
return v;
}
void main() {
matrix m = [
[2.0, -1.0, 5.0, 1.0],
[3.0, 2.0, 2.0, -6.0],
[1.0, 3.0, 3.0, -1.0],
[5.0, -2.0, -3.0, 3.0]
];
vector d = [-3.0, -32.0, -47.0, 49.0];
auto wxyz = cramer(m, d);
writeln("w = ", wxyz[0], ", x = ", wxyz[1], ", y = ", wxyz[2], ", z = ", wxyz[3]);
}
| 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)
}
|
Translate this program into C but keep the logic exactly as in Factor. | USING: kernel math math.matrices.laplace prettyprint sequences ;
IN: rosetta-code.cramers-rule
: replace-col ( elt n seq -- seq' ) flip [ set-nth ] keep flip ;
: solve ( m v -- seq )
dup length <iota> [
rot [ replace-col ] keep [ determinant ] bi@ /
] 2with map ;
: cramers-rule-demo ( -- )
{
{ 2 -1 5 1 }
{ 3 2 2 -6 }
{ 1 3 3 -1 }
{ 5 -2 -3 3 }
}
{ -3 -32 -47 49 } solve . ;
MAIN: cramers-rule-demo
| #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;
}
|
Write the same algorithm in C# as shown in this Factor implementation. | USING: kernel math math.matrices.laplace prettyprint sequences ;
IN: rosetta-code.cramers-rule
: replace-col ( elt n seq -- seq' ) flip [ set-nth ] keep flip ;
: solve ( m v -- seq )
dup length <iota> [
rot [ replace-col ] keep [ determinant ] bi@ /
] 2with map ;
: cramers-rule-demo ( -- )
{
{ 2 -1 5 1 }
{ 3 2 2 -6 }
{ 1 3 3 -1 }
{ 5 -2 -3 3 }
}
{ -3 -32 -47 49 } solve . ;
MAIN: cramers-rule-demo
| 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();
}
}
}
|
Write the same algorithm in C++ as shown in this Factor implementation. | USING: kernel math math.matrices.laplace prettyprint sequences ;
IN: rosetta-code.cramers-rule
: replace-col ( elt n seq -- seq' ) flip [ set-nth ] keep flip ;
: solve ( m v -- seq )
dup length <iota> [
rot [ replace-col ] keep [ determinant ] bi@ /
] 2with map ;
: cramers-rule-demo ( -- )
{
{ 2 -1 5 1 }
{ 3 2 2 -6 }
{ 1 3 3 -1 }
{ 5 -2 -3 3 }
}
{ -3 -32 -47 49 } solve . ;
MAIN: cramers-rule-demo
| #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;
}
|
Port the provided Factor code into Java while preserving the original functionality. | USING: kernel math math.matrices.laplace prettyprint sequences ;
IN: rosetta-code.cramers-rule
: replace-col ( elt n seq -- seq' ) flip [ set-nth ] keep flip ;
: solve ( m v -- seq )
dup length <iota> [
rot [ replace-col ] keep [ determinant ] bi@ /
] 2with map ;
: cramers-rule-demo ( -- )
{
{ 2 -1 5 1 }
{ 3 2 2 -6 }
{ 1 3 3 -1 }
{ 5 -2 -3 3 }
}
{ -3 -32 -47 49 } solve . ;
MAIN: cramers-rule-demo
| 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);
}
}
}
|
Keep all operations the same but rewrite the snippet in Python. | USING: kernel math math.matrices.laplace prettyprint sequences ;
IN: rosetta-code.cramers-rule
: replace-col ( elt n seq -- seq' ) flip [ set-nth ] keep flip ;
: solve ( m v -- seq )
dup length <iota> [
rot [ replace-col ] keep [ determinant ] bi@ /
] 2with map ;
: cramers-rule-demo ( -- )
{
{ 2 -1 5 1 }
{ 3 2 2 -6 }
{ 1 3 3 -1 }
{ 5 -2 -3 3 }
}
{ -3 -32 -47 49 } solve . ;
MAIN: cramers-rule-demo
| 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)
|
Generate an equivalent VB version of this Factor code. | USING: kernel math math.matrices.laplace prettyprint sequences ;
IN: rosetta-code.cramers-rule
: replace-col ( elt n seq -- seq' ) flip [ set-nth ] keep flip ;
: solve ( m v -- seq )
dup length <iota> [
rot [ replace-col ] keep [ determinant ] bi@ /
] 2with map ;
: cramers-rule-demo ( -- )
{
{ 2 -1 5 1 }
{ 3 2 2 -6 }
{ 1 3 3 -1 }
{ 5 -2 -3 3 }
}
{ -3 -32 -47 49 } solve . ;
MAIN: cramers-rule-demo
| 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
|
Maintain the same structure and functionality when rewriting this code in Go. | USING: kernel math math.matrices.laplace prettyprint sequences ;
IN: rosetta-code.cramers-rule
: replace-col ( elt n seq -- seq' ) flip [ set-nth ] keep flip ;
: solve ( m v -- seq )
dup length <iota> [
rot [ replace-col ] keep [ determinant ] bi@ /
] 2with map ;
: cramers-rule-demo ( -- )
{
{ 2 -1 5 1 }
{ 3 2 2 -6 }
{ 1 3 3 -1 }
{ 5 -2 -3 3 }
}
{ -3 -32 -47 49 } solve . ;
MAIN: cramers-rule-demo
| 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)
}
|
Please provide an equivalent version of this Fortran code in C#. | DATA A/2, -1, 5, 1
1 3, 2, 2, -6
2 1, 3, 3, -1
3 5, -2, -3, 3/
| 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();
}
}
}
|
Write the same code in C++ as shown below in Fortran. | DATA A/2, -1, 5, 1
1 3, 2, 2, -6
2 1, 3, 3, -1
3 5, -2, -3, 3/
| #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;
}
|
Port the following code from Fortran to C with equivalent syntax and logic. | DATA A/2, -1, 5, 1
1 3, 2, 2, -6
2 1, 3, 3, -1
3 5, -2, -3, 3/
| #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;
}
|
Produce a language-to-language conversion: from Fortran to Java, same semantics. | DATA A/2, -1, 5, 1
1 3, 2, 2, -6
2 1, 3, 3, -1
3 5, -2, -3, 3/
| 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 algorithm in Python as shown in this Fortran implementation. | DATA A/2, -1, 5, 1
1 3, 2, 2, -6
2 1, 3, 3, -1
3 5, -2, -3, 3/
| 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)
|
Transform the following Fortran implementation into VB, maintaining the same output and logic. | DATA A/2, -1, 5, 1
1 3, 2, 2, -6
2 1, 3, 3, -1
3 5, -2, -3, 3/
| 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
|
Translate this program into C but keep the logic exactly as in Groovy. | class CramersRule {
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)
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
String toString() {
return matrix.toString()
}
@SafeVarargs
Matrix(List<Double>... lists) {
matrix = new ArrayList<>()
for (List<Double> list : lists) {
matrix.add(list)
}
}
Matrix(List<List<Double>> mat) {
matrix = mat
}
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)
}
}
}
| #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;
}
|
Generate an equivalent C# version of this Groovy code. | class CramersRule {
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)
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
String toString() {
return matrix.toString()
}
@SafeVarargs
Matrix(List<Double>... lists) {
matrix = new ArrayList<>()
for (List<Double> list : lists) {
matrix.add(list)
}
}
Matrix(List<List<Double>> mat) {
matrix = mat
}
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)
}
}
}
| 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();
}
}
}
|
Please provide an equivalent version of this Groovy code in C++. | class CramersRule {
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)
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
String toString() {
return matrix.toString()
}
@SafeVarargs
Matrix(List<Double>... lists) {
matrix = new ArrayList<>()
for (List<Double> list : lists) {
matrix.add(list)
}
}
Matrix(List<List<Double>> mat) {
matrix = mat
}
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)
}
}
}
| #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;
}
|
Write a version of this Groovy function in Java with identical behavior. | class CramersRule {
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)
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
String toString() {
return matrix.toString()
}
@SafeVarargs
Matrix(List<Double>... lists) {
matrix = new ArrayList<>()
for (List<Double> list : lists) {
matrix.add(list)
}
}
Matrix(List<List<Double>> mat) {
matrix = mat
}
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)
}
}
}
| 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);
}
}
}
|
Generate an equivalent Python version of this Groovy code. | class CramersRule {
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)
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
String toString() {
return matrix.toString()
}
@SafeVarargs
Matrix(List<Double>... lists) {
matrix = new ArrayList<>()
for (List<Double> list : lists) {
matrix.add(list)
}
}
Matrix(List<List<Double>> mat) {
matrix = mat
}
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)
}
}
}
| 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)
|
Preserve the algorithm and functionality while converting the code from Groovy to VB. | class CramersRule {
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)
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
String toString() {
return matrix.toString()
}
@SafeVarargs
Matrix(List<Double>... lists) {
matrix = new ArrayList<>()
for (List<Double> list : lists) {
matrix.add(list)
}
}
Matrix(List<List<Double>> mat) {
matrix = mat
}
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)
}
}
}
| 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
|
Please provide an equivalent version of this Groovy code in Go. | class CramersRule {
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)
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
String toString() {
return matrix.toString()
}
@SafeVarargs
Matrix(List<Double>... lists) {
matrix = new ArrayList<>()
for (List<Double> list : lists) {
matrix.add(list)
}
}
Matrix(List<List<Double>> mat) {
matrix = mat
}
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)
}
}
}
| 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)
}
|
Ensure the translated C code behaves exactly like the original Haskell snippet. | import Data.Matrix
solveCramer :: (Ord a, Fractional a) => Matrix a -> Matrix a -> Maybe [a]
solveCramer a y
| da == 0 = Nothing
| otherwise = Just $ map (\i -> d i / da) [1..n]
where da = detLU a
d i = detLU $ submatrix 1 n 1 n $ switchCols i (n+1) ay
ay = a <|> y
n = ncols a
task = solveCramer a y
where a = fromLists [[2,-1, 5, 1]
,[3, 2, 2,-6]
,[1, 3, 3,-1]
,[5,-2,-3, 3]]
y = fromLists [[-3], [-32], [-47], [49]]
| #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;
}
|
Write the same code in C# as shown below in Haskell. | import Data.Matrix
solveCramer :: (Ord a, Fractional a) => Matrix a -> Matrix a -> Maybe [a]
solveCramer a y
| da == 0 = Nothing
| otherwise = Just $ map (\i -> d i / da) [1..n]
where da = detLU a
d i = detLU $ submatrix 1 n 1 n $ switchCols i (n+1) ay
ay = a <|> y
n = ncols a
task = solveCramer a y
where a = fromLists [[2,-1, 5, 1]
,[3, 2, 2,-6]
,[1, 3, 3,-1]
,[5,-2,-3, 3]]
y = fromLists [[-3], [-32], [-47], [49]]
| 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();
}
}
}
|
Ensure the translated C++ code behaves exactly like the original Haskell snippet. | import Data.Matrix
solveCramer :: (Ord a, Fractional a) => Matrix a -> Matrix a -> Maybe [a]
solveCramer a y
| da == 0 = Nothing
| otherwise = Just $ map (\i -> d i / da) [1..n]
where da = detLU a
d i = detLU $ submatrix 1 n 1 n $ switchCols i (n+1) ay
ay = a <|> y
n = ncols a
task = solveCramer a y
where a = fromLists [[2,-1, 5, 1]
,[3, 2, 2,-6]
,[1, 3, 3,-1]
,[5,-2,-3, 3]]
y = fromLists [[-3], [-32], [-47], [49]]
| #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. | import Data.Matrix
solveCramer :: (Ord a, Fractional a) => Matrix a -> Matrix a -> Maybe [a]
solveCramer a y
| da == 0 = Nothing
| otherwise = Just $ map (\i -> d i / da) [1..n]
where da = detLU a
d i = detLU $ submatrix 1 n 1 n $ switchCols i (n+1) ay
ay = a <|> y
n = ncols a
task = solveCramer a y
where a = fromLists [[2,-1, 5, 1]
,[3, 2, 2,-6]
,[1, 3, 3,-1]
,[5,-2,-3, 3]]
y = fromLists [[-3], [-32], [-47], [49]]
| 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);
}
}
}
|
Generate a Python translation of this Haskell snippet without changing its computational steps. | import Data.Matrix
solveCramer :: (Ord a, Fractional a) => Matrix a -> Matrix a -> Maybe [a]
solveCramer a y
| da == 0 = Nothing
| otherwise = Just $ map (\i -> d i / da) [1..n]
where da = detLU a
d i = detLU $ submatrix 1 n 1 n $ switchCols i (n+1) ay
ay = a <|> y
n = ncols a
task = solveCramer a y
where a = fromLists [[2,-1, 5, 1]
,[3, 2, 2,-6]
,[1, 3, 3,-1]
,[5,-2,-3, 3]]
y = fromLists [[-3], [-32], [-47], [49]]
| 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)
|
Rewrite the snippet below in VB so it works the same as the original Haskell code. | import Data.Matrix
solveCramer :: (Ord a, Fractional a) => Matrix a -> Matrix a -> Maybe [a]
solveCramer a y
| da == 0 = Nothing
| otherwise = Just $ map (\i -> d i / da) [1..n]
where da = detLU a
d i = detLU $ submatrix 1 n 1 n $ switchCols i (n+1) ay
ay = a <|> y
n = ncols a
task = solveCramer a y
where a = fromLists [[2,-1, 5, 1]
,[3, 2, 2,-6]
,[1, 3, 3,-1]
,[5,-2,-3, 3]]
y = fromLists [[-3], [-32], [-47], [49]]
| 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 Haskell version. | import Data.Matrix
solveCramer :: (Ord a, Fractional a) => Matrix a -> Matrix a -> Maybe [a]
solveCramer a y
| da == 0 = Nothing
| otherwise = Just $ map (\i -> d i / da) [1..n]
where da = detLU a
d i = detLU $ submatrix 1 n 1 n $ switchCols i (n+1) ay
ay = a <|> y
n = ncols a
task = solveCramer a y
where a = fromLists [[2,-1, 5, 1]
,[3, 2, 2,-6]
,[1, 3, 3,-1]
,[5,-2,-3, 3]]
y = fromLists [[-3], [-32], [-47], [49]]
| 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)
}
|
Convert this J snippet to C and keep its semantics consistent. | cramer=:4 :0
A=. x [ b=. y
det=. -/ .*
A %~&det (i.#A) b"_`[`]}&.|:"0 2 A
)
| #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;
}
|
Generate a C# translation of this J snippet without changing its computational steps. | cramer=:4 :0
A=. x [ b=. y
det=. -/ .*
A %~&det (i.#A) b"_`[`]}&.|:"0 2 A
)
| 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();
}
}
}
|
Generate a C++ translation of this J snippet without changing its computational steps. | cramer=:4 :0
A=. x [ b=. y
det=. -/ .*
A %~&det (i.#A) b"_`[`]}&.|:"0 2 A
)
| #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;
}
|
Generate an equivalent Java version of this J code. | cramer=:4 :0
A=. x [ b=. y
det=. -/ .*
A %~&det (i.#A) b"_`[`]}&.|:"0 2 A
)
| 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);
}
}
}
|
Rewrite this program in Python while keeping its functionality equivalent to the J version. | cramer=:4 :0
A=. x [ b=. y
det=. -/ .*
A %~&det (i.#A) b"_`[`]}&.|:"0 2 A
)
| 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)
|
Convert this J block to VB, preserving its control flow and logic. | cramer=:4 :0
A=. x [ b=. y
det=. -/ .*
A %~&det (i.#A) b"_`[`]}&.|:"0 2 A
)
| 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
|
Convert the following code from J to Go, ensuring the logic remains intact. | cramer=:4 :0
A=. x [ b=. y
det=. -/ .*
A %~&det (i.#A) b"_`[`]}&.|:"0 2 A
)
| 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 Julia version. | function cramersolve(A::Matrix, b::Vector)
return collect(begin B = copy(A); B[:, i] = b; det(B) end for i in eachindex(b)) ./ det(A)
end
A = [2 -1 5 1
3 2 2 -6
1 3 3 -1
5 -2 -3 3]
b = [-3, -32, -47, 49]
@show cramersolve(A, b)
| #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;
}
|
Rewrite the snippet below in C# so it works the same as the original Julia code. | function cramersolve(A::Matrix, b::Vector)
return collect(begin B = copy(A); B[:, i] = b; det(B) end for i in eachindex(b)) ./ det(A)
end
A = [2 -1 5 1
3 2 2 -6
1 3 3 -1
5 -2 -3 3]
b = [-3, -32, -47, 49]
@show cramersolve(A, b)
| 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();
}
}
}
|
Please provide an equivalent version of this Julia code in C++. | function cramersolve(A::Matrix, b::Vector)
return collect(begin B = copy(A); B[:, i] = b; det(B) end for i in eachindex(b)) ./ det(A)
end
A = [2 -1 5 1
3 2 2 -6
1 3 3 -1
5 -2 -3 3]
b = [-3, -32, -47, 49]
@show cramersolve(A, b)
| #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;
}
|
Write the same code in Java as shown below in Julia. | function cramersolve(A::Matrix, b::Vector)
return collect(begin B = copy(A); B[:, i] = b; det(B) end for i in eachindex(b)) ./ det(A)
end
A = [2 -1 5 1
3 2 2 -6
1 3 3 -1
5 -2 -3 3]
b = [-3, -32, -47, 49]
@show cramersolve(A, b)
| 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);
}
}
}
|
Convert this Julia block to Python, preserving its control flow and logic. | function cramersolve(A::Matrix, b::Vector)
return collect(begin B = copy(A); B[:, i] = b; det(B) end for i in eachindex(b)) ./ det(A)
end
A = [2 -1 5 1
3 2 2 -6
1 3 3 -1
5 -2 -3 3]
b = [-3, -32, -47, 49]
@show cramersolve(A, b)
| 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)
|
Rewrite the snippet below in VB so it works the same as the original Julia code. | function cramersolve(A::Matrix, b::Vector)
return collect(begin B = copy(A); B[:, i] = b; det(B) end for i in eachindex(b)) ./ det(A)
end
A = [2 -1 5 1
3 2 2 -6
1 3 3 -1
5 -2 -3 3]
b = [-3, -32, -47, 49]
@show cramersolve(A, b)
| 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
|
Keep all operations the same but rewrite the snippet in Go. | function cramersolve(A::Matrix, b::Vector)
return collect(begin B = copy(A); B[:, i] = b; det(B) end for i in eachindex(b)) ./ det(A)
end
A = [2 -1 5 1
3 2 2 -6
1 3 3 -1
5 -2 -3 3]
b = [-3, -32, -47, 49]
@show cramersolve(A, b)
| 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)
}
|
Write a version of this Lua function in C with identical behavior. | local matrix = require "matrix"
local function cramer(mat, vec)
assert(#mat == #mat[1], "Matrix is not square!")
assert(#mat == #vec, "Vector has not the same size of the matrix!")
local size = #mat
local main_det = matrix.det(mat)
local aux_mats = {}
local dets = {}
local result = {}
for i = 1, size do
aux_mats[i] = matrix.copy(mat)
for j = 1, size do
aux_mats[i][j][i] = vec[j]
end
dets[i] = matrix.det(aux_mats[i])
result[i] = dets[i]/main_det
end
return result
end
local A = {{ 2, -1, 5, 1},
{ 3, 2, 2, -6},
{ 1, 3, 3, -1},
{ 5, -2, -3, 3}}
local b = {-3, -32, -47, 49}
local result = cramer(A, b)
print("Result: " .. table.concat(result, ", "))
| #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;
}
|
Produce a functionally identical C# code for the snippet given in Lua. | local matrix = require "matrix"
local function cramer(mat, vec)
assert(#mat == #mat[1], "Matrix is not square!")
assert(#mat == #vec, "Vector has not the same size of the matrix!")
local size = #mat
local main_det = matrix.det(mat)
local aux_mats = {}
local dets = {}
local result = {}
for i = 1, size do
aux_mats[i] = matrix.copy(mat)
for j = 1, size do
aux_mats[i][j][i] = vec[j]
end
dets[i] = matrix.det(aux_mats[i])
result[i] = dets[i]/main_det
end
return result
end
local A = {{ 2, -1, 5, 1},
{ 3, 2, 2, -6},
{ 1, 3, 3, -1},
{ 5, -2, -3, 3}}
local b = {-3, -32, -47, 49}
local result = cramer(A, b)
print("Result: " .. table.concat(result, ", "))
| 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();
}
}
}
|
Preserve the algorithm and functionality while converting the code from Lua to C++. | local matrix = require "matrix"
local function cramer(mat, vec)
assert(#mat == #mat[1], "Matrix is not square!")
assert(#mat == #vec, "Vector has not the same size of the matrix!")
local size = #mat
local main_det = matrix.det(mat)
local aux_mats = {}
local dets = {}
local result = {}
for i = 1, size do
aux_mats[i] = matrix.copy(mat)
for j = 1, size do
aux_mats[i][j][i] = vec[j]
end
dets[i] = matrix.det(aux_mats[i])
result[i] = dets[i]/main_det
end
return result
end
local A = {{ 2, -1, 5, 1},
{ 3, 2, 2, -6},
{ 1, 3, 3, -1},
{ 5, -2, -3, 3}}
local b = {-3, -32, -47, 49}
local result = cramer(A, b)
print("Result: " .. table.concat(result, ", "))
| #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;
}
|
Can you help me rewrite this code in Java instead of Lua, keeping it the same logically? | local matrix = require "matrix"
local function cramer(mat, vec)
assert(#mat == #mat[1], "Matrix is not square!")
assert(#mat == #vec, "Vector has not the same size of the matrix!")
local size = #mat
local main_det = matrix.det(mat)
local aux_mats = {}
local dets = {}
local result = {}
for i = 1, size do
aux_mats[i] = matrix.copy(mat)
for j = 1, size do
aux_mats[i][j][i] = vec[j]
end
dets[i] = matrix.det(aux_mats[i])
result[i] = dets[i]/main_det
end
return result
end
local A = {{ 2, -1, 5, 1},
{ 3, 2, 2, -6},
{ 1, 3, 3, -1},
{ 5, -2, -3, 3}}
local b = {-3, -32, -47, 49}
local result = cramer(A, b)
print("Result: " .. table.concat(result, ", "))
| 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);
}
}
}
|
Produce a functionally identical Python code for the snippet given in Lua. | local matrix = require "matrix"
local function cramer(mat, vec)
assert(#mat == #mat[1], "Matrix is not square!")
assert(#mat == #vec, "Vector has not the same size of the matrix!")
local size = #mat
local main_det = matrix.det(mat)
local aux_mats = {}
local dets = {}
local result = {}
for i = 1, size do
aux_mats[i] = matrix.copy(mat)
for j = 1, size do
aux_mats[i][j][i] = vec[j]
end
dets[i] = matrix.det(aux_mats[i])
result[i] = dets[i]/main_det
end
return result
end
local A = {{ 2, -1, 5, 1},
{ 3, 2, 2, -6},
{ 1, 3, 3, -1},
{ 5, -2, -3, 3}}
local b = {-3, -32, -47, 49}
local result = cramer(A, b)
print("Result: " .. table.concat(result, ", "))
| 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)
|
Keep all operations the same but rewrite the snippet in VB. | local matrix = require "matrix"
local function cramer(mat, vec)
assert(#mat == #mat[1], "Matrix is not square!")
assert(#mat == #vec, "Vector has not the same size of the matrix!")
local size = #mat
local main_det = matrix.det(mat)
local aux_mats = {}
local dets = {}
local result = {}
for i = 1, size do
aux_mats[i] = matrix.copy(mat)
for j = 1, size do
aux_mats[i][j][i] = vec[j]
end
dets[i] = matrix.det(aux_mats[i])
result[i] = dets[i]/main_det
end
return result
end
local A = {{ 2, -1, 5, 1},
{ 3, 2, 2, -6},
{ 1, 3, 3, -1},
{ 5, -2, -3, 3}}
local b = {-3, -32, -47, 49}
local result = cramer(A, b)
print("Result: " .. table.concat(result, ", "))
| 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 Lua function in Go with identical behavior. | local matrix = require "matrix"
local function cramer(mat, vec)
assert(#mat == #mat[1], "Matrix is not square!")
assert(#mat == #vec, "Vector has not the same size of the matrix!")
local size = #mat
local main_det = matrix.det(mat)
local aux_mats = {}
local dets = {}
local result = {}
for i = 1, size do
aux_mats[i] = matrix.copy(mat)
for j = 1, size do
aux_mats[i][j][i] = vec[j]
end
dets[i] = matrix.det(aux_mats[i])
result[i] = dets[i]/main_det
end
return result
end
local A = {{ 2, -1, 5, 1},
{ 3, 2, 2, -6},
{ 1, 3, 3, -1},
{ 5, -2, -3, 3}}
local b = {-3, -32, -47, 49}
local result = cramer(A, b)
print("Result: " .. table.concat(result, ", "))
| 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)
}
|
Please provide an equivalent version of this Mathematica code in C. | crule[m_, b_] := Module[{d = Det[m], a},
Table[a = m; a[[All, k]] = b; Det[a]/d, {k, Length[m]}]]
crule[{
{2, -1, 5, 1},
{3, 2, 2, -6},
{1, 3, 3, -1},
{5, -2, -3, 3}
} , {-3, -32, -47, 49}]
| #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;
}
|
Convert this Mathematica block to C#, preserving its control flow and logic. | crule[m_, b_] := Module[{d = Det[m], a},
Table[a = m; a[[All, k]] = b; Det[a]/d, {k, Length[m]}]]
crule[{
{2, -1, 5, 1},
{3, 2, 2, -6},
{1, 3, 3, -1},
{5, -2, -3, 3}
} , {-3, -32, -47, 49}]
| 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();
}
}
}
|
Change the following Mathematica code into C++ without altering its purpose. | crule[m_, b_] := Module[{d = Det[m], a},
Table[a = m; a[[All, k]] = b; Det[a]/d, {k, Length[m]}]]
crule[{
{2, -1, 5, 1},
{3, 2, 2, -6},
{1, 3, 3, -1},
{5, -2, -3, 3}
} , {-3, -32, -47, 49}]
| #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;
}
|
Write a version of this Mathematica function in Java with identical behavior. | crule[m_, b_] := Module[{d = Det[m], a},
Table[a = m; a[[All, k]] = b; Det[a]/d, {k, Length[m]}]]
crule[{
{2, -1, 5, 1},
{3, 2, 2, -6},
{1, 3, 3, -1},
{5, -2, -3, 3}
} , {-3, -32, -47, 49}]
| 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);
}
}
}
|
Generate a Python translation of this Mathematica snippet without changing its computational steps. | crule[m_, b_] := Module[{d = Det[m], a},
Table[a = m; a[[All, k]] = b; Det[a]/d, {k, Length[m]}]]
crule[{
{2, -1, 5, 1},
{3, 2, 2, -6},
{1, 3, 3, -1},
{5, -2, -3, 3}
} , {-3, -32, -47, 49}]
| 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)
|
Change the following Mathematica code into VB without altering its purpose. | crule[m_, b_] := Module[{d = Det[m], a},
Table[a = m; a[[All, k]] = b; Det[a]/d, {k, Length[m]}]]
crule[{
{2, -1, 5, 1},
{3, 2, 2, -6},
{1, 3, 3, -1},
{5, -2, -3, 3}
} , {-3, -32, -47, 49}]
| 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
|
Can you help me rewrite this code in Go instead of Mathematica, keeping it the same logically? | crule[m_, b_] := Module[{d = Det[m], a},
Table[a = m; a[[All, k]] = b; Det[a]/d, {k, Length[m]}]]
crule[{
{2, -1, 5, 1},
{3, 2, 2, -6},
{1, 3, 3, -1},
{5, -2, -3, 3}
} , {-3, -32, -47, 49}]
| 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)
}
|
Ensure the translated C code behaves exactly like the original Nim snippet. | type
SquareMatrix[N: static Positive] = array[N, array[N, float]]
Vector[N: static Positive] = array[N, float]
template `[]`(m: SquareMatrix; i, j: Natural): float =
m[i][j]
template `[]=`(m: var SquareMatrix; i, j: Natural; val: float) =
m[i][j] = val
func det(m: SquareMatrix): float =
var m = m
result = 1
for j in 0..m.high:
var imax = j
for i in (j + 1)..m.high:
if m[i, j] > m[imax, j]:
imax = i
if imax != j:
swap m[iMax], m[j]
result = -result
if abs(m[j, j]) < 1e-12:
return NaN
for i in (j + 1)..m.high:
let mult = -m[i, j] / m[j, j]
for k in 0..m.high:
m[i, k] += mult * m[j, k]
for i in 0..m.high:
result *= m[i, i]
func cramerSolve(a: SquareMatrix; detA: float; b: Vector; col: Natural): float =
when a.N != b.N:
{.error: "incompatible matrix and vector sizes".}
else:
var a = a
for i in 0..a.high:
a[i, col] = b[i]
result = det(a) / detA
import strformat
const
A: SquareMatrix[4] = [[2.0, -1.0, 5.0, 1.0],
[3.0, 2.0, 2.0, -6.0],
[1.0, 3.0, 3.0, -1.0],
[5.0, -2.0, -3.0, 3.0]]
B: Vector[4] = [-3.0, -32.0, -47.0, 49.0]
let detA = det(A)
if detA == NaN:
echo "Singular matrix!"
quit(QuitFailure)
for i in 0..A.high:
echo &"{cramerSolve(A, detA, B, i):7.3f}"
| #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;
}
|
Rewrite the snippet below in C# so it works the same as the original Nim code. | type
SquareMatrix[N: static Positive] = array[N, array[N, float]]
Vector[N: static Positive] = array[N, float]
template `[]`(m: SquareMatrix; i, j: Natural): float =
m[i][j]
template `[]=`(m: var SquareMatrix; i, j: Natural; val: float) =
m[i][j] = val
func det(m: SquareMatrix): float =
var m = m
result = 1
for j in 0..m.high:
var imax = j
for i in (j + 1)..m.high:
if m[i, j] > m[imax, j]:
imax = i
if imax != j:
swap m[iMax], m[j]
result = -result
if abs(m[j, j]) < 1e-12:
return NaN
for i in (j + 1)..m.high:
let mult = -m[i, j] / m[j, j]
for k in 0..m.high:
m[i, k] += mult * m[j, k]
for i in 0..m.high:
result *= m[i, i]
func cramerSolve(a: SquareMatrix; detA: float; b: Vector; col: Natural): float =
when a.N != b.N:
{.error: "incompatible matrix and vector sizes".}
else:
var a = a
for i in 0..a.high:
a[i, col] = b[i]
result = det(a) / detA
import strformat
const
A: SquareMatrix[4] = [[2.0, -1.0, 5.0, 1.0],
[3.0, 2.0, 2.0, -6.0],
[1.0, 3.0, 3.0, -1.0],
[5.0, -2.0, -3.0, 3.0]]
B: Vector[4] = [-3.0, -32.0, -47.0, 49.0]
let detA = det(A)
if detA == NaN:
echo "Singular matrix!"
quit(QuitFailure)
for i in 0..A.high:
echo &"{cramerSolve(A, detA, B, i):7.3f}"
| 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();
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C++. | type
SquareMatrix[N: static Positive] = array[N, array[N, float]]
Vector[N: static Positive] = array[N, float]
template `[]`(m: SquareMatrix; i, j: Natural): float =
m[i][j]
template `[]=`(m: var SquareMatrix; i, j: Natural; val: float) =
m[i][j] = val
func det(m: SquareMatrix): float =
var m = m
result = 1
for j in 0..m.high:
var imax = j
for i in (j + 1)..m.high:
if m[i, j] > m[imax, j]:
imax = i
if imax != j:
swap m[iMax], m[j]
result = -result
if abs(m[j, j]) < 1e-12:
return NaN
for i in (j + 1)..m.high:
let mult = -m[i, j] / m[j, j]
for k in 0..m.high:
m[i, k] += mult * m[j, k]
for i in 0..m.high:
result *= m[i, i]
func cramerSolve(a: SquareMatrix; detA: float; b: Vector; col: Natural): float =
when a.N != b.N:
{.error: "incompatible matrix and vector sizes".}
else:
var a = a
for i in 0..a.high:
a[i, col] = b[i]
result = det(a) / detA
import strformat
const
A: SquareMatrix[4] = [[2.0, -1.0, 5.0, 1.0],
[3.0, 2.0, 2.0, -6.0],
[1.0, 3.0, 3.0, -1.0],
[5.0, -2.0, -3.0, 3.0]]
B: Vector[4] = [-3.0, -32.0, -47.0, 49.0]
let detA = det(A)
if detA == NaN:
echo "Singular matrix!"
quit(QuitFailure)
for i in 0..A.high:
echo &"{cramerSolve(A, detA, B, i):7.3f}"
| #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 this program into Java but keep the logic exactly as in Nim. | type
SquareMatrix[N: static Positive] = array[N, array[N, float]]
Vector[N: static Positive] = array[N, float]
template `[]`(m: SquareMatrix; i, j: Natural): float =
m[i][j]
template `[]=`(m: var SquareMatrix; i, j: Natural; val: float) =
m[i][j] = val
func det(m: SquareMatrix): float =
var m = m
result = 1
for j in 0..m.high:
var imax = j
for i in (j + 1)..m.high:
if m[i, j] > m[imax, j]:
imax = i
if imax != j:
swap m[iMax], m[j]
result = -result
if abs(m[j, j]) < 1e-12:
return NaN
for i in (j + 1)..m.high:
let mult = -m[i, j] / m[j, j]
for k in 0..m.high:
m[i, k] += mult * m[j, k]
for i in 0..m.high:
result *= m[i, i]
func cramerSolve(a: SquareMatrix; detA: float; b: Vector; col: Natural): float =
when a.N != b.N:
{.error: "incompatible matrix and vector sizes".}
else:
var a = a
for i in 0..a.high:
a[i, col] = b[i]
result = det(a) / detA
import strformat
const
A: SquareMatrix[4] = [[2.0, -1.0, 5.0, 1.0],
[3.0, 2.0, 2.0, -6.0],
[1.0, 3.0, 3.0, -1.0],
[5.0, -2.0, -3.0, 3.0]]
B: Vector[4] = [-3.0, -32.0, -47.0, 49.0]
let detA = det(A)
if detA == NaN:
echo "Singular matrix!"
quit(QuitFailure)
for i in 0..A.high:
echo &"{cramerSolve(A, detA, B, i):7.3f}"
| 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);
}
}
}
|
Generate a Python translation of this Nim snippet without changing its computational steps. | type
SquareMatrix[N: static Positive] = array[N, array[N, float]]
Vector[N: static Positive] = array[N, float]
template `[]`(m: SquareMatrix; i, j: Natural): float =
m[i][j]
template `[]=`(m: var SquareMatrix; i, j: Natural; val: float) =
m[i][j] = val
func det(m: SquareMatrix): float =
var m = m
result = 1
for j in 0..m.high:
var imax = j
for i in (j + 1)..m.high:
if m[i, j] > m[imax, j]:
imax = i
if imax != j:
swap m[iMax], m[j]
result = -result
if abs(m[j, j]) < 1e-12:
return NaN
for i in (j + 1)..m.high:
let mult = -m[i, j] / m[j, j]
for k in 0..m.high:
m[i, k] += mult * m[j, k]
for i in 0..m.high:
result *= m[i, i]
func cramerSolve(a: SquareMatrix; detA: float; b: Vector; col: Natural): float =
when a.N != b.N:
{.error: "incompatible matrix and vector sizes".}
else:
var a = a
for i in 0..a.high:
a[i, col] = b[i]
result = det(a) / detA
import strformat
const
A: SquareMatrix[4] = [[2.0, -1.0, 5.0, 1.0],
[3.0, 2.0, 2.0, -6.0],
[1.0, 3.0, 3.0, -1.0],
[5.0, -2.0, -3.0, 3.0]]
B: Vector[4] = [-3.0, -32.0, -47.0, 49.0]
let detA = det(A)
if detA == NaN:
echo "Singular matrix!"
quit(QuitFailure)
for i in 0..A.high:
echo &"{cramerSolve(A, detA, B, i):7.3f}"
| 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 Nim code in VB. | type
SquareMatrix[N: static Positive] = array[N, array[N, float]]
Vector[N: static Positive] = array[N, float]
template `[]`(m: SquareMatrix; i, j: Natural): float =
m[i][j]
template `[]=`(m: var SquareMatrix; i, j: Natural; val: float) =
m[i][j] = val
func det(m: SquareMatrix): float =
var m = m
result = 1
for j in 0..m.high:
var imax = j
for i in (j + 1)..m.high:
if m[i, j] > m[imax, j]:
imax = i
if imax != j:
swap m[iMax], m[j]
result = -result
if abs(m[j, j]) < 1e-12:
return NaN
for i in (j + 1)..m.high:
let mult = -m[i, j] / m[j, j]
for k in 0..m.high:
m[i, k] += mult * m[j, k]
for i in 0..m.high:
result *= m[i, i]
func cramerSolve(a: SquareMatrix; detA: float; b: Vector; col: Natural): float =
when a.N != b.N:
{.error: "incompatible matrix and vector sizes".}
else:
var a = a
for i in 0..a.high:
a[i, col] = b[i]
result = det(a) / detA
import strformat
const
A: SquareMatrix[4] = [[2.0, -1.0, 5.0, 1.0],
[3.0, 2.0, 2.0, -6.0],
[1.0, 3.0, 3.0, -1.0],
[5.0, -2.0, -3.0, 3.0]]
B: Vector[4] = [-3.0, -32.0, -47.0, 49.0]
let detA = det(A)
if detA == NaN:
echo "Singular matrix!"
quit(QuitFailure)
for i in 0..A.high:
echo &"{cramerSolve(A, detA, B, i):7.3f}"
| 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
|
Generate a Go translation of this Nim snippet without changing its computational steps. | type
SquareMatrix[N: static Positive] = array[N, array[N, float]]
Vector[N: static Positive] = array[N, float]
template `[]`(m: SquareMatrix; i, j: Natural): float =
m[i][j]
template `[]=`(m: var SquareMatrix; i, j: Natural; val: float) =
m[i][j] = val
func det(m: SquareMatrix): float =
var m = m
result = 1
for j in 0..m.high:
var imax = j
for i in (j + 1)..m.high:
if m[i, j] > m[imax, j]:
imax = i
if imax != j:
swap m[iMax], m[j]
result = -result
if abs(m[j, j]) < 1e-12:
return NaN
for i in (j + 1)..m.high:
let mult = -m[i, j] / m[j, j]
for k in 0..m.high:
m[i, k] += mult * m[j, k]
for i in 0..m.high:
result *= m[i, i]
func cramerSolve(a: SquareMatrix; detA: float; b: Vector; col: Natural): float =
when a.N != b.N:
{.error: "incompatible matrix and vector sizes".}
else:
var a = a
for i in 0..a.high:
a[i, col] = b[i]
result = det(a) / detA
import strformat
const
A: SquareMatrix[4] = [[2.0, -1.0, 5.0, 1.0],
[3.0, 2.0, 2.0, -6.0],
[1.0, 3.0, 3.0, -1.0],
[5.0, -2.0, -3.0, 3.0]]
B: Vector[4] = [-3.0, -32.0, -47.0, 49.0]
let detA = det(A)
if detA == NaN:
echo "Singular matrix!"
quit(QuitFailure)
for i in 0..A.high:
echo &"{cramerSolve(A, detA, B, i):7.3f}"
| 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)
}
|
Convert this Perl snippet to C and keep its semantics consistent. | use Math::Matrix;
sub cramers_rule {
my ($A, $terms) = @_;
my @solutions;
my $det = $A->determinant;
foreach my $i (0 .. $
my $Ai = $A->clone;
foreach my $j (0 .. $
$Ai->[$j][$i] = $terms->[$j];
}
push @solutions, $Ai->determinant / $det;
}
@solutions;
}
my $matrix = Math::Matrix->new(
[2, -1, 5, 1],
[3, 2, 2, -6],
[1, 3, 3, -1],
[5, -2, -3, 3],
);
my $free_terms = [-3, -32, -47, 49];
my ($w, $x, $y, $z) = cramers_rule($matrix, $free_terms);
print "w = $w\n";
print "x = $x\n";
print "y = $y\n";
print "z = $z\n";
| #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 Perl code into C# while preserving the original functionality. | use Math::Matrix;
sub cramers_rule {
my ($A, $terms) = @_;
my @solutions;
my $det = $A->determinant;
foreach my $i (0 .. $
my $Ai = $A->clone;
foreach my $j (0 .. $
$Ai->[$j][$i] = $terms->[$j];
}
push @solutions, $Ai->determinant / $det;
}
@solutions;
}
my $matrix = Math::Matrix->new(
[2, -1, 5, 1],
[3, 2, 2, -6],
[1, 3, 3, -1],
[5, -2, -3, 3],
);
my $free_terms = [-3, -32, -47, 49];
my ($w, $x, $y, $z) = cramers_rule($matrix, $free_terms);
print "w = $w\n";
print "x = $x\n";
print "y = $y\n";
print "z = $z\n";
| 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();
}
}
}
|
Write a version of this Perl function in C++ with identical behavior. | use Math::Matrix;
sub cramers_rule {
my ($A, $terms) = @_;
my @solutions;
my $det = $A->determinant;
foreach my $i (0 .. $
my $Ai = $A->clone;
foreach my $j (0 .. $
$Ai->[$j][$i] = $terms->[$j];
}
push @solutions, $Ai->determinant / $det;
}
@solutions;
}
my $matrix = Math::Matrix->new(
[2, -1, 5, 1],
[3, 2, 2, -6],
[1, 3, 3, -1],
[5, -2, -3, 3],
);
my $free_terms = [-3, -32, -47, 49];
my ($w, $x, $y, $z) = cramers_rule($matrix, $free_terms);
print "w = $w\n";
print "x = $x\n";
print "y = $y\n";
print "z = $z\n";
| #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;
}
|
Port the provided Perl code into Java while preserving the original functionality. | use Math::Matrix;
sub cramers_rule {
my ($A, $terms) = @_;
my @solutions;
my $det = $A->determinant;
foreach my $i (0 .. $
my $Ai = $A->clone;
foreach my $j (0 .. $
$Ai->[$j][$i] = $terms->[$j];
}
push @solutions, $Ai->determinant / $det;
}
@solutions;
}
my $matrix = Math::Matrix->new(
[2, -1, 5, 1],
[3, 2, 2, -6],
[1, 3, 3, -1],
[5, -2, -3, 3],
);
my $free_terms = [-3, -32, -47, 49];
my ($w, $x, $y, $z) = cramers_rule($matrix, $free_terms);
print "w = $w\n";
print "x = $x\n";
print "y = $y\n";
print "z = $z\n";
| 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);
}
}
}
|
Generate an equivalent Python version of this Perl code. | use Math::Matrix;
sub cramers_rule {
my ($A, $terms) = @_;
my @solutions;
my $det = $A->determinant;
foreach my $i (0 .. $
my $Ai = $A->clone;
foreach my $j (0 .. $
$Ai->[$j][$i] = $terms->[$j];
}
push @solutions, $Ai->determinant / $det;
}
@solutions;
}
my $matrix = Math::Matrix->new(
[2, -1, 5, 1],
[3, 2, 2, -6],
[1, 3, 3, -1],
[5, -2, -3, 3],
);
my $free_terms = [-3, -32, -47, 49];
my ($w, $x, $y, $z) = cramers_rule($matrix, $free_terms);
print "w = $w\n";
print "x = $x\n";
print "y = $y\n";
print "z = $z\n";
| 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)
|
Can you help me rewrite this code in VB instead of Perl, keeping it the same logically? | use Math::Matrix;
sub cramers_rule {
my ($A, $terms) = @_;
my @solutions;
my $det = $A->determinant;
foreach my $i (0 .. $
my $Ai = $A->clone;
foreach my $j (0 .. $
$Ai->[$j][$i] = $terms->[$j];
}
push @solutions, $Ai->determinant / $det;
}
@solutions;
}
my $matrix = Math::Matrix->new(
[2, -1, 5, 1],
[3, 2, 2, -6],
[1, 3, 3, -1],
[5, -2, -3, 3],
);
my $free_terms = [-3, -32, -47, 49];
my ($w, $x, $y, $z) = cramers_rule($matrix, $free_terms);
print "w = $w\n";
print "x = $x\n";
print "y = $y\n";
print "z = $z\n";
| 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
|
Can you help me rewrite this code in Go instead of Perl, keeping it the same logically? | use Math::Matrix;
sub cramers_rule {
my ($A, $terms) = @_;
my @solutions;
my $det = $A->determinant;
foreach my $i (0 .. $
my $Ai = $A->clone;
foreach my $j (0 .. $
$Ai->[$j][$i] = $terms->[$j];
}
push @solutions, $Ai->determinant / $det;
}
@solutions;
}
my $matrix = Math::Matrix->new(
[2, -1, 5, 1],
[3, 2, 2, -6],
[1, 3, 3, -1],
[5, -2, -3, 3],
);
my $free_terms = [-3, -32, -47, 49];
my ($w, $x, $y, $z) = cramers_rule($matrix, $free_terms);
print "w = $w\n";
print "x = $x\n";
print "y = $y\n";
print "z = $z\n";
| 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)
}
|
Convert this Racket block to C, preserving its control flow and logic. | #lang racket
(require math/matrix)
(define sys
(matrix [[2 -1 5 1]
[3 2 2 -6]
[1 3 3 -1]
[5 -2 -3 3]]))
(define soln
(col-matrix [-3 -32 -47 49]))
(define (matrix-set-column M new-col idx)
(matrix-augment (list-set (matrix-cols M) idx new-col)))
(define (cramers-rule M soln)
(let ([denom (matrix-determinant M)]
[nvars (matrix-num-cols M)])
(letrec ([roots (λ (position)
(if (>= position nvars)
'()
(cons (/ (matrix-determinant
(matrix-set-column M soln position))
denom)
(roots (add1 position)))))])
(map cons '(w x y z) (roots 0)))))
(cramers-rule sys soln)
| #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;
}
|
Generate an equivalent C# version of this Racket code. | #lang racket
(require math/matrix)
(define sys
(matrix [[2 -1 5 1]
[3 2 2 -6]
[1 3 3 -1]
[5 -2 -3 3]]))
(define soln
(col-matrix [-3 -32 -47 49]))
(define (matrix-set-column M new-col idx)
(matrix-augment (list-set (matrix-cols M) idx new-col)))
(define (cramers-rule M soln)
(let ([denom (matrix-determinant M)]
[nvars (matrix-num-cols M)])
(letrec ([roots (λ (position)
(if (>= position nvars)
'()
(cons (/ (matrix-determinant
(matrix-set-column M soln position))
denom)
(roots (add1 position)))))])
(map cons '(w x y z) (roots 0)))))
(cramers-rule sys soln)
| 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();
}
}
}
|
Convert the following code from Racket to C++, ensuring the logic remains intact. | #lang racket
(require math/matrix)
(define sys
(matrix [[2 -1 5 1]
[3 2 2 -6]
[1 3 3 -1]
[5 -2 -3 3]]))
(define soln
(col-matrix [-3 -32 -47 49]))
(define (matrix-set-column M new-col idx)
(matrix-augment (list-set (matrix-cols M) idx new-col)))
(define (cramers-rule M soln)
(let ([denom (matrix-determinant M)]
[nvars (matrix-num-cols M)])
(letrec ([roots (λ (position)
(if (>= position nvars)
'()
(cons (/ (matrix-determinant
(matrix-set-column M soln position))
denom)
(roots (add1 position)))))])
(map cons '(w x y z) (roots 0)))))
(cramers-rule sys soln)
| #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 Racket. | #lang racket
(require math/matrix)
(define sys
(matrix [[2 -1 5 1]
[3 2 2 -6]
[1 3 3 -1]
[5 -2 -3 3]]))
(define soln
(col-matrix [-3 -32 -47 49]))
(define (matrix-set-column M new-col idx)
(matrix-augment (list-set (matrix-cols M) idx new-col)))
(define (cramers-rule M soln)
(let ([denom (matrix-determinant M)]
[nvars (matrix-num-cols M)])
(letrec ([roots (λ (position)
(if (>= position nvars)
'()
(cons (/ (matrix-determinant
(matrix-set-column M soln position))
denom)
(roots (add1 position)))))])
(map cons '(w x y z) (roots 0)))))
(cramers-rule sys soln)
| 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);
}
}
}
|
Transform the following Racket implementation into Python, maintaining the same output and logic. | #lang racket
(require math/matrix)
(define sys
(matrix [[2 -1 5 1]
[3 2 2 -6]
[1 3 3 -1]
[5 -2 -3 3]]))
(define soln
(col-matrix [-3 -32 -47 49]))
(define (matrix-set-column M new-col idx)
(matrix-augment (list-set (matrix-cols M) idx new-col)))
(define (cramers-rule M soln)
(let ([denom (matrix-determinant M)]
[nvars (matrix-num-cols M)])
(letrec ([roots (λ (position)
(if (>= position nvars)
'()
(cons (/ (matrix-determinant
(matrix-set-column M soln position))
denom)
(roots (add1 position)))))])
(map cons '(w x y z) (roots 0)))))
(cramers-rule sys soln)
| 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)
|
Rewrite this program in VB while keeping its functionality equivalent to the Racket version. | #lang racket
(require math/matrix)
(define sys
(matrix [[2 -1 5 1]
[3 2 2 -6]
[1 3 3 -1]
[5 -2 -3 3]]))
(define soln
(col-matrix [-3 -32 -47 49]))
(define (matrix-set-column M new-col idx)
(matrix-augment (list-set (matrix-cols M) idx new-col)))
(define (cramers-rule M soln)
(let ([denom (matrix-determinant M)]
[nvars (matrix-num-cols M)])
(letrec ([roots (λ (position)
(if (>= position nvars)
'()
(cons (/ (matrix-determinant
(matrix-set-column M soln position))
denom)
(roots (add1 position)))))])
(map cons '(w x y z) (roots 0)))))
(cramers-rule sys soln)
| 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 Racket to Go. | #lang racket
(require math/matrix)
(define sys
(matrix [[2 -1 5 1]
[3 2 2 -6]
[1 3 3 -1]
[5 -2 -3 3]]))
(define soln
(col-matrix [-3 -32 -47 49]))
(define (matrix-set-column M new-col idx)
(matrix-augment (list-set (matrix-cols M) idx new-col)))
(define (cramers-rule M soln)
(let ([denom (matrix-determinant M)]
[nvars (matrix-num-cols M)])
(letrec ([roots (λ (position)
(if (>= position nvars)
'()
(cons (/ (matrix-determinant
(matrix-set-column M soln position))
denom)
(roots (add1 position)))))])
(map cons '(w x y z) (roots 0)))))
(cramers-rule sys soln)
| 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)
}
|
Port the provided REXX code into C while preserving the original functionality. |
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 <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;
}
|
Write a version of this REXX function in C# with identical 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
| 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();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.