Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Can you help me rewrite this code in PHP instead of Ada, keeping it the same logically? | procedure Array_Collection is
A : array (-3 .. -1) of Integer := (1, 2, 3);
begin
A (-3) := 3;
A (-2) := 2;
A (-1) := 1;
end Array_Collection;
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Rewrite this program in PHP while keeping its functionality equivalent to the Arturo version. |
arr: ["one" 2 "three" "four"]
arr: arr ++ 5
print arr
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Port the provided AutoHotKey code into PHP while preserving the original functionality. | myCol := Object()
mycol.mykey := "my value!"
mycol["mykey"] := "new val!"
MsgBox % mycol.mykey
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Write the same algorithm in PHP as shown in this AWK implementation. | a[0]="hello"
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Maintain the same structure and functionality when rewriting this code in PHP. | DIM text$(1)
text$(0) = "Hello "
text$(1) = "world!"
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Translate this program into PHP but keep the logic exactly as in Clojure. | {1 "a", "Q" 10}
(hash-map 1 "a" "Q" 10)
(let [my-map {1 "a"}]
(assoc my-map "Q" 10))
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Translate this program into PHP but keep the logic exactly as in Common_Lisp. | CL-USER> (let ((list '())
(hash-table (make-hash-table)))
(push 1 list)
(push 2 list)
(push 3 list)
(format t "~S~%" (reverse list))
(setf (gethash 'foo hash-table) 42)
(setf (gethash 'bar hash-table) 69)
(maphash (lambda (key value)
(format t "~S => ~S~%" key value))
hash-table)
(write hash-table :readably t)
(describe hash-table)
(describe list))
(1 2 3)
FOO => 42
BAR => 69
#.(SB-IMPL::%STUFF-HASH-TABLE
(MAKE-HASH-TABLE :TEST 'EQL :SIZE '16 :REHASH-SIZE '1.5
:REHASH-THRESHOLD '1.0 :WEAKNESS 'NIL)
'((BAR . 69) (FOO . 42)))
#<HASH-TABLE :TEST EQL :COUNT 2 {1002B6F391}>
[hash-table]
Occupancy: 0.1
Rehash-threshold: 1.0
Rehash-size: 1.5
Size: 16
Synchronized: no
(3 2 1)
[list]
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Translate the given D code snippet into PHP without altering its behavior. | int[3] array;
array[0] = 5;
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Ensure the translated PHP code behaves exactly like the original Delphi snippet. |
var
intArray: TArray<Integer> = [1, 2, 3, 4, 5];
intArray2: array of Integer = [1, 2, 3, 4, 5];
intArray3: array [0..4]of Integer;
intArray4: array [10..14]of Integer;
procedure
var
intArray5: TArray<Integer>;
begin
intArray := [1,2,3];
intArray2 := [1,2,3];
intArray[0] := 1;
SetLength(intArray,5);
var intArray6 := [1, 2, 3];
var intArray7: TArray<Integer> := [1, 2, 3];
end;
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Translate this program into PHP but keep the logic exactly as in Elixir. | empty_list = []
list = [1,2,3,4,5]
length(list)
[0 | list]
hd(list)
tl(list)
Enum.at(list,3)
list ++ [6,7]
list -- [4,2]
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Produce a functionally identical PHP code for the snippet given in Factor. | USING: assocs deques dlists lists lists.lazy sequences sets ;
{ 1 2 "foo" 3 }
[ 1 2 3 + * ]
"Hello, world
B{ 1 2 3 }
?{ f t t }
{ 1 2 3 } 4 suffix
{ 1 2 3 } { 4 5 6 } append
{ 1 1 2 3 } { 2 5 7 8 } intersect
"Hello" { } like
{ 72 101 108 108 111 } "" like
V{ 1 2 "foo" 3 }
BV{ 1 2 255 }
SBUF" Hello, world
V{ 1 2 3 } 4 suffix
V{ 1 2 3 } { 4 5 6 } append
V{ 1 2 3 } pop
{ { "hamburger" 150 } { "soda" 99 } { "fries" 99 } }
H{ { 1 "a" } { 2 "b" } }
3 "c" H{ { 1 "a" } { 2 "b" } } [ set-at ] keep
T{ cons-state f 1 +nil+ }
T{ cons-state { car 1 } { cdr +nil+ } }
1 2 3 4 +nil+ cons cons cons cons
1 2 2list
{ 1 2 3 4 } sequence>list
0 lfrom
0 [ 2 + ] lfrom-by
DL{ 1 2 3 }
3 DL{ 1 2 } [ push-front ] keep
3 DL{ 1 2 } [ push-back ] keep
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Keep all operations the same but rewrite the snippet in PHP. | include ffl/car.fs
10 car-create ar
2 0 ar car-set
3 1 ar car-set
1 0 ar car-insert
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Keep all operations the same but rewrite the snippet in PHP. | REAL A(36)
A(1) = 1
A(2) = 3*A(1) + 5
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Translate the given Groovy code snippet into PHP without altering its behavior. | def emptyList = []
assert emptyList.isEmpty() : "These are not the items you're looking for"
assert emptyList.size() == 0 : "Empty list has size 0"
assert ! emptyList : "Empty list evaluates as boolean 'false'"
def initializedList = [ 1, "b", java.awt.Color.BLUE ]
assert initializedList.size() == 3
assert initializedList : "Non-empty list evaluates as boolean 'true'"
assert initializedList[2] == java.awt.Color.BLUE : "referencing a single element (zero-based indexing)"
assert initializedList[-1] == java.awt.Color.BLUE : "referencing a single element (reverse indexing of last element)"
def combinedList = initializedList + [ "more stuff", "even more stuff" ]
assert combinedList.size() == 5
assert combinedList[1..3] == ["b", java.awt.Color.BLUE, "more stuff"] : "referencing a range of elements"
combinedList << "even more stuff"
assert combinedList.size() == 6
assert combinedList[-1..-3] == \
["even more stuff", "even more stuff", "more stuff"] \
: "reverse referencing last 3 elements"
println ([combinedList: combinedList])
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Convert this Haskell block to PHP, preserving its control flow and logic. | [1, 2, 3, 4, 5]
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Write the same algorithm in PHP as shown in this Icon implementation. |
s := "abccd"
c := 'abcd'
S := set()
T := table()
L := []
record constructorname(field1,field2,fieldetc)
R := constructorname()
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Produce a language-to-language conversion: from J to PHP, same semantics. | c =: 0 10 20 30 40
c, 50
0 10 20 30 40 50
_20 _10 , c
_20 _10 0 10 20 30 40
,~ c
0 10 20 30 40 0 10 20 30 40
,:~ c
0 10 20 30 40
0 10 20 30 40
30 e. c
1
30 i.~c
3
30 80 e. c
1 0
2 1 4 2 { c
20 10 40 20
|.c
40 30 20 10 0
1+c
1 11 21 31 41
c%10
0 1 2 3 4
{. c
0
{: c
40
3{.c
0 10 20
3}.c
30 40
_3{.c
20 30 40
_3}.c
0 10
keys_map_ =: 'one';'two';'three'
vals_map_ =: 'alpha';'beta';'gamma'
lookup_map_ =: a:& $: : (dyad def ' (keys i. y) { vals,x')&boxopen
exists_map_ =: verb def 'y e. keys'&boxopen
exists_map_ 'bad key'
0
exists_map_ 'two';'bad key'
1 0
lookup_map_ 'one'
+-----+
|alpha|
+-----+
lookup_map_ 'three';'one';'two';'one'
+-----+-----+----+-----+
|gamma|alpha|beta|alpha|
+-----+-----+----+-----+
lookup_map_ 'bad key'
++
||
++
'some other default' lookup_map_ 'bad key'
+------------------+
|some other default|
+------------------+
'some other default' lookup_map_ 'two';'bad key'
+----+------------------+
|beta|some other default|
+----+------------------+
+/ c
100
*/ c
0
i.5
0 1 2 3 4
10*i.5
0 10 20 30 40
c = 10*i.5
1 1 1 1 1
c -: 10 i.5
1
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Maintain the same structure and functionality when rewriting this code in PHP. | julia> collection = []
0-element Array{Any,1}
julia> push!(collection, 1,2,4,7)
4-element Array{Any,1}:
1
2
4
7
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Write a version of this Lua function in PHP with identical behavior. | collection = {0, '1'}
print(collection[1])
collection = {["foo"] = 0, ["bar"] = '1'}
print(collection["foo"])
print(collection.foo)
collection = {0, '1', ["foo"] = 0, ["bar"] = '1'}
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Convert this Mathematica snippet to PHP and keep its semantics consistent. | Lst = {3, 4, 5, 6}
->{3, 4, 5, 6}
PrependTo[ Lst, 2]
->{2, 3, 4, 5, 6}
PrependTo[ Lst, 1]
->{1, 2, 3, 4, 5, 6}
Lst
->{1, 2, 3, 4, 5, 6}
Insert[ Lst, X, 4]
->{1, 2, 3, X, 4, 5, 6}
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Maintain the same structure and functionality when rewriting this code in PHP. | >> A = {2,'TPS Report'}
A =
[2] 'TPS Report'
>> A{2} = struct('make','honda','year',2003)
A =
[2] [1x1 struct]
>> A{3} = {3,'HOVA'}
A =
[2] [1x1 struct] {1x2 cell}
>> A{2}
ans =
make: 'honda'
year: 2003
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Port the following code from Nim to PHP with equivalent syntax and logic. | var a = [1,2,3,4,5,6,7,8,9]
var b: array[128, int]
b[9] = 10
b[0..8] = a
var c: array['a'..'d', float] = [1.0, 1.1, 1.2, 1.3]
c['b'] = 10000
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Produce a functionally identical PHP code for the snippet given in OCaml. | [1; 2; 3; 4; 5]
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Convert the following code from Pascal to PHP, ensuring the logic remains intact. | var
MyArray: array[1..5] of real;
begin
MyArray[1] := 4.35;
end;
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Ensure the translated PHP code behaves exactly like the original Perl snippet. | use strict;
my @c = ();
push @c, 10, 11, 12;
push @c, 65;
print join(" ",@c) . "\n";
my %h = ();
$h{'one'} = 1;
$h{'two'} = 2;
foreach my $i ( keys %h ) {
print $i . " -> " . $h{$i} . "\n";
}
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Ensure the translated PHP code behaves exactly like the original PowerShell snippet. |
$array = "one", 2, "three", 4
$array = @("one", 2, "three", 4)
$var1, $var2, $var3, $var4 = $array
$array = 0, 1, 2, 3, 4, 5, 6, 7
$array = 0..7
[int[]] $stronglyTypedArray = 1, 2, 4, 8, 16, 32, 64, 128
$array = @()
$array = @("one")
$jaggedArray = @((11, 12, 13),
(21, 22, 23),
(31, 32, 33))
$jaggedArray | Format-Wide {$_} -Column 3 -Force
$jaggedArray[1][1]
$multiArray = New-Object -TypeName "System.Object[,]" -ArgumentList 6,6
for ($i = 0; $i -lt 6; $i++)
{
for ($j = 0; $j -lt 6; $j++)
{
$multiArray[$i,$j] = ($i + 1) * 10 + ($j + 1)
}
}
$multiArray | Format-Wide {$_} -Column 6 -Force
$multiArray[2,2]
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Ensure the translated PHP code behaves exactly like the original R snippet. | numeric(5)
1:10
c(1, 3, 6, 10, 7 + 8, sqrt(441))
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Translate this program into PHP but keep the logic exactly as in Racket. | #lang racket
(list 1 2 3 4)
(make-list 100 0)
(cons 1 (list 2 3 4))
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Change the following COBOL code into PHP without altering its purpose. | identification division.
program-id. collections.
data division.
working-storage section.
01 sample-table.
05 sample-record occurs 1 to 3 times depending on the-index.
10 sample-alpha pic x(4).
10 filler pic x value ":".
10 sample-number pic 9(4).
10 filler pic x value space.
77 the-index usage index.
procedure division.
collections-main.
set the-index to 3
move 1234 to sample-number(1)
move "abcd" to sample-alpha(1)
move "test" to sample-alpha(2)
move 6789 to sample-number(3)
move "wxyz" to sample-alpha(3)
display "sample-table : " sample-table
display "sample-number(1): " sample-number(1)
display "sample-record(2): " sample-record(2)
display "sample-number(3): " sample-number(3)
set the-index down by 1
display "sample-table : " sample-table
display "sample-number(3): " sample-number(3)
goback.
end program collections.
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Please provide an equivalent version of this REXX code in PHP. |
options replace format comments java crossref symbols nobinary
myVals = [ 'zero', 'one', 'two', 'three', 'four', 'five' ]
mySet = Set
mySet = HashSet()
loop val over myVals
mySet.add(val)
end val
loop val over mySet
say val
end val
return
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Translate the given Ruby code snippet into PHP without altering its behavior. |
a = []
a[0] = 1
a[3] = "abc"
a << 3.14
a = Array.new
a = Array.new(3)
a = Array.new(3, 0)
a = Array.new(3){|i| i*2}
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Change the programming language of this snippet from Scala to PHP without modifying what it does. | import java.util.PriorityQueue
fun main(args: Array<String>) {
val ga = arrayOf(1, 2, 3)
println(ga.joinToString(prefix = "[", postfix = "]"))
val da = doubleArrayOf(4.0, 5.0, 6.0)
println(da.joinToString(prefix = "[", postfix = "]"))
val li = listOf<Byte>(7, 8, 9)
println(li)
val ml = mutableListOf<Short>()
ml.add(10); ml.add(11); ml.add(12)
println(ml)
val hm = mapOf('a' to 97, 'b' to 98, 'c' to 99)
println(hm)
val mm = mutableMapOf<Char, Int>()
mm.put('d', 100); mm.put('e', 101); mm.put('f', 102)
println(mm)
val se = setOf(1, 2, 3)
println(se)
val ms = mutableSetOf<Long>()
ms.add(4L); ms.add(5L); ms.add(6L)
println(ms)
val pq = PriorityQueue<String>()
pq.add("First"); pq.add("Second"); pq.add("Third")
println(pq)
}
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Convert the following code from Tcl to PHP, ensuring the logic remains intact. | set c [list] ;
lappend c 10 11 13
set c [linsert $c 2 "twelve goes here"]
foreach elem $c {puts $elem}
proc show_size {l} {
puts [llength $l]
}
show_size $c
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Preserve the algorithm and functionality while converting the code from C to Rust. | #define cSize( a ) ( sizeof(a)/sizeof(a[0]) )
int ar[10];
ar[0] = 1;
ar[1] = 2;
int* p;
for (p=ar;
p<(ar+cSize(ar));
p++) {
printf("%d\n",*p);
}
| let a = [1u8,2,3,4,5];
let b = [0;256]
|
Port the provided C++ code into Rust while preserving the original functionality. | int a[5];
a[0] = 1;
int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };
#include <string>
std::string strings[4];
| let a = [1u8,2,3,4,5];
let b = [0;256]
|
Produce a language-to-language conversion: from C# to Rust, same semantics. |
int[] intArray = new int[5] { 1, 2, 3, 4, 5 };
int[] intArray = new int[]{ 1, 2, 3, 4, 5 };
int[] intArray = { 1, 2, 3, 4, 5 };
string[] stringArr = new string[5];
stringArr[0] = "string";
| let a = [1u8,2,3,4,5];
let b = [0;256]
|
Translate this program into Rust but keep the logic exactly as in Java. | List arrayList = new ArrayList();
arrayList.add(new Integer(0));
arrayList.add(0);
List<Integer> myarrlist = new ArrayList<Integer>();
int sum;
for(int i = 0; i < 10; i++) {
myarrlist.add(i);
}
| let a = [1u8,2,3,4,5];
let b = [0;256]
|
Maintain the same structure and functionality when rewriting this code in Rust. | package main
import "fmt"
func main() {
var a []interface{}
a = append(a, 3)
a = append(a, "apples", "oranges")
fmt.Println(a)
}
| let a = [1u8,2,3,4,5];
let b = [0;256]
|
Translate this program into Python but keep the logic exactly as in Rust. | let a = [1u8,2,3,4,5];
let b = [0;256]
| collection = [0, '1']
x = collection[0]
collection.append(2)
collection.insert(0, '-1')
y = collection[0]
collection.extend([2,'3'])
collection += [2,'3']
collection[2:6]
len(collection)
collection = (0, 1)
collection[:]
collection[-4:-1]
collection[::2]
collection="some string"
x = collection[::-1]
collection[::2] == "some string"[::2]
collection.__getitem__(slice(0,len(collection),2))
collection = {0: "zero", 1: "one"}
collection['zero'] = 2
collection = set([0, '1'])
|
Maintain the same structure and functionality when rewriting this code in VB. | let a = [1u8,2,3,4,5];
let b = [0;256]
| Dim coll As New Collection
coll.Add "apple"
coll.Add "banana"
|
Write a version of this Ada function in C# with identical behavior. | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Matrix is
generic
type Element is private;
Zero : Element;
One : Element;
with function "+" (A, B : Element) return Element is <>;
with function "*" (A, B : Element) return Element is <>;
with function Image (X : Element) return String is <>;
package Matrices is
type Matrix is array (Integer range <>, Integer range <>) of Element;
function "*" (A, B : Matrix) return Matrix;
function "**" (A : Matrix; Power : Natural) return Matrix;
procedure Put (A : Matrix);
end Matrices;
package body Matrices is
function "*" (A, B : Matrix) return Matrix is
R : Matrix (A'Range (1), B'Range (2));
Sum : Element := Zero;
begin
for I in R'Range (1) loop
for J in R'Range (2) loop
Sum := Zero;
for K in A'Range (2) loop
Sum := Sum + A (I, K) * B (K, J);
end loop;
R (I, J) := Sum;
end loop;
end loop;
return R;
end "*";
function "**" (A : Matrix; Power : Natural) return Matrix is
begin
if Power = 1 then
return A;
end if;
declare
R : Matrix (A'Range (1), A'Range (2)) := (others => (others => Zero));
P : Matrix := A;
E : Natural := Power;
begin
for I in P'Range (1) loop
R (I, I) := One;
end loop;
if E = 0 then
return R;
end if;
loop
if E mod 2 /= 0 then
R := R * P;
end if;
E := E / 2;
exit when E = 0;
P := P * P;
end loop;
return R;
end;
end "**";
procedure Put (A : Matrix) is
begin
for I in A'Range (1) loop
for J in A'Range (1) loop
Put (Image (A (I, J)));
end loop;
New_Line;
end loop;
end Put;
end Matrices;
package Integer_Matrices is new Matrices (Integer, 0, 1, Image => Integer'Image);
use Integer_Matrices;
M : Matrix (1..2, 1..2) := ((3,2),(2,1));
begin
Put_Line ("M ="); Put (M);
Put_Line ("M**0 ="); Put (M**0);
Put_Line ("M**1 ="); Put (M**1);
Put_Line ("M**2 ="); Put (M**2);
Put_Line ("M*M ="); Put (M*M);
Put_Line ("M**3 ="); Put (M**3);
Put_Line ("M*M*M ="); Put (M*M*M);
Put_Line ("M**4 ="); Put (M**4);
Put_Line ("M*M*M*M ="); Put (M*M*M*M);
Put_Line ("M**10 ="); Put (M**10);
Put_Line ("M*M*M*M*M*M*M*M*M*M ="); Put (M*M*M*M*M*M*M*M*M*M);
end Test_Matrix;
| using System;
using System.Collections;
using System.Collections.Generic;
using static System.Linq.Enumerable;
public static class MatrixExponentation
{
public static double[,] Identity(int size) {
double[,] matrix = new double[size, size];
for (int i = 0; i < size; i++) matrix[i, i] = 1;
return matrix;
}
public static double[,] Multiply(this double[,] left, double[,] right) {
if (left.ColumnCount() != right.RowCount()) throw new ArgumentException();
double[,] m = new double[left.RowCount(), right.ColumnCount()];
foreach (var (row, column) in from r in Range(0, m.RowCount()) from c in Range(0, m.ColumnCount()) select (r, c)) {
m[row, column] = Range(0, m.RowCount()).Sum(i => left[row, i] * right[i, column]);
}
return m;
}
public static double[,] Pow(this double[,] matrix, int exp) {
if (matrix.RowCount() != matrix.ColumnCount()) throw new ArgumentException("Matrix must be square.");
double[,] accumulator = Identity(matrix.RowCount());
for (int i = 0; i < exp; i++) {
accumulator = accumulator.Multiply(matrix);
}
return accumulator;
}
private static int RowCount(this double[,] matrix) => matrix.GetLength(0);
private static int ColumnCount(this double[,] matrix) => matrix.GetLength(1);
private static void Print(this double[,] m) {
foreach (var row in Rows()) {
Console.WriteLine("[ " + string.Join(" ", row) + " ]");
}
Console.WriteLine();
IEnumerable<IEnumerable<double>> Rows() =>
Range(0, m.RowCount()).Select(row => Range(0, m.ColumnCount()).Select(column => m[row, column]));
}
public static void Main() {
var matrix = new double[,] {
{ 3, 2 },
{ 2, 1 }
};
matrix.Pow(0).Print();
matrix.Pow(1).Print();
matrix.Pow(2).Print();
matrix.Pow(3).Print();
matrix.Pow(4).Print();
matrix.Pow(50).Print();
}
}
|
Rewrite this program in C while keeping its functionality equivalent to the Ada version. | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Matrix is
generic
type Element is private;
Zero : Element;
One : Element;
with function "+" (A, B : Element) return Element is <>;
with function "*" (A, B : Element) return Element is <>;
with function Image (X : Element) return String is <>;
package Matrices is
type Matrix is array (Integer range <>, Integer range <>) of Element;
function "*" (A, B : Matrix) return Matrix;
function "**" (A : Matrix; Power : Natural) return Matrix;
procedure Put (A : Matrix);
end Matrices;
package body Matrices is
function "*" (A, B : Matrix) return Matrix is
R : Matrix (A'Range (1), B'Range (2));
Sum : Element := Zero;
begin
for I in R'Range (1) loop
for J in R'Range (2) loop
Sum := Zero;
for K in A'Range (2) loop
Sum := Sum + A (I, K) * B (K, J);
end loop;
R (I, J) := Sum;
end loop;
end loop;
return R;
end "*";
function "**" (A : Matrix; Power : Natural) return Matrix is
begin
if Power = 1 then
return A;
end if;
declare
R : Matrix (A'Range (1), A'Range (2)) := (others => (others => Zero));
P : Matrix := A;
E : Natural := Power;
begin
for I in P'Range (1) loop
R (I, I) := One;
end loop;
if E = 0 then
return R;
end if;
loop
if E mod 2 /= 0 then
R := R * P;
end if;
E := E / 2;
exit when E = 0;
P := P * P;
end loop;
return R;
end;
end "**";
procedure Put (A : Matrix) is
begin
for I in A'Range (1) loop
for J in A'Range (1) loop
Put (Image (A (I, J)));
end loop;
New_Line;
end loop;
end Put;
end Matrices;
package Integer_Matrices is new Matrices (Integer, 0, 1, Image => Integer'Image);
use Integer_Matrices;
M : Matrix (1..2, 1..2) := ((3,2),(2,1));
begin
Put_Line ("M ="); Put (M);
Put_Line ("M**0 ="); Put (M**0);
Put_Line ("M**1 ="); Put (M**1);
Put_Line ("M**2 ="); Put (M**2);
Put_Line ("M*M ="); Put (M*M);
Put_Line ("M**3 ="); Put (M**3);
Put_Line ("M*M*M ="); Put (M*M*M);
Put_Line ("M**4 ="); Put (M**4);
Put_Line ("M*M*M*M ="); Put (M*M*M*M);
Put_Line ("M**10 ="); Put (M**10);
Put_Line ("M*M*M*M*M*M*M*M*M*M ="); Put (M*M*M*M*M*M*M*M*M*M);
end Test_Matrix;
| #include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct squareMtxStruct {
int dim;
double *cells;
double **m;
} *SquareMtx;
typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data);
SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data )
{
SquareMtx sm = malloc(sizeof(struct squareMtxStruct));
if (sm) {
int rw;
sm->dim = dim;
sm->cells = malloc(dim*dim * sizeof(double));
sm->m = malloc( dim * sizeof(double *));
if ((sm->cells != NULL) && (sm->m != NULL)) {
for (rw=0; rw<dim; rw++) {
sm->m[rw] = sm->cells + dim*rw;
fillFunc( sm->m[rw], rw, dim, ff_data );
}
}
else {
free(sm->m);
free(sm->cells);
free(sm);
printf("Square Matrix allocation failure\n");
return NULL;
}
}
else {
printf("Malloc failed for square matrix\n");
}
return sm;
}
void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 )
{
int col, ix;
double sum;
double *m0rw = m0->m[rw];
for (col = 0; col < dim; col++) {
sum = 0.0;
for (ix=0; ix<dim; ix++)
sum += m0rw[ix] * m0->m[ix][col];
cells[col] = sum;
}
}
void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] )
{
SquareMtx mleft = mplcnds[0];
SquareMtx mrigt = mplcnds[1];
double sum;
double *m0rw = mleft->m[rw];
int col, ix;
for (col = 0; col < dim; col++) {
sum = 0.0;
for (ix=0; ix<dim; ix++)
sum += m0rw[ix] * mrigt->m[ix][col];
cells[col] = sum;
}
}
void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt)
{
int rw;
SquareMtx mplcnds[2];
mplcnds[0] = left; mplcnds[1] = rigt;
for (rw = 0; rw < left->dim; rw++)
ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds);
}
void ffIdentity( double *cells, int rw, int dim, void *v )
{
int col;
for (col=0; col<dim; col++) cells[col] = 0.0;
cells[rw] = 1.0;
}
void ffCopy(double *cells, int rw, int dim, SquareMtx m1)
{
int col;
for (col=0; col<dim; col++) cells[col] = m1->m[rw][col];
}
void FreeSquareMtx( SquareMtx m )
{
free(m->m);
free(m->cells);
free(m);
}
SquareMtx SquareMtxPow( SquareMtx m0, int exp )
{
SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL);
SquareMtx v1 = NULL;
SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0);
SquareMtx base1 = NULL;
SquareMtx mplcnds[2], t;
while (exp) {
if (exp % 2) {
if (v1)
MatxMul( v1, v0, base0);
else {
mplcnds[0] = v0; mplcnds[1] = base0;
v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds);
}
{t = v0; v0=v1; v1 = t;}
}
if (base1)
MatxMul( base1, base0, base0);
else
base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0);
t = base0; base0 = base1; base1 = t;
exp = exp/2;
}
if (base0) FreeSquareMtx(base0);
if (base1) FreeSquareMtx(base1);
if (v1) FreeSquareMtx(v1);
return v0;
}
FILE *fout;
void SquareMtxPrint( SquareMtx mtx, const char *mn )
{
int rw, col;
int d = mtx->dim;
fprintf(fout, "%s dim:%d =\n", mn, mtx->dim);
for (rw=0; rw<d; rw++) {
fprintf(fout, " |");
for(col=0; col<d; col++)
fprintf(fout, "%8.5f ",mtx->m[rw][col] );
fprintf(fout, " |\n");
}
fprintf(fout, "\n");
}
void fillInit( double *cells, int rw, int dim, void *data)
{
double theta = 3.1415926536/6.0;
double c1 = cos( theta);
double s1 = sin( theta);
switch(rw) {
case 0:
cells[0]=c1; cells[1]=s1; cells[2]=0.0;
break;
case 1:
cells[0]=-s1; cells[1]=c1; cells[2]=0;
break;
case 2:
cells[0]=0.0; cells[1]=0.0; cells[2]=1.0;
break;
}
}
int main()
{
SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL);
SquareMtx m1 = SquareMtxPow( m0, 5);
SquareMtx m2 = SquareMtxPow( m0, 9);
SquareMtx m3 = SquareMtxPow( m0, 2);
fout = fopen("matrx_exp.txt", "w");
SquareMtxPrint(m0, "m0"); FreeSquareMtx(m0);
SquareMtxPrint(m1, "m0^5"); FreeSquareMtx(m1);
SquareMtxPrint(m2, "m0^9"); FreeSquareMtx(m2);
SquareMtxPrint(m3, "m0^2"); FreeSquareMtx(m3);
fclose(fout);
return 0;
}
|
Generate a C++ translation of this Ada snippet without changing its computational steps. | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Matrix is
generic
type Element is private;
Zero : Element;
One : Element;
with function "+" (A, B : Element) return Element is <>;
with function "*" (A, B : Element) return Element is <>;
with function Image (X : Element) return String is <>;
package Matrices is
type Matrix is array (Integer range <>, Integer range <>) of Element;
function "*" (A, B : Matrix) return Matrix;
function "**" (A : Matrix; Power : Natural) return Matrix;
procedure Put (A : Matrix);
end Matrices;
package body Matrices is
function "*" (A, B : Matrix) return Matrix is
R : Matrix (A'Range (1), B'Range (2));
Sum : Element := Zero;
begin
for I in R'Range (1) loop
for J in R'Range (2) loop
Sum := Zero;
for K in A'Range (2) loop
Sum := Sum + A (I, K) * B (K, J);
end loop;
R (I, J) := Sum;
end loop;
end loop;
return R;
end "*";
function "**" (A : Matrix; Power : Natural) return Matrix is
begin
if Power = 1 then
return A;
end if;
declare
R : Matrix (A'Range (1), A'Range (2)) := (others => (others => Zero));
P : Matrix := A;
E : Natural := Power;
begin
for I in P'Range (1) loop
R (I, I) := One;
end loop;
if E = 0 then
return R;
end if;
loop
if E mod 2 /= 0 then
R := R * P;
end if;
E := E / 2;
exit when E = 0;
P := P * P;
end loop;
return R;
end;
end "**";
procedure Put (A : Matrix) is
begin
for I in A'Range (1) loop
for J in A'Range (1) loop
Put (Image (A (I, J)));
end loop;
New_Line;
end loop;
end Put;
end Matrices;
package Integer_Matrices is new Matrices (Integer, 0, 1, Image => Integer'Image);
use Integer_Matrices;
M : Matrix (1..2, 1..2) := ((3,2),(2,1));
begin
Put_Line ("M ="); Put (M);
Put_Line ("M**0 ="); Put (M**0);
Put_Line ("M**1 ="); Put (M**1);
Put_Line ("M**2 ="); Put (M**2);
Put_Line ("M*M ="); Put (M*M);
Put_Line ("M**3 ="); Put (M**3);
Put_Line ("M*M*M ="); Put (M*M*M);
Put_Line ("M**4 ="); Put (M**4);
Put_Line ("M*M*M*M ="); Put (M*M*M*M);
Put_Line ("M**10 ="); Put (M**10);
Put_Line ("M*M*M*M*M*M*M*M*M*M ="); Put (M*M*M*M*M*M*M*M*M*M);
end Test_Matrix;
| #include <complex>
#include <cmath>
#include <iostream>
using namespace std;
template<int MSize = 3, class T = complex<double> >
class SqMx {
typedef T Ax[MSize][MSize];
typedef SqMx<MSize, T> Mx;
private:
Ax a;
SqMx() { }
public:
SqMx(const Ax &_a) {
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++)
a[r][c] = _a[r][c];
}
static Mx identity() {
Mx m;
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++)
m.a[r][c] = (r == c ? 1 : 0);
return m;
}
friend ostream &operator<<(ostream& os, const Mx &p)
{
for (int i = 0; i < MSize; i++) {
for (int j = 0; j < MSize; j++)
os << p.a[i][j] << ',';
os << endl;
}
return os;
}
Mx operator*(const Mx &b) {
Mx d;
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++) {
d.a[r][c] = 0;
for (int k = 0; k < MSize; k++)
d.a[r][c] += a[r][k] * b.a[k][c];
}
return d;
}
|
Transform the following Ada implementation into Go, maintaining the same output and logic. | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Matrix is
generic
type Element is private;
Zero : Element;
One : Element;
with function "+" (A, B : Element) return Element is <>;
with function "*" (A, B : Element) return Element is <>;
with function Image (X : Element) return String is <>;
package Matrices is
type Matrix is array (Integer range <>, Integer range <>) of Element;
function "*" (A, B : Matrix) return Matrix;
function "**" (A : Matrix; Power : Natural) return Matrix;
procedure Put (A : Matrix);
end Matrices;
package body Matrices is
function "*" (A, B : Matrix) return Matrix is
R : Matrix (A'Range (1), B'Range (2));
Sum : Element := Zero;
begin
for I in R'Range (1) loop
for J in R'Range (2) loop
Sum := Zero;
for K in A'Range (2) loop
Sum := Sum + A (I, K) * B (K, J);
end loop;
R (I, J) := Sum;
end loop;
end loop;
return R;
end "*";
function "**" (A : Matrix; Power : Natural) return Matrix is
begin
if Power = 1 then
return A;
end if;
declare
R : Matrix (A'Range (1), A'Range (2)) := (others => (others => Zero));
P : Matrix := A;
E : Natural := Power;
begin
for I in P'Range (1) loop
R (I, I) := One;
end loop;
if E = 0 then
return R;
end if;
loop
if E mod 2 /= 0 then
R := R * P;
end if;
E := E / 2;
exit when E = 0;
P := P * P;
end loop;
return R;
end;
end "**";
procedure Put (A : Matrix) is
begin
for I in A'Range (1) loop
for J in A'Range (1) loop
Put (Image (A (I, J)));
end loop;
New_Line;
end loop;
end Put;
end Matrices;
package Integer_Matrices is new Matrices (Integer, 0, 1, Image => Integer'Image);
use Integer_Matrices;
M : Matrix (1..2, 1..2) := ((3,2),(2,1));
begin
Put_Line ("M ="); Put (M);
Put_Line ("M**0 ="); Put (M**0);
Put_Line ("M**1 ="); Put (M**1);
Put_Line ("M**2 ="); Put (M**2);
Put_Line ("M*M ="); Put (M*M);
Put_Line ("M**3 ="); Put (M**3);
Put_Line ("M*M*M ="); Put (M*M*M);
Put_Line ("M**4 ="); Put (M**4);
Put_Line ("M*M*M*M ="); Put (M*M*M*M);
Put_Line ("M**10 ="); Put (M**10);
Put_Line ("M*M*M*M*M*M*M*M*M*M ="); Put (M*M*M*M*M*M*M*M*M*M);
end Test_Matrix;
| package main
import "fmt"
type vector = []float64
type matrix []vector
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != rows2 {
panic("Matrices cannot be multiplied.")
}
result := make(matrix, rows1)
for i := 0; i < rows1; i++ {
result[i] = make(vector, cols2)
for j := 0; j < cols2; j++ {
for k := 0; k < rows2; k++ {
result[i][j] += m1[i][k] * m2[k][j]
}
}
}
return result
}
func identityMatrix(n int) matrix {
if n < 1 {
panic("Size of identity matrix can't be less than 1")
}
ident := make(matrix, n)
for i := 0; i < n; i++ {
ident[i] = make(vector, n)
ident[i][i] = 1
}
return ident
}
func (m matrix) pow(n int) matrix {
le := len(m)
if le != len(m[0]) {
panic("Not a square matrix")
}
switch {
case n < 0:
panic("Negative exponents not supported")
case n == 0:
return identityMatrix(le)
case n == 1:
return m
}
pow := identityMatrix(le)
base := m
e := n
for e > 0 {
if (e & 1) == 1 {
pow = pow.mul(base)
}
e >>= 1
base = base.mul(base)
}
return pow
}
func main() {
m := matrix{{3, 2}, {2, 1}}
for i := 0; i <= 10; i++ {
fmt.Println("** Power of", i, "**")
fmt.Println(m.pow(i))
fmt.Println()
}
}
|
Transform the following Ada implementation into Python, maintaining the same output and logic. | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Matrix is
generic
type Element is private;
Zero : Element;
One : Element;
with function "+" (A, B : Element) return Element is <>;
with function "*" (A, B : Element) return Element is <>;
with function Image (X : Element) return String is <>;
package Matrices is
type Matrix is array (Integer range <>, Integer range <>) of Element;
function "*" (A, B : Matrix) return Matrix;
function "**" (A : Matrix; Power : Natural) return Matrix;
procedure Put (A : Matrix);
end Matrices;
package body Matrices is
function "*" (A, B : Matrix) return Matrix is
R : Matrix (A'Range (1), B'Range (2));
Sum : Element := Zero;
begin
for I in R'Range (1) loop
for J in R'Range (2) loop
Sum := Zero;
for K in A'Range (2) loop
Sum := Sum + A (I, K) * B (K, J);
end loop;
R (I, J) := Sum;
end loop;
end loop;
return R;
end "*";
function "**" (A : Matrix; Power : Natural) return Matrix is
begin
if Power = 1 then
return A;
end if;
declare
R : Matrix (A'Range (1), A'Range (2)) := (others => (others => Zero));
P : Matrix := A;
E : Natural := Power;
begin
for I in P'Range (1) loop
R (I, I) := One;
end loop;
if E = 0 then
return R;
end if;
loop
if E mod 2 /= 0 then
R := R * P;
end if;
E := E / 2;
exit when E = 0;
P := P * P;
end loop;
return R;
end;
end "**";
procedure Put (A : Matrix) is
begin
for I in A'Range (1) loop
for J in A'Range (1) loop
Put (Image (A (I, J)));
end loop;
New_Line;
end loop;
end Put;
end Matrices;
package Integer_Matrices is new Matrices (Integer, 0, 1, Image => Integer'Image);
use Integer_Matrices;
M : Matrix (1..2, 1..2) := ((3,2),(2,1));
begin
Put_Line ("M ="); Put (M);
Put_Line ("M**0 ="); Put (M**0);
Put_Line ("M**1 ="); Put (M**1);
Put_Line ("M**2 ="); Put (M**2);
Put_Line ("M*M ="); Put (M*M);
Put_Line ("M**3 ="); Put (M**3);
Put_Line ("M*M*M ="); Put (M*M*M);
Put_Line ("M**4 ="); Put (M**4);
Put_Line ("M*M*M*M ="); Put (M*M*M*M);
Put_Line ("M**10 ="); Put (M**10);
Put_Line ("M*M*M*M*M*M*M*M*M*M ="); Put (M*M*M*M*M*M*M*M*M*M);
end Test_Matrix;
| >>> from operator import mul
>>> def matrixMul(m1, m2):
return map(
lambda row:
map(
lambda *column:
sum(map(mul, row, column)),
*m2),
m1)
>>> def identity(size):
size = range(size)
return [[(i==j)*1 for i in size] for j in size]
>>> def matrixExp(m, pow):
assert pow>=0 and int(pow)==pow, "Only non-negative, integer powers allowed"
accumulator = identity(len(m))
for i in range(pow):
accumulator = matrixMul(accumulator, m)
return accumulator
>>> def printtable(data):
for row in data:
print ' '.join('%-5s' % ('%s' % cell) for cell in row)
>>> m = [[3,2], [2,1]]
>>> for i in range(5):
print '\n%i:' % i
printtable( matrixExp(m, i) )
0:
1 0
0 1
1:
3 2
2 1
2:
13 8
8 5
3:
55 34
34 21
4:
233 144
144 89
>>> printtable( matrixExp(m, 10) )
1346269 832040
832040 514229
>>>
|
Can you help me rewrite this code in VB instead of Ada, keeping it the same logically? | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Matrix is
generic
type Element is private;
Zero : Element;
One : Element;
with function "+" (A, B : Element) return Element is <>;
with function "*" (A, B : Element) return Element is <>;
with function Image (X : Element) return String is <>;
package Matrices is
type Matrix is array (Integer range <>, Integer range <>) of Element;
function "*" (A, B : Matrix) return Matrix;
function "**" (A : Matrix; Power : Natural) return Matrix;
procedure Put (A : Matrix);
end Matrices;
package body Matrices is
function "*" (A, B : Matrix) return Matrix is
R : Matrix (A'Range (1), B'Range (2));
Sum : Element := Zero;
begin
for I in R'Range (1) loop
for J in R'Range (2) loop
Sum := Zero;
for K in A'Range (2) loop
Sum := Sum + A (I, K) * B (K, J);
end loop;
R (I, J) := Sum;
end loop;
end loop;
return R;
end "*";
function "**" (A : Matrix; Power : Natural) return Matrix is
begin
if Power = 1 then
return A;
end if;
declare
R : Matrix (A'Range (1), A'Range (2)) := (others => (others => Zero));
P : Matrix := A;
E : Natural := Power;
begin
for I in P'Range (1) loop
R (I, I) := One;
end loop;
if E = 0 then
return R;
end if;
loop
if E mod 2 /= 0 then
R := R * P;
end if;
E := E / 2;
exit when E = 0;
P := P * P;
end loop;
return R;
end;
end "**";
procedure Put (A : Matrix) is
begin
for I in A'Range (1) loop
for J in A'Range (1) loop
Put (Image (A (I, J)));
end loop;
New_Line;
end loop;
end Put;
end Matrices;
package Integer_Matrices is new Matrices (Integer, 0, 1, Image => Integer'Image);
use Integer_Matrices;
M : Matrix (1..2, 1..2) := ((3,2),(2,1));
begin
Put_Line ("M ="); Put (M);
Put_Line ("M**0 ="); Put (M**0);
Put_Line ("M**1 ="); Put (M**1);
Put_Line ("M**2 ="); Put (M**2);
Put_Line ("M*M ="); Put (M*M);
Put_Line ("M**3 ="); Put (M**3);
Put_Line ("M*M*M ="); Put (M*M*M);
Put_Line ("M**4 ="); Put (M**4);
Put_Line ("M*M*M*M ="); Put (M*M*M*M);
Put_Line ("M**10 ="); Put (M**10);
Put_Line ("M*M*M*M*M*M*M*M*M*M ="); Put (M*M*M*M*M*M*M*M*M*M);
end Test_Matrix;
| Option Base 1
Private Function Identity(n As Integer) As Variant
Dim I() As Variant
ReDim I(n, n)
For j = 1 To n
For k = 1 To n
I(j, k) = 0
Next k
Next j
For j = 1 To n
I(j, j) = 1
Next j
Identity = I
End Function
Function MatrixExponentiation(ByVal x As Variant, ByVal n As Integer) As Variant
If n < 0 Then
x = WorksheetFunction.MInverse(x)
n = -n
End If
If n = 0 Then
MatrixExponentiation = Identity(UBound(x))
Exit Function
End If
Dim y() As Variant
y = Identity(UBound(x))
Do While n > 1
If n Mod 2 = 0 Then
x = WorksheetFunction.MMult(x, x)
n = n / 2
Else
y = WorksheetFunction.MMult(x, y)
x = WorksheetFunction.MMult(x, x)
n = (n - 1) / 2
End If
Loop
MatrixExponentiation = WorksheetFunction.MMult(x, y)
End Function
Public Sub pp(x As Variant)
For i_ = 1 To UBound(x)
For j_ = 1 To UBound(x)
Debug.Print x(i_, j_),
Next j_
Debug.Print
Next i_
End Sub
Public Sub main()
M2 = [{3,2;2,1}]
M3 = [{1,2,0;0,3,1;1,0,0}]
pp MatrixExponentiation(M2, -1)
Debug.Print
pp MatrixExponentiation(M2, 0)
Debug.Print
pp MatrixExponentiation(M2, 10)
Debug.Print
pp MatrixExponentiation(M3, 10)
End Sub
|
Convert this BBC_Basic snippet to C and keep its semantics consistent. | DIM matrix(1,1), output(1,1)
matrix() = 3, 2, 2, 1
FOR power% = 0 TO 9
PROCmatrixpower(matrix(), output(), power%)
PRINT "matrix()^" ; power% " = "
FOR row% = 0 TO DIM(output(), 1)
FOR col% = 0 TO DIM(output(), 2)
PRINT output(row%,col%);
NEXT
PRINT
NEXT row%
NEXT power%
END
DEF PROCmatrixpower(src(), dst(), pow%)
LOCAL i%
dst() = 0
FOR i% = 0 TO DIM(dst(), 1) : dst(i%,i%) = 1 : NEXT
IF pow% THEN
FOR i% = 1 TO pow%
dst() = dst() . src()
NEXT
ENDIF
ENDPROC
| #include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct squareMtxStruct {
int dim;
double *cells;
double **m;
} *SquareMtx;
typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data);
SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data )
{
SquareMtx sm = malloc(sizeof(struct squareMtxStruct));
if (sm) {
int rw;
sm->dim = dim;
sm->cells = malloc(dim*dim * sizeof(double));
sm->m = malloc( dim * sizeof(double *));
if ((sm->cells != NULL) && (sm->m != NULL)) {
for (rw=0; rw<dim; rw++) {
sm->m[rw] = sm->cells + dim*rw;
fillFunc( sm->m[rw], rw, dim, ff_data );
}
}
else {
free(sm->m);
free(sm->cells);
free(sm);
printf("Square Matrix allocation failure\n");
return NULL;
}
}
else {
printf("Malloc failed for square matrix\n");
}
return sm;
}
void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 )
{
int col, ix;
double sum;
double *m0rw = m0->m[rw];
for (col = 0; col < dim; col++) {
sum = 0.0;
for (ix=0; ix<dim; ix++)
sum += m0rw[ix] * m0->m[ix][col];
cells[col] = sum;
}
}
void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] )
{
SquareMtx mleft = mplcnds[0];
SquareMtx mrigt = mplcnds[1];
double sum;
double *m0rw = mleft->m[rw];
int col, ix;
for (col = 0; col < dim; col++) {
sum = 0.0;
for (ix=0; ix<dim; ix++)
sum += m0rw[ix] * mrigt->m[ix][col];
cells[col] = sum;
}
}
void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt)
{
int rw;
SquareMtx mplcnds[2];
mplcnds[0] = left; mplcnds[1] = rigt;
for (rw = 0; rw < left->dim; rw++)
ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds);
}
void ffIdentity( double *cells, int rw, int dim, void *v )
{
int col;
for (col=0; col<dim; col++) cells[col] = 0.0;
cells[rw] = 1.0;
}
void ffCopy(double *cells, int rw, int dim, SquareMtx m1)
{
int col;
for (col=0; col<dim; col++) cells[col] = m1->m[rw][col];
}
void FreeSquareMtx( SquareMtx m )
{
free(m->m);
free(m->cells);
free(m);
}
SquareMtx SquareMtxPow( SquareMtx m0, int exp )
{
SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL);
SquareMtx v1 = NULL;
SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0);
SquareMtx base1 = NULL;
SquareMtx mplcnds[2], t;
while (exp) {
if (exp % 2) {
if (v1)
MatxMul( v1, v0, base0);
else {
mplcnds[0] = v0; mplcnds[1] = base0;
v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds);
}
{t = v0; v0=v1; v1 = t;}
}
if (base1)
MatxMul( base1, base0, base0);
else
base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0);
t = base0; base0 = base1; base1 = t;
exp = exp/2;
}
if (base0) FreeSquareMtx(base0);
if (base1) FreeSquareMtx(base1);
if (v1) FreeSquareMtx(v1);
return v0;
}
FILE *fout;
void SquareMtxPrint( SquareMtx mtx, const char *mn )
{
int rw, col;
int d = mtx->dim;
fprintf(fout, "%s dim:%d =\n", mn, mtx->dim);
for (rw=0; rw<d; rw++) {
fprintf(fout, " |");
for(col=0; col<d; col++)
fprintf(fout, "%8.5f ",mtx->m[rw][col] );
fprintf(fout, " |\n");
}
fprintf(fout, "\n");
}
void fillInit( double *cells, int rw, int dim, void *data)
{
double theta = 3.1415926536/6.0;
double c1 = cos( theta);
double s1 = sin( theta);
switch(rw) {
case 0:
cells[0]=c1; cells[1]=s1; cells[2]=0.0;
break;
case 1:
cells[0]=-s1; cells[1]=c1; cells[2]=0;
break;
case 2:
cells[0]=0.0; cells[1]=0.0; cells[2]=1.0;
break;
}
}
int main()
{
SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL);
SquareMtx m1 = SquareMtxPow( m0, 5);
SquareMtx m2 = SquareMtxPow( m0, 9);
SquareMtx m3 = SquareMtxPow( m0, 2);
fout = fopen("matrx_exp.txt", "w");
SquareMtxPrint(m0, "m0"); FreeSquareMtx(m0);
SquareMtxPrint(m1, "m0^5"); FreeSquareMtx(m1);
SquareMtxPrint(m2, "m0^9"); FreeSquareMtx(m2);
SquareMtxPrint(m3, "m0^2"); FreeSquareMtx(m3);
fclose(fout);
return 0;
}
|
Generate an equivalent C# version of this BBC_Basic code. | DIM matrix(1,1), output(1,1)
matrix() = 3, 2, 2, 1
FOR power% = 0 TO 9
PROCmatrixpower(matrix(), output(), power%)
PRINT "matrix()^" ; power% " = "
FOR row% = 0 TO DIM(output(), 1)
FOR col% = 0 TO DIM(output(), 2)
PRINT output(row%,col%);
NEXT
PRINT
NEXT row%
NEXT power%
END
DEF PROCmatrixpower(src(), dst(), pow%)
LOCAL i%
dst() = 0
FOR i% = 0 TO DIM(dst(), 1) : dst(i%,i%) = 1 : NEXT
IF pow% THEN
FOR i% = 1 TO pow%
dst() = dst() . src()
NEXT
ENDIF
ENDPROC
| using System;
using System.Collections;
using System.Collections.Generic;
using static System.Linq.Enumerable;
public static class MatrixExponentation
{
public static double[,] Identity(int size) {
double[,] matrix = new double[size, size];
for (int i = 0; i < size; i++) matrix[i, i] = 1;
return matrix;
}
public static double[,] Multiply(this double[,] left, double[,] right) {
if (left.ColumnCount() != right.RowCount()) throw new ArgumentException();
double[,] m = new double[left.RowCount(), right.ColumnCount()];
foreach (var (row, column) in from r in Range(0, m.RowCount()) from c in Range(0, m.ColumnCount()) select (r, c)) {
m[row, column] = Range(0, m.RowCount()).Sum(i => left[row, i] * right[i, column]);
}
return m;
}
public static double[,] Pow(this double[,] matrix, int exp) {
if (matrix.RowCount() != matrix.ColumnCount()) throw new ArgumentException("Matrix must be square.");
double[,] accumulator = Identity(matrix.RowCount());
for (int i = 0; i < exp; i++) {
accumulator = accumulator.Multiply(matrix);
}
return accumulator;
}
private static int RowCount(this double[,] matrix) => matrix.GetLength(0);
private static int ColumnCount(this double[,] matrix) => matrix.GetLength(1);
private static void Print(this double[,] m) {
foreach (var row in Rows()) {
Console.WriteLine("[ " + string.Join(" ", row) + " ]");
}
Console.WriteLine();
IEnumerable<IEnumerable<double>> Rows() =>
Range(0, m.RowCount()).Select(row => Range(0, m.ColumnCount()).Select(column => m[row, column]));
}
public static void Main() {
var matrix = new double[,] {
{ 3, 2 },
{ 2, 1 }
};
matrix.Pow(0).Print();
matrix.Pow(1).Print();
matrix.Pow(2).Print();
matrix.Pow(3).Print();
matrix.Pow(4).Print();
matrix.Pow(50).Print();
}
}
|
Produce a functionally identical C++ code for the snippet given in BBC_Basic. | DIM matrix(1,1), output(1,1)
matrix() = 3, 2, 2, 1
FOR power% = 0 TO 9
PROCmatrixpower(matrix(), output(), power%)
PRINT "matrix()^" ; power% " = "
FOR row% = 0 TO DIM(output(), 1)
FOR col% = 0 TO DIM(output(), 2)
PRINT output(row%,col%);
NEXT
PRINT
NEXT row%
NEXT power%
END
DEF PROCmatrixpower(src(), dst(), pow%)
LOCAL i%
dst() = 0
FOR i% = 0 TO DIM(dst(), 1) : dst(i%,i%) = 1 : NEXT
IF pow% THEN
FOR i% = 1 TO pow%
dst() = dst() . src()
NEXT
ENDIF
ENDPROC
| #include <complex>
#include <cmath>
#include <iostream>
using namespace std;
template<int MSize = 3, class T = complex<double> >
class SqMx {
typedef T Ax[MSize][MSize];
typedef SqMx<MSize, T> Mx;
private:
Ax a;
SqMx() { }
public:
SqMx(const Ax &_a) {
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++)
a[r][c] = _a[r][c];
}
static Mx identity() {
Mx m;
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++)
m.a[r][c] = (r == c ? 1 : 0);
return m;
}
friend ostream &operator<<(ostream& os, const Mx &p)
{
for (int i = 0; i < MSize; i++) {
for (int j = 0; j < MSize; j++)
os << p.a[i][j] << ',';
os << endl;
}
return os;
}
Mx operator*(const Mx &b) {
Mx d;
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++) {
d.a[r][c] = 0;
for (int k = 0; k < MSize; k++)
d.a[r][c] += a[r][k] * b.a[k][c];
}
return d;
}
|
Please provide an equivalent version of this BBC_Basic code in Python. | DIM matrix(1,1), output(1,1)
matrix() = 3, 2, 2, 1
FOR power% = 0 TO 9
PROCmatrixpower(matrix(), output(), power%)
PRINT "matrix()^" ; power% " = "
FOR row% = 0 TO DIM(output(), 1)
FOR col% = 0 TO DIM(output(), 2)
PRINT output(row%,col%);
NEXT
PRINT
NEXT row%
NEXT power%
END
DEF PROCmatrixpower(src(), dst(), pow%)
LOCAL i%
dst() = 0
FOR i% = 0 TO DIM(dst(), 1) : dst(i%,i%) = 1 : NEXT
IF pow% THEN
FOR i% = 1 TO pow%
dst() = dst() . src()
NEXT
ENDIF
ENDPROC
| >>> from operator import mul
>>> def matrixMul(m1, m2):
return map(
lambda row:
map(
lambda *column:
sum(map(mul, row, column)),
*m2),
m1)
>>> def identity(size):
size = range(size)
return [[(i==j)*1 for i in size] for j in size]
>>> def matrixExp(m, pow):
assert pow>=0 and int(pow)==pow, "Only non-negative, integer powers allowed"
accumulator = identity(len(m))
for i in range(pow):
accumulator = matrixMul(accumulator, m)
return accumulator
>>> def printtable(data):
for row in data:
print ' '.join('%-5s' % ('%s' % cell) for cell in row)
>>> m = [[3,2], [2,1]]
>>> for i in range(5):
print '\n%i:' % i
printtable( matrixExp(m, i) )
0:
1 0
0 1
1:
3 2
2 1
2:
13 8
8 5
3:
55 34
34 21
4:
233 144
144 89
>>> printtable( matrixExp(m, 10) )
1346269 832040
832040 514229
>>>
|
Produce a functionally identical VB code for the snippet given in BBC_Basic. | DIM matrix(1,1), output(1,1)
matrix() = 3, 2, 2, 1
FOR power% = 0 TO 9
PROCmatrixpower(matrix(), output(), power%)
PRINT "matrix()^" ; power% " = "
FOR row% = 0 TO DIM(output(), 1)
FOR col% = 0 TO DIM(output(), 2)
PRINT output(row%,col%);
NEXT
PRINT
NEXT row%
NEXT power%
END
DEF PROCmatrixpower(src(), dst(), pow%)
LOCAL i%
dst() = 0
FOR i% = 0 TO DIM(dst(), 1) : dst(i%,i%) = 1 : NEXT
IF pow% THEN
FOR i% = 1 TO pow%
dst() = dst() . src()
NEXT
ENDIF
ENDPROC
| Option Base 1
Private Function Identity(n As Integer) As Variant
Dim I() As Variant
ReDim I(n, n)
For j = 1 To n
For k = 1 To n
I(j, k) = 0
Next k
Next j
For j = 1 To n
I(j, j) = 1
Next j
Identity = I
End Function
Function MatrixExponentiation(ByVal x As Variant, ByVal n As Integer) As Variant
If n < 0 Then
x = WorksheetFunction.MInverse(x)
n = -n
End If
If n = 0 Then
MatrixExponentiation = Identity(UBound(x))
Exit Function
End If
Dim y() As Variant
y = Identity(UBound(x))
Do While n > 1
If n Mod 2 = 0 Then
x = WorksheetFunction.MMult(x, x)
n = n / 2
Else
y = WorksheetFunction.MMult(x, y)
x = WorksheetFunction.MMult(x, x)
n = (n - 1) / 2
End If
Loop
MatrixExponentiation = WorksheetFunction.MMult(x, y)
End Function
Public Sub pp(x As Variant)
For i_ = 1 To UBound(x)
For j_ = 1 To UBound(x)
Debug.Print x(i_, j_),
Next j_
Debug.Print
Next i_
End Sub
Public Sub main()
M2 = [{3,2;2,1}]
M3 = [{1,2,0;0,3,1;1,0,0}]
pp MatrixExponentiation(M2, -1)
Debug.Print
pp MatrixExponentiation(M2, 0)
Debug.Print
pp MatrixExponentiation(M2, 10)
Debug.Print
pp MatrixExponentiation(M3, 10)
End Sub
|
Keep all operations the same but rewrite the snippet in Go. | DIM matrix(1,1), output(1,1)
matrix() = 3, 2, 2, 1
FOR power% = 0 TO 9
PROCmatrixpower(matrix(), output(), power%)
PRINT "matrix()^" ; power% " = "
FOR row% = 0 TO DIM(output(), 1)
FOR col% = 0 TO DIM(output(), 2)
PRINT output(row%,col%);
NEXT
PRINT
NEXT row%
NEXT power%
END
DEF PROCmatrixpower(src(), dst(), pow%)
LOCAL i%
dst() = 0
FOR i% = 0 TO DIM(dst(), 1) : dst(i%,i%) = 1 : NEXT
IF pow% THEN
FOR i% = 1 TO pow%
dst() = dst() . src()
NEXT
ENDIF
ENDPROC
| package main
import "fmt"
type vector = []float64
type matrix []vector
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != rows2 {
panic("Matrices cannot be multiplied.")
}
result := make(matrix, rows1)
for i := 0; i < rows1; i++ {
result[i] = make(vector, cols2)
for j := 0; j < cols2; j++ {
for k := 0; k < rows2; k++ {
result[i][j] += m1[i][k] * m2[k][j]
}
}
}
return result
}
func identityMatrix(n int) matrix {
if n < 1 {
panic("Size of identity matrix can't be less than 1")
}
ident := make(matrix, n)
for i := 0; i < n; i++ {
ident[i] = make(vector, n)
ident[i][i] = 1
}
return ident
}
func (m matrix) pow(n int) matrix {
le := len(m)
if le != len(m[0]) {
panic("Not a square matrix")
}
switch {
case n < 0:
panic("Negative exponents not supported")
case n == 0:
return identityMatrix(le)
case n == 1:
return m
}
pow := identityMatrix(le)
base := m
e := n
for e > 0 {
if (e & 1) == 1 {
pow = pow.mul(base)
}
e >>= 1
base = base.mul(base)
}
return pow
}
func main() {
m := matrix{{3, 2}, {2, 1}}
for i := 0; i <= 10; i++ {
fmt.Println("** Power of", i, "**")
fmt.Println(m.pow(i))
fmt.Println()
}
}
|
Change the programming language of this snippet from Common_Lisp to C without modifying what it does. | (defun multiply-matrices (matrix-0 matrix-1)
"Takes two 2D arrays and returns their product, or an error if they cannot be multiplied"
(let* ((m0-dims (array-dimensions matrix-0))
(m1-dims (array-dimensions matrix-1))
(m0-dim (length m0-dims))
(m1-dim (length m1-dims)))
(if (or (/= 2 m0-dim) (/= 2 m1-dim))
(error "Array given not a matrix")
(let ((m0-rows (car m0-dims))
(m0-cols (cadr m0-dims))
(m1-rows (car m1-dims))
(m1-cols (cadr m1-dims)))
(if (/= m0-cols m1-rows)
(error "Incompatible dimensions")
(do ((rarr (make-array (list m0-rows m1-cols)
:initial-element 0) rarr)
(n 0 (if (= n (1- m0-cols)) 0 (1+ n)))
(cc 0 (if (= n (1- m0-cols))
(if (/= cc (1- m1-cols))
(1+ cc) 0) cc))
(cr 0 (if (and (= (1- m0-cols) n)
(= (1- m1-cols) cc))
(1+ cr)
cr)))
((= cr m0-rows) rarr)
(setf (aref rarr cr cc)
(+ (aref rarr cr cc)
(* (aref matrix-0 cr n)
(aref matrix-1 n cc))))))))))
(defun matrix-identity (dim)
"Creates a new identity matrix of size dim*dim"
(do ((rarr (make-array (list dim dim)
:initial-element 0) rarr)
(n 0 (1+ n)))
((= n dim) rarr)
(setf (aref rarr n n) 1)))
(defun matrix-expt (matrix exp)
"Takes the first argument (a matrix) and multiplies it by itself exp times"
(let* ((m-dims (array-dimensions matrix))
(m-rows (car m-dims))
(m-cols (cadr m-dims)))
(cond
((/= m-rows m-cols) (error "Non-square matrix"))
((zerop exp) (matrix-identity m-rows))
((= 1 exp) (do ((rarr (make-array (list m-rows m-cols)) rarr)
(cc 0 (if (= cc (1- m-cols))
0
(1+ cc)))
(cr 0 (if (= cc (1- m-cols))
(1+ cr)
cr)))
((= cr m-rows) rarr)
(setf (aref rarr cr cc) (aref matrix cr cc))))
((zerop (mod exp 2)) (let ((me2 (matrix-expt matrix (/ exp 2))))
(multiply-matrices me2 me2)))
(t (let ((me2 (matrix-expt matrix (/ (1- exp) 2))))
(multiply-matrices matrix (multiply-matrices me2 me2)))))))
| #include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct squareMtxStruct {
int dim;
double *cells;
double **m;
} *SquareMtx;
typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data);
SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data )
{
SquareMtx sm = malloc(sizeof(struct squareMtxStruct));
if (sm) {
int rw;
sm->dim = dim;
sm->cells = malloc(dim*dim * sizeof(double));
sm->m = malloc( dim * sizeof(double *));
if ((sm->cells != NULL) && (sm->m != NULL)) {
for (rw=0; rw<dim; rw++) {
sm->m[rw] = sm->cells + dim*rw;
fillFunc( sm->m[rw], rw, dim, ff_data );
}
}
else {
free(sm->m);
free(sm->cells);
free(sm);
printf("Square Matrix allocation failure\n");
return NULL;
}
}
else {
printf("Malloc failed for square matrix\n");
}
return sm;
}
void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 )
{
int col, ix;
double sum;
double *m0rw = m0->m[rw];
for (col = 0; col < dim; col++) {
sum = 0.0;
for (ix=0; ix<dim; ix++)
sum += m0rw[ix] * m0->m[ix][col];
cells[col] = sum;
}
}
void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] )
{
SquareMtx mleft = mplcnds[0];
SquareMtx mrigt = mplcnds[1];
double sum;
double *m0rw = mleft->m[rw];
int col, ix;
for (col = 0; col < dim; col++) {
sum = 0.0;
for (ix=0; ix<dim; ix++)
sum += m0rw[ix] * mrigt->m[ix][col];
cells[col] = sum;
}
}
void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt)
{
int rw;
SquareMtx mplcnds[2];
mplcnds[0] = left; mplcnds[1] = rigt;
for (rw = 0; rw < left->dim; rw++)
ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds);
}
void ffIdentity( double *cells, int rw, int dim, void *v )
{
int col;
for (col=0; col<dim; col++) cells[col] = 0.0;
cells[rw] = 1.0;
}
void ffCopy(double *cells, int rw, int dim, SquareMtx m1)
{
int col;
for (col=0; col<dim; col++) cells[col] = m1->m[rw][col];
}
void FreeSquareMtx( SquareMtx m )
{
free(m->m);
free(m->cells);
free(m);
}
SquareMtx SquareMtxPow( SquareMtx m0, int exp )
{
SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL);
SquareMtx v1 = NULL;
SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0);
SquareMtx base1 = NULL;
SquareMtx mplcnds[2], t;
while (exp) {
if (exp % 2) {
if (v1)
MatxMul( v1, v0, base0);
else {
mplcnds[0] = v0; mplcnds[1] = base0;
v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds);
}
{t = v0; v0=v1; v1 = t;}
}
if (base1)
MatxMul( base1, base0, base0);
else
base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0);
t = base0; base0 = base1; base1 = t;
exp = exp/2;
}
if (base0) FreeSquareMtx(base0);
if (base1) FreeSquareMtx(base1);
if (v1) FreeSquareMtx(v1);
return v0;
}
FILE *fout;
void SquareMtxPrint( SquareMtx mtx, const char *mn )
{
int rw, col;
int d = mtx->dim;
fprintf(fout, "%s dim:%d =\n", mn, mtx->dim);
for (rw=0; rw<d; rw++) {
fprintf(fout, " |");
for(col=0; col<d; col++)
fprintf(fout, "%8.5f ",mtx->m[rw][col] );
fprintf(fout, " |\n");
}
fprintf(fout, "\n");
}
void fillInit( double *cells, int rw, int dim, void *data)
{
double theta = 3.1415926536/6.0;
double c1 = cos( theta);
double s1 = sin( theta);
switch(rw) {
case 0:
cells[0]=c1; cells[1]=s1; cells[2]=0.0;
break;
case 1:
cells[0]=-s1; cells[1]=c1; cells[2]=0;
break;
case 2:
cells[0]=0.0; cells[1]=0.0; cells[2]=1.0;
break;
}
}
int main()
{
SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL);
SquareMtx m1 = SquareMtxPow( m0, 5);
SquareMtx m2 = SquareMtxPow( m0, 9);
SquareMtx m3 = SquareMtxPow( m0, 2);
fout = fopen("matrx_exp.txt", "w");
SquareMtxPrint(m0, "m0"); FreeSquareMtx(m0);
SquareMtxPrint(m1, "m0^5"); FreeSquareMtx(m1);
SquareMtxPrint(m2, "m0^9"); FreeSquareMtx(m2);
SquareMtxPrint(m3, "m0^2"); FreeSquareMtx(m3);
fclose(fout);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C#. | (defun multiply-matrices (matrix-0 matrix-1)
"Takes two 2D arrays and returns their product, or an error if they cannot be multiplied"
(let* ((m0-dims (array-dimensions matrix-0))
(m1-dims (array-dimensions matrix-1))
(m0-dim (length m0-dims))
(m1-dim (length m1-dims)))
(if (or (/= 2 m0-dim) (/= 2 m1-dim))
(error "Array given not a matrix")
(let ((m0-rows (car m0-dims))
(m0-cols (cadr m0-dims))
(m1-rows (car m1-dims))
(m1-cols (cadr m1-dims)))
(if (/= m0-cols m1-rows)
(error "Incompatible dimensions")
(do ((rarr (make-array (list m0-rows m1-cols)
:initial-element 0) rarr)
(n 0 (if (= n (1- m0-cols)) 0 (1+ n)))
(cc 0 (if (= n (1- m0-cols))
(if (/= cc (1- m1-cols))
(1+ cc) 0) cc))
(cr 0 (if (and (= (1- m0-cols) n)
(= (1- m1-cols) cc))
(1+ cr)
cr)))
((= cr m0-rows) rarr)
(setf (aref rarr cr cc)
(+ (aref rarr cr cc)
(* (aref matrix-0 cr n)
(aref matrix-1 n cc))))))))))
(defun matrix-identity (dim)
"Creates a new identity matrix of size dim*dim"
(do ((rarr (make-array (list dim dim)
:initial-element 0) rarr)
(n 0 (1+ n)))
((= n dim) rarr)
(setf (aref rarr n n) 1)))
(defun matrix-expt (matrix exp)
"Takes the first argument (a matrix) and multiplies it by itself exp times"
(let* ((m-dims (array-dimensions matrix))
(m-rows (car m-dims))
(m-cols (cadr m-dims)))
(cond
((/= m-rows m-cols) (error "Non-square matrix"))
((zerop exp) (matrix-identity m-rows))
((= 1 exp) (do ((rarr (make-array (list m-rows m-cols)) rarr)
(cc 0 (if (= cc (1- m-cols))
0
(1+ cc)))
(cr 0 (if (= cc (1- m-cols))
(1+ cr)
cr)))
((= cr m-rows) rarr)
(setf (aref rarr cr cc) (aref matrix cr cc))))
((zerop (mod exp 2)) (let ((me2 (matrix-expt matrix (/ exp 2))))
(multiply-matrices me2 me2)))
(t (let ((me2 (matrix-expt matrix (/ (1- exp) 2))))
(multiply-matrices matrix (multiply-matrices me2 me2)))))))
| using System;
using System.Collections;
using System.Collections.Generic;
using static System.Linq.Enumerable;
public static class MatrixExponentation
{
public static double[,] Identity(int size) {
double[,] matrix = new double[size, size];
for (int i = 0; i < size; i++) matrix[i, i] = 1;
return matrix;
}
public static double[,] Multiply(this double[,] left, double[,] right) {
if (left.ColumnCount() != right.RowCount()) throw new ArgumentException();
double[,] m = new double[left.RowCount(), right.ColumnCount()];
foreach (var (row, column) in from r in Range(0, m.RowCount()) from c in Range(0, m.ColumnCount()) select (r, c)) {
m[row, column] = Range(0, m.RowCount()).Sum(i => left[row, i] * right[i, column]);
}
return m;
}
public static double[,] Pow(this double[,] matrix, int exp) {
if (matrix.RowCount() != matrix.ColumnCount()) throw new ArgumentException("Matrix must be square.");
double[,] accumulator = Identity(matrix.RowCount());
for (int i = 0; i < exp; i++) {
accumulator = accumulator.Multiply(matrix);
}
return accumulator;
}
private static int RowCount(this double[,] matrix) => matrix.GetLength(0);
private static int ColumnCount(this double[,] matrix) => matrix.GetLength(1);
private static void Print(this double[,] m) {
foreach (var row in Rows()) {
Console.WriteLine("[ " + string.Join(" ", row) + " ]");
}
Console.WriteLine();
IEnumerable<IEnumerable<double>> Rows() =>
Range(0, m.RowCount()).Select(row => Range(0, m.ColumnCount()).Select(column => m[row, column]));
}
public static void Main() {
var matrix = new double[,] {
{ 3, 2 },
{ 2, 1 }
};
matrix.Pow(0).Print();
matrix.Pow(1).Print();
matrix.Pow(2).Print();
matrix.Pow(3).Print();
matrix.Pow(4).Print();
matrix.Pow(50).Print();
}
}
|
Port the following code from Common_Lisp to C++ with equivalent syntax and logic. | (defun multiply-matrices (matrix-0 matrix-1)
"Takes two 2D arrays and returns their product, or an error if they cannot be multiplied"
(let* ((m0-dims (array-dimensions matrix-0))
(m1-dims (array-dimensions matrix-1))
(m0-dim (length m0-dims))
(m1-dim (length m1-dims)))
(if (or (/= 2 m0-dim) (/= 2 m1-dim))
(error "Array given not a matrix")
(let ((m0-rows (car m0-dims))
(m0-cols (cadr m0-dims))
(m1-rows (car m1-dims))
(m1-cols (cadr m1-dims)))
(if (/= m0-cols m1-rows)
(error "Incompatible dimensions")
(do ((rarr (make-array (list m0-rows m1-cols)
:initial-element 0) rarr)
(n 0 (if (= n (1- m0-cols)) 0 (1+ n)))
(cc 0 (if (= n (1- m0-cols))
(if (/= cc (1- m1-cols))
(1+ cc) 0) cc))
(cr 0 (if (and (= (1- m0-cols) n)
(= (1- m1-cols) cc))
(1+ cr)
cr)))
((= cr m0-rows) rarr)
(setf (aref rarr cr cc)
(+ (aref rarr cr cc)
(* (aref matrix-0 cr n)
(aref matrix-1 n cc))))))))))
(defun matrix-identity (dim)
"Creates a new identity matrix of size dim*dim"
(do ((rarr (make-array (list dim dim)
:initial-element 0) rarr)
(n 0 (1+ n)))
((= n dim) rarr)
(setf (aref rarr n n) 1)))
(defun matrix-expt (matrix exp)
"Takes the first argument (a matrix) and multiplies it by itself exp times"
(let* ((m-dims (array-dimensions matrix))
(m-rows (car m-dims))
(m-cols (cadr m-dims)))
(cond
((/= m-rows m-cols) (error "Non-square matrix"))
((zerop exp) (matrix-identity m-rows))
((= 1 exp) (do ((rarr (make-array (list m-rows m-cols)) rarr)
(cc 0 (if (= cc (1- m-cols))
0
(1+ cc)))
(cr 0 (if (= cc (1- m-cols))
(1+ cr)
cr)))
((= cr m-rows) rarr)
(setf (aref rarr cr cc) (aref matrix cr cc))))
((zerop (mod exp 2)) (let ((me2 (matrix-expt matrix (/ exp 2))))
(multiply-matrices me2 me2)))
(t (let ((me2 (matrix-expt matrix (/ (1- exp) 2))))
(multiply-matrices matrix (multiply-matrices me2 me2)))))))
| #include <complex>
#include <cmath>
#include <iostream>
using namespace std;
template<int MSize = 3, class T = complex<double> >
class SqMx {
typedef T Ax[MSize][MSize];
typedef SqMx<MSize, T> Mx;
private:
Ax a;
SqMx() { }
public:
SqMx(const Ax &_a) {
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++)
a[r][c] = _a[r][c];
}
static Mx identity() {
Mx m;
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++)
m.a[r][c] = (r == c ? 1 : 0);
return m;
}
friend ostream &operator<<(ostream& os, const Mx &p)
{
for (int i = 0; i < MSize; i++) {
for (int j = 0; j < MSize; j++)
os << p.a[i][j] << ',';
os << endl;
}
return os;
}
Mx operator*(const Mx &b) {
Mx d;
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++) {
d.a[r][c] = 0;
for (int k = 0; k < MSize; k++)
d.a[r][c] += a[r][k] * b.a[k][c];
}
return d;
}
|
Change the programming language of this snippet from Common_Lisp to Python without modifying what it does. | (defun multiply-matrices (matrix-0 matrix-1)
"Takes two 2D arrays and returns their product, or an error if they cannot be multiplied"
(let* ((m0-dims (array-dimensions matrix-0))
(m1-dims (array-dimensions matrix-1))
(m0-dim (length m0-dims))
(m1-dim (length m1-dims)))
(if (or (/= 2 m0-dim) (/= 2 m1-dim))
(error "Array given not a matrix")
(let ((m0-rows (car m0-dims))
(m0-cols (cadr m0-dims))
(m1-rows (car m1-dims))
(m1-cols (cadr m1-dims)))
(if (/= m0-cols m1-rows)
(error "Incompatible dimensions")
(do ((rarr (make-array (list m0-rows m1-cols)
:initial-element 0) rarr)
(n 0 (if (= n (1- m0-cols)) 0 (1+ n)))
(cc 0 (if (= n (1- m0-cols))
(if (/= cc (1- m1-cols))
(1+ cc) 0) cc))
(cr 0 (if (and (= (1- m0-cols) n)
(= (1- m1-cols) cc))
(1+ cr)
cr)))
((= cr m0-rows) rarr)
(setf (aref rarr cr cc)
(+ (aref rarr cr cc)
(* (aref matrix-0 cr n)
(aref matrix-1 n cc))))))))))
(defun matrix-identity (dim)
"Creates a new identity matrix of size dim*dim"
(do ((rarr (make-array (list dim dim)
:initial-element 0) rarr)
(n 0 (1+ n)))
((= n dim) rarr)
(setf (aref rarr n n) 1)))
(defun matrix-expt (matrix exp)
"Takes the first argument (a matrix) and multiplies it by itself exp times"
(let* ((m-dims (array-dimensions matrix))
(m-rows (car m-dims))
(m-cols (cadr m-dims)))
(cond
((/= m-rows m-cols) (error "Non-square matrix"))
((zerop exp) (matrix-identity m-rows))
((= 1 exp) (do ((rarr (make-array (list m-rows m-cols)) rarr)
(cc 0 (if (= cc (1- m-cols))
0
(1+ cc)))
(cr 0 (if (= cc (1- m-cols))
(1+ cr)
cr)))
((= cr m-rows) rarr)
(setf (aref rarr cr cc) (aref matrix cr cc))))
((zerop (mod exp 2)) (let ((me2 (matrix-expt matrix (/ exp 2))))
(multiply-matrices me2 me2)))
(t (let ((me2 (matrix-expt matrix (/ (1- exp) 2))))
(multiply-matrices matrix (multiply-matrices me2 me2)))))))
| >>> from operator import mul
>>> def matrixMul(m1, m2):
return map(
lambda row:
map(
lambda *column:
sum(map(mul, row, column)),
*m2),
m1)
>>> def identity(size):
size = range(size)
return [[(i==j)*1 for i in size] for j in size]
>>> def matrixExp(m, pow):
assert pow>=0 and int(pow)==pow, "Only non-negative, integer powers allowed"
accumulator = identity(len(m))
for i in range(pow):
accumulator = matrixMul(accumulator, m)
return accumulator
>>> def printtable(data):
for row in data:
print ' '.join('%-5s' % ('%s' % cell) for cell in row)
>>> m = [[3,2], [2,1]]
>>> for i in range(5):
print '\n%i:' % i
printtable( matrixExp(m, i) )
0:
1 0
0 1
1:
3 2
2 1
2:
13 8
8 5
3:
55 34
34 21
4:
233 144
144 89
>>> printtable( matrixExp(m, 10) )
1346269 832040
832040 514229
>>>
|
Convert this Common_Lisp block to VB, preserving its control flow and logic. | (defun multiply-matrices (matrix-0 matrix-1)
"Takes two 2D arrays and returns their product, or an error if they cannot be multiplied"
(let* ((m0-dims (array-dimensions matrix-0))
(m1-dims (array-dimensions matrix-1))
(m0-dim (length m0-dims))
(m1-dim (length m1-dims)))
(if (or (/= 2 m0-dim) (/= 2 m1-dim))
(error "Array given not a matrix")
(let ((m0-rows (car m0-dims))
(m0-cols (cadr m0-dims))
(m1-rows (car m1-dims))
(m1-cols (cadr m1-dims)))
(if (/= m0-cols m1-rows)
(error "Incompatible dimensions")
(do ((rarr (make-array (list m0-rows m1-cols)
:initial-element 0) rarr)
(n 0 (if (= n (1- m0-cols)) 0 (1+ n)))
(cc 0 (if (= n (1- m0-cols))
(if (/= cc (1- m1-cols))
(1+ cc) 0) cc))
(cr 0 (if (and (= (1- m0-cols) n)
(= (1- m1-cols) cc))
(1+ cr)
cr)))
((= cr m0-rows) rarr)
(setf (aref rarr cr cc)
(+ (aref rarr cr cc)
(* (aref matrix-0 cr n)
(aref matrix-1 n cc))))))))))
(defun matrix-identity (dim)
"Creates a new identity matrix of size dim*dim"
(do ((rarr (make-array (list dim dim)
:initial-element 0) rarr)
(n 0 (1+ n)))
((= n dim) rarr)
(setf (aref rarr n n) 1)))
(defun matrix-expt (matrix exp)
"Takes the first argument (a matrix) and multiplies it by itself exp times"
(let* ((m-dims (array-dimensions matrix))
(m-rows (car m-dims))
(m-cols (cadr m-dims)))
(cond
((/= m-rows m-cols) (error "Non-square matrix"))
((zerop exp) (matrix-identity m-rows))
((= 1 exp) (do ((rarr (make-array (list m-rows m-cols)) rarr)
(cc 0 (if (= cc (1- m-cols))
0
(1+ cc)))
(cr 0 (if (= cc (1- m-cols))
(1+ cr)
cr)))
((= cr m-rows) rarr)
(setf (aref rarr cr cc) (aref matrix cr cc))))
((zerop (mod exp 2)) (let ((me2 (matrix-expt matrix (/ exp 2))))
(multiply-matrices me2 me2)))
(t (let ((me2 (matrix-expt matrix (/ (1- exp) 2))))
(multiply-matrices matrix (multiply-matrices me2 me2)))))))
| Option Base 1
Private Function Identity(n As Integer) As Variant
Dim I() As Variant
ReDim I(n, n)
For j = 1 To n
For k = 1 To n
I(j, k) = 0
Next k
Next j
For j = 1 To n
I(j, j) = 1
Next j
Identity = I
End Function
Function MatrixExponentiation(ByVal x As Variant, ByVal n As Integer) As Variant
If n < 0 Then
x = WorksheetFunction.MInverse(x)
n = -n
End If
If n = 0 Then
MatrixExponentiation = Identity(UBound(x))
Exit Function
End If
Dim y() As Variant
y = Identity(UBound(x))
Do While n > 1
If n Mod 2 = 0 Then
x = WorksheetFunction.MMult(x, x)
n = n / 2
Else
y = WorksheetFunction.MMult(x, y)
x = WorksheetFunction.MMult(x, x)
n = (n - 1) / 2
End If
Loop
MatrixExponentiation = WorksheetFunction.MMult(x, y)
End Function
Public Sub pp(x As Variant)
For i_ = 1 To UBound(x)
For j_ = 1 To UBound(x)
Debug.Print x(i_, j_),
Next j_
Debug.Print
Next i_
End Sub
Public Sub main()
M2 = [{3,2;2,1}]
M3 = [{1,2,0;0,3,1;1,0,0}]
pp MatrixExponentiation(M2, -1)
Debug.Print
pp MatrixExponentiation(M2, 0)
Debug.Print
pp MatrixExponentiation(M2, 10)
Debug.Print
pp MatrixExponentiation(M3, 10)
End Sub
|
Preserve the algorithm and functionality while converting the code from Common_Lisp to Go. | (defun multiply-matrices (matrix-0 matrix-1)
"Takes two 2D arrays and returns their product, or an error if they cannot be multiplied"
(let* ((m0-dims (array-dimensions matrix-0))
(m1-dims (array-dimensions matrix-1))
(m0-dim (length m0-dims))
(m1-dim (length m1-dims)))
(if (or (/= 2 m0-dim) (/= 2 m1-dim))
(error "Array given not a matrix")
(let ((m0-rows (car m0-dims))
(m0-cols (cadr m0-dims))
(m1-rows (car m1-dims))
(m1-cols (cadr m1-dims)))
(if (/= m0-cols m1-rows)
(error "Incompatible dimensions")
(do ((rarr (make-array (list m0-rows m1-cols)
:initial-element 0) rarr)
(n 0 (if (= n (1- m0-cols)) 0 (1+ n)))
(cc 0 (if (= n (1- m0-cols))
(if (/= cc (1- m1-cols))
(1+ cc) 0) cc))
(cr 0 (if (and (= (1- m0-cols) n)
(= (1- m1-cols) cc))
(1+ cr)
cr)))
((= cr m0-rows) rarr)
(setf (aref rarr cr cc)
(+ (aref rarr cr cc)
(* (aref matrix-0 cr n)
(aref matrix-1 n cc))))))))))
(defun matrix-identity (dim)
"Creates a new identity matrix of size dim*dim"
(do ((rarr (make-array (list dim dim)
:initial-element 0) rarr)
(n 0 (1+ n)))
((= n dim) rarr)
(setf (aref rarr n n) 1)))
(defun matrix-expt (matrix exp)
"Takes the first argument (a matrix) and multiplies it by itself exp times"
(let* ((m-dims (array-dimensions matrix))
(m-rows (car m-dims))
(m-cols (cadr m-dims)))
(cond
((/= m-rows m-cols) (error "Non-square matrix"))
((zerop exp) (matrix-identity m-rows))
((= 1 exp) (do ((rarr (make-array (list m-rows m-cols)) rarr)
(cc 0 (if (= cc (1- m-cols))
0
(1+ cc)))
(cr 0 (if (= cc (1- m-cols))
(1+ cr)
cr)))
((= cr m-rows) rarr)
(setf (aref rarr cr cc) (aref matrix cr cc))))
((zerop (mod exp 2)) (let ((me2 (matrix-expt matrix (/ exp 2))))
(multiply-matrices me2 me2)))
(t (let ((me2 (matrix-expt matrix (/ (1- exp) 2))))
(multiply-matrices matrix (multiply-matrices me2 me2)))))))
| package main
import "fmt"
type vector = []float64
type matrix []vector
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != rows2 {
panic("Matrices cannot be multiplied.")
}
result := make(matrix, rows1)
for i := 0; i < rows1; i++ {
result[i] = make(vector, cols2)
for j := 0; j < cols2; j++ {
for k := 0; k < rows2; k++ {
result[i][j] += m1[i][k] * m2[k][j]
}
}
}
return result
}
func identityMatrix(n int) matrix {
if n < 1 {
panic("Size of identity matrix can't be less than 1")
}
ident := make(matrix, n)
for i := 0; i < n; i++ {
ident[i] = make(vector, n)
ident[i][i] = 1
}
return ident
}
func (m matrix) pow(n int) matrix {
le := len(m)
if le != len(m[0]) {
panic("Not a square matrix")
}
switch {
case n < 0:
panic("Negative exponents not supported")
case n == 0:
return identityMatrix(le)
case n == 1:
return m
}
pow := identityMatrix(le)
base := m
e := n
for e > 0 {
if (e & 1) == 1 {
pow = pow.mul(base)
}
e >>= 1
base = base.mul(base)
}
return pow
}
func main() {
m := matrix{{3, 2}, {2, 1}}
for i := 0; i <= 10; i++ {
fmt.Println("** Power of", i, "**")
fmt.Println(m.pow(i))
fmt.Println()
}
}
|
Rewrite this program in C while keeping its functionality equivalent to the D version. | import std.stdio, std.string, std.math, std.array, std.algorithm;
struct SquareMat(T = creal) {
public static string fmt = "%8.3f";
private alias TM = T[][];
private TM a;
public this(in size_t side) pure nothrow @safe
in {
assert(side > 0);
} body {
a = new TM(side, side);
}
public this(in TM m) pure nothrow @safe
in {
assert(!m.empty);
assert(m.all!(row => row.length == m.length));
} body {
a.length = m.length;
foreach (immutable i, const row; m)
a[i] = row.dup;
}
string toString() const @safe {
return format("<%(%(" ~ fmt ~ ", %)\n %)>", a);
}
public static SquareMat identity(in size_t side) pure nothrow @safe {
auto m = SquareMat(side);
foreach (immutable r, ref row; m.a)
foreach (immutable c; 0 .. side)
row[c] = (r == c) ? 1+0i : 0+0i;
return m;
}
public SquareMat opBinary(string op:"*")(in SquareMat other)
const pure nothrow @safe in {
assert (a.length == other.a.length);
} body {
immutable side = other.a.length;
auto d = SquareMat(side);
foreach (immutable r; 0 .. side)
foreach (immutable c; 0 .. side) {
d.a[r][c] = 0+0i;
foreach (immutable k, immutable ark; a[r])
d.a[r][c] += ark * other.a[k][c];
}
return d;
}
public SquareMat opBinary(string op:"^^")(int n)
const pure nothrow @safe in {
assert(n >= 0, "Negative exponent not implemented.");
} body {
auto sq = SquareMat(this.a);
auto d = SquareMat.identity(a.length);
for (; n > 0; sq = sq * sq, n >>= 1)
if (n & 1)
d = d * sq;
return d;
}
}
void main() {
alias M = SquareMat!();
enum real q = 0.5.sqrt;
immutable m = M([[ q + 0*1.0Li, q + 0*1.0Li, 0.0L + 0.0Li],
[0.0L - q*1.0Li, 0.0L + q*1.0Li, 0.0L + 0.0Li],
[0.0L + 0.0Li, 0.0L + 0.0Li, 0.0L + 1.0Li]]);
M.fmt = "%5.2f";
foreach (immutable p; [0, 1, 23, 24])
writefln("m ^^ %d =\n%s", p, m ^^ p);
}
| #include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct squareMtxStruct {
int dim;
double *cells;
double **m;
} *SquareMtx;
typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data);
SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data )
{
SquareMtx sm = malloc(sizeof(struct squareMtxStruct));
if (sm) {
int rw;
sm->dim = dim;
sm->cells = malloc(dim*dim * sizeof(double));
sm->m = malloc( dim * sizeof(double *));
if ((sm->cells != NULL) && (sm->m != NULL)) {
for (rw=0; rw<dim; rw++) {
sm->m[rw] = sm->cells + dim*rw;
fillFunc( sm->m[rw], rw, dim, ff_data );
}
}
else {
free(sm->m);
free(sm->cells);
free(sm);
printf("Square Matrix allocation failure\n");
return NULL;
}
}
else {
printf("Malloc failed for square matrix\n");
}
return sm;
}
void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 )
{
int col, ix;
double sum;
double *m0rw = m0->m[rw];
for (col = 0; col < dim; col++) {
sum = 0.0;
for (ix=0; ix<dim; ix++)
sum += m0rw[ix] * m0->m[ix][col];
cells[col] = sum;
}
}
void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] )
{
SquareMtx mleft = mplcnds[0];
SquareMtx mrigt = mplcnds[1];
double sum;
double *m0rw = mleft->m[rw];
int col, ix;
for (col = 0; col < dim; col++) {
sum = 0.0;
for (ix=0; ix<dim; ix++)
sum += m0rw[ix] * mrigt->m[ix][col];
cells[col] = sum;
}
}
void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt)
{
int rw;
SquareMtx mplcnds[2];
mplcnds[0] = left; mplcnds[1] = rigt;
for (rw = 0; rw < left->dim; rw++)
ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds);
}
void ffIdentity( double *cells, int rw, int dim, void *v )
{
int col;
for (col=0; col<dim; col++) cells[col] = 0.0;
cells[rw] = 1.0;
}
void ffCopy(double *cells, int rw, int dim, SquareMtx m1)
{
int col;
for (col=0; col<dim; col++) cells[col] = m1->m[rw][col];
}
void FreeSquareMtx( SquareMtx m )
{
free(m->m);
free(m->cells);
free(m);
}
SquareMtx SquareMtxPow( SquareMtx m0, int exp )
{
SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL);
SquareMtx v1 = NULL;
SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0);
SquareMtx base1 = NULL;
SquareMtx mplcnds[2], t;
while (exp) {
if (exp % 2) {
if (v1)
MatxMul( v1, v0, base0);
else {
mplcnds[0] = v0; mplcnds[1] = base0;
v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds);
}
{t = v0; v0=v1; v1 = t;}
}
if (base1)
MatxMul( base1, base0, base0);
else
base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0);
t = base0; base0 = base1; base1 = t;
exp = exp/2;
}
if (base0) FreeSquareMtx(base0);
if (base1) FreeSquareMtx(base1);
if (v1) FreeSquareMtx(v1);
return v0;
}
FILE *fout;
void SquareMtxPrint( SquareMtx mtx, const char *mn )
{
int rw, col;
int d = mtx->dim;
fprintf(fout, "%s dim:%d =\n", mn, mtx->dim);
for (rw=0; rw<d; rw++) {
fprintf(fout, " |");
for(col=0; col<d; col++)
fprintf(fout, "%8.5f ",mtx->m[rw][col] );
fprintf(fout, " |\n");
}
fprintf(fout, "\n");
}
void fillInit( double *cells, int rw, int dim, void *data)
{
double theta = 3.1415926536/6.0;
double c1 = cos( theta);
double s1 = sin( theta);
switch(rw) {
case 0:
cells[0]=c1; cells[1]=s1; cells[2]=0.0;
break;
case 1:
cells[0]=-s1; cells[1]=c1; cells[2]=0;
break;
case 2:
cells[0]=0.0; cells[1]=0.0; cells[2]=1.0;
break;
}
}
int main()
{
SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL);
SquareMtx m1 = SquareMtxPow( m0, 5);
SquareMtx m2 = SquareMtxPow( m0, 9);
SquareMtx m3 = SquareMtxPow( m0, 2);
fout = fopen("matrx_exp.txt", "w");
SquareMtxPrint(m0, "m0"); FreeSquareMtx(m0);
SquareMtxPrint(m1, "m0^5"); FreeSquareMtx(m1);
SquareMtxPrint(m2, "m0^9"); FreeSquareMtx(m2);
SquareMtxPrint(m3, "m0^2"); FreeSquareMtx(m3);
fclose(fout);
return 0;
}
|
Translate the given D code snippet into C# without altering its behavior. | import std.stdio, std.string, std.math, std.array, std.algorithm;
struct SquareMat(T = creal) {
public static string fmt = "%8.3f";
private alias TM = T[][];
private TM a;
public this(in size_t side) pure nothrow @safe
in {
assert(side > 0);
} body {
a = new TM(side, side);
}
public this(in TM m) pure nothrow @safe
in {
assert(!m.empty);
assert(m.all!(row => row.length == m.length));
} body {
a.length = m.length;
foreach (immutable i, const row; m)
a[i] = row.dup;
}
string toString() const @safe {
return format("<%(%(" ~ fmt ~ ", %)\n %)>", a);
}
public static SquareMat identity(in size_t side) pure nothrow @safe {
auto m = SquareMat(side);
foreach (immutable r, ref row; m.a)
foreach (immutable c; 0 .. side)
row[c] = (r == c) ? 1+0i : 0+0i;
return m;
}
public SquareMat opBinary(string op:"*")(in SquareMat other)
const pure nothrow @safe in {
assert (a.length == other.a.length);
} body {
immutable side = other.a.length;
auto d = SquareMat(side);
foreach (immutable r; 0 .. side)
foreach (immutable c; 0 .. side) {
d.a[r][c] = 0+0i;
foreach (immutable k, immutable ark; a[r])
d.a[r][c] += ark * other.a[k][c];
}
return d;
}
public SquareMat opBinary(string op:"^^")(int n)
const pure nothrow @safe in {
assert(n >= 0, "Negative exponent not implemented.");
} body {
auto sq = SquareMat(this.a);
auto d = SquareMat.identity(a.length);
for (; n > 0; sq = sq * sq, n >>= 1)
if (n & 1)
d = d * sq;
return d;
}
}
void main() {
alias M = SquareMat!();
enum real q = 0.5.sqrt;
immutable m = M([[ q + 0*1.0Li, q + 0*1.0Li, 0.0L + 0.0Li],
[0.0L - q*1.0Li, 0.0L + q*1.0Li, 0.0L + 0.0Li],
[0.0L + 0.0Li, 0.0L + 0.0Li, 0.0L + 1.0Li]]);
M.fmt = "%5.2f";
foreach (immutable p; [0, 1, 23, 24])
writefln("m ^^ %d =\n%s", p, m ^^ p);
}
| using System;
using System.Collections;
using System.Collections.Generic;
using static System.Linq.Enumerable;
public static class MatrixExponentation
{
public static double[,] Identity(int size) {
double[,] matrix = new double[size, size];
for (int i = 0; i < size; i++) matrix[i, i] = 1;
return matrix;
}
public static double[,] Multiply(this double[,] left, double[,] right) {
if (left.ColumnCount() != right.RowCount()) throw new ArgumentException();
double[,] m = new double[left.RowCount(), right.ColumnCount()];
foreach (var (row, column) in from r in Range(0, m.RowCount()) from c in Range(0, m.ColumnCount()) select (r, c)) {
m[row, column] = Range(0, m.RowCount()).Sum(i => left[row, i] * right[i, column]);
}
return m;
}
public static double[,] Pow(this double[,] matrix, int exp) {
if (matrix.RowCount() != matrix.ColumnCount()) throw new ArgumentException("Matrix must be square.");
double[,] accumulator = Identity(matrix.RowCount());
for (int i = 0; i < exp; i++) {
accumulator = accumulator.Multiply(matrix);
}
return accumulator;
}
private static int RowCount(this double[,] matrix) => matrix.GetLength(0);
private static int ColumnCount(this double[,] matrix) => matrix.GetLength(1);
private static void Print(this double[,] m) {
foreach (var row in Rows()) {
Console.WriteLine("[ " + string.Join(" ", row) + " ]");
}
Console.WriteLine();
IEnumerable<IEnumerable<double>> Rows() =>
Range(0, m.RowCount()).Select(row => Range(0, m.ColumnCount()).Select(column => m[row, column]));
}
public static void Main() {
var matrix = new double[,] {
{ 3, 2 },
{ 2, 1 }
};
matrix.Pow(0).Print();
matrix.Pow(1).Print();
matrix.Pow(2).Print();
matrix.Pow(3).Print();
matrix.Pow(4).Print();
matrix.Pow(50).Print();
}
}
|
Write a version of this D function in C++ with identical behavior. | import std.stdio, std.string, std.math, std.array, std.algorithm;
struct SquareMat(T = creal) {
public static string fmt = "%8.3f";
private alias TM = T[][];
private TM a;
public this(in size_t side) pure nothrow @safe
in {
assert(side > 0);
} body {
a = new TM(side, side);
}
public this(in TM m) pure nothrow @safe
in {
assert(!m.empty);
assert(m.all!(row => row.length == m.length));
} body {
a.length = m.length;
foreach (immutable i, const row; m)
a[i] = row.dup;
}
string toString() const @safe {
return format("<%(%(" ~ fmt ~ ", %)\n %)>", a);
}
public static SquareMat identity(in size_t side) pure nothrow @safe {
auto m = SquareMat(side);
foreach (immutable r, ref row; m.a)
foreach (immutable c; 0 .. side)
row[c] = (r == c) ? 1+0i : 0+0i;
return m;
}
public SquareMat opBinary(string op:"*")(in SquareMat other)
const pure nothrow @safe in {
assert (a.length == other.a.length);
} body {
immutable side = other.a.length;
auto d = SquareMat(side);
foreach (immutable r; 0 .. side)
foreach (immutable c; 0 .. side) {
d.a[r][c] = 0+0i;
foreach (immutable k, immutable ark; a[r])
d.a[r][c] += ark * other.a[k][c];
}
return d;
}
public SquareMat opBinary(string op:"^^")(int n)
const pure nothrow @safe in {
assert(n >= 0, "Negative exponent not implemented.");
} body {
auto sq = SquareMat(this.a);
auto d = SquareMat.identity(a.length);
for (; n > 0; sq = sq * sq, n >>= 1)
if (n & 1)
d = d * sq;
return d;
}
}
void main() {
alias M = SquareMat!();
enum real q = 0.5.sqrt;
immutable m = M([[ q + 0*1.0Li, q + 0*1.0Li, 0.0L + 0.0Li],
[0.0L - q*1.0Li, 0.0L + q*1.0Li, 0.0L + 0.0Li],
[0.0L + 0.0Li, 0.0L + 0.0Li, 0.0L + 1.0Li]]);
M.fmt = "%5.2f";
foreach (immutable p; [0, 1, 23, 24])
writefln("m ^^ %d =\n%s", p, m ^^ p);
}
| #include <complex>
#include <cmath>
#include <iostream>
using namespace std;
template<int MSize = 3, class T = complex<double> >
class SqMx {
typedef T Ax[MSize][MSize];
typedef SqMx<MSize, T> Mx;
private:
Ax a;
SqMx() { }
public:
SqMx(const Ax &_a) {
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++)
a[r][c] = _a[r][c];
}
static Mx identity() {
Mx m;
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++)
m.a[r][c] = (r == c ? 1 : 0);
return m;
}
friend ostream &operator<<(ostream& os, const Mx &p)
{
for (int i = 0; i < MSize; i++) {
for (int j = 0; j < MSize; j++)
os << p.a[i][j] << ',';
os << endl;
}
return os;
}
Mx operator*(const Mx &b) {
Mx d;
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++) {
d.a[r][c] = 0;
for (int k = 0; k < MSize; k++)
d.a[r][c] += a[r][k] * b.a[k][c];
}
return d;
}
|
Convert this D block to Python, preserving its control flow and logic. | import std.stdio, std.string, std.math, std.array, std.algorithm;
struct SquareMat(T = creal) {
public static string fmt = "%8.3f";
private alias TM = T[][];
private TM a;
public this(in size_t side) pure nothrow @safe
in {
assert(side > 0);
} body {
a = new TM(side, side);
}
public this(in TM m) pure nothrow @safe
in {
assert(!m.empty);
assert(m.all!(row => row.length == m.length));
} body {
a.length = m.length;
foreach (immutable i, const row; m)
a[i] = row.dup;
}
string toString() const @safe {
return format("<%(%(" ~ fmt ~ ", %)\n %)>", a);
}
public static SquareMat identity(in size_t side) pure nothrow @safe {
auto m = SquareMat(side);
foreach (immutable r, ref row; m.a)
foreach (immutable c; 0 .. side)
row[c] = (r == c) ? 1+0i : 0+0i;
return m;
}
public SquareMat opBinary(string op:"*")(in SquareMat other)
const pure nothrow @safe in {
assert (a.length == other.a.length);
} body {
immutable side = other.a.length;
auto d = SquareMat(side);
foreach (immutable r; 0 .. side)
foreach (immutable c; 0 .. side) {
d.a[r][c] = 0+0i;
foreach (immutable k, immutable ark; a[r])
d.a[r][c] += ark * other.a[k][c];
}
return d;
}
public SquareMat opBinary(string op:"^^")(int n)
const pure nothrow @safe in {
assert(n >= 0, "Negative exponent not implemented.");
} body {
auto sq = SquareMat(this.a);
auto d = SquareMat.identity(a.length);
for (; n > 0; sq = sq * sq, n >>= 1)
if (n & 1)
d = d * sq;
return d;
}
}
void main() {
alias M = SquareMat!();
enum real q = 0.5.sqrt;
immutable m = M([[ q + 0*1.0Li, q + 0*1.0Li, 0.0L + 0.0Li],
[0.0L - q*1.0Li, 0.0L + q*1.0Li, 0.0L + 0.0Li],
[0.0L + 0.0Li, 0.0L + 0.0Li, 0.0L + 1.0Li]]);
M.fmt = "%5.2f";
foreach (immutable p; [0, 1, 23, 24])
writefln("m ^^ %d =\n%s", p, m ^^ p);
}
| >>> from operator import mul
>>> def matrixMul(m1, m2):
return map(
lambda row:
map(
lambda *column:
sum(map(mul, row, column)),
*m2),
m1)
>>> def identity(size):
size = range(size)
return [[(i==j)*1 for i in size] for j in size]
>>> def matrixExp(m, pow):
assert pow>=0 and int(pow)==pow, "Only non-negative, integer powers allowed"
accumulator = identity(len(m))
for i in range(pow):
accumulator = matrixMul(accumulator, m)
return accumulator
>>> def printtable(data):
for row in data:
print ' '.join('%-5s' % ('%s' % cell) for cell in row)
>>> m = [[3,2], [2,1]]
>>> for i in range(5):
print '\n%i:' % i
printtable( matrixExp(m, i) )
0:
1 0
0 1
1:
3 2
2 1
2:
13 8
8 5
3:
55 34
34 21
4:
233 144
144 89
>>> printtable( matrixExp(m, 10) )
1346269 832040
832040 514229
>>>
|
Generate an equivalent VB version of this D code. | import std.stdio, std.string, std.math, std.array, std.algorithm;
struct SquareMat(T = creal) {
public static string fmt = "%8.3f";
private alias TM = T[][];
private TM a;
public this(in size_t side) pure nothrow @safe
in {
assert(side > 0);
} body {
a = new TM(side, side);
}
public this(in TM m) pure nothrow @safe
in {
assert(!m.empty);
assert(m.all!(row => row.length == m.length));
} body {
a.length = m.length;
foreach (immutable i, const row; m)
a[i] = row.dup;
}
string toString() const @safe {
return format("<%(%(" ~ fmt ~ ", %)\n %)>", a);
}
public static SquareMat identity(in size_t side) pure nothrow @safe {
auto m = SquareMat(side);
foreach (immutable r, ref row; m.a)
foreach (immutable c; 0 .. side)
row[c] = (r == c) ? 1+0i : 0+0i;
return m;
}
public SquareMat opBinary(string op:"*")(in SquareMat other)
const pure nothrow @safe in {
assert (a.length == other.a.length);
} body {
immutable side = other.a.length;
auto d = SquareMat(side);
foreach (immutable r; 0 .. side)
foreach (immutable c; 0 .. side) {
d.a[r][c] = 0+0i;
foreach (immutable k, immutable ark; a[r])
d.a[r][c] += ark * other.a[k][c];
}
return d;
}
public SquareMat opBinary(string op:"^^")(int n)
const pure nothrow @safe in {
assert(n >= 0, "Negative exponent not implemented.");
} body {
auto sq = SquareMat(this.a);
auto d = SquareMat.identity(a.length);
for (; n > 0; sq = sq * sq, n >>= 1)
if (n & 1)
d = d * sq;
return d;
}
}
void main() {
alias M = SquareMat!();
enum real q = 0.5.sqrt;
immutable m = M([[ q + 0*1.0Li, q + 0*1.0Li, 0.0L + 0.0Li],
[0.0L - q*1.0Li, 0.0L + q*1.0Li, 0.0L + 0.0Li],
[0.0L + 0.0Li, 0.0L + 0.0Li, 0.0L + 1.0Li]]);
M.fmt = "%5.2f";
foreach (immutable p; [0, 1, 23, 24])
writefln("m ^^ %d =\n%s", p, m ^^ p);
}
| Option Base 1
Private Function Identity(n As Integer) As Variant
Dim I() As Variant
ReDim I(n, n)
For j = 1 To n
For k = 1 To n
I(j, k) = 0
Next k
Next j
For j = 1 To n
I(j, j) = 1
Next j
Identity = I
End Function
Function MatrixExponentiation(ByVal x As Variant, ByVal n As Integer) As Variant
If n < 0 Then
x = WorksheetFunction.MInverse(x)
n = -n
End If
If n = 0 Then
MatrixExponentiation = Identity(UBound(x))
Exit Function
End If
Dim y() As Variant
y = Identity(UBound(x))
Do While n > 1
If n Mod 2 = 0 Then
x = WorksheetFunction.MMult(x, x)
n = n / 2
Else
y = WorksheetFunction.MMult(x, y)
x = WorksheetFunction.MMult(x, x)
n = (n - 1) / 2
End If
Loop
MatrixExponentiation = WorksheetFunction.MMult(x, y)
End Function
Public Sub pp(x As Variant)
For i_ = 1 To UBound(x)
For j_ = 1 To UBound(x)
Debug.Print x(i_, j_),
Next j_
Debug.Print
Next i_
End Sub
Public Sub main()
M2 = [{3,2;2,1}]
M3 = [{1,2,0;0,3,1;1,0,0}]
pp MatrixExponentiation(M2, -1)
Debug.Print
pp MatrixExponentiation(M2, 0)
Debug.Print
pp MatrixExponentiation(M2, 10)
Debug.Print
pp MatrixExponentiation(M3, 10)
End Sub
|
Write the same algorithm in Go as shown in this D implementation. | import std.stdio, std.string, std.math, std.array, std.algorithm;
struct SquareMat(T = creal) {
public static string fmt = "%8.3f";
private alias TM = T[][];
private TM a;
public this(in size_t side) pure nothrow @safe
in {
assert(side > 0);
} body {
a = new TM(side, side);
}
public this(in TM m) pure nothrow @safe
in {
assert(!m.empty);
assert(m.all!(row => row.length == m.length));
} body {
a.length = m.length;
foreach (immutable i, const row; m)
a[i] = row.dup;
}
string toString() const @safe {
return format("<%(%(" ~ fmt ~ ", %)\n %)>", a);
}
public static SquareMat identity(in size_t side) pure nothrow @safe {
auto m = SquareMat(side);
foreach (immutable r, ref row; m.a)
foreach (immutable c; 0 .. side)
row[c] = (r == c) ? 1+0i : 0+0i;
return m;
}
public SquareMat opBinary(string op:"*")(in SquareMat other)
const pure nothrow @safe in {
assert (a.length == other.a.length);
} body {
immutable side = other.a.length;
auto d = SquareMat(side);
foreach (immutable r; 0 .. side)
foreach (immutable c; 0 .. side) {
d.a[r][c] = 0+0i;
foreach (immutable k, immutable ark; a[r])
d.a[r][c] += ark * other.a[k][c];
}
return d;
}
public SquareMat opBinary(string op:"^^")(int n)
const pure nothrow @safe in {
assert(n >= 0, "Negative exponent not implemented.");
} body {
auto sq = SquareMat(this.a);
auto d = SquareMat.identity(a.length);
for (; n > 0; sq = sq * sq, n >>= 1)
if (n & 1)
d = d * sq;
return d;
}
}
void main() {
alias M = SquareMat!();
enum real q = 0.5.sqrt;
immutable m = M([[ q + 0*1.0Li, q + 0*1.0Li, 0.0L + 0.0Li],
[0.0L - q*1.0Li, 0.0L + q*1.0Li, 0.0L + 0.0Li],
[0.0L + 0.0Li, 0.0L + 0.0Li, 0.0L + 1.0Li]]);
M.fmt = "%5.2f";
foreach (immutable p; [0, 1, 23, 24])
writefln("m ^^ %d =\n%s", p, m ^^ p);
}
| package main
import "fmt"
type vector = []float64
type matrix []vector
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != rows2 {
panic("Matrices cannot be multiplied.")
}
result := make(matrix, rows1)
for i := 0; i < rows1; i++ {
result[i] = make(vector, cols2)
for j := 0; j < cols2; j++ {
for k := 0; k < rows2; k++ {
result[i][j] += m1[i][k] * m2[k][j]
}
}
}
return result
}
func identityMatrix(n int) matrix {
if n < 1 {
panic("Size of identity matrix can't be less than 1")
}
ident := make(matrix, n)
for i := 0; i < n; i++ {
ident[i] = make(vector, n)
ident[i][i] = 1
}
return ident
}
func (m matrix) pow(n int) matrix {
le := len(m)
if le != len(m[0]) {
panic("Not a square matrix")
}
switch {
case n < 0:
panic("Negative exponents not supported")
case n == 0:
return identityMatrix(le)
case n == 1:
return m
}
pow := identityMatrix(le)
base := m
e := n
for e > 0 {
if (e & 1) == 1 {
pow = pow.mul(base)
}
e >>= 1
base = base.mul(base)
}
return pow
}
func main() {
m := matrix{{3, 2}, {2, 1}}
for i := 0; i <= 10; i++ {
fmt.Println("** Power of", i, "**")
fmt.Println(m.pow(i))
fmt.Println()
}
}
|
Translate the given Delphi code snippet into C without altering its behavior. | program Matrix_exponentiation_operator;
uses
System.SysUtils;
type
TCells = array of array of double;
TMatrix = record
private
FCells: TCells;
function GetCells(r, c: Integer): Double;
procedure SetCells(r, c: Integer; const Value: Double);
class operator Implicit(a: TMatrix): string;
class operator BitwiseXor(a: TMatrix; e: Integer): TMatrix;
class operator Multiply(a: TMatrix; b: TMatrix): TMatrix;
public
constructor Create(w, h: integer); overload;
constructor Create(c: TCells); overload;
constructor Ident(size: Integer);
function Rows: Integer;
function Columns: Integer;
property Cells[r, c: Integer]: Double read GetCells write SetCells; default;
end;
constructor TMatrix.Create(c: TCells);
begin
Create(Length(c), Length(c[0]));
FCells := c;
end;
constructor TMatrix.Create(w, h: integer);
begin
SetLength(FCells, w, h);
end;
class operator TMatrix.BitwiseXor(a: TMatrix; e: Integer): TMatrix;
begin
if e < 0 then
raise Exception.Create('Matrix inversion not implemented');
Result.Ident(a.Rows);
while e > 0 do
begin
Result := Result * a;
dec(e);
end;
end;
function TMatrix.Rows: Integer;
begin
Result := Length(FCells);
end;
function TMatrix.Columns: Integer;
begin
Result := 0;
if Rows > 0 then
Result := Length(FCells);
end;
function TMatrix.GetCells(r, c: Integer): Double;
begin
Result := FCells[r, c];
end;
constructor TMatrix.Ident(size: Integer);
var
i: Integer;
begin
Create(size, size);
for i := 0 to size - 1 do
Cells[i, i] := 1;
end;
class operator TMatrix.Implicit(a: TMatrix): string;
var
i, j: Integer;
begin
Result := '[';
if a.Rows > 0 then
for i := 0 to a.Rows - 1 do
begin
if i > 0 then
Result := Trim(Result) + ']'#10'[';
for j := 0 to a.Columns - 1 do
begin
Result := Result + Format('%f', [a[i, j]]) + ' ';
end;
end;
Result := trim(Result) + ']';
end;
class operator TMatrix.Multiply(a, b: TMatrix): TMatrix;
var
size: Integer;
r: Integer;
c: Integer;
k: Integer;
begin
if (a.Rows <> b.Rows) or (a.Columns <> b.Columns) then
raise Exception.Create('The matrix must have same size');
size := a.Rows;
Result.Create(size, size);
for r := 0 to size - 1 do
for c := 0 to size - 1 do
begin
Result[r, c] := 0;
for k := 0 to size - 1 do
Result[r, c] := Result[r, c] + a[r, k] * b[k, c];
end;
end;
procedure TMatrix.SetCells(r, c: Integer; const Value: Double);
begin
FCells[r, c] := Value;
end;
var
M: TMatrix;
begin
M.Create([[3, 2], [2, 1]]);
Writeln(string(M xor 0), #10);
Writeln(string(M xor 1), #10);
Writeln(string(M xor 2), #10);
Writeln(string(M xor 3), #10);
Writeln(string(M xor 4), #10);
Writeln(string(M xor 50), #10);
Readln;
end.
| #include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct squareMtxStruct {
int dim;
double *cells;
double **m;
} *SquareMtx;
typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data);
SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data )
{
SquareMtx sm = malloc(sizeof(struct squareMtxStruct));
if (sm) {
int rw;
sm->dim = dim;
sm->cells = malloc(dim*dim * sizeof(double));
sm->m = malloc( dim * sizeof(double *));
if ((sm->cells != NULL) && (sm->m != NULL)) {
for (rw=0; rw<dim; rw++) {
sm->m[rw] = sm->cells + dim*rw;
fillFunc( sm->m[rw], rw, dim, ff_data );
}
}
else {
free(sm->m);
free(sm->cells);
free(sm);
printf("Square Matrix allocation failure\n");
return NULL;
}
}
else {
printf("Malloc failed for square matrix\n");
}
return sm;
}
void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 )
{
int col, ix;
double sum;
double *m0rw = m0->m[rw];
for (col = 0; col < dim; col++) {
sum = 0.0;
for (ix=0; ix<dim; ix++)
sum += m0rw[ix] * m0->m[ix][col];
cells[col] = sum;
}
}
void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] )
{
SquareMtx mleft = mplcnds[0];
SquareMtx mrigt = mplcnds[1];
double sum;
double *m0rw = mleft->m[rw];
int col, ix;
for (col = 0; col < dim; col++) {
sum = 0.0;
for (ix=0; ix<dim; ix++)
sum += m0rw[ix] * mrigt->m[ix][col];
cells[col] = sum;
}
}
void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt)
{
int rw;
SquareMtx mplcnds[2];
mplcnds[0] = left; mplcnds[1] = rigt;
for (rw = 0; rw < left->dim; rw++)
ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds);
}
void ffIdentity( double *cells, int rw, int dim, void *v )
{
int col;
for (col=0; col<dim; col++) cells[col] = 0.0;
cells[rw] = 1.0;
}
void ffCopy(double *cells, int rw, int dim, SquareMtx m1)
{
int col;
for (col=0; col<dim; col++) cells[col] = m1->m[rw][col];
}
void FreeSquareMtx( SquareMtx m )
{
free(m->m);
free(m->cells);
free(m);
}
SquareMtx SquareMtxPow( SquareMtx m0, int exp )
{
SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL);
SquareMtx v1 = NULL;
SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0);
SquareMtx base1 = NULL;
SquareMtx mplcnds[2], t;
while (exp) {
if (exp % 2) {
if (v1)
MatxMul( v1, v0, base0);
else {
mplcnds[0] = v0; mplcnds[1] = base0;
v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds);
}
{t = v0; v0=v1; v1 = t;}
}
if (base1)
MatxMul( base1, base0, base0);
else
base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0);
t = base0; base0 = base1; base1 = t;
exp = exp/2;
}
if (base0) FreeSquareMtx(base0);
if (base1) FreeSquareMtx(base1);
if (v1) FreeSquareMtx(v1);
return v0;
}
FILE *fout;
void SquareMtxPrint( SquareMtx mtx, const char *mn )
{
int rw, col;
int d = mtx->dim;
fprintf(fout, "%s dim:%d =\n", mn, mtx->dim);
for (rw=0; rw<d; rw++) {
fprintf(fout, " |");
for(col=0; col<d; col++)
fprintf(fout, "%8.5f ",mtx->m[rw][col] );
fprintf(fout, " |\n");
}
fprintf(fout, "\n");
}
void fillInit( double *cells, int rw, int dim, void *data)
{
double theta = 3.1415926536/6.0;
double c1 = cos( theta);
double s1 = sin( theta);
switch(rw) {
case 0:
cells[0]=c1; cells[1]=s1; cells[2]=0.0;
break;
case 1:
cells[0]=-s1; cells[1]=c1; cells[2]=0;
break;
case 2:
cells[0]=0.0; cells[1]=0.0; cells[2]=1.0;
break;
}
}
int main()
{
SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL);
SquareMtx m1 = SquareMtxPow( m0, 5);
SquareMtx m2 = SquareMtxPow( m0, 9);
SquareMtx m3 = SquareMtxPow( m0, 2);
fout = fopen("matrx_exp.txt", "w");
SquareMtxPrint(m0, "m0"); FreeSquareMtx(m0);
SquareMtxPrint(m1, "m0^5"); FreeSquareMtx(m1);
SquareMtxPrint(m2, "m0^9"); FreeSquareMtx(m2);
SquareMtxPrint(m3, "m0^2"); FreeSquareMtx(m3);
fclose(fout);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Delphi to C#. | program Matrix_exponentiation_operator;
uses
System.SysUtils;
type
TCells = array of array of double;
TMatrix = record
private
FCells: TCells;
function GetCells(r, c: Integer): Double;
procedure SetCells(r, c: Integer; const Value: Double);
class operator Implicit(a: TMatrix): string;
class operator BitwiseXor(a: TMatrix; e: Integer): TMatrix;
class operator Multiply(a: TMatrix; b: TMatrix): TMatrix;
public
constructor Create(w, h: integer); overload;
constructor Create(c: TCells); overload;
constructor Ident(size: Integer);
function Rows: Integer;
function Columns: Integer;
property Cells[r, c: Integer]: Double read GetCells write SetCells; default;
end;
constructor TMatrix.Create(c: TCells);
begin
Create(Length(c), Length(c[0]));
FCells := c;
end;
constructor TMatrix.Create(w, h: integer);
begin
SetLength(FCells, w, h);
end;
class operator TMatrix.BitwiseXor(a: TMatrix; e: Integer): TMatrix;
begin
if e < 0 then
raise Exception.Create('Matrix inversion not implemented');
Result.Ident(a.Rows);
while e > 0 do
begin
Result := Result * a;
dec(e);
end;
end;
function TMatrix.Rows: Integer;
begin
Result := Length(FCells);
end;
function TMatrix.Columns: Integer;
begin
Result := 0;
if Rows > 0 then
Result := Length(FCells);
end;
function TMatrix.GetCells(r, c: Integer): Double;
begin
Result := FCells[r, c];
end;
constructor TMatrix.Ident(size: Integer);
var
i: Integer;
begin
Create(size, size);
for i := 0 to size - 1 do
Cells[i, i] := 1;
end;
class operator TMatrix.Implicit(a: TMatrix): string;
var
i, j: Integer;
begin
Result := '[';
if a.Rows > 0 then
for i := 0 to a.Rows - 1 do
begin
if i > 0 then
Result := Trim(Result) + ']'#10'[';
for j := 0 to a.Columns - 1 do
begin
Result := Result + Format('%f', [a[i, j]]) + ' ';
end;
end;
Result := trim(Result) + ']';
end;
class operator TMatrix.Multiply(a, b: TMatrix): TMatrix;
var
size: Integer;
r: Integer;
c: Integer;
k: Integer;
begin
if (a.Rows <> b.Rows) or (a.Columns <> b.Columns) then
raise Exception.Create('The matrix must have same size');
size := a.Rows;
Result.Create(size, size);
for r := 0 to size - 1 do
for c := 0 to size - 1 do
begin
Result[r, c] := 0;
for k := 0 to size - 1 do
Result[r, c] := Result[r, c] + a[r, k] * b[k, c];
end;
end;
procedure TMatrix.SetCells(r, c: Integer; const Value: Double);
begin
FCells[r, c] := Value;
end;
var
M: TMatrix;
begin
M.Create([[3, 2], [2, 1]]);
Writeln(string(M xor 0), #10);
Writeln(string(M xor 1), #10);
Writeln(string(M xor 2), #10);
Writeln(string(M xor 3), #10);
Writeln(string(M xor 4), #10);
Writeln(string(M xor 50), #10);
Readln;
end.
| using System;
using System.Collections;
using System.Collections.Generic;
using static System.Linq.Enumerable;
public static class MatrixExponentation
{
public static double[,] Identity(int size) {
double[,] matrix = new double[size, size];
for (int i = 0; i < size; i++) matrix[i, i] = 1;
return matrix;
}
public static double[,] Multiply(this double[,] left, double[,] right) {
if (left.ColumnCount() != right.RowCount()) throw new ArgumentException();
double[,] m = new double[left.RowCount(), right.ColumnCount()];
foreach (var (row, column) in from r in Range(0, m.RowCount()) from c in Range(0, m.ColumnCount()) select (r, c)) {
m[row, column] = Range(0, m.RowCount()).Sum(i => left[row, i] * right[i, column]);
}
return m;
}
public static double[,] Pow(this double[,] matrix, int exp) {
if (matrix.RowCount() != matrix.ColumnCount()) throw new ArgumentException("Matrix must be square.");
double[,] accumulator = Identity(matrix.RowCount());
for (int i = 0; i < exp; i++) {
accumulator = accumulator.Multiply(matrix);
}
return accumulator;
}
private static int RowCount(this double[,] matrix) => matrix.GetLength(0);
private static int ColumnCount(this double[,] matrix) => matrix.GetLength(1);
private static void Print(this double[,] m) {
foreach (var row in Rows()) {
Console.WriteLine("[ " + string.Join(" ", row) + " ]");
}
Console.WriteLine();
IEnumerable<IEnumerable<double>> Rows() =>
Range(0, m.RowCount()).Select(row => Range(0, m.ColumnCount()).Select(column => m[row, column]));
}
public static void Main() {
var matrix = new double[,] {
{ 3, 2 },
{ 2, 1 }
};
matrix.Pow(0).Print();
matrix.Pow(1).Print();
matrix.Pow(2).Print();
matrix.Pow(3).Print();
matrix.Pow(4).Print();
matrix.Pow(50).Print();
}
}
|
Transform the following Delphi implementation into C++, maintaining the same output and logic. | program Matrix_exponentiation_operator;
uses
System.SysUtils;
type
TCells = array of array of double;
TMatrix = record
private
FCells: TCells;
function GetCells(r, c: Integer): Double;
procedure SetCells(r, c: Integer; const Value: Double);
class operator Implicit(a: TMatrix): string;
class operator BitwiseXor(a: TMatrix; e: Integer): TMatrix;
class operator Multiply(a: TMatrix; b: TMatrix): TMatrix;
public
constructor Create(w, h: integer); overload;
constructor Create(c: TCells); overload;
constructor Ident(size: Integer);
function Rows: Integer;
function Columns: Integer;
property Cells[r, c: Integer]: Double read GetCells write SetCells; default;
end;
constructor TMatrix.Create(c: TCells);
begin
Create(Length(c), Length(c[0]));
FCells := c;
end;
constructor TMatrix.Create(w, h: integer);
begin
SetLength(FCells, w, h);
end;
class operator TMatrix.BitwiseXor(a: TMatrix; e: Integer): TMatrix;
begin
if e < 0 then
raise Exception.Create('Matrix inversion not implemented');
Result.Ident(a.Rows);
while e > 0 do
begin
Result := Result * a;
dec(e);
end;
end;
function TMatrix.Rows: Integer;
begin
Result := Length(FCells);
end;
function TMatrix.Columns: Integer;
begin
Result := 0;
if Rows > 0 then
Result := Length(FCells);
end;
function TMatrix.GetCells(r, c: Integer): Double;
begin
Result := FCells[r, c];
end;
constructor TMatrix.Ident(size: Integer);
var
i: Integer;
begin
Create(size, size);
for i := 0 to size - 1 do
Cells[i, i] := 1;
end;
class operator TMatrix.Implicit(a: TMatrix): string;
var
i, j: Integer;
begin
Result := '[';
if a.Rows > 0 then
for i := 0 to a.Rows - 1 do
begin
if i > 0 then
Result := Trim(Result) + ']'#10'[';
for j := 0 to a.Columns - 1 do
begin
Result := Result + Format('%f', [a[i, j]]) + ' ';
end;
end;
Result := trim(Result) + ']';
end;
class operator TMatrix.Multiply(a, b: TMatrix): TMatrix;
var
size: Integer;
r: Integer;
c: Integer;
k: Integer;
begin
if (a.Rows <> b.Rows) or (a.Columns <> b.Columns) then
raise Exception.Create('The matrix must have same size');
size := a.Rows;
Result.Create(size, size);
for r := 0 to size - 1 do
for c := 0 to size - 1 do
begin
Result[r, c] := 0;
for k := 0 to size - 1 do
Result[r, c] := Result[r, c] + a[r, k] * b[k, c];
end;
end;
procedure TMatrix.SetCells(r, c: Integer; const Value: Double);
begin
FCells[r, c] := Value;
end;
var
M: TMatrix;
begin
M.Create([[3, 2], [2, 1]]);
Writeln(string(M xor 0), #10);
Writeln(string(M xor 1), #10);
Writeln(string(M xor 2), #10);
Writeln(string(M xor 3), #10);
Writeln(string(M xor 4), #10);
Writeln(string(M xor 50), #10);
Readln;
end.
| #include <complex>
#include <cmath>
#include <iostream>
using namespace std;
template<int MSize = 3, class T = complex<double> >
class SqMx {
typedef T Ax[MSize][MSize];
typedef SqMx<MSize, T> Mx;
private:
Ax a;
SqMx() { }
public:
SqMx(const Ax &_a) {
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++)
a[r][c] = _a[r][c];
}
static Mx identity() {
Mx m;
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++)
m.a[r][c] = (r == c ? 1 : 0);
return m;
}
friend ostream &operator<<(ostream& os, const Mx &p)
{
for (int i = 0; i < MSize; i++) {
for (int j = 0; j < MSize; j++)
os << p.a[i][j] << ',';
os << endl;
}
return os;
}
Mx operator*(const Mx &b) {
Mx d;
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++) {
d.a[r][c] = 0;
for (int k = 0; k < MSize; k++)
d.a[r][c] += a[r][k] * b.a[k][c];
}
return d;
}
|
Change the following Delphi code into Python without altering its purpose. | program Matrix_exponentiation_operator;
uses
System.SysUtils;
type
TCells = array of array of double;
TMatrix = record
private
FCells: TCells;
function GetCells(r, c: Integer): Double;
procedure SetCells(r, c: Integer; const Value: Double);
class operator Implicit(a: TMatrix): string;
class operator BitwiseXor(a: TMatrix; e: Integer): TMatrix;
class operator Multiply(a: TMatrix; b: TMatrix): TMatrix;
public
constructor Create(w, h: integer); overload;
constructor Create(c: TCells); overload;
constructor Ident(size: Integer);
function Rows: Integer;
function Columns: Integer;
property Cells[r, c: Integer]: Double read GetCells write SetCells; default;
end;
constructor TMatrix.Create(c: TCells);
begin
Create(Length(c), Length(c[0]));
FCells := c;
end;
constructor TMatrix.Create(w, h: integer);
begin
SetLength(FCells, w, h);
end;
class operator TMatrix.BitwiseXor(a: TMatrix; e: Integer): TMatrix;
begin
if e < 0 then
raise Exception.Create('Matrix inversion not implemented');
Result.Ident(a.Rows);
while e > 0 do
begin
Result := Result * a;
dec(e);
end;
end;
function TMatrix.Rows: Integer;
begin
Result := Length(FCells);
end;
function TMatrix.Columns: Integer;
begin
Result := 0;
if Rows > 0 then
Result := Length(FCells);
end;
function TMatrix.GetCells(r, c: Integer): Double;
begin
Result := FCells[r, c];
end;
constructor TMatrix.Ident(size: Integer);
var
i: Integer;
begin
Create(size, size);
for i := 0 to size - 1 do
Cells[i, i] := 1;
end;
class operator TMatrix.Implicit(a: TMatrix): string;
var
i, j: Integer;
begin
Result := '[';
if a.Rows > 0 then
for i := 0 to a.Rows - 1 do
begin
if i > 0 then
Result := Trim(Result) + ']'#10'[';
for j := 0 to a.Columns - 1 do
begin
Result := Result + Format('%f', [a[i, j]]) + ' ';
end;
end;
Result := trim(Result) + ']';
end;
class operator TMatrix.Multiply(a, b: TMatrix): TMatrix;
var
size: Integer;
r: Integer;
c: Integer;
k: Integer;
begin
if (a.Rows <> b.Rows) or (a.Columns <> b.Columns) then
raise Exception.Create('The matrix must have same size');
size := a.Rows;
Result.Create(size, size);
for r := 0 to size - 1 do
for c := 0 to size - 1 do
begin
Result[r, c] := 0;
for k := 0 to size - 1 do
Result[r, c] := Result[r, c] + a[r, k] * b[k, c];
end;
end;
procedure TMatrix.SetCells(r, c: Integer; const Value: Double);
begin
FCells[r, c] := Value;
end;
var
M: TMatrix;
begin
M.Create([[3, 2], [2, 1]]);
Writeln(string(M xor 0), #10);
Writeln(string(M xor 1), #10);
Writeln(string(M xor 2), #10);
Writeln(string(M xor 3), #10);
Writeln(string(M xor 4), #10);
Writeln(string(M xor 50), #10);
Readln;
end.
| >>> from operator import mul
>>> def matrixMul(m1, m2):
return map(
lambda row:
map(
lambda *column:
sum(map(mul, row, column)),
*m2),
m1)
>>> def identity(size):
size = range(size)
return [[(i==j)*1 for i in size] for j in size]
>>> def matrixExp(m, pow):
assert pow>=0 and int(pow)==pow, "Only non-negative, integer powers allowed"
accumulator = identity(len(m))
for i in range(pow):
accumulator = matrixMul(accumulator, m)
return accumulator
>>> def printtable(data):
for row in data:
print ' '.join('%-5s' % ('%s' % cell) for cell in row)
>>> m = [[3,2], [2,1]]
>>> for i in range(5):
print '\n%i:' % i
printtable( matrixExp(m, i) )
0:
1 0
0 1
1:
3 2
2 1
2:
13 8
8 5
3:
55 34
34 21
4:
233 144
144 89
>>> printtable( matrixExp(m, 10) )
1346269 832040
832040 514229
>>>
|
Change the programming language of this snippet from Delphi to VB without modifying what it does. | program Matrix_exponentiation_operator;
uses
System.SysUtils;
type
TCells = array of array of double;
TMatrix = record
private
FCells: TCells;
function GetCells(r, c: Integer): Double;
procedure SetCells(r, c: Integer; const Value: Double);
class operator Implicit(a: TMatrix): string;
class operator BitwiseXor(a: TMatrix; e: Integer): TMatrix;
class operator Multiply(a: TMatrix; b: TMatrix): TMatrix;
public
constructor Create(w, h: integer); overload;
constructor Create(c: TCells); overload;
constructor Ident(size: Integer);
function Rows: Integer;
function Columns: Integer;
property Cells[r, c: Integer]: Double read GetCells write SetCells; default;
end;
constructor TMatrix.Create(c: TCells);
begin
Create(Length(c), Length(c[0]));
FCells := c;
end;
constructor TMatrix.Create(w, h: integer);
begin
SetLength(FCells, w, h);
end;
class operator TMatrix.BitwiseXor(a: TMatrix; e: Integer): TMatrix;
begin
if e < 0 then
raise Exception.Create('Matrix inversion not implemented');
Result.Ident(a.Rows);
while e > 0 do
begin
Result := Result * a;
dec(e);
end;
end;
function TMatrix.Rows: Integer;
begin
Result := Length(FCells);
end;
function TMatrix.Columns: Integer;
begin
Result := 0;
if Rows > 0 then
Result := Length(FCells);
end;
function TMatrix.GetCells(r, c: Integer): Double;
begin
Result := FCells[r, c];
end;
constructor TMatrix.Ident(size: Integer);
var
i: Integer;
begin
Create(size, size);
for i := 0 to size - 1 do
Cells[i, i] := 1;
end;
class operator TMatrix.Implicit(a: TMatrix): string;
var
i, j: Integer;
begin
Result := '[';
if a.Rows > 0 then
for i := 0 to a.Rows - 1 do
begin
if i > 0 then
Result := Trim(Result) + ']'#10'[';
for j := 0 to a.Columns - 1 do
begin
Result := Result + Format('%f', [a[i, j]]) + ' ';
end;
end;
Result := trim(Result) + ']';
end;
class operator TMatrix.Multiply(a, b: TMatrix): TMatrix;
var
size: Integer;
r: Integer;
c: Integer;
k: Integer;
begin
if (a.Rows <> b.Rows) or (a.Columns <> b.Columns) then
raise Exception.Create('The matrix must have same size');
size := a.Rows;
Result.Create(size, size);
for r := 0 to size - 1 do
for c := 0 to size - 1 do
begin
Result[r, c] := 0;
for k := 0 to size - 1 do
Result[r, c] := Result[r, c] + a[r, k] * b[k, c];
end;
end;
procedure TMatrix.SetCells(r, c: Integer; const Value: Double);
begin
FCells[r, c] := Value;
end;
var
M: TMatrix;
begin
M.Create([[3, 2], [2, 1]]);
Writeln(string(M xor 0), #10);
Writeln(string(M xor 1), #10);
Writeln(string(M xor 2), #10);
Writeln(string(M xor 3), #10);
Writeln(string(M xor 4), #10);
Writeln(string(M xor 50), #10);
Readln;
end.
| Option Base 1
Private Function Identity(n As Integer) As Variant
Dim I() As Variant
ReDim I(n, n)
For j = 1 To n
For k = 1 To n
I(j, k) = 0
Next k
Next j
For j = 1 To n
I(j, j) = 1
Next j
Identity = I
End Function
Function MatrixExponentiation(ByVal x As Variant, ByVal n As Integer) As Variant
If n < 0 Then
x = WorksheetFunction.MInverse(x)
n = -n
End If
If n = 0 Then
MatrixExponentiation = Identity(UBound(x))
Exit Function
End If
Dim y() As Variant
y = Identity(UBound(x))
Do While n > 1
If n Mod 2 = 0 Then
x = WorksheetFunction.MMult(x, x)
n = n / 2
Else
y = WorksheetFunction.MMult(x, y)
x = WorksheetFunction.MMult(x, x)
n = (n - 1) / 2
End If
Loop
MatrixExponentiation = WorksheetFunction.MMult(x, y)
End Function
Public Sub pp(x As Variant)
For i_ = 1 To UBound(x)
For j_ = 1 To UBound(x)
Debug.Print x(i_, j_),
Next j_
Debug.Print
Next i_
End Sub
Public Sub main()
M2 = [{3,2;2,1}]
M3 = [{1,2,0;0,3,1;1,0,0}]
pp MatrixExponentiation(M2, -1)
Debug.Print
pp MatrixExponentiation(M2, 0)
Debug.Print
pp MatrixExponentiation(M2, 10)
Debug.Print
pp MatrixExponentiation(M3, 10)
End Sub
|
Translate this program into Go but keep the logic exactly as in Delphi. | program Matrix_exponentiation_operator;
uses
System.SysUtils;
type
TCells = array of array of double;
TMatrix = record
private
FCells: TCells;
function GetCells(r, c: Integer): Double;
procedure SetCells(r, c: Integer; const Value: Double);
class operator Implicit(a: TMatrix): string;
class operator BitwiseXor(a: TMatrix; e: Integer): TMatrix;
class operator Multiply(a: TMatrix; b: TMatrix): TMatrix;
public
constructor Create(w, h: integer); overload;
constructor Create(c: TCells); overload;
constructor Ident(size: Integer);
function Rows: Integer;
function Columns: Integer;
property Cells[r, c: Integer]: Double read GetCells write SetCells; default;
end;
constructor TMatrix.Create(c: TCells);
begin
Create(Length(c), Length(c[0]));
FCells := c;
end;
constructor TMatrix.Create(w, h: integer);
begin
SetLength(FCells, w, h);
end;
class operator TMatrix.BitwiseXor(a: TMatrix; e: Integer): TMatrix;
begin
if e < 0 then
raise Exception.Create('Matrix inversion not implemented');
Result.Ident(a.Rows);
while e > 0 do
begin
Result := Result * a;
dec(e);
end;
end;
function TMatrix.Rows: Integer;
begin
Result := Length(FCells);
end;
function TMatrix.Columns: Integer;
begin
Result := 0;
if Rows > 0 then
Result := Length(FCells);
end;
function TMatrix.GetCells(r, c: Integer): Double;
begin
Result := FCells[r, c];
end;
constructor TMatrix.Ident(size: Integer);
var
i: Integer;
begin
Create(size, size);
for i := 0 to size - 1 do
Cells[i, i] := 1;
end;
class operator TMatrix.Implicit(a: TMatrix): string;
var
i, j: Integer;
begin
Result := '[';
if a.Rows > 0 then
for i := 0 to a.Rows - 1 do
begin
if i > 0 then
Result := Trim(Result) + ']'#10'[';
for j := 0 to a.Columns - 1 do
begin
Result := Result + Format('%f', [a[i, j]]) + ' ';
end;
end;
Result := trim(Result) + ']';
end;
class operator TMatrix.Multiply(a, b: TMatrix): TMatrix;
var
size: Integer;
r: Integer;
c: Integer;
k: Integer;
begin
if (a.Rows <> b.Rows) or (a.Columns <> b.Columns) then
raise Exception.Create('The matrix must have same size');
size := a.Rows;
Result.Create(size, size);
for r := 0 to size - 1 do
for c := 0 to size - 1 do
begin
Result[r, c] := 0;
for k := 0 to size - 1 do
Result[r, c] := Result[r, c] + a[r, k] * b[k, c];
end;
end;
procedure TMatrix.SetCells(r, c: Integer; const Value: Double);
begin
FCells[r, c] := Value;
end;
var
M: TMatrix;
begin
M.Create([[3, 2], [2, 1]]);
Writeln(string(M xor 0), #10);
Writeln(string(M xor 1), #10);
Writeln(string(M xor 2), #10);
Writeln(string(M xor 3), #10);
Writeln(string(M xor 4), #10);
Writeln(string(M xor 50), #10);
Readln;
end.
| package main
import "fmt"
type vector = []float64
type matrix []vector
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != rows2 {
panic("Matrices cannot be multiplied.")
}
result := make(matrix, rows1)
for i := 0; i < rows1; i++ {
result[i] = make(vector, cols2)
for j := 0; j < cols2; j++ {
for k := 0; k < rows2; k++ {
result[i][j] += m1[i][k] * m2[k][j]
}
}
}
return result
}
func identityMatrix(n int) matrix {
if n < 1 {
panic("Size of identity matrix can't be less than 1")
}
ident := make(matrix, n)
for i := 0; i < n; i++ {
ident[i] = make(vector, n)
ident[i][i] = 1
}
return ident
}
func (m matrix) pow(n int) matrix {
le := len(m)
if le != len(m[0]) {
panic("Not a square matrix")
}
switch {
case n < 0:
panic("Negative exponents not supported")
case n == 0:
return identityMatrix(le)
case n == 1:
return m
}
pow := identityMatrix(le)
base := m
e := n
for e > 0 {
if (e & 1) == 1 {
pow = pow.mul(base)
}
e >>= 1
base = base.mul(base)
}
return pow
}
func main() {
m := matrix{{3, 2}, {2, 1}}
for i := 0; i <= 10; i++ {
fmt.Println("** Power of", i, "**")
fmt.Println(m.pow(i))
fmt.Println()
}
}
|
Rewrite the snippet below in C so it works the same as the original Factor code. | USING: kernel math math.matrices sequences ;
: my-m^n ( m n -- m' )
dup 0 < [ "no negative exponents" throw ] [
[ drop length identity-matrix ]
[ swap '[ _ m. ] times ] 2bi
] if ;
| #include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct squareMtxStruct {
int dim;
double *cells;
double **m;
} *SquareMtx;
typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data);
SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data )
{
SquareMtx sm = malloc(sizeof(struct squareMtxStruct));
if (sm) {
int rw;
sm->dim = dim;
sm->cells = malloc(dim*dim * sizeof(double));
sm->m = malloc( dim * sizeof(double *));
if ((sm->cells != NULL) && (sm->m != NULL)) {
for (rw=0; rw<dim; rw++) {
sm->m[rw] = sm->cells + dim*rw;
fillFunc( sm->m[rw], rw, dim, ff_data );
}
}
else {
free(sm->m);
free(sm->cells);
free(sm);
printf("Square Matrix allocation failure\n");
return NULL;
}
}
else {
printf("Malloc failed for square matrix\n");
}
return sm;
}
void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 )
{
int col, ix;
double sum;
double *m0rw = m0->m[rw];
for (col = 0; col < dim; col++) {
sum = 0.0;
for (ix=0; ix<dim; ix++)
sum += m0rw[ix] * m0->m[ix][col];
cells[col] = sum;
}
}
void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] )
{
SquareMtx mleft = mplcnds[0];
SquareMtx mrigt = mplcnds[1];
double sum;
double *m0rw = mleft->m[rw];
int col, ix;
for (col = 0; col < dim; col++) {
sum = 0.0;
for (ix=0; ix<dim; ix++)
sum += m0rw[ix] * mrigt->m[ix][col];
cells[col] = sum;
}
}
void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt)
{
int rw;
SquareMtx mplcnds[2];
mplcnds[0] = left; mplcnds[1] = rigt;
for (rw = 0; rw < left->dim; rw++)
ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds);
}
void ffIdentity( double *cells, int rw, int dim, void *v )
{
int col;
for (col=0; col<dim; col++) cells[col] = 0.0;
cells[rw] = 1.0;
}
void ffCopy(double *cells, int rw, int dim, SquareMtx m1)
{
int col;
for (col=0; col<dim; col++) cells[col] = m1->m[rw][col];
}
void FreeSquareMtx( SquareMtx m )
{
free(m->m);
free(m->cells);
free(m);
}
SquareMtx SquareMtxPow( SquareMtx m0, int exp )
{
SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL);
SquareMtx v1 = NULL;
SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0);
SquareMtx base1 = NULL;
SquareMtx mplcnds[2], t;
while (exp) {
if (exp % 2) {
if (v1)
MatxMul( v1, v0, base0);
else {
mplcnds[0] = v0; mplcnds[1] = base0;
v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds);
}
{t = v0; v0=v1; v1 = t;}
}
if (base1)
MatxMul( base1, base0, base0);
else
base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0);
t = base0; base0 = base1; base1 = t;
exp = exp/2;
}
if (base0) FreeSquareMtx(base0);
if (base1) FreeSquareMtx(base1);
if (v1) FreeSquareMtx(v1);
return v0;
}
FILE *fout;
void SquareMtxPrint( SquareMtx mtx, const char *mn )
{
int rw, col;
int d = mtx->dim;
fprintf(fout, "%s dim:%d =\n", mn, mtx->dim);
for (rw=0; rw<d; rw++) {
fprintf(fout, " |");
for(col=0; col<d; col++)
fprintf(fout, "%8.5f ",mtx->m[rw][col] );
fprintf(fout, " |\n");
}
fprintf(fout, "\n");
}
void fillInit( double *cells, int rw, int dim, void *data)
{
double theta = 3.1415926536/6.0;
double c1 = cos( theta);
double s1 = sin( theta);
switch(rw) {
case 0:
cells[0]=c1; cells[1]=s1; cells[2]=0.0;
break;
case 1:
cells[0]=-s1; cells[1]=c1; cells[2]=0;
break;
case 2:
cells[0]=0.0; cells[1]=0.0; cells[2]=1.0;
break;
}
}
int main()
{
SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL);
SquareMtx m1 = SquareMtxPow( m0, 5);
SquareMtx m2 = SquareMtxPow( m0, 9);
SquareMtx m3 = SquareMtxPow( m0, 2);
fout = fopen("matrx_exp.txt", "w");
SquareMtxPrint(m0, "m0"); FreeSquareMtx(m0);
SquareMtxPrint(m1, "m0^5"); FreeSquareMtx(m1);
SquareMtxPrint(m2, "m0^9"); FreeSquareMtx(m2);
SquareMtxPrint(m3, "m0^2"); FreeSquareMtx(m3);
fclose(fout);
return 0;
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Factor version. | USING: kernel math math.matrices sequences ;
: my-m^n ( m n -- m' )
dup 0 < [ "no negative exponents" throw ] [
[ drop length identity-matrix ]
[ swap '[ _ m. ] times ] 2bi
] if ;
| using System;
using System.Collections;
using System.Collections.Generic;
using static System.Linq.Enumerable;
public static class MatrixExponentation
{
public static double[,] Identity(int size) {
double[,] matrix = new double[size, size];
for (int i = 0; i < size; i++) matrix[i, i] = 1;
return matrix;
}
public static double[,] Multiply(this double[,] left, double[,] right) {
if (left.ColumnCount() != right.RowCount()) throw new ArgumentException();
double[,] m = new double[left.RowCount(), right.ColumnCount()];
foreach (var (row, column) in from r in Range(0, m.RowCount()) from c in Range(0, m.ColumnCount()) select (r, c)) {
m[row, column] = Range(0, m.RowCount()).Sum(i => left[row, i] * right[i, column]);
}
return m;
}
public static double[,] Pow(this double[,] matrix, int exp) {
if (matrix.RowCount() != matrix.ColumnCount()) throw new ArgumentException("Matrix must be square.");
double[,] accumulator = Identity(matrix.RowCount());
for (int i = 0; i < exp; i++) {
accumulator = accumulator.Multiply(matrix);
}
return accumulator;
}
private static int RowCount(this double[,] matrix) => matrix.GetLength(0);
private static int ColumnCount(this double[,] matrix) => matrix.GetLength(1);
private static void Print(this double[,] m) {
foreach (var row in Rows()) {
Console.WriteLine("[ " + string.Join(" ", row) + " ]");
}
Console.WriteLine();
IEnumerable<IEnumerable<double>> Rows() =>
Range(0, m.RowCount()).Select(row => Range(0, m.ColumnCount()).Select(column => m[row, column]));
}
public static void Main() {
var matrix = new double[,] {
{ 3, 2 },
{ 2, 1 }
};
matrix.Pow(0).Print();
matrix.Pow(1).Print();
matrix.Pow(2).Print();
matrix.Pow(3).Print();
matrix.Pow(4).Print();
matrix.Pow(50).Print();
}
}
|
Convert this Factor block to C++, preserving its control flow and logic. | USING: kernel math math.matrices sequences ;
: my-m^n ( m n -- m' )
dup 0 < [ "no negative exponents" throw ] [
[ drop length identity-matrix ]
[ swap '[ _ m. ] times ] 2bi
] if ;
| #include <complex>
#include <cmath>
#include <iostream>
using namespace std;
template<int MSize = 3, class T = complex<double> >
class SqMx {
typedef T Ax[MSize][MSize];
typedef SqMx<MSize, T> Mx;
private:
Ax a;
SqMx() { }
public:
SqMx(const Ax &_a) {
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++)
a[r][c] = _a[r][c];
}
static Mx identity() {
Mx m;
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++)
m.a[r][c] = (r == c ? 1 : 0);
return m;
}
friend ostream &operator<<(ostream& os, const Mx &p)
{
for (int i = 0; i < MSize; i++) {
for (int j = 0; j < MSize; j++)
os << p.a[i][j] << ',';
os << endl;
}
return os;
}
Mx operator*(const Mx &b) {
Mx d;
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++) {
d.a[r][c] = 0;
for (int k = 0; k < MSize; k++)
d.a[r][c] += a[r][k] * b.a[k][c];
}
return d;
}
|
Port the provided Factor code into Python while preserving the original functionality. | USING: kernel math math.matrices sequences ;
: my-m^n ( m n -- m' )
dup 0 < [ "no negative exponents" throw ] [
[ drop length identity-matrix ]
[ swap '[ _ m. ] times ] 2bi
] if ;
| >>> from operator import mul
>>> def matrixMul(m1, m2):
return map(
lambda row:
map(
lambda *column:
sum(map(mul, row, column)),
*m2),
m1)
>>> def identity(size):
size = range(size)
return [[(i==j)*1 for i in size] for j in size]
>>> def matrixExp(m, pow):
assert pow>=0 and int(pow)==pow, "Only non-negative, integer powers allowed"
accumulator = identity(len(m))
for i in range(pow):
accumulator = matrixMul(accumulator, m)
return accumulator
>>> def printtable(data):
for row in data:
print ' '.join('%-5s' % ('%s' % cell) for cell in row)
>>> m = [[3,2], [2,1]]
>>> for i in range(5):
print '\n%i:' % i
printtable( matrixExp(m, i) )
0:
1 0
0 1
1:
3 2
2 1
2:
13 8
8 5
3:
55 34
34 21
4:
233 144
144 89
>>> printtable( matrixExp(m, 10) )
1346269 832040
832040 514229
>>>
|
Please provide an equivalent version of this Factor code in VB. | USING: kernel math math.matrices sequences ;
: my-m^n ( m n -- m' )
dup 0 < [ "no negative exponents" throw ] [
[ drop length identity-matrix ]
[ swap '[ _ m. ] times ] 2bi
] if ;
| Option Base 1
Private Function Identity(n As Integer) As Variant
Dim I() As Variant
ReDim I(n, n)
For j = 1 To n
For k = 1 To n
I(j, k) = 0
Next k
Next j
For j = 1 To n
I(j, j) = 1
Next j
Identity = I
End Function
Function MatrixExponentiation(ByVal x As Variant, ByVal n As Integer) As Variant
If n < 0 Then
x = WorksheetFunction.MInverse(x)
n = -n
End If
If n = 0 Then
MatrixExponentiation = Identity(UBound(x))
Exit Function
End If
Dim y() As Variant
y = Identity(UBound(x))
Do While n > 1
If n Mod 2 = 0 Then
x = WorksheetFunction.MMult(x, x)
n = n / 2
Else
y = WorksheetFunction.MMult(x, y)
x = WorksheetFunction.MMult(x, x)
n = (n - 1) / 2
End If
Loop
MatrixExponentiation = WorksheetFunction.MMult(x, y)
End Function
Public Sub pp(x As Variant)
For i_ = 1 To UBound(x)
For j_ = 1 To UBound(x)
Debug.Print x(i_, j_),
Next j_
Debug.Print
Next i_
End Sub
Public Sub main()
M2 = [{3,2;2,1}]
M3 = [{1,2,0;0,3,1;1,0,0}]
pp MatrixExponentiation(M2, -1)
Debug.Print
pp MatrixExponentiation(M2, 0)
Debug.Print
pp MatrixExponentiation(M2, 10)
Debug.Print
pp MatrixExponentiation(M3, 10)
End Sub
|
Convert the following code from Factor to Go, ensuring the logic remains intact. | USING: kernel math math.matrices sequences ;
: my-m^n ( m n -- m' )
dup 0 < [ "no negative exponents" throw ] [
[ drop length identity-matrix ]
[ swap '[ _ m. ] times ] 2bi
] if ;
| package main
import "fmt"
type vector = []float64
type matrix []vector
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != rows2 {
panic("Matrices cannot be multiplied.")
}
result := make(matrix, rows1)
for i := 0; i < rows1; i++ {
result[i] = make(vector, cols2)
for j := 0; j < cols2; j++ {
for k := 0; k < rows2; k++ {
result[i][j] += m1[i][k] * m2[k][j]
}
}
}
return result
}
func identityMatrix(n int) matrix {
if n < 1 {
panic("Size of identity matrix can't be less than 1")
}
ident := make(matrix, n)
for i := 0; i < n; i++ {
ident[i] = make(vector, n)
ident[i][i] = 1
}
return ident
}
func (m matrix) pow(n int) matrix {
le := len(m)
if le != len(m[0]) {
panic("Not a square matrix")
}
switch {
case n < 0:
panic("Negative exponents not supported")
case n == 0:
return identityMatrix(le)
case n == 1:
return m
}
pow := identityMatrix(le)
base := m
e := n
for e > 0 {
if (e & 1) == 1 {
pow = pow.mul(base)
}
e >>= 1
base = base.mul(base)
}
return pow
}
func main() {
m := matrix{{3, 2}, {2, 1}}
for i := 0; i <= 10; i++ {
fmt.Println("** Power of", i, "**")
fmt.Println(m.pow(i))
fmt.Println()
}
}
|
Translate the given Fortran code snippet into C# without altering its behavior. | module matmod
implicit none
interface operator (.matpow.)
module procedure matrix_exp
end interface
contains
function matrix_exp(m, n) result (res)
real, intent(in) :: m(:,:)
integer, intent(in) :: n
real :: res(size(m,1),size(m,2))
integer :: i
if(n == 0) then
res = 0
do i = 1, size(m,1)
res(i,i) = 1
end do
return
end if
res = m
do i = 2, n
res = matmul(res, m)
end do
end function matrix_exp
end module matmod
program Matrix_exponentiation
use matmod
implicit none
integer, parameter :: n = 3
real, dimension(n,n) :: m1, m2
integer :: i, j
m1 = reshape((/ (i, i = 1, n*n) /), (/ n, n /), order = (/ 2, 1 /))
do i = 0, 4
m2 = m1 .matpow. i
do j = 1, size(m2,1)
write(*,*) m2(j,:)
end do
write(*,*)
end do
end program Matrix_exponentiation
| using System;
using System.Collections;
using System.Collections.Generic;
using static System.Linq.Enumerable;
public static class MatrixExponentation
{
public static double[,] Identity(int size) {
double[,] matrix = new double[size, size];
for (int i = 0; i < size; i++) matrix[i, i] = 1;
return matrix;
}
public static double[,] Multiply(this double[,] left, double[,] right) {
if (left.ColumnCount() != right.RowCount()) throw new ArgumentException();
double[,] m = new double[left.RowCount(), right.ColumnCount()];
foreach (var (row, column) in from r in Range(0, m.RowCount()) from c in Range(0, m.ColumnCount()) select (r, c)) {
m[row, column] = Range(0, m.RowCount()).Sum(i => left[row, i] * right[i, column]);
}
return m;
}
public static double[,] Pow(this double[,] matrix, int exp) {
if (matrix.RowCount() != matrix.ColumnCount()) throw new ArgumentException("Matrix must be square.");
double[,] accumulator = Identity(matrix.RowCount());
for (int i = 0; i < exp; i++) {
accumulator = accumulator.Multiply(matrix);
}
return accumulator;
}
private static int RowCount(this double[,] matrix) => matrix.GetLength(0);
private static int ColumnCount(this double[,] matrix) => matrix.GetLength(1);
private static void Print(this double[,] m) {
foreach (var row in Rows()) {
Console.WriteLine("[ " + string.Join(" ", row) + " ]");
}
Console.WriteLine();
IEnumerable<IEnumerable<double>> Rows() =>
Range(0, m.RowCount()).Select(row => Range(0, m.ColumnCount()).Select(column => m[row, column]));
}
public static void Main() {
var matrix = new double[,] {
{ 3, 2 },
{ 2, 1 }
};
matrix.Pow(0).Print();
matrix.Pow(1).Print();
matrix.Pow(2).Print();
matrix.Pow(3).Print();
matrix.Pow(4).Print();
matrix.Pow(50).Print();
}
}
|
Translate this program into C++ but keep the logic exactly as in Fortran. | module matmod
implicit none
interface operator (.matpow.)
module procedure matrix_exp
end interface
contains
function matrix_exp(m, n) result (res)
real, intent(in) :: m(:,:)
integer, intent(in) :: n
real :: res(size(m,1),size(m,2))
integer :: i
if(n == 0) then
res = 0
do i = 1, size(m,1)
res(i,i) = 1
end do
return
end if
res = m
do i = 2, n
res = matmul(res, m)
end do
end function matrix_exp
end module matmod
program Matrix_exponentiation
use matmod
implicit none
integer, parameter :: n = 3
real, dimension(n,n) :: m1, m2
integer :: i, j
m1 = reshape((/ (i, i = 1, n*n) /), (/ n, n /), order = (/ 2, 1 /))
do i = 0, 4
m2 = m1 .matpow. i
do j = 1, size(m2,1)
write(*,*) m2(j,:)
end do
write(*,*)
end do
end program Matrix_exponentiation
| #include <complex>
#include <cmath>
#include <iostream>
using namespace std;
template<int MSize = 3, class T = complex<double> >
class SqMx {
typedef T Ax[MSize][MSize];
typedef SqMx<MSize, T> Mx;
private:
Ax a;
SqMx() { }
public:
SqMx(const Ax &_a) {
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++)
a[r][c] = _a[r][c];
}
static Mx identity() {
Mx m;
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++)
m.a[r][c] = (r == c ? 1 : 0);
return m;
}
friend ostream &operator<<(ostream& os, const Mx &p)
{
for (int i = 0; i < MSize; i++) {
for (int j = 0; j < MSize; j++)
os << p.a[i][j] << ',';
os << endl;
}
return os;
}
Mx operator*(const Mx &b) {
Mx d;
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++) {
d.a[r][c] = 0;
for (int k = 0; k < MSize; k++)
d.a[r][c] += a[r][k] * b.a[k][c];
}
return d;
}
|
Transform the following Fortran implementation into C, maintaining the same output and logic. | module matmod
implicit none
interface operator (.matpow.)
module procedure matrix_exp
end interface
contains
function matrix_exp(m, n) result (res)
real, intent(in) :: m(:,:)
integer, intent(in) :: n
real :: res(size(m,1),size(m,2))
integer :: i
if(n == 0) then
res = 0
do i = 1, size(m,1)
res(i,i) = 1
end do
return
end if
res = m
do i = 2, n
res = matmul(res, m)
end do
end function matrix_exp
end module matmod
program Matrix_exponentiation
use matmod
implicit none
integer, parameter :: n = 3
real, dimension(n,n) :: m1, m2
integer :: i, j
m1 = reshape((/ (i, i = 1, n*n) /), (/ n, n /), order = (/ 2, 1 /))
do i = 0, 4
m2 = m1 .matpow. i
do j = 1, size(m2,1)
write(*,*) m2(j,:)
end do
write(*,*)
end do
end program Matrix_exponentiation
| #include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct squareMtxStruct {
int dim;
double *cells;
double **m;
} *SquareMtx;
typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data);
SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data )
{
SquareMtx sm = malloc(sizeof(struct squareMtxStruct));
if (sm) {
int rw;
sm->dim = dim;
sm->cells = malloc(dim*dim * sizeof(double));
sm->m = malloc( dim * sizeof(double *));
if ((sm->cells != NULL) && (sm->m != NULL)) {
for (rw=0; rw<dim; rw++) {
sm->m[rw] = sm->cells + dim*rw;
fillFunc( sm->m[rw], rw, dim, ff_data );
}
}
else {
free(sm->m);
free(sm->cells);
free(sm);
printf("Square Matrix allocation failure\n");
return NULL;
}
}
else {
printf("Malloc failed for square matrix\n");
}
return sm;
}
void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 )
{
int col, ix;
double sum;
double *m0rw = m0->m[rw];
for (col = 0; col < dim; col++) {
sum = 0.0;
for (ix=0; ix<dim; ix++)
sum += m0rw[ix] * m0->m[ix][col];
cells[col] = sum;
}
}
void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] )
{
SquareMtx mleft = mplcnds[0];
SquareMtx mrigt = mplcnds[1];
double sum;
double *m0rw = mleft->m[rw];
int col, ix;
for (col = 0; col < dim; col++) {
sum = 0.0;
for (ix=0; ix<dim; ix++)
sum += m0rw[ix] * mrigt->m[ix][col];
cells[col] = sum;
}
}
void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt)
{
int rw;
SquareMtx mplcnds[2];
mplcnds[0] = left; mplcnds[1] = rigt;
for (rw = 0; rw < left->dim; rw++)
ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds);
}
void ffIdentity( double *cells, int rw, int dim, void *v )
{
int col;
for (col=0; col<dim; col++) cells[col] = 0.0;
cells[rw] = 1.0;
}
void ffCopy(double *cells, int rw, int dim, SquareMtx m1)
{
int col;
for (col=0; col<dim; col++) cells[col] = m1->m[rw][col];
}
void FreeSquareMtx( SquareMtx m )
{
free(m->m);
free(m->cells);
free(m);
}
SquareMtx SquareMtxPow( SquareMtx m0, int exp )
{
SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL);
SquareMtx v1 = NULL;
SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0);
SquareMtx base1 = NULL;
SquareMtx mplcnds[2], t;
while (exp) {
if (exp % 2) {
if (v1)
MatxMul( v1, v0, base0);
else {
mplcnds[0] = v0; mplcnds[1] = base0;
v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds);
}
{t = v0; v0=v1; v1 = t;}
}
if (base1)
MatxMul( base1, base0, base0);
else
base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0);
t = base0; base0 = base1; base1 = t;
exp = exp/2;
}
if (base0) FreeSquareMtx(base0);
if (base1) FreeSquareMtx(base1);
if (v1) FreeSquareMtx(v1);
return v0;
}
FILE *fout;
void SquareMtxPrint( SquareMtx mtx, const char *mn )
{
int rw, col;
int d = mtx->dim;
fprintf(fout, "%s dim:%d =\n", mn, mtx->dim);
for (rw=0; rw<d; rw++) {
fprintf(fout, " |");
for(col=0; col<d; col++)
fprintf(fout, "%8.5f ",mtx->m[rw][col] );
fprintf(fout, " |\n");
}
fprintf(fout, "\n");
}
void fillInit( double *cells, int rw, int dim, void *data)
{
double theta = 3.1415926536/6.0;
double c1 = cos( theta);
double s1 = sin( theta);
switch(rw) {
case 0:
cells[0]=c1; cells[1]=s1; cells[2]=0.0;
break;
case 1:
cells[0]=-s1; cells[1]=c1; cells[2]=0;
break;
case 2:
cells[0]=0.0; cells[1]=0.0; cells[2]=1.0;
break;
}
}
int main()
{
SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL);
SquareMtx m1 = SquareMtxPow( m0, 5);
SquareMtx m2 = SquareMtxPow( m0, 9);
SquareMtx m3 = SquareMtxPow( m0, 2);
fout = fopen("matrx_exp.txt", "w");
SquareMtxPrint(m0, "m0"); FreeSquareMtx(m0);
SquareMtxPrint(m1, "m0^5"); FreeSquareMtx(m1);
SquareMtxPrint(m2, "m0^9"); FreeSquareMtx(m2);
SquareMtxPrint(m3, "m0^2"); FreeSquareMtx(m3);
fclose(fout);
return 0;
}
|
Generate an equivalent Python version of this Fortran code. | module matmod
implicit none
interface operator (.matpow.)
module procedure matrix_exp
end interface
contains
function matrix_exp(m, n) result (res)
real, intent(in) :: m(:,:)
integer, intent(in) :: n
real :: res(size(m,1),size(m,2))
integer :: i
if(n == 0) then
res = 0
do i = 1, size(m,1)
res(i,i) = 1
end do
return
end if
res = m
do i = 2, n
res = matmul(res, m)
end do
end function matrix_exp
end module matmod
program Matrix_exponentiation
use matmod
implicit none
integer, parameter :: n = 3
real, dimension(n,n) :: m1, m2
integer :: i, j
m1 = reshape((/ (i, i = 1, n*n) /), (/ n, n /), order = (/ 2, 1 /))
do i = 0, 4
m2 = m1 .matpow. i
do j = 1, size(m2,1)
write(*,*) m2(j,:)
end do
write(*,*)
end do
end program Matrix_exponentiation
| >>> from operator import mul
>>> def matrixMul(m1, m2):
return map(
lambda row:
map(
lambda *column:
sum(map(mul, row, column)),
*m2),
m1)
>>> def identity(size):
size = range(size)
return [[(i==j)*1 for i in size] for j in size]
>>> def matrixExp(m, pow):
assert pow>=0 and int(pow)==pow, "Only non-negative, integer powers allowed"
accumulator = identity(len(m))
for i in range(pow):
accumulator = matrixMul(accumulator, m)
return accumulator
>>> def printtable(data):
for row in data:
print ' '.join('%-5s' % ('%s' % cell) for cell in row)
>>> m = [[3,2], [2,1]]
>>> for i in range(5):
print '\n%i:' % i
printtable( matrixExp(m, i) )
0:
1 0
0 1
1:
3 2
2 1
2:
13 8
8 5
3:
55 34
34 21
4:
233 144
144 89
>>> printtable( matrixExp(m, 10) )
1346269 832040
832040 514229
>>>
|
Ensure the translated VB code behaves exactly like the original Fortran snippet. | module matmod
implicit none
interface operator (.matpow.)
module procedure matrix_exp
end interface
contains
function matrix_exp(m, n) result (res)
real, intent(in) :: m(:,:)
integer, intent(in) :: n
real :: res(size(m,1),size(m,2))
integer :: i
if(n == 0) then
res = 0
do i = 1, size(m,1)
res(i,i) = 1
end do
return
end if
res = m
do i = 2, n
res = matmul(res, m)
end do
end function matrix_exp
end module matmod
program Matrix_exponentiation
use matmod
implicit none
integer, parameter :: n = 3
real, dimension(n,n) :: m1, m2
integer :: i, j
m1 = reshape((/ (i, i = 1, n*n) /), (/ n, n /), order = (/ 2, 1 /))
do i = 0, 4
m2 = m1 .matpow. i
do j = 1, size(m2,1)
write(*,*) m2(j,:)
end do
write(*,*)
end do
end program Matrix_exponentiation
| Option Base 1
Private Function Identity(n As Integer) As Variant
Dim I() As Variant
ReDim I(n, n)
For j = 1 To n
For k = 1 To n
I(j, k) = 0
Next k
Next j
For j = 1 To n
I(j, j) = 1
Next j
Identity = I
End Function
Function MatrixExponentiation(ByVal x As Variant, ByVal n As Integer) As Variant
If n < 0 Then
x = WorksheetFunction.MInverse(x)
n = -n
End If
If n = 0 Then
MatrixExponentiation = Identity(UBound(x))
Exit Function
End If
Dim y() As Variant
y = Identity(UBound(x))
Do While n > 1
If n Mod 2 = 0 Then
x = WorksheetFunction.MMult(x, x)
n = n / 2
Else
y = WorksheetFunction.MMult(x, y)
x = WorksheetFunction.MMult(x, x)
n = (n - 1) / 2
End If
Loop
MatrixExponentiation = WorksheetFunction.MMult(x, y)
End Function
Public Sub pp(x As Variant)
For i_ = 1 To UBound(x)
For j_ = 1 To UBound(x)
Debug.Print x(i_, j_),
Next j_
Debug.Print
Next i_
End Sub
Public Sub main()
M2 = [{3,2;2,1}]
M3 = [{1,2,0;0,3,1;1,0,0}]
pp MatrixExponentiation(M2, -1)
Debug.Print
pp MatrixExponentiation(M2, 0)
Debug.Print
pp MatrixExponentiation(M2, 10)
Debug.Print
pp MatrixExponentiation(M3, 10)
End Sub
|
Keep all operations the same but rewrite the snippet in C. | import Data.List (transpose)
(<+>)
:: Num a
=> [a] -> [a] -> [a]
(<+>) = zipWith (+)
(<*>)
:: Num a
=> [a] -> [a] -> a
(<*>) = (sum .) . zipWith (*)
newtype Mat a =
Mat [[a]]
deriving (Eq, Show)
instance Num a =>
Num (Mat a) where
negate (Mat x) = Mat $ map (map negate) x
Mat x + Mat y = Mat $ zipWith (<+>) x y
Mat x * Mat y =
Mat
[ [ xs Main.<*> ys
| ys <- transpose y ]
| xs <- x ]
abs = undefined
fromInteger _ = undefined
signum = undefined
main :: IO ()
main = print $ Mat [[1, 2], [0, 1]] ^ 4
| #include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct squareMtxStruct {
int dim;
double *cells;
double **m;
} *SquareMtx;
typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data);
SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data )
{
SquareMtx sm = malloc(sizeof(struct squareMtxStruct));
if (sm) {
int rw;
sm->dim = dim;
sm->cells = malloc(dim*dim * sizeof(double));
sm->m = malloc( dim * sizeof(double *));
if ((sm->cells != NULL) && (sm->m != NULL)) {
for (rw=0; rw<dim; rw++) {
sm->m[rw] = sm->cells + dim*rw;
fillFunc( sm->m[rw], rw, dim, ff_data );
}
}
else {
free(sm->m);
free(sm->cells);
free(sm);
printf("Square Matrix allocation failure\n");
return NULL;
}
}
else {
printf("Malloc failed for square matrix\n");
}
return sm;
}
void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 )
{
int col, ix;
double sum;
double *m0rw = m0->m[rw];
for (col = 0; col < dim; col++) {
sum = 0.0;
for (ix=0; ix<dim; ix++)
sum += m0rw[ix] * m0->m[ix][col];
cells[col] = sum;
}
}
void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] )
{
SquareMtx mleft = mplcnds[0];
SquareMtx mrigt = mplcnds[1];
double sum;
double *m0rw = mleft->m[rw];
int col, ix;
for (col = 0; col < dim; col++) {
sum = 0.0;
for (ix=0; ix<dim; ix++)
sum += m0rw[ix] * mrigt->m[ix][col];
cells[col] = sum;
}
}
void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt)
{
int rw;
SquareMtx mplcnds[2];
mplcnds[0] = left; mplcnds[1] = rigt;
for (rw = 0; rw < left->dim; rw++)
ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds);
}
void ffIdentity( double *cells, int rw, int dim, void *v )
{
int col;
for (col=0; col<dim; col++) cells[col] = 0.0;
cells[rw] = 1.0;
}
void ffCopy(double *cells, int rw, int dim, SquareMtx m1)
{
int col;
for (col=0; col<dim; col++) cells[col] = m1->m[rw][col];
}
void FreeSquareMtx( SquareMtx m )
{
free(m->m);
free(m->cells);
free(m);
}
SquareMtx SquareMtxPow( SquareMtx m0, int exp )
{
SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL);
SquareMtx v1 = NULL;
SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0);
SquareMtx base1 = NULL;
SquareMtx mplcnds[2], t;
while (exp) {
if (exp % 2) {
if (v1)
MatxMul( v1, v0, base0);
else {
mplcnds[0] = v0; mplcnds[1] = base0;
v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds);
}
{t = v0; v0=v1; v1 = t;}
}
if (base1)
MatxMul( base1, base0, base0);
else
base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0);
t = base0; base0 = base1; base1 = t;
exp = exp/2;
}
if (base0) FreeSquareMtx(base0);
if (base1) FreeSquareMtx(base1);
if (v1) FreeSquareMtx(v1);
return v0;
}
FILE *fout;
void SquareMtxPrint( SquareMtx mtx, const char *mn )
{
int rw, col;
int d = mtx->dim;
fprintf(fout, "%s dim:%d =\n", mn, mtx->dim);
for (rw=0; rw<d; rw++) {
fprintf(fout, " |");
for(col=0; col<d; col++)
fprintf(fout, "%8.5f ",mtx->m[rw][col] );
fprintf(fout, " |\n");
}
fprintf(fout, "\n");
}
void fillInit( double *cells, int rw, int dim, void *data)
{
double theta = 3.1415926536/6.0;
double c1 = cos( theta);
double s1 = sin( theta);
switch(rw) {
case 0:
cells[0]=c1; cells[1]=s1; cells[2]=0.0;
break;
case 1:
cells[0]=-s1; cells[1]=c1; cells[2]=0;
break;
case 2:
cells[0]=0.0; cells[1]=0.0; cells[2]=1.0;
break;
}
}
int main()
{
SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL);
SquareMtx m1 = SquareMtxPow( m0, 5);
SquareMtx m2 = SquareMtxPow( m0, 9);
SquareMtx m3 = SquareMtxPow( m0, 2);
fout = fopen("matrx_exp.txt", "w");
SquareMtxPrint(m0, "m0"); FreeSquareMtx(m0);
SquareMtxPrint(m1, "m0^5"); FreeSquareMtx(m1);
SquareMtxPrint(m2, "m0^9"); FreeSquareMtx(m2);
SquareMtxPrint(m3, "m0^2"); FreeSquareMtx(m3);
fclose(fout);
return 0;
}
|
Port the following code from Haskell to C# with equivalent syntax and logic. | import Data.List (transpose)
(<+>)
:: Num a
=> [a] -> [a] -> [a]
(<+>) = zipWith (+)
(<*>)
:: Num a
=> [a] -> [a] -> a
(<*>) = (sum .) . zipWith (*)
newtype Mat a =
Mat [[a]]
deriving (Eq, Show)
instance Num a =>
Num (Mat a) where
negate (Mat x) = Mat $ map (map negate) x
Mat x + Mat y = Mat $ zipWith (<+>) x y
Mat x * Mat y =
Mat
[ [ xs Main.<*> ys
| ys <- transpose y ]
| xs <- x ]
abs = undefined
fromInteger _ = undefined
signum = undefined
main :: IO ()
main = print $ Mat [[1, 2], [0, 1]] ^ 4
| using System;
using System.Collections;
using System.Collections.Generic;
using static System.Linq.Enumerable;
public static class MatrixExponentation
{
public static double[,] Identity(int size) {
double[,] matrix = new double[size, size];
for (int i = 0; i < size; i++) matrix[i, i] = 1;
return matrix;
}
public static double[,] Multiply(this double[,] left, double[,] right) {
if (left.ColumnCount() != right.RowCount()) throw new ArgumentException();
double[,] m = new double[left.RowCount(), right.ColumnCount()];
foreach (var (row, column) in from r in Range(0, m.RowCount()) from c in Range(0, m.ColumnCount()) select (r, c)) {
m[row, column] = Range(0, m.RowCount()).Sum(i => left[row, i] * right[i, column]);
}
return m;
}
public static double[,] Pow(this double[,] matrix, int exp) {
if (matrix.RowCount() != matrix.ColumnCount()) throw new ArgumentException("Matrix must be square.");
double[,] accumulator = Identity(matrix.RowCount());
for (int i = 0; i < exp; i++) {
accumulator = accumulator.Multiply(matrix);
}
return accumulator;
}
private static int RowCount(this double[,] matrix) => matrix.GetLength(0);
private static int ColumnCount(this double[,] matrix) => matrix.GetLength(1);
private static void Print(this double[,] m) {
foreach (var row in Rows()) {
Console.WriteLine("[ " + string.Join(" ", row) + " ]");
}
Console.WriteLine();
IEnumerable<IEnumerable<double>> Rows() =>
Range(0, m.RowCount()).Select(row => Range(0, m.ColumnCount()).Select(column => m[row, column]));
}
public static void Main() {
var matrix = new double[,] {
{ 3, 2 },
{ 2, 1 }
};
matrix.Pow(0).Print();
matrix.Pow(1).Print();
matrix.Pow(2).Print();
matrix.Pow(3).Print();
matrix.Pow(4).Print();
matrix.Pow(50).Print();
}
}
|
Generate a C++ translation of this Haskell snippet without changing its computational steps. | import Data.List (transpose)
(<+>)
:: Num a
=> [a] -> [a] -> [a]
(<+>) = zipWith (+)
(<*>)
:: Num a
=> [a] -> [a] -> a
(<*>) = (sum .) . zipWith (*)
newtype Mat a =
Mat [[a]]
deriving (Eq, Show)
instance Num a =>
Num (Mat a) where
negate (Mat x) = Mat $ map (map negate) x
Mat x + Mat y = Mat $ zipWith (<+>) x y
Mat x * Mat y =
Mat
[ [ xs Main.<*> ys
| ys <- transpose y ]
| xs <- x ]
abs = undefined
fromInteger _ = undefined
signum = undefined
main :: IO ()
main = print $ Mat [[1, 2], [0, 1]] ^ 4
| #include <complex>
#include <cmath>
#include <iostream>
using namespace std;
template<int MSize = 3, class T = complex<double> >
class SqMx {
typedef T Ax[MSize][MSize];
typedef SqMx<MSize, T> Mx;
private:
Ax a;
SqMx() { }
public:
SqMx(const Ax &_a) {
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++)
a[r][c] = _a[r][c];
}
static Mx identity() {
Mx m;
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++)
m.a[r][c] = (r == c ? 1 : 0);
return m;
}
friend ostream &operator<<(ostream& os, const Mx &p)
{
for (int i = 0; i < MSize; i++) {
for (int j = 0; j < MSize; j++)
os << p.a[i][j] << ',';
os << endl;
}
return os;
}
Mx operator*(const Mx &b) {
Mx d;
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++) {
d.a[r][c] = 0;
for (int k = 0; k < MSize; k++)
d.a[r][c] += a[r][k] * b.a[k][c];
}
return d;
}
|
Port the provided Haskell code into Python while preserving the original functionality. | import Data.List (transpose)
(<+>)
:: Num a
=> [a] -> [a] -> [a]
(<+>) = zipWith (+)
(<*>)
:: Num a
=> [a] -> [a] -> a
(<*>) = (sum .) . zipWith (*)
newtype Mat a =
Mat [[a]]
deriving (Eq, Show)
instance Num a =>
Num (Mat a) where
negate (Mat x) = Mat $ map (map negate) x
Mat x + Mat y = Mat $ zipWith (<+>) x y
Mat x * Mat y =
Mat
[ [ xs Main.<*> ys
| ys <- transpose y ]
| xs <- x ]
abs = undefined
fromInteger _ = undefined
signum = undefined
main :: IO ()
main = print $ Mat [[1, 2], [0, 1]] ^ 4
| >>> from operator import mul
>>> def matrixMul(m1, m2):
return map(
lambda row:
map(
lambda *column:
sum(map(mul, row, column)),
*m2),
m1)
>>> def identity(size):
size = range(size)
return [[(i==j)*1 for i in size] for j in size]
>>> def matrixExp(m, pow):
assert pow>=0 and int(pow)==pow, "Only non-negative, integer powers allowed"
accumulator = identity(len(m))
for i in range(pow):
accumulator = matrixMul(accumulator, m)
return accumulator
>>> def printtable(data):
for row in data:
print ' '.join('%-5s' % ('%s' % cell) for cell in row)
>>> m = [[3,2], [2,1]]
>>> for i in range(5):
print '\n%i:' % i
printtable( matrixExp(m, i) )
0:
1 0
0 1
1:
3 2
2 1
2:
13 8
8 5
3:
55 34
34 21
4:
233 144
144 89
>>> printtable( matrixExp(m, 10) )
1346269 832040
832040 514229
>>>
|
Maintain the same structure and functionality when rewriting this code in VB. | import Data.List (transpose)
(<+>)
:: Num a
=> [a] -> [a] -> [a]
(<+>) = zipWith (+)
(<*>)
:: Num a
=> [a] -> [a] -> a
(<*>) = (sum .) . zipWith (*)
newtype Mat a =
Mat [[a]]
deriving (Eq, Show)
instance Num a =>
Num (Mat a) where
negate (Mat x) = Mat $ map (map negate) x
Mat x + Mat y = Mat $ zipWith (<+>) x y
Mat x * Mat y =
Mat
[ [ xs Main.<*> ys
| ys <- transpose y ]
| xs <- x ]
abs = undefined
fromInteger _ = undefined
signum = undefined
main :: IO ()
main = print $ Mat [[1, 2], [0, 1]] ^ 4
| Option Base 1
Private Function Identity(n As Integer) As Variant
Dim I() As Variant
ReDim I(n, n)
For j = 1 To n
For k = 1 To n
I(j, k) = 0
Next k
Next j
For j = 1 To n
I(j, j) = 1
Next j
Identity = I
End Function
Function MatrixExponentiation(ByVal x As Variant, ByVal n As Integer) As Variant
If n < 0 Then
x = WorksheetFunction.MInverse(x)
n = -n
End If
If n = 0 Then
MatrixExponentiation = Identity(UBound(x))
Exit Function
End If
Dim y() As Variant
y = Identity(UBound(x))
Do While n > 1
If n Mod 2 = 0 Then
x = WorksheetFunction.MMult(x, x)
n = n / 2
Else
y = WorksheetFunction.MMult(x, y)
x = WorksheetFunction.MMult(x, x)
n = (n - 1) / 2
End If
Loop
MatrixExponentiation = WorksheetFunction.MMult(x, y)
End Function
Public Sub pp(x As Variant)
For i_ = 1 To UBound(x)
For j_ = 1 To UBound(x)
Debug.Print x(i_, j_),
Next j_
Debug.Print
Next i_
End Sub
Public Sub main()
M2 = [{3,2;2,1}]
M3 = [{1,2,0;0,3,1;1,0,0}]
pp MatrixExponentiation(M2, -1)
Debug.Print
pp MatrixExponentiation(M2, 0)
Debug.Print
pp MatrixExponentiation(M2, 10)
Debug.Print
pp MatrixExponentiation(M3, 10)
End Sub
|
Produce a functionally identical Go code for the snippet given in Haskell. | import Data.List (transpose)
(<+>)
:: Num a
=> [a] -> [a] -> [a]
(<+>) = zipWith (+)
(<*>)
:: Num a
=> [a] -> [a] -> a
(<*>) = (sum .) . zipWith (*)
newtype Mat a =
Mat [[a]]
deriving (Eq, Show)
instance Num a =>
Num (Mat a) where
negate (Mat x) = Mat $ map (map negate) x
Mat x + Mat y = Mat $ zipWith (<+>) x y
Mat x * Mat y =
Mat
[ [ xs Main.<*> ys
| ys <- transpose y ]
| xs <- x ]
abs = undefined
fromInteger _ = undefined
signum = undefined
main :: IO ()
main = print $ Mat [[1, 2], [0, 1]] ^ 4
| package main
import "fmt"
type vector = []float64
type matrix []vector
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != rows2 {
panic("Matrices cannot be multiplied.")
}
result := make(matrix, rows1)
for i := 0; i < rows1; i++ {
result[i] = make(vector, cols2)
for j := 0; j < cols2; j++ {
for k := 0; k < rows2; k++ {
result[i][j] += m1[i][k] * m2[k][j]
}
}
}
return result
}
func identityMatrix(n int) matrix {
if n < 1 {
panic("Size of identity matrix can't be less than 1")
}
ident := make(matrix, n)
for i := 0; i < n; i++ {
ident[i] = make(vector, n)
ident[i][i] = 1
}
return ident
}
func (m matrix) pow(n int) matrix {
le := len(m)
if le != len(m[0]) {
panic("Not a square matrix")
}
switch {
case n < 0:
panic("Negative exponents not supported")
case n == 0:
return identityMatrix(le)
case n == 1:
return m
}
pow := identityMatrix(le)
base := m
e := n
for e > 0 {
if (e & 1) == 1 {
pow = pow.mul(base)
}
e >>= 1
base = base.mul(base)
}
return pow
}
func main() {
m := matrix{{3, 2}, {2, 1}}
for i := 0; i <= 10; i++ {
fmt.Println("** Power of", i, "**")
fmt.Println(m.pow(i))
fmt.Println()
}
}
|
Change the following J code into C without altering its purpose. | mp=: +/ .*
pow=: pow0=: 4 : 'mp&x^:y =i.#x'
| #include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct squareMtxStruct {
int dim;
double *cells;
double **m;
} *SquareMtx;
typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data);
SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data )
{
SquareMtx sm = malloc(sizeof(struct squareMtxStruct));
if (sm) {
int rw;
sm->dim = dim;
sm->cells = malloc(dim*dim * sizeof(double));
sm->m = malloc( dim * sizeof(double *));
if ((sm->cells != NULL) && (sm->m != NULL)) {
for (rw=0; rw<dim; rw++) {
sm->m[rw] = sm->cells + dim*rw;
fillFunc( sm->m[rw], rw, dim, ff_data );
}
}
else {
free(sm->m);
free(sm->cells);
free(sm);
printf("Square Matrix allocation failure\n");
return NULL;
}
}
else {
printf("Malloc failed for square matrix\n");
}
return sm;
}
void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 )
{
int col, ix;
double sum;
double *m0rw = m0->m[rw];
for (col = 0; col < dim; col++) {
sum = 0.0;
for (ix=0; ix<dim; ix++)
sum += m0rw[ix] * m0->m[ix][col];
cells[col] = sum;
}
}
void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] )
{
SquareMtx mleft = mplcnds[0];
SquareMtx mrigt = mplcnds[1];
double sum;
double *m0rw = mleft->m[rw];
int col, ix;
for (col = 0; col < dim; col++) {
sum = 0.0;
for (ix=0; ix<dim; ix++)
sum += m0rw[ix] * mrigt->m[ix][col];
cells[col] = sum;
}
}
void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt)
{
int rw;
SquareMtx mplcnds[2];
mplcnds[0] = left; mplcnds[1] = rigt;
for (rw = 0; rw < left->dim; rw++)
ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds);
}
void ffIdentity( double *cells, int rw, int dim, void *v )
{
int col;
for (col=0; col<dim; col++) cells[col] = 0.0;
cells[rw] = 1.0;
}
void ffCopy(double *cells, int rw, int dim, SquareMtx m1)
{
int col;
for (col=0; col<dim; col++) cells[col] = m1->m[rw][col];
}
void FreeSquareMtx( SquareMtx m )
{
free(m->m);
free(m->cells);
free(m);
}
SquareMtx SquareMtxPow( SquareMtx m0, int exp )
{
SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL);
SquareMtx v1 = NULL;
SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0);
SquareMtx base1 = NULL;
SquareMtx mplcnds[2], t;
while (exp) {
if (exp % 2) {
if (v1)
MatxMul( v1, v0, base0);
else {
mplcnds[0] = v0; mplcnds[1] = base0;
v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds);
}
{t = v0; v0=v1; v1 = t;}
}
if (base1)
MatxMul( base1, base0, base0);
else
base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0);
t = base0; base0 = base1; base1 = t;
exp = exp/2;
}
if (base0) FreeSquareMtx(base0);
if (base1) FreeSquareMtx(base1);
if (v1) FreeSquareMtx(v1);
return v0;
}
FILE *fout;
void SquareMtxPrint( SquareMtx mtx, const char *mn )
{
int rw, col;
int d = mtx->dim;
fprintf(fout, "%s dim:%d =\n", mn, mtx->dim);
for (rw=0; rw<d; rw++) {
fprintf(fout, " |");
for(col=0; col<d; col++)
fprintf(fout, "%8.5f ",mtx->m[rw][col] );
fprintf(fout, " |\n");
}
fprintf(fout, "\n");
}
void fillInit( double *cells, int rw, int dim, void *data)
{
double theta = 3.1415926536/6.0;
double c1 = cos( theta);
double s1 = sin( theta);
switch(rw) {
case 0:
cells[0]=c1; cells[1]=s1; cells[2]=0.0;
break;
case 1:
cells[0]=-s1; cells[1]=c1; cells[2]=0;
break;
case 2:
cells[0]=0.0; cells[1]=0.0; cells[2]=1.0;
break;
}
}
int main()
{
SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL);
SquareMtx m1 = SquareMtxPow( m0, 5);
SquareMtx m2 = SquareMtxPow( m0, 9);
SquareMtx m3 = SquareMtxPow( m0, 2);
fout = fopen("matrx_exp.txt", "w");
SquareMtxPrint(m0, "m0"); FreeSquareMtx(m0);
SquareMtxPrint(m1, "m0^5"); FreeSquareMtx(m1);
SquareMtxPrint(m2, "m0^9"); FreeSquareMtx(m2);
SquareMtxPrint(m3, "m0^2"); FreeSquareMtx(m3);
fclose(fout);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C#. | mp=: +/ .*
pow=: pow0=: 4 : 'mp&x^:y =i.#x'
| using System;
using System.Collections;
using System.Collections.Generic;
using static System.Linq.Enumerable;
public static class MatrixExponentation
{
public static double[,] Identity(int size) {
double[,] matrix = new double[size, size];
for (int i = 0; i < size; i++) matrix[i, i] = 1;
return matrix;
}
public static double[,] Multiply(this double[,] left, double[,] right) {
if (left.ColumnCount() != right.RowCount()) throw new ArgumentException();
double[,] m = new double[left.RowCount(), right.ColumnCount()];
foreach (var (row, column) in from r in Range(0, m.RowCount()) from c in Range(0, m.ColumnCount()) select (r, c)) {
m[row, column] = Range(0, m.RowCount()).Sum(i => left[row, i] * right[i, column]);
}
return m;
}
public static double[,] Pow(this double[,] matrix, int exp) {
if (matrix.RowCount() != matrix.ColumnCount()) throw new ArgumentException("Matrix must be square.");
double[,] accumulator = Identity(matrix.RowCount());
for (int i = 0; i < exp; i++) {
accumulator = accumulator.Multiply(matrix);
}
return accumulator;
}
private static int RowCount(this double[,] matrix) => matrix.GetLength(0);
private static int ColumnCount(this double[,] matrix) => matrix.GetLength(1);
private static void Print(this double[,] m) {
foreach (var row in Rows()) {
Console.WriteLine("[ " + string.Join(" ", row) + " ]");
}
Console.WriteLine();
IEnumerable<IEnumerable<double>> Rows() =>
Range(0, m.RowCount()).Select(row => Range(0, m.ColumnCount()).Select(column => m[row, column]));
}
public static void Main() {
var matrix = new double[,] {
{ 3, 2 },
{ 2, 1 }
};
matrix.Pow(0).Print();
matrix.Pow(1).Print();
matrix.Pow(2).Print();
matrix.Pow(3).Print();
matrix.Pow(4).Print();
matrix.Pow(50).Print();
}
}
|
Generate a C++ translation of this J snippet without changing its computational steps. | mp=: +/ .*
pow=: pow0=: 4 : 'mp&x^:y =i.#x'
| #include <complex>
#include <cmath>
#include <iostream>
using namespace std;
template<int MSize = 3, class T = complex<double> >
class SqMx {
typedef T Ax[MSize][MSize];
typedef SqMx<MSize, T> Mx;
private:
Ax a;
SqMx() { }
public:
SqMx(const Ax &_a) {
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++)
a[r][c] = _a[r][c];
}
static Mx identity() {
Mx m;
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++)
m.a[r][c] = (r == c ? 1 : 0);
return m;
}
friend ostream &operator<<(ostream& os, const Mx &p)
{
for (int i = 0; i < MSize; i++) {
for (int j = 0; j < MSize; j++)
os << p.a[i][j] << ',';
os << endl;
}
return os;
}
Mx operator*(const Mx &b) {
Mx d;
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++) {
d.a[r][c] = 0;
for (int k = 0; k < MSize; k++)
d.a[r][c] += a[r][k] * b.a[k][c];
}
return d;
}
|
Convert the following code from J to Python, ensuring the logic remains intact. | mp=: +/ .*
pow=: pow0=: 4 : 'mp&x^:y =i.#x'
| >>> from operator import mul
>>> def matrixMul(m1, m2):
return map(
lambda row:
map(
lambda *column:
sum(map(mul, row, column)),
*m2),
m1)
>>> def identity(size):
size = range(size)
return [[(i==j)*1 for i in size] for j in size]
>>> def matrixExp(m, pow):
assert pow>=0 and int(pow)==pow, "Only non-negative, integer powers allowed"
accumulator = identity(len(m))
for i in range(pow):
accumulator = matrixMul(accumulator, m)
return accumulator
>>> def printtable(data):
for row in data:
print ' '.join('%-5s' % ('%s' % cell) for cell in row)
>>> m = [[3,2], [2,1]]
>>> for i in range(5):
print '\n%i:' % i
printtable( matrixExp(m, i) )
0:
1 0
0 1
1:
3 2
2 1
2:
13 8
8 5
3:
55 34
34 21
4:
233 144
144 89
>>> printtable( matrixExp(m, 10) )
1346269 832040
832040 514229
>>>
|
Please provide an equivalent version of this J code in VB. | mp=: +/ .*
pow=: pow0=: 4 : 'mp&x^:y =i.#x'
| Option Base 1
Private Function Identity(n As Integer) As Variant
Dim I() As Variant
ReDim I(n, n)
For j = 1 To n
For k = 1 To n
I(j, k) = 0
Next k
Next j
For j = 1 To n
I(j, j) = 1
Next j
Identity = I
End Function
Function MatrixExponentiation(ByVal x As Variant, ByVal n As Integer) As Variant
If n < 0 Then
x = WorksheetFunction.MInverse(x)
n = -n
End If
If n = 0 Then
MatrixExponentiation = Identity(UBound(x))
Exit Function
End If
Dim y() As Variant
y = Identity(UBound(x))
Do While n > 1
If n Mod 2 = 0 Then
x = WorksheetFunction.MMult(x, x)
n = n / 2
Else
y = WorksheetFunction.MMult(x, y)
x = WorksheetFunction.MMult(x, x)
n = (n - 1) / 2
End If
Loop
MatrixExponentiation = WorksheetFunction.MMult(x, y)
End Function
Public Sub pp(x As Variant)
For i_ = 1 To UBound(x)
For j_ = 1 To UBound(x)
Debug.Print x(i_, j_),
Next j_
Debug.Print
Next i_
End Sub
Public Sub main()
M2 = [{3,2;2,1}]
M3 = [{1,2,0;0,3,1;1,0,0}]
pp MatrixExponentiation(M2, -1)
Debug.Print
pp MatrixExponentiation(M2, 0)
Debug.Print
pp MatrixExponentiation(M2, 10)
Debug.Print
pp MatrixExponentiation(M3, 10)
End Sub
|
Rewrite the snippet below in Go so it works the same as the original J code. | mp=: +/ .*
pow=: pow0=: 4 : 'mp&x^:y =i.#x'
| package main
import "fmt"
type vector = []float64
type matrix []vector
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != rows2 {
panic("Matrices cannot be multiplied.")
}
result := make(matrix, rows1)
for i := 0; i < rows1; i++ {
result[i] = make(vector, cols2)
for j := 0; j < cols2; j++ {
for k := 0; k < rows2; k++ {
result[i][j] += m1[i][k] * m2[k][j]
}
}
}
return result
}
func identityMatrix(n int) matrix {
if n < 1 {
panic("Size of identity matrix can't be less than 1")
}
ident := make(matrix, n)
for i := 0; i < n; i++ {
ident[i] = make(vector, n)
ident[i][i] = 1
}
return ident
}
func (m matrix) pow(n int) matrix {
le := len(m)
if le != len(m[0]) {
panic("Not a square matrix")
}
switch {
case n < 0:
panic("Negative exponents not supported")
case n == 0:
return identityMatrix(le)
case n == 1:
return m
}
pow := identityMatrix(le)
base := m
e := n
for e > 0 {
if (e & 1) == 1 {
pow = pow.mul(base)
}
e >>= 1
base = base.mul(base)
}
return pow
}
func main() {
m := matrix{{3, 2}, {2, 1}}
for i := 0; i <= 10; i++ {
fmt.Println("** Power of", i, "**")
fmt.Println(m.pow(i))
fmt.Println()
}
}
|
Change the following Julia code into C without altering its purpose. | julia> [1 1 ; 1 0]^10
2x2 Array{Int64,2}:
89 55
55 34
| #include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct squareMtxStruct {
int dim;
double *cells;
double **m;
} *SquareMtx;
typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data);
SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data )
{
SquareMtx sm = malloc(sizeof(struct squareMtxStruct));
if (sm) {
int rw;
sm->dim = dim;
sm->cells = malloc(dim*dim * sizeof(double));
sm->m = malloc( dim * sizeof(double *));
if ((sm->cells != NULL) && (sm->m != NULL)) {
for (rw=0; rw<dim; rw++) {
sm->m[rw] = sm->cells + dim*rw;
fillFunc( sm->m[rw], rw, dim, ff_data );
}
}
else {
free(sm->m);
free(sm->cells);
free(sm);
printf("Square Matrix allocation failure\n");
return NULL;
}
}
else {
printf("Malloc failed for square matrix\n");
}
return sm;
}
void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 )
{
int col, ix;
double sum;
double *m0rw = m0->m[rw];
for (col = 0; col < dim; col++) {
sum = 0.0;
for (ix=0; ix<dim; ix++)
sum += m0rw[ix] * m0->m[ix][col];
cells[col] = sum;
}
}
void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] )
{
SquareMtx mleft = mplcnds[0];
SquareMtx mrigt = mplcnds[1];
double sum;
double *m0rw = mleft->m[rw];
int col, ix;
for (col = 0; col < dim; col++) {
sum = 0.0;
for (ix=0; ix<dim; ix++)
sum += m0rw[ix] * mrigt->m[ix][col];
cells[col] = sum;
}
}
void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt)
{
int rw;
SquareMtx mplcnds[2];
mplcnds[0] = left; mplcnds[1] = rigt;
for (rw = 0; rw < left->dim; rw++)
ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds);
}
void ffIdentity( double *cells, int rw, int dim, void *v )
{
int col;
for (col=0; col<dim; col++) cells[col] = 0.0;
cells[rw] = 1.0;
}
void ffCopy(double *cells, int rw, int dim, SquareMtx m1)
{
int col;
for (col=0; col<dim; col++) cells[col] = m1->m[rw][col];
}
void FreeSquareMtx( SquareMtx m )
{
free(m->m);
free(m->cells);
free(m);
}
SquareMtx SquareMtxPow( SquareMtx m0, int exp )
{
SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL);
SquareMtx v1 = NULL;
SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0);
SquareMtx base1 = NULL;
SquareMtx mplcnds[2], t;
while (exp) {
if (exp % 2) {
if (v1)
MatxMul( v1, v0, base0);
else {
mplcnds[0] = v0; mplcnds[1] = base0;
v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds);
}
{t = v0; v0=v1; v1 = t;}
}
if (base1)
MatxMul( base1, base0, base0);
else
base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0);
t = base0; base0 = base1; base1 = t;
exp = exp/2;
}
if (base0) FreeSquareMtx(base0);
if (base1) FreeSquareMtx(base1);
if (v1) FreeSquareMtx(v1);
return v0;
}
FILE *fout;
void SquareMtxPrint( SquareMtx mtx, const char *mn )
{
int rw, col;
int d = mtx->dim;
fprintf(fout, "%s dim:%d =\n", mn, mtx->dim);
for (rw=0; rw<d; rw++) {
fprintf(fout, " |");
for(col=0; col<d; col++)
fprintf(fout, "%8.5f ",mtx->m[rw][col] );
fprintf(fout, " |\n");
}
fprintf(fout, "\n");
}
void fillInit( double *cells, int rw, int dim, void *data)
{
double theta = 3.1415926536/6.0;
double c1 = cos( theta);
double s1 = sin( theta);
switch(rw) {
case 0:
cells[0]=c1; cells[1]=s1; cells[2]=0.0;
break;
case 1:
cells[0]=-s1; cells[1]=c1; cells[2]=0;
break;
case 2:
cells[0]=0.0; cells[1]=0.0; cells[2]=1.0;
break;
}
}
int main()
{
SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL);
SquareMtx m1 = SquareMtxPow( m0, 5);
SquareMtx m2 = SquareMtxPow( m0, 9);
SquareMtx m3 = SquareMtxPow( m0, 2);
fout = fopen("matrx_exp.txt", "w");
SquareMtxPrint(m0, "m0"); FreeSquareMtx(m0);
SquareMtxPrint(m1, "m0^5"); FreeSquareMtx(m1);
SquareMtxPrint(m2, "m0^9"); FreeSquareMtx(m2);
SquareMtxPrint(m3, "m0^2"); FreeSquareMtx(m3);
fclose(fout);
return 0;
}
|
Please provide an equivalent version of this Julia code in C#. | julia> [1 1 ; 1 0]^10
2x2 Array{Int64,2}:
89 55
55 34
| using System;
using System.Collections;
using System.Collections.Generic;
using static System.Linq.Enumerable;
public static class MatrixExponentation
{
public static double[,] Identity(int size) {
double[,] matrix = new double[size, size];
for (int i = 0; i < size; i++) matrix[i, i] = 1;
return matrix;
}
public static double[,] Multiply(this double[,] left, double[,] right) {
if (left.ColumnCount() != right.RowCount()) throw new ArgumentException();
double[,] m = new double[left.RowCount(), right.ColumnCount()];
foreach (var (row, column) in from r in Range(0, m.RowCount()) from c in Range(0, m.ColumnCount()) select (r, c)) {
m[row, column] = Range(0, m.RowCount()).Sum(i => left[row, i] * right[i, column]);
}
return m;
}
public static double[,] Pow(this double[,] matrix, int exp) {
if (matrix.RowCount() != matrix.ColumnCount()) throw new ArgumentException("Matrix must be square.");
double[,] accumulator = Identity(matrix.RowCount());
for (int i = 0; i < exp; i++) {
accumulator = accumulator.Multiply(matrix);
}
return accumulator;
}
private static int RowCount(this double[,] matrix) => matrix.GetLength(0);
private static int ColumnCount(this double[,] matrix) => matrix.GetLength(1);
private static void Print(this double[,] m) {
foreach (var row in Rows()) {
Console.WriteLine("[ " + string.Join(" ", row) + " ]");
}
Console.WriteLine();
IEnumerable<IEnumerable<double>> Rows() =>
Range(0, m.RowCount()).Select(row => Range(0, m.ColumnCount()).Select(column => m[row, column]));
}
public static void Main() {
var matrix = new double[,] {
{ 3, 2 },
{ 2, 1 }
};
matrix.Pow(0).Print();
matrix.Pow(1).Print();
matrix.Pow(2).Print();
matrix.Pow(3).Print();
matrix.Pow(4).Print();
matrix.Pow(50).Print();
}
}
|
Write the same algorithm in C++ as shown in this Julia implementation. | julia> [1 1 ; 1 0]^10
2x2 Array{Int64,2}:
89 55
55 34
| #include <complex>
#include <cmath>
#include <iostream>
using namespace std;
template<int MSize = 3, class T = complex<double> >
class SqMx {
typedef T Ax[MSize][MSize];
typedef SqMx<MSize, T> Mx;
private:
Ax a;
SqMx() { }
public:
SqMx(const Ax &_a) {
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++)
a[r][c] = _a[r][c];
}
static Mx identity() {
Mx m;
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++)
m.a[r][c] = (r == c ? 1 : 0);
return m;
}
friend ostream &operator<<(ostream& os, const Mx &p)
{
for (int i = 0; i < MSize; i++) {
for (int j = 0; j < MSize; j++)
os << p.a[i][j] << ',';
os << endl;
}
return os;
}
Mx operator*(const Mx &b) {
Mx d;
for (int r = 0; r < MSize; r++)
for (int c = 0; c < MSize; c++) {
d.a[r][c] = 0;
for (int k = 0; k < MSize; k++)
d.a[r][c] += a[r][k] * b.a[k][c];
}
return d;
}
|
Transform the following Julia implementation into Python, maintaining the same output and logic. | julia> [1 1 ; 1 0]^10
2x2 Array{Int64,2}:
89 55
55 34
| >>> from operator import mul
>>> def matrixMul(m1, m2):
return map(
lambda row:
map(
lambda *column:
sum(map(mul, row, column)),
*m2),
m1)
>>> def identity(size):
size = range(size)
return [[(i==j)*1 for i in size] for j in size]
>>> def matrixExp(m, pow):
assert pow>=0 and int(pow)==pow, "Only non-negative, integer powers allowed"
accumulator = identity(len(m))
for i in range(pow):
accumulator = matrixMul(accumulator, m)
return accumulator
>>> def printtable(data):
for row in data:
print ' '.join('%-5s' % ('%s' % cell) for cell in row)
>>> m = [[3,2], [2,1]]
>>> for i in range(5):
print '\n%i:' % i
printtable( matrixExp(m, i) )
0:
1 0
0 1
1:
3 2
2 1
2:
13 8
8 5
3:
55 34
34 21
4:
233 144
144 89
>>> printtable( matrixExp(m, 10) )
1346269 832040
832040 514229
>>>
|
Translate this program into VB but keep the logic exactly as in Julia. | julia> [1 1 ; 1 0]^10
2x2 Array{Int64,2}:
89 55
55 34
| Option Base 1
Private Function Identity(n As Integer) As Variant
Dim I() As Variant
ReDim I(n, n)
For j = 1 To n
For k = 1 To n
I(j, k) = 0
Next k
Next j
For j = 1 To n
I(j, j) = 1
Next j
Identity = I
End Function
Function MatrixExponentiation(ByVal x As Variant, ByVal n As Integer) As Variant
If n < 0 Then
x = WorksheetFunction.MInverse(x)
n = -n
End If
If n = 0 Then
MatrixExponentiation = Identity(UBound(x))
Exit Function
End If
Dim y() As Variant
y = Identity(UBound(x))
Do While n > 1
If n Mod 2 = 0 Then
x = WorksheetFunction.MMult(x, x)
n = n / 2
Else
y = WorksheetFunction.MMult(x, y)
x = WorksheetFunction.MMult(x, x)
n = (n - 1) / 2
End If
Loop
MatrixExponentiation = WorksheetFunction.MMult(x, y)
End Function
Public Sub pp(x As Variant)
For i_ = 1 To UBound(x)
For j_ = 1 To UBound(x)
Debug.Print x(i_, j_),
Next j_
Debug.Print
Next i_
End Sub
Public Sub main()
M2 = [{3,2;2,1}]
M3 = [{1,2,0;0,3,1;1,0,0}]
pp MatrixExponentiation(M2, -1)
Debug.Print
pp MatrixExponentiation(M2, 0)
Debug.Print
pp MatrixExponentiation(M2, 10)
Debug.Print
pp MatrixExponentiation(M3, 10)
End Sub
|
Convert the following code from Julia to Go, ensuring the logic remains intact. | julia> [1 1 ; 1 0]^10
2x2 Array{Int64,2}:
89 55
55 34
| package main
import "fmt"
type vector = []float64
type matrix []vector
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != rows2 {
panic("Matrices cannot be multiplied.")
}
result := make(matrix, rows1)
for i := 0; i < rows1; i++ {
result[i] = make(vector, cols2)
for j := 0; j < cols2; j++ {
for k := 0; k < rows2; k++ {
result[i][j] += m1[i][k] * m2[k][j]
}
}
}
return result
}
func identityMatrix(n int) matrix {
if n < 1 {
panic("Size of identity matrix can't be less than 1")
}
ident := make(matrix, n)
for i := 0; i < n; i++ {
ident[i] = make(vector, n)
ident[i][i] = 1
}
return ident
}
func (m matrix) pow(n int) matrix {
le := len(m)
if le != len(m[0]) {
panic("Not a square matrix")
}
switch {
case n < 0:
panic("Negative exponents not supported")
case n == 0:
return identityMatrix(le)
case n == 1:
return m
}
pow := identityMatrix(le)
base := m
e := n
for e > 0 {
if (e & 1) == 1 {
pow = pow.mul(base)
}
e >>= 1
base = base.mul(base)
}
return pow
}
func main() {
m := matrix{{3, 2}, {2, 1}}
for i := 0; i <= 10; i++ {
fmt.Println("** Power of", i, "**")
fmt.Println(m.pow(i))
fmt.Println()
}
}
|
Produce a language-to-language conversion: from Lua to C, same semantics. | Matrix = {}
function Matrix.new( dim_y, dim_x )
assert( dim_y and dim_x )
local matrix = {}
local metatab = {}
setmetatable( matrix, metatab )
metatab.__add = Matrix.Add
metatab.__mul = Matrix.Mul
metatab.__pow = Matrix.Pow
matrix.dim_y = dim_y
matrix.dim_x = dim_x
matrix.data = {}
for i = 1, dim_y do
matrix.data[i] = {}
end
return matrix
end
function Matrix.Show( m )
for i = 1, m.dim_y do
for j = 1, m.dim_x do
io.write( tostring( m.data[i][j] ), " " )
end
io.write( "\n" )
end
end
function Matrix.Add( m, n )
assert( m.dim_x == n.dim_x and m.dim_y == n.dim_y )
local r = Matrix.new( m.dim_y, m.dim_x )
for i = 1, m.dim_y do
for j = 1, m.dim_x do
r.data[i][j] = m.data[i][j] + n.data[i][j]
end
end
return r
end
function Matrix.Mul( m, n )
assert( m.dim_x == n.dim_y )
local r = Matrix.new( m.dim_y, n.dim_x )
for i = 1, m.dim_y do
for j = 1, n.dim_x do
r.data[i][j] = 0
for k = 1, m.dim_x do
r.data[i][j] = r.data[i][j] + m.data[i][k] * n.data[k][j]
end
end
end
return r
end
function Matrix.Pow( m, p )
assert( m.dim_x == m.dim_y )
local r = Matrix.new( m.dim_y, m.dim_x )
if p == 0 then
for i = 1, m.dim_y do
for j = 1, m.dim_x do
if i == j then
r.data[i][j] = 1
else
r.data[i][j] = 0
end
end
end
elseif p == 1 then
for i = 1, m.dim_y do
for j = 1, m.dim_x do
r.data[i][j] = m.data[i][j]
end
end
else
r = m
for i = 2, p do
r = r * m
end
end
return r
end
m = Matrix.new( 2, 2 )
m.data = { { 1, 2 }, { 3, 4 } }
n = m^4;
Matrix.Show( n )
| #include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct squareMtxStruct {
int dim;
double *cells;
double **m;
} *SquareMtx;
typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data);
SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data )
{
SquareMtx sm = malloc(sizeof(struct squareMtxStruct));
if (sm) {
int rw;
sm->dim = dim;
sm->cells = malloc(dim*dim * sizeof(double));
sm->m = malloc( dim * sizeof(double *));
if ((sm->cells != NULL) && (sm->m != NULL)) {
for (rw=0; rw<dim; rw++) {
sm->m[rw] = sm->cells + dim*rw;
fillFunc( sm->m[rw], rw, dim, ff_data );
}
}
else {
free(sm->m);
free(sm->cells);
free(sm);
printf("Square Matrix allocation failure\n");
return NULL;
}
}
else {
printf("Malloc failed for square matrix\n");
}
return sm;
}
void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 )
{
int col, ix;
double sum;
double *m0rw = m0->m[rw];
for (col = 0; col < dim; col++) {
sum = 0.0;
for (ix=0; ix<dim; ix++)
sum += m0rw[ix] * m0->m[ix][col];
cells[col] = sum;
}
}
void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] )
{
SquareMtx mleft = mplcnds[0];
SquareMtx mrigt = mplcnds[1];
double sum;
double *m0rw = mleft->m[rw];
int col, ix;
for (col = 0; col < dim; col++) {
sum = 0.0;
for (ix=0; ix<dim; ix++)
sum += m0rw[ix] * mrigt->m[ix][col];
cells[col] = sum;
}
}
void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt)
{
int rw;
SquareMtx mplcnds[2];
mplcnds[0] = left; mplcnds[1] = rigt;
for (rw = 0; rw < left->dim; rw++)
ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds);
}
void ffIdentity( double *cells, int rw, int dim, void *v )
{
int col;
for (col=0; col<dim; col++) cells[col] = 0.0;
cells[rw] = 1.0;
}
void ffCopy(double *cells, int rw, int dim, SquareMtx m1)
{
int col;
for (col=0; col<dim; col++) cells[col] = m1->m[rw][col];
}
void FreeSquareMtx( SquareMtx m )
{
free(m->m);
free(m->cells);
free(m);
}
SquareMtx SquareMtxPow( SquareMtx m0, int exp )
{
SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL);
SquareMtx v1 = NULL;
SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0);
SquareMtx base1 = NULL;
SquareMtx mplcnds[2], t;
while (exp) {
if (exp % 2) {
if (v1)
MatxMul( v1, v0, base0);
else {
mplcnds[0] = v0; mplcnds[1] = base0;
v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds);
}
{t = v0; v0=v1; v1 = t;}
}
if (base1)
MatxMul( base1, base0, base0);
else
base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0);
t = base0; base0 = base1; base1 = t;
exp = exp/2;
}
if (base0) FreeSquareMtx(base0);
if (base1) FreeSquareMtx(base1);
if (v1) FreeSquareMtx(v1);
return v0;
}
FILE *fout;
void SquareMtxPrint( SquareMtx mtx, const char *mn )
{
int rw, col;
int d = mtx->dim;
fprintf(fout, "%s dim:%d =\n", mn, mtx->dim);
for (rw=0; rw<d; rw++) {
fprintf(fout, " |");
for(col=0; col<d; col++)
fprintf(fout, "%8.5f ",mtx->m[rw][col] );
fprintf(fout, " |\n");
}
fprintf(fout, "\n");
}
void fillInit( double *cells, int rw, int dim, void *data)
{
double theta = 3.1415926536/6.0;
double c1 = cos( theta);
double s1 = sin( theta);
switch(rw) {
case 0:
cells[0]=c1; cells[1]=s1; cells[2]=0.0;
break;
case 1:
cells[0]=-s1; cells[1]=c1; cells[2]=0;
break;
case 2:
cells[0]=0.0; cells[1]=0.0; cells[2]=1.0;
break;
}
}
int main()
{
SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL);
SquareMtx m1 = SquareMtxPow( m0, 5);
SquareMtx m2 = SquareMtxPow( m0, 9);
SquareMtx m3 = SquareMtxPow( m0, 2);
fout = fopen("matrx_exp.txt", "w");
SquareMtxPrint(m0, "m0"); FreeSquareMtx(m0);
SquareMtxPrint(m1, "m0^5"); FreeSquareMtx(m1);
SquareMtxPrint(m2, "m0^9"); FreeSquareMtx(m2);
SquareMtxPrint(m3, "m0^2"); FreeSquareMtx(m3);
fclose(fout);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.