Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Translate this program into C# but keep the logic exactly as in Ruby. | libm = LibC.dlopen("libm.so.6", LibC::RTLD_LAZY)
sqrtptr = LibC.dlsym(libm, "sqrt") unless libm.null?
if sqrtptr
sqrtproc = Proc(Float64, Float64).new sqrtptr, Pointer(Void).null
at_exit { LibC.dlclose(libm) }
else
sqrtproc = ->Math.sqrt(Float64)
end
puts "the sqrt of 4 is
| using System.Runtime.InteropServices;
class Program {
[DllImport("fakelib.dll")]
public static extern int fakefunction(int args);
static void Main(string[] args) {
int r = fakefunction(10);
}
}
|
Translate the given Ruby code snippet into Java without altering its behavior. | libm = LibC.dlopen("libm.so.6", LibC::RTLD_LAZY)
sqrtptr = LibC.dlsym(libm, "sqrt") unless libm.null?
if sqrtptr
sqrtproc = Proc(Float64, Float64).new sqrtptr, Pointer(Void).null
at_exit { LibC.dlclose(libm) }
else
sqrtproc = ->Math.sqrt(Float64)
end
puts "the sqrt of 4 is
|
import java.util.Collections;
import java.util.Random;
public class TrySort {
static boolean useC;
static {
try {
System.loadLibrary("TrySort");
useC = true;
} catch(UnsatisfiedLinkError e) {
useC = false;
}
}
static native void sortInC(int[] ary);
static class IntList extends java.util.AbstractList<Integer> {
int[] ary;
IntList(int[] ary) { this.ary = ary; }
public Integer get(int i) { return ary[i]; }
public Integer set(int i, Integer j) {
Integer o = ary[i]; ary[i] = j; return o;
}
public int size() { return ary.length; }
}
static class ReverseAbsCmp
implements java.util.Comparator<Integer>
{
public int compare(Integer pa, Integer pb) {
int a = pa > 0 ? -pa : pa;
int b = pb > 0 ? -pb : pb;
return a < b ? -1 : a > b ? 1 : 0;
}
}
static void sortInJava(int[] ary) {
Collections.sort(new IntList(ary), new ReverseAbsCmp());
}
public static void main(String[] args) {
int[] ary = new int[1000000];
Random rng = new Random();
for (int i = 0; i < ary.length; i++)
ary[i] = rng.nextInt();
if (useC) {
System.out.print("Sorting in C... ");
sortInC(ary);
} else {
System.out.print
("Missing library for C! Sorting in Java... ");
sortInJava(ary);
}
for (int i = 0; i < ary.length - 1; i++) {
int a = ary[i];
int b = ary[i + 1];
if ((a > 0 ? -a : a) > (b > 0 ? -b : b)) {
System.out.println("*BUG IN SORT*");
System.exit(1);
}
}
System.out.println("ok");
}
}
|
Convert the following code from Ruby to Python, ensuring the logic remains intact. | libm = LibC.dlopen("libm.so.6", LibC::RTLD_LAZY)
sqrtptr = LibC.dlsym(libm, "sqrt") unless libm.null?
if sqrtptr
sqrtproc = Proc(Float64, Float64).new sqrtptr, Pointer(Void).null
at_exit { LibC.dlclose(libm) }
else
sqrtproc = ->Math.sqrt(Float64)
end
puts "the sqrt of 4 is
| import ctypes
user32_dll = ctypes.cdll.LoadLibrary('User32.dll')
print user32_dll.GetDoubleClickTime()
|
Preserve the algorithm and functionality while converting the code from Ruby to VB. | libm = LibC.dlopen("libm.so.6", LibC::RTLD_LAZY)
sqrtptr = LibC.dlsym(libm, "sqrt") unless libm.null?
if sqrtptr
sqrtproc = Proc(Float64, Float64).new sqrtptr, Pointer(Void).null
at_exit { LibC.dlclose(libm) }
else
sqrtproc = ->Math.sqrt(Float64)
end
puts "the sqrt of 4 is
| Declare Dynamic Library "Kernel32"
Sub SetLastError (ByVal dwErr As Long)
Function GetLastError& ()
End Declare
SetLastError 20
Print GetLastError
|
Port the following code from Ruby to Go with equivalent syntax and logic. | libm = LibC.dlopen("libm.so.6", LibC::RTLD_LAZY)
sqrtptr = LibC.dlsym(libm, "sqrt") unless libm.null?
if sqrtptr
sqrtproc = Proc(Float64, Float64).new sqrtptr, Pointer(Void).null
at_exit { LibC.dlclose(libm) }
else
sqrtproc = ->Math.sqrt(Float64)
end
puts "the sqrt of 4 is
| package main
import "C"
import (
"fmt"
"os"
"unsafe"
)
var handle = -1
func myOpenImage(s string) int {
fmt.Fprintf(os.Stderr, "internal openImage opens %s...\n", s)
handle++
return handle
}
func main() {
libpath := C.CString("./fakeimglib.so")
defer C.free(unsafe.Pointer(libpath))
imglib := C.dlopen(libpath, C.RTLD_LAZY)
var imghandle int
if imglib != nil {
openimage := C.CString("openimage")
defer C.free(unsafe.Pointer(openimage))
fp := C.dlsym(imglib, openimage)
if fp != nil {
fi := C.CString("fake.img")
defer C.free(unsafe.Pointer(fi))
imghandle = int(C.bridge_someFunc(C.someFunc(fp), fi))
} else {
imghandle = myOpenImage("fake.img")
}
C.dlclose(imglib)
} else {
imghandle = myOpenImage("fake.img")
}
fmt.Printf("opened with handle %d\n", imghandle)
}
|
Maintain the same structure and functionality when rewriting this code in C. |
import kotlinx.cinterop.*
import platform.posix.*
import platform.linux.*
typealias Func = (String)-> Int
var handle = 0
fun myOpenImage(s: String): Int {
fprintf(stderr, "internal openImage opens %s...\n", s)
return handle++
}
fun main(args: Array<String>) {
var imgHandle: Int
val imglib = dlopen("./fakeimglib.so", RTLD_LAZY)
if (imglib != null) {
val fp = dlsym(imglib, "openimage")
if (fp != null) {
val extOpenImage: CPointer<CFunction<Func>> = fp.reinterpret()
imgHandle = extOpenImage("fake.img")
}
else {
imgHandle = myOpenImage("fake.img")
}
dlclose(imglib)
}
else {
imgHandle = myOpenImage("fake.img")
}
println("opened with handle $imgHandle")
}
| #include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int myopenimage(const char *in)
{
static int handle=0;
fprintf(stderr, "internal openimage opens %s...\n", in);
return handle++;
}
int main()
{
void *imglib;
int (*extopenimage)(const char *);
int imghandle;
imglib = dlopen("./fakeimglib.so", RTLD_LAZY);
if ( imglib != NULL ) {
*(void **)(&extopenimage) = dlsym(imglib, "openimage");
imghandle = extopenimage("fake.img");
} else {
imghandle = myopenimage("fake.img");
}
printf("opened with handle %d\n", imghandle);
if (imglib != NULL ) dlclose(imglib);
return EXIT_SUCCESS;
}
|
Preserve the algorithm and functionality while converting the code from Scala to C#. |
import kotlinx.cinterop.*
import platform.posix.*
import platform.linux.*
typealias Func = (String)-> Int
var handle = 0
fun myOpenImage(s: String): Int {
fprintf(stderr, "internal openImage opens %s...\n", s)
return handle++
}
fun main(args: Array<String>) {
var imgHandle: Int
val imglib = dlopen("./fakeimglib.so", RTLD_LAZY)
if (imglib != null) {
val fp = dlsym(imglib, "openimage")
if (fp != null) {
val extOpenImage: CPointer<CFunction<Func>> = fp.reinterpret()
imgHandle = extOpenImage("fake.img")
}
else {
imgHandle = myOpenImage("fake.img")
}
dlclose(imglib)
}
else {
imgHandle = myOpenImage("fake.img")
}
println("opened with handle $imgHandle")
}
| using System.Runtime.InteropServices;
class Program {
[DllImport("fakelib.dll")]
public static extern int fakefunction(int args);
static void Main(string[] args) {
int r = fakefunction(10);
}
}
|
Change the following Scala code into Java without altering its purpose. |
import kotlinx.cinterop.*
import platform.posix.*
import platform.linux.*
typealias Func = (String)-> Int
var handle = 0
fun myOpenImage(s: String): Int {
fprintf(stderr, "internal openImage opens %s...\n", s)
return handle++
}
fun main(args: Array<String>) {
var imgHandle: Int
val imglib = dlopen("./fakeimglib.so", RTLD_LAZY)
if (imglib != null) {
val fp = dlsym(imglib, "openimage")
if (fp != null) {
val extOpenImage: CPointer<CFunction<Func>> = fp.reinterpret()
imgHandle = extOpenImage("fake.img")
}
else {
imgHandle = myOpenImage("fake.img")
}
dlclose(imglib)
}
else {
imgHandle = myOpenImage("fake.img")
}
println("opened with handle $imgHandle")
}
|
import java.util.Collections;
import java.util.Random;
public class TrySort {
static boolean useC;
static {
try {
System.loadLibrary("TrySort");
useC = true;
} catch(UnsatisfiedLinkError e) {
useC = false;
}
}
static native void sortInC(int[] ary);
static class IntList extends java.util.AbstractList<Integer> {
int[] ary;
IntList(int[] ary) { this.ary = ary; }
public Integer get(int i) { return ary[i]; }
public Integer set(int i, Integer j) {
Integer o = ary[i]; ary[i] = j; return o;
}
public int size() { return ary.length; }
}
static class ReverseAbsCmp
implements java.util.Comparator<Integer>
{
public int compare(Integer pa, Integer pb) {
int a = pa > 0 ? -pa : pa;
int b = pb > 0 ? -pb : pb;
return a < b ? -1 : a > b ? 1 : 0;
}
}
static void sortInJava(int[] ary) {
Collections.sort(new IntList(ary), new ReverseAbsCmp());
}
public static void main(String[] args) {
int[] ary = new int[1000000];
Random rng = new Random();
for (int i = 0; i < ary.length; i++)
ary[i] = rng.nextInt();
if (useC) {
System.out.print("Sorting in C... ");
sortInC(ary);
} else {
System.out.print
("Missing library for C! Sorting in Java... ");
sortInJava(ary);
}
for (int i = 0; i < ary.length - 1; i++) {
int a = ary[i];
int b = ary[i + 1];
if ((a > 0 ? -a : a) > (b > 0 ? -b : b)) {
System.out.println("*BUG IN SORT*");
System.exit(1);
}
}
System.out.println("ok");
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. |
import kotlinx.cinterop.*
import platform.posix.*
import platform.linux.*
typealias Func = (String)-> Int
var handle = 0
fun myOpenImage(s: String): Int {
fprintf(stderr, "internal openImage opens %s...\n", s)
return handle++
}
fun main(args: Array<String>) {
var imgHandle: Int
val imglib = dlopen("./fakeimglib.so", RTLD_LAZY)
if (imglib != null) {
val fp = dlsym(imglib, "openimage")
if (fp != null) {
val extOpenImage: CPointer<CFunction<Func>> = fp.reinterpret()
imgHandle = extOpenImage("fake.img")
}
else {
imgHandle = myOpenImage("fake.img")
}
dlclose(imglib)
}
else {
imgHandle = myOpenImage("fake.img")
}
println("opened with handle $imgHandle")
}
| import ctypes
user32_dll = ctypes.cdll.LoadLibrary('User32.dll')
print user32_dll.GetDoubleClickTime()
|
Port the provided Scala code into VB while preserving the original functionality. |
import kotlinx.cinterop.*
import platform.posix.*
import platform.linux.*
typealias Func = (String)-> Int
var handle = 0
fun myOpenImage(s: String): Int {
fprintf(stderr, "internal openImage opens %s...\n", s)
return handle++
}
fun main(args: Array<String>) {
var imgHandle: Int
val imglib = dlopen("./fakeimglib.so", RTLD_LAZY)
if (imglib != null) {
val fp = dlsym(imglib, "openimage")
if (fp != null) {
val extOpenImage: CPointer<CFunction<Func>> = fp.reinterpret()
imgHandle = extOpenImage("fake.img")
}
else {
imgHandle = myOpenImage("fake.img")
}
dlclose(imglib)
}
else {
imgHandle = myOpenImage("fake.img")
}
println("opened with handle $imgHandle")
}
| Declare Dynamic Library "Kernel32"
Sub SetLastError (ByVal dwErr As Long)
Function GetLastError& ()
End Declare
SetLastError 20
Print GetLastError
|
Generate an equivalent Go version of this Scala code. |
import kotlinx.cinterop.*
import platform.posix.*
import platform.linux.*
typealias Func = (String)-> Int
var handle = 0
fun myOpenImage(s: String): Int {
fprintf(stderr, "internal openImage opens %s...\n", s)
return handle++
}
fun main(args: Array<String>) {
var imgHandle: Int
val imglib = dlopen("./fakeimglib.so", RTLD_LAZY)
if (imglib != null) {
val fp = dlsym(imglib, "openimage")
if (fp != null) {
val extOpenImage: CPointer<CFunction<Func>> = fp.reinterpret()
imgHandle = extOpenImage("fake.img")
}
else {
imgHandle = myOpenImage("fake.img")
}
dlclose(imglib)
}
else {
imgHandle = myOpenImage("fake.img")
}
println("opened with handle $imgHandle")
}
| package main
import "C"
import (
"fmt"
"os"
"unsafe"
)
var handle = -1
func myOpenImage(s string) int {
fmt.Fprintf(os.Stderr, "internal openImage opens %s...\n", s)
handle++
return handle
}
func main() {
libpath := C.CString("./fakeimglib.so")
defer C.free(unsafe.Pointer(libpath))
imglib := C.dlopen(libpath, C.RTLD_LAZY)
var imghandle int
if imglib != nil {
openimage := C.CString("openimage")
defer C.free(unsafe.Pointer(openimage))
fp := C.dlsym(imglib, openimage)
if fp != nil {
fi := C.CString("fake.img")
defer C.free(unsafe.Pointer(fi))
imghandle = int(C.bridge_someFunc(C.someFunc(fp), fi))
} else {
imghandle = myOpenImage("fake.img")
}
C.dlclose(imglib)
} else {
imghandle = myOpenImage("fake.img")
}
fmt.Printf("opened with handle %d\n", imghandle)
}
|
Change the following Tcl code into C without altering its purpose. | package require Ffidl
if {[catch {
ffidl::callout OpenImage {pointer-utf8} int [ffidl::symbol fakeimglib.so openimage]
}]} then {
}
set handle [OpenImage "/the/file/name"]
| #include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int myopenimage(const char *in)
{
static int handle=0;
fprintf(stderr, "internal openimage opens %s...\n", in);
return handle++;
}
int main()
{
void *imglib;
int (*extopenimage)(const char *);
int imghandle;
imglib = dlopen("./fakeimglib.so", RTLD_LAZY);
if ( imglib != NULL ) {
*(void **)(&extopenimage) = dlsym(imglib, "openimage");
imghandle = extopenimage("fake.img");
} else {
imghandle = myopenimage("fake.img");
}
printf("opened with handle %d\n", imghandle);
if (imglib != NULL ) dlclose(imglib);
return EXIT_SUCCESS;
}
|
Convert this Tcl snippet to C# and keep its semantics consistent. | package require Ffidl
if {[catch {
ffidl::callout OpenImage {pointer-utf8} int [ffidl::symbol fakeimglib.so openimage]
}]} then {
}
set handle [OpenImage "/the/file/name"]
| using System.Runtime.InteropServices;
class Program {
[DllImport("fakelib.dll")]
public static extern int fakefunction(int args);
static void Main(string[] args) {
int r = fakefunction(10);
}
}
|
Write the same code in Java as shown below in Tcl. | package require Ffidl
if {[catch {
ffidl::callout OpenImage {pointer-utf8} int [ffidl::symbol fakeimglib.so openimage]
}]} then {
}
set handle [OpenImage "/the/file/name"]
|
import java.util.Collections;
import java.util.Random;
public class TrySort {
static boolean useC;
static {
try {
System.loadLibrary("TrySort");
useC = true;
} catch(UnsatisfiedLinkError e) {
useC = false;
}
}
static native void sortInC(int[] ary);
static class IntList extends java.util.AbstractList<Integer> {
int[] ary;
IntList(int[] ary) { this.ary = ary; }
public Integer get(int i) { return ary[i]; }
public Integer set(int i, Integer j) {
Integer o = ary[i]; ary[i] = j; return o;
}
public int size() { return ary.length; }
}
static class ReverseAbsCmp
implements java.util.Comparator<Integer>
{
public int compare(Integer pa, Integer pb) {
int a = pa > 0 ? -pa : pa;
int b = pb > 0 ? -pb : pb;
return a < b ? -1 : a > b ? 1 : 0;
}
}
static void sortInJava(int[] ary) {
Collections.sort(new IntList(ary), new ReverseAbsCmp());
}
public static void main(String[] args) {
int[] ary = new int[1000000];
Random rng = new Random();
for (int i = 0; i < ary.length; i++)
ary[i] = rng.nextInt();
if (useC) {
System.out.print("Sorting in C... ");
sortInC(ary);
} else {
System.out.print
("Missing library for C! Sorting in Java... ");
sortInJava(ary);
}
for (int i = 0; i < ary.length - 1; i++) {
int a = ary[i];
int b = ary[i + 1];
if ((a > 0 ? -a : a) > (b > 0 ? -b : b)) {
System.out.println("*BUG IN SORT*");
System.exit(1);
}
}
System.out.println("ok");
}
}
|
Write a version of this Tcl function in Python with identical behavior. | package require Ffidl
if {[catch {
ffidl::callout OpenImage {pointer-utf8} int [ffidl::symbol fakeimglib.so openimage]
}]} then {
}
set handle [OpenImage "/the/file/name"]
| import ctypes
user32_dll = ctypes.cdll.LoadLibrary('User32.dll')
print user32_dll.GetDoubleClickTime()
|
Port the following code from Tcl to VB with equivalent syntax and logic. | package require Ffidl
if {[catch {
ffidl::callout OpenImage {pointer-utf8} int [ffidl::symbol fakeimglib.so openimage]
}]} then {
}
set handle [OpenImage "/the/file/name"]
| Declare Dynamic Library "Kernel32"
Sub SetLastError (ByVal dwErr As Long)
Function GetLastError& ()
End Declare
SetLastError 20
Print GetLastError
|
Port the following code from Tcl to Go with equivalent syntax and logic. | package require Ffidl
if {[catch {
ffidl::callout OpenImage {pointer-utf8} int [ffidl::symbol fakeimglib.so openimage]
}]} then {
}
set handle [OpenImage "/the/file/name"]
| package main
import "C"
import (
"fmt"
"os"
"unsafe"
)
var handle = -1
func myOpenImage(s string) int {
fmt.Fprintf(os.Stderr, "internal openImage opens %s...\n", s)
handle++
return handle
}
func main() {
libpath := C.CString("./fakeimglib.so")
defer C.free(unsafe.Pointer(libpath))
imglib := C.dlopen(libpath, C.RTLD_LAZY)
var imghandle int
if imglib != nil {
openimage := C.CString("openimage")
defer C.free(unsafe.Pointer(openimage))
fp := C.dlsym(imglib, openimage)
if fp != nil {
fi := C.CString("fake.img")
defer C.free(unsafe.Pointer(fi))
imghandle = int(C.bridge_someFunc(C.someFunc(fp), fi))
} else {
imghandle = myOpenImage("fake.img")
}
C.dlclose(imglib)
} else {
imghandle = myOpenImage("fake.img")
}
fmt.Printf("opened with handle %d\n", imghandle)
}
|
Transform the following C implementation into Rust, maintaining the same output and logic. | #include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int myopenimage(const char *in)
{
static int handle=0;
fprintf(stderr, "internal openimage opens %s...\n", in);
return handle++;
}
int main()
{
void *imglib;
int (*extopenimage)(const char *);
int imghandle;
imglib = dlopen("./fakeimglib.so", RTLD_LAZY);
if ( imglib != NULL ) {
*(void **)(&extopenimage) = dlsym(imglib, "openimage");
imghandle = extopenimage("fake.img");
} else {
imghandle = myopenimage("fake.img");
}
printf("opened with handle %d\n", imghandle);
if (imglib != NULL ) dlclose(imglib);
return EXIT_SUCCESS;
}
| #![allow(unused_unsafe)]
extern crate libc;
use std::io::{self,Write};
use std::{mem,ffi,process};
use libc::{c_double, RTLD_NOW};
macro_rules! to_cstr {
($s:expr) => {unsafe {ffi::CStr::from_bytes_with_nul_unchecked(concat!($s, "\0").as_bytes()).as_ptr()}}
}
macro_rules! from_cstr {
($p:expr) => {ffi::CStr::from_ptr($p).to_string_lossy().as_ref() }
}
fn main() {
unsafe {
let handle = libc::dlopen(to_cstr!("libm.so.6"), RTLD_NOW);
if handle.is_null() {
writeln!(&mut io::stderr(), "{}", from_cstr!(libc::dlerror())).unwrap();
process::exit(1);
}
let extern_cos = libc::dlsym(handle, to_cstr!("cos"))
.as_ref()
.map(mem::transmute::<_,fn (c_double) -> c_double)
.unwrap_or(builtin_cos);
println!("{}", extern_cos(4.0));
}
}
fn builtin_cos(x: c_double) -> c_double {
x.cos()
}
|
Generate an equivalent Rust version of this C# code. | using System.Runtime.InteropServices;
class Program {
[DllImport("fakelib.dll")]
public static extern int fakefunction(int args);
static void Main(string[] args) {
int r = fakefunction(10);
}
}
| #![allow(unused_unsafe)]
extern crate libc;
use std::io::{self,Write};
use std::{mem,ffi,process};
use libc::{c_double, RTLD_NOW};
macro_rules! to_cstr {
($s:expr) => {unsafe {ffi::CStr::from_bytes_with_nul_unchecked(concat!($s, "\0").as_bytes()).as_ptr()}}
}
macro_rules! from_cstr {
($p:expr) => {ffi::CStr::from_ptr($p).to_string_lossy().as_ref() }
}
fn main() {
unsafe {
let handle = libc::dlopen(to_cstr!("libm.so.6"), RTLD_NOW);
if handle.is_null() {
writeln!(&mut io::stderr(), "{}", from_cstr!(libc::dlerror())).unwrap();
process::exit(1);
}
let extern_cos = libc::dlsym(handle, to_cstr!("cos"))
.as_ref()
.map(mem::transmute::<_,fn (c_double) -> c_double)
.unwrap_or(builtin_cos);
println!("{}", extern_cos(4.0));
}
}
fn builtin_cos(x: c_double) -> c_double {
x.cos()
}
|
Write the same code in Rust as shown below in Java. |
import java.util.Collections;
import java.util.Random;
public class TrySort {
static boolean useC;
static {
try {
System.loadLibrary("TrySort");
useC = true;
} catch(UnsatisfiedLinkError e) {
useC = false;
}
}
static native void sortInC(int[] ary);
static class IntList extends java.util.AbstractList<Integer> {
int[] ary;
IntList(int[] ary) { this.ary = ary; }
public Integer get(int i) { return ary[i]; }
public Integer set(int i, Integer j) {
Integer o = ary[i]; ary[i] = j; return o;
}
public int size() { return ary.length; }
}
static class ReverseAbsCmp
implements java.util.Comparator<Integer>
{
public int compare(Integer pa, Integer pb) {
int a = pa > 0 ? -pa : pa;
int b = pb > 0 ? -pb : pb;
return a < b ? -1 : a > b ? 1 : 0;
}
}
static void sortInJava(int[] ary) {
Collections.sort(new IntList(ary), new ReverseAbsCmp());
}
public static void main(String[] args) {
int[] ary = new int[1000000];
Random rng = new Random();
for (int i = 0; i < ary.length; i++)
ary[i] = rng.nextInt();
if (useC) {
System.out.print("Sorting in C... ");
sortInC(ary);
} else {
System.out.print
("Missing library for C! Sorting in Java... ");
sortInJava(ary);
}
for (int i = 0; i < ary.length - 1; i++) {
int a = ary[i];
int b = ary[i + 1];
if ((a > 0 ? -a : a) > (b > 0 ? -b : b)) {
System.out.println("*BUG IN SORT*");
System.exit(1);
}
}
System.out.println("ok");
}
}
| #![allow(unused_unsafe)]
extern crate libc;
use std::io::{self,Write};
use std::{mem,ffi,process};
use libc::{c_double, RTLD_NOW};
macro_rules! to_cstr {
($s:expr) => {unsafe {ffi::CStr::from_bytes_with_nul_unchecked(concat!($s, "\0").as_bytes()).as_ptr()}}
}
macro_rules! from_cstr {
($p:expr) => {ffi::CStr::from_ptr($p).to_string_lossy().as_ref() }
}
fn main() {
unsafe {
let handle = libc::dlopen(to_cstr!("libm.so.6"), RTLD_NOW);
if handle.is_null() {
writeln!(&mut io::stderr(), "{}", from_cstr!(libc::dlerror())).unwrap();
process::exit(1);
}
let extern_cos = libc::dlsym(handle, to_cstr!("cos"))
.as_ref()
.map(mem::transmute::<_,fn (c_double) -> c_double)
.unwrap_or(builtin_cos);
println!("{}", extern_cos(4.0));
}
}
fn builtin_cos(x: c_double) -> c_double {
x.cos()
}
|
Port the following code from Rust to Python with equivalent syntax and logic. | #![allow(unused_unsafe)]
extern crate libc;
use std::io::{self,Write};
use std::{mem,ffi,process};
use libc::{c_double, RTLD_NOW};
macro_rules! to_cstr {
($s:expr) => {unsafe {ffi::CStr::from_bytes_with_nul_unchecked(concat!($s, "\0").as_bytes()).as_ptr()}}
}
macro_rules! from_cstr {
($p:expr) => {ffi::CStr::from_ptr($p).to_string_lossy().as_ref() }
}
fn main() {
unsafe {
let handle = libc::dlopen(to_cstr!("libm.so.6"), RTLD_NOW);
if handle.is_null() {
writeln!(&mut io::stderr(), "{}", from_cstr!(libc::dlerror())).unwrap();
process::exit(1);
}
let extern_cos = libc::dlsym(handle, to_cstr!("cos"))
.as_ref()
.map(mem::transmute::<_,fn (c_double) -> c_double)
.unwrap_or(builtin_cos);
println!("{}", extern_cos(4.0));
}
}
fn builtin_cos(x: c_double) -> c_double {
x.cos()
}
| import ctypes
user32_dll = ctypes.cdll.LoadLibrary('User32.dll')
print user32_dll.GetDoubleClickTime()
|
Port the provided Rust code into VB while preserving the original functionality. | #![allow(unused_unsafe)]
extern crate libc;
use std::io::{self,Write};
use std::{mem,ffi,process};
use libc::{c_double, RTLD_NOW};
macro_rules! to_cstr {
($s:expr) => {unsafe {ffi::CStr::from_bytes_with_nul_unchecked(concat!($s, "\0").as_bytes()).as_ptr()}}
}
macro_rules! from_cstr {
($p:expr) => {ffi::CStr::from_ptr($p).to_string_lossy().as_ref() }
}
fn main() {
unsafe {
let handle = libc::dlopen(to_cstr!("libm.so.6"), RTLD_NOW);
if handle.is_null() {
writeln!(&mut io::stderr(), "{}", from_cstr!(libc::dlerror())).unwrap();
process::exit(1);
}
let extern_cos = libc::dlsym(handle, to_cstr!("cos"))
.as_ref()
.map(mem::transmute::<_,fn (c_double) -> c_double)
.unwrap_or(builtin_cos);
println!("{}", extern_cos(4.0));
}
}
fn builtin_cos(x: c_double) -> c_double {
x.cos()
}
| Declare Dynamic Library "Kernel32"
Sub SetLastError (ByVal dwErr As Long)
Function GetLastError& ()
End Declare
SetLastError 20
Print GetLastError
|
Convert the following code from Go to Rust, ensuring the logic remains intact. | package main
import "C"
import (
"fmt"
"os"
"unsafe"
)
var handle = -1
func myOpenImage(s string) int {
fmt.Fprintf(os.Stderr, "internal openImage opens %s...\n", s)
handle++
return handle
}
func main() {
libpath := C.CString("./fakeimglib.so")
defer C.free(unsafe.Pointer(libpath))
imglib := C.dlopen(libpath, C.RTLD_LAZY)
var imghandle int
if imglib != nil {
openimage := C.CString("openimage")
defer C.free(unsafe.Pointer(openimage))
fp := C.dlsym(imglib, openimage)
if fp != nil {
fi := C.CString("fake.img")
defer C.free(unsafe.Pointer(fi))
imghandle = int(C.bridge_someFunc(C.someFunc(fp), fi))
} else {
imghandle = myOpenImage("fake.img")
}
C.dlclose(imglib)
} else {
imghandle = myOpenImage("fake.img")
}
fmt.Printf("opened with handle %d\n", imghandle)
}
| #![allow(unused_unsafe)]
extern crate libc;
use std::io::{self,Write};
use std::{mem,ffi,process};
use libc::{c_double, RTLD_NOW};
macro_rules! to_cstr {
($s:expr) => {unsafe {ffi::CStr::from_bytes_with_nul_unchecked(concat!($s, "\0").as_bytes()).as_ptr()}}
}
macro_rules! from_cstr {
($p:expr) => {ffi::CStr::from_ptr($p).to_string_lossy().as_ref() }
}
fn main() {
unsafe {
let handle = libc::dlopen(to_cstr!("libm.so.6"), RTLD_NOW);
if handle.is_null() {
writeln!(&mut io::stderr(), "{}", from_cstr!(libc::dlerror())).unwrap();
process::exit(1);
}
let extern_cos = libc::dlsym(handle, to_cstr!("cos"))
.as_ref()
.map(mem::transmute::<_,fn (c_double) -> c_double)
.unwrap_or(builtin_cos);
println!("{}", extern_cos(4.0));
}
}
fn builtin_cos(x: c_double) -> c_double {
x.cos()
}
|
Produce a language-to-language conversion: from Ada to C#, same semantics. | generic
type Element_Type is private;
Zero : Element_Type;
with function "-" (Left, Right : in Element_Type) return Element_Type is <>;
with function "*" (Left, Right : in Element_Type) return Element_Type is <>;
with function "/" (Left, Right : in Element_Type) return Element_Type is <>;
package Matrices is
type Matrix is
array (Positive range <>, Positive range <>) of Element_Type;
function Reduced_Row_Echelon_form (Source : Matrix) return Matrix;
end Matrices;
| using System;
namespace rref
{
class Program
{
static void Main(string[] args)
{
int[,] matrix = new int[3, 4]{
{ 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 }
};
matrix = rref(matrix);
}
private static int[,] rref(int[,] matrix)
{
int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1);
for (int r = 0; r < rowCount; r++)
{
if (columnCount <= lead) break;
int i = r;
while (matrix[i, lead] == 0)
{
i++;
if (i == rowCount)
{
i = r;
lead++;
if (columnCount == lead)
{
lead--;
break;
}
}
}
for (int j = 0; j < columnCount; j++)
{
int temp = matrix[r, j];
matrix[r, j] = matrix[i, j];
matrix[i, j] = temp;
}
int div = matrix[r, lead];
if(div != 0)
for (int j = 0; j < columnCount; j++) matrix[r, j] /= div;
for (int j = 0; j < rowCount; j++)
{
if (j != r)
{
int sub = matrix[j, lead];
for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]);
}
}
lead++;
}
return matrix;
}
}
}
|
Convert this Ada snippet to C and keep its semantics consistent. | generic
type Element_Type is private;
Zero : Element_Type;
with function "-" (Left, Right : in Element_Type) return Element_Type is <>;
with function "*" (Left, Right : in Element_Type) return Element_Type is <>;
with function "/" (Left, Right : in Element_Type) return Element_Type is <>;
package Matrices is
type Matrix is
array (Positive range <>, Positive range <>) of Element_Type;
function Reduced_Row_Echelon_form (Source : Matrix) return Matrix;
end Matrices;
| #include <stdio.h>
#define TALLOC(n,typ) malloc(n*sizeof(typ))
#define EL_Type int
typedef struct sMtx {
int dim_x, dim_y;
EL_Type *m_stor;
EL_Type **mtx;
} *Matrix, sMatrix;
typedef struct sRvec {
int dim_x;
EL_Type *m_stor;
} *RowVec, sRowVec;
Matrix NewMatrix( int x_dim, int y_dim )
{
int n;
Matrix m;
m = TALLOC( 1, sMatrix);
n = x_dim * y_dim;
m->dim_x = x_dim;
m->dim_y = y_dim;
m->m_stor = TALLOC(n, EL_Type);
m->mtx = TALLOC(m->dim_y, EL_Type *);
for(n=0; n<y_dim; n++) {
m->mtx[n] = m->m_stor+n*x_dim;
}
return m;
}
void MtxSetRow(Matrix m, int irow, EL_Type *v)
{
int ix;
EL_Type *mr;
mr = m->mtx[irow];
for(ix=0; ix<m->dim_x; ix++)
mr[ix] = v[ix];
}
Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v)
{
Matrix m;
int iy;
m = NewMatrix(x_dim, y_dim);
for (iy=0; iy<y_dim; iy++)
MtxSetRow(m, iy, v[iy]);
return m;
}
void MtxDisplay( Matrix m )
{
int iy, ix;
const char *sc;
for (iy=0; iy<m->dim_y; iy++) {
printf(" ");
sc = " ";
for (ix=0; ix<m->dim_x; ix++) {
printf("%s %3d", sc, m->mtx[iy][ix]);
sc = ",";
}
printf("\n");
}
printf("\n");
}
void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr)
{
int ix;
EL_Type *drow, *srow;
drow = m->mtx[ixrdest];
srow = m->mtx[ixrsrc];
for (ix=0; ix<m->dim_x; ix++)
drow[ix] += mplr * srow[ix];
}
void MtxSwapRows( Matrix m, int rix1, int rix2)
{
EL_Type *r1, *r2, temp;
int ix;
if (rix1 == rix2) return;
r1 = m->mtx[rix1];
r2 = m->mtx[rix2];
for (ix=0; ix<m->dim_x; ix++)
temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp;
}
void MtxNormalizeRow( Matrix m, int rix, int lead)
{
int ix;
EL_Type *drow;
EL_Type lv;
drow = m->mtx[rix];
lv = drow[lead];
for (ix=0; ix<m->dim_x; ix++)
drow[ix] /= lv;
}
#define MtxGet( m, rix, cix ) m->mtx[rix][cix]
void MtxToReducedREForm(Matrix m)
{
int lead;
int rix, iix;
EL_Type lv;
int rowCount = m->dim_y;
lead = 0;
for (rix=0; rix<rowCount; rix++) {
if (lead >= m->dim_x)
return;
iix = rix;
while (0 == MtxGet(m, iix,lead)) {
iix++;
if (iix == rowCount) {
iix = rix;
lead++;
if (lead == m->dim_x)
return;
}
}
MtxSwapRows(m, iix, rix );
MtxNormalizeRow(m, rix, lead );
for (iix=0; iix<rowCount; iix++) {
if ( iix != rix ) {
lv = MtxGet(m, iix, lead );
MtxMulAndAddRows(m,iix, rix, -lv) ;
}
}
lead++;
}
}
int main()
{
Matrix m1;
static EL_Type r1[] = {1,2,-1,-4};
static EL_Type r2[] = {2,3,-1,-11};
static EL_Type r3[] = {-2,0,-3,22};
static EL_Type *im[] = { r1, r2, r3 };
m1 = InitMatrix( 4,3, im );
printf("Initial\n");
MtxDisplay(m1);
MtxToReducedREForm(m1);
printf("Reduced R-E form\n");
MtxDisplay(m1);
return 0;
}
|
Generate an equivalent C++ version of this Ada code. | generic
type Element_Type is private;
Zero : Element_Type;
with function "-" (Left, Right : in Element_Type) return Element_Type is <>;
with function "*" (Left, Right : in Element_Type) return Element_Type is <>;
with function "/" (Left, Right : in Element_Type) return Element_Type is <>;
package Matrices is
type Matrix is
array (Positive range <>, Positive range <>) of Element_Type;
function Reduced_Row_Echelon_form (Source : Matrix) return Matrix;
end Matrices;
| #include <algorithm>
#include <cstddef>
#include <cassert>
template<typename MatrixType> struct matrix_traits
{
typedef typename MatrixType::index_type index_type;
typedef typename MatrixType::value_type value_type;
static index_type min_row(MatrixType const& A)
{ return A.min_row(); }
static index_type max_row(MatrixType const& A)
{ return A.max_row(); }
static index_type min_column(MatrixType const& A)
{ return A.min_column(); }
static index_type max_column(MatrixType const& A)
{ return A.max_column(); }
static value_type& element(MatrixType& A, index_type i, index_type k)
{ return A(i,k); }
static value_type element(MatrixType const& A, index_type i, index_type k)
{ return A(i,k); }
};
template<typename T, std::size_t rows, std::size_t columns>
struct matrix_traits<T[rows][columns]>
{
typedef std::size_t index_type;
typedef T value_type;
static index_type min_row(T const (&)[rows][columns])
{ return 0; }
static index_type max_row(T const (&)[rows][columns])
{ return rows-1; }
static index_type min_column(T const (&)[rows][columns])
{ return 0; }
static index_type max_column(T const (&)[rows][columns])
{ return columns-1; }
static value_type& element(T (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
static value_type element(T const (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
};
template<typename MatrixType>
void swap_rows(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
std::swap(mt.element(A, i, col), mt.element(A, k, col));
}
template<typename MatrixType>
void divide_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(v != 0);
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) /= v;
}
template<typename MatrixType>
void add_multiple_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) += v * mt.element(A, k, col);
}
template<typename MatrixType>
void to_reduced_row_echelon_form(MatrixType& A)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
index_type lead = mt.min_row(A);
for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row)
{
if (lead > mt.max_column(A))
return;
index_type i = row;
while (mt.element(A, i, lead) == 0)
{
++i;
if (i > mt.max_row(A))
{
i = row;
++lead;
if (lead > mt.max_column(A))
return;
}
}
swap_rows(A, i, row);
divide_row(A, row, mt.element(A, row, lead));
for (i = mt.min_row(A); i <= mt.max_row(A); ++i)
{
if (i != row)
add_multiple_row(A, i, row, -mt.element(A, i, lead));
}
}
}
#include <iostream>
int main()
{
double M[3][4] = { { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } };
to_reduced_row_echelon_form(M);
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
std::cout << M[i][j] << '\t';
std::cout << "\n";
}
return EXIT_SUCCESS;
}
|
Write the same code in Go as shown below in Ada. | generic
type Element_Type is private;
Zero : Element_Type;
with function "-" (Left, Right : in Element_Type) return Element_Type is <>;
with function "*" (Left, Right : in Element_Type) return Element_Type is <>;
with function "/" (Left, Right : in Element_Type) return Element_Type is <>;
package Matrices is
type Matrix is
array (Positive range <>, Positive range <>) of Element_Type;
function Reduced_Row_Echelon_form (Source : Matrix) return Matrix;
end Matrices;
| package main
import "fmt"
type matrix [][]float64
func (m matrix) print() {
for _, r := range m {
fmt.Println(r)
}
fmt.Println("")
}
func main() {
m := matrix{
{ 1, 2, -1, -4},
{ 2, 3, -1, -11},
{-2, 0, -3, 22},
}
m.print()
rref(m)
m.print()
}
func rref(m matrix) {
lead := 0
rowCount := len(m)
columnCount := len(m[0])
for r := 0; r < rowCount; r++ {
if lead >= columnCount {
return
}
i := r
for m[i][lead] == 0 {
i++
if rowCount == i {
i = r
lead++
if columnCount == lead {
return
}
}
}
m[i], m[r] = m[r], m[i]
f := 1 / m[r][lead]
for j, _ := range m[r] {
m[r][j] *= f
}
for i = 0; i < rowCount; i++ {
if i != r {
f = m[i][lead]
for j, e := range m[r] {
m[i][j] -= e * f
}
}
}
lead++
}
}
|
Generate a Java translation of this Ada snippet without changing its computational steps. | generic
type Element_Type is private;
Zero : Element_Type;
with function "-" (Left, Right : in Element_Type) return Element_Type is <>;
with function "*" (Left, Right : in Element_Type) return Element_Type is <>;
with function "/" (Left, Right : in Element_Type) return Element_Type is <>;
package Matrices is
type Matrix is
array (Positive range <>, Positive range <>) of Element_Type;
function Reduced_Row_Echelon_form (Source : Matrix) return Matrix;
end Matrices;
| import java.util.*;
import java.lang.Math;
import org.apache.commons.math.fraction.Fraction;
import org.apache.commons.math.fraction.FractionConversionException;
class Matrix {
LinkedList<LinkedList<Fraction>> matrix;
int numRows;
int numCols;
static class Coordinate {
int row;
int col;
Coordinate(int r, int c) {
row = r;
col = c;
}
public String toString() {
return "(" + row + ", " + col + ")";
}
}
Matrix(double [][] m) {
numRows = m.length;
numCols = m[0].length;
matrix = new LinkedList<LinkedList<Fraction>>();
for (int i = 0; i < numRows; i++) {
matrix.add(new LinkedList<Fraction>());
for (int j = 0; j < numCols; j++) {
try {
matrix.get(i).add(new Fraction(m[i][j]));
} catch (FractionConversionException e) {
System.err.println("Fraction could not be converted from double by apache commons . . .");
}
}
}
}
public void Interchange(Coordinate a, Coordinate b) {
LinkedList<Fraction> temp = matrix.get(a.row);
matrix.set(a.row, matrix.get(b.row));
matrix.set(b.row, temp);
int t = a.row;
a.row = b.row;
b.row = t;
}
public void Scale(Coordinate x, Fraction d) {
LinkedList<Fraction> row = matrix.get(x.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).multiply(d));
}
}
public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) {
LinkedList<Fraction> row = matrix.get(to.row);
LinkedList<Fraction> rowMultiplied = matrix.get(from.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar))));
}
}
public void RREF() {
Coordinate pivot = new Coordinate(0,0);
int submatrix = 0;
for (int x = 0; x < numCols; x++) {
pivot = new Coordinate(pivot.row, x);
for (int i = x; i < numCols; i++) {
if (isColumnZeroes(pivot) == false) {
break;
} else {
pivot.col = i;
}
}
pivot = findPivot(pivot);
if (getCoordinate(pivot).doubleValue() == 0.0) {
pivot.row++;
continue;
}
if (pivot.row != submatrix) {
Interchange(new Coordinate(submatrix, pivot.col), pivot);
}
if (getCoordinate(pivot).doubleValue() != 1) {
Fraction scalar = getCoordinate(pivot).reciprocal();
Scale(pivot, scalar);
}
for (int i = pivot.row; i < numRows; i++) {
if (i == pivot.row) {
continue;
}
Coordinate belowPivot = new Coordinate(i, pivot.col);
Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot)));
MultiplyAndAdd(belowPivot, pivot, complement);
}
for (int i = pivot.row; i >= 0; i--) {
if (i == pivot.row) {
if (getCoordinate(pivot).doubleValue() != 1.0) {
Scale(pivot, getCoordinate(pivot).reciprocal());
}
continue;
}
if (i == pivot.row) {
continue;
}
Coordinate abovePivot = new Coordinate(i, pivot.col);
Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot)));
MultiplyAndAdd(abovePivot, pivot, complement);
}
if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) {
break;
}
submatrix++;
pivot.row++;
}
}
public boolean isColumnZeroes(Coordinate a) {
for (int i = 0; i < numRows; i++) {
if (matrix.get(i).get(a.col).doubleValue() != 0.0) {
return false;
}
}
return true;
}
public boolean isRowZeroes(Coordinate a) {
for (int i = 0; i < numCols; i++) {
if (matrix.get(a.row).get(i).doubleValue() != 0.0) {
return false;
}
}
return true;
}
public Coordinate findPivot(Coordinate a) {
int first_row = a.row;
Coordinate pivot = new Coordinate(a.row, a.col);
Coordinate current = new Coordinate(a.row, a.col);
for (int i = a.row; i < (numRows - first_row); i++) {
current.row = i;
if (getCoordinate(current).doubleValue() == 1.0) {
Interchange(current, a);
}
}
current.row = a.row;
for (int i = current.row; i < (numRows - first_row); i++) {
current.row = i;
if (getCoordinate(current).doubleValue() != 0) {
pivot.row = i;
break;
}
}
return pivot;
}
public Fraction getCoordinate(Coordinate a) {
return matrix.get(a.row).get(a.col);
}
public String toString() {
return matrix.toString().replace("], ", "]\n");
}
public static void main (String[] args) {
double[][] matrix_1 = {
{1, 2, -1, -4},
{2, 3, -1, -11},
{-2, 0, -3, 22}
};
Matrix x = new Matrix(matrix_1);
System.out.println("before\n" + x.toString() + "\n");
x.RREF();
System.out.println("after\n" + x.toString() + "\n");
double matrix_2 [][] = {
{2, 0, -1, 0, 0},
{1, 0, 0, -1, 0},
{3, 0, 0, -2, -1},
{0, 1, 0, 0, -2},
{0, 1, -1, 0, 0}
};
Matrix y = new Matrix(matrix_2);
System.out.println("before\n" + y.toString() + "\n");
y.RREF();
System.out.println("after\n" + y.toString() + "\n");
double matrix_3 [][] = {
{1, 2, 3, 4, 3, 1},
{2, 4, 6, 2, 6, 2},
{3, 6, 18, 9, 9, -6},
{4, 8, 12, 10, 12, 4},
{5, 10, 24, 11, 15, -4}
};
Matrix z = new Matrix(matrix_3);
System.out.println("before\n" + z.toString() + "\n");
z.RREF();
System.out.println("after\n" + z.toString() + "\n");
double matrix_4 [][] = {
{0, 1},
{1, 2},
{0,5}
};
Matrix a = new Matrix(matrix_4);
System.out.println("before\n" + a.toString() + "\n");
a.RREF();
System.out.println("after\n" + a.toString() + "\n");
}
}
|
Can you help me rewrite this code in Python instead of Ada, keeping it the same logically? | generic
type Element_Type is private;
Zero : Element_Type;
with function "-" (Left, Right : in Element_Type) return Element_Type is <>;
with function "*" (Left, Right : in Element_Type) return Element_Type is <>;
with function "/" (Left, Right : in Element_Type) return Element_Type is <>;
package Matrices is
type Matrix is
array (Positive range <>, Positive range <>) of Element_Type;
function Reduced_Row_Echelon_form (Source : Matrix) return Matrix;
end Matrices;
| def ToReducedRowEchelonForm( M):
if not M: return
lead = 0
rowCount = len(M)
columnCount = len(M[0])
for r in range(rowCount):
if lead >= columnCount:
return
i = r
while M[i][lead] == 0:
i += 1
if i == rowCount:
i = r
lead += 1
if columnCount == lead:
return
M[i],M[r] = M[r],M[i]
lv = M[r][lead]
M[r] = [ mrx / float(lv) for mrx in M[r]]
for i in range(rowCount):
if i != r:
lv = M[i][lead]
M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]
lead += 1
mtx = [
[ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[-2, 0, -3, 22],]
ToReducedRowEchelonForm( mtx )
for rw in mtx:
print ', '.join( (str(rv) for rv in rw) )
|
Convert this Ada block to VB, preserving its control flow and logic. | generic
type Element_Type is private;
Zero : Element_Type;
with function "-" (Left, Right : in Element_Type) return Element_Type is <>;
with function "*" (Left, Right : in Element_Type) return Element_Type is <>;
with function "/" (Left, Right : in Element_Type) return Element_Type is <>;
package Matrices is
type Matrix is
array (Positive range <>, Positive range <>) of Element_Type;
function Reduced_Row_Echelon_form (Source : Matrix) return Matrix;
end Matrices;
| Private Function ToReducedRowEchelonForm(M As Variant) As Variant
Dim lead As Integer: lead = 0
Dim rowCount As Integer: rowCount = UBound(M)
Dim columnCount As Integer: columnCount = UBound(M(0))
Dim i As Integer
For r = 0 To rowCount
If lead >= columnCount Then
Exit For
End If
i = r
Do While M(i)(lead) = 0
i = i + 1
If i = rowCount Then
i = r
lead = lead + 1
If lead = columnCount Then
Exit For
End If
End If
Loop
Dim tmp As Variant
tmp = M(r)
M(r) = M(i)
M(i) = tmp
If M(r)(lead) <> 0 Then
div = M(r)(lead)
For t = LBound(M(r)) To UBound(M(r))
M(r)(t) = M(r)(t) / div
Next t
End If
For j = 0 To rowCount
If j <> r Then
subt = M(j)(lead)
For t = LBound(M(j)) To UBound(M(j))
M(j)(t) = M(j)(t) - subt * M(r)(t)
Next t
End If
Next j
lead = lead + 1
Next r
ToReducedRowEchelonForm = M
End Function
Public Sub main()
r = ToReducedRowEchelonForm(Array( _
Array(1, 2, -1, -4), _
Array(2, 3, -1, -11), _
Array(-2, 0, -3, 22)))
For i = LBound(r) To UBound(r)
Debug.Print Join(r(i), vbTab)
Next i
End Sub
|
Can you help me rewrite this code in C instead of AutoHotKey, keeping it the same logically? | ToReducedRowEchelonForm(M){
rowCount := M.Count()
columnCount := M.1.Count()
r := lead := 1
while (r <= rowCount) {
if (columnCount < lead)
return M
i := r
while (M[i, lead] = 0) {
i++
if (rowCount+1 = i) {
i := r, lead++
if (columnCount+1 = lead)
return M
}
}
if (i<>r)
for col, v in M[i]
tempVal := M[i, col], M[i, col] := M[r, col], M[r, col] := tempVal
num := M[r, lead]
if (M[r, lead] <> 0)
for col, val in M[r]
M[r, col] /= num
i := 2
while (i <= rowCount) {
num := M[i, lead]
if (i <> r)
for col, val in M[i]
M[i, col] -= num * M[r, col]
i++
}
lead++, r++
}
return M
}
| #include <stdio.h>
#define TALLOC(n,typ) malloc(n*sizeof(typ))
#define EL_Type int
typedef struct sMtx {
int dim_x, dim_y;
EL_Type *m_stor;
EL_Type **mtx;
} *Matrix, sMatrix;
typedef struct sRvec {
int dim_x;
EL_Type *m_stor;
} *RowVec, sRowVec;
Matrix NewMatrix( int x_dim, int y_dim )
{
int n;
Matrix m;
m = TALLOC( 1, sMatrix);
n = x_dim * y_dim;
m->dim_x = x_dim;
m->dim_y = y_dim;
m->m_stor = TALLOC(n, EL_Type);
m->mtx = TALLOC(m->dim_y, EL_Type *);
for(n=0; n<y_dim; n++) {
m->mtx[n] = m->m_stor+n*x_dim;
}
return m;
}
void MtxSetRow(Matrix m, int irow, EL_Type *v)
{
int ix;
EL_Type *mr;
mr = m->mtx[irow];
for(ix=0; ix<m->dim_x; ix++)
mr[ix] = v[ix];
}
Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v)
{
Matrix m;
int iy;
m = NewMatrix(x_dim, y_dim);
for (iy=0; iy<y_dim; iy++)
MtxSetRow(m, iy, v[iy]);
return m;
}
void MtxDisplay( Matrix m )
{
int iy, ix;
const char *sc;
for (iy=0; iy<m->dim_y; iy++) {
printf(" ");
sc = " ";
for (ix=0; ix<m->dim_x; ix++) {
printf("%s %3d", sc, m->mtx[iy][ix]);
sc = ",";
}
printf("\n");
}
printf("\n");
}
void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr)
{
int ix;
EL_Type *drow, *srow;
drow = m->mtx[ixrdest];
srow = m->mtx[ixrsrc];
for (ix=0; ix<m->dim_x; ix++)
drow[ix] += mplr * srow[ix];
}
void MtxSwapRows( Matrix m, int rix1, int rix2)
{
EL_Type *r1, *r2, temp;
int ix;
if (rix1 == rix2) return;
r1 = m->mtx[rix1];
r2 = m->mtx[rix2];
for (ix=0; ix<m->dim_x; ix++)
temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp;
}
void MtxNormalizeRow( Matrix m, int rix, int lead)
{
int ix;
EL_Type *drow;
EL_Type lv;
drow = m->mtx[rix];
lv = drow[lead];
for (ix=0; ix<m->dim_x; ix++)
drow[ix] /= lv;
}
#define MtxGet( m, rix, cix ) m->mtx[rix][cix]
void MtxToReducedREForm(Matrix m)
{
int lead;
int rix, iix;
EL_Type lv;
int rowCount = m->dim_y;
lead = 0;
for (rix=0; rix<rowCount; rix++) {
if (lead >= m->dim_x)
return;
iix = rix;
while (0 == MtxGet(m, iix,lead)) {
iix++;
if (iix == rowCount) {
iix = rix;
lead++;
if (lead == m->dim_x)
return;
}
}
MtxSwapRows(m, iix, rix );
MtxNormalizeRow(m, rix, lead );
for (iix=0; iix<rowCount; iix++) {
if ( iix != rix ) {
lv = MtxGet(m, iix, lead );
MtxMulAndAddRows(m,iix, rix, -lv) ;
}
}
lead++;
}
}
int main()
{
Matrix m1;
static EL_Type r1[] = {1,2,-1,-4};
static EL_Type r2[] = {2,3,-1,-11};
static EL_Type r3[] = {-2,0,-3,22};
static EL_Type *im[] = { r1, r2, r3 };
m1 = InitMatrix( 4,3, im );
printf("Initial\n");
MtxDisplay(m1);
MtxToReducedREForm(m1);
printf("Reduced R-E form\n");
MtxDisplay(m1);
return 0;
}
|
Produce a language-to-language conversion: from AutoHotKey to C#, same semantics. | ToReducedRowEchelonForm(M){
rowCount := M.Count()
columnCount := M.1.Count()
r := lead := 1
while (r <= rowCount) {
if (columnCount < lead)
return M
i := r
while (M[i, lead] = 0) {
i++
if (rowCount+1 = i) {
i := r, lead++
if (columnCount+1 = lead)
return M
}
}
if (i<>r)
for col, v in M[i]
tempVal := M[i, col], M[i, col] := M[r, col], M[r, col] := tempVal
num := M[r, lead]
if (M[r, lead] <> 0)
for col, val in M[r]
M[r, col] /= num
i := 2
while (i <= rowCount) {
num := M[i, lead]
if (i <> r)
for col, val in M[i]
M[i, col] -= num * M[r, col]
i++
}
lead++, r++
}
return M
}
| using System;
namespace rref
{
class Program
{
static void Main(string[] args)
{
int[,] matrix = new int[3, 4]{
{ 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 }
};
matrix = rref(matrix);
}
private static int[,] rref(int[,] matrix)
{
int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1);
for (int r = 0; r < rowCount; r++)
{
if (columnCount <= lead) break;
int i = r;
while (matrix[i, lead] == 0)
{
i++;
if (i == rowCount)
{
i = r;
lead++;
if (columnCount == lead)
{
lead--;
break;
}
}
}
for (int j = 0; j < columnCount; j++)
{
int temp = matrix[r, j];
matrix[r, j] = matrix[i, j];
matrix[i, j] = temp;
}
int div = matrix[r, lead];
if(div != 0)
for (int j = 0; j < columnCount; j++) matrix[r, j] /= div;
for (int j = 0; j < rowCount; j++)
{
if (j != r)
{
int sub = matrix[j, lead];
for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]);
}
}
lead++;
}
return matrix;
}
}
}
|
Change the following AutoHotKey code into C++ without altering its purpose. | ToReducedRowEchelonForm(M){
rowCount := M.Count()
columnCount := M.1.Count()
r := lead := 1
while (r <= rowCount) {
if (columnCount < lead)
return M
i := r
while (M[i, lead] = 0) {
i++
if (rowCount+1 = i) {
i := r, lead++
if (columnCount+1 = lead)
return M
}
}
if (i<>r)
for col, v in M[i]
tempVal := M[i, col], M[i, col] := M[r, col], M[r, col] := tempVal
num := M[r, lead]
if (M[r, lead] <> 0)
for col, val in M[r]
M[r, col] /= num
i := 2
while (i <= rowCount) {
num := M[i, lead]
if (i <> r)
for col, val in M[i]
M[i, col] -= num * M[r, col]
i++
}
lead++, r++
}
return M
}
| #include <algorithm>
#include <cstddef>
#include <cassert>
template<typename MatrixType> struct matrix_traits
{
typedef typename MatrixType::index_type index_type;
typedef typename MatrixType::value_type value_type;
static index_type min_row(MatrixType const& A)
{ return A.min_row(); }
static index_type max_row(MatrixType const& A)
{ return A.max_row(); }
static index_type min_column(MatrixType const& A)
{ return A.min_column(); }
static index_type max_column(MatrixType const& A)
{ return A.max_column(); }
static value_type& element(MatrixType& A, index_type i, index_type k)
{ return A(i,k); }
static value_type element(MatrixType const& A, index_type i, index_type k)
{ return A(i,k); }
};
template<typename T, std::size_t rows, std::size_t columns>
struct matrix_traits<T[rows][columns]>
{
typedef std::size_t index_type;
typedef T value_type;
static index_type min_row(T const (&)[rows][columns])
{ return 0; }
static index_type max_row(T const (&)[rows][columns])
{ return rows-1; }
static index_type min_column(T const (&)[rows][columns])
{ return 0; }
static index_type max_column(T const (&)[rows][columns])
{ return columns-1; }
static value_type& element(T (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
static value_type element(T const (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
};
template<typename MatrixType>
void swap_rows(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
std::swap(mt.element(A, i, col), mt.element(A, k, col));
}
template<typename MatrixType>
void divide_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(v != 0);
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) /= v;
}
template<typename MatrixType>
void add_multiple_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) += v * mt.element(A, k, col);
}
template<typename MatrixType>
void to_reduced_row_echelon_form(MatrixType& A)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
index_type lead = mt.min_row(A);
for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row)
{
if (lead > mt.max_column(A))
return;
index_type i = row;
while (mt.element(A, i, lead) == 0)
{
++i;
if (i > mt.max_row(A))
{
i = row;
++lead;
if (lead > mt.max_column(A))
return;
}
}
swap_rows(A, i, row);
divide_row(A, row, mt.element(A, row, lead));
for (i = mt.min_row(A); i <= mt.max_row(A); ++i)
{
if (i != row)
add_multiple_row(A, i, row, -mt.element(A, i, lead));
}
}
}
#include <iostream>
int main()
{
double M[3][4] = { { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } };
to_reduced_row_echelon_form(M);
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
std::cout << M[i][j] << '\t';
std::cout << "\n";
}
return EXIT_SUCCESS;
}
|
Please provide an equivalent version of this AutoHotKey code in Java. | ToReducedRowEchelonForm(M){
rowCount := M.Count()
columnCount := M.1.Count()
r := lead := 1
while (r <= rowCount) {
if (columnCount < lead)
return M
i := r
while (M[i, lead] = 0) {
i++
if (rowCount+1 = i) {
i := r, lead++
if (columnCount+1 = lead)
return M
}
}
if (i<>r)
for col, v in M[i]
tempVal := M[i, col], M[i, col] := M[r, col], M[r, col] := tempVal
num := M[r, lead]
if (M[r, lead] <> 0)
for col, val in M[r]
M[r, col] /= num
i := 2
while (i <= rowCount) {
num := M[i, lead]
if (i <> r)
for col, val in M[i]
M[i, col] -= num * M[r, col]
i++
}
lead++, r++
}
return M
}
| import java.util.*;
import java.lang.Math;
import org.apache.commons.math.fraction.Fraction;
import org.apache.commons.math.fraction.FractionConversionException;
class Matrix {
LinkedList<LinkedList<Fraction>> matrix;
int numRows;
int numCols;
static class Coordinate {
int row;
int col;
Coordinate(int r, int c) {
row = r;
col = c;
}
public String toString() {
return "(" + row + ", " + col + ")";
}
}
Matrix(double [][] m) {
numRows = m.length;
numCols = m[0].length;
matrix = new LinkedList<LinkedList<Fraction>>();
for (int i = 0; i < numRows; i++) {
matrix.add(new LinkedList<Fraction>());
for (int j = 0; j < numCols; j++) {
try {
matrix.get(i).add(new Fraction(m[i][j]));
} catch (FractionConversionException e) {
System.err.println("Fraction could not be converted from double by apache commons . . .");
}
}
}
}
public void Interchange(Coordinate a, Coordinate b) {
LinkedList<Fraction> temp = matrix.get(a.row);
matrix.set(a.row, matrix.get(b.row));
matrix.set(b.row, temp);
int t = a.row;
a.row = b.row;
b.row = t;
}
public void Scale(Coordinate x, Fraction d) {
LinkedList<Fraction> row = matrix.get(x.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).multiply(d));
}
}
public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) {
LinkedList<Fraction> row = matrix.get(to.row);
LinkedList<Fraction> rowMultiplied = matrix.get(from.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar))));
}
}
public void RREF() {
Coordinate pivot = new Coordinate(0,0);
int submatrix = 0;
for (int x = 0; x < numCols; x++) {
pivot = new Coordinate(pivot.row, x);
for (int i = x; i < numCols; i++) {
if (isColumnZeroes(pivot) == false) {
break;
} else {
pivot.col = i;
}
}
pivot = findPivot(pivot);
if (getCoordinate(pivot).doubleValue() == 0.0) {
pivot.row++;
continue;
}
if (pivot.row != submatrix) {
Interchange(new Coordinate(submatrix, pivot.col), pivot);
}
if (getCoordinate(pivot).doubleValue() != 1) {
Fraction scalar = getCoordinate(pivot).reciprocal();
Scale(pivot, scalar);
}
for (int i = pivot.row; i < numRows; i++) {
if (i == pivot.row) {
continue;
}
Coordinate belowPivot = new Coordinate(i, pivot.col);
Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot)));
MultiplyAndAdd(belowPivot, pivot, complement);
}
for (int i = pivot.row; i >= 0; i--) {
if (i == pivot.row) {
if (getCoordinate(pivot).doubleValue() != 1.0) {
Scale(pivot, getCoordinate(pivot).reciprocal());
}
continue;
}
if (i == pivot.row) {
continue;
}
Coordinate abovePivot = new Coordinate(i, pivot.col);
Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot)));
MultiplyAndAdd(abovePivot, pivot, complement);
}
if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) {
break;
}
submatrix++;
pivot.row++;
}
}
public boolean isColumnZeroes(Coordinate a) {
for (int i = 0; i < numRows; i++) {
if (matrix.get(i).get(a.col).doubleValue() != 0.0) {
return false;
}
}
return true;
}
public boolean isRowZeroes(Coordinate a) {
for (int i = 0; i < numCols; i++) {
if (matrix.get(a.row).get(i).doubleValue() != 0.0) {
return false;
}
}
return true;
}
public Coordinate findPivot(Coordinate a) {
int first_row = a.row;
Coordinate pivot = new Coordinate(a.row, a.col);
Coordinate current = new Coordinate(a.row, a.col);
for (int i = a.row; i < (numRows - first_row); i++) {
current.row = i;
if (getCoordinate(current).doubleValue() == 1.0) {
Interchange(current, a);
}
}
current.row = a.row;
for (int i = current.row; i < (numRows - first_row); i++) {
current.row = i;
if (getCoordinate(current).doubleValue() != 0) {
pivot.row = i;
break;
}
}
return pivot;
}
public Fraction getCoordinate(Coordinate a) {
return matrix.get(a.row).get(a.col);
}
public String toString() {
return matrix.toString().replace("], ", "]\n");
}
public static void main (String[] args) {
double[][] matrix_1 = {
{1, 2, -1, -4},
{2, 3, -1, -11},
{-2, 0, -3, 22}
};
Matrix x = new Matrix(matrix_1);
System.out.println("before\n" + x.toString() + "\n");
x.RREF();
System.out.println("after\n" + x.toString() + "\n");
double matrix_2 [][] = {
{2, 0, -1, 0, 0},
{1, 0, 0, -1, 0},
{3, 0, 0, -2, -1},
{0, 1, 0, 0, -2},
{0, 1, -1, 0, 0}
};
Matrix y = new Matrix(matrix_2);
System.out.println("before\n" + y.toString() + "\n");
y.RREF();
System.out.println("after\n" + y.toString() + "\n");
double matrix_3 [][] = {
{1, 2, 3, 4, 3, 1},
{2, 4, 6, 2, 6, 2},
{3, 6, 18, 9, 9, -6},
{4, 8, 12, 10, 12, 4},
{5, 10, 24, 11, 15, -4}
};
Matrix z = new Matrix(matrix_3);
System.out.println("before\n" + z.toString() + "\n");
z.RREF();
System.out.println("after\n" + z.toString() + "\n");
double matrix_4 [][] = {
{0, 1},
{1, 2},
{0,5}
};
Matrix a = new Matrix(matrix_4);
System.out.println("before\n" + a.toString() + "\n");
a.RREF();
System.out.println("after\n" + a.toString() + "\n");
}
}
|
Convert this AutoHotKey snippet to Python and keep its semantics consistent. | ToReducedRowEchelonForm(M){
rowCount := M.Count()
columnCount := M.1.Count()
r := lead := 1
while (r <= rowCount) {
if (columnCount < lead)
return M
i := r
while (M[i, lead] = 0) {
i++
if (rowCount+1 = i) {
i := r, lead++
if (columnCount+1 = lead)
return M
}
}
if (i<>r)
for col, v in M[i]
tempVal := M[i, col], M[i, col] := M[r, col], M[r, col] := tempVal
num := M[r, lead]
if (M[r, lead] <> 0)
for col, val in M[r]
M[r, col] /= num
i := 2
while (i <= rowCount) {
num := M[i, lead]
if (i <> r)
for col, val in M[i]
M[i, col] -= num * M[r, col]
i++
}
lead++, r++
}
return M
}
| def ToReducedRowEchelonForm( M):
if not M: return
lead = 0
rowCount = len(M)
columnCount = len(M[0])
for r in range(rowCount):
if lead >= columnCount:
return
i = r
while M[i][lead] == 0:
i += 1
if i == rowCount:
i = r
lead += 1
if columnCount == lead:
return
M[i],M[r] = M[r],M[i]
lv = M[r][lead]
M[r] = [ mrx / float(lv) for mrx in M[r]]
for i in range(rowCount):
if i != r:
lv = M[i][lead]
M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]
lead += 1
mtx = [
[ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[-2, 0, -3, 22],]
ToReducedRowEchelonForm( mtx )
for rw in mtx:
print ', '.join( (str(rv) for rv in rw) )
|
Please provide an equivalent version of this AutoHotKey code in VB. | ToReducedRowEchelonForm(M){
rowCount := M.Count()
columnCount := M.1.Count()
r := lead := 1
while (r <= rowCount) {
if (columnCount < lead)
return M
i := r
while (M[i, lead] = 0) {
i++
if (rowCount+1 = i) {
i := r, lead++
if (columnCount+1 = lead)
return M
}
}
if (i<>r)
for col, v in M[i]
tempVal := M[i, col], M[i, col] := M[r, col], M[r, col] := tempVal
num := M[r, lead]
if (M[r, lead] <> 0)
for col, val in M[r]
M[r, col] /= num
i := 2
while (i <= rowCount) {
num := M[i, lead]
if (i <> r)
for col, val in M[i]
M[i, col] -= num * M[r, col]
i++
}
lead++, r++
}
return M
}
| Private Function ToReducedRowEchelonForm(M As Variant) As Variant
Dim lead As Integer: lead = 0
Dim rowCount As Integer: rowCount = UBound(M)
Dim columnCount As Integer: columnCount = UBound(M(0))
Dim i As Integer
For r = 0 To rowCount
If lead >= columnCount Then
Exit For
End If
i = r
Do While M(i)(lead) = 0
i = i + 1
If i = rowCount Then
i = r
lead = lead + 1
If lead = columnCount Then
Exit For
End If
End If
Loop
Dim tmp As Variant
tmp = M(r)
M(r) = M(i)
M(i) = tmp
If M(r)(lead) <> 0 Then
div = M(r)(lead)
For t = LBound(M(r)) To UBound(M(r))
M(r)(t) = M(r)(t) / div
Next t
End If
For j = 0 To rowCount
If j <> r Then
subt = M(j)(lead)
For t = LBound(M(j)) To UBound(M(j))
M(j)(t) = M(j)(t) - subt * M(r)(t)
Next t
End If
Next j
lead = lead + 1
Next r
ToReducedRowEchelonForm = M
End Function
Public Sub main()
r = ToReducedRowEchelonForm(Array( _
Array(1, 2, -1, -4), _
Array(2, 3, -1, -11), _
Array(-2, 0, -3, 22)))
For i = LBound(r) To UBound(r)
Debug.Print Join(r(i), vbTab)
Next i
End Sub
|
Translate this program into Go but keep the logic exactly as in AutoHotKey. | ToReducedRowEchelonForm(M){
rowCount := M.Count()
columnCount := M.1.Count()
r := lead := 1
while (r <= rowCount) {
if (columnCount < lead)
return M
i := r
while (M[i, lead] = 0) {
i++
if (rowCount+1 = i) {
i := r, lead++
if (columnCount+1 = lead)
return M
}
}
if (i<>r)
for col, v in M[i]
tempVal := M[i, col], M[i, col] := M[r, col], M[r, col] := tempVal
num := M[r, lead]
if (M[r, lead] <> 0)
for col, val in M[r]
M[r, col] /= num
i := 2
while (i <= rowCount) {
num := M[i, lead]
if (i <> r)
for col, val in M[i]
M[i, col] -= num * M[r, col]
i++
}
lead++, r++
}
return M
}
| package main
import "fmt"
type matrix [][]float64
func (m matrix) print() {
for _, r := range m {
fmt.Println(r)
}
fmt.Println("")
}
func main() {
m := matrix{
{ 1, 2, -1, -4},
{ 2, 3, -1, -11},
{-2, 0, -3, 22},
}
m.print()
rref(m)
m.print()
}
func rref(m matrix) {
lead := 0
rowCount := len(m)
columnCount := len(m[0])
for r := 0; r < rowCount; r++ {
if lead >= columnCount {
return
}
i := r
for m[i][lead] == 0 {
i++
if rowCount == i {
i = r
lead++
if columnCount == lead {
return
}
}
}
m[i], m[r] = m[r], m[i]
f := 1 / m[r][lead]
for j, _ := range m[r] {
m[r][j] *= f
}
for i = 0; i < rowCount; i++ {
if i != r {
f = m[i][lead]
for j, e := range m[r] {
m[i][j] -= e * f
}
}
}
lead++
}
}
|
Produce a language-to-language conversion: from BBC_Basic to C, same semantics. | DIM matrix(2,3)
matrix() = 1, 2, -1, -4, \
\ 2, 3, -1, -11, \
\ -2, 0, -3, 22
PROCrref(matrix())
FOR row% = 0 TO 2
FOR col% = 0 TO 3
PRINT matrix(row%,col%);
NEXT
PRINT
NEXT row%
END
DEF PROCrref(m())
LOCAL lead%, nrows%, ncols%, i%, j%, r%, n
nrows% = DIM(m(),1)+1
ncols% = DIM(m(),2)+1
FOR r% = 0 TO nrows%-1
IF lead% >= ncols% EXIT FOR
i% = r%
WHILE m(i%,lead%) = 0
i% += 1
IF i% = nrows% THEN
i% = r%
lead% += 1
IF lead% = ncols% EXIT FOR
ENDIF
ENDWHILE
FOR j% = 0 TO ncols%-1 : SWAP m(i%,j%),m(r%,j%) : NEXT
n = m(r%,lead%)
IF n <> 0 FOR j% = 0 TO ncols%-1 : m(r%,j%) /= n : NEXT
FOR i% = 0 TO nrows%-1
IF i% <> r% THEN
n = m(i%,lead%)
FOR j% = 0 TO ncols%-1
m(i%,j%) -= m(r%,j%) * n
NEXT
ENDIF
NEXT
lead% += 1
NEXT r%
ENDPROC
| #include <stdio.h>
#define TALLOC(n,typ) malloc(n*sizeof(typ))
#define EL_Type int
typedef struct sMtx {
int dim_x, dim_y;
EL_Type *m_stor;
EL_Type **mtx;
} *Matrix, sMatrix;
typedef struct sRvec {
int dim_x;
EL_Type *m_stor;
} *RowVec, sRowVec;
Matrix NewMatrix( int x_dim, int y_dim )
{
int n;
Matrix m;
m = TALLOC( 1, sMatrix);
n = x_dim * y_dim;
m->dim_x = x_dim;
m->dim_y = y_dim;
m->m_stor = TALLOC(n, EL_Type);
m->mtx = TALLOC(m->dim_y, EL_Type *);
for(n=0; n<y_dim; n++) {
m->mtx[n] = m->m_stor+n*x_dim;
}
return m;
}
void MtxSetRow(Matrix m, int irow, EL_Type *v)
{
int ix;
EL_Type *mr;
mr = m->mtx[irow];
for(ix=0; ix<m->dim_x; ix++)
mr[ix] = v[ix];
}
Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v)
{
Matrix m;
int iy;
m = NewMatrix(x_dim, y_dim);
for (iy=0; iy<y_dim; iy++)
MtxSetRow(m, iy, v[iy]);
return m;
}
void MtxDisplay( Matrix m )
{
int iy, ix;
const char *sc;
for (iy=0; iy<m->dim_y; iy++) {
printf(" ");
sc = " ";
for (ix=0; ix<m->dim_x; ix++) {
printf("%s %3d", sc, m->mtx[iy][ix]);
sc = ",";
}
printf("\n");
}
printf("\n");
}
void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr)
{
int ix;
EL_Type *drow, *srow;
drow = m->mtx[ixrdest];
srow = m->mtx[ixrsrc];
for (ix=0; ix<m->dim_x; ix++)
drow[ix] += mplr * srow[ix];
}
void MtxSwapRows( Matrix m, int rix1, int rix2)
{
EL_Type *r1, *r2, temp;
int ix;
if (rix1 == rix2) return;
r1 = m->mtx[rix1];
r2 = m->mtx[rix2];
for (ix=0; ix<m->dim_x; ix++)
temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp;
}
void MtxNormalizeRow( Matrix m, int rix, int lead)
{
int ix;
EL_Type *drow;
EL_Type lv;
drow = m->mtx[rix];
lv = drow[lead];
for (ix=0; ix<m->dim_x; ix++)
drow[ix] /= lv;
}
#define MtxGet( m, rix, cix ) m->mtx[rix][cix]
void MtxToReducedREForm(Matrix m)
{
int lead;
int rix, iix;
EL_Type lv;
int rowCount = m->dim_y;
lead = 0;
for (rix=0; rix<rowCount; rix++) {
if (lead >= m->dim_x)
return;
iix = rix;
while (0 == MtxGet(m, iix,lead)) {
iix++;
if (iix == rowCount) {
iix = rix;
lead++;
if (lead == m->dim_x)
return;
}
}
MtxSwapRows(m, iix, rix );
MtxNormalizeRow(m, rix, lead );
for (iix=0; iix<rowCount; iix++) {
if ( iix != rix ) {
lv = MtxGet(m, iix, lead );
MtxMulAndAddRows(m,iix, rix, -lv) ;
}
}
lead++;
}
}
int main()
{
Matrix m1;
static EL_Type r1[] = {1,2,-1,-4};
static EL_Type r2[] = {2,3,-1,-11};
static EL_Type r3[] = {-2,0,-3,22};
static EL_Type *im[] = { r1, r2, r3 };
m1 = InitMatrix( 4,3, im );
printf("Initial\n");
MtxDisplay(m1);
MtxToReducedREForm(m1);
printf("Reduced R-E form\n");
MtxDisplay(m1);
return 0;
}
|
Convert the following code from BBC_Basic to C#, ensuring the logic remains intact. | DIM matrix(2,3)
matrix() = 1, 2, -1, -4, \
\ 2, 3, -1, -11, \
\ -2, 0, -3, 22
PROCrref(matrix())
FOR row% = 0 TO 2
FOR col% = 0 TO 3
PRINT matrix(row%,col%);
NEXT
PRINT
NEXT row%
END
DEF PROCrref(m())
LOCAL lead%, nrows%, ncols%, i%, j%, r%, n
nrows% = DIM(m(),1)+1
ncols% = DIM(m(),2)+1
FOR r% = 0 TO nrows%-1
IF lead% >= ncols% EXIT FOR
i% = r%
WHILE m(i%,lead%) = 0
i% += 1
IF i% = nrows% THEN
i% = r%
lead% += 1
IF lead% = ncols% EXIT FOR
ENDIF
ENDWHILE
FOR j% = 0 TO ncols%-1 : SWAP m(i%,j%),m(r%,j%) : NEXT
n = m(r%,lead%)
IF n <> 0 FOR j% = 0 TO ncols%-1 : m(r%,j%) /= n : NEXT
FOR i% = 0 TO nrows%-1
IF i% <> r% THEN
n = m(i%,lead%)
FOR j% = 0 TO ncols%-1
m(i%,j%) -= m(r%,j%) * n
NEXT
ENDIF
NEXT
lead% += 1
NEXT r%
ENDPROC
| using System;
namespace rref
{
class Program
{
static void Main(string[] args)
{
int[,] matrix = new int[3, 4]{
{ 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 }
};
matrix = rref(matrix);
}
private static int[,] rref(int[,] matrix)
{
int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1);
for (int r = 0; r < rowCount; r++)
{
if (columnCount <= lead) break;
int i = r;
while (matrix[i, lead] == 0)
{
i++;
if (i == rowCount)
{
i = r;
lead++;
if (columnCount == lead)
{
lead--;
break;
}
}
}
for (int j = 0; j < columnCount; j++)
{
int temp = matrix[r, j];
matrix[r, j] = matrix[i, j];
matrix[i, j] = temp;
}
int div = matrix[r, lead];
if(div != 0)
for (int j = 0; j < columnCount; j++) matrix[r, j] /= div;
for (int j = 0; j < rowCount; j++)
{
if (j != r)
{
int sub = matrix[j, lead];
for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]);
}
}
lead++;
}
return matrix;
}
}
}
|
Change the programming language of this snippet from BBC_Basic to C++ without modifying what it does. | DIM matrix(2,3)
matrix() = 1, 2, -1, -4, \
\ 2, 3, -1, -11, \
\ -2, 0, -3, 22
PROCrref(matrix())
FOR row% = 0 TO 2
FOR col% = 0 TO 3
PRINT matrix(row%,col%);
NEXT
PRINT
NEXT row%
END
DEF PROCrref(m())
LOCAL lead%, nrows%, ncols%, i%, j%, r%, n
nrows% = DIM(m(),1)+1
ncols% = DIM(m(),2)+1
FOR r% = 0 TO nrows%-1
IF lead% >= ncols% EXIT FOR
i% = r%
WHILE m(i%,lead%) = 0
i% += 1
IF i% = nrows% THEN
i% = r%
lead% += 1
IF lead% = ncols% EXIT FOR
ENDIF
ENDWHILE
FOR j% = 0 TO ncols%-1 : SWAP m(i%,j%),m(r%,j%) : NEXT
n = m(r%,lead%)
IF n <> 0 FOR j% = 0 TO ncols%-1 : m(r%,j%) /= n : NEXT
FOR i% = 0 TO nrows%-1
IF i% <> r% THEN
n = m(i%,lead%)
FOR j% = 0 TO ncols%-1
m(i%,j%) -= m(r%,j%) * n
NEXT
ENDIF
NEXT
lead% += 1
NEXT r%
ENDPROC
| #include <algorithm>
#include <cstddef>
#include <cassert>
template<typename MatrixType> struct matrix_traits
{
typedef typename MatrixType::index_type index_type;
typedef typename MatrixType::value_type value_type;
static index_type min_row(MatrixType const& A)
{ return A.min_row(); }
static index_type max_row(MatrixType const& A)
{ return A.max_row(); }
static index_type min_column(MatrixType const& A)
{ return A.min_column(); }
static index_type max_column(MatrixType const& A)
{ return A.max_column(); }
static value_type& element(MatrixType& A, index_type i, index_type k)
{ return A(i,k); }
static value_type element(MatrixType const& A, index_type i, index_type k)
{ return A(i,k); }
};
template<typename T, std::size_t rows, std::size_t columns>
struct matrix_traits<T[rows][columns]>
{
typedef std::size_t index_type;
typedef T value_type;
static index_type min_row(T const (&)[rows][columns])
{ return 0; }
static index_type max_row(T const (&)[rows][columns])
{ return rows-1; }
static index_type min_column(T const (&)[rows][columns])
{ return 0; }
static index_type max_column(T const (&)[rows][columns])
{ return columns-1; }
static value_type& element(T (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
static value_type element(T const (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
};
template<typename MatrixType>
void swap_rows(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
std::swap(mt.element(A, i, col), mt.element(A, k, col));
}
template<typename MatrixType>
void divide_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(v != 0);
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) /= v;
}
template<typename MatrixType>
void add_multiple_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) += v * mt.element(A, k, col);
}
template<typename MatrixType>
void to_reduced_row_echelon_form(MatrixType& A)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
index_type lead = mt.min_row(A);
for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row)
{
if (lead > mt.max_column(A))
return;
index_type i = row;
while (mt.element(A, i, lead) == 0)
{
++i;
if (i > mt.max_row(A))
{
i = row;
++lead;
if (lead > mt.max_column(A))
return;
}
}
swap_rows(A, i, row);
divide_row(A, row, mt.element(A, row, lead));
for (i = mt.min_row(A); i <= mt.max_row(A); ++i)
{
if (i != row)
add_multiple_row(A, i, row, -mt.element(A, i, lead));
}
}
}
#include <iostream>
int main()
{
double M[3][4] = { { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } };
to_reduced_row_echelon_form(M);
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
std::cout << M[i][j] << '\t';
std::cout << "\n";
}
return EXIT_SUCCESS;
}
|
Convert this BBC_Basic snippet to Java and keep its semantics consistent. | DIM matrix(2,3)
matrix() = 1, 2, -1, -4, \
\ 2, 3, -1, -11, \
\ -2, 0, -3, 22
PROCrref(matrix())
FOR row% = 0 TO 2
FOR col% = 0 TO 3
PRINT matrix(row%,col%);
NEXT
PRINT
NEXT row%
END
DEF PROCrref(m())
LOCAL lead%, nrows%, ncols%, i%, j%, r%, n
nrows% = DIM(m(),1)+1
ncols% = DIM(m(),2)+1
FOR r% = 0 TO nrows%-1
IF lead% >= ncols% EXIT FOR
i% = r%
WHILE m(i%,lead%) = 0
i% += 1
IF i% = nrows% THEN
i% = r%
lead% += 1
IF lead% = ncols% EXIT FOR
ENDIF
ENDWHILE
FOR j% = 0 TO ncols%-1 : SWAP m(i%,j%),m(r%,j%) : NEXT
n = m(r%,lead%)
IF n <> 0 FOR j% = 0 TO ncols%-1 : m(r%,j%) /= n : NEXT
FOR i% = 0 TO nrows%-1
IF i% <> r% THEN
n = m(i%,lead%)
FOR j% = 0 TO ncols%-1
m(i%,j%) -= m(r%,j%) * n
NEXT
ENDIF
NEXT
lead% += 1
NEXT r%
ENDPROC
| import java.util.*;
import java.lang.Math;
import org.apache.commons.math.fraction.Fraction;
import org.apache.commons.math.fraction.FractionConversionException;
class Matrix {
LinkedList<LinkedList<Fraction>> matrix;
int numRows;
int numCols;
static class Coordinate {
int row;
int col;
Coordinate(int r, int c) {
row = r;
col = c;
}
public String toString() {
return "(" + row + ", " + col + ")";
}
}
Matrix(double [][] m) {
numRows = m.length;
numCols = m[0].length;
matrix = new LinkedList<LinkedList<Fraction>>();
for (int i = 0; i < numRows; i++) {
matrix.add(new LinkedList<Fraction>());
for (int j = 0; j < numCols; j++) {
try {
matrix.get(i).add(new Fraction(m[i][j]));
} catch (FractionConversionException e) {
System.err.println("Fraction could not be converted from double by apache commons . . .");
}
}
}
}
public void Interchange(Coordinate a, Coordinate b) {
LinkedList<Fraction> temp = matrix.get(a.row);
matrix.set(a.row, matrix.get(b.row));
matrix.set(b.row, temp);
int t = a.row;
a.row = b.row;
b.row = t;
}
public void Scale(Coordinate x, Fraction d) {
LinkedList<Fraction> row = matrix.get(x.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).multiply(d));
}
}
public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) {
LinkedList<Fraction> row = matrix.get(to.row);
LinkedList<Fraction> rowMultiplied = matrix.get(from.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar))));
}
}
public void RREF() {
Coordinate pivot = new Coordinate(0,0);
int submatrix = 0;
for (int x = 0; x < numCols; x++) {
pivot = new Coordinate(pivot.row, x);
for (int i = x; i < numCols; i++) {
if (isColumnZeroes(pivot) == false) {
break;
} else {
pivot.col = i;
}
}
pivot = findPivot(pivot);
if (getCoordinate(pivot).doubleValue() == 0.0) {
pivot.row++;
continue;
}
if (pivot.row != submatrix) {
Interchange(new Coordinate(submatrix, pivot.col), pivot);
}
if (getCoordinate(pivot).doubleValue() != 1) {
Fraction scalar = getCoordinate(pivot).reciprocal();
Scale(pivot, scalar);
}
for (int i = pivot.row; i < numRows; i++) {
if (i == pivot.row) {
continue;
}
Coordinate belowPivot = new Coordinate(i, pivot.col);
Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot)));
MultiplyAndAdd(belowPivot, pivot, complement);
}
for (int i = pivot.row; i >= 0; i--) {
if (i == pivot.row) {
if (getCoordinate(pivot).doubleValue() != 1.0) {
Scale(pivot, getCoordinate(pivot).reciprocal());
}
continue;
}
if (i == pivot.row) {
continue;
}
Coordinate abovePivot = new Coordinate(i, pivot.col);
Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot)));
MultiplyAndAdd(abovePivot, pivot, complement);
}
if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) {
break;
}
submatrix++;
pivot.row++;
}
}
public boolean isColumnZeroes(Coordinate a) {
for (int i = 0; i < numRows; i++) {
if (matrix.get(i).get(a.col).doubleValue() != 0.0) {
return false;
}
}
return true;
}
public boolean isRowZeroes(Coordinate a) {
for (int i = 0; i < numCols; i++) {
if (matrix.get(a.row).get(i).doubleValue() != 0.0) {
return false;
}
}
return true;
}
public Coordinate findPivot(Coordinate a) {
int first_row = a.row;
Coordinate pivot = new Coordinate(a.row, a.col);
Coordinate current = new Coordinate(a.row, a.col);
for (int i = a.row; i < (numRows - first_row); i++) {
current.row = i;
if (getCoordinate(current).doubleValue() == 1.0) {
Interchange(current, a);
}
}
current.row = a.row;
for (int i = current.row; i < (numRows - first_row); i++) {
current.row = i;
if (getCoordinate(current).doubleValue() != 0) {
pivot.row = i;
break;
}
}
return pivot;
}
public Fraction getCoordinate(Coordinate a) {
return matrix.get(a.row).get(a.col);
}
public String toString() {
return matrix.toString().replace("], ", "]\n");
}
public static void main (String[] args) {
double[][] matrix_1 = {
{1, 2, -1, -4},
{2, 3, -1, -11},
{-2, 0, -3, 22}
};
Matrix x = new Matrix(matrix_1);
System.out.println("before\n" + x.toString() + "\n");
x.RREF();
System.out.println("after\n" + x.toString() + "\n");
double matrix_2 [][] = {
{2, 0, -1, 0, 0},
{1, 0, 0, -1, 0},
{3, 0, 0, -2, -1},
{0, 1, 0, 0, -2},
{0, 1, -1, 0, 0}
};
Matrix y = new Matrix(matrix_2);
System.out.println("before\n" + y.toString() + "\n");
y.RREF();
System.out.println("after\n" + y.toString() + "\n");
double matrix_3 [][] = {
{1, 2, 3, 4, 3, 1},
{2, 4, 6, 2, 6, 2},
{3, 6, 18, 9, 9, -6},
{4, 8, 12, 10, 12, 4},
{5, 10, 24, 11, 15, -4}
};
Matrix z = new Matrix(matrix_3);
System.out.println("before\n" + z.toString() + "\n");
z.RREF();
System.out.println("after\n" + z.toString() + "\n");
double matrix_4 [][] = {
{0, 1},
{1, 2},
{0,5}
};
Matrix a = new Matrix(matrix_4);
System.out.println("before\n" + a.toString() + "\n");
a.RREF();
System.out.println("after\n" + a.toString() + "\n");
}
}
|
Write the same code in Python as shown below in BBC_Basic. | DIM matrix(2,3)
matrix() = 1, 2, -1, -4, \
\ 2, 3, -1, -11, \
\ -2, 0, -3, 22
PROCrref(matrix())
FOR row% = 0 TO 2
FOR col% = 0 TO 3
PRINT matrix(row%,col%);
NEXT
PRINT
NEXT row%
END
DEF PROCrref(m())
LOCAL lead%, nrows%, ncols%, i%, j%, r%, n
nrows% = DIM(m(),1)+1
ncols% = DIM(m(),2)+1
FOR r% = 0 TO nrows%-1
IF lead% >= ncols% EXIT FOR
i% = r%
WHILE m(i%,lead%) = 0
i% += 1
IF i% = nrows% THEN
i% = r%
lead% += 1
IF lead% = ncols% EXIT FOR
ENDIF
ENDWHILE
FOR j% = 0 TO ncols%-1 : SWAP m(i%,j%),m(r%,j%) : NEXT
n = m(r%,lead%)
IF n <> 0 FOR j% = 0 TO ncols%-1 : m(r%,j%) /= n : NEXT
FOR i% = 0 TO nrows%-1
IF i% <> r% THEN
n = m(i%,lead%)
FOR j% = 0 TO ncols%-1
m(i%,j%) -= m(r%,j%) * n
NEXT
ENDIF
NEXT
lead% += 1
NEXT r%
ENDPROC
| def ToReducedRowEchelonForm( M):
if not M: return
lead = 0
rowCount = len(M)
columnCount = len(M[0])
for r in range(rowCount):
if lead >= columnCount:
return
i = r
while M[i][lead] == 0:
i += 1
if i == rowCount:
i = r
lead += 1
if columnCount == lead:
return
M[i],M[r] = M[r],M[i]
lv = M[r][lead]
M[r] = [ mrx / float(lv) for mrx in M[r]]
for i in range(rowCount):
if i != r:
lv = M[i][lead]
M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]
lead += 1
mtx = [
[ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[-2, 0, -3, 22],]
ToReducedRowEchelonForm( mtx )
for rw in mtx:
print ', '.join( (str(rv) for rv in rw) )
|
Change the programming language of this snippet from BBC_Basic to VB without modifying what it does. | DIM matrix(2,3)
matrix() = 1, 2, -1, -4, \
\ 2, 3, -1, -11, \
\ -2, 0, -3, 22
PROCrref(matrix())
FOR row% = 0 TO 2
FOR col% = 0 TO 3
PRINT matrix(row%,col%);
NEXT
PRINT
NEXT row%
END
DEF PROCrref(m())
LOCAL lead%, nrows%, ncols%, i%, j%, r%, n
nrows% = DIM(m(),1)+1
ncols% = DIM(m(),2)+1
FOR r% = 0 TO nrows%-1
IF lead% >= ncols% EXIT FOR
i% = r%
WHILE m(i%,lead%) = 0
i% += 1
IF i% = nrows% THEN
i% = r%
lead% += 1
IF lead% = ncols% EXIT FOR
ENDIF
ENDWHILE
FOR j% = 0 TO ncols%-1 : SWAP m(i%,j%),m(r%,j%) : NEXT
n = m(r%,lead%)
IF n <> 0 FOR j% = 0 TO ncols%-1 : m(r%,j%) /= n : NEXT
FOR i% = 0 TO nrows%-1
IF i% <> r% THEN
n = m(i%,lead%)
FOR j% = 0 TO ncols%-1
m(i%,j%) -= m(r%,j%) * n
NEXT
ENDIF
NEXT
lead% += 1
NEXT r%
ENDPROC
| Private Function ToReducedRowEchelonForm(M As Variant) As Variant
Dim lead As Integer: lead = 0
Dim rowCount As Integer: rowCount = UBound(M)
Dim columnCount As Integer: columnCount = UBound(M(0))
Dim i As Integer
For r = 0 To rowCount
If lead >= columnCount Then
Exit For
End If
i = r
Do While M(i)(lead) = 0
i = i + 1
If i = rowCount Then
i = r
lead = lead + 1
If lead = columnCount Then
Exit For
End If
End If
Loop
Dim tmp As Variant
tmp = M(r)
M(r) = M(i)
M(i) = tmp
If M(r)(lead) <> 0 Then
div = M(r)(lead)
For t = LBound(M(r)) To UBound(M(r))
M(r)(t) = M(r)(t) / div
Next t
End If
For j = 0 To rowCount
If j <> r Then
subt = M(j)(lead)
For t = LBound(M(j)) To UBound(M(j))
M(j)(t) = M(j)(t) - subt * M(r)(t)
Next t
End If
Next j
lead = lead + 1
Next r
ToReducedRowEchelonForm = M
End Function
Public Sub main()
r = ToReducedRowEchelonForm(Array( _
Array(1, 2, -1, -4), _
Array(2, 3, -1, -11), _
Array(-2, 0, -3, 22)))
For i = LBound(r) To UBound(r)
Debug.Print Join(r(i), vbTab)
Next i
End Sub
|
Convert the following code from BBC_Basic to Go, ensuring the logic remains intact. | DIM matrix(2,3)
matrix() = 1, 2, -1, -4, \
\ 2, 3, -1, -11, \
\ -2, 0, -3, 22
PROCrref(matrix())
FOR row% = 0 TO 2
FOR col% = 0 TO 3
PRINT matrix(row%,col%);
NEXT
PRINT
NEXT row%
END
DEF PROCrref(m())
LOCAL lead%, nrows%, ncols%, i%, j%, r%, n
nrows% = DIM(m(),1)+1
ncols% = DIM(m(),2)+1
FOR r% = 0 TO nrows%-1
IF lead% >= ncols% EXIT FOR
i% = r%
WHILE m(i%,lead%) = 0
i% += 1
IF i% = nrows% THEN
i% = r%
lead% += 1
IF lead% = ncols% EXIT FOR
ENDIF
ENDWHILE
FOR j% = 0 TO ncols%-1 : SWAP m(i%,j%),m(r%,j%) : NEXT
n = m(r%,lead%)
IF n <> 0 FOR j% = 0 TO ncols%-1 : m(r%,j%) /= n : NEXT
FOR i% = 0 TO nrows%-1
IF i% <> r% THEN
n = m(i%,lead%)
FOR j% = 0 TO ncols%-1
m(i%,j%) -= m(r%,j%) * n
NEXT
ENDIF
NEXT
lead% += 1
NEXT r%
ENDPROC
| package main
import "fmt"
type matrix [][]float64
func (m matrix) print() {
for _, r := range m {
fmt.Println(r)
}
fmt.Println("")
}
func main() {
m := matrix{
{ 1, 2, -1, -4},
{ 2, 3, -1, -11},
{-2, 0, -3, 22},
}
m.print()
rref(m)
m.print()
}
func rref(m matrix) {
lead := 0
rowCount := len(m)
columnCount := len(m[0])
for r := 0; r < rowCount; r++ {
if lead >= columnCount {
return
}
i := r
for m[i][lead] == 0 {
i++
if rowCount == i {
i = r
lead++
if columnCount == lead {
return
}
}
}
m[i], m[r] = m[r], m[i]
f := 1 / m[r][lead]
for j, _ := range m[r] {
m[r][j] *= f
}
for i = 0; i < rowCount; i++ {
if i != r {
f = m[i][lead]
for j, e := range m[r] {
m[i][j] -= e * f
}
}
}
lead++
}
}
|
Translate the given Common_Lisp code snippet into C without altering its behavior. | (defun convert-to-row-echelon-form (matrix)
(let* ((dimensions (array-dimensions matrix))
(row-count (first dimensions))
(column-count (second dimensions))
(lead 0))
(labels ((find-pivot (start lead)
(let ((i start))
(loop
:while (zerop (aref matrix i lead))
:do (progn
(incf i)
(when (= i row-count)
(setf i start)
(incf lead)
(when (= lead column-count)
(return-from convert-to-row-echelon-form matrix))))
:finally (return (values i lead)))))
(swap-rows (r1 r2)
(loop
:for c :upfrom 0 :below column-count
:do (rotatef (aref matrix r1 c) (aref matrix r2 c))))
(divide-row (r value)
(loop
:for c :upfrom 0 :below column-count
:do (setf (aref matrix r c)
(/ (aref matrix r c) value)))))
(loop
:for r :upfrom 0 :below row-count
:when (<= column-count lead)
:do (return matrix)
:do (multiple-value-bind (i nlead) (find-pivot r lead)
(setf lead nlead)
(swap-rows i r)
(divide-row r (aref matrix r lead))
(loop
:for i :upfrom 0 :below row-count
:when (/= i r)
:do (let ((scale (aref matrix i lead)))
(loop
:for c :upfrom 0 :below column-count
:do (decf (aref matrix i c)
(* scale (aref matrix r c))))))
(incf lead))
:finally (return matrix)))))
| #include <stdio.h>
#define TALLOC(n,typ) malloc(n*sizeof(typ))
#define EL_Type int
typedef struct sMtx {
int dim_x, dim_y;
EL_Type *m_stor;
EL_Type **mtx;
} *Matrix, sMatrix;
typedef struct sRvec {
int dim_x;
EL_Type *m_stor;
} *RowVec, sRowVec;
Matrix NewMatrix( int x_dim, int y_dim )
{
int n;
Matrix m;
m = TALLOC( 1, sMatrix);
n = x_dim * y_dim;
m->dim_x = x_dim;
m->dim_y = y_dim;
m->m_stor = TALLOC(n, EL_Type);
m->mtx = TALLOC(m->dim_y, EL_Type *);
for(n=0; n<y_dim; n++) {
m->mtx[n] = m->m_stor+n*x_dim;
}
return m;
}
void MtxSetRow(Matrix m, int irow, EL_Type *v)
{
int ix;
EL_Type *mr;
mr = m->mtx[irow];
for(ix=0; ix<m->dim_x; ix++)
mr[ix] = v[ix];
}
Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v)
{
Matrix m;
int iy;
m = NewMatrix(x_dim, y_dim);
for (iy=0; iy<y_dim; iy++)
MtxSetRow(m, iy, v[iy]);
return m;
}
void MtxDisplay( Matrix m )
{
int iy, ix;
const char *sc;
for (iy=0; iy<m->dim_y; iy++) {
printf(" ");
sc = " ";
for (ix=0; ix<m->dim_x; ix++) {
printf("%s %3d", sc, m->mtx[iy][ix]);
sc = ",";
}
printf("\n");
}
printf("\n");
}
void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr)
{
int ix;
EL_Type *drow, *srow;
drow = m->mtx[ixrdest];
srow = m->mtx[ixrsrc];
for (ix=0; ix<m->dim_x; ix++)
drow[ix] += mplr * srow[ix];
}
void MtxSwapRows( Matrix m, int rix1, int rix2)
{
EL_Type *r1, *r2, temp;
int ix;
if (rix1 == rix2) return;
r1 = m->mtx[rix1];
r2 = m->mtx[rix2];
for (ix=0; ix<m->dim_x; ix++)
temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp;
}
void MtxNormalizeRow( Matrix m, int rix, int lead)
{
int ix;
EL_Type *drow;
EL_Type lv;
drow = m->mtx[rix];
lv = drow[lead];
for (ix=0; ix<m->dim_x; ix++)
drow[ix] /= lv;
}
#define MtxGet( m, rix, cix ) m->mtx[rix][cix]
void MtxToReducedREForm(Matrix m)
{
int lead;
int rix, iix;
EL_Type lv;
int rowCount = m->dim_y;
lead = 0;
for (rix=0; rix<rowCount; rix++) {
if (lead >= m->dim_x)
return;
iix = rix;
while (0 == MtxGet(m, iix,lead)) {
iix++;
if (iix == rowCount) {
iix = rix;
lead++;
if (lead == m->dim_x)
return;
}
}
MtxSwapRows(m, iix, rix );
MtxNormalizeRow(m, rix, lead );
for (iix=0; iix<rowCount; iix++) {
if ( iix != rix ) {
lv = MtxGet(m, iix, lead );
MtxMulAndAddRows(m,iix, rix, -lv) ;
}
}
lead++;
}
}
int main()
{
Matrix m1;
static EL_Type r1[] = {1,2,-1,-4};
static EL_Type r2[] = {2,3,-1,-11};
static EL_Type r3[] = {-2,0,-3,22};
static EL_Type *im[] = { r1, r2, r3 };
m1 = InitMatrix( 4,3, im );
printf("Initial\n");
MtxDisplay(m1);
MtxToReducedREForm(m1);
printf("Reduced R-E form\n");
MtxDisplay(m1);
return 0;
}
|
Ensure the translated C# code behaves exactly like the original Common_Lisp snippet. | (defun convert-to-row-echelon-form (matrix)
(let* ((dimensions (array-dimensions matrix))
(row-count (first dimensions))
(column-count (second dimensions))
(lead 0))
(labels ((find-pivot (start lead)
(let ((i start))
(loop
:while (zerop (aref matrix i lead))
:do (progn
(incf i)
(when (= i row-count)
(setf i start)
(incf lead)
(when (= lead column-count)
(return-from convert-to-row-echelon-form matrix))))
:finally (return (values i lead)))))
(swap-rows (r1 r2)
(loop
:for c :upfrom 0 :below column-count
:do (rotatef (aref matrix r1 c) (aref matrix r2 c))))
(divide-row (r value)
(loop
:for c :upfrom 0 :below column-count
:do (setf (aref matrix r c)
(/ (aref matrix r c) value)))))
(loop
:for r :upfrom 0 :below row-count
:when (<= column-count lead)
:do (return matrix)
:do (multiple-value-bind (i nlead) (find-pivot r lead)
(setf lead nlead)
(swap-rows i r)
(divide-row r (aref matrix r lead))
(loop
:for i :upfrom 0 :below row-count
:when (/= i r)
:do (let ((scale (aref matrix i lead)))
(loop
:for c :upfrom 0 :below column-count
:do (decf (aref matrix i c)
(* scale (aref matrix r c))))))
(incf lead))
:finally (return matrix)))))
| using System;
namespace rref
{
class Program
{
static void Main(string[] args)
{
int[,] matrix = new int[3, 4]{
{ 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 }
};
matrix = rref(matrix);
}
private static int[,] rref(int[,] matrix)
{
int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1);
for (int r = 0; r < rowCount; r++)
{
if (columnCount <= lead) break;
int i = r;
while (matrix[i, lead] == 0)
{
i++;
if (i == rowCount)
{
i = r;
lead++;
if (columnCount == lead)
{
lead--;
break;
}
}
}
for (int j = 0; j < columnCount; j++)
{
int temp = matrix[r, j];
matrix[r, j] = matrix[i, j];
matrix[i, j] = temp;
}
int div = matrix[r, lead];
if(div != 0)
for (int j = 0; j < columnCount; j++) matrix[r, j] /= div;
for (int j = 0; j < rowCount; j++)
{
if (j != r)
{
int sub = matrix[j, lead];
for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]);
}
}
lead++;
}
return matrix;
}
}
}
|
Write a version of this Common_Lisp function in C++ with identical behavior. | (defun convert-to-row-echelon-form (matrix)
(let* ((dimensions (array-dimensions matrix))
(row-count (first dimensions))
(column-count (second dimensions))
(lead 0))
(labels ((find-pivot (start lead)
(let ((i start))
(loop
:while (zerop (aref matrix i lead))
:do (progn
(incf i)
(when (= i row-count)
(setf i start)
(incf lead)
(when (= lead column-count)
(return-from convert-to-row-echelon-form matrix))))
:finally (return (values i lead)))))
(swap-rows (r1 r2)
(loop
:for c :upfrom 0 :below column-count
:do (rotatef (aref matrix r1 c) (aref matrix r2 c))))
(divide-row (r value)
(loop
:for c :upfrom 0 :below column-count
:do (setf (aref matrix r c)
(/ (aref matrix r c) value)))))
(loop
:for r :upfrom 0 :below row-count
:when (<= column-count lead)
:do (return matrix)
:do (multiple-value-bind (i nlead) (find-pivot r lead)
(setf lead nlead)
(swap-rows i r)
(divide-row r (aref matrix r lead))
(loop
:for i :upfrom 0 :below row-count
:when (/= i r)
:do (let ((scale (aref matrix i lead)))
(loop
:for c :upfrom 0 :below column-count
:do (decf (aref matrix i c)
(* scale (aref matrix r c))))))
(incf lead))
:finally (return matrix)))))
| #include <algorithm>
#include <cstddef>
#include <cassert>
template<typename MatrixType> struct matrix_traits
{
typedef typename MatrixType::index_type index_type;
typedef typename MatrixType::value_type value_type;
static index_type min_row(MatrixType const& A)
{ return A.min_row(); }
static index_type max_row(MatrixType const& A)
{ return A.max_row(); }
static index_type min_column(MatrixType const& A)
{ return A.min_column(); }
static index_type max_column(MatrixType const& A)
{ return A.max_column(); }
static value_type& element(MatrixType& A, index_type i, index_type k)
{ return A(i,k); }
static value_type element(MatrixType const& A, index_type i, index_type k)
{ return A(i,k); }
};
template<typename T, std::size_t rows, std::size_t columns>
struct matrix_traits<T[rows][columns]>
{
typedef std::size_t index_type;
typedef T value_type;
static index_type min_row(T const (&)[rows][columns])
{ return 0; }
static index_type max_row(T const (&)[rows][columns])
{ return rows-1; }
static index_type min_column(T const (&)[rows][columns])
{ return 0; }
static index_type max_column(T const (&)[rows][columns])
{ return columns-1; }
static value_type& element(T (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
static value_type element(T const (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
};
template<typename MatrixType>
void swap_rows(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
std::swap(mt.element(A, i, col), mt.element(A, k, col));
}
template<typename MatrixType>
void divide_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(v != 0);
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) /= v;
}
template<typename MatrixType>
void add_multiple_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) += v * mt.element(A, k, col);
}
template<typename MatrixType>
void to_reduced_row_echelon_form(MatrixType& A)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
index_type lead = mt.min_row(A);
for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row)
{
if (lead > mt.max_column(A))
return;
index_type i = row;
while (mt.element(A, i, lead) == 0)
{
++i;
if (i > mt.max_row(A))
{
i = row;
++lead;
if (lead > mt.max_column(A))
return;
}
}
swap_rows(A, i, row);
divide_row(A, row, mt.element(A, row, lead));
for (i = mt.min_row(A); i <= mt.max_row(A); ++i)
{
if (i != row)
add_multiple_row(A, i, row, -mt.element(A, i, lead));
}
}
}
#include <iostream>
int main()
{
double M[3][4] = { { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } };
to_reduced_row_echelon_form(M);
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
std::cout << M[i][j] << '\t';
std::cout << "\n";
}
return EXIT_SUCCESS;
}
|
Generate a Java translation of this Common_Lisp snippet without changing its computational steps. | (defun convert-to-row-echelon-form (matrix)
(let* ((dimensions (array-dimensions matrix))
(row-count (first dimensions))
(column-count (second dimensions))
(lead 0))
(labels ((find-pivot (start lead)
(let ((i start))
(loop
:while (zerop (aref matrix i lead))
:do (progn
(incf i)
(when (= i row-count)
(setf i start)
(incf lead)
(when (= lead column-count)
(return-from convert-to-row-echelon-form matrix))))
:finally (return (values i lead)))))
(swap-rows (r1 r2)
(loop
:for c :upfrom 0 :below column-count
:do (rotatef (aref matrix r1 c) (aref matrix r2 c))))
(divide-row (r value)
(loop
:for c :upfrom 0 :below column-count
:do (setf (aref matrix r c)
(/ (aref matrix r c) value)))))
(loop
:for r :upfrom 0 :below row-count
:when (<= column-count lead)
:do (return matrix)
:do (multiple-value-bind (i nlead) (find-pivot r lead)
(setf lead nlead)
(swap-rows i r)
(divide-row r (aref matrix r lead))
(loop
:for i :upfrom 0 :below row-count
:when (/= i r)
:do (let ((scale (aref matrix i lead)))
(loop
:for c :upfrom 0 :below column-count
:do (decf (aref matrix i c)
(* scale (aref matrix r c))))))
(incf lead))
:finally (return matrix)))))
| import java.util.*;
import java.lang.Math;
import org.apache.commons.math.fraction.Fraction;
import org.apache.commons.math.fraction.FractionConversionException;
class Matrix {
LinkedList<LinkedList<Fraction>> matrix;
int numRows;
int numCols;
static class Coordinate {
int row;
int col;
Coordinate(int r, int c) {
row = r;
col = c;
}
public String toString() {
return "(" + row + ", " + col + ")";
}
}
Matrix(double [][] m) {
numRows = m.length;
numCols = m[0].length;
matrix = new LinkedList<LinkedList<Fraction>>();
for (int i = 0; i < numRows; i++) {
matrix.add(new LinkedList<Fraction>());
for (int j = 0; j < numCols; j++) {
try {
matrix.get(i).add(new Fraction(m[i][j]));
} catch (FractionConversionException e) {
System.err.println("Fraction could not be converted from double by apache commons . . .");
}
}
}
}
public void Interchange(Coordinate a, Coordinate b) {
LinkedList<Fraction> temp = matrix.get(a.row);
matrix.set(a.row, matrix.get(b.row));
matrix.set(b.row, temp);
int t = a.row;
a.row = b.row;
b.row = t;
}
public void Scale(Coordinate x, Fraction d) {
LinkedList<Fraction> row = matrix.get(x.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).multiply(d));
}
}
public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) {
LinkedList<Fraction> row = matrix.get(to.row);
LinkedList<Fraction> rowMultiplied = matrix.get(from.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar))));
}
}
public void RREF() {
Coordinate pivot = new Coordinate(0,0);
int submatrix = 0;
for (int x = 0; x < numCols; x++) {
pivot = new Coordinate(pivot.row, x);
for (int i = x; i < numCols; i++) {
if (isColumnZeroes(pivot) == false) {
break;
} else {
pivot.col = i;
}
}
pivot = findPivot(pivot);
if (getCoordinate(pivot).doubleValue() == 0.0) {
pivot.row++;
continue;
}
if (pivot.row != submatrix) {
Interchange(new Coordinate(submatrix, pivot.col), pivot);
}
if (getCoordinate(pivot).doubleValue() != 1) {
Fraction scalar = getCoordinate(pivot).reciprocal();
Scale(pivot, scalar);
}
for (int i = pivot.row; i < numRows; i++) {
if (i == pivot.row) {
continue;
}
Coordinate belowPivot = new Coordinate(i, pivot.col);
Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot)));
MultiplyAndAdd(belowPivot, pivot, complement);
}
for (int i = pivot.row; i >= 0; i--) {
if (i == pivot.row) {
if (getCoordinate(pivot).doubleValue() != 1.0) {
Scale(pivot, getCoordinate(pivot).reciprocal());
}
continue;
}
if (i == pivot.row) {
continue;
}
Coordinate abovePivot = new Coordinate(i, pivot.col);
Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot)));
MultiplyAndAdd(abovePivot, pivot, complement);
}
if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) {
break;
}
submatrix++;
pivot.row++;
}
}
public boolean isColumnZeroes(Coordinate a) {
for (int i = 0; i < numRows; i++) {
if (matrix.get(i).get(a.col).doubleValue() != 0.0) {
return false;
}
}
return true;
}
public boolean isRowZeroes(Coordinate a) {
for (int i = 0; i < numCols; i++) {
if (matrix.get(a.row).get(i).doubleValue() != 0.0) {
return false;
}
}
return true;
}
public Coordinate findPivot(Coordinate a) {
int first_row = a.row;
Coordinate pivot = new Coordinate(a.row, a.col);
Coordinate current = new Coordinate(a.row, a.col);
for (int i = a.row; i < (numRows - first_row); i++) {
current.row = i;
if (getCoordinate(current).doubleValue() == 1.0) {
Interchange(current, a);
}
}
current.row = a.row;
for (int i = current.row; i < (numRows - first_row); i++) {
current.row = i;
if (getCoordinate(current).doubleValue() != 0) {
pivot.row = i;
break;
}
}
return pivot;
}
public Fraction getCoordinate(Coordinate a) {
return matrix.get(a.row).get(a.col);
}
public String toString() {
return matrix.toString().replace("], ", "]\n");
}
public static void main (String[] args) {
double[][] matrix_1 = {
{1, 2, -1, -4},
{2, 3, -1, -11},
{-2, 0, -3, 22}
};
Matrix x = new Matrix(matrix_1);
System.out.println("before\n" + x.toString() + "\n");
x.RREF();
System.out.println("after\n" + x.toString() + "\n");
double matrix_2 [][] = {
{2, 0, -1, 0, 0},
{1, 0, 0, -1, 0},
{3, 0, 0, -2, -1},
{0, 1, 0, 0, -2},
{0, 1, -1, 0, 0}
};
Matrix y = new Matrix(matrix_2);
System.out.println("before\n" + y.toString() + "\n");
y.RREF();
System.out.println("after\n" + y.toString() + "\n");
double matrix_3 [][] = {
{1, 2, 3, 4, 3, 1},
{2, 4, 6, 2, 6, 2},
{3, 6, 18, 9, 9, -6},
{4, 8, 12, 10, 12, 4},
{5, 10, 24, 11, 15, -4}
};
Matrix z = new Matrix(matrix_3);
System.out.println("before\n" + z.toString() + "\n");
z.RREF();
System.out.println("after\n" + z.toString() + "\n");
double matrix_4 [][] = {
{0, 1},
{1, 2},
{0,5}
};
Matrix a = new Matrix(matrix_4);
System.out.println("before\n" + a.toString() + "\n");
a.RREF();
System.out.println("after\n" + a.toString() + "\n");
}
}
|
Write the same code in Python as shown below in Common_Lisp. | (defun convert-to-row-echelon-form (matrix)
(let* ((dimensions (array-dimensions matrix))
(row-count (first dimensions))
(column-count (second dimensions))
(lead 0))
(labels ((find-pivot (start lead)
(let ((i start))
(loop
:while (zerop (aref matrix i lead))
:do (progn
(incf i)
(when (= i row-count)
(setf i start)
(incf lead)
(when (= lead column-count)
(return-from convert-to-row-echelon-form matrix))))
:finally (return (values i lead)))))
(swap-rows (r1 r2)
(loop
:for c :upfrom 0 :below column-count
:do (rotatef (aref matrix r1 c) (aref matrix r2 c))))
(divide-row (r value)
(loop
:for c :upfrom 0 :below column-count
:do (setf (aref matrix r c)
(/ (aref matrix r c) value)))))
(loop
:for r :upfrom 0 :below row-count
:when (<= column-count lead)
:do (return matrix)
:do (multiple-value-bind (i nlead) (find-pivot r lead)
(setf lead nlead)
(swap-rows i r)
(divide-row r (aref matrix r lead))
(loop
:for i :upfrom 0 :below row-count
:when (/= i r)
:do (let ((scale (aref matrix i lead)))
(loop
:for c :upfrom 0 :below column-count
:do (decf (aref matrix i c)
(* scale (aref matrix r c))))))
(incf lead))
:finally (return matrix)))))
| def ToReducedRowEchelonForm( M):
if not M: return
lead = 0
rowCount = len(M)
columnCount = len(M[0])
for r in range(rowCount):
if lead >= columnCount:
return
i = r
while M[i][lead] == 0:
i += 1
if i == rowCount:
i = r
lead += 1
if columnCount == lead:
return
M[i],M[r] = M[r],M[i]
lv = M[r][lead]
M[r] = [ mrx / float(lv) for mrx in M[r]]
for i in range(rowCount):
if i != r:
lv = M[i][lead]
M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]
lead += 1
mtx = [
[ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[-2, 0, -3, 22],]
ToReducedRowEchelonForm( mtx )
for rw in mtx:
print ', '.join( (str(rv) for rv in rw) )
|
Please provide an equivalent version of this Common_Lisp code in VB. | (defun convert-to-row-echelon-form (matrix)
(let* ((dimensions (array-dimensions matrix))
(row-count (first dimensions))
(column-count (second dimensions))
(lead 0))
(labels ((find-pivot (start lead)
(let ((i start))
(loop
:while (zerop (aref matrix i lead))
:do (progn
(incf i)
(when (= i row-count)
(setf i start)
(incf lead)
(when (= lead column-count)
(return-from convert-to-row-echelon-form matrix))))
:finally (return (values i lead)))))
(swap-rows (r1 r2)
(loop
:for c :upfrom 0 :below column-count
:do (rotatef (aref matrix r1 c) (aref matrix r2 c))))
(divide-row (r value)
(loop
:for c :upfrom 0 :below column-count
:do (setf (aref matrix r c)
(/ (aref matrix r c) value)))))
(loop
:for r :upfrom 0 :below row-count
:when (<= column-count lead)
:do (return matrix)
:do (multiple-value-bind (i nlead) (find-pivot r lead)
(setf lead nlead)
(swap-rows i r)
(divide-row r (aref matrix r lead))
(loop
:for i :upfrom 0 :below row-count
:when (/= i r)
:do (let ((scale (aref matrix i lead)))
(loop
:for c :upfrom 0 :below column-count
:do (decf (aref matrix i c)
(* scale (aref matrix r c))))))
(incf lead))
:finally (return matrix)))))
| Private Function ToReducedRowEchelonForm(M As Variant) As Variant
Dim lead As Integer: lead = 0
Dim rowCount As Integer: rowCount = UBound(M)
Dim columnCount As Integer: columnCount = UBound(M(0))
Dim i As Integer
For r = 0 To rowCount
If lead >= columnCount Then
Exit For
End If
i = r
Do While M(i)(lead) = 0
i = i + 1
If i = rowCount Then
i = r
lead = lead + 1
If lead = columnCount Then
Exit For
End If
End If
Loop
Dim tmp As Variant
tmp = M(r)
M(r) = M(i)
M(i) = tmp
If M(r)(lead) <> 0 Then
div = M(r)(lead)
For t = LBound(M(r)) To UBound(M(r))
M(r)(t) = M(r)(t) / div
Next t
End If
For j = 0 To rowCount
If j <> r Then
subt = M(j)(lead)
For t = LBound(M(j)) To UBound(M(j))
M(j)(t) = M(j)(t) - subt * M(r)(t)
Next t
End If
Next j
lead = lead + 1
Next r
ToReducedRowEchelonForm = M
End Function
Public Sub main()
r = ToReducedRowEchelonForm(Array( _
Array(1, 2, -1, -4), _
Array(2, 3, -1, -11), _
Array(-2, 0, -3, 22)))
For i = LBound(r) To UBound(r)
Debug.Print Join(r(i), vbTab)
Next i
End Sub
|
Convert this Common_Lisp block to Go, preserving its control flow and logic. | (defun convert-to-row-echelon-form (matrix)
(let* ((dimensions (array-dimensions matrix))
(row-count (first dimensions))
(column-count (second dimensions))
(lead 0))
(labels ((find-pivot (start lead)
(let ((i start))
(loop
:while (zerop (aref matrix i lead))
:do (progn
(incf i)
(when (= i row-count)
(setf i start)
(incf lead)
(when (= lead column-count)
(return-from convert-to-row-echelon-form matrix))))
:finally (return (values i lead)))))
(swap-rows (r1 r2)
(loop
:for c :upfrom 0 :below column-count
:do (rotatef (aref matrix r1 c) (aref matrix r2 c))))
(divide-row (r value)
(loop
:for c :upfrom 0 :below column-count
:do (setf (aref matrix r c)
(/ (aref matrix r c) value)))))
(loop
:for r :upfrom 0 :below row-count
:when (<= column-count lead)
:do (return matrix)
:do (multiple-value-bind (i nlead) (find-pivot r lead)
(setf lead nlead)
(swap-rows i r)
(divide-row r (aref matrix r lead))
(loop
:for i :upfrom 0 :below row-count
:when (/= i r)
:do (let ((scale (aref matrix i lead)))
(loop
:for c :upfrom 0 :below column-count
:do (decf (aref matrix i c)
(* scale (aref matrix r c))))))
(incf lead))
:finally (return matrix)))))
| package main
import "fmt"
type matrix [][]float64
func (m matrix) print() {
for _, r := range m {
fmt.Println(r)
}
fmt.Println("")
}
func main() {
m := matrix{
{ 1, 2, -1, -4},
{ 2, 3, -1, -11},
{-2, 0, -3, 22},
}
m.print()
rref(m)
m.print()
}
func rref(m matrix) {
lead := 0
rowCount := len(m)
columnCount := len(m[0])
for r := 0; r < rowCount; r++ {
if lead >= columnCount {
return
}
i := r
for m[i][lead] == 0 {
i++
if rowCount == i {
i = r
lead++
if columnCount == lead {
return
}
}
}
m[i], m[r] = m[r], m[i]
f := 1 / m[r][lead]
for j, _ := range m[r] {
m[r][j] *= f
}
for i = 0; i < rowCount; i++ {
if i != r {
f = m[i][lead]
for j, e := range m[r] {
m[i][j] -= e * f
}
}
}
lead++
}
}
|
Rewrite the snippet below in C so it works the same as the original D code. | import std.stdio, std.algorithm, std.array, std.conv;
void toReducedRowEchelonForm(T)(T[][] M) pure nothrow @nogc {
if (M.empty)
return;
immutable nrows = M.length;
immutable ncols = M[0].length;
size_t lead;
foreach (immutable r; 0 .. nrows) {
if (ncols <= lead)
return;
{
size_t i = r;
while (M[i][lead] == 0) {
i++;
if (nrows == i) {
i = r;
lead++;
if (ncols == lead)
return;
}
}
swap(M[i], M[r]);
}
M[r][] /= M[r][lead];
foreach (j, ref mj; M)
if (j != r)
mj[] -= M[r][] * mj[lead];
lead++;
}
}
void main() {
auto A = [[ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[-2, 0, -3, 22]];
A.toReducedRowEchelonForm;
writefln("%(%(%2d %)\n%)", A);
}
| #include <stdio.h>
#define TALLOC(n,typ) malloc(n*sizeof(typ))
#define EL_Type int
typedef struct sMtx {
int dim_x, dim_y;
EL_Type *m_stor;
EL_Type **mtx;
} *Matrix, sMatrix;
typedef struct sRvec {
int dim_x;
EL_Type *m_stor;
} *RowVec, sRowVec;
Matrix NewMatrix( int x_dim, int y_dim )
{
int n;
Matrix m;
m = TALLOC( 1, sMatrix);
n = x_dim * y_dim;
m->dim_x = x_dim;
m->dim_y = y_dim;
m->m_stor = TALLOC(n, EL_Type);
m->mtx = TALLOC(m->dim_y, EL_Type *);
for(n=0; n<y_dim; n++) {
m->mtx[n] = m->m_stor+n*x_dim;
}
return m;
}
void MtxSetRow(Matrix m, int irow, EL_Type *v)
{
int ix;
EL_Type *mr;
mr = m->mtx[irow];
for(ix=0; ix<m->dim_x; ix++)
mr[ix] = v[ix];
}
Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v)
{
Matrix m;
int iy;
m = NewMatrix(x_dim, y_dim);
for (iy=0; iy<y_dim; iy++)
MtxSetRow(m, iy, v[iy]);
return m;
}
void MtxDisplay( Matrix m )
{
int iy, ix;
const char *sc;
for (iy=0; iy<m->dim_y; iy++) {
printf(" ");
sc = " ";
for (ix=0; ix<m->dim_x; ix++) {
printf("%s %3d", sc, m->mtx[iy][ix]);
sc = ",";
}
printf("\n");
}
printf("\n");
}
void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr)
{
int ix;
EL_Type *drow, *srow;
drow = m->mtx[ixrdest];
srow = m->mtx[ixrsrc];
for (ix=0; ix<m->dim_x; ix++)
drow[ix] += mplr * srow[ix];
}
void MtxSwapRows( Matrix m, int rix1, int rix2)
{
EL_Type *r1, *r2, temp;
int ix;
if (rix1 == rix2) return;
r1 = m->mtx[rix1];
r2 = m->mtx[rix2];
for (ix=0; ix<m->dim_x; ix++)
temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp;
}
void MtxNormalizeRow( Matrix m, int rix, int lead)
{
int ix;
EL_Type *drow;
EL_Type lv;
drow = m->mtx[rix];
lv = drow[lead];
for (ix=0; ix<m->dim_x; ix++)
drow[ix] /= lv;
}
#define MtxGet( m, rix, cix ) m->mtx[rix][cix]
void MtxToReducedREForm(Matrix m)
{
int lead;
int rix, iix;
EL_Type lv;
int rowCount = m->dim_y;
lead = 0;
for (rix=0; rix<rowCount; rix++) {
if (lead >= m->dim_x)
return;
iix = rix;
while (0 == MtxGet(m, iix,lead)) {
iix++;
if (iix == rowCount) {
iix = rix;
lead++;
if (lead == m->dim_x)
return;
}
}
MtxSwapRows(m, iix, rix );
MtxNormalizeRow(m, rix, lead );
for (iix=0; iix<rowCount; iix++) {
if ( iix != rix ) {
lv = MtxGet(m, iix, lead );
MtxMulAndAddRows(m,iix, rix, -lv) ;
}
}
lead++;
}
}
int main()
{
Matrix m1;
static EL_Type r1[] = {1,2,-1,-4};
static EL_Type r2[] = {2,3,-1,-11};
static EL_Type r3[] = {-2,0,-3,22};
static EL_Type *im[] = { r1, r2, r3 };
m1 = InitMatrix( 4,3, im );
printf("Initial\n");
MtxDisplay(m1);
MtxToReducedREForm(m1);
printf("Reduced R-E form\n");
MtxDisplay(m1);
return 0;
}
|
Change the programming language of this snippet from D to C# without modifying what it does. | import std.stdio, std.algorithm, std.array, std.conv;
void toReducedRowEchelonForm(T)(T[][] M) pure nothrow @nogc {
if (M.empty)
return;
immutable nrows = M.length;
immutable ncols = M[0].length;
size_t lead;
foreach (immutable r; 0 .. nrows) {
if (ncols <= lead)
return;
{
size_t i = r;
while (M[i][lead] == 0) {
i++;
if (nrows == i) {
i = r;
lead++;
if (ncols == lead)
return;
}
}
swap(M[i], M[r]);
}
M[r][] /= M[r][lead];
foreach (j, ref mj; M)
if (j != r)
mj[] -= M[r][] * mj[lead];
lead++;
}
}
void main() {
auto A = [[ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[-2, 0, -3, 22]];
A.toReducedRowEchelonForm;
writefln("%(%(%2d %)\n%)", A);
}
| using System;
namespace rref
{
class Program
{
static void Main(string[] args)
{
int[,] matrix = new int[3, 4]{
{ 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 }
};
matrix = rref(matrix);
}
private static int[,] rref(int[,] matrix)
{
int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1);
for (int r = 0; r < rowCount; r++)
{
if (columnCount <= lead) break;
int i = r;
while (matrix[i, lead] == 0)
{
i++;
if (i == rowCount)
{
i = r;
lead++;
if (columnCount == lead)
{
lead--;
break;
}
}
}
for (int j = 0; j < columnCount; j++)
{
int temp = matrix[r, j];
matrix[r, j] = matrix[i, j];
matrix[i, j] = temp;
}
int div = matrix[r, lead];
if(div != 0)
for (int j = 0; j < columnCount; j++) matrix[r, j] /= div;
for (int j = 0; j < rowCount; j++)
{
if (j != r)
{
int sub = matrix[j, lead];
for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]);
}
}
lead++;
}
return matrix;
}
}
}
|
Produce a functionally identical C++ code for the snippet given in D. | import std.stdio, std.algorithm, std.array, std.conv;
void toReducedRowEchelonForm(T)(T[][] M) pure nothrow @nogc {
if (M.empty)
return;
immutable nrows = M.length;
immutable ncols = M[0].length;
size_t lead;
foreach (immutable r; 0 .. nrows) {
if (ncols <= lead)
return;
{
size_t i = r;
while (M[i][lead] == 0) {
i++;
if (nrows == i) {
i = r;
lead++;
if (ncols == lead)
return;
}
}
swap(M[i], M[r]);
}
M[r][] /= M[r][lead];
foreach (j, ref mj; M)
if (j != r)
mj[] -= M[r][] * mj[lead];
lead++;
}
}
void main() {
auto A = [[ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[-2, 0, -3, 22]];
A.toReducedRowEchelonForm;
writefln("%(%(%2d %)\n%)", A);
}
| #include <algorithm>
#include <cstddef>
#include <cassert>
template<typename MatrixType> struct matrix_traits
{
typedef typename MatrixType::index_type index_type;
typedef typename MatrixType::value_type value_type;
static index_type min_row(MatrixType const& A)
{ return A.min_row(); }
static index_type max_row(MatrixType const& A)
{ return A.max_row(); }
static index_type min_column(MatrixType const& A)
{ return A.min_column(); }
static index_type max_column(MatrixType const& A)
{ return A.max_column(); }
static value_type& element(MatrixType& A, index_type i, index_type k)
{ return A(i,k); }
static value_type element(MatrixType const& A, index_type i, index_type k)
{ return A(i,k); }
};
template<typename T, std::size_t rows, std::size_t columns>
struct matrix_traits<T[rows][columns]>
{
typedef std::size_t index_type;
typedef T value_type;
static index_type min_row(T const (&)[rows][columns])
{ return 0; }
static index_type max_row(T const (&)[rows][columns])
{ return rows-1; }
static index_type min_column(T const (&)[rows][columns])
{ return 0; }
static index_type max_column(T const (&)[rows][columns])
{ return columns-1; }
static value_type& element(T (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
static value_type element(T const (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
};
template<typename MatrixType>
void swap_rows(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
std::swap(mt.element(A, i, col), mt.element(A, k, col));
}
template<typename MatrixType>
void divide_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(v != 0);
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) /= v;
}
template<typename MatrixType>
void add_multiple_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) += v * mt.element(A, k, col);
}
template<typename MatrixType>
void to_reduced_row_echelon_form(MatrixType& A)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
index_type lead = mt.min_row(A);
for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row)
{
if (lead > mt.max_column(A))
return;
index_type i = row;
while (mt.element(A, i, lead) == 0)
{
++i;
if (i > mt.max_row(A))
{
i = row;
++lead;
if (lead > mt.max_column(A))
return;
}
}
swap_rows(A, i, row);
divide_row(A, row, mt.element(A, row, lead));
for (i = mt.min_row(A); i <= mt.max_row(A); ++i)
{
if (i != row)
add_multiple_row(A, i, row, -mt.element(A, i, lead));
}
}
}
#include <iostream>
int main()
{
double M[3][4] = { { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } };
to_reduced_row_echelon_form(M);
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
std::cout << M[i][j] << '\t';
std::cout << "\n";
}
return EXIT_SUCCESS;
}
|
Produce a language-to-language conversion: from D to Java, same semantics. | import std.stdio, std.algorithm, std.array, std.conv;
void toReducedRowEchelonForm(T)(T[][] M) pure nothrow @nogc {
if (M.empty)
return;
immutable nrows = M.length;
immutable ncols = M[0].length;
size_t lead;
foreach (immutable r; 0 .. nrows) {
if (ncols <= lead)
return;
{
size_t i = r;
while (M[i][lead] == 0) {
i++;
if (nrows == i) {
i = r;
lead++;
if (ncols == lead)
return;
}
}
swap(M[i], M[r]);
}
M[r][] /= M[r][lead];
foreach (j, ref mj; M)
if (j != r)
mj[] -= M[r][] * mj[lead];
lead++;
}
}
void main() {
auto A = [[ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[-2, 0, -3, 22]];
A.toReducedRowEchelonForm;
writefln("%(%(%2d %)\n%)", A);
}
| import java.util.*;
import java.lang.Math;
import org.apache.commons.math.fraction.Fraction;
import org.apache.commons.math.fraction.FractionConversionException;
class Matrix {
LinkedList<LinkedList<Fraction>> matrix;
int numRows;
int numCols;
static class Coordinate {
int row;
int col;
Coordinate(int r, int c) {
row = r;
col = c;
}
public String toString() {
return "(" + row + ", " + col + ")";
}
}
Matrix(double [][] m) {
numRows = m.length;
numCols = m[0].length;
matrix = new LinkedList<LinkedList<Fraction>>();
for (int i = 0; i < numRows; i++) {
matrix.add(new LinkedList<Fraction>());
for (int j = 0; j < numCols; j++) {
try {
matrix.get(i).add(new Fraction(m[i][j]));
} catch (FractionConversionException e) {
System.err.println("Fraction could not be converted from double by apache commons . . .");
}
}
}
}
public void Interchange(Coordinate a, Coordinate b) {
LinkedList<Fraction> temp = matrix.get(a.row);
matrix.set(a.row, matrix.get(b.row));
matrix.set(b.row, temp);
int t = a.row;
a.row = b.row;
b.row = t;
}
public void Scale(Coordinate x, Fraction d) {
LinkedList<Fraction> row = matrix.get(x.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).multiply(d));
}
}
public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) {
LinkedList<Fraction> row = matrix.get(to.row);
LinkedList<Fraction> rowMultiplied = matrix.get(from.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar))));
}
}
public void RREF() {
Coordinate pivot = new Coordinate(0,0);
int submatrix = 0;
for (int x = 0; x < numCols; x++) {
pivot = new Coordinate(pivot.row, x);
for (int i = x; i < numCols; i++) {
if (isColumnZeroes(pivot) == false) {
break;
} else {
pivot.col = i;
}
}
pivot = findPivot(pivot);
if (getCoordinate(pivot).doubleValue() == 0.0) {
pivot.row++;
continue;
}
if (pivot.row != submatrix) {
Interchange(new Coordinate(submatrix, pivot.col), pivot);
}
if (getCoordinate(pivot).doubleValue() != 1) {
Fraction scalar = getCoordinate(pivot).reciprocal();
Scale(pivot, scalar);
}
for (int i = pivot.row; i < numRows; i++) {
if (i == pivot.row) {
continue;
}
Coordinate belowPivot = new Coordinate(i, pivot.col);
Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot)));
MultiplyAndAdd(belowPivot, pivot, complement);
}
for (int i = pivot.row; i >= 0; i--) {
if (i == pivot.row) {
if (getCoordinate(pivot).doubleValue() != 1.0) {
Scale(pivot, getCoordinate(pivot).reciprocal());
}
continue;
}
if (i == pivot.row) {
continue;
}
Coordinate abovePivot = new Coordinate(i, pivot.col);
Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot)));
MultiplyAndAdd(abovePivot, pivot, complement);
}
if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) {
break;
}
submatrix++;
pivot.row++;
}
}
public boolean isColumnZeroes(Coordinate a) {
for (int i = 0; i < numRows; i++) {
if (matrix.get(i).get(a.col).doubleValue() != 0.0) {
return false;
}
}
return true;
}
public boolean isRowZeroes(Coordinate a) {
for (int i = 0; i < numCols; i++) {
if (matrix.get(a.row).get(i).doubleValue() != 0.0) {
return false;
}
}
return true;
}
public Coordinate findPivot(Coordinate a) {
int first_row = a.row;
Coordinate pivot = new Coordinate(a.row, a.col);
Coordinate current = new Coordinate(a.row, a.col);
for (int i = a.row; i < (numRows - first_row); i++) {
current.row = i;
if (getCoordinate(current).doubleValue() == 1.0) {
Interchange(current, a);
}
}
current.row = a.row;
for (int i = current.row; i < (numRows - first_row); i++) {
current.row = i;
if (getCoordinate(current).doubleValue() != 0) {
pivot.row = i;
break;
}
}
return pivot;
}
public Fraction getCoordinate(Coordinate a) {
return matrix.get(a.row).get(a.col);
}
public String toString() {
return matrix.toString().replace("], ", "]\n");
}
public static void main (String[] args) {
double[][] matrix_1 = {
{1, 2, -1, -4},
{2, 3, -1, -11},
{-2, 0, -3, 22}
};
Matrix x = new Matrix(matrix_1);
System.out.println("before\n" + x.toString() + "\n");
x.RREF();
System.out.println("after\n" + x.toString() + "\n");
double matrix_2 [][] = {
{2, 0, -1, 0, 0},
{1, 0, 0, -1, 0},
{3, 0, 0, -2, -1},
{0, 1, 0, 0, -2},
{0, 1, -1, 0, 0}
};
Matrix y = new Matrix(matrix_2);
System.out.println("before\n" + y.toString() + "\n");
y.RREF();
System.out.println("after\n" + y.toString() + "\n");
double matrix_3 [][] = {
{1, 2, 3, 4, 3, 1},
{2, 4, 6, 2, 6, 2},
{3, 6, 18, 9, 9, -6},
{4, 8, 12, 10, 12, 4},
{5, 10, 24, 11, 15, -4}
};
Matrix z = new Matrix(matrix_3);
System.out.println("before\n" + z.toString() + "\n");
z.RREF();
System.out.println("after\n" + z.toString() + "\n");
double matrix_4 [][] = {
{0, 1},
{1, 2},
{0,5}
};
Matrix a = new Matrix(matrix_4);
System.out.println("before\n" + a.toString() + "\n");
a.RREF();
System.out.println("after\n" + a.toString() + "\n");
}
}
|
Generate an equivalent Python version of this D code. | import std.stdio, std.algorithm, std.array, std.conv;
void toReducedRowEchelonForm(T)(T[][] M) pure nothrow @nogc {
if (M.empty)
return;
immutable nrows = M.length;
immutable ncols = M[0].length;
size_t lead;
foreach (immutable r; 0 .. nrows) {
if (ncols <= lead)
return;
{
size_t i = r;
while (M[i][lead] == 0) {
i++;
if (nrows == i) {
i = r;
lead++;
if (ncols == lead)
return;
}
}
swap(M[i], M[r]);
}
M[r][] /= M[r][lead];
foreach (j, ref mj; M)
if (j != r)
mj[] -= M[r][] * mj[lead];
lead++;
}
}
void main() {
auto A = [[ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[-2, 0, -3, 22]];
A.toReducedRowEchelonForm;
writefln("%(%(%2d %)\n%)", A);
}
| def ToReducedRowEchelonForm( M):
if not M: return
lead = 0
rowCount = len(M)
columnCount = len(M[0])
for r in range(rowCount):
if lead >= columnCount:
return
i = r
while M[i][lead] == 0:
i += 1
if i == rowCount:
i = r
lead += 1
if columnCount == lead:
return
M[i],M[r] = M[r],M[i]
lv = M[r][lead]
M[r] = [ mrx / float(lv) for mrx in M[r]]
for i in range(rowCount):
if i != r:
lv = M[i][lead]
M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]
lead += 1
mtx = [
[ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[-2, 0, -3, 22],]
ToReducedRowEchelonForm( mtx )
for rw in mtx:
print ', '.join( (str(rv) for rv in rw) )
|
Convert this D block to VB, preserving its control flow and logic. | import std.stdio, std.algorithm, std.array, std.conv;
void toReducedRowEchelonForm(T)(T[][] M) pure nothrow @nogc {
if (M.empty)
return;
immutable nrows = M.length;
immutable ncols = M[0].length;
size_t lead;
foreach (immutable r; 0 .. nrows) {
if (ncols <= lead)
return;
{
size_t i = r;
while (M[i][lead] == 0) {
i++;
if (nrows == i) {
i = r;
lead++;
if (ncols == lead)
return;
}
}
swap(M[i], M[r]);
}
M[r][] /= M[r][lead];
foreach (j, ref mj; M)
if (j != r)
mj[] -= M[r][] * mj[lead];
lead++;
}
}
void main() {
auto A = [[ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[-2, 0, -3, 22]];
A.toReducedRowEchelonForm;
writefln("%(%(%2d %)\n%)", A);
}
| Private Function ToReducedRowEchelonForm(M As Variant) As Variant
Dim lead As Integer: lead = 0
Dim rowCount As Integer: rowCount = UBound(M)
Dim columnCount As Integer: columnCount = UBound(M(0))
Dim i As Integer
For r = 0 To rowCount
If lead >= columnCount Then
Exit For
End If
i = r
Do While M(i)(lead) = 0
i = i + 1
If i = rowCount Then
i = r
lead = lead + 1
If lead = columnCount Then
Exit For
End If
End If
Loop
Dim tmp As Variant
tmp = M(r)
M(r) = M(i)
M(i) = tmp
If M(r)(lead) <> 0 Then
div = M(r)(lead)
For t = LBound(M(r)) To UBound(M(r))
M(r)(t) = M(r)(t) / div
Next t
End If
For j = 0 To rowCount
If j <> r Then
subt = M(j)(lead)
For t = LBound(M(j)) To UBound(M(j))
M(j)(t) = M(j)(t) - subt * M(r)(t)
Next t
End If
Next j
lead = lead + 1
Next r
ToReducedRowEchelonForm = M
End Function
Public Sub main()
r = ToReducedRowEchelonForm(Array( _
Array(1, 2, -1, -4), _
Array(2, 3, -1, -11), _
Array(-2, 0, -3, 22)))
For i = LBound(r) To UBound(r)
Debug.Print Join(r(i), vbTab)
Next i
End Sub
|
Ensure the translated Go code behaves exactly like the original D snippet. | import std.stdio, std.algorithm, std.array, std.conv;
void toReducedRowEchelonForm(T)(T[][] M) pure nothrow @nogc {
if (M.empty)
return;
immutable nrows = M.length;
immutable ncols = M[0].length;
size_t lead;
foreach (immutable r; 0 .. nrows) {
if (ncols <= lead)
return;
{
size_t i = r;
while (M[i][lead] == 0) {
i++;
if (nrows == i) {
i = r;
lead++;
if (ncols == lead)
return;
}
}
swap(M[i], M[r]);
}
M[r][] /= M[r][lead];
foreach (j, ref mj; M)
if (j != r)
mj[] -= M[r][] * mj[lead];
lead++;
}
}
void main() {
auto A = [[ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[-2, 0, -3, 22]];
A.toReducedRowEchelonForm;
writefln("%(%(%2d %)\n%)", A);
}
| package main
import "fmt"
type matrix [][]float64
func (m matrix) print() {
for _, r := range m {
fmt.Println(r)
}
fmt.Println("")
}
func main() {
m := matrix{
{ 1, 2, -1, -4},
{ 2, 3, -1, -11},
{-2, 0, -3, 22},
}
m.print()
rref(m)
m.print()
}
func rref(m matrix) {
lead := 0
rowCount := len(m)
columnCount := len(m[0])
for r := 0; r < rowCount; r++ {
if lead >= columnCount {
return
}
i := r
for m[i][lead] == 0 {
i++
if rowCount == i {
i = r
lead++
if columnCount == lead {
return
}
}
}
m[i], m[r] = m[r], m[i]
f := 1 / m[r][lead]
for j, _ := range m[r] {
m[r][j] *= f
}
for i = 0; i < rowCount; i++ {
if i != r {
f = m[i][lead]
for j, e := range m[r] {
m[i][j] -= e * f
}
}
}
lead++
}
}
|
Can you help me rewrite this code in C instead of Factor, keeping it the same logically? | USE: math.matrices.elimination
{ { 1 2 -1 -4 } { 2 3 -1 -11 } { -2 0 -3 22 } } solution .
| #include <stdio.h>
#define TALLOC(n,typ) malloc(n*sizeof(typ))
#define EL_Type int
typedef struct sMtx {
int dim_x, dim_y;
EL_Type *m_stor;
EL_Type **mtx;
} *Matrix, sMatrix;
typedef struct sRvec {
int dim_x;
EL_Type *m_stor;
} *RowVec, sRowVec;
Matrix NewMatrix( int x_dim, int y_dim )
{
int n;
Matrix m;
m = TALLOC( 1, sMatrix);
n = x_dim * y_dim;
m->dim_x = x_dim;
m->dim_y = y_dim;
m->m_stor = TALLOC(n, EL_Type);
m->mtx = TALLOC(m->dim_y, EL_Type *);
for(n=0; n<y_dim; n++) {
m->mtx[n] = m->m_stor+n*x_dim;
}
return m;
}
void MtxSetRow(Matrix m, int irow, EL_Type *v)
{
int ix;
EL_Type *mr;
mr = m->mtx[irow];
for(ix=0; ix<m->dim_x; ix++)
mr[ix] = v[ix];
}
Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v)
{
Matrix m;
int iy;
m = NewMatrix(x_dim, y_dim);
for (iy=0; iy<y_dim; iy++)
MtxSetRow(m, iy, v[iy]);
return m;
}
void MtxDisplay( Matrix m )
{
int iy, ix;
const char *sc;
for (iy=0; iy<m->dim_y; iy++) {
printf(" ");
sc = " ";
for (ix=0; ix<m->dim_x; ix++) {
printf("%s %3d", sc, m->mtx[iy][ix]);
sc = ",";
}
printf("\n");
}
printf("\n");
}
void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr)
{
int ix;
EL_Type *drow, *srow;
drow = m->mtx[ixrdest];
srow = m->mtx[ixrsrc];
for (ix=0; ix<m->dim_x; ix++)
drow[ix] += mplr * srow[ix];
}
void MtxSwapRows( Matrix m, int rix1, int rix2)
{
EL_Type *r1, *r2, temp;
int ix;
if (rix1 == rix2) return;
r1 = m->mtx[rix1];
r2 = m->mtx[rix2];
for (ix=0; ix<m->dim_x; ix++)
temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp;
}
void MtxNormalizeRow( Matrix m, int rix, int lead)
{
int ix;
EL_Type *drow;
EL_Type lv;
drow = m->mtx[rix];
lv = drow[lead];
for (ix=0; ix<m->dim_x; ix++)
drow[ix] /= lv;
}
#define MtxGet( m, rix, cix ) m->mtx[rix][cix]
void MtxToReducedREForm(Matrix m)
{
int lead;
int rix, iix;
EL_Type lv;
int rowCount = m->dim_y;
lead = 0;
for (rix=0; rix<rowCount; rix++) {
if (lead >= m->dim_x)
return;
iix = rix;
while (0 == MtxGet(m, iix,lead)) {
iix++;
if (iix == rowCount) {
iix = rix;
lead++;
if (lead == m->dim_x)
return;
}
}
MtxSwapRows(m, iix, rix );
MtxNormalizeRow(m, rix, lead );
for (iix=0; iix<rowCount; iix++) {
if ( iix != rix ) {
lv = MtxGet(m, iix, lead );
MtxMulAndAddRows(m,iix, rix, -lv) ;
}
}
lead++;
}
}
int main()
{
Matrix m1;
static EL_Type r1[] = {1,2,-1,-4};
static EL_Type r2[] = {2,3,-1,-11};
static EL_Type r3[] = {-2,0,-3,22};
static EL_Type *im[] = { r1, r2, r3 };
m1 = InitMatrix( 4,3, im );
printf("Initial\n");
MtxDisplay(m1);
MtxToReducedREForm(m1);
printf("Reduced R-E form\n");
MtxDisplay(m1);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C#. | USE: math.matrices.elimination
{ { 1 2 -1 -4 } { 2 3 -1 -11 } { -2 0 -3 22 } } solution .
| using System;
namespace rref
{
class Program
{
static void Main(string[] args)
{
int[,] matrix = new int[3, 4]{
{ 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 }
};
matrix = rref(matrix);
}
private static int[,] rref(int[,] matrix)
{
int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1);
for (int r = 0; r < rowCount; r++)
{
if (columnCount <= lead) break;
int i = r;
while (matrix[i, lead] == 0)
{
i++;
if (i == rowCount)
{
i = r;
lead++;
if (columnCount == lead)
{
lead--;
break;
}
}
}
for (int j = 0; j < columnCount; j++)
{
int temp = matrix[r, j];
matrix[r, j] = matrix[i, j];
matrix[i, j] = temp;
}
int div = matrix[r, lead];
if(div != 0)
for (int j = 0; j < columnCount; j++) matrix[r, j] /= div;
for (int j = 0; j < rowCount; j++)
{
if (j != r)
{
int sub = matrix[j, lead];
for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]);
}
}
lead++;
}
return matrix;
}
}
}
|
Keep all operations the same but rewrite the snippet in C++. | USE: math.matrices.elimination
{ { 1 2 -1 -4 } { 2 3 -1 -11 } { -2 0 -3 22 } } solution .
| #include <algorithm>
#include <cstddef>
#include <cassert>
template<typename MatrixType> struct matrix_traits
{
typedef typename MatrixType::index_type index_type;
typedef typename MatrixType::value_type value_type;
static index_type min_row(MatrixType const& A)
{ return A.min_row(); }
static index_type max_row(MatrixType const& A)
{ return A.max_row(); }
static index_type min_column(MatrixType const& A)
{ return A.min_column(); }
static index_type max_column(MatrixType const& A)
{ return A.max_column(); }
static value_type& element(MatrixType& A, index_type i, index_type k)
{ return A(i,k); }
static value_type element(MatrixType const& A, index_type i, index_type k)
{ return A(i,k); }
};
template<typename T, std::size_t rows, std::size_t columns>
struct matrix_traits<T[rows][columns]>
{
typedef std::size_t index_type;
typedef T value_type;
static index_type min_row(T const (&)[rows][columns])
{ return 0; }
static index_type max_row(T const (&)[rows][columns])
{ return rows-1; }
static index_type min_column(T const (&)[rows][columns])
{ return 0; }
static index_type max_column(T const (&)[rows][columns])
{ return columns-1; }
static value_type& element(T (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
static value_type element(T const (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
};
template<typename MatrixType>
void swap_rows(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
std::swap(mt.element(A, i, col), mt.element(A, k, col));
}
template<typename MatrixType>
void divide_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(v != 0);
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) /= v;
}
template<typename MatrixType>
void add_multiple_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) += v * mt.element(A, k, col);
}
template<typename MatrixType>
void to_reduced_row_echelon_form(MatrixType& A)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
index_type lead = mt.min_row(A);
for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row)
{
if (lead > mt.max_column(A))
return;
index_type i = row;
while (mt.element(A, i, lead) == 0)
{
++i;
if (i > mt.max_row(A))
{
i = row;
++lead;
if (lead > mt.max_column(A))
return;
}
}
swap_rows(A, i, row);
divide_row(A, row, mt.element(A, row, lead));
for (i = mt.min_row(A); i <= mt.max_row(A); ++i)
{
if (i != row)
add_multiple_row(A, i, row, -mt.element(A, i, lead));
}
}
}
#include <iostream>
int main()
{
double M[3][4] = { { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } };
to_reduced_row_echelon_form(M);
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
std::cout << M[i][j] << '\t';
std::cout << "\n";
}
return EXIT_SUCCESS;
}
|
Generate an equivalent Java version of this Factor code. | USE: math.matrices.elimination
{ { 1 2 -1 -4 } { 2 3 -1 -11 } { -2 0 -3 22 } } solution .
| import java.util.*;
import java.lang.Math;
import org.apache.commons.math.fraction.Fraction;
import org.apache.commons.math.fraction.FractionConversionException;
class Matrix {
LinkedList<LinkedList<Fraction>> matrix;
int numRows;
int numCols;
static class Coordinate {
int row;
int col;
Coordinate(int r, int c) {
row = r;
col = c;
}
public String toString() {
return "(" + row + ", " + col + ")";
}
}
Matrix(double [][] m) {
numRows = m.length;
numCols = m[0].length;
matrix = new LinkedList<LinkedList<Fraction>>();
for (int i = 0; i < numRows; i++) {
matrix.add(new LinkedList<Fraction>());
for (int j = 0; j < numCols; j++) {
try {
matrix.get(i).add(new Fraction(m[i][j]));
} catch (FractionConversionException e) {
System.err.println("Fraction could not be converted from double by apache commons . . .");
}
}
}
}
public void Interchange(Coordinate a, Coordinate b) {
LinkedList<Fraction> temp = matrix.get(a.row);
matrix.set(a.row, matrix.get(b.row));
matrix.set(b.row, temp);
int t = a.row;
a.row = b.row;
b.row = t;
}
public void Scale(Coordinate x, Fraction d) {
LinkedList<Fraction> row = matrix.get(x.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).multiply(d));
}
}
public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) {
LinkedList<Fraction> row = matrix.get(to.row);
LinkedList<Fraction> rowMultiplied = matrix.get(from.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar))));
}
}
public void RREF() {
Coordinate pivot = new Coordinate(0,0);
int submatrix = 0;
for (int x = 0; x < numCols; x++) {
pivot = new Coordinate(pivot.row, x);
for (int i = x; i < numCols; i++) {
if (isColumnZeroes(pivot) == false) {
break;
} else {
pivot.col = i;
}
}
pivot = findPivot(pivot);
if (getCoordinate(pivot).doubleValue() == 0.0) {
pivot.row++;
continue;
}
if (pivot.row != submatrix) {
Interchange(new Coordinate(submatrix, pivot.col), pivot);
}
if (getCoordinate(pivot).doubleValue() != 1) {
Fraction scalar = getCoordinate(pivot).reciprocal();
Scale(pivot, scalar);
}
for (int i = pivot.row; i < numRows; i++) {
if (i == pivot.row) {
continue;
}
Coordinate belowPivot = new Coordinate(i, pivot.col);
Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot)));
MultiplyAndAdd(belowPivot, pivot, complement);
}
for (int i = pivot.row; i >= 0; i--) {
if (i == pivot.row) {
if (getCoordinate(pivot).doubleValue() != 1.0) {
Scale(pivot, getCoordinate(pivot).reciprocal());
}
continue;
}
if (i == pivot.row) {
continue;
}
Coordinate abovePivot = new Coordinate(i, pivot.col);
Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot)));
MultiplyAndAdd(abovePivot, pivot, complement);
}
if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) {
break;
}
submatrix++;
pivot.row++;
}
}
public boolean isColumnZeroes(Coordinate a) {
for (int i = 0; i < numRows; i++) {
if (matrix.get(i).get(a.col).doubleValue() != 0.0) {
return false;
}
}
return true;
}
public boolean isRowZeroes(Coordinate a) {
for (int i = 0; i < numCols; i++) {
if (matrix.get(a.row).get(i).doubleValue() != 0.0) {
return false;
}
}
return true;
}
public Coordinate findPivot(Coordinate a) {
int first_row = a.row;
Coordinate pivot = new Coordinate(a.row, a.col);
Coordinate current = new Coordinate(a.row, a.col);
for (int i = a.row; i < (numRows - first_row); i++) {
current.row = i;
if (getCoordinate(current).doubleValue() == 1.0) {
Interchange(current, a);
}
}
current.row = a.row;
for (int i = current.row; i < (numRows - first_row); i++) {
current.row = i;
if (getCoordinate(current).doubleValue() != 0) {
pivot.row = i;
break;
}
}
return pivot;
}
public Fraction getCoordinate(Coordinate a) {
return matrix.get(a.row).get(a.col);
}
public String toString() {
return matrix.toString().replace("], ", "]\n");
}
public static void main (String[] args) {
double[][] matrix_1 = {
{1, 2, -1, -4},
{2, 3, -1, -11},
{-2, 0, -3, 22}
};
Matrix x = new Matrix(matrix_1);
System.out.println("before\n" + x.toString() + "\n");
x.RREF();
System.out.println("after\n" + x.toString() + "\n");
double matrix_2 [][] = {
{2, 0, -1, 0, 0},
{1, 0, 0, -1, 0},
{3, 0, 0, -2, -1},
{0, 1, 0, 0, -2},
{0, 1, -1, 0, 0}
};
Matrix y = new Matrix(matrix_2);
System.out.println("before\n" + y.toString() + "\n");
y.RREF();
System.out.println("after\n" + y.toString() + "\n");
double matrix_3 [][] = {
{1, 2, 3, 4, 3, 1},
{2, 4, 6, 2, 6, 2},
{3, 6, 18, 9, 9, -6},
{4, 8, 12, 10, 12, 4},
{5, 10, 24, 11, 15, -4}
};
Matrix z = new Matrix(matrix_3);
System.out.println("before\n" + z.toString() + "\n");
z.RREF();
System.out.println("after\n" + z.toString() + "\n");
double matrix_4 [][] = {
{0, 1},
{1, 2},
{0,5}
};
Matrix a = new Matrix(matrix_4);
System.out.println("before\n" + a.toString() + "\n");
a.RREF();
System.out.println("after\n" + a.toString() + "\n");
}
}
|
Port the following code from Factor to Python with equivalent syntax and logic. | USE: math.matrices.elimination
{ { 1 2 -1 -4 } { 2 3 -1 -11 } { -2 0 -3 22 } } solution .
| def ToReducedRowEchelonForm( M):
if not M: return
lead = 0
rowCount = len(M)
columnCount = len(M[0])
for r in range(rowCount):
if lead >= columnCount:
return
i = r
while M[i][lead] == 0:
i += 1
if i == rowCount:
i = r
lead += 1
if columnCount == lead:
return
M[i],M[r] = M[r],M[i]
lv = M[r][lead]
M[r] = [ mrx / float(lv) for mrx in M[r]]
for i in range(rowCount):
if i != r:
lv = M[i][lead]
M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]
lead += 1
mtx = [
[ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[-2, 0, -3, 22],]
ToReducedRowEchelonForm( mtx )
for rw in mtx:
print ', '.join( (str(rv) for rv in rw) )
|
Transform the following Factor implementation into VB, maintaining the same output and logic. | USE: math.matrices.elimination
{ { 1 2 -1 -4 } { 2 3 -1 -11 } { -2 0 -3 22 } } solution .
| Private Function ToReducedRowEchelonForm(M As Variant) As Variant
Dim lead As Integer: lead = 0
Dim rowCount As Integer: rowCount = UBound(M)
Dim columnCount As Integer: columnCount = UBound(M(0))
Dim i As Integer
For r = 0 To rowCount
If lead >= columnCount Then
Exit For
End If
i = r
Do While M(i)(lead) = 0
i = i + 1
If i = rowCount Then
i = r
lead = lead + 1
If lead = columnCount Then
Exit For
End If
End If
Loop
Dim tmp As Variant
tmp = M(r)
M(r) = M(i)
M(i) = tmp
If M(r)(lead) <> 0 Then
div = M(r)(lead)
For t = LBound(M(r)) To UBound(M(r))
M(r)(t) = M(r)(t) / div
Next t
End If
For j = 0 To rowCount
If j <> r Then
subt = M(j)(lead)
For t = LBound(M(j)) To UBound(M(j))
M(j)(t) = M(j)(t) - subt * M(r)(t)
Next t
End If
Next j
lead = lead + 1
Next r
ToReducedRowEchelonForm = M
End Function
Public Sub main()
r = ToReducedRowEchelonForm(Array( _
Array(1, 2, -1, -4), _
Array(2, 3, -1, -11), _
Array(-2, 0, -3, 22)))
For i = LBound(r) To UBound(r)
Debug.Print Join(r(i), vbTab)
Next i
End Sub
|
Generate a Go translation of this Factor snippet without changing its computational steps. | USE: math.matrices.elimination
{ { 1 2 -1 -4 } { 2 3 -1 -11 } { -2 0 -3 22 } } solution .
| package main
import "fmt"
type matrix [][]float64
func (m matrix) print() {
for _, r := range m {
fmt.Println(r)
}
fmt.Println("")
}
func main() {
m := matrix{
{ 1, 2, -1, -4},
{ 2, 3, -1, -11},
{-2, 0, -3, 22},
}
m.print()
rref(m)
m.print()
}
func rref(m matrix) {
lead := 0
rowCount := len(m)
columnCount := len(m[0])
for r := 0; r < rowCount; r++ {
if lead >= columnCount {
return
}
i := r
for m[i][lead] == 0 {
i++
if rowCount == i {
i = r
lead++
if columnCount == lead {
return
}
}
}
m[i], m[r] = m[r], m[i]
f := 1 / m[r][lead]
for j, _ := range m[r] {
m[r][j] *= f
}
for i = 0; i < rowCount; i++ {
if i != r {
f = m[i][lead]
for j, e := range m[r] {
m[i][j] -= e * f
}
}
}
lead++
}
}
|
Port the provided Fortran code into C# while preserving the original functionality. | module Rref
implicit none
contains
subroutine to_rref(matrix)
real, dimension(:,:), intent(inout) :: matrix
integer :: pivot, norow, nocolumn
integer :: r, i
real, dimension(:), allocatable :: trow
pivot = 1
norow = size(matrix, 1)
nocolumn = size(matrix, 2)
allocate(trow(nocolumn))
do r = 1, norow
if ( nocolumn <= pivot ) exit
i = r
do while ( matrix(i, pivot) == 0 )
i = i + 1
if ( norow == i ) then
i = r
pivot = pivot + 1
if ( nocolumn == pivot ) return
end if
end do
trow = matrix(i, :)
matrix(i, :) = matrix(r, :)
matrix(r, :) = trow
matrix(r, :) = matrix(r, :) / matrix(r, pivot)
do i = 1, norow
if ( i /= r ) matrix(i, :) = matrix(i, :) - matrix(r, :) * matrix(i, pivot)
end do
pivot = pivot + 1
end do
deallocate(trow)
end subroutine to_rref
end module Rref
| using System;
namespace rref
{
class Program
{
static void Main(string[] args)
{
int[,] matrix = new int[3, 4]{
{ 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 }
};
matrix = rref(matrix);
}
private static int[,] rref(int[,] matrix)
{
int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1);
for (int r = 0; r < rowCount; r++)
{
if (columnCount <= lead) break;
int i = r;
while (matrix[i, lead] == 0)
{
i++;
if (i == rowCount)
{
i = r;
lead++;
if (columnCount == lead)
{
lead--;
break;
}
}
}
for (int j = 0; j < columnCount; j++)
{
int temp = matrix[r, j];
matrix[r, j] = matrix[i, j];
matrix[i, j] = temp;
}
int div = matrix[r, lead];
if(div != 0)
for (int j = 0; j < columnCount; j++) matrix[r, j] /= div;
for (int j = 0; j < rowCount; j++)
{
if (j != r)
{
int sub = matrix[j, lead];
for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]);
}
}
lead++;
}
return matrix;
}
}
}
|
Convert this Fortran snippet to C++ and keep its semantics consistent. | module Rref
implicit none
contains
subroutine to_rref(matrix)
real, dimension(:,:), intent(inout) :: matrix
integer :: pivot, norow, nocolumn
integer :: r, i
real, dimension(:), allocatable :: trow
pivot = 1
norow = size(matrix, 1)
nocolumn = size(matrix, 2)
allocate(trow(nocolumn))
do r = 1, norow
if ( nocolumn <= pivot ) exit
i = r
do while ( matrix(i, pivot) == 0 )
i = i + 1
if ( norow == i ) then
i = r
pivot = pivot + 1
if ( nocolumn == pivot ) return
end if
end do
trow = matrix(i, :)
matrix(i, :) = matrix(r, :)
matrix(r, :) = trow
matrix(r, :) = matrix(r, :) / matrix(r, pivot)
do i = 1, norow
if ( i /= r ) matrix(i, :) = matrix(i, :) - matrix(r, :) * matrix(i, pivot)
end do
pivot = pivot + 1
end do
deallocate(trow)
end subroutine to_rref
end module Rref
| #include <algorithm>
#include <cstddef>
#include <cassert>
template<typename MatrixType> struct matrix_traits
{
typedef typename MatrixType::index_type index_type;
typedef typename MatrixType::value_type value_type;
static index_type min_row(MatrixType const& A)
{ return A.min_row(); }
static index_type max_row(MatrixType const& A)
{ return A.max_row(); }
static index_type min_column(MatrixType const& A)
{ return A.min_column(); }
static index_type max_column(MatrixType const& A)
{ return A.max_column(); }
static value_type& element(MatrixType& A, index_type i, index_type k)
{ return A(i,k); }
static value_type element(MatrixType const& A, index_type i, index_type k)
{ return A(i,k); }
};
template<typename T, std::size_t rows, std::size_t columns>
struct matrix_traits<T[rows][columns]>
{
typedef std::size_t index_type;
typedef T value_type;
static index_type min_row(T const (&)[rows][columns])
{ return 0; }
static index_type max_row(T const (&)[rows][columns])
{ return rows-1; }
static index_type min_column(T const (&)[rows][columns])
{ return 0; }
static index_type max_column(T const (&)[rows][columns])
{ return columns-1; }
static value_type& element(T (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
static value_type element(T const (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
};
template<typename MatrixType>
void swap_rows(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
std::swap(mt.element(A, i, col), mt.element(A, k, col));
}
template<typename MatrixType>
void divide_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(v != 0);
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) /= v;
}
template<typename MatrixType>
void add_multiple_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) += v * mt.element(A, k, col);
}
template<typename MatrixType>
void to_reduced_row_echelon_form(MatrixType& A)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
index_type lead = mt.min_row(A);
for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row)
{
if (lead > mt.max_column(A))
return;
index_type i = row;
while (mt.element(A, i, lead) == 0)
{
++i;
if (i > mt.max_row(A))
{
i = row;
++lead;
if (lead > mt.max_column(A))
return;
}
}
swap_rows(A, i, row);
divide_row(A, row, mt.element(A, row, lead));
for (i = mt.min_row(A); i <= mt.max_row(A); ++i)
{
if (i != row)
add_multiple_row(A, i, row, -mt.element(A, i, lead));
}
}
}
#include <iostream>
int main()
{
double M[3][4] = { { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } };
to_reduced_row_echelon_form(M);
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
std::cout << M[i][j] << '\t';
std::cout << "\n";
}
return EXIT_SUCCESS;
}
|
Ensure the translated C code behaves exactly like the original Fortran snippet. | module Rref
implicit none
contains
subroutine to_rref(matrix)
real, dimension(:,:), intent(inout) :: matrix
integer :: pivot, norow, nocolumn
integer :: r, i
real, dimension(:), allocatable :: trow
pivot = 1
norow = size(matrix, 1)
nocolumn = size(matrix, 2)
allocate(trow(nocolumn))
do r = 1, norow
if ( nocolumn <= pivot ) exit
i = r
do while ( matrix(i, pivot) == 0 )
i = i + 1
if ( norow == i ) then
i = r
pivot = pivot + 1
if ( nocolumn == pivot ) return
end if
end do
trow = matrix(i, :)
matrix(i, :) = matrix(r, :)
matrix(r, :) = trow
matrix(r, :) = matrix(r, :) / matrix(r, pivot)
do i = 1, norow
if ( i /= r ) matrix(i, :) = matrix(i, :) - matrix(r, :) * matrix(i, pivot)
end do
pivot = pivot + 1
end do
deallocate(trow)
end subroutine to_rref
end module Rref
| #include <stdio.h>
#define TALLOC(n,typ) malloc(n*sizeof(typ))
#define EL_Type int
typedef struct sMtx {
int dim_x, dim_y;
EL_Type *m_stor;
EL_Type **mtx;
} *Matrix, sMatrix;
typedef struct sRvec {
int dim_x;
EL_Type *m_stor;
} *RowVec, sRowVec;
Matrix NewMatrix( int x_dim, int y_dim )
{
int n;
Matrix m;
m = TALLOC( 1, sMatrix);
n = x_dim * y_dim;
m->dim_x = x_dim;
m->dim_y = y_dim;
m->m_stor = TALLOC(n, EL_Type);
m->mtx = TALLOC(m->dim_y, EL_Type *);
for(n=0; n<y_dim; n++) {
m->mtx[n] = m->m_stor+n*x_dim;
}
return m;
}
void MtxSetRow(Matrix m, int irow, EL_Type *v)
{
int ix;
EL_Type *mr;
mr = m->mtx[irow];
for(ix=0; ix<m->dim_x; ix++)
mr[ix] = v[ix];
}
Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v)
{
Matrix m;
int iy;
m = NewMatrix(x_dim, y_dim);
for (iy=0; iy<y_dim; iy++)
MtxSetRow(m, iy, v[iy]);
return m;
}
void MtxDisplay( Matrix m )
{
int iy, ix;
const char *sc;
for (iy=0; iy<m->dim_y; iy++) {
printf(" ");
sc = " ";
for (ix=0; ix<m->dim_x; ix++) {
printf("%s %3d", sc, m->mtx[iy][ix]);
sc = ",";
}
printf("\n");
}
printf("\n");
}
void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr)
{
int ix;
EL_Type *drow, *srow;
drow = m->mtx[ixrdest];
srow = m->mtx[ixrsrc];
for (ix=0; ix<m->dim_x; ix++)
drow[ix] += mplr * srow[ix];
}
void MtxSwapRows( Matrix m, int rix1, int rix2)
{
EL_Type *r1, *r2, temp;
int ix;
if (rix1 == rix2) return;
r1 = m->mtx[rix1];
r2 = m->mtx[rix2];
for (ix=0; ix<m->dim_x; ix++)
temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp;
}
void MtxNormalizeRow( Matrix m, int rix, int lead)
{
int ix;
EL_Type *drow;
EL_Type lv;
drow = m->mtx[rix];
lv = drow[lead];
for (ix=0; ix<m->dim_x; ix++)
drow[ix] /= lv;
}
#define MtxGet( m, rix, cix ) m->mtx[rix][cix]
void MtxToReducedREForm(Matrix m)
{
int lead;
int rix, iix;
EL_Type lv;
int rowCount = m->dim_y;
lead = 0;
for (rix=0; rix<rowCount; rix++) {
if (lead >= m->dim_x)
return;
iix = rix;
while (0 == MtxGet(m, iix,lead)) {
iix++;
if (iix == rowCount) {
iix = rix;
lead++;
if (lead == m->dim_x)
return;
}
}
MtxSwapRows(m, iix, rix );
MtxNormalizeRow(m, rix, lead );
for (iix=0; iix<rowCount; iix++) {
if ( iix != rix ) {
lv = MtxGet(m, iix, lead );
MtxMulAndAddRows(m,iix, rix, -lv) ;
}
}
lead++;
}
}
int main()
{
Matrix m1;
static EL_Type r1[] = {1,2,-1,-4};
static EL_Type r2[] = {2,3,-1,-11};
static EL_Type r3[] = {-2,0,-3,22};
static EL_Type *im[] = { r1, r2, r3 };
m1 = InitMatrix( 4,3, im );
printf("Initial\n");
MtxDisplay(m1);
MtxToReducedREForm(m1);
printf("Reduced R-E form\n");
MtxDisplay(m1);
return 0;
}
|
Change the programming language of this snippet from Fortran to Java without modifying what it does. | module Rref
implicit none
contains
subroutine to_rref(matrix)
real, dimension(:,:), intent(inout) :: matrix
integer :: pivot, norow, nocolumn
integer :: r, i
real, dimension(:), allocatable :: trow
pivot = 1
norow = size(matrix, 1)
nocolumn = size(matrix, 2)
allocate(trow(nocolumn))
do r = 1, norow
if ( nocolumn <= pivot ) exit
i = r
do while ( matrix(i, pivot) == 0 )
i = i + 1
if ( norow == i ) then
i = r
pivot = pivot + 1
if ( nocolumn == pivot ) return
end if
end do
trow = matrix(i, :)
matrix(i, :) = matrix(r, :)
matrix(r, :) = trow
matrix(r, :) = matrix(r, :) / matrix(r, pivot)
do i = 1, norow
if ( i /= r ) matrix(i, :) = matrix(i, :) - matrix(r, :) * matrix(i, pivot)
end do
pivot = pivot + 1
end do
deallocate(trow)
end subroutine to_rref
end module Rref
| import java.util.*;
import java.lang.Math;
import org.apache.commons.math.fraction.Fraction;
import org.apache.commons.math.fraction.FractionConversionException;
class Matrix {
LinkedList<LinkedList<Fraction>> matrix;
int numRows;
int numCols;
static class Coordinate {
int row;
int col;
Coordinate(int r, int c) {
row = r;
col = c;
}
public String toString() {
return "(" + row + ", " + col + ")";
}
}
Matrix(double [][] m) {
numRows = m.length;
numCols = m[0].length;
matrix = new LinkedList<LinkedList<Fraction>>();
for (int i = 0; i < numRows; i++) {
matrix.add(new LinkedList<Fraction>());
for (int j = 0; j < numCols; j++) {
try {
matrix.get(i).add(new Fraction(m[i][j]));
} catch (FractionConversionException e) {
System.err.println("Fraction could not be converted from double by apache commons . . .");
}
}
}
}
public void Interchange(Coordinate a, Coordinate b) {
LinkedList<Fraction> temp = matrix.get(a.row);
matrix.set(a.row, matrix.get(b.row));
matrix.set(b.row, temp);
int t = a.row;
a.row = b.row;
b.row = t;
}
public void Scale(Coordinate x, Fraction d) {
LinkedList<Fraction> row = matrix.get(x.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).multiply(d));
}
}
public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) {
LinkedList<Fraction> row = matrix.get(to.row);
LinkedList<Fraction> rowMultiplied = matrix.get(from.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar))));
}
}
public void RREF() {
Coordinate pivot = new Coordinate(0,0);
int submatrix = 0;
for (int x = 0; x < numCols; x++) {
pivot = new Coordinate(pivot.row, x);
for (int i = x; i < numCols; i++) {
if (isColumnZeroes(pivot) == false) {
break;
} else {
pivot.col = i;
}
}
pivot = findPivot(pivot);
if (getCoordinate(pivot).doubleValue() == 0.0) {
pivot.row++;
continue;
}
if (pivot.row != submatrix) {
Interchange(new Coordinate(submatrix, pivot.col), pivot);
}
if (getCoordinate(pivot).doubleValue() != 1) {
Fraction scalar = getCoordinate(pivot).reciprocal();
Scale(pivot, scalar);
}
for (int i = pivot.row; i < numRows; i++) {
if (i == pivot.row) {
continue;
}
Coordinate belowPivot = new Coordinate(i, pivot.col);
Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot)));
MultiplyAndAdd(belowPivot, pivot, complement);
}
for (int i = pivot.row; i >= 0; i--) {
if (i == pivot.row) {
if (getCoordinate(pivot).doubleValue() != 1.0) {
Scale(pivot, getCoordinate(pivot).reciprocal());
}
continue;
}
if (i == pivot.row) {
continue;
}
Coordinate abovePivot = new Coordinate(i, pivot.col);
Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot)));
MultiplyAndAdd(abovePivot, pivot, complement);
}
if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) {
break;
}
submatrix++;
pivot.row++;
}
}
public boolean isColumnZeroes(Coordinate a) {
for (int i = 0; i < numRows; i++) {
if (matrix.get(i).get(a.col).doubleValue() != 0.0) {
return false;
}
}
return true;
}
public boolean isRowZeroes(Coordinate a) {
for (int i = 0; i < numCols; i++) {
if (matrix.get(a.row).get(i).doubleValue() != 0.0) {
return false;
}
}
return true;
}
public Coordinate findPivot(Coordinate a) {
int first_row = a.row;
Coordinate pivot = new Coordinate(a.row, a.col);
Coordinate current = new Coordinate(a.row, a.col);
for (int i = a.row; i < (numRows - first_row); i++) {
current.row = i;
if (getCoordinate(current).doubleValue() == 1.0) {
Interchange(current, a);
}
}
current.row = a.row;
for (int i = current.row; i < (numRows - first_row); i++) {
current.row = i;
if (getCoordinate(current).doubleValue() != 0) {
pivot.row = i;
break;
}
}
return pivot;
}
public Fraction getCoordinate(Coordinate a) {
return matrix.get(a.row).get(a.col);
}
public String toString() {
return matrix.toString().replace("], ", "]\n");
}
public static void main (String[] args) {
double[][] matrix_1 = {
{1, 2, -1, -4},
{2, 3, -1, -11},
{-2, 0, -3, 22}
};
Matrix x = new Matrix(matrix_1);
System.out.println("before\n" + x.toString() + "\n");
x.RREF();
System.out.println("after\n" + x.toString() + "\n");
double matrix_2 [][] = {
{2, 0, -1, 0, 0},
{1, 0, 0, -1, 0},
{3, 0, 0, -2, -1},
{0, 1, 0, 0, -2},
{0, 1, -1, 0, 0}
};
Matrix y = new Matrix(matrix_2);
System.out.println("before\n" + y.toString() + "\n");
y.RREF();
System.out.println("after\n" + y.toString() + "\n");
double matrix_3 [][] = {
{1, 2, 3, 4, 3, 1},
{2, 4, 6, 2, 6, 2},
{3, 6, 18, 9, 9, -6},
{4, 8, 12, 10, 12, 4},
{5, 10, 24, 11, 15, -4}
};
Matrix z = new Matrix(matrix_3);
System.out.println("before\n" + z.toString() + "\n");
z.RREF();
System.out.println("after\n" + z.toString() + "\n");
double matrix_4 [][] = {
{0, 1},
{1, 2},
{0,5}
};
Matrix a = new Matrix(matrix_4);
System.out.println("before\n" + a.toString() + "\n");
a.RREF();
System.out.println("after\n" + a.toString() + "\n");
}
}
|
Rewrite the snippet below in Python so it works the same as the original Fortran code. | module Rref
implicit none
contains
subroutine to_rref(matrix)
real, dimension(:,:), intent(inout) :: matrix
integer :: pivot, norow, nocolumn
integer :: r, i
real, dimension(:), allocatable :: trow
pivot = 1
norow = size(matrix, 1)
nocolumn = size(matrix, 2)
allocate(trow(nocolumn))
do r = 1, norow
if ( nocolumn <= pivot ) exit
i = r
do while ( matrix(i, pivot) == 0 )
i = i + 1
if ( norow == i ) then
i = r
pivot = pivot + 1
if ( nocolumn == pivot ) return
end if
end do
trow = matrix(i, :)
matrix(i, :) = matrix(r, :)
matrix(r, :) = trow
matrix(r, :) = matrix(r, :) / matrix(r, pivot)
do i = 1, norow
if ( i /= r ) matrix(i, :) = matrix(i, :) - matrix(r, :) * matrix(i, pivot)
end do
pivot = pivot + 1
end do
deallocate(trow)
end subroutine to_rref
end module Rref
| def ToReducedRowEchelonForm( M):
if not M: return
lead = 0
rowCount = len(M)
columnCount = len(M[0])
for r in range(rowCount):
if lead >= columnCount:
return
i = r
while M[i][lead] == 0:
i += 1
if i == rowCount:
i = r
lead += 1
if columnCount == lead:
return
M[i],M[r] = M[r],M[i]
lv = M[r][lead]
M[r] = [ mrx / float(lv) for mrx in M[r]]
for i in range(rowCount):
if i != r:
lv = M[i][lead]
M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]
lead += 1
mtx = [
[ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[-2, 0, -3, 22],]
ToReducedRowEchelonForm( mtx )
for rw in mtx:
print ', '.join( (str(rv) for rv in rw) )
|
Rewrite this program in VB while keeping its functionality equivalent to the Fortran version. | module Rref
implicit none
contains
subroutine to_rref(matrix)
real, dimension(:,:), intent(inout) :: matrix
integer :: pivot, norow, nocolumn
integer :: r, i
real, dimension(:), allocatable :: trow
pivot = 1
norow = size(matrix, 1)
nocolumn = size(matrix, 2)
allocate(trow(nocolumn))
do r = 1, norow
if ( nocolumn <= pivot ) exit
i = r
do while ( matrix(i, pivot) == 0 )
i = i + 1
if ( norow == i ) then
i = r
pivot = pivot + 1
if ( nocolumn == pivot ) return
end if
end do
trow = matrix(i, :)
matrix(i, :) = matrix(r, :)
matrix(r, :) = trow
matrix(r, :) = matrix(r, :) / matrix(r, pivot)
do i = 1, norow
if ( i /= r ) matrix(i, :) = matrix(i, :) - matrix(r, :) * matrix(i, pivot)
end do
pivot = pivot + 1
end do
deallocate(trow)
end subroutine to_rref
end module Rref
| Private Function ToReducedRowEchelonForm(M As Variant) As Variant
Dim lead As Integer: lead = 0
Dim rowCount As Integer: rowCount = UBound(M)
Dim columnCount As Integer: columnCount = UBound(M(0))
Dim i As Integer
For r = 0 To rowCount
If lead >= columnCount Then
Exit For
End If
i = r
Do While M(i)(lead) = 0
i = i + 1
If i = rowCount Then
i = r
lead = lead + 1
If lead = columnCount Then
Exit For
End If
End If
Loop
Dim tmp As Variant
tmp = M(r)
M(r) = M(i)
M(i) = tmp
If M(r)(lead) <> 0 Then
div = M(r)(lead)
For t = LBound(M(r)) To UBound(M(r))
M(r)(t) = M(r)(t) / div
Next t
End If
For j = 0 To rowCount
If j <> r Then
subt = M(j)(lead)
For t = LBound(M(j)) To UBound(M(j))
M(j)(t) = M(j)(t) - subt * M(r)(t)
Next t
End If
Next j
lead = lead + 1
Next r
ToReducedRowEchelonForm = M
End Function
Public Sub main()
r = ToReducedRowEchelonForm(Array( _
Array(1, 2, -1, -4), _
Array(2, 3, -1, -11), _
Array(-2, 0, -3, 22)))
For i = LBound(r) To UBound(r)
Debug.Print Join(r(i), vbTab)
Next i
End Sub
|
Preserve the algorithm and functionality while converting the code from Fortran to PHP. | module Rref
implicit none
contains
subroutine to_rref(matrix)
real, dimension(:,:), intent(inout) :: matrix
integer :: pivot, norow, nocolumn
integer :: r, i
real, dimension(:), allocatable :: trow
pivot = 1
norow = size(matrix, 1)
nocolumn = size(matrix, 2)
allocate(trow(nocolumn))
do r = 1, norow
if ( nocolumn <= pivot ) exit
i = r
do while ( matrix(i, pivot) == 0 )
i = i + 1
if ( norow == i ) then
i = r
pivot = pivot + 1
if ( nocolumn == pivot ) return
end if
end do
trow = matrix(i, :)
matrix(i, :) = matrix(r, :)
matrix(r, :) = trow
matrix(r, :) = matrix(r, :) / matrix(r, pivot)
do i = 1, norow
if ( i /= r ) matrix(i, :) = matrix(i, :) - matrix(r, :) * matrix(i, pivot)
end do
pivot = pivot + 1
end do
deallocate(trow)
end subroutine to_rref
end module Rref
| <?php
function rref($matrix)
{
$lead = 0;
$rowCount = count($matrix);
if ($rowCount == 0)
return $matrix;
$columnCount = 0;
if (isset($matrix[0])) {
$columnCount = count($matrix[0]);
}
for ($r = 0; $r < $rowCount; $r++) {
if ($lead >= $columnCount)
break; {
$i = $r;
while ($matrix[$i][$lead] == 0) {
$i++;
if ($i == $rowCount) {
$i = $r;
$lead++;
if ($lead == $columnCount)
return $matrix;
}
}
$temp = $matrix[$r];
$matrix[$r] = $matrix[$i];
$matrix[$i] = $temp;
} {
$lv = $matrix[$r][$lead];
for ($j = 0; $j < $columnCount; $j++) {
$matrix[$r][$j] = $matrix[$r][$j] / $lv;
}
}
for ($i = 0; $i < $rowCount; $i++) {
if ($i != $r) {
$lv = $matrix[$i][$lead];
for ($j = 0; $j < $columnCount; $j++) {
$matrix[$i][$j] -= $lv * $matrix[$r][$j];
}
}
}
$lead++;
}
return $matrix;
}
?>
|
Write a version of this Groovy function in C with identical behavior. | enum Pivoting {
NONE({ i, it -> 1 }),
PARTIAL({ i, it -> - (it[i].abs()) }),
SCALED({ i, it -> - it[i].abs()/(it.inject(0) { sum, elt -> sum + elt.abs() } ) });
public final Closure comparer
private Pivoting(Closure c) {
comparer = c
}
}
def isReducibleMatrix = { matrix ->
def m = matrix.size()
m > 1 && matrix[0].size() > m && matrix[1..<m].every { row -> row.size() == matrix[0].size() }
}
def reducedRowEchelonForm = { matrix, Pivoting pivoting = Pivoting.NONE ->
assert isReducibleMatrix(matrix)
def m = matrix.size()
def n = matrix[0].size()
(0..<m).each { i ->
matrix[i..<m].sort(pivoting.comparer.curry(i))
matrix[i][i..<n] = matrix[i][i..<n].collect { it/matrix[i][i] }
((0..<i) + ((i+1)..<m)).each { k ->
(i..<n).reverse().each { j ->
matrix[k][j] -= matrix[i][j]*matrix[k][i]
}
}
}
matrix
}
| #include <stdio.h>
#define TALLOC(n,typ) malloc(n*sizeof(typ))
#define EL_Type int
typedef struct sMtx {
int dim_x, dim_y;
EL_Type *m_stor;
EL_Type **mtx;
} *Matrix, sMatrix;
typedef struct sRvec {
int dim_x;
EL_Type *m_stor;
} *RowVec, sRowVec;
Matrix NewMatrix( int x_dim, int y_dim )
{
int n;
Matrix m;
m = TALLOC( 1, sMatrix);
n = x_dim * y_dim;
m->dim_x = x_dim;
m->dim_y = y_dim;
m->m_stor = TALLOC(n, EL_Type);
m->mtx = TALLOC(m->dim_y, EL_Type *);
for(n=0; n<y_dim; n++) {
m->mtx[n] = m->m_stor+n*x_dim;
}
return m;
}
void MtxSetRow(Matrix m, int irow, EL_Type *v)
{
int ix;
EL_Type *mr;
mr = m->mtx[irow];
for(ix=0; ix<m->dim_x; ix++)
mr[ix] = v[ix];
}
Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v)
{
Matrix m;
int iy;
m = NewMatrix(x_dim, y_dim);
for (iy=0; iy<y_dim; iy++)
MtxSetRow(m, iy, v[iy]);
return m;
}
void MtxDisplay( Matrix m )
{
int iy, ix;
const char *sc;
for (iy=0; iy<m->dim_y; iy++) {
printf(" ");
sc = " ";
for (ix=0; ix<m->dim_x; ix++) {
printf("%s %3d", sc, m->mtx[iy][ix]);
sc = ",";
}
printf("\n");
}
printf("\n");
}
void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr)
{
int ix;
EL_Type *drow, *srow;
drow = m->mtx[ixrdest];
srow = m->mtx[ixrsrc];
for (ix=0; ix<m->dim_x; ix++)
drow[ix] += mplr * srow[ix];
}
void MtxSwapRows( Matrix m, int rix1, int rix2)
{
EL_Type *r1, *r2, temp;
int ix;
if (rix1 == rix2) return;
r1 = m->mtx[rix1];
r2 = m->mtx[rix2];
for (ix=0; ix<m->dim_x; ix++)
temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp;
}
void MtxNormalizeRow( Matrix m, int rix, int lead)
{
int ix;
EL_Type *drow;
EL_Type lv;
drow = m->mtx[rix];
lv = drow[lead];
for (ix=0; ix<m->dim_x; ix++)
drow[ix] /= lv;
}
#define MtxGet( m, rix, cix ) m->mtx[rix][cix]
void MtxToReducedREForm(Matrix m)
{
int lead;
int rix, iix;
EL_Type lv;
int rowCount = m->dim_y;
lead = 0;
for (rix=0; rix<rowCount; rix++) {
if (lead >= m->dim_x)
return;
iix = rix;
while (0 == MtxGet(m, iix,lead)) {
iix++;
if (iix == rowCount) {
iix = rix;
lead++;
if (lead == m->dim_x)
return;
}
}
MtxSwapRows(m, iix, rix );
MtxNormalizeRow(m, rix, lead );
for (iix=0; iix<rowCount; iix++) {
if ( iix != rix ) {
lv = MtxGet(m, iix, lead );
MtxMulAndAddRows(m,iix, rix, -lv) ;
}
}
lead++;
}
}
int main()
{
Matrix m1;
static EL_Type r1[] = {1,2,-1,-4};
static EL_Type r2[] = {2,3,-1,-11};
static EL_Type r3[] = {-2,0,-3,22};
static EL_Type *im[] = { r1, r2, r3 };
m1 = InitMatrix( 4,3, im );
printf("Initial\n");
MtxDisplay(m1);
MtxToReducedREForm(m1);
printf("Reduced R-E form\n");
MtxDisplay(m1);
return 0;
}
|
Convert this Groovy block to C#, preserving its control flow and logic. | enum Pivoting {
NONE({ i, it -> 1 }),
PARTIAL({ i, it -> - (it[i].abs()) }),
SCALED({ i, it -> - it[i].abs()/(it.inject(0) { sum, elt -> sum + elt.abs() } ) });
public final Closure comparer
private Pivoting(Closure c) {
comparer = c
}
}
def isReducibleMatrix = { matrix ->
def m = matrix.size()
m > 1 && matrix[0].size() > m && matrix[1..<m].every { row -> row.size() == matrix[0].size() }
}
def reducedRowEchelonForm = { matrix, Pivoting pivoting = Pivoting.NONE ->
assert isReducibleMatrix(matrix)
def m = matrix.size()
def n = matrix[0].size()
(0..<m).each { i ->
matrix[i..<m].sort(pivoting.comparer.curry(i))
matrix[i][i..<n] = matrix[i][i..<n].collect { it/matrix[i][i] }
((0..<i) + ((i+1)..<m)).each { k ->
(i..<n).reverse().each { j ->
matrix[k][j] -= matrix[i][j]*matrix[k][i]
}
}
}
matrix
}
| using System;
namespace rref
{
class Program
{
static void Main(string[] args)
{
int[,] matrix = new int[3, 4]{
{ 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 }
};
matrix = rref(matrix);
}
private static int[,] rref(int[,] matrix)
{
int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1);
for (int r = 0; r < rowCount; r++)
{
if (columnCount <= lead) break;
int i = r;
while (matrix[i, lead] == 0)
{
i++;
if (i == rowCount)
{
i = r;
lead++;
if (columnCount == lead)
{
lead--;
break;
}
}
}
for (int j = 0; j < columnCount; j++)
{
int temp = matrix[r, j];
matrix[r, j] = matrix[i, j];
matrix[i, j] = temp;
}
int div = matrix[r, lead];
if(div != 0)
for (int j = 0; j < columnCount; j++) matrix[r, j] /= div;
for (int j = 0; j < rowCount; j++)
{
if (j != r)
{
int sub = matrix[j, lead];
for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]);
}
}
lead++;
}
return matrix;
}
}
}
|
Translate this program into C++ but keep the logic exactly as in Groovy. | enum Pivoting {
NONE({ i, it -> 1 }),
PARTIAL({ i, it -> - (it[i].abs()) }),
SCALED({ i, it -> - it[i].abs()/(it.inject(0) { sum, elt -> sum + elt.abs() } ) });
public final Closure comparer
private Pivoting(Closure c) {
comparer = c
}
}
def isReducibleMatrix = { matrix ->
def m = matrix.size()
m > 1 && matrix[0].size() > m && matrix[1..<m].every { row -> row.size() == matrix[0].size() }
}
def reducedRowEchelonForm = { matrix, Pivoting pivoting = Pivoting.NONE ->
assert isReducibleMatrix(matrix)
def m = matrix.size()
def n = matrix[0].size()
(0..<m).each { i ->
matrix[i..<m].sort(pivoting.comparer.curry(i))
matrix[i][i..<n] = matrix[i][i..<n].collect { it/matrix[i][i] }
((0..<i) + ((i+1)..<m)).each { k ->
(i..<n).reverse().each { j ->
matrix[k][j] -= matrix[i][j]*matrix[k][i]
}
}
}
matrix
}
| #include <algorithm>
#include <cstddef>
#include <cassert>
template<typename MatrixType> struct matrix_traits
{
typedef typename MatrixType::index_type index_type;
typedef typename MatrixType::value_type value_type;
static index_type min_row(MatrixType const& A)
{ return A.min_row(); }
static index_type max_row(MatrixType const& A)
{ return A.max_row(); }
static index_type min_column(MatrixType const& A)
{ return A.min_column(); }
static index_type max_column(MatrixType const& A)
{ return A.max_column(); }
static value_type& element(MatrixType& A, index_type i, index_type k)
{ return A(i,k); }
static value_type element(MatrixType const& A, index_type i, index_type k)
{ return A(i,k); }
};
template<typename T, std::size_t rows, std::size_t columns>
struct matrix_traits<T[rows][columns]>
{
typedef std::size_t index_type;
typedef T value_type;
static index_type min_row(T const (&)[rows][columns])
{ return 0; }
static index_type max_row(T const (&)[rows][columns])
{ return rows-1; }
static index_type min_column(T const (&)[rows][columns])
{ return 0; }
static index_type max_column(T const (&)[rows][columns])
{ return columns-1; }
static value_type& element(T (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
static value_type element(T const (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
};
template<typename MatrixType>
void swap_rows(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
std::swap(mt.element(A, i, col), mt.element(A, k, col));
}
template<typename MatrixType>
void divide_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(v != 0);
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) /= v;
}
template<typename MatrixType>
void add_multiple_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) += v * mt.element(A, k, col);
}
template<typename MatrixType>
void to_reduced_row_echelon_form(MatrixType& A)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
index_type lead = mt.min_row(A);
for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row)
{
if (lead > mt.max_column(A))
return;
index_type i = row;
while (mt.element(A, i, lead) == 0)
{
++i;
if (i > mt.max_row(A))
{
i = row;
++lead;
if (lead > mt.max_column(A))
return;
}
}
swap_rows(A, i, row);
divide_row(A, row, mt.element(A, row, lead));
for (i = mt.min_row(A); i <= mt.max_row(A); ++i)
{
if (i != row)
add_multiple_row(A, i, row, -mt.element(A, i, lead));
}
}
}
#include <iostream>
int main()
{
double M[3][4] = { { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } };
to_reduced_row_echelon_form(M);
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
std::cout << M[i][j] << '\t';
std::cout << "\n";
}
return EXIT_SUCCESS;
}
|
Convert this Groovy block to Java, preserving its control flow and logic. | enum Pivoting {
NONE({ i, it -> 1 }),
PARTIAL({ i, it -> - (it[i].abs()) }),
SCALED({ i, it -> - it[i].abs()/(it.inject(0) { sum, elt -> sum + elt.abs() } ) });
public final Closure comparer
private Pivoting(Closure c) {
comparer = c
}
}
def isReducibleMatrix = { matrix ->
def m = matrix.size()
m > 1 && matrix[0].size() > m && matrix[1..<m].every { row -> row.size() == matrix[0].size() }
}
def reducedRowEchelonForm = { matrix, Pivoting pivoting = Pivoting.NONE ->
assert isReducibleMatrix(matrix)
def m = matrix.size()
def n = matrix[0].size()
(0..<m).each { i ->
matrix[i..<m].sort(pivoting.comparer.curry(i))
matrix[i][i..<n] = matrix[i][i..<n].collect { it/matrix[i][i] }
((0..<i) + ((i+1)..<m)).each { k ->
(i..<n).reverse().each { j ->
matrix[k][j] -= matrix[i][j]*matrix[k][i]
}
}
}
matrix
}
| import java.util.*;
import java.lang.Math;
import org.apache.commons.math.fraction.Fraction;
import org.apache.commons.math.fraction.FractionConversionException;
class Matrix {
LinkedList<LinkedList<Fraction>> matrix;
int numRows;
int numCols;
static class Coordinate {
int row;
int col;
Coordinate(int r, int c) {
row = r;
col = c;
}
public String toString() {
return "(" + row + ", " + col + ")";
}
}
Matrix(double [][] m) {
numRows = m.length;
numCols = m[0].length;
matrix = new LinkedList<LinkedList<Fraction>>();
for (int i = 0; i < numRows; i++) {
matrix.add(new LinkedList<Fraction>());
for (int j = 0; j < numCols; j++) {
try {
matrix.get(i).add(new Fraction(m[i][j]));
} catch (FractionConversionException e) {
System.err.println("Fraction could not be converted from double by apache commons . . .");
}
}
}
}
public void Interchange(Coordinate a, Coordinate b) {
LinkedList<Fraction> temp = matrix.get(a.row);
matrix.set(a.row, matrix.get(b.row));
matrix.set(b.row, temp);
int t = a.row;
a.row = b.row;
b.row = t;
}
public void Scale(Coordinate x, Fraction d) {
LinkedList<Fraction> row = matrix.get(x.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).multiply(d));
}
}
public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) {
LinkedList<Fraction> row = matrix.get(to.row);
LinkedList<Fraction> rowMultiplied = matrix.get(from.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar))));
}
}
public void RREF() {
Coordinate pivot = new Coordinate(0,0);
int submatrix = 0;
for (int x = 0; x < numCols; x++) {
pivot = new Coordinate(pivot.row, x);
for (int i = x; i < numCols; i++) {
if (isColumnZeroes(pivot) == false) {
break;
} else {
pivot.col = i;
}
}
pivot = findPivot(pivot);
if (getCoordinate(pivot).doubleValue() == 0.0) {
pivot.row++;
continue;
}
if (pivot.row != submatrix) {
Interchange(new Coordinate(submatrix, pivot.col), pivot);
}
if (getCoordinate(pivot).doubleValue() != 1) {
Fraction scalar = getCoordinate(pivot).reciprocal();
Scale(pivot, scalar);
}
for (int i = pivot.row; i < numRows; i++) {
if (i == pivot.row) {
continue;
}
Coordinate belowPivot = new Coordinate(i, pivot.col);
Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot)));
MultiplyAndAdd(belowPivot, pivot, complement);
}
for (int i = pivot.row; i >= 0; i--) {
if (i == pivot.row) {
if (getCoordinate(pivot).doubleValue() != 1.0) {
Scale(pivot, getCoordinate(pivot).reciprocal());
}
continue;
}
if (i == pivot.row) {
continue;
}
Coordinate abovePivot = new Coordinate(i, pivot.col);
Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot)));
MultiplyAndAdd(abovePivot, pivot, complement);
}
if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) {
break;
}
submatrix++;
pivot.row++;
}
}
public boolean isColumnZeroes(Coordinate a) {
for (int i = 0; i < numRows; i++) {
if (matrix.get(i).get(a.col).doubleValue() != 0.0) {
return false;
}
}
return true;
}
public boolean isRowZeroes(Coordinate a) {
for (int i = 0; i < numCols; i++) {
if (matrix.get(a.row).get(i).doubleValue() != 0.0) {
return false;
}
}
return true;
}
public Coordinate findPivot(Coordinate a) {
int first_row = a.row;
Coordinate pivot = new Coordinate(a.row, a.col);
Coordinate current = new Coordinate(a.row, a.col);
for (int i = a.row; i < (numRows - first_row); i++) {
current.row = i;
if (getCoordinate(current).doubleValue() == 1.0) {
Interchange(current, a);
}
}
current.row = a.row;
for (int i = current.row; i < (numRows - first_row); i++) {
current.row = i;
if (getCoordinate(current).doubleValue() != 0) {
pivot.row = i;
break;
}
}
return pivot;
}
public Fraction getCoordinate(Coordinate a) {
return matrix.get(a.row).get(a.col);
}
public String toString() {
return matrix.toString().replace("], ", "]\n");
}
public static void main (String[] args) {
double[][] matrix_1 = {
{1, 2, -1, -4},
{2, 3, -1, -11},
{-2, 0, -3, 22}
};
Matrix x = new Matrix(matrix_1);
System.out.println("before\n" + x.toString() + "\n");
x.RREF();
System.out.println("after\n" + x.toString() + "\n");
double matrix_2 [][] = {
{2, 0, -1, 0, 0},
{1, 0, 0, -1, 0},
{3, 0, 0, -2, -1},
{0, 1, 0, 0, -2},
{0, 1, -1, 0, 0}
};
Matrix y = new Matrix(matrix_2);
System.out.println("before\n" + y.toString() + "\n");
y.RREF();
System.out.println("after\n" + y.toString() + "\n");
double matrix_3 [][] = {
{1, 2, 3, 4, 3, 1},
{2, 4, 6, 2, 6, 2},
{3, 6, 18, 9, 9, -6},
{4, 8, 12, 10, 12, 4},
{5, 10, 24, 11, 15, -4}
};
Matrix z = new Matrix(matrix_3);
System.out.println("before\n" + z.toString() + "\n");
z.RREF();
System.out.println("after\n" + z.toString() + "\n");
double matrix_4 [][] = {
{0, 1},
{1, 2},
{0,5}
};
Matrix a = new Matrix(matrix_4);
System.out.println("before\n" + a.toString() + "\n");
a.RREF();
System.out.println("after\n" + a.toString() + "\n");
}
}
|
Change the following Groovy code into Python without altering its purpose. | enum Pivoting {
NONE({ i, it -> 1 }),
PARTIAL({ i, it -> - (it[i].abs()) }),
SCALED({ i, it -> - it[i].abs()/(it.inject(0) { sum, elt -> sum + elt.abs() } ) });
public final Closure comparer
private Pivoting(Closure c) {
comparer = c
}
}
def isReducibleMatrix = { matrix ->
def m = matrix.size()
m > 1 && matrix[0].size() > m && matrix[1..<m].every { row -> row.size() == matrix[0].size() }
}
def reducedRowEchelonForm = { matrix, Pivoting pivoting = Pivoting.NONE ->
assert isReducibleMatrix(matrix)
def m = matrix.size()
def n = matrix[0].size()
(0..<m).each { i ->
matrix[i..<m].sort(pivoting.comparer.curry(i))
matrix[i][i..<n] = matrix[i][i..<n].collect { it/matrix[i][i] }
((0..<i) + ((i+1)..<m)).each { k ->
(i..<n).reverse().each { j ->
matrix[k][j] -= matrix[i][j]*matrix[k][i]
}
}
}
matrix
}
| def ToReducedRowEchelonForm( M):
if not M: return
lead = 0
rowCount = len(M)
columnCount = len(M[0])
for r in range(rowCount):
if lead >= columnCount:
return
i = r
while M[i][lead] == 0:
i += 1
if i == rowCount:
i = r
lead += 1
if columnCount == lead:
return
M[i],M[r] = M[r],M[i]
lv = M[r][lead]
M[r] = [ mrx / float(lv) for mrx in M[r]]
for i in range(rowCount):
if i != r:
lv = M[i][lead]
M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]
lead += 1
mtx = [
[ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[-2, 0, -3, 22],]
ToReducedRowEchelonForm( mtx )
for rw in mtx:
print ', '.join( (str(rv) for rv in rw) )
|
Change the programming language of this snippet from Groovy to VB without modifying what it does. | enum Pivoting {
NONE({ i, it -> 1 }),
PARTIAL({ i, it -> - (it[i].abs()) }),
SCALED({ i, it -> - it[i].abs()/(it.inject(0) { sum, elt -> sum + elt.abs() } ) });
public final Closure comparer
private Pivoting(Closure c) {
comparer = c
}
}
def isReducibleMatrix = { matrix ->
def m = matrix.size()
m > 1 && matrix[0].size() > m && matrix[1..<m].every { row -> row.size() == matrix[0].size() }
}
def reducedRowEchelonForm = { matrix, Pivoting pivoting = Pivoting.NONE ->
assert isReducibleMatrix(matrix)
def m = matrix.size()
def n = matrix[0].size()
(0..<m).each { i ->
matrix[i..<m].sort(pivoting.comparer.curry(i))
matrix[i][i..<n] = matrix[i][i..<n].collect { it/matrix[i][i] }
((0..<i) + ((i+1)..<m)).each { k ->
(i..<n).reverse().each { j ->
matrix[k][j] -= matrix[i][j]*matrix[k][i]
}
}
}
matrix
}
| Private Function ToReducedRowEchelonForm(M As Variant) As Variant
Dim lead As Integer: lead = 0
Dim rowCount As Integer: rowCount = UBound(M)
Dim columnCount As Integer: columnCount = UBound(M(0))
Dim i As Integer
For r = 0 To rowCount
If lead >= columnCount Then
Exit For
End If
i = r
Do While M(i)(lead) = 0
i = i + 1
If i = rowCount Then
i = r
lead = lead + 1
If lead = columnCount Then
Exit For
End If
End If
Loop
Dim tmp As Variant
tmp = M(r)
M(r) = M(i)
M(i) = tmp
If M(r)(lead) <> 0 Then
div = M(r)(lead)
For t = LBound(M(r)) To UBound(M(r))
M(r)(t) = M(r)(t) / div
Next t
End If
For j = 0 To rowCount
If j <> r Then
subt = M(j)(lead)
For t = LBound(M(j)) To UBound(M(j))
M(j)(t) = M(j)(t) - subt * M(r)(t)
Next t
End If
Next j
lead = lead + 1
Next r
ToReducedRowEchelonForm = M
End Function
Public Sub main()
r = ToReducedRowEchelonForm(Array( _
Array(1, 2, -1, -4), _
Array(2, 3, -1, -11), _
Array(-2, 0, -3, 22)))
For i = LBound(r) To UBound(r)
Debug.Print Join(r(i), vbTab)
Next i
End Sub
|
Change the programming language of this snippet from Groovy to Go without modifying what it does. | enum Pivoting {
NONE({ i, it -> 1 }),
PARTIAL({ i, it -> - (it[i].abs()) }),
SCALED({ i, it -> - it[i].abs()/(it.inject(0) { sum, elt -> sum + elt.abs() } ) });
public final Closure comparer
private Pivoting(Closure c) {
comparer = c
}
}
def isReducibleMatrix = { matrix ->
def m = matrix.size()
m > 1 && matrix[0].size() > m && matrix[1..<m].every { row -> row.size() == matrix[0].size() }
}
def reducedRowEchelonForm = { matrix, Pivoting pivoting = Pivoting.NONE ->
assert isReducibleMatrix(matrix)
def m = matrix.size()
def n = matrix[0].size()
(0..<m).each { i ->
matrix[i..<m].sort(pivoting.comparer.curry(i))
matrix[i][i..<n] = matrix[i][i..<n].collect { it/matrix[i][i] }
((0..<i) + ((i+1)..<m)).each { k ->
(i..<n).reverse().each { j ->
matrix[k][j] -= matrix[i][j]*matrix[k][i]
}
}
}
matrix
}
| package main
import "fmt"
type matrix [][]float64
func (m matrix) print() {
for _, r := range m {
fmt.Println(r)
}
fmt.Println("")
}
func main() {
m := matrix{
{ 1, 2, -1, -4},
{ 2, 3, -1, -11},
{-2, 0, -3, 22},
}
m.print()
rref(m)
m.print()
}
func rref(m matrix) {
lead := 0
rowCount := len(m)
columnCount := len(m[0])
for r := 0; r < rowCount; r++ {
if lead >= columnCount {
return
}
i := r
for m[i][lead] == 0 {
i++
if rowCount == i {
i = r
lead++
if columnCount == lead {
return
}
}
}
m[i], m[r] = m[r], m[i]
f := 1 / m[r][lead]
for j, _ := range m[r] {
m[r][j] *= f
}
for i = 0; i < rowCount; i++ {
if i != r {
f = m[i][lead]
for j, e := range m[r] {
m[i][j] -= e * f
}
}
}
lead++
}
}
|
Preserve the algorithm and functionality while converting the code from Haskell to C. | import Data.List (find)
rref :: Fractional a => [[a]] -> [[a]]
rref m = f m 0 [0 .. rows - 1]
where rows = length m
cols = length $ head m
f m _ [] = m
f m lead (r : rs)
| indices == Nothing = m
| otherwise = f m' (lead' + 1) rs
where indices = find p l
p (col, row) = m !! row !! col /= 0
l = [(col, row) |
col <- [lead .. cols - 1],
row <- [r .. rows - 1]]
Just (lead', i) = indices
newRow = map (/ m !! i !! lead') $ m !! i
m' = zipWith g [0..] $
replace r newRow $
replace i (m !! r) m
g n row
| n == r = row
| otherwise = zipWith h newRow row
where h = subtract . (* row !! lead')
replace :: Int -> a -> [a] -> [a]
replace n e l = a ++ e : b
where (a, _ : b) = splitAt n l
| #include <stdio.h>
#define TALLOC(n,typ) malloc(n*sizeof(typ))
#define EL_Type int
typedef struct sMtx {
int dim_x, dim_y;
EL_Type *m_stor;
EL_Type **mtx;
} *Matrix, sMatrix;
typedef struct sRvec {
int dim_x;
EL_Type *m_stor;
} *RowVec, sRowVec;
Matrix NewMatrix( int x_dim, int y_dim )
{
int n;
Matrix m;
m = TALLOC( 1, sMatrix);
n = x_dim * y_dim;
m->dim_x = x_dim;
m->dim_y = y_dim;
m->m_stor = TALLOC(n, EL_Type);
m->mtx = TALLOC(m->dim_y, EL_Type *);
for(n=0; n<y_dim; n++) {
m->mtx[n] = m->m_stor+n*x_dim;
}
return m;
}
void MtxSetRow(Matrix m, int irow, EL_Type *v)
{
int ix;
EL_Type *mr;
mr = m->mtx[irow];
for(ix=0; ix<m->dim_x; ix++)
mr[ix] = v[ix];
}
Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v)
{
Matrix m;
int iy;
m = NewMatrix(x_dim, y_dim);
for (iy=0; iy<y_dim; iy++)
MtxSetRow(m, iy, v[iy]);
return m;
}
void MtxDisplay( Matrix m )
{
int iy, ix;
const char *sc;
for (iy=0; iy<m->dim_y; iy++) {
printf(" ");
sc = " ";
for (ix=0; ix<m->dim_x; ix++) {
printf("%s %3d", sc, m->mtx[iy][ix]);
sc = ",";
}
printf("\n");
}
printf("\n");
}
void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr)
{
int ix;
EL_Type *drow, *srow;
drow = m->mtx[ixrdest];
srow = m->mtx[ixrsrc];
for (ix=0; ix<m->dim_x; ix++)
drow[ix] += mplr * srow[ix];
}
void MtxSwapRows( Matrix m, int rix1, int rix2)
{
EL_Type *r1, *r2, temp;
int ix;
if (rix1 == rix2) return;
r1 = m->mtx[rix1];
r2 = m->mtx[rix2];
for (ix=0; ix<m->dim_x; ix++)
temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp;
}
void MtxNormalizeRow( Matrix m, int rix, int lead)
{
int ix;
EL_Type *drow;
EL_Type lv;
drow = m->mtx[rix];
lv = drow[lead];
for (ix=0; ix<m->dim_x; ix++)
drow[ix] /= lv;
}
#define MtxGet( m, rix, cix ) m->mtx[rix][cix]
void MtxToReducedREForm(Matrix m)
{
int lead;
int rix, iix;
EL_Type lv;
int rowCount = m->dim_y;
lead = 0;
for (rix=0; rix<rowCount; rix++) {
if (lead >= m->dim_x)
return;
iix = rix;
while (0 == MtxGet(m, iix,lead)) {
iix++;
if (iix == rowCount) {
iix = rix;
lead++;
if (lead == m->dim_x)
return;
}
}
MtxSwapRows(m, iix, rix );
MtxNormalizeRow(m, rix, lead );
for (iix=0; iix<rowCount; iix++) {
if ( iix != rix ) {
lv = MtxGet(m, iix, lead );
MtxMulAndAddRows(m,iix, rix, -lv) ;
}
}
lead++;
}
}
int main()
{
Matrix m1;
static EL_Type r1[] = {1,2,-1,-4};
static EL_Type r2[] = {2,3,-1,-11};
static EL_Type r3[] = {-2,0,-3,22};
static EL_Type *im[] = { r1, r2, r3 };
m1 = InitMatrix( 4,3, im );
printf("Initial\n");
MtxDisplay(m1);
MtxToReducedREForm(m1);
printf("Reduced R-E form\n");
MtxDisplay(m1);
return 0;
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Haskell version. | import Data.List (find)
rref :: Fractional a => [[a]] -> [[a]]
rref m = f m 0 [0 .. rows - 1]
where rows = length m
cols = length $ head m
f m _ [] = m
f m lead (r : rs)
| indices == Nothing = m
| otherwise = f m' (lead' + 1) rs
where indices = find p l
p (col, row) = m !! row !! col /= 0
l = [(col, row) |
col <- [lead .. cols - 1],
row <- [r .. rows - 1]]
Just (lead', i) = indices
newRow = map (/ m !! i !! lead') $ m !! i
m' = zipWith g [0..] $
replace r newRow $
replace i (m !! r) m
g n row
| n == r = row
| otherwise = zipWith h newRow row
where h = subtract . (* row !! lead')
replace :: Int -> a -> [a] -> [a]
replace n e l = a ++ e : b
where (a, _ : b) = splitAt n l
| using System;
namespace rref
{
class Program
{
static void Main(string[] args)
{
int[,] matrix = new int[3, 4]{
{ 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 }
};
matrix = rref(matrix);
}
private static int[,] rref(int[,] matrix)
{
int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1);
for (int r = 0; r < rowCount; r++)
{
if (columnCount <= lead) break;
int i = r;
while (matrix[i, lead] == 0)
{
i++;
if (i == rowCount)
{
i = r;
lead++;
if (columnCount == lead)
{
lead--;
break;
}
}
}
for (int j = 0; j < columnCount; j++)
{
int temp = matrix[r, j];
matrix[r, j] = matrix[i, j];
matrix[i, j] = temp;
}
int div = matrix[r, lead];
if(div != 0)
for (int j = 0; j < columnCount; j++) matrix[r, j] /= div;
for (int j = 0; j < rowCount; j++)
{
if (j != r)
{
int sub = matrix[j, lead];
for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]);
}
}
lead++;
}
return matrix;
}
}
}
|
Produce a language-to-language conversion: from Haskell to C++, same semantics. | import Data.List (find)
rref :: Fractional a => [[a]] -> [[a]]
rref m = f m 0 [0 .. rows - 1]
where rows = length m
cols = length $ head m
f m _ [] = m
f m lead (r : rs)
| indices == Nothing = m
| otherwise = f m' (lead' + 1) rs
where indices = find p l
p (col, row) = m !! row !! col /= 0
l = [(col, row) |
col <- [lead .. cols - 1],
row <- [r .. rows - 1]]
Just (lead', i) = indices
newRow = map (/ m !! i !! lead') $ m !! i
m' = zipWith g [0..] $
replace r newRow $
replace i (m !! r) m
g n row
| n == r = row
| otherwise = zipWith h newRow row
where h = subtract . (* row !! lead')
replace :: Int -> a -> [a] -> [a]
replace n e l = a ++ e : b
where (a, _ : b) = splitAt n l
| #include <algorithm>
#include <cstddef>
#include <cassert>
template<typename MatrixType> struct matrix_traits
{
typedef typename MatrixType::index_type index_type;
typedef typename MatrixType::value_type value_type;
static index_type min_row(MatrixType const& A)
{ return A.min_row(); }
static index_type max_row(MatrixType const& A)
{ return A.max_row(); }
static index_type min_column(MatrixType const& A)
{ return A.min_column(); }
static index_type max_column(MatrixType const& A)
{ return A.max_column(); }
static value_type& element(MatrixType& A, index_type i, index_type k)
{ return A(i,k); }
static value_type element(MatrixType const& A, index_type i, index_type k)
{ return A(i,k); }
};
template<typename T, std::size_t rows, std::size_t columns>
struct matrix_traits<T[rows][columns]>
{
typedef std::size_t index_type;
typedef T value_type;
static index_type min_row(T const (&)[rows][columns])
{ return 0; }
static index_type max_row(T const (&)[rows][columns])
{ return rows-1; }
static index_type min_column(T const (&)[rows][columns])
{ return 0; }
static index_type max_column(T const (&)[rows][columns])
{ return columns-1; }
static value_type& element(T (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
static value_type element(T const (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
};
template<typename MatrixType>
void swap_rows(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
std::swap(mt.element(A, i, col), mt.element(A, k, col));
}
template<typename MatrixType>
void divide_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(v != 0);
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) /= v;
}
template<typename MatrixType>
void add_multiple_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) += v * mt.element(A, k, col);
}
template<typename MatrixType>
void to_reduced_row_echelon_form(MatrixType& A)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
index_type lead = mt.min_row(A);
for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row)
{
if (lead > mt.max_column(A))
return;
index_type i = row;
while (mt.element(A, i, lead) == 0)
{
++i;
if (i > mt.max_row(A))
{
i = row;
++lead;
if (lead > mt.max_column(A))
return;
}
}
swap_rows(A, i, row);
divide_row(A, row, mt.element(A, row, lead));
for (i = mt.min_row(A); i <= mt.max_row(A); ++i)
{
if (i != row)
add_multiple_row(A, i, row, -mt.element(A, i, lead));
}
}
}
#include <iostream>
int main()
{
double M[3][4] = { { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } };
to_reduced_row_echelon_form(M);
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
std::cout << M[i][j] << '\t';
std::cout << "\n";
}
return EXIT_SUCCESS;
}
|
Transform the following Haskell implementation into Java, maintaining the same output and logic. | import Data.List (find)
rref :: Fractional a => [[a]] -> [[a]]
rref m = f m 0 [0 .. rows - 1]
where rows = length m
cols = length $ head m
f m _ [] = m
f m lead (r : rs)
| indices == Nothing = m
| otherwise = f m' (lead' + 1) rs
where indices = find p l
p (col, row) = m !! row !! col /= 0
l = [(col, row) |
col <- [lead .. cols - 1],
row <- [r .. rows - 1]]
Just (lead', i) = indices
newRow = map (/ m !! i !! lead') $ m !! i
m' = zipWith g [0..] $
replace r newRow $
replace i (m !! r) m
g n row
| n == r = row
| otherwise = zipWith h newRow row
where h = subtract . (* row !! lead')
replace :: Int -> a -> [a] -> [a]
replace n e l = a ++ e : b
where (a, _ : b) = splitAt n l
| import java.util.*;
import java.lang.Math;
import org.apache.commons.math.fraction.Fraction;
import org.apache.commons.math.fraction.FractionConversionException;
class Matrix {
LinkedList<LinkedList<Fraction>> matrix;
int numRows;
int numCols;
static class Coordinate {
int row;
int col;
Coordinate(int r, int c) {
row = r;
col = c;
}
public String toString() {
return "(" + row + ", " + col + ")";
}
}
Matrix(double [][] m) {
numRows = m.length;
numCols = m[0].length;
matrix = new LinkedList<LinkedList<Fraction>>();
for (int i = 0; i < numRows; i++) {
matrix.add(new LinkedList<Fraction>());
for (int j = 0; j < numCols; j++) {
try {
matrix.get(i).add(new Fraction(m[i][j]));
} catch (FractionConversionException e) {
System.err.println("Fraction could not be converted from double by apache commons . . .");
}
}
}
}
public void Interchange(Coordinate a, Coordinate b) {
LinkedList<Fraction> temp = matrix.get(a.row);
matrix.set(a.row, matrix.get(b.row));
matrix.set(b.row, temp);
int t = a.row;
a.row = b.row;
b.row = t;
}
public void Scale(Coordinate x, Fraction d) {
LinkedList<Fraction> row = matrix.get(x.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).multiply(d));
}
}
public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) {
LinkedList<Fraction> row = matrix.get(to.row);
LinkedList<Fraction> rowMultiplied = matrix.get(from.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar))));
}
}
public void RREF() {
Coordinate pivot = new Coordinate(0,0);
int submatrix = 0;
for (int x = 0; x < numCols; x++) {
pivot = new Coordinate(pivot.row, x);
for (int i = x; i < numCols; i++) {
if (isColumnZeroes(pivot) == false) {
break;
} else {
pivot.col = i;
}
}
pivot = findPivot(pivot);
if (getCoordinate(pivot).doubleValue() == 0.0) {
pivot.row++;
continue;
}
if (pivot.row != submatrix) {
Interchange(new Coordinate(submatrix, pivot.col), pivot);
}
if (getCoordinate(pivot).doubleValue() != 1) {
Fraction scalar = getCoordinate(pivot).reciprocal();
Scale(pivot, scalar);
}
for (int i = pivot.row; i < numRows; i++) {
if (i == pivot.row) {
continue;
}
Coordinate belowPivot = new Coordinate(i, pivot.col);
Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot)));
MultiplyAndAdd(belowPivot, pivot, complement);
}
for (int i = pivot.row; i >= 0; i--) {
if (i == pivot.row) {
if (getCoordinate(pivot).doubleValue() != 1.0) {
Scale(pivot, getCoordinate(pivot).reciprocal());
}
continue;
}
if (i == pivot.row) {
continue;
}
Coordinate abovePivot = new Coordinate(i, pivot.col);
Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot)));
MultiplyAndAdd(abovePivot, pivot, complement);
}
if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) {
break;
}
submatrix++;
pivot.row++;
}
}
public boolean isColumnZeroes(Coordinate a) {
for (int i = 0; i < numRows; i++) {
if (matrix.get(i).get(a.col).doubleValue() != 0.0) {
return false;
}
}
return true;
}
public boolean isRowZeroes(Coordinate a) {
for (int i = 0; i < numCols; i++) {
if (matrix.get(a.row).get(i).doubleValue() != 0.0) {
return false;
}
}
return true;
}
public Coordinate findPivot(Coordinate a) {
int first_row = a.row;
Coordinate pivot = new Coordinate(a.row, a.col);
Coordinate current = new Coordinate(a.row, a.col);
for (int i = a.row; i < (numRows - first_row); i++) {
current.row = i;
if (getCoordinate(current).doubleValue() == 1.0) {
Interchange(current, a);
}
}
current.row = a.row;
for (int i = current.row; i < (numRows - first_row); i++) {
current.row = i;
if (getCoordinate(current).doubleValue() != 0) {
pivot.row = i;
break;
}
}
return pivot;
}
public Fraction getCoordinate(Coordinate a) {
return matrix.get(a.row).get(a.col);
}
public String toString() {
return matrix.toString().replace("], ", "]\n");
}
public static void main (String[] args) {
double[][] matrix_1 = {
{1, 2, -1, -4},
{2, 3, -1, -11},
{-2, 0, -3, 22}
};
Matrix x = new Matrix(matrix_1);
System.out.println("before\n" + x.toString() + "\n");
x.RREF();
System.out.println("after\n" + x.toString() + "\n");
double matrix_2 [][] = {
{2, 0, -1, 0, 0},
{1, 0, 0, -1, 0},
{3, 0, 0, -2, -1},
{0, 1, 0, 0, -2},
{0, 1, -1, 0, 0}
};
Matrix y = new Matrix(matrix_2);
System.out.println("before\n" + y.toString() + "\n");
y.RREF();
System.out.println("after\n" + y.toString() + "\n");
double matrix_3 [][] = {
{1, 2, 3, 4, 3, 1},
{2, 4, 6, 2, 6, 2},
{3, 6, 18, 9, 9, -6},
{4, 8, 12, 10, 12, 4},
{5, 10, 24, 11, 15, -4}
};
Matrix z = new Matrix(matrix_3);
System.out.println("before\n" + z.toString() + "\n");
z.RREF();
System.out.println("after\n" + z.toString() + "\n");
double matrix_4 [][] = {
{0, 1},
{1, 2},
{0,5}
};
Matrix a = new Matrix(matrix_4);
System.out.println("before\n" + a.toString() + "\n");
a.RREF();
System.out.println("after\n" + a.toString() + "\n");
}
}
|
Convert this Haskell snippet to Python and keep its semantics consistent. | import Data.List (find)
rref :: Fractional a => [[a]] -> [[a]]
rref m = f m 0 [0 .. rows - 1]
where rows = length m
cols = length $ head m
f m _ [] = m
f m lead (r : rs)
| indices == Nothing = m
| otherwise = f m' (lead' + 1) rs
where indices = find p l
p (col, row) = m !! row !! col /= 0
l = [(col, row) |
col <- [lead .. cols - 1],
row <- [r .. rows - 1]]
Just (lead', i) = indices
newRow = map (/ m !! i !! lead') $ m !! i
m' = zipWith g [0..] $
replace r newRow $
replace i (m !! r) m
g n row
| n == r = row
| otherwise = zipWith h newRow row
where h = subtract . (* row !! lead')
replace :: Int -> a -> [a] -> [a]
replace n e l = a ++ e : b
where (a, _ : b) = splitAt n l
| def ToReducedRowEchelonForm( M):
if not M: return
lead = 0
rowCount = len(M)
columnCount = len(M[0])
for r in range(rowCount):
if lead >= columnCount:
return
i = r
while M[i][lead] == 0:
i += 1
if i == rowCount:
i = r
lead += 1
if columnCount == lead:
return
M[i],M[r] = M[r],M[i]
lv = M[r][lead]
M[r] = [ mrx / float(lv) for mrx in M[r]]
for i in range(rowCount):
if i != r:
lv = M[i][lead]
M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]
lead += 1
mtx = [
[ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[-2, 0, -3, 22],]
ToReducedRowEchelonForm( mtx )
for rw in mtx:
print ', '.join( (str(rv) for rv in rw) )
|
Convert this Haskell block to VB, preserving its control flow and logic. | import Data.List (find)
rref :: Fractional a => [[a]] -> [[a]]
rref m = f m 0 [0 .. rows - 1]
where rows = length m
cols = length $ head m
f m _ [] = m
f m lead (r : rs)
| indices == Nothing = m
| otherwise = f m' (lead' + 1) rs
where indices = find p l
p (col, row) = m !! row !! col /= 0
l = [(col, row) |
col <- [lead .. cols - 1],
row <- [r .. rows - 1]]
Just (lead', i) = indices
newRow = map (/ m !! i !! lead') $ m !! i
m' = zipWith g [0..] $
replace r newRow $
replace i (m !! r) m
g n row
| n == r = row
| otherwise = zipWith h newRow row
where h = subtract . (* row !! lead')
replace :: Int -> a -> [a] -> [a]
replace n e l = a ++ e : b
where (a, _ : b) = splitAt n l
| Private Function ToReducedRowEchelonForm(M As Variant) As Variant
Dim lead As Integer: lead = 0
Dim rowCount As Integer: rowCount = UBound(M)
Dim columnCount As Integer: columnCount = UBound(M(0))
Dim i As Integer
For r = 0 To rowCount
If lead >= columnCount Then
Exit For
End If
i = r
Do While M(i)(lead) = 0
i = i + 1
If i = rowCount Then
i = r
lead = lead + 1
If lead = columnCount Then
Exit For
End If
End If
Loop
Dim tmp As Variant
tmp = M(r)
M(r) = M(i)
M(i) = tmp
If M(r)(lead) <> 0 Then
div = M(r)(lead)
For t = LBound(M(r)) To UBound(M(r))
M(r)(t) = M(r)(t) / div
Next t
End If
For j = 0 To rowCount
If j <> r Then
subt = M(j)(lead)
For t = LBound(M(j)) To UBound(M(j))
M(j)(t) = M(j)(t) - subt * M(r)(t)
Next t
End If
Next j
lead = lead + 1
Next r
ToReducedRowEchelonForm = M
End Function
Public Sub main()
r = ToReducedRowEchelonForm(Array( _
Array(1, 2, -1, -4), _
Array(2, 3, -1, -11), _
Array(-2, 0, -3, 22)))
For i = LBound(r) To UBound(r)
Debug.Print Join(r(i), vbTab)
Next i
End Sub
|
Convert this Haskell block to Go, preserving its control flow and logic. | import Data.List (find)
rref :: Fractional a => [[a]] -> [[a]]
rref m = f m 0 [0 .. rows - 1]
where rows = length m
cols = length $ head m
f m _ [] = m
f m lead (r : rs)
| indices == Nothing = m
| otherwise = f m' (lead' + 1) rs
where indices = find p l
p (col, row) = m !! row !! col /= 0
l = [(col, row) |
col <- [lead .. cols - 1],
row <- [r .. rows - 1]]
Just (lead', i) = indices
newRow = map (/ m !! i !! lead') $ m !! i
m' = zipWith g [0..] $
replace r newRow $
replace i (m !! r) m
g n row
| n == r = row
| otherwise = zipWith h newRow row
where h = subtract . (* row !! lead')
replace :: Int -> a -> [a] -> [a]
replace n e l = a ++ e : b
where (a, _ : b) = splitAt n l
| package main
import "fmt"
type matrix [][]float64
func (m matrix) print() {
for _, r := range m {
fmt.Println(r)
}
fmt.Println("")
}
func main() {
m := matrix{
{ 1, 2, -1, -4},
{ 2, 3, -1, -11},
{-2, 0, -3, 22},
}
m.print()
rref(m)
m.print()
}
func rref(m matrix) {
lead := 0
rowCount := len(m)
columnCount := len(m[0])
for r := 0; r < rowCount; r++ {
if lead >= columnCount {
return
}
i := r
for m[i][lead] == 0 {
i++
if rowCount == i {
i = r
lead++
if columnCount == lead {
return
}
}
}
m[i], m[r] = m[r], m[i]
f := 1 / m[r][lead]
for j, _ := range m[r] {
m[r][j] *= f
}
for i = 0; i < rowCount; i++ {
if i != r {
f = m[i][lead]
for j, e := range m[r] {
m[i][j] -= e * f
}
}
}
lead++
}
}
|
Produce a functionally identical C code for the snippet given in J. | require 'math/misc/linear'
]A=: 1 2 _1 _4 , 2 3 _1 _11 ,: _2 0 _3 22
1 2 _1 _4
2 3 _1 _11
_2 0 _3 22
gauss_jordan A
1 0 0 _8
0 1 0 1
0 0 1 _2
| #include <stdio.h>
#define TALLOC(n,typ) malloc(n*sizeof(typ))
#define EL_Type int
typedef struct sMtx {
int dim_x, dim_y;
EL_Type *m_stor;
EL_Type **mtx;
} *Matrix, sMatrix;
typedef struct sRvec {
int dim_x;
EL_Type *m_stor;
} *RowVec, sRowVec;
Matrix NewMatrix( int x_dim, int y_dim )
{
int n;
Matrix m;
m = TALLOC( 1, sMatrix);
n = x_dim * y_dim;
m->dim_x = x_dim;
m->dim_y = y_dim;
m->m_stor = TALLOC(n, EL_Type);
m->mtx = TALLOC(m->dim_y, EL_Type *);
for(n=0; n<y_dim; n++) {
m->mtx[n] = m->m_stor+n*x_dim;
}
return m;
}
void MtxSetRow(Matrix m, int irow, EL_Type *v)
{
int ix;
EL_Type *mr;
mr = m->mtx[irow];
for(ix=0; ix<m->dim_x; ix++)
mr[ix] = v[ix];
}
Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v)
{
Matrix m;
int iy;
m = NewMatrix(x_dim, y_dim);
for (iy=0; iy<y_dim; iy++)
MtxSetRow(m, iy, v[iy]);
return m;
}
void MtxDisplay( Matrix m )
{
int iy, ix;
const char *sc;
for (iy=0; iy<m->dim_y; iy++) {
printf(" ");
sc = " ";
for (ix=0; ix<m->dim_x; ix++) {
printf("%s %3d", sc, m->mtx[iy][ix]);
sc = ",";
}
printf("\n");
}
printf("\n");
}
void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr)
{
int ix;
EL_Type *drow, *srow;
drow = m->mtx[ixrdest];
srow = m->mtx[ixrsrc];
for (ix=0; ix<m->dim_x; ix++)
drow[ix] += mplr * srow[ix];
}
void MtxSwapRows( Matrix m, int rix1, int rix2)
{
EL_Type *r1, *r2, temp;
int ix;
if (rix1 == rix2) return;
r1 = m->mtx[rix1];
r2 = m->mtx[rix2];
for (ix=0; ix<m->dim_x; ix++)
temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp;
}
void MtxNormalizeRow( Matrix m, int rix, int lead)
{
int ix;
EL_Type *drow;
EL_Type lv;
drow = m->mtx[rix];
lv = drow[lead];
for (ix=0; ix<m->dim_x; ix++)
drow[ix] /= lv;
}
#define MtxGet( m, rix, cix ) m->mtx[rix][cix]
void MtxToReducedREForm(Matrix m)
{
int lead;
int rix, iix;
EL_Type lv;
int rowCount = m->dim_y;
lead = 0;
for (rix=0; rix<rowCount; rix++) {
if (lead >= m->dim_x)
return;
iix = rix;
while (0 == MtxGet(m, iix,lead)) {
iix++;
if (iix == rowCount) {
iix = rix;
lead++;
if (lead == m->dim_x)
return;
}
}
MtxSwapRows(m, iix, rix );
MtxNormalizeRow(m, rix, lead );
for (iix=0; iix<rowCount; iix++) {
if ( iix != rix ) {
lv = MtxGet(m, iix, lead );
MtxMulAndAddRows(m,iix, rix, -lv) ;
}
}
lead++;
}
}
int main()
{
Matrix m1;
static EL_Type r1[] = {1,2,-1,-4};
static EL_Type r2[] = {2,3,-1,-11};
static EL_Type r3[] = {-2,0,-3,22};
static EL_Type *im[] = { r1, r2, r3 };
m1 = InitMatrix( 4,3, im );
printf("Initial\n");
MtxDisplay(m1);
MtxToReducedREForm(m1);
printf("Reduced R-E form\n");
MtxDisplay(m1);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from J to C#. | require 'math/misc/linear'
]A=: 1 2 _1 _4 , 2 3 _1 _11 ,: _2 0 _3 22
1 2 _1 _4
2 3 _1 _11
_2 0 _3 22
gauss_jordan A
1 0 0 _8
0 1 0 1
0 0 1 _2
| using System;
namespace rref
{
class Program
{
static void Main(string[] args)
{
int[,] matrix = new int[3, 4]{
{ 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 }
};
matrix = rref(matrix);
}
private static int[,] rref(int[,] matrix)
{
int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1);
for (int r = 0; r < rowCount; r++)
{
if (columnCount <= lead) break;
int i = r;
while (matrix[i, lead] == 0)
{
i++;
if (i == rowCount)
{
i = r;
lead++;
if (columnCount == lead)
{
lead--;
break;
}
}
}
for (int j = 0; j < columnCount; j++)
{
int temp = matrix[r, j];
matrix[r, j] = matrix[i, j];
matrix[i, j] = temp;
}
int div = matrix[r, lead];
if(div != 0)
for (int j = 0; j < columnCount; j++) matrix[r, j] /= div;
for (int j = 0; j < rowCount; j++)
{
if (j != r)
{
int sub = matrix[j, lead];
for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]);
}
}
lead++;
}
return matrix;
}
}
}
|
Please provide an equivalent version of this J code in C++. | require 'math/misc/linear'
]A=: 1 2 _1 _4 , 2 3 _1 _11 ,: _2 0 _3 22
1 2 _1 _4
2 3 _1 _11
_2 0 _3 22
gauss_jordan A
1 0 0 _8
0 1 0 1
0 0 1 _2
| #include <algorithm>
#include <cstddef>
#include <cassert>
template<typename MatrixType> struct matrix_traits
{
typedef typename MatrixType::index_type index_type;
typedef typename MatrixType::value_type value_type;
static index_type min_row(MatrixType const& A)
{ return A.min_row(); }
static index_type max_row(MatrixType const& A)
{ return A.max_row(); }
static index_type min_column(MatrixType const& A)
{ return A.min_column(); }
static index_type max_column(MatrixType const& A)
{ return A.max_column(); }
static value_type& element(MatrixType& A, index_type i, index_type k)
{ return A(i,k); }
static value_type element(MatrixType const& A, index_type i, index_type k)
{ return A(i,k); }
};
template<typename T, std::size_t rows, std::size_t columns>
struct matrix_traits<T[rows][columns]>
{
typedef std::size_t index_type;
typedef T value_type;
static index_type min_row(T const (&)[rows][columns])
{ return 0; }
static index_type max_row(T const (&)[rows][columns])
{ return rows-1; }
static index_type min_column(T const (&)[rows][columns])
{ return 0; }
static index_type max_column(T const (&)[rows][columns])
{ return columns-1; }
static value_type& element(T (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
static value_type element(T const (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
};
template<typename MatrixType>
void swap_rows(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
std::swap(mt.element(A, i, col), mt.element(A, k, col));
}
template<typename MatrixType>
void divide_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(v != 0);
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) /= v;
}
template<typename MatrixType>
void add_multiple_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) += v * mt.element(A, k, col);
}
template<typename MatrixType>
void to_reduced_row_echelon_form(MatrixType& A)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
index_type lead = mt.min_row(A);
for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row)
{
if (lead > mt.max_column(A))
return;
index_type i = row;
while (mt.element(A, i, lead) == 0)
{
++i;
if (i > mt.max_row(A))
{
i = row;
++lead;
if (lead > mt.max_column(A))
return;
}
}
swap_rows(A, i, row);
divide_row(A, row, mt.element(A, row, lead));
for (i = mt.min_row(A); i <= mt.max_row(A); ++i)
{
if (i != row)
add_multiple_row(A, i, row, -mt.element(A, i, lead));
}
}
}
#include <iostream>
int main()
{
double M[3][4] = { { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } };
to_reduced_row_echelon_form(M);
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
std::cout << M[i][j] << '\t';
std::cout << "\n";
}
return EXIT_SUCCESS;
}
|
Generate an equivalent Java version of this J code. | require 'math/misc/linear'
]A=: 1 2 _1 _4 , 2 3 _1 _11 ,: _2 0 _3 22
1 2 _1 _4
2 3 _1 _11
_2 0 _3 22
gauss_jordan A
1 0 0 _8
0 1 0 1
0 0 1 _2
| import java.util.*;
import java.lang.Math;
import org.apache.commons.math.fraction.Fraction;
import org.apache.commons.math.fraction.FractionConversionException;
class Matrix {
LinkedList<LinkedList<Fraction>> matrix;
int numRows;
int numCols;
static class Coordinate {
int row;
int col;
Coordinate(int r, int c) {
row = r;
col = c;
}
public String toString() {
return "(" + row + ", " + col + ")";
}
}
Matrix(double [][] m) {
numRows = m.length;
numCols = m[0].length;
matrix = new LinkedList<LinkedList<Fraction>>();
for (int i = 0; i < numRows; i++) {
matrix.add(new LinkedList<Fraction>());
for (int j = 0; j < numCols; j++) {
try {
matrix.get(i).add(new Fraction(m[i][j]));
} catch (FractionConversionException e) {
System.err.println("Fraction could not be converted from double by apache commons . . .");
}
}
}
}
public void Interchange(Coordinate a, Coordinate b) {
LinkedList<Fraction> temp = matrix.get(a.row);
matrix.set(a.row, matrix.get(b.row));
matrix.set(b.row, temp);
int t = a.row;
a.row = b.row;
b.row = t;
}
public void Scale(Coordinate x, Fraction d) {
LinkedList<Fraction> row = matrix.get(x.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).multiply(d));
}
}
public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) {
LinkedList<Fraction> row = matrix.get(to.row);
LinkedList<Fraction> rowMultiplied = matrix.get(from.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar))));
}
}
public void RREF() {
Coordinate pivot = new Coordinate(0,0);
int submatrix = 0;
for (int x = 0; x < numCols; x++) {
pivot = new Coordinate(pivot.row, x);
for (int i = x; i < numCols; i++) {
if (isColumnZeroes(pivot) == false) {
break;
} else {
pivot.col = i;
}
}
pivot = findPivot(pivot);
if (getCoordinate(pivot).doubleValue() == 0.0) {
pivot.row++;
continue;
}
if (pivot.row != submatrix) {
Interchange(new Coordinate(submatrix, pivot.col), pivot);
}
if (getCoordinate(pivot).doubleValue() != 1) {
Fraction scalar = getCoordinate(pivot).reciprocal();
Scale(pivot, scalar);
}
for (int i = pivot.row; i < numRows; i++) {
if (i == pivot.row) {
continue;
}
Coordinate belowPivot = new Coordinate(i, pivot.col);
Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot)));
MultiplyAndAdd(belowPivot, pivot, complement);
}
for (int i = pivot.row; i >= 0; i--) {
if (i == pivot.row) {
if (getCoordinate(pivot).doubleValue() != 1.0) {
Scale(pivot, getCoordinate(pivot).reciprocal());
}
continue;
}
if (i == pivot.row) {
continue;
}
Coordinate abovePivot = new Coordinate(i, pivot.col);
Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot)));
MultiplyAndAdd(abovePivot, pivot, complement);
}
if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) {
break;
}
submatrix++;
pivot.row++;
}
}
public boolean isColumnZeroes(Coordinate a) {
for (int i = 0; i < numRows; i++) {
if (matrix.get(i).get(a.col).doubleValue() != 0.0) {
return false;
}
}
return true;
}
public boolean isRowZeroes(Coordinate a) {
for (int i = 0; i < numCols; i++) {
if (matrix.get(a.row).get(i).doubleValue() != 0.0) {
return false;
}
}
return true;
}
public Coordinate findPivot(Coordinate a) {
int first_row = a.row;
Coordinate pivot = new Coordinate(a.row, a.col);
Coordinate current = new Coordinate(a.row, a.col);
for (int i = a.row; i < (numRows - first_row); i++) {
current.row = i;
if (getCoordinate(current).doubleValue() == 1.0) {
Interchange(current, a);
}
}
current.row = a.row;
for (int i = current.row; i < (numRows - first_row); i++) {
current.row = i;
if (getCoordinate(current).doubleValue() != 0) {
pivot.row = i;
break;
}
}
return pivot;
}
public Fraction getCoordinate(Coordinate a) {
return matrix.get(a.row).get(a.col);
}
public String toString() {
return matrix.toString().replace("], ", "]\n");
}
public static void main (String[] args) {
double[][] matrix_1 = {
{1, 2, -1, -4},
{2, 3, -1, -11},
{-2, 0, -3, 22}
};
Matrix x = new Matrix(matrix_1);
System.out.println("before\n" + x.toString() + "\n");
x.RREF();
System.out.println("after\n" + x.toString() + "\n");
double matrix_2 [][] = {
{2, 0, -1, 0, 0},
{1, 0, 0, -1, 0},
{3, 0, 0, -2, -1},
{0, 1, 0, 0, -2},
{0, 1, -1, 0, 0}
};
Matrix y = new Matrix(matrix_2);
System.out.println("before\n" + y.toString() + "\n");
y.RREF();
System.out.println("after\n" + y.toString() + "\n");
double matrix_3 [][] = {
{1, 2, 3, 4, 3, 1},
{2, 4, 6, 2, 6, 2},
{3, 6, 18, 9, 9, -6},
{4, 8, 12, 10, 12, 4},
{5, 10, 24, 11, 15, -4}
};
Matrix z = new Matrix(matrix_3);
System.out.println("before\n" + z.toString() + "\n");
z.RREF();
System.out.println("after\n" + z.toString() + "\n");
double matrix_4 [][] = {
{0, 1},
{1, 2},
{0,5}
};
Matrix a = new Matrix(matrix_4);
System.out.println("before\n" + a.toString() + "\n");
a.RREF();
System.out.println("after\n" + a.toString() + "\n");
}
}
|
Convert the following code from J to Python, ensuring the logic remains intact. | require 'math/misc/linear'
]A=: 1 2 _1 _4 , 2 3 _1 _11 ,: _2 0 _3 22
1 2 _1 _4
2 3 _1 _11
_2 0 _3 22
gauss_jordan A
1 0 0 _8
0 1 0 1
0 0 1 _2
| def ToReducedRowEchelonForm( M):
if not M: return
lead = 0
rowCount = len(M)
columnCount = len(M[0])
for r in range(rowCount):
if lead >= columnCount:
return
i = r
while M[i][lead] == 0:
i += 1
if i == rowCount:
i = r
lead += 1
if columnCount == lead:
return
M[i],M[r] = M[r],M[i]
lv = M[r][lead]
M[r] = [ mrx / float(lv) for mrx in M[r]]
for i in range(rowCount):
if i != r:
lv = M[i][lead]
M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]
lead += 1
mtx = [
[ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[-2, 0, -3, 22],]
ToReducedRowEchelonForm( mtx )
for rw in mtx:
print ', '.join( (str(rv) for rv in rw) )
|
Can you help me rewrite this code in VB instead of J, keeping it the same logically? | require 'math/misc/linear'
]A=: 1 2 _1 _4 , 2 3 _1 _11 ,: _2 0 _3 22
1 2 _1 _4
2 3 _1 _11
_2 0 _3 22
gauss_jordan A
1 0 0 _8
0 1 0 1
0 0 1 _2
| Private Function ToReducedRowEchelonForm(M As Variant) As Variant
Dim lead As Integer: lead = 0
Dim rowCount As Integer: rowCount = UBound(M)
Dim columnCount As Integer: columnCount = UBound(M(0))
Dim i As Integer
For r = 0 To rowCount
If lead >= columnCount Then
Exit For
End If
i = r
Do While M(i)(lead) = 0
i = i + 1
If i = rowCount Then
i = r
lead = lead + 1
If lead = columnCount Then
Exit For
End If
End If
Loop
Dim tmp As Variant
tmp = M(r)
M(r) = M(i)
M(i) = tmp
If M(r)(lead) <> 0 Then
div = M(r)(lead)
For t = LBound(M(r)) To UBound(M(r))
M(r)(t) = M(r)(t) / div
Next t
End If
For j = 0 To rowCount
If j <> r Then
subt = M(j)(lead)
For t = LBound(M(j)) To UBound(M(j))
M(j)(t) = M(j)(t) - subt * M(r)(t)
Next t
End If
Next j
lead = lead + 1
Next r
ToReducedRowEchelonForm = M
End Function
Public Sub main()
r = ToReducedRowEchelonForm(Array( _
Array(1, 2, -1, -4), _
Array(2, 3, -1, -11), _
Array(-2, 0, -3, 22)))
For i = LBound(r) To UBound(r)
Debug.Print Join(r(i), vbTab)
Next i
End Sub
|
Can you help me rewrite this code in Go instead of J, keeping it the same logically? | require 'math/misc/linear'
]A=: 1 2 _1 _4 , 2 3 _1 _11 ,: _2 0 _3 22
1 2 _1 _4
2 3 _1 _11
_2 0 _3 22
gauss_jordan A
1 0 0 _8
0 1 0 1
0 0 1 _2
| package main
import "fmt"
type matrix [][]float64
func (m matrix) print() {
for _, r := range m {
fmt.Println(r)
}
fmt.Println("")
}
func main() {
m := matrix{
{ 1, 2, -1, -4},
{ 2, 3, -1, -11},
{-2, 0, -3, 22},
}
m.print()
rref(m)
m.print()
}
func rref(m matrix) {
lead := 0
rowCount := len(m)
columnCount := len(m[0])
for r := 0; r < rowCount; r++ {
if lead >= columnCount {
return
}
i := r
for m[i][lead] == 0 {
i++
if rowCount == i {
i = r
lead++
if columnCount == lead {
return
}
}
}
m[i], m[r] = m[r], m[i]
f := 1 / m[r][lead]
for j, _ := range m[r] {
m[r][j] *= f
}
for i = 0; i < rowCount; i++ {
if i != r {
f = m[i][lead]
for j, e := range m[r] {
m[i][j] -= e * f
}
}
}
lead++
}
}
|
Convert the following code from Lua to C, ensuring the logic remains intact. | function ToReducedRowEchelonForm ( M )
local lead = 1
local n_rows, n_cols = #M, #M[1]
for r = 1, n_rows do
if n_cols <= lead then break end
local i = r
while M[i][lead] == 0 do
i = i + 1
if n_rows == i then
i = r
lead = lead + 1
if n_cols == lead then break end
end
end
M[i], M[r] = M[r], M[i]
local m = M[r][lead]
for k = 1, n_cols do
M[r][k] = M[r][k] / m
end
for i = 1, n_rows do
if i ~= r then
local m = M[i][lead]
for k = 1, n_cols do
M[i][k] = M[i][k] - m * M[r][k]
end
end
end
lead = lead + 1
end
end
M = { { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } }
res = ToReducedRowEchelonForm( M )
for i = 1, #M do
for j = 1, #M[1] do
io.write( M[i][j], " " )
end
io.write( "\n" )
end
| #include <stdio.h>
#define TALLOC(n,typ) malloc(n*sizeof(typ))
#define EL_Type int
typedef struct sMtx {
int dim_x, dim_y;
EL_Type *m_stor;
EL_Type **mtx;
} *Matrix, sMatrix;
typedef struct sRvec {
int dim_x;
EL_Type *m_stor;
} *RowVec, sRowVec;
Matrix NewMatrix( int x_dim, int y_dim )
{
int n;
Matrix m;
m = TALLOC( 1, sMatrix);
n = x_dim * y_dim;
m->dim_x = x_dim;
m->dim_y = y_dim;
m->m_stor = TALLOC(n, EL_Type);
m->mtx = TALLOC(m->dim_y, EL_Type *);
for(n=0; n<y_dim; n++) {
m->mtx[n] = m->m_stor+n*x_dim;
}
return m;
}
void MtxSetRow(Matrix m, int irow, EL_Type *v)
{
int ix;
EL_Type *mr;
mr = m->mtx[irow];
for(ix=0; ix<m->dim_x; ix++)
mr[ix] = v[ix];
}
Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v)
{
Matrix m;
int iy;
m = NewMatrix(x_dim, y_dim);
for (iy=0; iy<y_dim; iy++)
MtxSetRow(m, iy, v[iy]);
return m;
}
void MtxDisplay( Matrix m )
{
int iy, ix;
const char *sc;
for (iy=0; iy<m->dim_y; iy++) {
printf(" ");
sc = " ";
for (ix=0; ix<m->dim_x; ix++) {
printf("%s %3d", sc, m->mtx[iy][ix]);
sc = ",";
}
printf("\n");
}
printf("\n");
}
void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr)
{
int ix;
EL_Type *drow, *srow;
drow = m->mtx[ixrdest];
srow = m->mtx[ixrsrc];
for (ix=0; ix<m->dim_x; ix++)
drow[ix] += mplr * srow[ix];
}
void MtxSwapRows( Matrix m, int rix1, int rix2)
{
EL_Type *r1, *r2, temp;
int ix;
if (rix1 == rix2) return;
r1 = m->mtx[rix1];
r2 = m->mtx[rix2];
for (ix=0; ix<m->dim_x; ix++)
temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp;
}
void MtxNormalizeRow( Matrix m, int rix, int lead)
{
int ix;
EL_Type *drow;
EL_Type lv;
drow = m->mtx[rix];
lv = drow[lead];
for (ix=0; ix<m->dim_x; ix++)
drow[ix] /= lv;
}
#define MtxGet( m, rix, cix ) m->mtx[rix][cix]
void MtxToReducedREForm(Matrix m)
{
int lead;
int rix, iix;
EL_Type lv;
int rowCount = m->dim_y;
lead = 0;
for (rix=0; rix<rowCount; rix++) {
if (lead >= m->dim_x)
return;
iix = rix;
while (0 == MtxGet(m, iix,lead)) {
iix++;
if (iix == rowCount) {
iix = rix;
lead++;
if (lead == m->dim_x)
return;
}
}
MtxSwapRows(m, iix, rix );
MtxNormalizeRow(m, rix, lead );
for (iix=0; iix<rowCount; iix++) {
if ( iix != rix ) {
lv = MtxGet(m, iix, lead );
MtxMulAndAddRows(m,iix, rix, -lv) ;
}
}
lead++;
}
}
int main()
{
Matrix m1;
static EL_Type r1[] = {1,2,-1,-4};
static EL_Type r2[] = {2,3,-1,-11};
static EL_Type r3[] = {-2,0,-3,22};
static EL_Type *im[] = { r1, r2, r3 };
m1 = InitMatrix( 4,3, im );
printf("Initial\n");
MtxDisplay(m1);
MtxToReducedREForm(m1);
printf("Reduced R-E form\n");
MtxDisplay(m1);
return 0;
}
|
Ensure the translated C# code behaves exactly like the original Lua snippet. | function ToReducedRowEchelonForm ( M )
local lead = 1
local n_rows, n_cols = #M, #M[1]
for r = 1, n_rows do
if n_cols <= lead then break end
local i = r
while M[i][lead] == 0 do
i = i + 1
if n_rows == i then
i = r
lead = lead + 1
if n_cols == lead then break end
end
end
M[i], M[r] = M[r], M[i]
local m = M[r][lead]
for k = 1, n_cols do
M[r][k] = M[r][k] / m
end
for i = 1, n_rows do
if i ~= r then
local m = M[i][lead]
for k = 1, n_cols do
M[i][k] = M[i][k] - m * M[r][k]
end
end
end
lead = lead + 1
end
end
M = { { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } }
res = ToReducedRowEchelonForm( M )
for i = 1, #M do
for j = 1, #M[1] do
io.write( M[i][j], " " )
end
io.write( "\n" )
end
| using System;
namespace rref
{
class Program
{
static void Main(string[] args)
{
int[,] matrix = new int[3, 4]{
{ 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 }
};
matrix = rref(matrix);
}
private static int[,] rref(int[,] matrix)
{
int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1);
for (int r = 0; r < rowCount; r++)
{
if (columnCount <= lead) break;
int i = r;
while (matrix[i, lead] == 0)
{
i++;
if (i == rowCount)
{
i = r;
lead++;
if (columnCount == lead)
{
lead--;
break;
}
}
}
for (int j = 0; j < columnCount; j++)
{
int temp = matrix[r, j];
matrix[r, j] = matrix[i, j];
matrix[i, j] = temp;
}
int div = matrix[r, lead];
if(div != 0)
for (int j = 0; j < columnCount; j++) matrix[r, j] /= div;
for (int j = 0; j < rowCount; j++)
{
if (j != r)
{
int sub = matrix[j, lead];
for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]);
}
}
lead++;
}
return matrix;
}
}
}
|
Generate an equivalent C++ version of this Lua code. | function ToReducedRowEchelonForm ( M )
local lead = 1
local n_rows, n_cols = #M, #M[1]
for r = 1, n_rows do
if n_cols <= lead then break end
local i = r
while M[i][lead] == 0 do
i = i + 1
if n_rows == i then
i = r
lead = lead + 1
if n_cols == lead then break end
end
end
M[i], M[r] = M[r], M[i]
local m = M[r][lead]
for k = 1, n_cols do
M[r][k] = M[r][k] / m
end
for i = 1, n_rows do
if i ~= r then
local m = M[i][lead]
for k = 1, n_cols do
M[i][k] = M[i][k] - m * M[r][k]
end
end
end
lead = lead + 1
end
end
M = { { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } }
res = ToReducedRowEchelonForm( M )
for i = 1, #M do
for j = 1, #M[1] do
io.write( M[i][j], " " )
end
io.write( "\n" )
end
| #include <algorithm>
#include <cstddef>
#include <cassert>
template<typename MatrixType> struct matrix_traits
{
typedef typename MatrixType::index_type index_type;
typedef typename MatrixType::value_type value_type;
static index_type min_row(MatrixType const& A)
{ return A.min_row(); }
static index_type max_row(MatrixType const& A)
{ return A.max_row(); }
static index_type min_column(MatrixType const& A)
{ return A.min_column(); }
static index_type max_column(MatrixType const& A)
{ return A.max_column(); }
static value_type& element(MatrixType& A, index_type i, index_type k)
{ return A(i,k); }
static value_type element(MatrixType const& A, index_type i, index_type k)
{ return A(i,k); }
};
template<typename T, std::size_t rows, std::size_t columns>
struct matrix_traits<T[rows][columns]>
{
typedef std::size_t index_type;
typedef T value_type;
static index_type min_row(T const (&)[rows][columns])
{ return 0; }
static index_type max_row(T const (&)[rows][columns])
{ return rows-1; }
static index_type min_column(T const (&)[rows][columns])
{ return 0; }
static index_type max_column(T const (&)[rows][columns])
{ return columns-1; }
static value_type& element(T (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
static value_type element(T const (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
};
template<typename MatrixType>
void swap_rows(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
std::swap(mt.element(A, i, col), mt.element(A, k, col));
}
template<typename MatrixType>
void divide_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(v != 0);
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) /= v;
}
template<typename MatrixType>
void add_multiple_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) += v * mt.element(A, k, col);
}
template<typename MatrixType>
void to_reduced_row_echelon_form(MatrixType& A)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
index_type lead = mt.min_row(A);
for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row)
{
if (lead > mt.max_column(A))
return;
index_type i = row;
while (mt.element(A, i, lead) == 0)
{
++i;
if (i > mt.max_row(A))
{
i = row;
++lead;
if (lead > mt.max_column(A))
return;
}
}
swap_rows(A, i, row);
divide_row(A, row, mt.element(A, row, lead));
for (i = mt.min_row(A); i <= mt.max_row(A); ++i)
{
if (i != row)
add_multiple_row(A, i, row, -mt.element(A, i, lead));
}
}
}
#include <iostream>
int main()
{
double M[3][4] = { { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } };
to_reduced_row_echelon_form(M);
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
std::cout << M[i][j] << '\t';
std::cout << "\n";
}
return EXIT_SUCCESS;
}
|
Rewrite the snippet below in Java so it works the same as the original Lua code. | function ToReducedRowEchelonForm ( M )
local lead = 1
local n_rows, n_cols = #M, #M[1]
for r = 1, n_rows do
if n_cols <= lead then break end
local i = r
while M[i][lead] == 0 do
i = i + 1
if n_rows == i then
i = r
lead = lead + 1
if n_cols == lead then break end
end
end
M[i], M[r] = M[r], M[i]
local m = M[r][lead]
for k = 1, n_cols do
M[r][k] = M[r][k] / m
end
for i = 1, n_rows do
if i ~= r then
local m = M[i][lead]
for k = 1, n_cols do
M[i][k] = M[i][k] - m * M[r][k]
end
end
end
lead = lead + 1
end
end
M = { { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } }
res = ToReducedRowEchelonForm( M )
for i = 1, #M do
for j = 1, #M[1] do
io.write( M[i][j], " " )
end
io.write( "\n" )
end
| import java.util.*;
import java.lang.Math;
import org.apache.commons.math.fraction.Fraction;
import org.apache.commons.math.fraction.FractionConversionException;
class Matrix {
LinkedList<LinkedList<Fraction>> matrix;
int numRows;
int numCols;
static class Coordinate {
int row;
int col;
Coordinate(int r, int c) {
row = r;
col = c;
}
public String toString() {
return "(" + row + ", " + col + ")";
}
}
Matrix(double [][] m) {
numRows = m.length;
numCols = m[0].length;
matrix = new LinkedList<LinkedList<Fraction>>();
for (int i = 0; i < numRows; i++) {
matrix.add(new LinkedList<Fraction>());
for (int j = 0; j < numCols; j++) {
try {
matrix.get(i).add(new Fraction(m[i][j]));
} catch (FractionConversionException e) {
System.err.println("Fraction could not be converted from double by apache commons . . .");
}
}
}
}
public void Interchange(Coordinate a, Coordinate b) {
LinkedList<Fraction> temp = matrix.get(a.row);
matrix.set(a.row, matrix.get(b.row));
matrix.set(b.row, temp);
int t = a.row;
a.row = b.row;
b.row = t;
}
public void Scale(Coordinate x, Fraction d) {
LinkedList<Fraction> row = matrix.get(x.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).multiply(d));
}
}
public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) {
LinkedList<Fraction> row = matrix.get(to.row);
LinkedList<Fraction> rowMultiplied = matrix.get(from.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar))));
}
}
public void RREF() {
Coordinate pivot = new Coordinate(0,0);
int submatrix = 0;
for (int x = 0; x < numCols; x++) {
pivot = new Coordinate(pivot.row, x);
for (int i = x; i < numCols; i++) {
if (isColumnZeroes(pivot) == false) {
break;
} else {
pivot.col = i;
}
}
pivot = findPivot(pivot);
if (getCoordinate(pivot).doubleValue() == 0.0) {
pivot.row++;
continue;
}
if (pivot.row != submatrix) {
Interchange(new Coordinate(submatrix, pivot.col), pivot);
}
if (getCoordinate(pivot).doubleValue() != 1) {
Fraction scalar = getCoordinate(pivot).reciprocal();
Scale(pivot, scalar);
}
for (int i = pivot.row; i < numRows; i++) {
if (i == pivot.row) {
continue;
}
Coordinate belowPivot = new Coordinate(i, pivot.col);
Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot)));
MultiplyAndAdd(belowPivot, pivot, complement);
}
for (int i = pivot.row; i >= 0; i--) {
if (i == pivot.row) {
if (getCoordinate(pivot).doubleValue() != 1.0) {
Scale(pivot, getCoordinate(pivot).reciprocal());
}
continue;
}
if (i == pivot.row) {
continue;
}
Coordinate abovePivot = new Coordinate(i, pivot.col);
Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot)));
MultiplyAndAdd(abovePivot, pivot, complement);
}
if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) {
break;
}
submatrix++;
pivot.row++;
}
}
public boolean isColumnZeroes(Coordinate a) {
for (int i = 0; i < numRows; i++) {
if (matrix.get(i).get(a.col).doubleValue() != 0.0) {
return false;
}
}
return true;
}
public boolean isRowZeroes(Coordinate a) {
for (int i = 0; i < numCols; i++) {
if (matrix.get(a.row).get(i).doubleValue() != 0.0) {
return false;
}
}
return true;
}
public Coordinate findPivot(Coordinate a) {
int first_row = a.row;
Coordinate pivot = new Coordinate(a.row, a.col);
Coordinate current = new Coordinate(a.row, a.col);
for (int i = a.row; i < (numRows - first_row); i++) {
current.row = i;
if (getCoordinate(current).doubleValue() == 1.0) {
Interchange(current, a);
}
}
current.row = a.row;
for (int i = current.row; i < (numRows - first_row); i++) {
current.row = i;
if (getCoordinate(current).doubleValue() != 0) {
pivot.row = i;
break;
}
}
return pivot;
}
public Fraction getCoordinate(Coordinate a) {
return matrix.get(a.row).get(a.col);
}
public String toString() {
return matrix.toString().replace("], ", "]\n");
}
public static void main (String[] args) {
double[][] matrix_1 = {
{1, 2, -1, -4},
{2, 3, -1, -11},
{-2, 0, -3, 22}
};
Matrix x = new Matrix(matrix_1);
System.out.println("before\n" + x.toString() + "\n");
x.RREF();
System.out.println("after\n" + x.toString() + "\n");
double matrix_2 [][] = {
{2, 0, -1, 0, 0},
{1, 0, 0, -1, 0},
{3, 0, 0, -2, -1},
{0, 1, 0, 0, -2},
{0, 1, -1, 0, 0}
};
Matrix y = new Matrix(matrix_2);
System.out.println("before\n" + y.toString() + "\n");
y.RREF();
System.out.println("after\n" + y.toString() + "\n");
double matrix_3 [][] = {
{1, 2, 3, 4, 3, 1},
{2, 4, 6, 2, 6, 2},
{3, 6, 18, 9, 9, -6},
{4, 8, 12, 10, 12, 4},
{5, 10, 24, 11, 15, -4}
};
Matrix z = new Matrix(matrix_3);
System.out.println("before\n" + z.toString() + "\n");
z.RREF();
System.out.println("after\n" + z.toString() + "\n");
double matrix_4 [][] = {
{0, 1},
{1, 2},
{0,5}
};
Matrix a = new Matrix(matrix_4);
System.out.println("before\n" + a.toString() + "\n");
a.RREF();
System.out.println("after\n" + a.toString() + "\n");
}
}
|
Port the provided Lua code into Python while preserving the original functionality. | function ToReducedRowEchelonForm ( M )
local lead = 1
local n_rows, n_cols = #M, #M[1]
for r = 1, n_rows do
if n_cols <= lead then break end
local i = r
while M[i][lead] == 0 do
i = i + 1
if n_rows == i then
i = r
lead = lead + 1
if n_cols == lead then break end
end
end
M[i], M[r] = M[r], M[i]
local m = M[r][lead]
for k = 1, n_cols do
M[r][k] = M[r][k] / m
end
for i = 1, n_rows do
if i ~= r then
local m = M[i][lead]
for k = 1, n_cols do
M[i][k] = M[i][k] - m * M[r][k]
end
end
end
lead = lead + 1
end
end
M = { { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } }
res = ToReducedRowEchelonForm( M )
for i = 1, #M do
for j = 1, #M[1] do
io.write( M[i][j], " " )
end
io.write( "\n" )
end
| def ToReducedRowEchelonForm( M):
if not M: return
lead = 0
rowCount = len(M)
columnCount = len(M[0])
for r in range(rowCount):
if lead >= columnCount:
return
i = r
while M[i][lead] == 0:
i += 1
if i == rowCount:
i = r
lead += 1
if columnCount == lead:
return
M[i],M[r] = M[r],M[i]
lv = M[r][lead]
M[r] = [ mrx / float(lv) for mrx in M[r]]
for i in range(rowCount):
if i != r:
lv = M[i][lead]
M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]
lead += 1
mtx = [
[ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[-2, 0, -3, 22],]
ToReducedRowEchelonForm( mtx )
for rw in mtx:
print ', '.join( (str(rv) for rv in rw) )
|
Preserve the algorithm and functionality while converting the code from Lua to VB. | function ToReducedRowEchelonForm ( M )
local lead = 1
local n_rows, n_cols = #M, #M[1]
for r = 1, n_rows do
if n_cols <= lead then break end
local i = r
while M[i][lead] == 0 do
i = i + 1
if n_rows == i then
i = r
lead = lead + 1
if n_cols == lead then break end
end
end
M[i], M[r] = M[r], M[i]
local m = M[r][lead]
for k = 1, n_cols do
M[r][k] = M[r][k] / m
end
for i = 1, n_rows do
if i ~= r then
local m = M[i][lead]
for k = 1, n_cols do
M[i][k] = M[i][k] - m * M[r][k]
end
end
end
lead = lead + 1
end
end
M = { { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } }
res = ToReducedRowEchelonForm( M )
for i = 1, #M do
for j = 1, #M[1] do
io.write( M[i][j], " " )
end
io.write( "\n" )
end
| Private Function ToReducedRowEchelonForm(M As Variant) As Variant
Dim lead As Integer: lead = 0
Dim rowCount As Integer: rowCount = UBound(M)
Dim columnCount As Integer: columnCount = UBound(M(0))
Dim i As Integer
For r = 0 To rowCount
If lead >= columnCount Then
Exit For
End If
i = r
Do While M(i)(lead) = 0
i = i + 1
If i = rowCount Then
i = r
lead = lead + 1
If lead = columnCount Then
Exit For
End If
End If
Loop
Dim tmp As Variant
tmp = M(r)
M(r) = M(i)
M(i) = tmp
If M(r)(lead) <> 0 Then
div = M(r)(lead)
For t = LBound(M(r)) To UBound(M(r))
M(r)(t) = M(r)(t) / div
Next t
End If
For j = 0 To rowCount
If j <> r Then
subt = M(j)(lead)
For t = LBound(M(j)) To UBound(M(j))
M(j)(t) = M(j)(t) - subt * M(r)(t)
Next t
End If
Next j
lead = lead + 1
Next r
ToReducedRowEchelonForm = M
End Function
Public Sub main()
r = ToReducedRowEchelonForm(Array( _
Array(1, 2, -1, -4), _
Array(2, 3, -1, -11), _
Array(-2, 0, -3, 22)))
For i = LBound(r) To UBound(r)
Debug.Print Join(r(i), vbTab)
Next i
End Sub
|
Can you help me rewrite this code in Go instead of Lua, keeping it the same logically? | function ToReducedRowEchelonForm ( M )
local lead = 1
local n_rows, n_cols = #M, #M[1]
for r = 1, n_rows do
if n_cols <= lead then break end
local i = r
while M[i][lead] == 0 do
i = i + 1
if n_rows == i then
i = r
lead = lead + 1
if n_cols == lead then break end
end
end
M[i], M[r] = M[r], M[i]
local m = M[r][lead]
for k = 1, n_cols do
M[r][k] = M[r][k] / m
end
for i = 1, n_rows do
if i ~= r then
local m = M[i][lead]
for k = 1, n_cols do
M[i][k] = M[i][k] - m * M[r][k]
end
end
end
lead = lead + 1
end
end
M = { { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } }
res = ToReducedRowEchelonForm( M )
for i = 1, #M do
for j = 1, #M[1] do
io.write( M[i][j], " " )
end
io.write( "\n" )
end
| package main
import "fmt"
type matrix [][]float64
func (m matrix) print() {
for _, r := range m {
fmt.Println(r)
}
fmt.Println("")
}
func main() {
m := matrix{
{ 1, 2, -1, -4},
{ 2, 3, -1, -11},
{-2, 0, -3, 22},
}
m.print()
rref(m)
m.print()
}
func rref(m matrix) {
lead := 0
rowCount := len(m)
columnCount := len(m[0])
for r := 0; r < rowCount; r++ {
if lead >= columnCount {
return
}
i := r
for m[i][lead] == 0 {
i++
if rowCount == i {
i = r
lead++
if columnCount == lead {
return
}
}
}
m[i], m[r] = m[r], m[i]
f := 1 / m[r][lead]
for j, _ := range m[r] {
m[r][j] *= f
}
for i = 0; i < rowCount; i++ {
if i != r {
f = m[i][lead]
for j, e := range m[r] {
m[i][j] -= e * f
}
}
}
lead++
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.