Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write the same code in PHP as shown below in Racket.
#lang racket (require math) (define earth-radius 6371) (define (distance lat1 long1 lat2 long2) (define (h a b) (sqr (sin (/ (- b a) 2)))) (* 2 earth-radius (asin (sqrt (+ (h lat1 lat2) (* (cos lat1) (cos lat2) (h long1 long2))))))) (define (deg-to-rad d m s) (* (/ pi 180) (+ d (/ m 60) (/ s 3600)))) (distance (deg-to-rad 36 7.2 0) (deg-to-rad 86 40.2 0) (deg-to-rad 33 56.4 0) (deg-to-rad 118 24.0 0))
class POI { private $latitude; private $longitude; public function __construct($latitude, $longitude) { $this->latitude = deg2rad($latitude); $this->longitude = deg2rad($longitude); } public function getLatitude() { return $this->latitude; } public function getLongitude() { return $this->longitude; } public function getDistanceInMetersTo(POI $other) { $radiusOfEarth = 6371; // Earth's radius in kilometers. $diffLatitude = $other->getLatitude() - $this->latitude; $diffLongitude = $other->getLongitude() - $this->longitude; $a = sin($diffLatitude / 2) ** 2 + cos($this->latitude) * cos($other->getLatitude()) * sin($diffLongitude / 2) ** 2; $c = 2 * asin(sqrt($a)); $distance = $radiusOfEarth * $c; return $distance; } }
Write the same algorithm in PHP as shown in this REXX implementation.
say " Nashville: north 36º 7.2', west 86º 40.2' = 36.12º, -86.67º" say "Los Angles: north 33º 56.4', west 118º 24.0' = 33.94º, -118.40º" say dist=surfaceDistance(36.12, -86.67, 33.94, -118.4) kdist=format(dist/1 ,,2) mdist=format(dist/1.609344,,2) ndist=format(mdist*5280/6076.1,,2) say ' distance between= ' kdist " kilometers," say ' or ' mdist " statute miles," say ' or ' ndist " nautical or air miles." exit surfaceDistance: arg th1,ph1,th2,ph2 radius = 6372.8 ph1 = ph1-ph2 x = cos(ph1) * cos(th1) - cos(th2) y = sin(ph1) * cos(th1) z = sin(th1) - sin(th2) return radius * 2 * aSin(sqrt(x**2+y**2+z**2)/2 ) cos: Return RxCalcCos(arg(1)) sin: Return RxCalcSin(arg(1)) asin: Return RxCalcArcSin(arg(1),,'R') sqrt: Return RxCalcSqrt(arg(1)) ::requires rxMath library
class POI { private $latitude; private $longitude; public function __construct($latitude, $longitude) { $this->latitude = deg2rad($latitude); $this->longitude = deg2rad($longitude); } public function getLatitude() { return $this->latitude; } public function getLongitude() { return $this->longitude; } public function getDistanceInMetersTo(POI $other) { $radiusOfEarth = 6371; // Earth's radius in kilometers. $diffLatitude = $other->getLatitude() - $this->latitude; $diffLongitude = $other->getLongitude() - $this->longitude; $a = sin($diffLatitude / 2) ** 2 + cos($this->latitude) * cos($other->getLatitude()) * sin($diffLongitude / 2) ** 2; $c = 2 * asin(sqrt($a)); $distance = $radiusOfEarth * $c; return $distance; } }
Convert the following code from REXX to PHP, ensuring the logic remains intact.
say " Nashville: north 36º 7.2', west 86º 40.2' = 36.12º, -86.67º" say "Los Angles: north 33º 56.4', west 118º 24.0' = 33.94º, -118.40º" say dist=surfaceDistance(36.12, -86.67, 33.94, -118.4) kdist=format(dist/1 ,,2) mdist=format(dist/1.609344,,2) ndist=format(mdist*5280/6076.1,,2) say ' distance between= ' kdist " kilometers," say ' or ' mdist " statute miles," say ' or ' ndist " nautical or air miles." exit surfaceDistance: arg th1,ph1,th2,ph2 radius = 6372.8 ph1 = ph1-ph2 x = cos(ph1) * cos(th1) - cos(th2) y = sin(ph1) * cos(th1) z = sin(th1) - sin(th2) return radius * 2 * aSin(sqrt(x**2+y**2+z**2)/2 ) cos: Return RxCalcCos(arg(1)) sin: Return RxCalcSin(arg(1)) asin: Return RxCalcArcSin(arg(1),,'R') sqrt: Return RxCalcSqrt(arg(1)) ::requires rxMath library
class POI { private $latitude; private $longitude; public function __construct($latitude, $longitude) { $this->latitude = deg2rad($latitude); $this->longitude = deg2rad($longitude); } public function getLatitude() { return $this->latitude; } public function getLongitude() { return $this->longitude; } public function getDistanceInMetersTo(POI $other) { $radiusOfEarth = 6371; // Earth's radius in kilometers. $diffLatitude = $other->getLatitude() - $this->latitude; $diffLongitude = $other->getLongitude() - $this->longitude; $a = sin($diffLatitude / 2) ** 2 + cos($this->latitude) * cos($other->getLatitude()) * sin($diffLongitude / 2) ** 2; $c = 2 * asin(sqrt($a)); $distance = $radiusOfEarth * $c; return $distance; } }
Write a version of this Ruby function in PHP with identical behavior.
include Math def haversine(lat1, lon1, lat2, lon2) r = 6372.8 deg2rad = PI/180 dLat = (lat2 - lat1) * deg2rad dLon = (lon2 - lon1) * deg2rad lat1 = lat1 * deg2rad lat2 = lat2 * deg2rad a = sin(dLat / 2)**2 + cos(lat1) * cos(lat2) * sin(dLon / 2)**2 c = 2 * asin(sqrt(a)) r * c end puts "distance is
class POI { private $latitude; private $longitude; public function __construct($latitude, $longitude) { $this->latitude = deg2rad($latitude); $this->longitude = deg2rad($longitude); } public function getLatitude() { return $this->latitude; } public function getLongitude() { return $this->longitude; } public function getDistanceInMetersTo(POI $other) { $radiusOfEarth = 6371; // Earth's radius in kilometers. $diffLatitude = $other->getLatitude() - $this->latitude; $diffLongitude = $other->getLongitude() - $this->longitude; $a = sin($diffLatitude / 2) ** 2 + cos($this->latitude) * cos($other->getLatitude()) * sin($diffLongitude / 2) ** 2; $c = 2 * asin(sqrt($a)); $distance = $radiusOfEarth * $c; return $distance; } }
Please provide an equivalent version of this Ruby code in PHP.
include Math def haversine(lat1, lon1, lat2, lon2) r = 6372.8 deg2rad = PI/180 dLat = (lat2 - lat1) * deg2rad dLon = (lon2 - lon1) * deg2rad lat1 = lat1 * deg2rad lat2 = lat2 * deg2rad a = sin(dLat / 2)**2 + cos(lat1) * cos(lat2) * sin(dLon / 2)**2 c = 2 * asin(sqrt(a)) r * c end puts "distance is
class POI { private $latitude; private $longitude; public function __construct($latitude, $longitude) { $this->latitude = deg2rad($latitude); $this->longitude = deg2rad($longitude); } public function getLatitude() { return $this->latitude; } public function getLongitude() { return $this->longitude; } public function getDistanceInMetersTo(POI $other) { $radiusOfEarth = 6371; // Earth's radius in kilometers. $diffLatitude = $other->getLatitude() - $this->latitude; $diffLongitude = $other->getLongitude() - $this->longitude; $a = sin($diffLatitude / 2) ** 2 + cos($this->latitude) * cos($other->getLatitude()) * sin($diffLongitude / 2) ** 2; $c = 2 * asin(sqrt($a)); $distance = $radiusOfEarth * $c; return $distance; } }
Port the following code from Scala to PHP with equivalent syntax and logic.
import java.lang.Math.* const val R = 6372.8 fun haversine(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double { val λ1 = toRadians(lat1) val λ2 = toRadians(lat2) val Δλ = toRadians(lat2 - lat1) val Δφ = toRadians(lon2 - lon1) return 2 * R * asin(sqrt(pow(sin(Δλ / 2), 2.0) + pow(sin(Δφ / 2), 2.0) * cos(λ1) * cos(λ2))) } fun main(args: Array<String>) = println("result: " + haversine(36.12, -86.67, 33.94, -118.40))
class POI { private $latitude; private $longitude; public function __construct($latitude, $longitude) { $this->latitude = deg2rad($latitude); $this->longitude = deg2rad($longitude); } public function getLatitude() { return $this->latitude; } public function getLongitude() { return $this->longitude; } public function getDistanceInMetersTo(POI $other) { $radiusOfEarth = 6371; // Earth's radius in kilometers. $diffLatitude = $other->getLatitude() - $this->latitude; $diffLongitude = $other->getLongitude() - $this->longitude; $a = sin($diffLatitude / 2) ** 2 + cos($this->latitude) * cos($other->getLatitude()) * sin($diffLongitude / 2) ** 2; $c = 2 * asin(sqrt($a)); $distance = $radiusOfEarth * $c; return $distance; } }
Generate an equivalent PHP version of this Scala code.
import java.lang.Math.* const val R = 6372.8 fun haversine(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double { val λ1 = toRadians(lat1) val λ2 = toRadians(lat2) val Δλ = toRadians(lat2 - lat1) val Δφ = toRadians(lon2 - lon1) return 2 * R * asin(sqrt(pow(sin(Δλ / 2), 2.0) + pow(sin(Δφ / 2), 2.0) * cos(λ1) * cos(λ2))) } fun main(args: Array<String>) = println("result: " + haversine(36.12, -86.67, 33.94, -118.40))
class POI { private $latitude; private $longitude; public function __construct($latitude, $longitude) { $this->latitude = deg2rad($latitude); $this->longitude = deg2rad($longitude); } public function getLatitude() { return $this->latitude; } public function getLongitude() { return $this->longitude; } public function getDistanceInMetersTo(POI $other) { $radiusOfEarth = 6371; // Earth's radius in kilometers. $diffLatitude = $other->getLatitude() - $this->latitude; $diffLongitude = $other->getLongitude() - $this->longitude; $a = sin($diffLatitude / 2) ** 2 + cos($this->latitude) * cos($other->getLatitude()) * sin($diffLongitude / 2) ** 2; $c = 2 * asin(sqrt($a)); $distance = $radiusOfEarth * $c; return $distance; } }
Rewrite the snippet below in PHP so it works the same as the original Swift code.
import Foundation func haversine(lat1:Double, lon1:Double, lat2:Double, lon2:Double) -> Double { let lat1rad = lat1 * Double.pi/180 let lon1rad = lon1 * Double.pi/180 let lat2rad = lat2 * Double.pi/180 let lon2rad = lon2 * Double.pi/180 let dLat = lat2rad - lat1rad let dLon = lon2rad - lon1rad let a = sin(dLat/2) * sin(dLat/2) + sin(dLon/2) * sin(dLon/2) * cos(lat1rad) * cos(lat2rad) let c = 2 * asin(sqrt(a)) let R = 6372.8 return R * c } print(haversine(lat1:36.12, lon1:-86.67, lat2:33.94, lon2:-118.40))
class POI { private $latitude; private $longitude; public function __construct($latitude, $longitude) { $this->latitude = deg2rad($latitude); $this->longitude = deg2rad($longitude); } public function getLatitude() { return $this->latitude; } public function getLongitude() { return $this->longitude; } public function getDistanceInMetersTo(POI $other) { $radiusOfEarth = 6371; // Earth's radius in kilometers. $diffLatitude = $other->getLatitude() - $this->latitude; $diffLongitude = $other->getLongitude() - $this->longitude; $a = sin($diffLatitude / 2) ** 2 + cos($this->latitude) * cos($other->getLatitude()) * sin($diffLongitude / 2) ** 2; $c = 2 * asin(sqrt($a)); $distance = $radiusOfEarth * $c; return $distance; } }
Rewrite this program in PHP while keeping its functionality equivalent to the Swift version.
import Foundation func haversine(lat1:Double, lon1:Double, lat2:Double, lon2:Double) -> Double { let lat1rad = lat1 * Double.pi/180 let lon1rad = lon1 * Double.pi/180 let lat2rad = lat2 * Double.pi/180 let lon2rad = lon2 * Double.pi/180 let dLat = lat2rad - lat1rad let dLon = lon2rad - lon1rad let a = sin(dLat/2) * sin(dLat/2) + sin(dLon/2) * sin(dLon/2) * cos(lat1rad) * cos(lat2rad) let c = 2 * asin(sqrt(a)) let R = 6372.8 return R * c } print(haversine(lat1:36.12, lon1:-86.67, lat2:33.94, lon2:-118.40))
class POI { private $latitude; private $longitude; public function __construct($latitude, $longitude) { $this->latitude = deg2rad($latitude); $this->longitude = deg2rad($longitude); } public function getLatitude() { return $this->latitude; } public function getLongitude() { return $this->longitude; } public function getDistanceInMetersTo(POI $other) { $radiusOfEarth = 6371; // Earth's radius in kilometers. $diffLatitude = $other->getLatitude() - $this->latitude; $diffLongitude = $other->getLongitude() - $this->longitude; $a = sin($diffLatitude / 2) ** 2 + cos($this->latitude) * cos($other->getLatitude()) * sin($diffLongitude / 2) ** 2; $c = 2 * asin(sqrt($a)); $distance = $radiusOfEarth * $c; return $distance; } }
Please provide an equivalent version of this Tcl code in PHP.
package require Tcl 8.5 proc haversineFormula {lat1 lon1 lat2 lon2} { set rads [expr atan2(0,-1)/180] set R 6372.8 ; set dLat [expr {($lat2-$lat1) * $rads}] set dLon [expr {($lon2-$lon1) * $rads}] set lat1 [expr {$lat1 * $rads}] set lat2 [expr {$lat2 * $rads}] set a [expr {sin($dLat/2)**2 + sin($dLon/2)**2*cos($lat1)*cos($lat2)}] set c [expr {2*asin(sqrt($a))}] return [expr {$R * $c}] } puts [format "distance=%.1f km" [haversineFormula 36.12 -86.67 33.94 -118.40]]
class POI { private $latitude; private $longitude; public function __construct($latitude, $longitude) { $this->latitude = deg2rad($latitude); $this->longitude = deg2rad($longitude); } public function getLatitude() { return $this->latitude; } public function getLongitude() { return $this->longitude; } public function getDistanceInMetersTo(POI $other) { $radiusOfEarth = 6371; // Earth's radius in kilometers. $diffLatitude = $other->getLatitude() - $this->latitude; $diffLongitude = $other->getLongitude() - $this->longitude; $a = sin($diffLatitude / 2) ** 2 + cos($this->latitude) * cos($other->getLatitude()) * sin($diffLongitude / 2) ** 2; $c = 2 * asin(sqrt($a)); $distance = $radiusOfEarth * $c; return $distance; } }
Generate an equivalent PHP version of this Tcl code.
package require Tcl 8.5 proc haversineFormula {lat1 lon1 lat2 lon2} { set rads [expr atan2(0,-1)/180] set R 6372.8 ; set dLat [expr {($lat2-$lat1) * $rads}] set dLon [expr {($lon2-$lon1) * $rads}] set lat1 [expr {$lat1 * $rads}] set lat2 [expr {$lat2 * $rads}] set a [expr {sin($dLat/2)**2 + sin($dLon/2)**2*cos($lat1)*cos($lat2)}] set c [expr {2*asin(sqrt($a))}] return [expr {$R * $c}] } puts [format "distance=%.1f km" [haversineFormula 36.12 -86.67 33.94 -118.40]]
class POI { private $latitude; private $longitude; public function __construct($latitude, $longitude) { $this->latitude = deg2rad($latitude); $this->longitude = deg2rad($longitude); } public function getLatitude() { return $this->latitude; } public function getLongitude() { return $this->longitude; } public function getDistanceInMetersTo(POI $other) { $radiusOfEarth = 6371; // Earth's radius in kilometers. $diffLatitude = $other->getLatitude() - $this->latitude; $diffLongitude = $other->getLongitude() - $this->longitude; $a = sin($diffLatitude / 2) ** 2 + cos($this->latitude) * cos($other->getLatitude()) * sin($diffLongitude / 2) ** 2; $c = 2 * asin(sqrt($a)); $distance = $radiusOfEarth * $c; return $distance; } }
Write the same code in Rust as shown below in C.
#include <stdio.h> #include <stdlib.h> #include <math.h> #define R 6371 #define TO_RAD (3.1415926536 / 180) double dist(double th1, double ph1, double th2, double ph2) { double dx, dy, dz; ph1 -= ph2; ph1 *= TO_RAD, th1 *= TO_RAD, th2 *= TO_RAD; dz = sin(th1) - sin(th2); dx = cos(ph1) * cos(th1) - cos(th2); dy = sin(ph1) * cos(th1); return asin(sqrt(dx * dx + dy * dy + dz * dz) / 2) * 2 * R; } int main() { double d = dist(36.12, -86.67, 33.94, -118.4); printf("dist: %.1f km (%.1f mi.)\n", d, d / 1.609344); return 0; }
struct Point { lat: f64, lon: f64, } fn haversine(origin: Point, destination: Point) -> f64 { const R: f64 = 6372.8; let lat1 = origin.lat.to_radians(); let lat2 = destination.lat.to_radians(); let d_lat = lat2 - lat1; let d_lon = (destination.lon - origin.lon).to_radians(); let a = (d_lat / 2.0).sin().powi(2) + (d_lon / 2.0).sin().powi(2) * lat1.cos() * lat2.cos(); let c = 2.0 * a.sqrt().asin(); R * c } #[cfg(test)] mod test { use super::{Point, haversine}; #[test] fn test_haversine() { let origin: Point = Point { lat: 36.12, lon: -86.67 }; let destination: Point = Point { lat: 33.94, lon: -118.4 }; let d: f64 = haversine(origin, destination); println!("Distance: {} km ({} mi)", d, d / 1.609344); assert_eq!(d, 2887.2599506071106); } }
Write the same code in Rust as shown below in C.
#include <stdio.h> #include <stdlib.h> #include <math.h> #define R 6371 #define TO_RAD (3.1415926536 / 180) double dist(double th1, double ph1, double th2, double ph2) { double dx, dy, dz; ph1 -= ph2; ph1 *= TO_RAD, th1 *= TO_RAD, th2 *= TO_RAD; dz = sin(th1) - sin(th2); dx = cos(ph1) * cos(th1) - cos(th2); dy = sin(ph1) * cos(th1); return asin(sqrt(dx * dx + dy * dy + dz * dz) / 2) * 2 * R; } int main() { double d = dist(36.12, -86.67, 33.94, -118.4); printf("dist: %.1f km (%.1f mi.)\n", d, d / 1.609344); return 0; }
struct Point { lat: f64, lon: f64, } fn haversine(origin: Point, destination: Point) -> f64 { const R: f64 = 6372.8; let lat1 = origin.lat.to_radians(); let lat2 = destination.lat.to_radians(); let d_lat = lat2 - lat1; let d_lon = (destination.lon - origin.lon).to_radians(); let a = (d_lat / 2.0).sin().powi(2) + (d_lon / 2.0).sin().powi(2) * lat1.cos() * lat2.cos(); let c = 2.0 * a.sqrt().asin(); R * c } #[cfg(test)] mod test { use super::{Point, haversine}; #[test] fn test_haversine() { let origin: Point = Point { lat: 36.12, lon: -86.67 }; let destination: Point = Point { lat: 33.94, lon: -118.4 }; let d: f64 = haversine(origin, destination); println!("Distance: {} km ({} mi)", d, d / 1.609344); assert_eq!(d, 2887.2599506071106); } }
Convert this C++ block to Rust, preserving its control flow and logic.
#define _USE_MATH_DEFINES #include <math.h> #include <iostream> const static double EarthRadiusKm = 6372.8; inline double DegreeToRadian(double angle) { return M_PI * angle / 180.0; } class Coordinate { public: Coordinate(double latitude ,double longitude):myLatitude(latitude), myLongitude(longitude) {} double Latitude() const { return myLatitude; } double Longitude() const { return myLongitude; } private: double myLatitude; double myLongitude; }; double HaversineDistance(const Coordinate& p1, const Coordinate& p2) { double latRad1 = DegreeToRadian(p1.Latitude()); double latRad2 = DegreeToRadian(p2.Latitude()); double lonRad1 = DegreeToRadian(p1.Longitude()); double lonRad2 = DegreeToRadian(p2.Longitude()); double diffLa = latRad2 - latRad1; double doffLo = lonRad2 - lonRad1; double computation = asin(sqrt(sin(diffLa / 2) * sin(diffLa / 2) + cos(latRad1) * cos(latRad2) * sin(doffLo / 2) * sin(doffLo / 2))); return 2 * EarthRadiusKm * computation; } int main() { Coordinate c1(36.12, -86.67); Coordinate c2(33.94, -118.4); std::cout << "Distance = " << HaversineDistance(c1, c2) << std::endl; return 0; }
struct Point { lat: f64, lon: f64, } fn haversine(origin: Point, destination: Point) -> f64 { const R: f64 = 6372.8; let lat1 = origin.lat.to_radians(); let lat2 = destination.lat.to_radians(); let d_lat = lat2 - lat1; let d_lon = (destination.lon - origin.lon).to_radians(); let a = (d_lat / 2.0).sin().powi(2) + (d_lon / 2.0).sin().powi(2) * lat1.cos() * lat2.cos(); let c = 2.0 * a.sqrt().asin(); R * c } #[cfg(test)] mod test { use super::{Point, haversine}; #[test] fn test_haversine() { let origin: Point = Point { lat: 36.12, lon: -86.67 }; let destination: Point = Point { lat: 33.94, lon: -118.4 }; let d: f64 = haversine(origin, destination); println!("Distance: {} km ({} mi)", d, d / 1.609344); assert_eq!(d, 2887.2599506071106); } }
Produce a language-to-language conversion: from C# to Rust, same semantics.
public static class Haversine { public static double calculate(double lat1, double lon1, double lat2, double lon2) { var R = 6372.8; var dLat = toRadians(lat2 - lat1); var dLon = toRadians(lon2 - lon1); lat1 = toRadians(lat1); lat2 = toRadians(lat2); var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Sin(dLon / 2) * Math.Sin(dLon / 2) * Math.Cos(lat1) * Math.Cos(lat2); var c = 2 * Math.Asin(Math.Sqrt(a)); return R * 2 * Math.Asin(Math.Sqrt(a)); } public static double toRadians(double angle) { return Math.PI * angle / 180.0; } } void Main() { Console.WriteLine(String.Format("The distance between coordinates {0},{1} and {2},{3} is: {4}", 36.12, -86.67, 33.94, -118.40, Haversine.calculate(36.12, -86.67, 33.94, -118.40))); }
struct Point { lat: f64, lon: f64, } fn haversine(origin: Point, destination: Point) -> f64 { const R: f64 = 6372.8; let lat1 = origin.lat.to_radians(); let lat2 = destination.lat.to_radians(); let d_lat = lat2 - lat1; let d_lon = (destination.lon - origin.lon).to_radians(); let a = (d_lat / 2.0).sin().powi(2) + (d_lon / 2.0).sin().powi(2) * lat1.cos() * lat2.cos(); let c = 2.0 * a.sqrt().asin(); R * c } #[cfg(test)] mod test { use super::{Point, haversine}; #[test] fn test_haversine() { let origin: Point = Point { lat: 36.12, lon: -86.67 }; let destination: Point = Point { lat: 33.94, lon: -118.4 }; let d: f64 = haversine(origin, destination); println!("Distance: {} km ({} mi)", d, d / 1.609344); assert_eq!(d, 2887.2599506071106); } }
Write the same algorithm in Rust as shown in this C# implementation.
public static class Haversine { public static double calculate(double lat1, double lon1, double lat2, double lon2) { var R = 6372.8; var dLat = toRadians(lat2 - lat1); var dLon = toRadians(lon2 - lon1); lat1 = toRadians(lat1); lat2 = toRadians(lat2); var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Sin(dLon / 2) * Math.Sin(dLon / 2) * Math.Cos(lat1) * Math.Cos(lat2); var c = 2 * Math.Asin(Math.Sqrt(a)); return R * 2 * Math.Asin(Math.Sqrt(a)); } public static double toRadians(double angle) { return Math.PI * angle / 180.0; } } void Main() { Console.WriteLine(String.Format("The distance between coordinates {0},{1} and {2},{3} is: {4}", 36.12, -86.67, 33.94, -118.40, Haversine.calculate(36.12, -86.67, 33.94, -118.40))); }
struct Point { lat: f64, lon: f64, } fn haversine(origin: Point, destination: Point) -> f64 { const R: f64 = 6372.8; let lat1 = origin.lat.to_radians(); let lat2 = destination.lat.to_radians(); let d_lat = lat2 - lat1; let d_lon = (destination.lon - origin.lon).to_radians(); let a = (d_lat / 2.0).sin().powi(2) + (d_lon / 2.0).sin().powi(2) * lat1.cos() * lat2.cos(); let c = 2.0 * a.sqrt().asin(); R * c } #[cfg(test)] mod test { use super::{Point, haversine}; #[test] fn test_haversine() { let origin: Point = Point { lat: 36.12, lon: -86.67 }; let destination: Point = Point { lat: 33.94, lon: -118.4 }; let d: f64 = haversine(origin, destination); println!("Distance: {} km ({} mi)", d, d / 1.609344); assert_eq!(d, 2887.2599506071106); } }
Convert the following code from Java to Rust, ensuring the logic remains intact.
public class Haversine { public static final double R = 6372.8; public static double haversine(double lat1, double lon1, double lat2, double lon2) { lat1 = Math.toRadians(lat1); lat2 = Math.toRadians(lat2); double dLat = lat2 - lat1; double dLon = Math.toRadians(lon2 - lon1); double a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2); double c = 2 * Math.asin(Math.sqrt(a)); return R * c; } public static void main(String[] args) { System.out.println(haversine(36.12, -86.67, 33.94, -118.40)); } }
struct Point { lat: f64, lon: f64, } fn haversine(origin: Point, destination: Point) -> f64 { const R: f64 = 6372.8; let lat1 = origin.lat.to_radians(); let lat2 = destination.lat.to_radians(); let d_lat = lat2 - lat1; let d_lon = (destination.lon - origin.lon).to_radians(); let a = (d_lat / 2.0).sin().powi(2) + (d_lon / 2.0).sin().powi(2) * lat1.cos() * lat2.cos(); let c = 2.0 * a.sqrt().asin(); R * c } #[cfg(test)] mod test { use super::{Point, haversine}; #[test] fn test_haversine() { let origin: Point = Point { lat: 36.12, lon: -86.67 }; let destination: Point = Point { lat: 33.94, lon: -118.4 }; let d: f64 = haversine(origin, destination); println!("Distance: {} km ({} mi)", d, d / 1.609344); assert_eq!(d, 2887.2599506071106); } }
Change the programming language of this snippet from Java to Rust without modifying what it does.
public class Haversine { public static final double R = 6372.8; public static double haversine(double lat1, double lon1, double lat2, double lon2) { lat1 = Math.toRadians(lat1); lat2 = Math.toRadians(lat2); double dLat = lat2 - lat1; double dLon = Math.toRadians(lon2 - lon1); double a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2); double c = 2 * Math.asin(Math.sqrt(a)); return R * c; } public static void main(String[] args) { System.out.println(haversine(36.12, -86.67, 33.94, -118.40)); } }
struct Point { lat: f64, lon: f64, } fn haversine(origin: Point, destination: Point) -> f64 { const R: f64 = 6372.8; let lat1 = origin.lat.to_radians(); let lat2 = destination.lat.to_radians(); let d_lat = lat2 - lat1; let d_lon = (destination.lon - origin.lon).to_radians(); let a = (d_lat / 2.0).sin().powi(2) + (d_lon / 2.0).sin().powi(2) * lat1.cos() * lat2.cos(); let c = 2.0 * a.sqrt().asin(); R * c } #[cfg(test)] mod test { use super::{Point, haversine}; #[test] fn test_haversine() { let origin: Point = Point { lat: 36.12, lon: -86.67 }; let destination: Point = Point { lat: 33.94, lon: -118.4 }; let d: f64 = haversine(origin, destination); println!("Distance: {} km ({} mi)", d, d / 1.609344); assert_eq!(d, 2887.2599506071106); } }
Port the provided Go code into Rust while preserving the original functionality.
package main import ( "fmt" "math" ) func haversine(θ float64) float64 { return .5 * (1 - math.Cos(θ)) } type pos struct { φ float64 ψ float64 } func degPos(lat, lon float64) pos { return pos{lat * math.Pi / 180, lon * math.Pi / 180} } const rEarth = 6372.8 func hsDist(p1, p2 pos) float64 { return 2 * rEarth * math.Asin(math.Sqrt(haversine(p2.φ-p1.φ)+ math.Cos(p1.φ)*math.Cos(p2.φ)*haversine(p2.ψ-p1.ψ))) } func main() { fmt.Println(hsDist(degPos(36.12, -86.67), degPos(33.94, -118.40))) }
struct Point { lat: f64, lon: f64, } fn haversine(origin: Point, destination: Point) -> f64 { const R: f64 = 6372.8; let lat1 = origin.lat.to_radians(); let lat2 = destination.lat.to_radians(); let d_lat = lat2 - lat1; let d_lon = (destination.lon - origin.lon).to_radians(); let a = (d_lat / 2.0).sin().powi(2) + (d_lon / 2.0).sin().powi(2) * lat1.cos() * lat2.cos(); let c = 2.0 * a.sqrt().asin(); R * c } #[cfg(test)] mod test { use super::{Point, haversine}; #[test] fn test_haversine() { let origin: Point = Point { lat: 36.12, lon: -86.67 }; let destination: Point = Point { lat: 33.94, lon: -118.4 }; let d: f64 = haversine(origin, destination); println!("Distance: {} km ({} mi)", d, d / 1.609344); assert_eq!(d, 2887.2599506071106); } }
Generate a Rust translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math" ) func haversine(θ float64) float64 { return .5 * (1 - math.Cos(θ)) } type pos struct { φ float64 ψ float64 } func degPos(lat, lon float64) pos { return pos{lat * math.Pi / 180, lon * math.Pi / 180} } const rEarth = 6372.8 func hsDist(p1, p2 pos) float64 { return 2 * rEarth * math.Asin(math.Sqrt(haversine(p2.φ-p1.φ)+ math.Cos(p1.φ)*math.Cos(p2.φ)*haversine(p2.ψ-p1.ψ))) } func main() { fmt.Println(hsDist(degPos(36.12, -86.67), degPos(33.94, -118.40))) }
struct Point { lat: f64, lon: f64, } fn haversine(origin: Point, destination: Point) -> f64 { const R: f64 = 6372.8; let lat1 = origin.lat.to_radians(); let lat2 = destination.lat.to_radians(); let d_lat = lat2 - lat1; let d_lon = (destination.lon - origin.lon).to_radians(); let a = (d_lat / 2.0).sin().powi(2) + (d_lon / 2.0).sin().powi(2) * lat1.cos() * lat2.cos(); let c = 2.0 * a.sqrt().asin(); R * c } #[cfg(test)] mod test { use super::{Point, haversine}; #[test] fn test_haversine() { let origin: Point = Point { lat: 36.12, lon: -86.67 }; let destination: Point = Point { lat: 33.94, lon: -118.4 }; let d: f64 = haversine(origin, destination); println!("Distance: {} km ({} mi)", d, d / 1.609344); assert_eq!(d, 2887.2599506071106); } }
Please provide an equivalent version of this Rust code in Python.
struct Point { lat: f64, lon: f64, } fn haversine(origin: Point, destination: Point) -> f64 { const R: f64 = 6372.8; let lat1 = origin.lat.to_radians(); let lat2 = destination.lat.to_radians(); let d_lat = lat2 - lat1; let d_lon = (destination.lon - origin.lon).to_radians(); let a = (d_lat / 2.0).sin().powi(2) + (d_lon / 2.0).sin().powi(2) * lat1.cos() * lat2.cos(); let c = 2.0 * a.sqrt().asin(); R * c } #[cfg(test)] mod test { use super::{Point, haversine}; #[test] fn test_haversine() { let origin: Point = Point { lat: 36.12, lon: -86.67 }; let destination: Point = Point { lat: 33.94, lon: -118.4 }; let d: f64 = haversine(origin, destination); println!("Distance: {} km ({} mi)", d, d / 1.609344); assert_eq!(d, 2887.2599506071106); } }
from math import radians, sin, cos, sqrt, asin def haversine(lat1, lon1, lat2, lon2): R = 6372.8 dLat = radians(lat2 - lat1) dLon = radians(lon2 - lon1) lat1 = radians(lat1) lat2 = radians(lat2) a = sin(dLat / 2)**2 + cos(lat1) * cos(lat2) * sin(dLon / 2)**2 c = 2 * asin(sqrt(a)) return R * c >>> haversine(36.12, -86.67, 33.94, -118.40) 2887.2599506071106 >>>
Preserve the algorithm and functionality while converting the code from Rust to VB.
struct Point { lat: f64, lon: f64, } fn haversine(origin: Point, destination: Point) -> f64 { const R: f64 = 6372.8; let lat1 = origin.lat.to_radians(); let lat2 = destination.lat.to_radians(); let d_lat = lat2 - lat1; let d_lon = (destination.lon - origin.lon).to_radians(); let a = (d_lat / 2.0).sin().powi(2) + (d_lon / 2.0).sin().powi(2) * lat1.cos() * lat2.cos(); let c = 2.0 * a.sqrt().asin(); R * c } #[cfg(test)] mod test { use super::{Point, haversine}; #[test] fn test_haversine() { let origin: Point = Point { lat: 36.12, lon: -86.67 }; let destination: Point = Point { lat: 33.94, lon: -118.4 }; let d: f64 = haversine(origin, destination); println!("Distance: {} km ({} mi)", d, d / 1.609344); assert_eq!(d, 2887.2599506071106); } }
Const MER = 6371 Public DEG_TO_RAD As Double Function haversine(lat1 As Double, long1 As Double, lat2 As Double, long2 As Double) As Double lat1 = lat1 * DEG_TO_RAD lat2 = lat2 * DEG_TO_RAD long1 = long1 * DEG_TO_RAD long2 = long2 * DEG_TO_RAD haversine = MER * WorksheetFunction.Acos(Sin(lat1) * Sin(lat2) + Cos(lat1) * Cos(lat2) * Cos(long2 - long1)) End Function Public Sub main() DEG_TO_RAD = WorksheetFunction.Pi / 180 d = haversine(36.12, -86.67, 33.94, -118.4) Debug.Print "Distance is "; Format(d, "#.######"); " km ("; Format(d / 1.609344, "#.######"); " miles)." End Sub
Convert this Rust snippet to VB and keep its semantics consistent.
struct Point { lat: f64, lon: f64, } fn haversine(origin: Point, destination: Point) -> f64 { const R: f64 = 6372.8; let lat1 = origin.lat.to_radians(); let lat2 = destination.lat.to_radians(); let d_lat = lat2 - lat1; let d_lon = (destination.lon - origin.lon).to_radians(); let a = (d_lat / 2.0).sin().powi(2) + (d_lon / 2.0).sin().powi(2) * lat1.cos() * lat2.cos(); let c = 2.0 * a.sqrt().asin(); R * c } #[cfg(test)] mod test { use super::{Point, haversine}; #[test] fn test_haversine() { let origin: Point = Point { lat: 36.12, lon: -86.67 }; let destination: Point = Point { lat: 33.94, lon: -118.4 }; let d: f64 = haversine(origin, destination); println!("Distance: {} km ({} mi)", d, d / 1.609344); assert_eq!(d, 2887.2599506071106); } }
Const MER = 6371 Public DEG_TO_RAD As Double Function haversine(lat1 As Double, long1 As Double, lat2 As Double, long2 As Double) As Double lat1 = lat1 * DEG_TO_RAD lat2 = lat2 * DEG_TO_RAD long1 = long1 * DEG_TO_RAD long2 = long2 * DEG_TO_RAD haversine = MER * WorksheetFunction.Acos(Sin(lat1) * Sin(lat2) + Cos(lat1) * Cos(lat2) * Cos(long2 - long1)) End Function Public Sub main() DEG_TO_RAD = WorksheetFunction.Pi / 180 d = haversine(36.12, -86.67, 33.94, -118.4) Debug.Print "Distance is "; Format(d, "#.######"); " km ("; Format(d / 1.609344, "#.######"); " miles)." End Sub
Convert this Rust block to Python, preserving its control flow and logic.
struct Point { lat: f64, lon: f64, } fn haversine(origin: Point, destination: Point) -> f64 { const R: f64 = 6372.8; let lat1 = origin.lat.to_radians(); let lat2 = destination.lat.to_radians(); let d_lat = lat2 - lat1; let d_lon = (destination.lon - origin.lon).to_radians(); let a = (d_lat / 2.0).sin().powi(2) + (d_lon / 2.0).sin().powi(2) * lat1.cos() * lat2.cos(); let c = 2.0 * a.sqrt().asin(); R * c } #[cfg(test)] mod test { use super::{Point, haversine}; #[test] fn test_haversine() { let origin: Point = Point { lat: 36.12, lon: -86.67 }; let destination: Point = Point { lat: 33.94, lon: -118.4 }; let d: f64 = haversine(origin, destination); println!("Distance: {} km ({} mi)", d, d / 1.609344); assert_eq!(d, 2887.2599506071106); } }
from math import radians, sin, cos, sqrt, asin def haversine(lat1, lon1, lat2, lon2): R = 6372.8 dLat = radians(lat2 - lat1) dLon = radians(lon2 - lon1) lat1 = radians(lat1) lat2 = radians(lat2) a = sin(dLat / 2)**2 + cos(lat1) * cos(lat2) * sin(dLon / 2)**2 c = 2 * asin(sqrt(a)) return R * c >>> haversine(36.12, -86.67, 33.94, -118.40) 2887.2599506071106 >>>
Ensure the translated Rust code behaves exactly like the original C++ snippet.
#define _USE_MATH_DEFINES #include <math.h> #include <iostream> const static double EarthRadiusKm = 6372.8; inline double DegreeToRadian(double angle) { return M_PI * angle / 180.0; } class Coordinate { public: Coordinate(double latitude ,double longitude):myLatitude(latitude), myLongitude(longitude) {} double Latitude() const { return myLatitude; } double Longitude() const { return myLongitude; } private: double myLatitude; double myLongitude; }; double HaversineDistance(const Coordinate& p1, const Coordinate& p2) { double latRad1 = DegreeToRadian(p1.Latitude()); double latRad2 = DegreeToRadian(p2.Latitude()); double lonRad1 = DegreeToRadian(p1.Longitude()); double lonRad2 = DegreeToRadian(p2.Longitude()); double diffLa = latRad2 - latRad1; double doffLo = lonRad2 - lonRad1; double computation = asin(sqrt(sin(diffLa / 2) * sin(diffLa / 2) + cos(latRad1) * cos(latRad2) * sin(doffLo / 2) * sin(doffLo / 2))); return 2 * EarthRadiusKm * computation; } int main() { Coordinate c1(36.12, -86.67); Coordinate c2(33.94, -118.4); std::cout << "Distance = " << HaversineDistance(c1, c2) << std::endl; return 0; }
struct Point { lat: f64, lon: f64, } fn haversine(origin: Point, destination: Point) -> f64 { const R: f64 = 6372.8; let lat1 = origin.lat.to_radians(); let lat2 = destination.lat.to_radians(); let d_lat = lat2 - lat1; let d_lon = (destination.lon - origin.lon).to_radians(); let a = (d_lat / 2.0).sin().powi(2) + (d_lon / 2.0).sin().powi(2) * lat1.cos() * lat2.cos(); let c = 2.0 * a.sqrt().asin(); R * c } #[cfg(test)] mod test { use super::{Point, haversine}; #[test] fn test_haversine() { let origin: Point = Point { lat: 36.12, lon: -86.67 }; let destination: Point = Point { lat: 33.94, lon: -118.4 }; let d: f64 = haversine(origin, destination); println!("Distance: {} km ({} mi)", d, d / 1.609344); assert_eq!(d, 2887.2599506071106); } }
Generate a C# translation of this Ada snippet without changing its computational steps.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Generic_Array_Sort; procedure Main is package Real_Io is new Float_IO (Long_Float); use Real_Io; type Data_Array is array (Natural range <>) of Long_Float; subtype Five_Num_Type is Data_Array (0 .. 4); procedure Sort is new Ada.Containers.Generic_Array_Sort (Index_Type => Natural, Element_Type => Long_Float, Array_Type => Data_Array); function Median (X : Data_Array) return Long_Float with Pre => X'Length > 0; function Median (X : Data_Array) return Long_Float is M : constant Natural := X'First + X'Last / 2; begin if X'Length rem 2 = 1 then return X (M); else return (X (M - 1) + X (M)) / 2.0; end if; end Median; procedure fivenum (X : Data_Array; Result : out Five_Num_Type) is Temp : Data_Array := X; m : Natural := X'Length / 2; Lower_end : Natural := (if X'Length rem 2 = 0 then m - 1 else m); begin Sort (Temp); Result (0) := Temp (Temp'First); Result (2) := Median (Temp); Result (4) := Temp (Temp'Last); Result (1) := Median (Temp (1 .. Lower_end)); Result (3) := Median (Temp (m .. Temp'Last)); end fivenum; procedure print (Result : Five_Num_Type; Aft : Natural) is begin Put ("["); for I in Result'Range loop Put (Item => Result (I), Fore => 1, Aft => Aft, Exp => 0); if I < Result'Last then Put (", "); else Put_Line ("]"); end if; end loop; New_Line; end print; X1 : Data_Array := (15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0); X2 : Data_Array := (36.0, 40.0, 7.0, 39.0, 41.0, 15.0); X3 : Data_Array := (0.140_828_34, 0.097_487_90, 1.731_315_07, 0.876_360_09, -1.950_595_94, 0.734_385_55, -0.030_357_26, 1.466_759_70, -0.746_213_49, -0.725_887_72, 0.639_051_60, 0.615_015_27, -0.989_837_80, -1.004_478_74, -0.627_594_69, 0.662_061_63, 1.043_120_09, -0.103_053_85, 0.757_756_34, 0.325_665_78); Result : Five_Num_Type; begin fivenum (X1, Result); print (Result, 1); fivenum (X2, Result); print (Result, 1); fivenum (X3, Result); print (Result, 9); end Main;
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Fivenum { public static class Helper { public static string AsString<T>(this ICollection<T> c, string format = "{0}") { StringBuilder sb = new StringBuilder("["); int count = 0; foreach (var t in c) { if (count++ > 0) { sb.Append(", "); } sb.AppendFormat(format, t); } return sb.Append("]").ToString(); } } class Program { static double Median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new ArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] Fivenum(double[] x) { foreach (var d in x) { if (Double.IsNaN(d)) { throw new ArgumentException("Unable to deal with arrays containing NaN"); } } double[] result = new double[5]; Array.Sort(x); result[0] = x.First(); result[2] = Median(x, 0, x.Length - 1); result[4] = x.Last(); int m = x.Length / 2; int lowerEnd = (x.Length % 2 == 1) ? m : m - 1; result[1] = Median(x, 0, lowerEnd); result[3] = Median(x, m, x.Length - 1); return result; } static void Main(string[] args) { double[][] x1 = new double[][]{ new double[]{ 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, new double[]{ 36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, new double[]{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }, }; foreach(var x in x1) { var result = Fivenum(x); Console.WriteLine(result.AsString("{0:F8}")); } } } }
Maintain the same structure and functionality when rewriting this code in C#.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Generic_Array_Sort; procedure Main is package Real_Io is new Float_IO (Long_Float); use Real_Io; type Data_Array is array (Natural range <>) of Long_Float; subtype Five_Num_Type is Data_Array (0 .. 4); procedure Sort is new Ada.Containers.Generic_Array_Sort (Index_Type => Natural, Element_Type => Long_Float, Array_Type => Data_Array); function Median (X : Data_Array) return Long_Float with Pre => X'Length > 0; function Median (X : Data_Array) return Long_Float is M : constant Natural := X'First + X'Last / 2; begin if X'Length rem 2 = 1 then return X (M); else return (X (M - 1) + X (M)) / 2.0; end if; end Median; procedure fivenum (X : Data_Array; Result : out Five_Num_Type) is Temp : Data_Array := X; m : Natural := X'Length / 2; Lower_end : Natural := (if X'Length rem 2 = 0 then m - 1 else m); begin Sort (Temp); Result (0) := Temp (Temp'First); Result (2) := Median (Temp); Result (4) := Temp (Temp'Last); Result (1) := Median (Temp (1 .. Lower_end)); Result (3) := Median (Temp (m .. Temp'Last)); end fivenum; procedure print (Result : Five_Num_Type; Aft : Natural) is begin Put ("["); for I in Result'Range loop Put (Item => Result (I), Fore => 1, Aft => Aft, Exp => 0); if I < Result'Last then Put (", "); else Put_Line ("]"); end if; end loop; New_Line; end print; X1 : Data_Array := (15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0); X2 : Data_Array := (36.0, 40.0, 7.0, 39.0, 41.0, 15.0); X3 : Data_Array := (0.140_828_34, 0.097_487_90, 1.731_315_07, 0.876_360_09, -1.950_595_94, 0.734_385_55, -0.030_357_26, 1.466_759_70, -0.746_213_49, -0.725_887_72, 0.639_051_60, 0.615_015_27, -0.989_837_80, -1.004_478_74, -0.627_594_69, 0.662_061_63, 1.043_120_09, -0.103_053_85, 0.757_756_34, 0.325_665_78); Result : Five_Num_Type; begin fivenum (X1, Result); print (Result, 1); fivenum (X2, Result); print (Result, 1); fivenum (X3, Result); print (Result, 9); end Main;
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Fivenum { public static class Helper { public static string AsString<T>(this ICollection<T> c, string format = "{0}") { StringBuilder sb = new StringBuilder("["); int count = 0; foreach (var t in c) { if (count++ > 0) { sb.Append(", "); } sb.AppendFormat(format, t); } return sb.Append("]").ToString(); } } class Program { static double Median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new ArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] Fivenum(double[] x) { foreach (var d in x) { if (Double.IsNaN(d)) { throw new ArgumentException("Unable to deal with arrays containing NaN"); } } double[] result = new double[5]; Array.Sort(x); result[0] = x.First(); result[2] = Median(x, 0, x.Length - 1); result[4] = x.Last(); int m = x.Length / 2; int lowerEnd = (x.Length % 2 == 1) ? m : m - 1; result[1] = Median(x, 0, lowerEnd); result[3] = Median(x, m, x.Length - 1); return result; } static void Main(string[] args) { double[][] x1 = new double[][]{ new double[]{ 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, new double[]{ 36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, new double[]{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }, }; foreach(var x in x1) { var result = Fivenum(x); Console.WriteLine(result.AsString("{0:F8}")); } } } }
Write the same code in C as shown below in Ada.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Generic_Array_Sort; procedure Main is package Real_Io is new Float_IO (Long_Float); use Real_Io; type Data_Array is array (Natural range <>) of Long_Float; subtype Five_Num_Type is Data_Array (0 .. 4); procedure Sort is new Ada.Containers.Generic_Array_Sort (Index_Type => Natural, Element_Type => Long_Float, Array_Type => Data_Array); function Median (X : Data_Array) return Long_Float with Pre => X'Length > 0; function Median (X : Data_Array) return Long_Float is M : constant Natural := X'First + X'Last / 2; begin if X'Length rem 2 = 1 then return X (M); else return (X (M - 1) + X (M)) / 2.0; end if; end Median; procedure fivenum (X : Data_Array; Result : out Five_Num_Type) is Temp : Data_Array := X; m : Natural := X'Length / 2; Lower_end : Natural := (if X'Length rem 2 = 0 then m - 1 else m); begin Sort (Temp); Result (0) := Temp (Temp'First); Result (2) := Median (Temp); Result (4) := Temp (Temp'Last); Result (1) := Median (Temp (1 .. Lower_end)); Result (3) := Median (Temp (m .. Temp'Last)); end fivenum; procedure print (Result : Five_Num_Type; Aft : Natural) is begin Put ("["); for I in Result'Range loop Put (Item => Result (I), Fore => 1, Aft => Aft, Exp => 0); if I < Result'Last then Put (", "); else Put_Line ("]"); end if; end loop; New_Line; end print; X1 : Data_Array := (15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0); X2 : Data_Array := (36.0, 40.0, 7.0, 39.0, 41.0, 15.0); X3 : Data_Array := (0.140_828_34, 0.097_487_90, 1.731_315_07, 0.876_360_09, -1.950_595_94, 0.734_385_55, -0.030_357_26, 1.466_759_70, -0.746_213_49, -0.725_887_72, 0.639_051_60, 0.615_015_27, -0.989_837_80, -1.004_478_74, -0.627_594_69, 0.662_061_63, 1.043_120_09, -0.103_053_85, 0.757_756_34, 0.325_665_78); Result : Five_Num_Type; begin fivenum (X1, Result); print (Result, 1); fivenum (X2, Result); print (Result, 1); fivenum (X3, Result); print (Result, 9); end Main;
#include <stdio.h> #include <stdlib.h> double median(double *x, int start, int end_inclusive) { int size = end_inclusive - start + 1; if (size <= 0) { printf("Array slice cannot be empty\n"); exit(1); } int m = start + size / 2; if (size % 2) return x[m]; return (x[m - 1] + x[m]) / 2.0; } int compare (const void *a, const void *b) { double aa = *(double*)a; double bb = *(double*)b; if (aa > bb) return 1; if (aa < bb) return -1; return 0; } int fivenum(double *x, double *result, int x_len) { int i, m, lower_end; for (i = 0; i < x_len; i++) { if (x[i] != x[i]) { printf("Unable to deal with arrays containing NaN\n\n"); return 1; } } qsort(x, x_len, sizeof(double), compare); result[0] = x[0]; result[2] = median(x, 0, x_len - 1); result[4] = x[x_len - 1]; m = x_len / 2; lower_end = (x_len % 2) ? m : m - 1; result[1] = median(x, 0, lower_end); result[3] = median(x, m, x_len - 1); return 0; } int show(double *result, int places) { int i; char f[7]; sprintf(f, "%%.%dlf", places); printf("["); for (i = 0; i < 5; i++) { printf(f, result[i]); if (i < 4) printf(", "); } printf("]\n\n"); } int main() { double result[5]; double x1[11] = {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}; if (!fivenum(x1, result, 11)) show(result, 1); double x2[6] = {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}; if (!fivenum(x2, result, 6)) show(result, 1); double x3[20] = { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }; if (!fivenum(x3, result, 20)) show(result, 9); return 0; }
Preserve the algorithm and functionality while converting the code from Ada to C.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Generic_Array_Sort; procedure Main is package Real_Io is new Float_IO (Long_Float); use Real_Io; type Data_Array is array (Natural range <>) of Long_Float; subtype Five_Num_Type is Data_Array (0 .. 4); procedure Sort is new Ada.Containers.Generic_Array_Sort (Index_Type => Natural, Element_Type => Long_Float, Array_Type => Data_Array); function Median (X : Data_Array) return Long_Float with Pre => X'Length > 0; function Median (X : Data_Array) return Long_Float is M : constant Natural := X'First + X'Last / 2; begin if X'Length rem 2 = 1 then return X (M); else return (X (M - 1) + X (M)) / 2.0; end if; end Median; procedure fivenum (X : Data_Array; Result : out Five_Num_Type) is Temp : Data_Array := X; m : Natural := X'Length / 2; Lower_end : Natural := (if X'Length rem 2 = 0 then m - 1 else m); begin Sort (Temp); Result (0) := Temp (Temp'First); Result (2) := Median (Temp); Result (4) := Temp (Temp'Last); Result (1) := Median (Temp (1 .. Lower_end)); Result (3) := Median (Temp (m .. Temp'Last)); end fivenum; procedure print (Result : Five_Num_Type; Aft : Natural) is begin Put ("["); for I in Result'Range loop Put (Item => Result (I), Fore => 1, Aft => Aft, Exp => 0); if I < Result'Last then Put (", "); else Put_Line ("]"); end if; end loop; New_Line; end print; X1 : Data_Array := (15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0); X2 : Data_Array := (36.0, 40.0, 7.0, 39.0, 41.0, 15.0); X3 : Data_Array := (0.140_828_34, 0.097_487_90, 1.731_315_07, 0.876_360_09, -1.950_595_94, 0.734_385_55, -0.030_357_26, 1.466_759_70, -0.746_213_49, -0.725_887_72, 0.639_051_60, 0.615_015_27, -0.989_837_80, -1.004_478_74, -0.627_594_69, 0.662_061_63, 1.043_120_09, -0.103_053_85, 0.757_756_34, 0.325_665_78); Result : Five_Num_Type; begin fivenum (X1, Result); print (Result, 1); fivenum (X2, Result); print (Result, 1); fivenum (X3, Result); print (Result, 9); end Main;
#include <stdio.h> #include <stdlib.h> double median(double *x, int start, int end_inclusive) { int size = end_inclusive - start + 1; if (size <= 0) { printf("Array slice cannot be empty\n"); exit(1); } int m = start + size / 2; if (size % 2) return x[m]; return (x[m - 1] + x[m]) / 2.0; } int compare (const void *a, const void *b) { double aa = *(double*)a; double bb = *(double*)b; if (aa > bb) return 1; if (aa < bb) return -1; return 0; } int fivenum(double *x, double *result, int x_len) { int i, m, lower_end; for (i = 0; i < x_len; i++) { if (x[i] != x[i]) { printf("Unable to deal with arrays containing NaN\n\n"); return 1; } } qsort(x, x_len, sizeof(double), compare); result[0] = x[0]; result[2] = median(x, 0, x_len - 1); result[4] = x[x_len - 1]; m = x_len / 2; lower_end = (x_len % 2) ? m : m - 1; result[1] = median(x, 0, lower_end); result[3] = median(x, m, x_len - 1); return 0; } int show(double *result, int places) { int i; char f[7]; sprintf(f, "%%.%dlf", places); printf("["); for (i = 0; i < 5; i++) { printf(f, result[i]); if (i < 4) printf(", "); } printf("]\n\n"); } int main() { double result[5]; double x1[11] = {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}; if (!fivenum(x1, result, 11)) show(result, 1); double x2[6] = {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}; if (!fivenum(x2, result, 6)) show(result, 1); double x3[20] = { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }; if (!fivenum(x3, result, 20)) show(result, 9); return 0; }
Write the same algorithm in C++ as shown in this Ada implementation.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Generic_Array_Sort; procedure Main is package Real_Io is new Float_IO (Long_Float); use Real_Io; type Data_Array is array (Natural range <>) of Long_Float; subtype Five_Num_Type is Data_Array (0 .. 4); procedure Sort is new Ada.Containers.Generic_Array_Sort (Index_Type => Natural, Element_Type => Long_Float, Array_Type => Data_Array); function Median (X : Data_Array) return Long_Float with Pre => X'Length > 0; function Median (X : Data_Array) return Long_Float is M : constant Natural := X'First + X'Last / 2; begin if X'Length rem 2 = 1 then return X (M); else return (X (M - 1) + X (M)) / 2.0; end if; end Median; procedure fivenum (X : Data_Array; Result : out Five_Num_Type) is Temp : Data_Array := X; m : Natural := X'Length / 2; Lower_end : Natural := (if X'Length rem 2 = 0 then m - 1 else m); begin Sort (Temp); Result (0) := Temp (Temp'First); Result (2) := Median (Temp); Result (4) := Temp (Temp'Last); Result (1) := Median (Temp (1 .. Lower_end)); Result (3) := Median (Temp (m .. Temp'Last)); end fivenum; procedure print (Result : Five_Num_Type; Aft : Natural) is begin Put ("["); for I in Result'Range loop Put (Item => Result (I), Fore => 1, Aft => Aft, Exp => 0); if I < Result'Last then Put (", "); else Put_Line ("]"); end if; end loop; New_Line; end print; X1 : Data_Array := (15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0); X2 : Data_Array := (36.0, 40.0, 7.0, 39.0, 41.0, 15.0); X3 : Data_Array := (0.140_828_34, 0.097_487_90, 1.731_315_07, 0.876_360_09, -1.950_595_94, 0.734_385_55, -0.030_357_26, 1.466_759_70, -0.746_213_49, -0.725_887_72, 0.639_051_60, 0.615_015_27, -0.989_837_80, -1.004_478_74, -0.627_594_69, 0.662_061_63, 1.043_120_09, -0.103_053_85, 0.757_756_34, 0.325_665_78); Result : Five_Num_Type; begin fivenum (X1, Result); print (Result, 1); fivenum (X2, Result); print (Result, 1); fivenum (X3, Result); print (Result, 9); end Main;
#include <algorithm> #include <iostream> #include <ostream> #include <vector> template<std::size_t> struct int_ {}; template <class Tuple, size_t Pos> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<Pos>) { out << std::get< std::tuple_size<Tuple>::value - Pos >(t) << ", "; return print_tuple(out, t, int_<Pos - 1>()); } template <class Tuple> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<1>) { return out << std::get<std::tuple_size<Tuple>::value - 1>(t); } template <class... Args> std::ostream& operator<<(std::ostream& out, const std::tuple<Args...>& t) { out << '('; print_tuple(out, t, int_<sizeof...(Args)>()); return out << ')'; } template <class RI> double median(RI beg, RI end) { if (beg == end) throw std::runtime_error("Range cannot be empty"); auto len = end - beg; auto m = len / 2; if (len % 2 == 1) { return *(beg + m); } return (beg[m - 1] + beg[m]) / 2.0; } template <class C> auto fivenum(C& c) { std::sort(c.begin(), c.end()); auto cbeg = c.cbegin(); auto cend = c.cend(); auto len = cend - cbeg; auto m = len / 2; auto lower = (len % 2 == 1) ? m : m - 1; double r2 = median(cbeg, cbeg + lower + 1); double r3 = median(cbeg, cend); double r4 = median(cbeg + lower + 1, cend); return std::make_tuple(*cbeg, r2, r3, r4, *(cend - 1)); } int main() { using namespace std; vector<vector<double>> cs = { { 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0 }, { 36.0, 40.0, 7.0, 39.0, 41.0, 15.0 }, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (auto & c : cs) { cout << fivenum(c) << endl; } return 0; }
Change the programming language of this snippet from Ada to C++ without modifying what it does.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Generic_Array_Sort; procedure Main is package Real_Io is new Float_IO (Long_Float); use Real_Io; type Data_Array is array (Natural range <>) of Long_Float; subtype Five_Num_Type is Data_Array (0 .. 4); procedure Sort is new Ada.Containers.Generic_Array_Sort (Index_Type => Natural, Element_Type => Long_Float, Array_Type => Data_Array); function Median (X : Data_Array) return Long_Float with Pre => X'Length > 0; function Median (X : Data_Array) return Long_Float is M : constant Natural := X'First + X'Last / 2; begin if X'Length rem 2 = 1 then return X (M); else return (X (M - 1) + X (M)) / 2.0; end if; end Median; procedure fivenum (X : Data_Array; Result : out Five_Num_Type) is Temp : Data_Array := X; m : Natural := X'Length / 2; Lower_end : Natural := (if X'Length rem 2 = 0 then m - 1 else m); begin Sort (Temp); Result (0) := Temp (Temp'First); Result (2) := Median (Temp); Result (4) := Temp (Temp'Last); Result (1) := Median (Temp (1 .. Lower_end)); Result (3) := Median (Temp (m .. Temp'Last)); end fivenum; procedure print (Result : Five_Num_Type; Aft : Natural) is begin Put ("["); for I in Result'Range loop Put (Item => Result (I), Fore => 1, Aft => Aft, Exp => 0); if I < Result'Last then Put (", "); else Put_Line ("]"); end if; end loop; New_Line; end print; X1 : Data_Array := (15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0); X2 : Data_Array := (36.0, 40.0, 7.0, 39.0, 41.0, 15.0); X3 : Data_Array := (0.140_828_34, 0.097_487_90, 1.731_315_07, 0.876_360_09, -1.950_595_94, 0.734_385_55, -0.030_357_26, 1.466_759_70, -0.746_213_49, -0.725_887_72, 0.639_051_60, 0.615_015_27, -0.989_837_80, -1.004_478_74, -0.627_594_69, 0.662_061_63, 1.043_120_09, -0.103_053_85, 0.757_756_34, 0.325_665_78); Result : Five_Num_Type; begin fivenum (X1, Result); print (Result, 1); fivenum (X2, Result); print (Result, 1); fivenum (X3, Result); print (Result, 9); end Main;
#include <algorithm> #include <iostream> #include <ostream> #include <vector> template<std::size_t> struct int_ {}; template <class Tuple, size_t Pos> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<Pos>) { out << std::get< std::tuple_size<Tuple>::value - Pos >(t) << ", "; return print_tuple(out, t, int_<Pos - 1>()); } template <class Tuple> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<1>) { return out << std::get<std::tuple_size<Tuple>::value - 1>(t); } template <class... Args> std::ostream& operator<<(std::ostream& out, const std::tuple<Args...>& t) { out << '('; print_tuple(out, t, int_<sizeof...(Args)>()); return out << ')'; } template <class RI> double median(RI beg, RI end) { if (beg == end) throw std::runtime_error("Range cannot be empty"); auto len = end - beg; auto m = len / 2; if (len % 2 == 1) { return *(beg + m); } return (beg[m - 1] + beg[m]) / 2.0; } template <class C> auto fivenum(C& c) { std::sort(c.begin(), c.end()); auto cbeg = c.cbegin(); auto cend = c.cend(); auto len = cend - cbeg; auto m = len / 2; auto lower = (len % 2 == 1) ? m : m - 1; double r2 = median(cbeg, cbeg + lower + 1); double r3 = median(cbeg, cend); double r4 = median(cbeg + lower + 1, cend); return std::make_tuple(*cbeg, r2, r3, r4, *(cend - 1)); } int main() { using namespace std; vector<vector<double>> cs = { { 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0 }, { 36.0, 40.0, 7.0, 39.0, 41.0, 15.0 }, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (auto & c : cs) { cout << fivenum(c) << endl; } return 0; }
Generate an equivalent Go version of this Ada code.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Generic_Array_Sort; procedure Main is package Real_Io is new Float_IO (Long_Float); use Real_Io; type Data_Array is array (Natural range <>) of Long_Float; subtype Five_Num_Type is Data_Array (0 .. 4); procedure Sort is new Ada.Containers.Generic_Array_Sort (Index_Type => Natural, Element_Type => Long_Float, Array_Type => Data_Array); function Median (X : Data_Array) return Long_Float with Pre => X'Length > 0; function Median (X : Data_Array) return Long_Float is M : constant Natural := X'First + X'Last / 2; begin if X'Length rem 2 = 1 then return X (M); else return (X (M - 1) + X (M)) / 2.0; end if; end Median; procedure fivenum (X : Data_Array; Result : out Five_Num_Type) is Temp : Data_Array := X; m : Natural := X'Length / 2; Lower_end : Natural := (if X'Length rem 2 = 0 then m - 1 else m); begin Sort (Temp); Result (0) := Temp (Temp'First); Result (2) := Median (Temp); Result (4) := Temp (Temp'Last); Result (1) := Median (Temp (1 .. Lower_end)); Result (3) := Median (Temp (m .. Temp'Last)); end fivenum; procedure print (Result : Five_Num_Type; Aft : Natural) is begin Put ("["); for I in Result'Range loop Put (Item => Result (I), Fore => 1, Aft => Aft, Exp => 0); if I < Result'Last then Put (", "); else Put_Line ("]"); end if; end loop; New_Line; end print; X1 : Data_Array := (15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0); X2 : Data_Array := (36.0, 40.0, 7.0, 39.0, 41.0, 15.0); X3 : Data_Array := (0.140_828_34, 0.097_487_90, 1.731_315_07, 0.876_360_09, -1.950_595_94, 0.734_385_55, -0.030_357_26, 1.466_759_70, -0.746_213_49, -0.725_887_72, 0.639_051_60, 0.615_015_27, -0.989_837_80, -1.004_478_74, -0.627_594_69, 0.662_061_63, 1.043_120_09, -0.103_053_85, 0.757_756_34, 0.325_665_78); Result : Five_Num_Type; begin fivenum (X1, Result); print (Result, 1); fivenum (X2, Result); print (Result, 1); fivenum (X3, Result); print (Result, 9); end Main;
package main import ( "fmt" "math" "sort" ) func fivenum(a []float64) (n5 [5]float64) { sort.Float64s(a) n := float64(len(a)) n4 := float64((len(a)+3)/2) / 2 d := []float64{1, n4, (n + 1) / 2, n + 1 - n4, n} for e, de := range d { floor := int(de - 1) ceil := int(math.Ceil(de - 1)) n5[e] = .5 * (a[floor] + a[ceil]) } return } var ( x1 = []float64{36, 40, 7, 39, 41, 15} x2 = []float64{15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43} x3 = []float64{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578, } ) func main() { fmt.Println(fivenum(x1)) fmt.Println(fivenum(x2)) fmt.Println(fivenum(x3)) }
Convert this Ada block to Go, preserving its control flow and logic.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Generic_Array_Sort; procedure Main is package Real_Io is new Float_IO (Long_Float); use Real_Io; type Data_Array is array (Natural range <>) of Long_Float; subtype Five_Num_Type is Data_Array (0 .. 4); procedure Sort is new Ada.Containers.Generic_Array_Sort (Index_Type => Natural, Element_Type => Long_Float, Array_Type => Data_Array); function Median (X : Data_Array) return Long_Float with Pre => X'Length > 0; function Median (X : Data_Array) return Long_Float is M : constant Natural := X'First + X'Last / 2; begin if X'Length rem 2 = 1 then return X (M); else return (X (M - 1) + X (M)) / 2.0; end if; end Median; procedure fivenum (X : Data_Array; Result : out Five_Num_Type) is Temp : Data_Array := X; m : Natural := X'Length / 2; Lower_end : Natural := (if X'Length rem 2 = 0 then m - 1 else m); begin Sort (Temp); Result (0) := Temp (Temp'First); Result (2) := Median (Temp); Result (4) := Temp (Temp'Last); Result (1) := Median (Temp (1 .. Lower_end)); Result (3) := Median (Temp (m .. Temp'Last)); end fivenum; procedure print (Result : Five_Num_Type; Aft : Natural) is begin Put ("["); for I in Result'Range loop Put (Item => Result (I), Fore => 1, Aft => Aft, Exp => 0); if I < Result'Last then Put (", "); else Put_Line ("]"); end if; end loop; New_Line; end print; X1 : Data_Array := (15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0); X2 : Data_Array := (36.0, 40.0, 7.0, 39.0, 41.0, 15.0); X3 : Data_Array := (0.140_828_34, 0.097_487_90, 1.731_315_07, 0.876_360_09, -1.950_595_94, 0.734_385_55, -0.030_357_26, 1.466_759_70, -0.746_213_49, -0.725_887_72, 0.639_051_60, 0.615_015_27, -0.989_837_80, -1.004_478_74, -0.627_594_69, 0.662_061_63, 1.043_120_09, -0.103_053_85, 0.757_756_34, 0.325_665_78); Result : Five_Num_Type; begin fivenum (X1, Result); print (Result, 1); fivenum (X2, Result); print (Result, 1); fivenum (X3, Result); print (Result, 9); end Main;
package main import ( "fmt" "math" "sort" ) func fivenum(a []float64) (n5 [5]float64) { sort.Float64s(a) n := float64(len(a)) n4 := float64((len(a)+3)/2) / 2 d := []float64{1, n4, (n + 1) / 2, n + 1 - n4, n} for e, de := range d { floor := int(de - 1) ceil := int(math.Ceil(de - 1)) n5[e] = .5 * (a[floor] + a[ceil]) } return } var ( x1 = []float64{36, 40, 7, 39, 41, 15} x2 = []float64{15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43} x3 = []float64{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578, } ) func main() { fmt.Println(fivenum(x1)) fmt.Println(fivenum(x2)) fmt.Println(fivenum(x3)) }
Generate an equivalent Java version of this Ada code.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Generic_Array_Sort; procedure Main is package Real_Io is new Float_IO (Long_Float); use Real_Io; type Data_Array is array (Natural range <>) of Long_Float; subtype Five_Num_Type is Data_Array (0 .. 4); procedure Sort is new Ada.Containers.Generic_Array_Sort (Index_Type => Natural, Element_Type => Long_Float, Array_Type => Data_Array); function Median (X : Data_Array) return Long_Float with Pre => X'Length > 0; function Median (X : Data_Array) return Long_Float is M : constant Natural := X'First + X'Last / 2; begin if X'Length rem 2 = 1 then return X (M); else return (X (M - 1) + X (M)) / 2.0; end if; end Median; procedure fivenum (X : Data_Array; Result : out Five_Num_Type) is Temp : Data_Array := X; m : Natural := X'Length / 2; Lower_end : Natural := (if X'Length rem 2 = 0 then m - 1 else m); begin Sort (Temp); Result (0) := Temp (Temp'First); Result (2) := Median (Temp); Result (4) := Temp (Temp'Last); Result (1) := Median (Temp (1 .. Lower_end)); Result (3) := Median (Temp (m .. Temp'Last)); end fivenum; procedure print (Result : Five_Num_Type; Aft : Natural) is begin Put ("["); for I in Result'Range loop Put (Item => Result (I), Fore => 1, Aft => Aft, Exp => 0); if I < Result'Last then Put (", "); else Put_Line ("]"); end if; end loop; New_Line; end print; X1 : Data_Array := (15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0); X2 : Data_Array := (36.0, 40.0, 7.0, 39.0, 41.0, 15.0); X3 : Data_Array := (0.140_828_34, 0.097_487_90, 1.731_315_07, 0.876_360_09, -1.950_595_94, 0.734_385_55, -0.030_357_26, 1.466_759_70, -0.746_213_49, -0.725_887_72, 0.639_051_60, 0.615_015_27, -0.989_837_80, -1.004_478_74, -0.627_594_69, 0.662_061_63, 1.043_120_09, -0.103_053_85, 0.757_756_34, 0.325_665_78); Result : Five_Num_Type; begin fivenum (X1, Result); print (Result, 1); fivenum (X2, Result); print (Result, 1); fivenum (X3, Result); print (Result, 9); end Main;
import java.util.Arrays; public class Fivenum { static double median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new IllegalArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] fivenum(double[] x) { for (Double d : x) { if (d.isNaN()) throw new IllegalArgumentException("Unable to deal with arrays containing NaN"); } double[] result = new double[5]; Arrays.sort(x); result[0] = x[0]; result[2] = median(x, 0, x.length - 1); result[4] = x[x.length - 1]; int m = x.length / 2; int lowerEnd = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x, 0, lowerEnd); result[3] = median(x, m, x.length - 1); return result; } public static void main(String[] args) { double xl[][] = { {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (double[] x : xl) System.out.printf("%s\n\n", Arrays.toString(fivenum(x))); } }
Preserve the algorithm and functionality while converting the code from Ada to Java.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Generic_Array_Sort; procedure Main is package Real_Io is new Float_IO (Long_Float); use Real_Io; type Data_Array is array (Natural range <>) of Long_Float; subtype Five_Num_Type is Data_Array (0 .. 4); procedure Sort is new Ada.Containers.Generic_Array_Sort (Index_Type => Natural, Element_Type => Long_Float, Array_Type => Data_Array); function Median (X : Data_Array) return Long_Float with Pre => X'Length > 0; function Median (X : Data_Array) return Long_Float is M : constant Natural := X'First + X'Last / 2; begin if X'Length rem 2 = 1 then return X (M); else return (X (M - 1) + X (M)) / 2.0; end if; end Median; procedure fivenum (X : Data_Array; Result : out Five_Num_Type) is Temp : Data_Array := X; m : Natural := X'Length / 2; Lower_end : Natural := (if X'Length rem 2 = 0 then m - 1 else m); begin Sort (Temp); Result (0) := Temp (Temp'First); Result (2) := Median (Temp); Result (4) := Temp (Temp'Last); Result (1) := Median (Temp (1 .. Lower_end)); Result (3) := Median (Temp (m .. Temp'Last)); end fivenum; procedure print (Result : Five_Num_Type; Aft : Natural) is begin Put ("["); for I in Result'Range loop Put (Item => Result (I), Fore => 1, Aft => Aft, Exp => 0); if I < Result'Last then Put (", "); else Put_Line ("]"); end if; end loop; New_Line; end print; X1 : Data_Array := (15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0); X2 : Data_Array := (36.0, 40.0, 7.0, 39.0, 41.0, 15.0); X3 : Data_Array := (0.140_828_34, 0.097_487_90, 1.731_315_07, 0.876_360_09, -1.950_595_94, 0.734_385_55, -0.030_357_26, 1.466_759_70, -0.746_213_49, -0.725_887_72, 0.639_051_60, 0.615_015_27, -0.989_837_80, -1.004_478_74, -0.627_594_69, 0.662_061_63, 1.043_120_09, -0.103_053_85, 0.757_756_34, 0.325_665_78); Result : Five_Num_Type; begin fivenum (X1, Result); print (Result, 1); fivenum (X2, Result); print (Result, 1); fivenum (X3, Result); print (Result, 9); end Main;
import java.util.Arrays; public class Fivenum { static double median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new IllegalArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] fivenum(double[] x) { for (Double d : x) { if (d.isNaN()) throw new IllegalArgumentException("Unable to deal with arrays containing NaN"); } double[] result = new double[5]; Arrays.sort(x); result[0] = x[0]; result[2] = median(x, 0, x.length - 1); result[4] = x[x.length - 1]; int m = x.length / 2; int lowerEnd = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x, 0, lowerEnd); result[3] = median(x, m, x.length - 1); return result; } public static void main(String[] args) { double xl[][] = { {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (double[] x : xl) System.out.printf("%s\n\n", Arrays.toString(fivenum(x))); } }
Preserve the algorithm and functionality while converting the code from Ada to Python.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Generic_Array_Sort; procedure Main is package Real_Io is new Float_IO (Long_Float); use Real_Io; type Data_Array is array (Natural range <>) of Long_Float; subtype Five_Num_Type is Data_Array (0 .. 4); procedure Sort is new Ada.Containers.Generic_Array_Sort (Index_Type => Natural, Element_Type => Long_Float, Array_Type => Data_Array); function Median (X : Data_Array) return Long_Float with Pre => X'Length > 0; function Median (X : Data_Array) return Long_Float is M : constant Natural := X'First + X'Last / 2; begin if X'Length rem 2 = 1 then return X (M); else return (X (M - 1) + X (M)) / 2.0; end if; end Median; procedure fivenum (X : Data_Array; Result : out Five_Num_Type) is Temp : Data_Array := X; m : Natural := X'Length / 2; Lower_end : Natural := (if X'Length rem 2 = 0 then m - 1 else m); begin Sort (Temp); Result (0) := Temp (Temp'First); Result (2) := Median (Temp); Result (4) := Temp (Temp'Last); Result (1) := Median (Temp (1 .. Lower_end)); Result (3) := Median (Temp (m .. Temp'Last)); end fivenum; procedure print (Result : Five_Num_Type; Aft : Natural) is begin Put ("["); for I in Result'Range loop Put (Item => Result (I), Fore => 1, Aft => Aft, Exp => 0); if I < Result'Last then Put (", "); else Put_Line ("]"); end if; end loop; New_Line; end print; X1 : Data_Array := (15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0); X2 : Data_Array := (36.0, 40.0, 7.0, 39.0, 41.0, 15.0); X3 : Data_Array := (0.140_828_34, 0.097_487_90, 1.731_315_07, 0.876_360_09, -1.950_595_94, 0.734_385_55, -0.030_357_26, 1.466_759_70, -0.746_213_49, -0.725_887_72, 0.639_051_60, 0.615_015_27, -0.989_837_80, -1.004_478_74, -0.627_594_69, 0.662_061_63, 1.043_120_09, -0.103_053_85, 0.757_756_34, 0.325_665_78); Result : Five_Num_Type; begin fivenum (X1, Result); print (Result, 1); fivenum (X2, Result); print (Result, 1); fivenum (X3, Result); print (Result, 9); end Main;
from __future__ import division import math import sys def fivenum(array): n = len(array) if n == 0: print("you entered an empty array.") sys.exit() x = sorted(array) n4 = math.floor((n+3.0)/2.0)/2.0 d = [1, n4, (n+1)/2, n+1-n4, n] sum_array = [] for e in range(5): floor = int(math.floor(d[e] - 1)) ceil = int(math.ceil(d[e] - 1)) sum_array.append(0.5 * (x[floor] + x[ceil])) return sum_array x = [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578] y = fivenum(x) print(y)
Port the following code from Ada to Python with equivalent syntax and logic.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Generic_Array_Sort; procedure Main is package Real_Io is new Float_IO (Long_Float); use Real_Io; type Data_Array is array (Natural range <>) of Long_Float; subtype Five_Num_Type is Data_Array (0 .. 4); procedure Sort is new Ada.Containers.Generic_Array_Sort (Index_Type => Natural, Element_Type => Long_Float, Array_Type => Data_Array); function Median (X : Data_Array) return Long_Float with Pre => X'Length > 0; function Median (X : Data_Array) return Long_Float is M : constant Natural := X'First + X'Last / 2; begin if X'Length rem 2 = 1 then return X (M); else return (X (M - 1) + X (M)) / 2.0; end if; end Median; procedure fivenum (X : Data_Array; Result : out Five_Num_Type) is Temp : Data_Array := X; m : Natural := X'Length / 2; Lower_end : Natural := (if X'Length rem 2 = 0 then m - 1 else m); begin Sort (Temp); Result (0) := Temp (Temp'First); Result (2) := Median (Temp); Result (4) := Temp (Temp'Last); Result (1) := Median (Temp (1 .. Lower_end)); Result (3) := Median (Temp (m .. Temp'Last)); end fivenum; procedure print (Result : Five_Num_Type; Aft : Natural) is begin Put ("["); for I in Result'Range loop Put (Item => Result (I), Fore => 1, Aft => Aft, Exp => 0); if I < Result'Last then Put (", "); else Put_Line ("]"); end if; end loop; New_Line; end print; X1 : Data_Array := (15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0); X2 : Data_Array := (36.0, 40.0, 7.0, 39.0, 41.0, 15.0); X3 : Data_Array := (0.140_828_34, 0.097_487_90, 1.731_315_07, 0.876_360_09, -1.950_595_94, 0.734_385_55, -0.030_357_26, 1.466_759_70, -0.746_213_49, -0.725_887_72, 0.639_051_60, 0.615_015_27, -0.989_837_80, -1.004_478_74, -0.627_594_69, 0.662_061_63, 1.043_120_09, -0.103_053_85, 0.757_756_34, 0.325_665_78); Result : Five_Num_Type; begin fivenum (X1, Result); print (Result, 1); fivenum (X2, Result); print (Result, 1); fivenum (X3, Result); print (Result, 9); end Main;
from __future__ import division import math import sys def fivenum(array): n = len(array) if n == 0: print("you entered an empty array.") sys.exit() x = sorted(array) n4 = math.floor((n+3.0)/2.0)/2.0 d = [1, n4, (n+1)/2, n+1-n4, n] sum_array = [] for e in range(5): floor = int(math.floor(d[e] - 1)) ceil = int(math.ceil(d[e] - 1)) sum_array.append(0.5 * (x[floor] + x[ceil])) return sum_array x = [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578] y = fivenum(x) print(y)
Translate the given Ada code snippet into VB without altering its behavior.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Generic_Array_Sort; procedure Main is package Real_Io is new Float_IO (Long_Float); use Real_Io; type Data_Array is array (Natural range <>) of Long_Float; subtype Five_Num_Type is Data_Array (0 .. 4); procedure Sort is new Ada.Containers.Generic_Array_Sort (Index_Type => Natural, Element_Type => Long_Float, Array_Type => Data_Array); function Median (X : Data_Array) return Long_Float with Pre => X'Length > 0; function Median (X : Data_Array) return Long_Float is M : constant Natural := X'First + X'Last / 2; begin if X'Length rem 2 = 1 then return X (M); else return (X (M - 1) + X (M)) / 2.0; end if; end Median; procedure fivenum (X : Data_Array; Result : out Five_Num_Type) is Temp : Data_Array := X; m : Natural := X'Length / 2; Lower_end : Natural := (if X'Length rem 2 = 0 then m - 1 else m); begin Sort (Temp); Result (0) := Temp (Temp'First); Result (2) := Median (Temp); Result (4) := Temp (Temp'Last); Result (1) := Median (Temp (1 .. Lower_end)); Result (3) := Median (Temp (m .. Temp'Last)); end fivenum; procedure print (Result : Five_Num_Type; Aft : Natural) is begin Put ("["); for I in Result'Range loop Put (Item => Result (I), Fore => 1, Aft => Aft, Exp => 0); if I < Result'Last then Put (", "); else Put_Line ("]"); end if; end loop; New_Line; end print; X1 : Data_Array := (15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0); X2 : Data_Array := (36.0, 40.0, 7.0, 39.0, 41.0, 15.0); X3 : Data_Array := (0.140_828_34, 0.097_487_90, 1.731_315_07, 0.876_360_09, -1.950_595_94, 0.734_385_55, -0.030_357_26, 1.466_759_70, -0.746_213_49, -0.725_887_72, 0.639_051_60, 0.615_015_27, -0.989_837_80, -1.004_478_74, -0.627_594_69, 0.662_061_63, 1.043_120_09, -0.103_053_85, 0.757_756_34, 0.325_665_78); Result : Five_Num_Type; begin fivenum (X1, Result); print (Result, 1); fivenum (X2, Result); print (Result, 1); fivenum (X3, Result); print (Result, 9); end Main;
Option Base 1 Private Function median(tbl As Variant, lo As Integer, hi As Integer) Dim l As Integer: l = hi - lo + 1 Dim m As Integer: m = lo + WorksheetFunction.Floor_Precise(l / 2) If l Mod 2 = 1 Then median = tbl(m) Else median = (tbl(m - 1) + tbl(m)) / 2 End if End Function Private Function fivenum(tbl As Variant) As Variant Sort tbl, UBound(tbl) Dim l As Integer: l = UBound(tbl) Dim m As Integer: m = WorksheetFunction.Floor_Precise(l / 2) + l Mod 2 Dim r(5) As String r(1) = CStr(tbl(1)) r(2) = CStr(median(tbl, 1, m)) r(3) = CStr(median(tbl, 1, l)) r(4) = CStr(median(tbl, m + 1, l)) r(5) = CStr(tbl(l)) fivenum = r End Function Public Sub main() Dim x1 As Variant, x2 As Variant, x3 As Variant x1 = [{15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43}] x2 = [{36, 40, 7, 39, 41, 15}] x3 = [{0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578}] Debug.Print Join(fivenum(x1), " | ") Debug.Print Join(fivenum(x2), " | ") Debug.Print Join(fivenum(x3), " | ") End Sub
Generate an equivalent VB version of this Ada code.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Generic_Array_Sort; procedure Main is package Real_Io is new Float_IO (Long_Float); use Real_Io; type Data_Array is array (Natural range <>) of Long_Float; subtype Five_Num_Type is Data_Array (0 .. 4); procedure Sort is new Ada.Containers.Generic_Array_Sort (Index_Type => Natural, Element_Type => Long_Float, Array_Type => Data_Array); function Median (X : Data_Array) return Long_Float with Pre => X'Length > 0; function Median (X : Data_Array) return Long_Float is M : constant Natural := X'First + X'Last / 2; begin if X'Length rem 2 = 1 then return X (M); else return (X (M - 1) + X (M)) / 2.0; end if; end Median; procedure fivenum (X : Data_Array; Result : out Five_Num_Type) is Temp : Data_Array := X; m : Natural := X'Length / 2; Lower_end : Natural := (if X'Length rem 2 = 0 then m - 1 else m); begin Sort (Temp); Result (0) := Temp (Temp'First); Result (2) := Median (Temp); Result (4) := Temp (Temp'Last); Result (1) := Median (Temp (1 .. Lower_end)); Result (3) := Median (Temp (m .. Temp'Last)); end fivenum; procedure print (Result : Five_Num_Type; Aft : Natural) is begin Put ("["); for I in Result'Range loop Put (Item => Result (I), Fore => 1, Aft => Aft, Exp => 0); if I < Result'Last then Put (", "); else Put_Line ("]"); end if; end loop; New_Line; end print; X1 : Data_Array := (15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0); X2 : Data_Array := (36.0, 40.0, 7.0, 39.0, 41.0, 15.0); X3 : Data_Array := (0.140_828_34, 0.097_487_90, 1.731_315_07, 0.876_360_09, -1.950_595_94, 0.734_385_55, -0.030_357_26, 1.466_759_70, -0.746_213_49, -0.725_887_72, 0.639_051_60, 0.615_015_27, -0.989_837_80, -1.004_478_74, -0.627_594_69, 0.662_061_63, 1.043_120_09, -0.103_053_85, 0.757_756_34, 0.325_665_78); Result : Five_Num_Type; begin fivenum (X1, Result); print (Result, 1); fivenum (X2, Result); print (Result, 1); fivenum (X3, Result); print (Result, 9); end Main;
Option Base 1 Private Function median(tbl As Variant, lo As Integer, hi As Integer) Dim l As Integer: l = hi - lo + 1 Dim m As Integer: m = lo + WorksheetFunction.Floor_Precise(l / 2) If l Mod 2 = 1 Then median = tbl(m) Else median = (tbl(m - 1) + tbl(m)) / 2 End if End Function Private Function fivenum(tbl As Variant) As Variant Sort tbl, UBound(tbl) Dim l As Integer: l = UBound(tbl) Dim m As Integer: m = WorksheetFunction.Floor_Precise(l / 2) + l Mod 2 Dim r(5) As String r(1) = CStr(tbl(1)) r(2) = CStr(median(tbl, 1, m)) r(3) = CStr(median(tbl, 1, l)) r(4) = CStr(median(tbl, m + 1, l)) r(5) = CStr(tbl(l)) fivenum = r End Function Public Sub main() Dim x1 As Variant, x2 As Variant, x3 As Variant x1 = [{15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43}] x2 = [{36, 40, 7, 39, 41, 15}] x3 = [{0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578}] Debug.Print Join(fivenum(x1), " | ") Debug.Print Join(fivenum(x2), " | ") Debug.Print Join(fivenum(x3), " | ") End Sub
Translate this program into C but keep the logic exactly as in Arturo.
fivenum: function [lst][ lst: sort lst m: (size lst)/2 lowerEnd: (odd? size lst)? -> m -> m-1 return @[ first lst median slice lst 0 lowerEnd median slice lst 0 dec size lst median slice lst m dec size lst last lst ] ] lists: @[ @[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], @[36.0, 40.0, 7.0, 39.0, 41.0, 15.0], @[0.14082834, 0.09748790, 1.73131507, 0.87636009,0-1.95059594, 0.73438555,0-0.03035726, 1.46675970,0-0.74621349,0-0.72588772, 0.63905160, 0.61501527,0-0.98983780,0-1.00447874,0-0.62759469, 0.66206163, 1.04312009,0-0.10305385, 0.75775634, 0.32566578] ] loop lists 'l [ print [l "->"] print [fivenum l] print "" ]
#include <stdio.h> #include <stdlib.h> double median(double *x, int start, int end_inclusive) { int size = end_inclusive - start + 1; if (size <= 0) { printf("Array slice cannot be empty\n"); exit(1); } int m = start + size / 2; if (size % 2) return x[m]; return (x[m - 1] + x[m]) / 2.0; } int compare (const void *a, const void *b) { double aa = *(double*)a; double bb = *(double*)b; if (aa > bb) return 1; if (aa < bb) return -1; return 0; } int fivenum(double *x, double *result, int x_len) { int i, m, lower_end; for (i = 0; i < x_len; i++) { if (x[i] != x[i]) { printf("Unable to deal with arrays containing NaN\n\n"); return 1; } } qsort(x, x_len, sizeof(double), compare); result[0] = x[0]; result[2] = median(x, 0, x_len - 1); result[4] = x[x_len - 1]; m = x_len / 2; lower_end = (x_len % 2) ? m : m - 1; result[1] = median(x, 0, lower_end); result[3] = median(x, m, x_len - 1); return 0; } int show(double *result, int places) { int i; char f[7]; sprintf(f, "%%.%dlf", places); printf("["); for (i = 0; i < 5; i++) { printf(f, result[i]); if (i < 4) printf(", "); } printf("]\n\n"); } int main() { double result[5]; double x1[11] = {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}; if (!fivenum(x1, result, 11)) show(result, 1); double x2[6] = {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}; if (!fivenum(x2, result, 6)) show(result, 1); double x3[20] = { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }; if (!fivenum(x3, result, 20)) show(result, 9); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
fivenum: function [lst][ lst: sort lst m: (size lst)/2 lowerEnd: (odd? size lst)? -> m -> m-1 return @[ first lst median slice lst 0 lowerEnd median slice lst 0 dec size lst median slice lst m dec size lst last lst ] ] lists: @[ @[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], @[36.0, 40.0, 7.0, 39.0, 41.0, 15.0], @[0.14082834, 0.09748790, 1.73131507, 0.87636009,0-1.95059594, 0.73438555,0-0.03035726, 1.46675970,0-0.74621349,0-0.72588772, 0.63905160, 0.61501527,0-0.98983780,0-1.00447874,0-0.62759469, 0.66206163, 1.04312009,0-0.10305385, 0.75775634, 0.32566578] ] loop lists 'l [ print [l "->"] print [fivenum l] print "" ]
#include <stdio.h> #include <stdlib.h> double median(double *x, int start, int end_inclusive) { int size = end_inclusive - start + 1; if (size <= 0) { printf("Array slice cannot be empty\n"); exit(1); } int m = start + size / 2; if (size % 2) return x[m]; return (x[m - 1] + x[m]) / 2.0; } int compare (const void *a, const void *b) { double aa = *(double*)a; double bb = *(double*)b; if (aa > bb) return 1; if (aa < bb) return -1; return 0; } int fivenum(double *x, double *result, int x_len) { int i, m, lower_end; for (i = 0; i < x_len; i++) { if (x[i] != x[i]) { printf("Unable to deal with arrays containing NaN\n\n"); return 1; } } qsort(x, x_len, sizeof(double), compare); result[0] = x[0]; result[2] = median(x, 0, x_len - 1); result[4] = x[x_len - 1]; m = x_len / 2; lower_end = (x_len % 2) ? m : m - 1; result[1] = median(x, 0, lower_end); result[3] = median(x, m, x_len - 1); return 0; } int show(double *result, int places) { int i; char f[7]; sprintf(f, "%%.%dlf", places); printf("["); for (i = 0; i < 5; i++) { printf(f, result[i]); if (i < 4) printf(", "); } printf("]\n\n"); } int main() { double result[5]; double x1[11] = {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}; if (!fivenum(x1, result, 11)) show(result, 1); double x2[6] = {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}; if (!fivenum(x2, result, 6)) show(result, 1); double x3[20] = { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }; if (!fivenum(x3, result, 20)) show(result, 9); return 0; }
Change the programming language of this snippet from Arturo to C# without modifying what it does.
fivenum: function [lst][ lst: sort lst m: (size lst)/2 lowerEnd: (odd? size lst)? -> m -> m-1 return @[ first lst median slice lst 0 lowerEnd median slice lst 0 dec size lst median slice lst m dec size lst last lst ] ] lists: @[ @[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], @[36.0, 40.0, 7.0, 39.0, 41.0, 15.0], @[0.14082834, 0.09748790, 1.73131507, 0.87636009,0-1.95059594, 0.73438555,0-0.03035726, 1.46675970,0-0.74621349,0-0.72588772, 0.63905160, 0.61501527,0-0.98983780,0-1.00447874,0-0.62759469, 0.66206163, 1.04312009,0-0.10305385, 0.75775634, 0.32566578] ] loop lists 'l [ print [l "->"] print [fivenum l] print "" ]
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Fivenum { public static class Helper { public static string AsString<T>(this ICollection<T> c, string format = "{0}") { StringBuilder sb = new StringBuilder("["); int count = 0; foreach (var t in c) { if (count++ > 0) { sb.Append(", "); } sb.AppendFormat(format, t); } return sb.Append("]").ToString(); } } class Program { static double Median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new ArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] Fivenum(double[] x) { foreach (var d in x) { if (Double.IsNaN(d)) { throw new ArgumentException("Unable to deal with arrays containing NaN"); } } double[] result = new double[5]; Array.Sort(x); result[0] = x.First(); result[2] = Median(x, 0, x.Length - 1); result[4] = x.Last(); int m = x.Length / 2; int lowerEnd = (x.Length % 2 == 1) ? m : m - 1; result[1] = Median(x, 0, lowerEnd); result[3] = Median(x, m, x.Length - 1); return result; } static void Main(string[] args) { double[][] x1 = new double[][]{ new double[]{ 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, new double[]{ 36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, new double[]{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }, }; foreach(var x in x1) { var result = Fivenum(x); Console.WriteLine(result.AsString("{0:F8}")); } } } }
Preserve the algorithm and functionality while converting the code from Arturo to C#.
fivenum: function [lst][ lst: sort lst m: (size lst)/2 lowerEnd: (odd? size lst)? -> m -> m-1 return @[ first lst median slice lst 0 lowerEnd median slice lst 0 dec size lst median slice lst m dec size lst last lst ] ] lists: @[ @[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], @[36.0, 40.0, 7.0, 39.0, 41.0, 15.0], @[0.14082834, 0.09748790, 1.73131507, 0.87636009,0-1.95059594, 0.73438555,0-0.03035726, 1.46675970,0-0.74621349,0-0.72588772, 0.63905160, 0.61501527,0-0.98983780,0-1.00447874,0-0.62759469, 0.66206163, 1.04312009,0-0.10305385, 0.75775634, 0.32566578] ] loop lists 'l [ print [l "->"] print [fivenum l] print "" ]
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Fivenum { public static class Helper { public static string AsString<T>(this ICollection<T> c, string format = "{0}") { StringBuilder sb = new StringBuilder("["); int count = 0; foreach (var t in c) { if (count++ > 0) { sb.Append(", "); } sb.AppendFormat(format, t); } return sb.Append("]").ToString(); } } class Program { static double Median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new ArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] Fivenum(double[] x) { foreach (var d in x) { if (Double.IsNaN(d)) { throw new ArgumentException("Unable to deal with arrays containing NaN"); } } double[] result = new double[5]; Array.Sort(x); result[0] = x.First(); result[2] = Median(x, 0, x.Length - 1); result[4] = x.Last(); int m = x.Length / 2; int lowerEnd = (x.Length % 2 == 1) ? m : m - 1; result[1] = Median(x, 0, lowerEnd); result[3] = Median(x, m, x.Length - 1); return result; } static void Main(string[] args) { double[][] x1 = new double[][]{ new double[]{ 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, new double[]{ 36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, new double[]{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }, }; foreach(var x in x1) { var result = Fivenum(x); Console.WriteLine(result.AsString("{0:F8}")); } } } }
Rewrite the snippet below in C++ so it works the same as the original Arturo code.
fivenum: function [lst][ lst: sort lst m: (size lst)/2 lowerEnd: (odd? size lst)? -> m -> m-1 return @[ first lst median slice lst 0 lowerEnd median slice lst 0 dec size lst median slice lst m dec size lst last lst ] ] lists: @[ @[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], @[36.0, 40.0, 7.0, 39.0, 41.0, 15.0], @[0.14082834, 0.09748790, 1.73131507, 0.87636009,0-1.95059594, 0.73438555,0-0.03035726, 1.46675970,0-0.74621349,0-0.72588772, 0.63905160, 0.61501527,0-0.98983780,0-1.00447874,0-0.62759469, 0.66206163, 1.04312009,0-0.10305385, 0.75775634, 0.32566578] ] loop lists 'l [ print [l "->"] print [fivenum l] print "" ]
#include <algorithm> #include <iostream> #include <ostream> #include <vector> template<std::size_t> struct int_ {}; template <class Tuple, size_t Pos> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<Pos>) { out << std::get< std::tuple_size<Tuple>::value - Pos >(t) << ", "; return print_tuple(out, t, int_<Pos - 1>()); } template <class Tuple> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<1>) { return out << std::get<std::tuple_size<Tuple>::value - 1>(t); } template <class... Args> std::ostream& operator<<(std::ostream& out, const std::tuple<Args...>& t) { out << '('; print_tuple(out, t, int_<sizeof...(Args)>()); return out << ')'; } template <class RI> double median(RI beg, RI end) { if (beg == end) throw std::runtime_error("Range cannot be empty"); auto len = end - beg; auto m = len / 2; if (len % 2 == 1) { return *(beg + m); } return (beg[m - 1] + beg[m]) / 2.0; } template <class C> auto fivenum(C& c) { std::sort(c.begin(), c.end()); auto cbeg = c.cbegin(); auto cend = c.cend(); auto len = cend - cbeg; auto m = len / 2; auto lower = (len % 2 == 1) ? m : m - 1; double r2 = median(cbeg, cbeg + lower + 1); double r3 = median(cbeg, cend); double r4 = median(cbeg + lower + 1, cend); return std::make_tuple(*cbeg, r2, r3, r4, *(cend - 1)); } int main() { using namespace std; vector<vector<double>> cs = { { 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0 }, { 36.0, 40.0, 7.0, 39.0, 41.0, 15.0 }, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (auto & c : cs) { cout << fivenum(c) << endl; } return 0; }
Keep all operations the same but rewrite the snippet in C++.
fivenum: function [lst][ lst: sort lst m: (size lst)/2 lowerEnd: (odd? size lst)? -> m -> m-1 return @[ first lst median slice lst 0 lowerEnd median slice lst 0 dec size lst median slice lst m dec size lst last lst ] ] lists: @[ @[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], @[36.0, 40.0, 7.0, 39.0, 41.0, 15.0], @[0.14082834, 0.09748790, 1.73131507, 0.87636009,0-1.95059594, 0.73438555,0-0.03035726, 1.46675970,0-0.74621349,0-0.72588772, 0.63905160, 0.61501527,0-0.98983780,0-1.00447874,0-0.62759469, 0.66206163, 1.04312009,0-0.10305385, 0.75775634, 0.32566578] ] loop lists 'l [ print [l "->"] print [fivenum l] print "" ]
#include <algorithm> #include <iostream> #include <ostream> #include <vector> template<std::size_t> struct int_ {}; template <class Tuple, size_t Pos> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<Pos>) { out << std::get< std::tuple_size<Tuple>::value - Pos >(t) << ", "; return print_tuple(out, t, int_<Pos - 1>()); } template <class Tuple> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<1>) { return out << std::get<std::tuple_size<Tuple>::value - 1>(t); } template <class... Args> std::ostream& operator<<(std::ostream& out, const std::tuple<Args...>& t) { out << '('; print_tuple(out, t, int_<sizeof...(Args)>()); return out << ')'; } template <class RI> double median(RI beg, RI end) { if (beg == end) throw std::runtime_error("Range cannot be empty"); auto len = end - beg; auto m = len / 2; if (len % 2 == 1) { return *(beg + m); } return (beg[m - 1] + beg[m]) / 2.0; } template <class C> auto fivenum(C& c) { std::sort(c.begin(), c.end()); auto cbeg = c.cbegin(); auto cend = c.cend(); auto len = cend - cbeg; auto m = len / 2; auto lower = (len % 2 == 1) ? m : m - 1; double r2 = median(cbeg, cbeg + lower + 1); double r3 = median(cbeg, cend); double r4 = median(cbeg + lower + 1, cend); return std::make_tuple(*cbeg, r2, r3, r4, *(cend - 1)); } int main() { using namespace std; vector<vector<double>> cs = { { 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0 }, { 36.0, 40.0, 7.0, 39.0, 41.0, 15.0 }, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (auto & c : cs) { cout << fivenum(c) << endl; } return 0; }
Produce a functionally identical Java code for the snippet given in Arturo.
fivenum: function [lst][ lst: sort lst m: (size lst)/2 lowerEnd: (odd? size lst)? -> m -> m-1 return @[ first lst median slice lst 0 lowerEnd median slice lst 0 dec size lst median slice lst m dec size lst last lst ] ] lists: @[ @[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], @[36.0, 40.0, 7.0, 39.0, 41.0, 15.0], @[0.14082834, 0.09748790, 1.73131507, 0.87636009,0-1.95059594, 0.73438555,0-0.03035726, 1.46675970,0-0.74621349,0-0.72588772, 0.63905160, 0.61501527,0-0.98983780,0-1.00447874,0-0.62759469, 0.66206163, 1.04312009,0-0.10305385, 0.75775634, 0.32566578] ] loop lists 'l [ print [l "->"] print [fivenum l] print "" ]
import java.util.Arrays; public class Fivenum { static double median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new IllegalArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] fivenum(double[] x) { for (Double d : x) { if (d.isNaN()) throw new IllegalArgumentException("Unable to deal with arrays containing NaN"); } double[] result = new double[5]; Arrays.sort(x); result[0] = x[0]; result[2] = median(x, 0, x.length - 1); result[4] = x[x.length - 1]; int m = x.length / 2; int lowerEnd = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x, 0, lowerEnd); result[3] = median(x, m, x.length - 1); return result; } public static void main(String[] args) { double xl[][] = { {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (double[] x : xl) System.out.printf("%s\n\n", Arrays.toString(fivenum(x))); } }
Translate the given Arturo code snippet into Java without altering its behavior.
fivenum: function [lst][ lst: sort lst m: (size lst)/2 lowerEnd: (odd? size lst)? -> m -> m-1 return @[ first lst median slice lst 0 lowerEnd median slice lst 0 dec size lst median slice lst m dec size lst last lst ] ] lists: @[ @[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], @[36.0, 40.0, 7.0, 39.0, 41.0, 15.0], @[0.14082834, 0.09748790, 1.73131507, 0.87636009,0-1.95059594, 0.73438555,0-0.03035726, 1.46675970,0-0.74621349,0-0.72588772, 0.63905160, 0.61501527,0-0.98983780,0-1.00447874,0-0.62759469, 0.66206163, 1.04312009,0-0.10305385, 0.75775634, 0.32566578] ] loop lists 'l [ print [l "->"] print [fivenum l] print "" ]
import java.util.Arrays; public class Fivenum { static double median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new IllegalArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] fivenum(double[] x) { for (Double d : x) { if (d.isNaN()) throw new IllegalArgumentException("Unable to deal with arrays containing NaN"); } double[] result = new double[5]; Arrays.sort(x); result[0] = x[0]; result[2] = median(x, 0, x.length - 1); result[4] = x[x.length - 1]; int m = x.length / 2; int lowerEnd = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x, 0, lowerEnd); result[3] = median(x, m, x.length - 1); return result; } public static void main(String[] args) { double xl[][] = { {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (double[] x : xl) System.out.printf("%s\n\n", Arrays.toString(fivenum(x))); } }
Convert this Arturo block to Python, preserving its control flow and logic.
fivenum: function [lst][ lst: sort lst m: (size lst)/2 lowerEnd: (odd? size lst)? -> m -> m-1 return @[ first lst median slice lst 0 lowerEnd median slice lst 0 dec size lst median slice lst m dec size lst last lst ] ] lists: @[ @[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], @[36.0, 40.0, 7.0, 39.0, 41.0, 15.0], @[0.14082834, 0.09748790, 1.73131507, 0.87636009,0-1.95059594, 0.73438555,0-0.03035726, 1.46675970,0-0.74621349,0-0.72588772, 0.63905160, 0.61501527,0-0.98983780,0-1.00447874,0-0.62759469, 0.66206163, 1.04312009,0-0.10305385, 0.75775634, 0.32566578] ] loop lists 'l [ print [l "->"] print [fivenum l] print "" ]
from __future__ import division import math import sys def fivenum(array): n = len(array) if n == 0: print("you entered an empty array.") sys.exit() x = sorted(array) n4 = math.floor((n+3.0)/2.0)/2.0 d = [1, n4, (n+1)/2, n+1-n4, n] sum_array = [] for e in range(5): floor = int(math.floor(d[e] - 1)) ceil = int(math.ceil(d[e] - 1)) sum_array.append(0.5 * (x[floor] + x[ceil])) return sum_array x = [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578] y = fivenum(x) print(y)
Write a version of this Arturo function in Python with identical behavior.
fivenum: function [lst][ lst: sort lst m: (size lst)/2 lowerEnd: (odd? size lst)? -> m -> m-1 return @[ first lst median slice lst 0 lowerEnd median slice lst 0 dec size lst median slice lst m dec size lst last lst ] ] lists: @[ @[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], @[36.0, 40.0, 7.0, 39.0, 41.0, 15.0], @[0.14082834, 0.09748790, 1.73131507, 0.87636009,0-1.95059594, 0.73438555,0-0.03035726, 1.46675970,0-0.74621349,0-0.72588772, 0.63905160, 0.61501527,0-0.98983780,0-1.00447874,0-0.62759469, 0.66206163, 1.04312009,0-0.10305385, 0.75775634, 0.32566578] ] loop lists 'l [ print [l "->"] print [fivenum l] print "" ]
from __future__ import division import math import sys def fivenum(array): n = len(array) if n == 0: print("you entered an empty array.") sys.exit() x = sorted(array) n4 = math.floor((n+3.0)/2.0)/2.0 d = [1, n4, (n+1)/2, n+1-n4, n] sum_array = [] for e in range(5): floor = int(math.floor(d[e] - 1)) ceil = int(math.ceil(d[e] - 1)) sum_array.append(0.5 * (x[floor] + x[ceil])) return sum_array x = [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578] y = fivenum(x) print(y)
Port the following code from Arturo to VB with equivalent syntax and logic.
fivenum: function [lst][ lst: sort lst m: (size lst)/2 lowerEnd: (odd? size lst)? -> m -> m-1 return @[ first lst median slice lst 0 lowerEnd median slice lst 0 dec size lst median slice lst m dec size lst last lst ] ] lists: @[ @[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], @[36.0, 40.0, 7.0, 39.0, 41.0, 15.0], @[0.14082834, 0.09748790, 1.73131507, 0.87636009,0-1.95059594, 0.73438555,0-0.03035726, 1.46675970,0-0.74621349,0-0.72588772, 0.63905160, 0.61501527,0-0.98983780,0-1.00447874,0-0.62759469, 0.66206163, 1.04312009,0-0.10305385, 0.75775634, 0.32566578] ] loop lists 'l [ print [l "->"] print [fivenum l] print "" ]
#define floor(x) ((x*2.0-0.5) Shr 1) Sub rapidSort (array()As Single, l As Integer, r As Integer) Dim As Integer n, wert, nptr, rep Dim As Single arr, LoVal = array(l), HiVal = array(r) For n = l To r If LoVal > array(n) Then LoVal = array(n) If HiVal < array(n) Then HiVal = array(n) Next n Redim SortArray(LoVal To HiVal) As Single For n = l To r wert = array(n) SortArray(wert) += 1 Next n nptr = l-1 For arr = LoVal To HiVal rep = SortArray(arr) For n = 1 To rep nptr += 1 array(nptr) = arr Next n Next arr Erase SortArray End Sub Function median(tbl() As Single, lo As Integer, hi As Integer) As Single Dim As Integer l = hi-lo+1 Dim As Integer m = lo+floor(l/2) If l Mod 2 = 1 Then Return tbl(m) Return (tbl(m-1)+tbl(m))/2 End Function Sub fivenum(tbl() As Single) rapidSort(tbl(), Lbound(tbl), Ubound(tbl)) Dim As Integer l = Ubound(tbl) Dim As Single m = floor(l/2) + (l Mod 2) Dim As Single r1,r2,r3,r4,r5 r1 = tbl(1) r2 = median(tbl(),1,m) r3 = median(tbl(),1,l) r4 = median(tbl(),m+1,l) r5 = tbl(l) Print "[" & r1; ","; r2; ","; r3; ","; r4; ", "; r5 & "]" End Sub Dim As Single x1(1 To ...) = {15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43} Dim As Single x2(1 To ...) = {36, 40, 7, 39, 41, 15} Dim As Single x3(1 To ...) = {_ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, _ 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, _ 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, _ 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578} fivenum(x1()) fivenum(x2()) fivenum(x3()) Sleep
Keep all operations the same but rewrite the snippet in VB.
fivenum: function [lst][ lst: sort lst m: (size lst)/2 lowerEnd: (odd? size lst)? -> m -> m-1 return @[ first lst median slice lst 0 lowerEnd median slice lst 0 dec size lst median slice lst m dec size lst last lst ] ] lists: @[ @[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], @[36.0, 40.0, 7.0, 39.0, 41.0, 15.0], @[0.14082834, 0.09748790, 1.73131507, 0.87636009,0-1.95059594, 0.73438555,0-0.03035726, 1.46675970,0-0.74621349,0-0.72588772, 0.63905160, 0.61501527,0-0.98983780,0-1.00447874,0-0.62759469, 0.66206163, 1.04312009,0-0.10305385, 0.75775634, 0.32566578] ] loop lists 'l [ print [l "->"] print [fivenum l] print "" ]
#define floor(x) ((x*2.0-0.5) Shr 1) Sub rapidSort (array()As Single, l As Integer, r As Integer) Dim As Integer n, wert, nptr, rep Dim As Single arr, LoVal = array(l), HiVal = array(r) For n = l To r If LoVal > array(n) Then LoVal = array(n) If HiVal < array(n) Then HiVal = array(n) Next n Redim SortArray(LoVal To HiVal) As Single For n = l To r wert = array(n) SortArray(wert) += 1 Next n nptr = l-1 For arr = LoVal To HiVal rep = SortArray(arr) For n = 1 To rep nptr += 1 array(nptr) = arr Next n Next arr Erase SortArray End Sub Function median(tbl() As Single, lo As Integer, hi As Integer) As Single Dim As Integer l = hi-lo+1 Dim As Integer m = lo+floor(l/2) If l Mod 2 = 1 Then Return tbl(m) Return (tbl(m-1)+tbl(m))/2 End Function Sub fivenum(tbl() As Single) rapidSort(tbl(), Lbound(tbl), Ubound(tbl)) Dim As Integer l = Ubound(tbl) Dim As Single m = floor(l/2) + (l Mod 2) Dim As Single r1,r2,r3,r4,r5 r1 = tbl(1) r2 = median(tbl(),1,m) r3 = median(tbl(),1,l) r4 = median(tbl(),m+1,l) r5 = tbl(l) Print "[" & r1; ","; r2; ","; r3; ","; r4; ", "; r5 & "]" End Sub Dim As Single x1(1 To ...) = {15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43} Dim As Single x2(1 To ...) = {36, 40, 7, 39, 41, 15} Dim As Single x3(1 To ...) = {_ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, _ 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, _ 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, _ 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578} fivenum(x1()) fivenum(x2()) fivenum(x3()) Sleep
Produce a language-to-language conversion: from Arturo to Go, same semantics.
fivenum: function [lst][ lst: sort lst m: (size lst)/2 lowerEnd: (odd? size lst)? -> m -> m-1 return @[ first lst median slice lst 0 lowerEnd median slice lst 0 dec size lst median slice lst m dec size lst last lst ] ] lists: @[ @[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], @[36.0, 40.0, 7.0, 39.0, 41.0, 15.0], @[0.14082834, 0.09748790, 1.73131507, 0.87636009,0-1.95059594, 0.73438555,0-0.03035726, 1.46675970,0-0.74621349,0-0.72588772, 0.63905160, 0.61501527,0-0.98983780,0-1.00447874,0-0.62759469, 0.66206163, 1.04312009,0-0.10305385, 0.75775634, 0.32566578] ] loop lists 'l [ print [l "->"] print [fivenum l] print "" ]
package main import ( "fmt" "math" "sort" ) func fivenum(a []float64) (n5 [5]float64) { sort.Float64s(a) n := float64(len(a)) n4 := float64((len(a)+3)/2) / 2 d := []float64{1, n4, (n + 1) / 2, n + 1 - n4, n} for e, de := range d { floor := int(de - 1) ceil := int(math.Ceil(de - 1)) n5[e] = .5 * (a[floor] + a[ceil]) } return } var ( x1 = []float64{36, 40, 7, 39, 41, 15} x2 = []float64{15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43} x3 = []float64{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578, } ) func main() { fmt.Println(fivenum(x1)) fmt.Println(fivenum(x2)) fmt.Println(fivenum(x3)) }
Can you help me rewrite this code in Go instead of Arturo, keeping it the same logically?
fivenum: function [lst][ lst: sort lst m: (size lst)/2 lowerEnd: (odd? size lst)? -> m -> m-1 return @[ first lst median slice lst 0 lowerEnd median slice lst 0 dec size lst median slice lst m dec size lst last lst ] ] lists: @[ @[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], @[36.0, 40.0, 7.0, 39.0, 41.0, 15.0], @[0.14082834, 0.09748790, 1.73131507, 0.87636009,0-1.95059594, 0.73438555,0-0.03035726, 1.46675970,0-0.74621349,0-0.72588772, 0.63905160, 0.61501527,0-0.98983780,0-1.00447874,0-0.62759469, 0.66206163, 1.04312009,0-0.10305385, 0.75775634, 0.32566578] ] loop lists 'l [ print [l "->"] print [fivenum l] print "" ]
package main import ( "fmt" "math" "sort" ) func fivenum(a []float64) (n5 [5]float64) { sort.Float64s(a) n := float64(len(a)) n4 := float64((len(a)+3)/2) / 2 d := []float64{1, n4, (n + 1) / 2, n + 1 - n4, n} for e, de := range d { floor := int(de - 1) ceil := int(math.Ceil(de - 1)) n5[e] = .5 * (a[floor] + a[ceil]) } return } var ( x1 = []float64{36, 40, 7, 39, 41, 15} x2 = []float64{15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43} x3 = []float64{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578, } ) func main() { fmt.Println(fivenum(x1)) fmt.Println(fivenum(x2)) fmt.Println(fivenum(x3)) }
Convert this D block to C, preserving its control flow and logic.
import std.algorithm; import std.exception; import std.math; import std.stdio; double median(double[] x) { enforce(x.length >= 0, "Array slice cannot be empty"); int m = x.length / 2; if (x.length % 2 == 1) { return x[m]; } return (x[m-1] + x[m]) / 2.0; } double[] fivenum(double[] x) { foreach (d; x) { enforce(!d.isNaN, "Unable to deal with arrays containing NaN"); } double[] result; result.length = 5; x.sort; result[0] = x[0]; result[2] = median(x); result[4] = x[$-1]; int m = x.length / 2; int lower = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x[0..lower+1]); result[3] = median(x[lower+1..$]); return result; } void main() { double[][] x1 = [ [15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 ] ]; foreach(x; x1) { writeln(fivenum(x)); } }
#include <stdio.h> #include <stdlib.h> double median(double *x, int start, int end_inclusive) { int size = end_inclusive - start + 1; if (size <= 0) { printf("Array slice cannot be empty\n"); exit(1); } int m = start + size / 2; if (size % 2) return x[m]; return (x[m - 1] + x[m]) / 2.0; } int compare (const void *a, const void *b) { double aa = *(double*)a; double bb = *(double*)b; if (aa > bb) return 1; if (aa < bb) return -1; return 0; } int fivenum(double *x, double *result, int x_len) { int i, m, lower_end; for (i = 0; i < x_len; i++) { if (x[i] != x[i]) { printf("Unable to deal with arrays containing NaN\n\n"); return 1; } } qsort(x, x_len, sizeof(double), compare); result[0] = x[0]; result[2] = median(x, 0, x_len - 1); result[4] = x[x_len - 1]; m = x_len / 2; lower_end = (x_len % 2) ? m : m - 1; result[1] = median(x, 0, lower_end); result[3] = median(x, m, x_len - 1); return 0; } int show(double *result, int places) { int i; char f[7]; sprintf(f, "%%.%dlf", places); printf("["); for (i = 0; i < 5; i++) { printf(f, result[i]); if (i < 4) printf(", "); } printf("]\n\n"); } int main() { double result[5]; double x1[11] = {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}; if (!fivenum(x1, result, 11)) show(result, 1); double x2[6] = {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}; if (!fivenum(x2, result, 6)) show(result, 1); double x3[20] = { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }; if (!fivenum(x3, result, 20)) show(result, 9); return 0; }
Rewrite this program in C while keeping its functionality equivalent to the D version.
import std.algorithm; import std.exception; import std.math; import std.stdio; double median(double[] x) { enforce(x.length >= 0, "Array slice cannot be empty"); int m = x.length / 2; if (x.length % 2 == 1) { return x[m]; } return (x[m-1] + x[m]) / 2.0; } double[] fivenum(double[] x) { foreach (d; x) { enforce(!d.isNaN, "Unable to deal with arrays containing NaN"); } double[] result; result.length = 5; x.sort; result[0] = x[0]; result[2] = median(x); result[4] = x[$-1]; int m = x.length / 2; int lower = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x[0..lower+1]); result[3] = median(x[lower+1..$]); return result; } void main() { double[][] x1 = [ [15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 ] ]; foreach(x; x1) { writeln(fivenum(x)); } }
#include <stdio.h> #include <stdlib.h> double median(double *x, int start, int end_inclusive) { int size = end_inclusive - start + 1; if (size <= 0) { printf("Array slice cannot be empty\n"); exit(1); } int m = start + size / 2; if (size % 2) return x[m]; return (x[m - 1] + x[m]) / 2.0; } int compare (const void *a, const void *b) { double aa = *(double*)a; double bb = *(double*)b; if (aa > bb) return 1; if (aa < bb) return -1; return 0; } int fivenum(double *x, double *result, int x_len) { int i, m, lower_end; for (i = 0; i < x_len; i++) { if (x[i] != x[i]) { printf("Unable to deal with arrays containing NaN\n\n"); return 1; } } qsort(x, x_len, sizeof(double), compare); result[0] = x[0]; result[2] = median(x, 0, x_len - 1); result[4] = x[x_len - 1]; m = x_len / 2; lower_end = (x_len % 2) ? m : m - 1; result[1] = median(x, 0, lower_end); result[3] = median(x, m, x_len - 1); return 0; } int show(double *result, int places) { int i; char f[7]; sprintf(f, "%%.%dlf", places); printf("["); for (i = 0; i < 5; i++) { printf(f, result[i]); if (i < 4) printf(", "); } printf("]\n\n"); } int main() { double result[5]; double x1[11] = {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}; if (!fivenum(x1, result, 11)) show(result, 1); double x2[6] = {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}; if (!fivenum(x2, result, 6)) show(result, 1); double x3[20] = { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }; if (!fivenum(x3, result, 20)) show(result, 9); return 0; }
Preserve the algorithm and functionality while converting the code from D to C#.
import std.algorithm; import std.exception; import std.math; import std.stdio; double median(double[] x) { enforce(x.length >= 0, "Array slice cannot be empty"); int m = x.length / 2; if (x.length % 2 == 1) { return x[m]; } return (x[m-1] + x[m]) / 2.0; } double[] fivenum(double[] x) { foreach (d; x) { enforce(!d.isNaN, "Unable to deal with arrays containing NaN"); } double[] result; result.length = 5; x.sort; result[0] = x[0]; result[2] = median(x); result[4] = x[$-1]; int m = x.length / 2; int lower = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x[0..lower+1]); result[3] = median(x[lower+1..$]); return result; } void main() { double[][] x1 = [ [15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 ] ]; foreach(x; x1) { writeln(fivenum(x)); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Fivenum { public static class Helper { public static string AsString<T>(this ICollection<T> c, string format = "{0}") { StringBuilder sb = new StringBuilder("["); int count = 0; foreach (var t in c) { if (count++ > 0) { sb.Append(", "); } sb.AppendFormat(format, t); } return sb.Append("]").ToString(); } } class Program { static double Median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new ArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] Fivenum(double[] x) { foreach (var d in x) { if (Double.IsNaN(d)) { throw new ArgumentException("Unable to deal with arrays containing NaN"); } } double[] result = new double[5]; Array.Sort(x); result[0] = x.First(); result[2] = Median(x, 0, x.Length - 1); result[4] = x.Last(); int m = x.Length / 2; int lowerEnd = (x.Length % 2 == 1) ? m : m - 1; result[1] = Median(x, 0, lowerEnd); result[3] = Median(x, m, x.Length - 1); return result; } static void Main(string[] args) { double[][] x1 = new double[][]{ new double[]{ 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, new double[]{ 36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, new double[]{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }, }; foreach(var x in x1) { var result = Fivenum(x); Console.WriteLine(result.AsString("{0:F8}")); } } } }
Write a version of this D function in C# with identical behavior.
import std.algorithm; import std.exception; import std.math; import std.stdio; double median(double[] x) { enforce(x.length >= 0, "Array slice cannot be empty"); int m = x.length / 2; if (x.length % 2 == 1) { return x[m]; } return (x[m-1] + x[m]) / 2.0; } double[] fivenum(double[] x) { foreach (d; x) { enforce(!d.isNaN, "Unable to deal with arrays containing NaN"); } double[] result; result.length = 5; x.sort; result[0] = x[0]; result[2] = median(x); result[4] = x[$-1]; int m = x.length / 2; int lower = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x[0..lower+1]); result[3] = median(x[lower+1..$]); return result; } void main() { double[][] x1 = [ [15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 ] ]; foreach(x; x1) { writeln(fivenum(x)); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Fivenum { public static class Helper { public static string AsString<T>(this ICollection<T> c, string format = "{0}") { StringBuilder sb = new StringBuilder("["); int count = 0; foreach (var t in c) { if (count++ > 0) { sb.Append(", "); } sb.AppendFormat(format, t); } return sb.Append("]").ToString(); } } class Program { static double Median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new ArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] Fivenum(double[] x) { foreach (var d in x) { if (Double.IsNaN(d)) { throw new ArgumentException("Unable to deal with arrays containing NaN"); } } double[] result = new double[5]; Array.Sort(x); result[0] = x.First(); result[2] = Median(x, 0, x.Length - 1); result[4] = x.Last(); int m = x.Length / 2; int lowerEnd = (x.Length % 2 == 1) ? m : m - 1; result[1] = Median(x, 0, lowerEnd); result[3] = Median(x, m, x.Length - 1); return result; } static void Main(string[] args) { double[][] x1 = new double[][]{ new double[]{ 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, new double[]{ 36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, new double[]{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }, }; foreach(var x in x1) { var result = Fivenum(x); Console.WriteLine(result.AsString("{0:F8}")); } } } }
Convert this D snippet to C++ and keep its semantics consistent.
import std.algorithm; import std.exception; import std.math; import std.stdio; double median(double[] x) { enforce(x.length >= 0, "Array slice cannot be empty"); int m = x.length / 2; if (x.length % 2 == 1) { return x[m]; } return (x[m-1] + x[m]) / 2.0; } double[] fivenum(double[] x) { foreach (d; x) { enforce(!d.isNaN, "Unable to deal with arrays containing NaN"); } double[] result; result.length = 5; x.sort; result[0] = x[0]; result[2] = median(x); result[4] = x[$-1]; int m = x.length / 2; int lower = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x[0..lower+1]); result[3] = median(x[lower+1..$]); return result; } void main() { double[][] x1 = [ [15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 ] ]; foreach(x; x1) { writeln(fivenum(x)); } }
#include <algorithm> #include <iostream> #include <ostream> #include <vector> template<std::size_t> struct int_ {}; template <class Tuple, size_t Pos> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<Pos>) { out << std::get< std::tuple_size<Tuple>::value - Pos >(t) << ", "; return print_tuple(out, t, int_<Pos - 1>()); } template <class Tuple> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<1>) { return out << std::get<std::tuple_size<Tuple>::value - 1>(t); } template <class... Args> std::ostream& operator<<(std::ostream& out, const std::tuple<Args...>& t) { out << '('; print_tuple(out, t, int_<sizeof...(Args)>()); return out << ')'; } template <class RI> double median(RI beg, RI end) { if (beg == end) throw std::runtime_error("Range cannot be empty"); auto len = end - beg; auto m = len / 2; if (len % 2 == 1) { return *(beg + m); } return (beg[m - 1] + beg[m]) / 2.0; } template <class C> auto fivenum(C& c) { std::sort(c.begin(), c.end()); auto cbeg = c.cbegin(); auto cend = c.cend(); auto len = cend - cbeg; auto m = len / 2; auto lower = (len % 2 == 1) ? m : m - 1; double r2 = median(cbeg, cbeg + lower + 1); double r3 = median(cbeg, cend); double r4 = median(cbeg + lower + 1, cend); return std::make_tuple(*cbeg, r2, r3, r4, *(cend - 1)); } int main() { using namespace std; vector<vector<double>> cs = { { 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0 }, { 36.0, 40.0, 7.0, 39.0, 41.0, 15.0 }, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (auto & c : cs) { cout << fivenum(c) << endl; } return 0; }
Produce a language-to-language conversion: from D to C++, same semantics.
import std.algorithm; import std.exception; import std.math; import std.stdio; double median(double[] x) { enforce(x.length >= 0, "Array slice cannot be empty"); int m = x.length / 2; if (x.length % 2 == 1) { return x[m]; } return (x[m-1] + x[m]) / 2.0; } double[] fivenum(double[] x) { foreach (d; x) { enforce(!d.isNaN, "Unable to deal with arrays containing NaN"); } double[] result; result.length = 5; x.sort; result[0] = x[0]; result[2] = median(x); result[4] = x[$-1]; int m = x.length / 2; int lower = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x[0..lower+1]); result[3] = median(x[lower+1..$]); return result; } void main() { double[][] x1 = [ [15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 ] ]; foreach(x; x1) { writeln(fivenum(x)); } }
#include <algorithm> #include <iostream> #include <ostream> #include <vector> template<std::size_t> struct int_ {}; template <class Tuple, size_t Pos> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<Pos>) { out << std::get< std::tuple_size<Tuple>::value - Pos >(t) << ", "; return print_tuple(out, t, int_<Pos - 1>()); } template <class Tuple> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<1>) { return out << std::get<std::tuple_size<Tuple>::value - 1>(t); } template <class... Args> std::ostream& operator<<(std::ostream& out, const std::tuple<Args...>& t) { out << '('; print_tuple(out, t, int_<sizeof...(Args)>()); return out << ')'; } template <class RI> double median(RI beg, RI end) { if (beg == end) throw std::runtime_error("Range cannot be empty"); auto len = end - beg; auto m = len / 2; if (len % 2 == 1) { return *(beg + m); } return (beg[m - 1] + beg[m]) / 2.0; } template <class C> auto fivenum(C& c) { std::sort(c.begin(), c.end()); auto cbeg = c.cbegin(); auto cend = c.cend(); auto len = cend - cbeg; auto m = len / 2; auto lower = (len % 2 == 1) ? m : m - 1; double r2 = median(cbeg, cbeg + lower + 1); double r3 = median(cbeg, cend); double r4 = median(cbeg + lower + 1, cend); return std::make_tuple(*cbeg, r2, r3, r4, *(cend - 1)); } int main() { using namespace std; vector<vector<double>> cs = { { 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0 }, { 36.0, 40.0, 7.0, 39.0, 41.0, 15.0 }, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (auto & c : cs) { cout << fivenum(c) << endl; } return 0; }
Ensure the translated Java code behaves exactly like the original D snippet.
import std.algorithm; import std.exception; import std.math; import std.stdio; double median(double[] x) { enforce(x.length >= 0, "Array slice cannot be empty"); int m = x.length / 2; if (x.length % 2 == 1) { return x[m]; } return (x[m-1] + x[m]) / 2.0; } double[] fivenum(double[] x) { foreach (d; x) { enforce(!d.isNaN, "Unable to deal with arrays containing NaN"); } double[] result; result.length = 5; x.sort; result[0] = x[0]; result[2] = median(x); result[4] = x[$-1]; int m = x.length / 2; int lower = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x[0..lower+1]); result[3] = median(x[lower+1..$]); return result; } void main() { double[][] x1 = [ [15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 ] ]; foreach(x; x1) { writeln(fivenum(x)); } }
import java.util.Arrays; public class Fivenum { static double median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new IllegalArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] fivenum(double[] x) { for (Double d : x) { if (d.isNaN()) throw new IllegalArgumentException("Unable to deal with arrays containing NaN"); } double[] result = new double[5]; Arrays.sort(x); result[0] = x[0]; result[2] = median(x, 0, x.length - 1); result[4] = x[x.length - 1]; int m = x.length / 2; int lowerEnd = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x, 0, lowerEnd); result[3] = median(x, m, x.length - 1); return result; } public static void main(String[] args) { double xl[][] = { {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (double[] x : xl) System.out.printf("%s\n\n", Arrays.toString(fivenum(x))); } }
Produce a functionally identical Java code for the snippet given in D.
import std.algorithm; import std.exception; import std.math; import std.stdio; double median(double[] x) { enforce(x.length >= 0, "Array slice cannot be empty"); int m = x.length / 2; if (x.length % 2 == 1) { return x[m]; } return (x[m-1] + x[m]) / 2.0; } double[] fivenum(double[] x) { foreach (d; x) { enforce(!d.isNaN, "Unable to deal with arrays containing NaN"); } double[] result; result.length = 5; x.sort; result[0] = x[0]; result[2] = median(x); result[4] = x[$-1]; int m = x.length / 2; int lower = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x[0..lower+1]); result[3] = median(x[lower+1..$]); return result; } void main() { double[][] x1 = [ [15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 ] ]; foreach(x; x1) { writeln(fivenum(x)); } }
import java.util.Arrays; public class Fivenum { static double median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new IllegalArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] fivenum(double[] x) { for (Double d : x) { if (d.isNaN()) throw new IllegalArgumentException("Unable to deal with arrays containing NaN"); } double[] result = new double[5]; Arrays.sort(x); result[0] = x[0]; result[2] = median(x, 0, x.length - 1); result[4] = x[x.length - 1]; int m = x.length / 2; int lowerEnd = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x, 0, lowerEnd); result[3] = median(x, m, x.length - 1); return result; } public static void main(String[] args) { double xl[][] = { {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (double[] x : xl) System.out.printf("%s\n\n", Arrays.toString(fivenum(x))); } }
Ensure the translated Python code behaves exactly like the original D snippet.
import std.algorithm; import std.exception; import std.math; import std.stdio; double median(double[] x) { enforce(x.length >= 0, "Array slice cannot be empty"); int m = x.length / 2; if (x.length % 2 == 1) { return x[m]; } return (x[m-1] + x[m]) / 2.0; } double[] fivenum(double[] x) { foreach (d; x) { enforce(!d.isNaN, "Unable to deal with arrays containing NaN"); } double[] result; result.length = 5; x.sort; result[0] = x[0]; result[2] = median(x); result[4] = x[$-1]; int m = x.length / 2; int lower = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x[0..lower+1]); result[3] = median(x[lower+1..$]); return result; } void main() { double[][] x1 = [ [15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 ] ]; foreach(x; x1) { writeln(fivenum(x)); } }
from __future__ import division import math import sys def fivenum(array): n = len(array) if n == 0: print("you entered an empty array.") sys.exit() x = sorted(array) n4 = math.floor((n+3.0)/2.0)/2.0 d = [1, n4, (n+1)/2, n+1-n4, n] sum_array = [] for e in range(5): floor = int(math.floor(d[e] - 1)) ceil = int(math.ceil(d[e] - 1)) sum_array.append(0.5 * (x[floor] + x[ceil])) return sum_array x = [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578] y = fivenum(x) print(y)
Convert this D snippet to Python and keep its semantics consistent.
import std.algorithm; import std.exception; import std.math; import std.stdio; double median(double[] x) { enforce(x.length >= 0, "Array slice cannot be empty"); int m = x.length / 2; if (x.length % 2 == 1) { return x[m]; } return (x[m-1] + x[m]) / 2.0; } double[] fivenum(double[] x) { foreach (d; x) { enforce(!d.isNaN, "Unable to deal with arrays containing NaN"); } double[] result; result.length = 5; x.sort; result[0] = x[0]; result[2] = median(x); result[4] = x[$-1]; int m = x.length / 2; int lower = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x[0..lower+1]); result[3] = median(x[lower+1..$]); return result; } void main() { double[][] x1 = [ [15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 ] ]; foreach(x; x1) { writeln(fivenum(x)); } }
from __future__ import division import math import sys def fivenum(array): n = len(array) if n == 0: print("you entered an empty array.") sys.exit() x = sorted(array) n4 = math.floor((n+3.0)/2.0)/2.0 d = [1, n4, (n+1)/2, n+1-n4, n] sum_array = [] for e in range(5): floor = int(math.floor(d[e] - 1)) ceil = int(math.ceil(d[e] - 1)) sum_array.append(0.5 * (x[floor] + x[ceil])) return sum_array x = [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578] y = fivenum(x) print(y)
Convert the following code from D to VB, ensuring the logic remains intact.
import std.algorithm; import std.exception; import std.math; import std.stdio; double median(double[] x) { enforce(x.length >= 0, "Array slice cannot be empty"); int m = x.length / 2; if (x.length % 2 == 1) { return x[m]; } return (x[m-1] + x[m]) / 2.0; } double[] fivenum(double[] x) { foreach (d; x) { enforce(!d.isNaN, "Unable to deal with arrays containing NaN"); } double[] result; result.length = 5; x.sort; result[0] = x[0]; result[2] = median(x); result[4] = x[$-1]; int m = x.length / 2; int lower = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x[0..lower+1]); result[3] = median(x[lower+1..$]); return result; } void main() { double[][] x1 = [ [15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 ] ]; foreach(x; x1) { writeln(fivenum(x)); } }
#define floor(x) ((x*2.0-0.5) Shr 1) Sub rapidSort (array()As Single, l As Integer, r As Integer) Dim As Integer n, wert, nptr, rep Dim As Single arr, LoVal = array(l), HiVal = array(r) For n = l To r If LoVal > array(n) Then LoVal = array(n) If HiVal < array(n) Then HiVal = array(n) Next n Redim SortArray(LoVal To HiVal) As Single For n = l To r wert = array(n) SortArray(wert) += 1 Next n nptr = l-1 For arr = LoVal To HiVal rep = SortArray(arr) For n = 1 To rep nptr += 1 array(nptr) = arr Next n Next arr Erase SortArray End Sub Function median(tbl() As Single, lo As Integer, hi As Integer) As Single Dim As Integer l = hi-lo+1 Dim As Integer m = lo+floor(l/2) If l Mod 2 = 1 Then Return tbl(m) Return (tbl(m-1)+tbl(m))/2 End Function Sub fivenum(tbl() As Single) rapidSort(tbl(), Lbound(tbl), Ubound(tbl)) Dim As Integer l = Ubound(tbl) Dim As Single m = floor(l/2) + (l Mod 2) Dim As Single r1,r2,r3,r4,r5 r1 = tbl(1) r2 = median(tbl(),1,m) r3 = median(tbl(),1,l) r4 = median(tbl(),m+1,l) r5 = tbl(l) Print "[" & r1; ","; r2; ","; r3; ","; r4; ", "; r5 & "]" End Sub Dim As Single x1(1 To ...) = {15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43} Dim As Single x2(1 To ...) = {36, 40, 7, 39, 41, 15} Dim As Single x3(1 To ...) = {_ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, _ 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, _ 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, _ 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578} fivenum(x1()) fivenum(x2()) fivenum(x3()) Sleep
Transform the following D implementation into VB, maintaining the same output and logic.
import std.algorithm; import std.exception; import std.math; import std.stdio; double median(double[] x) { enforce(x.length >= 0, "Array slice cannot be empty"); int m = x.length / 2; if (x.length % 2 == 1) { return x[m]; } return (x[m-1] + x[m]) / 2.0; } double[] fivenum(double[] x) { foreach (d; x) { enforce(!d.isNaN, "Unable to deal with arrays containing NaN"); } double[] result; result.length = 5; x.sort; result[0] = x[0]; result[2] = median(x); result[4] = x[$-1]; int m = x.length / 2; int lower = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x[0..lower+1]); result[3] = median(x[lower+1..$]); return result; } void main() { double[][] x1 = [ [15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 ] ]; foreach(x; x1) { writeln(fivenum(x)); } }
#define floor(x) ((x*2.0-0.5) Shr 1) Sub rapidSort (array()As Single, l As Integer, r As Integer) Dim As Integer n, wert, nptr, rep Dim As Single arr, LoVal = array(l), HiVal = array(r) For n = l To r If LoVal > array(n) Then LoVal = array(n) If HiVal < array(n) Then HiVal = array(n) Next n Redim SortArray(LoVal To HiVal) As Single For n = l To r wert = array(n) SortArray(wert) += 1 Next n nptr = l-1 For arr = LoVal To HiVal rep = SortArray(arr) For n = 1 To rep nptr += 1 array(nptr) = arr Next n Next arr Erase SortArray End Sub Function median(tbl() As Single, lo As Integer, hi As Integer) As Single Dim As Integer l = hi-lo+1 Dim As Integer m = lo+floor(l/2) If l Mod 2 = 1 Then Return tbl(m) Return (tbl(m-1)+tbl(m))/2 End Function Sub fivenum(tbl() As Single) rapidSort(tbl(), Lbound(tbl), Ubound(tbl)) Dim As Integer l = Ubound(tbl) Dim As Single m = floor(l/2) + (l Mod 2) Dim As Single r1,r2,r3,r4,r5 r1 = tbl(1) r2 = median(tbl(),1,m) r3 = median(tbl(),1,l) r4 = median(tbl(),m+1,l) r5 = tbl(l) Print "[" & r1; ","; r2; ","; r3; ","; r4; ", "; r5 & "]" End Sub Dim As Single x1(1 To ...) = {15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43} Dim As Single x2(1 To ...) = {36, 40, 7, 39, 41, 15} Dim As Single x3(1 To ...) = {_ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, _ 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, _ 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, _ 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578} fivenum(x1()) fivenum(x2()) fivenum(x3()) Sleep
Produce a functionally identical Go code for the snippet given in D.
import std.algorithm; import std.exception; import std.math; import std.stdio; double median(double[] x) { enforce(x.length >= 0, "Array slice cannot be empty"); int m = x.length / 2; if (x.length % 2 == 1) { return x[m]; } return (x[m-1] + x[m]) / 2.0; } double[] fivenum(double[] x) { foreach (d; x) { enforce(!d.isNaN, "Unable to deal with arrays containing NaN"); } double[] result; result.length = 5; x.sort; result[0] = x[0]; result[2] = median(x); result[4] = x[$-1]; int m = x.length / 2; int lower = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x[0..lower+1]); result[3] = median(x[lower+1..$]); return result; } void main() { double[][] x1 = [ [15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 ] ]; foreach(x; x1) { writeln(fivenum(x)); } }
package main import ( "fmt" "math" "sort" ) func fivenum(a []float64) (n5 [5]float64) { sort.Float64s(a) n := float64(len(a)) n4 := float64((len(a)+3)/2) / 2 d := []float64{1, n4, (n + 1) / 2, n + 1 - n4, n} for e, de := range d { floor := int(de - 1) ceil := int(math.Ceil(de - 1)) n5[e] = .5 * (a[floor] + a[ceil]) } return } var ( x1 = []float64{36, 40, 7, 39, 41, 15} x2 = []float64{15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43} x3 = []float64{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578, } ) func main() { fmt.Println(fivenum(x1)) fmt.Println(fivenum(x2)) fmt.Println(fivenum(x3)) }
Please provide an equivalent version of this D code in Go.
import std.algorithm; import std.exception; import std.math; import std.stdio; double median(double[] x) { enforce(x.length >= 0, "Array slice cannot be empty"); int m = x.length / 2; if (x.length % 2 == 1) { return x[m]; } return (x[m-1] + x[m]) / 2.0; } double[] fivenum(double[] x) { foreach (d; x) { enforce(!d.isNaN, "Unable to deal with arrays containing NaN"); } double[] result; result.length = 5; x.sort; result[0] = x[0]; result[2] = median(x); result[4] = x[$-1]; int m = x.length / 2; int lower = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x[0..lower+1]); result[3] = median(x[lower+1..$]); return result; } void main() { double[][] x1 = [ [15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 ] ]; foreach(x; x1) { writeln(fivenum(x)); } }
package main import ( "fmt" "math" "sort" ) func fivenum(a []float64) (n5 [5]float64) { sort.Float64s(a) n := float64(len(a)) n4 := float64((len(a)+3)/2) / 2 d := []float64{1, n4, (n + 1) / 2, n + 1 - n4, n} for e, de := range d { floor := int(de - 1) ceil := int(math.Ceil(de - 1)) n5[e] = .5 * (a[floor] + a[ceil]) } return } var ( x1 = []float64{36, 40, 7, 39, 41, 15} x2 = []float64{15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43} x3 = []float64{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578, } ) func main() { fmt.Println(fivenum(x1)) fmt.Println(fivenum(x2)) fmt.Println(fivenum(x3)) }
Produce a functionally identical C code for the snippet given in Delphi.
program Fivenum; uses System.SysUtils, System.Generics.Collections; function Median(x: TArray<Double>; start, endInclusive: Integer): Double; var size, m: Integer; begin size := endInclusive - start + 1; if (size <= 0) then raise EArgumentException.Create('Array slice cannot be empty'); m := start + size div 2; if (odd(size)) then Result := x[m] else Result := (x[m - 1] + x[m]) / 2; end; function FiveNumber(x: TArray<Double>): TArray<Double>; var m, lowerEnd: Integer; begin SetLength(result, 5); TArray.Sort<double>(x); result[0] := x[0]; result[2] := median(x, 0, length(x) - 1); result[4] := x[length(x) - 1]; m := length(x) div 2; if odd(length(x)) then lowerEnd := m else lowerEnd := m - 1; result[1] := median(x, 0, lowerEnd); result[3] := median(x, m, length(x) - 1); end; function ArrayToString(x: TArray<double>): string; var i: Integer; begin Result := '['; for i := 0 to High(x) do begin if i > 0 then Result := Result + ','; Result := Result + format('%.4f', [x[i]]); end; Result := Result + ']'; end; var xl: array of TArray<double> = [[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, - 1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578]]; x: TArray<double>; begin for x in xl do writeln(ArrayToString(FiveNumber(x)), #10); readln; end.
#include <stdio.h> #include <stdlib.h> double median(double *x, int start, int end_inclusive) { int size = end_inclusive - start + 1; if (size <= 0) { printf("Array slice cannot be empty\n"); exit(1); } int m = start + size / 2; if (size % 2) return x[m]; return (x[m - 1] + x[m]) / 2.0; } int compare (const void *a, const void *b) { double aa = *(double*)a; double bb = *(double*)b; if (aa > bb) return 1; if (aa < bb) return -1; return 0; } int fivenum(double *x, double *result, int x_len) { int i, m, lower_end; for (i = 0; i < x_len; i++) { if (x[i] != x[i]) { printf("Unable to deal with arrays containing NaN\n\n"); return 1; } } qsort(x, x_len, sizeof(double), compare); result[0] = x[0]; result[2] = median(x, 0, x_len - 1); result[4] = x[x_len - 1]; m = x_len / 2; lower_end = (x_len % 2) ? m : m - 1; result[1] = median(x, 0, lower_end); result[3] = median(x, m, x_len - 1); return 0; } int show(double *result, int places) { int i; char f[7]; sprintf(f, "%%.%dlf", places); printf("["); for (i = 0; i < 5; i++) { printf(f, result[i]); if (i < 4) printf(", "); } printf("]\n\n"); } int main() { double result[5]; double x1[11] = {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}; if (!fivenum(x1, result, 11)) show(result, 1); double x2[6] = {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}; if (!fivenum(x2, result, 6)) show(result, 1); double x3[20] = { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }; if (!fivenum(x3, result, 20)) show(result, 9); return 0; }
Rewrite the snippet below in C so it works the same as the original Delphi code.
program Fivenum; uses System.SysUtils, System.Generics.Collections; function Median(x: TArray<Double>; start, endInclusive: Integer): Double; var size, m: Integer; begin size := endInclusive - start + 1; if (size <= 0) then raise EArgumentException.Create('Array slice cannot be empty'); m := start + size div 2; if (odd(size)) then Result := x[m] else Result := (x[m - 1] + x[m]) / 2; end; function FiveNumber(x: TArray<Double>): TArray<Double>; var m, lowerEnd: Integer; begin SetLength(result, 5); TArray.Sort<double>(x); result[0] := x[0]; result[2] := median(x, 0, length(x) - 1); result[4] := x[length(x) - 1]; m := length(x) div 2; if odd(length(x)) then lowerEnd := m else lowerEnd := m - 1; result[1] := median(x, 0, lowerEnd); result[3] := median(x, m, length(x) - 1); end; function ArrayToString(x: TArray<double>): string; var i: Integer; begin Result := '['; for i := 0 to High(x) do begin if i > 0 then Result := Result + ','; Result := Result + format('%.4f', [x[i]]); end; Result := Result + ']'; end; var xl: array of TArray<double> = [[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, - 1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578]]; x: TArray<double>; begin for x in xl do writeln(ArrayToString(FiveNumber(x)), #10); readln; end.
#include <stdio.h> #include <stdlib.h> double median(double *x, int start, int end_inclusive) { int size = end_inclusive - start + 1; if (size <= 0) { printf("Array slice cannot be empty\n"); exit(1); } int m = start + size / 2; if (size % 2) return x[m]; return (x[m - 1] + x[m]) / 2.0; } int compare (const void *a, const void *b) { double aa = *(double*)a; double bb = *(double*)b; if (aa > bb) return 1; if (aa < bb) return -1; return 0; } int fivenum(double *x, double *result, int x_len) { int i, m, lower_end; for (i = 0; i < x_len; i++) { if (x[i] != x[i]) { printf("Unable to deal with arrays containing NaN\n\n"); return 1; } } qsort(x, x_len, sizeof(double), compare); result[0] = x[0]; result[2] = median(x, 0, x_len - 1); result[4] = x[x_len - 1]; m = x_len / 2; lower_end = (x_len % 2) ? m : m - 1; result[1] = median(x, 0, lower_end); result[3] = median(x, m, x_len - 1); return 0; } int show(double *result, int places) { int i; char f[7]; sprintf(f, "%%.%dlf", places); printf("["); for (i = 0; i < 5; i++) { printf(f, result[i]); if (i < 4) printf(", "); } printf("]\n\n"); } int main() { double result[5]; double x1[11] = {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}; if (!fivenum(x1, result, 11)) show(result, 1); double x2[6] = {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}; if (!fivenum(x2, result, 6)) show(result, 1); double x3[20] = { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }; if (!fivenum(x3, result, 20)) show(result, 9); return 0; }
Translate the given Delphi code snippet into C# without altering its behavior.
program Fivenum; uses System.SysUtils, System.Generics.Collections; function Median(x: TArray<Double>; start, endInclusive: Integer): Double; var size, m: Integer; begin size := endInclusive - start + 1; if (size <= 0) then raise EArgumentException.Create('Array slice cannot be empty'); m := start + size div 2; if (odd(size)) then Result := x[m] else Result := (x[m - 1] + x[m]) / 2; end; function FiveNumber(x: TArray<Double>): TArray<Double>; var m, lowerEnd: Integer; begin SetLength(result, 5); TArray.Sort<double>(x); result[0] := x[0]; result[2] := median(x, 0, length(x) - 1); result[4] := x[length(x) - 1]; m := length(x) div 2; if odd(length(x)) then lowerEnd := m else lowerEnd := m - 1; result[1] := median(x, 0, lowerEnd); result[3] := median(x, m, length(x) - 1); end; function ArrayToString(x: TArray<double>): string; var i: Integer; begin Result := '['; for i := 0 to High(x) do begin if i > 0 then Result := Result + ','; Result := Result + format('%.4f', [x[i]]); end; Result := Result + ']'; end; var xl: array of TArray<double> = [[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, - 1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578]]; x: TArray<double>; begin for x in xl do writeln(ArrayToString(FiveNumber(x)), #10); readln; end.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Fivenum { public static class Helper { public static string AsString<T>(this ICollection<T> c, string format = "{0}") { StringBuilder sb = new StringBuilder("["); int count = 0; foreach (var t in c) { if (count++ > 0) { sb.Append(", "); } sb.AppendFormat(format, t); } return sb.Append("]").ToString(); } } class Program { static double Median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new ArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] Fivenum(double[] x) { foreach (var d in x) { if (Double.IsNaN(d)) { throw new ArgumentException("Unable to deal with arrays containing NaN"); } } double[] result = new double[5]; Array.Sort(x); result[0] = x.First(); result[2] = Median(x, 0, x.Length - 1); result[4] = x.Last(); int m = x.Length / 2; int lowerEnd = (x.Length % 2 == 1) ? m : m - 1; result[1] = Median(x, 0, lowerEnd); result[3] = Median(x, m, x.Length - 1); return result; } static void Main(string[] args) { double[][] x1 = new double[][]{ new double[]{ 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, new double[]{ 36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, new double[]{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }, }; foreach(var x in x1) { var result = Fivenum(x); Console.WriteLine(result.AsString("{0:F8}")); } } } }
Keep all operations the same but rewrite the snippet in C#.
program Fivenum; uses System.SysUtils, System.Generics.Collections; function Median(x: TArray<Double>; start, endInclusive: Integer): Double; var size, m: Integer; begin size := endInclusive - start + 1; if (size <= 0) then raise EArgumentException.Create('Array slice cannot be empty'); m := start + size div 2; if (odd(size)) then Result := x[m] else Result := (x[m - 1] + x[m]) / 2; end; function FiveNumber(x: TArray<Double>): TArray<Double>; var m, lowerEnd: Integer; begin SetLength(result, 5); TArray.Sort<double>(x); result[0] := x[0]; result[2] := median(x, 0, length(x) - 1); result[4] := x[length(x) - 1]; m := length(x) div 2; if odd(length(x)) then lowerEnd := m else lowerEnd := m - 1; result[1] := median(x, 0, lowerEnd); result[3] := median(x, m, length(x) - 1); end; function ArrayToString(x: TArray<double>): string; var i: Integer; begin Result := '['; for i := 0 to High(x) do begin if i > 0 then Result := Result + ','; Result := Result + format('%.4f', [x[i]]); end; Result := Result + ']'; end; var xl: array of TArray<double> = [[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, - 1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578]]; x: TArray<double>; begin for x in xl do writeln(ArrayToString(FiveNumber(x)), #10); readln; end.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Fivenum { public static class Helper { public static string AsString<T>(this ICollection<T> c, string format = "{0}") { StringBuilder sb = new StringBuilder("["); int count = 0; foreach (var t in c) { if (count++ > 0) { sb.Append(", "); } sb.AppendFormat(format, t); } return sb.Append("]").ToString(); } } class Program { static double Median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new ArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] Fivenum(double[] x) { foreach (var d in x) { if (Double.IsNaN(d)) { throw new ArgumentException("Unable to deal with arrays containing NaN"); } } double[] result = new double[5]; Array.Sort(x); result[0] = x.First(); result[2] = Median(x, 0, x.Length - 1); result[4] = x.Last(); int m = x.Length / 2; int lowerEnd = (x.Length % 2 == 1) ? m : m - 1; result[1] = Median(x, 0, lowerEnd); result[3] = Median(x, m, x.Length - 1); return result; } static void Main(string[] args) { double[][] x1 = new double[][]{ new double[]{ 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, new double[]{ 36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, new double[]{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }, }; foreach(var x in x1) { var result = Fivenum(x); Console.WriteLine(result.AsString("{0:F8}")); } } } }
Translate the given Delphi code snippet into C++ without altering its behavior.
program Fivenum; uses System.SysUtils, System.Generics.Collections; function Median(x: TArray<Double>; start, endInclusive: Integer): Double; var size, m: Integer; begin size := endInclusive - start + 1; if (size <= 0) then raise EArgumentException.Create('Array slice cannot be empty'); m := start + size div 2; if (odd(size)) then Result := x[m] else Result := (x[m - 1] + x[m]) / 2; end; function FiveNumber(x: TArray<Double>): TArray<Double>; var m, lowerEnd: Integer; begin SetLength(result, 5); TArray.Sort<double>(x); result[0] := x[0]; result[2] := median(x, 0, length(x) - 1); result[4] := x[length(x) - 1]; m := length(x) div 2; if odd(length(x)) then lowerEnd := m else lowerEnd := m - 1; result[1] := median(x, 0, lowerEnd); result[3] := median(x, m, length(x) - 1); end; function ArrayToString(x: TArray<double>): string; var i: Integer; begin Result := '['; for i := 0 to High(x) do begin if i > 0 then Result := Result + ','; Result := Result + format('%.4f', [x[i]]); end; Result := Result + ']'; end; var xl: array of TArray<double> = [[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, - 1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578]]; x: TArray<double>; begin for x in xl do writeln(ArrayToString(FiveNumber(x)), #10); readln; end.
#include <algorithm> #include <iostream> #include <ostream> #include <vector> template<std::size_t> struct int_ {}; template <class Tuple, size_t Pos> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<Pos>) { out << std::get< std::tuple_size<Tuple>::value - Pos >(t) << ", "; return print_tuple(out, t, int_<Pos - 1>()); } template <class Tuple> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<1>) { return out << std::get<std::tuple_size<Tuple>::value - 1>(t); } template <class... Args> std::ostream& operator<<(std::ostream& out, const std::tuple<Args...>& t) { out << '('; print_tuple(out, t, int_<sizeof...(Args)>()); return out << ')'; } template <class RI> double median(RI beg, RI end) { if (beg == end) throw std::runtime_error("Range cannot be empty"); auto len = end - beg; auto m = len / 2; if (len % 2 == 1) { return *(beg + m); } return (beg[m - 1] + beg[m]) / 2.0; } template <class C> auto fivenum(C& c) { std::sort(c.begin(), c.end()); auto cbeg = c.cbegin(); auto cend = c.cend(); auto len = cend - cbeg; auto m = len / 2; auto lower = (len % 2 == 1) ? m : m - 1; double r2 = median(cbeg, cbeg + lower + 1); double r3 = median(cbeg, cend); double r4 = median(cbeg + lower + 1, cend); return std::make_tuple(*cbeg, r2, r3, r4, *(cend - 1)); } int main() { using namespace std; vector<vector<double>> cs = { { 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0 }, { 36.0, 40.0, 7.0, 39.0, 41.0, 15.0 }, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (auto & c : cs) { cout << fivenum(c) << endl; } return 0; }
Please provide an equivalent version of this Delphi code in C++.
program Fivenum; uses System.SysUtils, System.Generics.Collections; function Median(x: TArray<Double>; start, endInclusive: Integer): Double; var size, m: Integer; begin size := endInclusive - start + 1; if (size <= 0) then raise EArgumentException.Create('Array slice cannot be empty'); m := start + size div 2; if (odd(size)) then Result := x[m] else Result := (x[m - 1] + x[m]) / 2; end; function FiveNumber(x: TArray<Double>): TArray<Double>; var m, lowerEnd: Integer; begin SetLength(result, 5); TArray.Sort<double>(x); result[0] := x[0]; result[2] := median(x, 0, length(x) - 1); result[4] := x[length(x) - 1]; m := length(x) div 2; if odd(length(x)) then lowerEnd := m else lowerEnd := m - 1; result[1] := median(x, 0, lowerEnd); result[3] := median(x, m, length(x) - 1); end; function ArrayToString(x: TArray<double>): string; var i: Integer; begin Result := '['; for i := 0 to High(x) do begin if i > 0 then Result := Result + ','; Result := Result + format('%.4f', [x[i]]); end; Result := Result + ']'; end; var xl: array of TArray<double> = [[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, - 1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578]]; x: TArray<double>; begin for x in xl do writeln(ArrayToString(FiveNumber(x)), #10); readln; end.
#include <algorithm> #include <iostream> #include <ostream> #include <vector> template<std::size_t> struct int_ {}; template <class Tuple, size_t Pos> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<Pos>) { out << std::get< std::tuple_size<Tuple>::value - Pos >(t) << ", "; return print_tuple(out, t, int_<Pos - 1>()); } template <class Tuple> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<1>) { return out << std::get<std::tuple_size<Tuple>::value - 1>(t); } template <class... Args> std::ostream& operator<<(std::ostream& out, const std::tuple<Args...>& t) { out << '('; print_tuple(out, t, int_<sizeof...(Args)>()); return out << ')'; } template <class RI> double median(RI beg, RI end) { if (beg == end) throw std::runtime_error("Range cannot be empty"); auto len = end - beg; auto m = len / 2; if (len % 2 == 1) { return *(beg + m); } return (beg[m - 1] + beg[m]) / 2.0; } template <class C> auto fivenum(C& c) { std::sort(c.begin(), c.end()); auto cbeg = c.cbegin(); auto cend = c.cend(); auto len = cend - cbeg; auto m = len / 2; auto lower = (len % 2 == 1) ? m : m - 1; double r2 = median(cbeg, cbeg + lower + 1); double r3 = median(cbeg, cend); double r4 = median(cbeg + lower + 1, cend); return std::make_tuple(*cbeg, r2, r3, r4, *(cend - 1)); } int main() { using namespace std; vector<vector<double>> cs = { { 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0 }, { 36.0, 40.0, 7.0, 39.0, 41.0, 15.0 }, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (auto & c : cs) { cout << fivenum(c) << endl; } return 0; }
Translate this program into Java but keep the logic exactly as in Delphi.
program Fivenum; uses System.SysUtils, System.Generics.Collections; function Median(x: TArray<Double>; start, endInclusive: Integer): Double; var size, m: Integer; begin size := endInclusive - start + 1; if (size <= 0) then raise EArgumentException.Create('Array slice cannot be empty'); m := start + size div 2; if (odd(size)) then Result := x[m] else Result := (x[m - 1] + x[m]) / 2; end; function FiveNumber(x: TArray<Double>): TArray<Double>; var m, lowerEnd: Integer; begin SetLength(result, 5); TArray.Sort<double>(x); result[0] := x[0]; result[2] := median(x, 0, length(x) - 1); result[4] := x[length(x) - 1]; m := length(x) div 2; if odd(length(x)) then lowerEnd := m else lowerEnd := m - 1; result[1] := median(x, 0, lowerEnd); result[3] := median(x, m, length(x) - 1); end; function ArrayToString(x: TArray<double>): string; var i: Integer; begin Result := '['; for i := 0 to High(x) do begin if i > 0 then Result := Result + ','; Result := Result + format('%.4f', [x[i]]); end; Result := Result + ']'; end; var xl: array of TArray<double> = [[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, - 1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578]]; x: TArray<double>; begin for x in xl do writeln(ArrayToString(FiveNumber(x)), #10); readln; end.
import java.util.Arrays; public class Fivenum { static double median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new IllegalArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] fivenum(double[] x) { for (Double d : x) { if (d.isNaN()) throw new IllegalArgumentException("Unable to deal with arrays containing NaN"); } double[] result = new double[5]; Arrays.sort(x); result[0] = x[0]; result[2] = median(x, 0, x.length - 1); result[4] = x[x.length - 1]; int m = x.length / 2; int lowerEnd = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x, 0, lowerEnd); result[3] = median(x, m, x.length - 1); return result; } public static void main(String[] args) { double xl[][] = { {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (double[] x : xl) System.out.printf("%s\n\n", Arrays.toString(fivenum(x))); } }
Convert this Delphi snippet to Java and keep its semantics consistent.
program Fivenum; uses System.SysUtils, System.Generics.Collections; function Median(x: TArray<Double>; start, endInclusive: Integer): Double; var size, m: Integer; begin size := endInclusive - start + 1; if (size <= 0) then raise EArgumentException.Create('Array slice cannot be empty'); m := start + size div 2; if (odd(size)) then Result := x[m] else Result := (x[m - 1] + x[m]) / 2; end; function FiveNumber(x: TArray<Double>): TArray<Double>; var m, lowerEnd: Integer; begin SetLength(result, 5); TArray.Sort<double>(x); result[0] := x[0]; result[2] := median(x, 0, length(x) - 1); result[4] := x[length(x) - 1]; m := length(x) div 2; if odd(length(x)) then lowerEnd := m else lowerEnd := m - 1; result[1] := median(x, 0, lowerEnd); result[3] := median(x, m, length(x) - 1); end; function ArrayToString(x: TArray<double>): string; var i: Integer; begin Result := '['; for i := 0 to High(x) do begin if i > 0 then Result := Result + ','; Result := Result + format('%.4f', [x[i]]); end; Result := Result + ']'; end; var xl: array of TArray<double> = [[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, - 1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578]]; x: TArray<double>; begin for x in xl do writeln(ArrayToString(FiveNumber(x)), #10); readln; end.
import java.util.Arrays; public class Fivenum { static double median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new IllegalArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] fivenum(double[] x) { for (Double d : x) { if (d.isNaN()) throw new IllegalArgumentException("Unable to deal with arrays containing NaN"); } double[] result = new double[5]; Arrays.sort(x); result[0] = x[0]; result[2] = median(x, 0, x.length - 1); result[4] = x[x.length - 1]; int m = x.length / 2; int lowerEnd = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x, 0, lowerEnd); result[3] = median(x, m, x.length - 1); return result; } public static void main(String[] args) { double xl[][] = { {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (double[] x : xl) System.out.printf("%s\n\n", Arrays.toString(fivenum(x))); } }
Change the programming language of this snippet from Delphi to Python without modifying what it does.
program Fivenum; uses System.SysUtils, System.Generics.Collections; function Median(x: TArray<Double>; start, endInclusive: Integer): Double; var size, m: Integer; begin size := endInclusive - start + 1; if (size <= 0) then raise EArgumentException.Create('Array slice cannot be empty'); m := start + size div 2; if (odd(size)) then Result := x[m] else Result := (x[m - 1] + x[m]) / 2; end; function FiveNumber(x: TArray<Double>): TArray<Double>; var m, lowerEnd: Integer; begin SetLength(result, 5); TArray.Sort<double>(x); result[0] := x[0]; result[2] := median(x, 0, length(x) - 1); result[4] := x[length(x) - 1]; m := length(x) div 2; if odd(length(x)) then lowerEnd := m else lowerEnd := m - 1; result[1] := median(x, 0, lowerEnd); result[3] := median(x, m, length(x) - 1); end; function ArrayToString(x: TArray<double>): string; var i: Integer; begin Result := '['; for i := 0 to High(x) do begin if i > 0 then Result := Result + ','; Result := Result + format('%.4f', [x[i]]); end; Result := Result + ']'; end; var xl: array of TArray<double> = [[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, - 1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578]]; x: TArray<double>; begin for x in xl do writeln(ArrayToString(FiveNumber(x)), #10); readln; end.
from __future__ import division import math import sys def fivenum(array): n = len(array) if n == 0: print("you entered an empty array.") sys.exit() x = sorted(array) n4 = math.floor((n+3.0)/2.0)/2.0 d = [1, n4, (n+1)/2, n+1-n4, n] sum_array = [] for e in range(5): floor = int(math.floor(d[e] - 1)) ceil = int(math.ceil(d[e] - 1)) sum_array.append(0.5 * (x[floor] + x[ceil])) return sum_array x = [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578] y = fivenum(x) print(y)
Rewrite the snippet below in Python so it works the same as the original Delphi code.
program Fivenum; uses System.SysUtils, System.Generics.Collections; function Median(x: TArray<Double>; start, endInclusive: Integer): Double; var size, m: Integer; begin size := endInclusive - start + 1; if (size <= 0) then raise EArgumentException.Create('Array slice cannot be empty'); m := start + size div 2; if (odd(size)) then Result := x[m] else Result := (x[m - 1] + x[m]) / 2; end; function FiveNumber(x: TArray<Double>): TArray<Double>; var m, lowerEnd: Integer; begin SetLength(result, 5); TArray.Sort<double>(x); result[0] := x[0]; result[2] := median(x, 0, length(x) - 1); result[4] := x[length(x) - 1]; m := length(x) div 2; if odd(length(x)) then lowerEnd := m else lowerEnd := m - 1; result[1] := median(x, 0, lowerEnd); result[3] := median(x, m, length(x) - 1); end; function ArrayToString(x: TArray<double>): string; var i: Integer; begin Result := '['; for i := 0 to High(x) do begin if i > 0 then Result := Result + ','; Result := Result + format('%.4f', [x[i]]); end; Result := Result + ']'; end; var xl: array of TArray<double> = [[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, - 1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578]]; x: TArray<double>; begin for x in xl do writeln(ArrayToString(FiveNumber(x)), #10); readln; end.
from __future__ import division import math import sys def fivenum(array): n = len(array) if n == 0: print("you entered an empty array.") sys.exit() x = sorted(array) n4 = math.floor((n+3.0)/2.0)/2.0 d = [1, n4, (n+1)/2, n+1-n4, n] sum_array = [] for e in range(5): floor = int(math.floor(d[e] - 1)) ceil = int(math.ceil(d[e] - 1)) sum_array.append(0.5 * (x[floor] + x[ceil])) return sum_array x = [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578] y = fivenum(x) print(y)
Convert the following code from Delphi to VB, ensuring the logic remains intact.
program Fivenum; uses System.SysUtils, System.Generics.Collections; function Median(x: TArray<Double>; start, endInclusive: Integer): Double; var size, m: Integer; begin size := endInclusive - start + 1; if (size <= 0) then raise EArgumentException.Create('Array slice cannot be empty'); m := start + size div 2; if (odd(size)) then Result := x[m] else Result := (x[m - 1] + x[m]) / 2; end; function FiveNumber(x: TArray<Double>): TArray<Double>; var m, lowerEnd: Integer; begin SetLength(result, 5); TArray.Sort<double>(x); result[0] := x[0]; result[2] := median(x, 0, length(x) - 1); result[4] := x[length(x) - 1]; m := length(x) div 2; if odd(length(x)) then lowerEnd := m else lowerEnd := m - 1; result[1] := median(x, 0, lowerEnd); result[3] := median(x, m, length(x) - 1); end; function ArrayToString(x: TArray<double>): string; var i: Integer; begin Result := '['; for i := 0 to High(x) do begin if i > 0 then Result := Result + ','; Result := Result + format('%.4f', [x[i]]); end; Result := Result + ']'; end; var xl: array of TArray<double> = [[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, - 1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578]]; x: TArray<double>; begin for x in xl do writeln(ArrayToString(FiveNumber(x)), #10); readln; end.
#define floor(x) ((x*2.0-0.5) Shr 1) Sub rapidSort (array()As Single, l As Integer, r As Integer) Dim As Integer n, wert, nptr, rep Dim As Single arr, LoVal = array(l), HiVal = array(r) For n = l To r If LoVal > array(n) Then LoVal = array(n) If HiVal < array(n) Then HiVal = array(n) Next n Redim SortArray(LoVal To HiVal) As Single For n = l To r wert = array(n) SortArray(wert) += 1 Next n nptr = l-1 For arr = LoVal To HiVal rep = SortArray(arr) For n = 1 To rep nptr += 1 array(nptr) = arr Next n Next arr Erase SortArray End Sub Function median(tbl() As Single, lo As Integer, hi As Integer) As Single Dim As Integer l = hi-lo+1 Dim As Integer m = lo+floor(l/2) If l Mod 2 = 1 Then Return tbl(m) Return (tbl(m-1)+tbl(m))/2 End Function Sub fivenum(tbl() As Single) rapidSort(tbl(), Lbound(tbl), Ubound(tbl)) Dim As Integer l = Ubound(tbl) Dim As Single m = floor(l/2) + (l Mod 2) Dim As Single r1,r2,r3,r4,r5 r1 = tbl(1) r2 = median(tbl(),1,m) r3 = median(tbl(),1,l) r4 = median(tbl(),m+1,l) r5 = tbl(l) Print "[" & r1; ","; r2; ","; r3; ","; r4; ", "; r5 & "]" End Sub Dim As Single x1(1 To ...) = {15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43} Dim As Single x2(1 To ...) = {36, 40, 7, 39, 41, 15} Dim As Single x3(1 To ...) = {_ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, _ 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, _ 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, _ 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578} fivenum(x1()) fivenum(x2()) fivenum(x3()) Sleep
Keep all operations the same but rewrite the snippet in VB.
program Fivenum; uses System.SysUtils, System.Generics.Collections; function Median(x: TArray<Double>; start, endInclusive: Integer): Double; var size, m: Integer; begin size := endInclusive - start + 1; if (size <= 0) then raise EArgumentException.Create('Array slice cannot be empty'); m := start + size div 2; if (odd(size)) then Result := x[m] else Result := (x[m - 1] + x[m]) / 2; end; function FiveNumber(x: TArray<Double>): TArray<Double>; var m, lowerEnd: Integer; begin SetLength(result, 5); TArray.Sort<double>(x); result[0] := x[0]; result[2] := median(x, 0, length(x) - 1); result[4] := x[length(x) - 1]; m := length(x) div 2; if odd(length(x)) then lowerEnd := m else lowerEnd := m - 1; result[1] := median(x, 0, lowerEnd); result[3] := median(x, m, length(x) - 1); end; function ArrayToString(x: TArray<double>): string; var i: Integer; begin Result := '['; for i := 0 to High(x) do begin if i > 0 then Result := Result + ','; Result := Result + format('%.4f', [x[i]]); end; Result := Result + ']'; end; var xl: array of TArray<double> = [[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, - 1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578]]; x: TArray<double>; begin for x in xl do writeln(ArrayToString(FiveNumber(x)), #10); readln; end.
#define floor(x) ((x*2.0-0.5) Shr 1) Sub rapidSort (array()As Single, l As Integer, r As Integer) Dim As Integer n, wert, nptr, rep Dim As Single arr, LoVal = array(l), HiVal = array(r) For n = l To r If LoVal > array(n) Then LoVal = array(n) If HiVal < array(n) Then HiVal = array(n) Next n Redim SortArray(LoVal To HiVal) As Single For n = l To r wert = array(n) SortArray(wert) += 1 Next n nptr = l-1 For arr = LoVal To HiVal rep = SortArray(arr) For n = 1 To rep nptr += 1 array(nptr) = arr Next n Next arr Erase SortArray End Sub Function median(tbl() As Single, lo As Integer, hi As Integer) As Single Dim As Integer l = hi-lo+1 Dim As Integer m = lo+floor(l/2) If l Mod 2 = 1 Then Return tbl(m) Return (tbl(m-1)+tbl(m))/2 End Function Sub fivenum(tbl() As Single) rapidSort(tbl(), Lbound(tbl), Ubound(tbl)) Dim As Integer l = Ubound(tbl) Dim As Single m = floor(l/2) + (l Mod 2) Dim As Single r1,r2,r3,r4,r5 r1 = tbl(1) r2 = median(tbl(),1,m) r3 = median(tbl(),1,l) r4 = median(tbl(),m+1,l) r5 = tbl(l) Print "[" & r1; ","; r2; ","; r3; ","; r4; ", "; r5 & "]" End Sub Dim As Single x1(1 To ...) = {15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43} Dim As Single x2(1 To ...) = {36, 40, 7, 39, 41, 15} Dim As Single x3(1 To ...) = {_ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, _ 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, _ 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, _ 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578} fivenum(x1()) fivenum(x2()) fivenum(x3()) Sleep
Produce a language-to-language conversion: from Delphi to Go, same semantics.
program Fivenum; uses System.SysUtils, System.Generics.Collections; function Median(x: TArray<Double>; start, endInclusive: Integer): Double; var size, m: Integer; begin size := endInclusive - start + 1; if (size <= 0) then raise EArgumentException.Create('Array slice cannot be empty'); m := start + size div 2; if (odd(size)) then Result := x[m] else Result := (x[m - 1] + x[m]) / 2; end; function FiveNumber(x: TArray<Double>): TArray<Double>; var m, lowerEnd: Integer; begin SetLength(result, 5); TArray.Sort<double>(x); result[0] := x[0]; result[2] := median(x, 0, length(x) - 1); result[4] := x[length(x) - 1]; m := length(x) div 2; if odd(length(x)) then lowerEnd := m else lowerEnd := m - 1; result[1] := median(x, 0, lowerEnd); result[3] := median(x, m, length(x) - 1); end; function ArrayToString(x: TArray<double>): string; var i: Integer; begin Result := '['; for i := 0 to High(x) do begin if i > 0 then Result := Result + ','; Result := Result + format('%.4f', [x[i]]); end; Result := Result + ']'; end; var xl: array of TArray<double> = [[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, - 1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578]]; x: TArray<double>; begin for x in xl do writeln(ArrayToString(FiveNumber(x)), #10); readln; end.
package main import ( "fmt" "math" "sort" ) func fivenum(a []float64) (n5 [5]float64) { sort.Float64s(a) n := float64(len(a)) n4 := float64((len(a)+3)/2) / 2 d := []float64{1, n4, (n + 1) / 2, n + 1 - n4, n} for e, de := range d { floor := int(de - 1) ceil := int(math.Ceil(de - 1)) n5[e] = .5 * (a[floor] + a[ceil]) } return } var ( x1 = []float64{36, 40, 7, 39, 41, 15} x2 = []float64{15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43} x3 = []float64{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578, } ) func main() { fmt.Println(fivenum(x1)) fmt.Println(fivenum(x2)) fmt.Println(fivenum(x3)) }
Maintain the same structure and functionality when rewriting this code in Go.
program Fivenum; uses System.SysUtils, System.Generics.Collections; function Median(x: TArray<Double>; start, endInclusive: Integer): Double; var size, m: Integer; begin size := endInclusive - start + 1; if (size <= 0) then raise EArgumentException.Create('Array slice cannot be empty'); m := start + size div 2; if (odd(size)) then Result := x[m] else Result := (x[m - 1] + x[m]) / 2; end; function FiveNumber(x: TArray<Double>): TArray<Double>; var m, lowerEnd: Integer; begin SetLength(result, 5); TArray.Sort<double>(x); result[0] := x[0]; result[2] := median(x, 0, length(x) - 1); result[4] := x[length(x) - 1]; m := length(x) div 2; if odd(length(x)) then lowerEnd := m else lowerEnd := m - 1; result[1] := median(x, 0, lowerEnd); result[3] := median(x, m, length(x) - 1); end; function ArrayToString(x: TArray<double>): string; var i: Integer; begin Result := '['; for i := 0 to High(x) do begin if i > 0 then Result := Result + ','; Result := Result + format('%.4f', [x[i]]); end; Result := Result + ']'; end; var xl: array of TArray<double> = [[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, - 1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578]]; x: TArray<double>; begin for x in xl do writeln(ArrayToString(FiveNumber(x)), #10); readln; end.
package main import ( "fmt" "math" "sort" ) func fivenum(a []float64) (n5 [5]float64) { sort.Float64s(a) n := float64(len(a)) n4 := float64((len(a)+3)/2) / 2 d := []float64{1, n4, (n + 1) / 2, n + 1 - n4, n} for e, de := range d { floor := int(de - 1) ceil := int(math.Ceil(de - 1)) n5[e] = .5 * (a[floor] + a[ceil]) } return } var ( x1 = []float64{36, 40, 7, 39, 41, 15} x2 = []float64{15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43} x3 = []float64{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578, } ) func main() { fmt.Println(fivenum(x1)) fmt.Println(fivenum(x2)) fmt.Println(fivenum(x3)) }
Generate an equivalent C version of this F# code.
open System let rec last = function | hd :: [] -> hd | _ :: tl -> last tl | _ -> failwith "Empty list." let median x = for e in x do if Double.IsNaN(e) then failwith "unable to deal with lists containing NaN" let size = List.length(x) if size <= 0 then failwith "Array slice cannot be empty" let m = size / 2 if size % 2 = 1 then x.[m] else (x.[m - 1] + x.[m]) / 2.0 let fivenum x = let x2 = List.sort(x) let m = List.length(x2) / 2 let lowerEnd = if List.length(x2) % 2 = 1 then m else m - 1 [List.head x2, median x2.[..lowerEnd], median x2, median x2.[m..], last x2] [<EntryPoint>] let main _ = let x1 = [ [15.0; 6.0; 42.0; 41.0; 7.0; 36.0; 49.0; 40.0; 39.0; 47.0; 43.0]; [36.0; 40.0; 7.0; 39.0; 41.0; 15.0]; [ 0.14082834; 0.09748790; 1.73131507; 0.87636009; -1.95059594; 0.73438555; -0.03035726; 1.46675970; -0.74621349; -0.72588772; 0.63905160; 0.61501527; -0.98983780; -1.00447874; -0.62759469; 0.66206163; 1.04312009; -0.10305385; 0.75775634; 0.32566578 ] ] for a in x1 do let y = fivenum a Console.WriteLine("{0}", y); 0
#include <stdio.h> #include <stdlib.h> double median(double *x, int start, int end_inclusive) { int size = end_inclusive - start + 1; if (size <= 0) { printf("Array slice cannot be empty\n"); exit(1); } int m = start + size / 2; if (size % 2) return x[m]; return (x[m - 1] + x[m]) / 2.0; } int compare (const void *a, const void *b) { double aa = *(double*)a; double bb = *(double*)b; if (aa > bb) return 1; if (aa < bb) return -1; return 0; } int fivenum(double *x, double *result, int x_len) { int i, m, lower_end; for (i = 0; i < x_len; i++) { if (x[i] != x[i]) { printf("Unable to deal with arrays containing NaN\n\n"); return 1; } } qsort(x, x_len, sizeof(double), compare); result[0] = x[0]; result[2] = median(x, 0, x_len - 1); result[4] = x[x_len - 1]; m = x_len / 2; lower_end = (x_len % 2) ? m : m - 1; result[1] = median(x, 0, lower_end); result[3] = median(x, m, x_len - 1); return 0; } int show(double *result, int places) { int i; char f[7]; sprintf(f, "%%.%dlf", places); printf("["); for (i = 0; i < 5; i++) { printf(f, result[i]); if (i < 4) printf(", "); } printf("]\n\n"); } int main() { double result[5]; double x1[11] = {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}; if (!fivenum(x1, result, 11)) show(result, 1); double x2[6] = {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}; if (!fivenum(x2, result, 6)) show(result, 1); double x3[20] = { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }; if (!fivenum(x3, result, 20)) show(result, 9); return 0; }
Port the provided F# code into C while preserving the original functionality.
open System let rec last = function | hd :: [] -> hd | _ :: tl -> last tl | _ -> failwith "Empty list." let median x = for e in x do if Double.IsNaN(e) then failwith "unable to deal with lists containing NaN" let size = List.length(x) if size <= 0 then failwith "Array slice cannot be empty" let m = size / 2 if size % 2 = 1 then x.[m] else (x.[m - 1] + x.[m]) / 2.0 let fivenum x = let x2 = List.sort(x) let m = List.length(x2) / 2 let lowerEnd = if List.length(x2) % 2 = 1 then m else m - 1 [List.head x2, median x2.[..lowerEnd], median x2, median x2.[m..], last x2] [<EntryPoint>] let main _ = let x1 = [ [15.0; 6.0; 42.0; 41.0; 7.0; 36.0; 49.0; 40.0; 39.0; 47.0; 43.0]; [36.0; 40.0; 7.0; 39.0; 41.0; 15.0]; [ 0.14082834; 0.09748790; 1.73131507; 0.87636009; -1.95059594; 0.73438555; -0.03035726; 1.46675970; -0.74621349; -0.72588772; 0.63905160; 0.61501527; -0.98983780; -1.00447874; -0.62759469; 0.66206163; 1.04312009; -0.10305385; 0.75775634; 0.32566578 ] ] for a in x1 do let y = fivenum a Console.WriteLine("{0}", y); 0
#include <stdio.h> #include <stdlib.h> double median(double *x, int start, int end_inclusive) { int size = end_inclusive - start + 1; if (size <= 0) { printf("Array slice cannot be empty\n"); exit(1); } int m = start + size / 2; if (size % 2) return x[m]; return (x[m - 1] + x[m]) / 2.0; } int compare (const void *a, const void *b) { double aa = *(double*)a; double bb = *(double*)b; if (aa > bb) return 1; if (aa < bb) return -1; return 0; } int fivenum(double *x, double *result, int x_len) { int i, m, lower_end; for (i = 0; i < x_len; i++) { if (x[i] != x[i]) { printf("Unable to deal with arrays containing NaN\n\n"); return 1; } } qsort(x, x_len, sizeof(double), compare); result[0] = x[0]; result[2] = median(x, 0, x_len - 1); result[4] = x[x_len - 1]; m = x_len / 2; lower_end = (x_len % 2) ? m : m - 1; result[1] = median(x, 0, lower_end); result[3] = median(x, m, x_len - 1); return 0; } int show(double *result, int places) { int i; char f[7]; sprintf(f, "%%.%dlf", places); printf("["); for (i = 0; i < 5; i++) { printf(f, result[i]); if (i < 4) printf(", "); } printf("]\n\n"); } int main() { double result[5]; double x1[11] = {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}; if (!fivenum(x1, result, 11)) show(result, 1); double x2[6] = {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}; if (!fivenum(x2, result, 6)) show(result, 1); double x3[20] = { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }; if (!fivenum(x3, result, 20)) show(result, 9); return 0; }
Convert the following code from F# to C#, ensuring the logic remains intact.
open System let rec last = function | hd :: [] -> hd | _ :: tl -> last tl | _ -> failwith "Empty list." let median x = for e in x do if Double.IsNaN(e) then failwith "unable to deal with lists containing NaN" let size = List.length(x) if size <= 0 then failwith "Array slice cannot be empty" let m = size / 2 if size % 2 = 1 then x.[m] else (x.[m - 1] + x.[m]) / 2.0 let fivenum x = let x2 = List.sort(x) let m = List.length(x2) / 2 let lowerEnd = if List.length(x2) % 2 = 1 then m else m - 1 [List.head x2, median x2.[..lowerEnd], median x2, median x2.[m..], last x2] [<EntryPoint>] let main _ = let x1 = [ [15.0; 6.0; 42.0; 41.0; 7.0; 36.0; 49.0; 40.0; 39.0; 47.0; 43.0]; [36.0; 40.0; 7.0; 39.0; 41.0; 15.0]; [ 0.14082834; 0.09748790; 1.73131507; 0.87636009; -1.95059594; 0.73438555; -0.03035726; 1.46675970; -0.74621349; -0.72588772; 0.63905160; 0.61501527; -0.98983780; -1.00447874; -0.62759469; 0.66206163; 1.04312009; -0.10305385; 0.75775634; 0.32566578 ] ] for a in x1 do let y = fivenum a Console.WriteLine("{0}", y); 0
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Fivenum { public static class Helper { public static string AsString<T>(this ICollection<T> c, string format = "{0}") { StringBuilder sb = new StringBuilder("["); int count = 0; foreach (var t in c) { if (count++ > 0) { sb.Append(", "); } sb.AppendFormat(format, t); } return sb.Append("]").ToString(); } } class Program { static double Median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new ArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] Fivenum(double[] x) { foreach (var d in x) { if (Double.IsNaN(d)) { throw new ArgumentException("Unable to deal with arrays containing NaN"); } } double[] result = new double[5]; Array.Sort(x); result[0] = x.First(); result[2] = Median(x, 0, x.Length - 1); result[4] = x.Last(); int m = x.Length / 2; int lowerEnd = (x.Length % 2 == 1) ? m : m - 1; result[1] = Median(x, 0, lowerEnd); result[3] = Median(x, m, x.Length - 1); return result; } static void Main(string[] args) { double[][] x1 = new double[][]{ new double[]{ 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, new double[]{ 36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, new double[]{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }, }; foreach(var x in x1) { var result = Fivenum(x); Console.WriteLine(result.AsString("{0:F8}")); } } } }
Change the following F# code into C# without altering its purpose.
open System let rec last = function | hd :: [] -> hd | _ :: tl -> last tl | _ -> failwith "Empty list." let median x = for e in x do if Double.IsNaN(e) then failwith "unable to deal with lists containing NaN" let size = List.length(x) if size <= 0 then failwith "Array slice cannot be empty" let m = size / 2 if size % 2 = 1 then x.[m] else (x.[m - 1] + x.[m]) / 2.0 let fivenum x = let x2 = List.sort(x) let m = List.length(x2) / 2 let lowerEnd = if List.length(x2) % 2 = 1 then m else m - 1 [List.head x2, median x2.[..lowerEnd], median x2, median x2.[m..], last x2] [<EntryPoint>] let main _ = let x1 = [ [15.0; 6.0; 42.0; 41.0; 7.0; 36.0; 49.0; 40.0; 39.0; 47.0; 43.0]; [36.0; 40.0; 7.0; 39.0; 41.0; 15.0]; [ 0.14082834; 0.09748790; 1.73131507; 0.87636009; -1.95059594; 0.73438555; -0.03035726; 1.46675970; -0.74621349; -0.72588772; 0.63905160; 0.61501527; -0.98983780; -1.00447874; -0.62759469; 0.66206163; 1.04312009; -0.10305385; 0.75775634; 0.32566578 ] ] for a in x1 do let y = fivenum a Console.WriteLine("{0}", y); 0
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Fivenum { public static class Helper { public static string AsString<T>(this ICollection<T> c, string format = "{0}") { StringBuilder sb = new StringBuilder("["); int count = 0; foreach (var t in c) { if (count++ > 0) { sb.Append(", "); } sb.AppendFormat(format, t); } return sb.Append("]").ToString(); } } class Program { static double Median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new ArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] Fivenum(double[] x) { foreach (var d in x) { if (Double.IsNaN(d)) { throw new ArgumentException("Unable to deal with arrays containing NaN"); } } double[] result = new double[5]; Array.Sort(x); result[0] = x.First(); result[2] = Median(x, 0, x.Length - 1); result[4] = x.Last(); int m = x.Length / 2; int lowerEnd = (x.Length % 2 == 1) ? m : m - 1; result[1] = Median(x, 0, lowerEnd); result[3] = Median(x, m, x.Length - 1); return result; } static void Main(string[] args) { double[][] x1 = new double[][]{ new double[]{ 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, new double[]{ 36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, new double[]{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }, }; foreach(var x in x1) { var result = Fivenum(x); Console.WriteLine(result.AsString("{0:F8}")); } } } }
Rewrite this program in C++ while keeping its functionality equivalent to the F# version.
open System let rec last = function | hd :: [] -> hd | _ :: tl -> last tl | _ -> failwith "Empty list." let median x = for e in x do if Double.IsNaN(e) then failwith "unable to deal with lists containing NaN" let size = List.length(x) if size <= 0 then failwith "Array slice cannot be empty" let m = size / 2 if size % 2 = 1 then x.[m] else (x.[m - 1] + x.[m]) / 2.0 let fivenum x = let x2 = List.sort(x) let m = List.length(x2) / 2 let lowerEnd = if List.length(x2) % 2 = 1 then m else m - 1 [List.head x2, median x2.[..lowerEnd], median x2, median x2.[m..], last x2] [<EntryPoint>] let main _ = let x1 = [ [15.0; 6.0; 42.0; 41.0; 7.0; 36.0; 49.0; 40.0; 39.0; 47.0; 43.0]; [36.0; 40.0; 7.0; 39.0; 41.0; 15.0]; [ 0.14082834; 0.09748790; 1.73131507; 0.87636009; -1.95059594; 0.73438555; -0.03035726; 1.46675970; -0.74621349; -0.72588772; 0.63905160; 0.61501527; -0.98983780; -1.00447874; -0.62759469; 0.66206163; 1.04312009; -0.10305385; 0.75775634; 0.32566578 ] ] for a in x1 do let y = fivenum a Console.WriteLine("{0}", y); 0
#include <algorithm> #include <iostream> #include <ostream> #include <vector> template<std::size_t> struct int_ {}; template <class Tuple, size_t Pos> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<Pos>) { out << std::get< std::tuple_size<Tuple>::value - Pos >(t) << ", "; return print_tuple(out, t, int_<Pos - 1>()); } template <class Tuple> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<1>) { return out << std::get<std::tuple_size<Tuple>::value - 1>(t); } template <class... Args> std::ostream& operator<<(std::ostream& out, const std::tuple<Args...>& t) { out << '('; print_tuple(out, t, int_<sizeof...(Args)>()); return out << ')'; } template <class RI> double median(RI beg, RI end) { if (beg == end) throw std::runtime_error("Range cannot be empty"); auto len = end - beg; auto m = len / 2; if (len % 2 == 1) { return *(beg + m); } return (beg[m - 1] + beg[m]) / 2.0; } template <class C> auto fivenum(C& c) { std::sort(c.begin(), c.end()); auto cbeg = c.cbegin(); auto cend = c.cend(); auto len = cend - cbeg; auto m = len / 2; auto lower = (len % 2 == 1) ? m : m - 1; double r2 = median(cbeg, cbeg + lower + 1); double r3 = median(cbeg, cend); double r4 = median(cbeg + lower + 1, cend); return std::make_tuple(*cbeg, r2, r3, r4, *(cend - 1)); } int main() { using namespace std; vector<vector<double>> cs = { { 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0 }, { 36.0, 40.0, 7.0, 39.0, 41.0, 15.0 }, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (auto & c : cs) { cout << fivenum(c) << endl; } return 0; }
Generate a C++ translation of this F# snippet without changing its computational steps.
open System let rec last = function | hd :: [] -> hd | _ :: tl -> last tl | _ -> failwith "Empty list." let median x = for e in x do if Double.IsNaN(e) then failwith "unable to deal with lists containing NaN" let size = List.length(x) if size <= 0 then failwith "Array slice cannot be empty" let m = size / 2 if size % 2 = 1 then x.[m] else (x.[m - 1] + x.[m]) / 2.0 let fivenum x = let x2 = List.sort(x) let m = List.length(x2) / 2 let lowerEnd = if List.length(x2) % 2 = 1 then m else m - 1 [List.head x2, median x2.[..lowerEnd], median x2, median x2.[m..], last x2] [<EntryPoint>] let main _ = let x1 = [ [15.0; 6.0; 42.0; 41.0; 7.0; 36.0; 49.0; 40.0; 39.0; 47.0; 43.0]; [36.0; 40.0; 7.0; 39.0; 41.0; 15.0]; [ 0.14082834; 0.09748790; 1.73131507; 0.87636009; -1.95059594; 0.73438555; -0.03035726; 1.46675970; -0.74621349; -0.72588772; 0.63905160; 0.61501527; -0.98983780; -1.00447874; -0.62759469; 0.66206163; 1.04312009; -0.10305385; 0.75775634; 0.32566578 ] ] for a in x1 do let y = fivenum a Console.WriteLine("{0}", y); 0
#include <algorithm> #include <iostream> #include <ostream> #include <vector> template<std::size_t> struct int_ {}; template <class Tuple, size_t Pos> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<Pos>) { out << std::get< std::tuple_size<Tuple>::value - Pos >(t) << ", "; return print_tuple(out, t, int_<Pos - 1>()); } template <class Tuple> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<1>) { return out << std::get<std::tuple_size<Tuple>::value - 1>(t); } template <class... Args> std::ostream& operator<<(std::ostream& out, const std::tuple<Args...>& t) { out << '('; print_tuple(out, t, int_<sizeof...(Args)>()); return out << ')'; } template <class RI> double median(RI beg, RI end) { if (beg == end) throw std::runtime_error("Range cannot be empty"); auto len = end - beg; auto m = len / 2; if (len % 2 == 1) { return *(beg + m); } return (beg[m - 1] + beg[m]) / 2.0; } template <class C> auto fivenum(C& c) { std::sort(c.begin(), c.end()); auto cbeg = c.cbegin(); auto cend = c.cend(); auto len = cend - cbeg; auto m = len / 2; auto lower = (len % 2 == 1) ? m : m - 1; double r2 = median(cbeg, cbeg + lower + 1); double r3 = median(cbeg, cend); double r4 = median(cbeg + lower + 1, cend); return std::make_tuple(*cbeg, r2, r3, r4, *(cend - 1)); } int main() { using namespace std; vector<vector<double>> cs = { { 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0 }, { 36.0, 40.0, 7.0, 39.0, 41.0, 15.0 }, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (auto & c : cs) { cout << fivenum(c) << endl; } return 0; }
Write the same code in Java as shown below in F#.
open System let rec last = function | hd :: [] -> hd | _ :: tl -> last tl | _ -> failwith "Empty list." let median x = for e in x do if Double.IsNaN(e) then failwith "unable to deal with lists containing NaN" let size = List.length(x) if size <= 0 then failwith "Array slice cannot be empty" let m = size / 2 if size % 2 = 1 then x.[m] else (x.[m - 1] + x.[m]) / 2.0 let fivenum x = let x2 = List.sort(x) let m = List.length(x2) / 2 let lowerEnd = if List.length(x2) % 2 = 1 then m else m - 1 [List.head x2, median x2.[..lowerEnd], median x2, median x2.[m..], last x2] [<EntryPoint>] let main _ = let x1 = [ [15.0; 6.0; 42.0; 41.0; 7.0; 36.0; 49.0; 40.0; 39.0; 47.0; 43.0]; [36.0; 40.0; 7.0; 39.0; 41.0; 15.0]; [ 0.14082834; 0.09748790; 1.73131507; 0.87636009; -1.95059594; 0.73438555; -0.03035726; 1.46675970; -0.74621349; -0.72588772; 0.63905160; 0.61501527; -0.98983780; -1.00447874; -0.62759469; 0.66206163; 1.04312009; -0.10305385; 0.75775634; 0.32566578 ] ] for a in x1 do let y = fivenum a Console.WriteLine("{0}", y); 0
import java.util.Arrays; public class Fivenum { static double median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new IllegalArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] fivenum(double[] x) { for (Double d : x) { if (d.isNaN()) throw new IllegalArgumentException("Unable to deal with arrays containing NaN"); } double[] result = new double[5]; Arrays.sort(x); result[0] = x[0]; result[2] = median(x, 0, x.length - 1); result[4] = x[x.length - 1]; int m = x.length / 2; int lowerEnd = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x, 0, lowerEnd); result[3] = median(x, m, x.length - 1); return result; } public static void main(String[] args) { double xl[][] = { {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (double[] x : xl) System.out.printf("%s\n\n", Arrays.toString(fivenum(x))); } }
Convert this F# snippet to Java and keep its semantics consistent.
open System let rec last = function | hd :: [] -> hd | _ :: tl -> last tl | _ -> failwith "Empty list." let median x = for e in x do if Double.IsNaN(e) then failwith "unable to deal with lists containing NaN" let size = List.length(x) if size <= 0 then failwith "Array slice cannot be empty" let m = size / 2 if size % 2 = 1 then x.[m] else (x.[m - 1] + x.[m]) / 2.0 let fivenum x = let x2 = List.sort(x) let m = List.length(x2) / 2 let lowerEnd = if List.length(x2) % 2 = 1 then m else m - 1 [List.head x2, median x2.[..lowerEnd], median x2, median x2.[m..], last x2] [<EntryPoint>] let main _ = let x1 = [ [15.0; 6.0; 42.0; 41.0; 7.0; 36.0; 49.0; 40.0; 39.0; 47.0; 43.0]; [36.0; 40.0; 7.0; 39.0; 41.0; 15.0]; [ 0.14082834; 0.09748790; 1.73131507; 0.87636009; -1.95059594; 0.73438555; -0.03035726; 1.46675970; -0.74621349; -0.72588772; 0.63905160; 0.61501527; -0.98983780; -1.00447874; -0.62759469; 0.66206163; 1.04312009; -0.10305385; 0.75775634; 0.32566578 ] ] for a in x1 do let y = fivenum a Console.WriteLine("{0}", y); 0
import java.util.Arrays; public class Fivenum { static double median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new IllegalArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] fivenum(double[] x) { for (Double d : x) { if (d.isNaN()) throw new IllegalArgumentException("Unable to deal with arrays containing NaN"); } double[] result = new double[5]; Arrays.sort(x); result[0] = x[0]; result[2] = median(x, 0, x.length - 1); result[4] = x[x.length - 1]; int m = x.length / 2; int lowerEnd = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x, 0, lowerEnd); result[3] = median(x, m, x.length - 1); return result; } public static void main(String[] args) { double xl[][] = { {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (double[] x : xl) System.out.printf("%s\n\n", Arrays.toString(fivenum(x))); } }
Please provide an equivalent version of this F# code in Python.
open System let rec last = function | hd :: [] -> hd | _ :: tl -> last tl | _ -> failwith "Empty list." let median x = for e in x do if Double.IsNaN(e) then failwith "unable to deal with lists containing NaN" let size = List.length(x) if size <= 0 then failwith "Array slice cannot be empty" let m = size / 2 if size % 2 = 1 then x.[m] else (x.[m - 1] + x.[m]) / 2.0 let fivenum x = let x2 = List.sort(x) let m = List.length(x2) / 2 let lowerEnd = if List.length(x2) % 2 = 1 then m else m - 1 [List.head x2, median x2.[..lowerEnd], median x2, median x2.[m..], last x2] [<EntryPoint>] let main _ = let x1 = [ [15.0; 6.0; 42.0; 41.0; 7.0; 36.0; 49.0; 40.0; 39.0; 47.0; 43.0]; [36.0; 40.0; 7.0; 39.0; 41.0; 15.0]; [ 0.14082834; 0.09748790; 1.73131507; 0.87636009; -1.95059594; 0.73438555; -0.03035726; 1.46675970; -0.74621349; -0.72588772; 0.63905160; 0.61501527; -0.98983780; -1.00447874; -0.62759469; 0.66206163; 1.04312009; -0.10305385; 0.75775634; 0.32566578 ] ] for a in x1 do let y = fivenum a Console.WriteLine("{0}", y); 0
from __future__ import division import math import sys def fivenum(array): n = len(array) if n == 0: print("you entered an empty array.") sys.exit() x = sorted(array) n4 = math.floor((n+3.0)/2.0)/2.0 d = [1, n4, (n+1)/2, n+1-n4, n] sum_array = [] for e in range(5): floor = int(math.floor(d[e] - 1)) ceil = int(math.ceil(d[e] - 1)) sum_array.append(0.5 * (x[floor] + x[ceil])) return sum_array x = [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578] y = fivenum(x) print(y)
Produce a language-to-language conversion: from F# to Python, same semantics.
open System let rec last = function | hd :: [] -> hd | _ :: tl -> last tl | _ -> failwith "Empty list." let median x = for e in x do if Double.IsNaN(e) then failwith "unable to deal with lists containing NaN" let size = List.length(x) if size <= 0 then failwith "Array slice cannot be empty" let m = size / 2 if size % 2 = 1 then x.[m] else (x.[m - 1] + x.[m]) / 2.0 let fivenum x = let x2 = List.sort(x) let m = List.length(x2) / 2 let lowerEnd = if List.length(x2) % 2 = 1 then m else m - 1 [List.head x2, median x2.[..lowerEnd], median x2, median x2.[m..], last x2] [<EntryPoint>] let main _ = let x1 = [ [15.0; 6.0; 42.0; 41.0; 7.0; 36.0; 49.0; 40.0; 39.0; 47.0; 43.0]; [36.0; 40.0; 7.0; 39.0; 41.0; 15.0]; [ 0.14082834; 0.09748790; 1.73131507; 0.87636009; -1.95059594; 0.73438555; -0.03035726; 1.46675970; -0.74621349; -0.72588772; 0.63905160; 0.61501527; -0.98983780; -1.00447874; -0.62759469; 0.66206163; 1.04312009; -0.10305385; 0.75775634; 0.32566578 ] ] for a in x1 do let y = fivenum a Console.WriteLine("{0}", y); 0
from __future__ import division import math import sys def fivenum(array): n = len(array) if n == 0: print("you entered an empty array.") sys.exit() x = sorted(array) n4 = math.floor((n+3.0)/2.0)/2.0 d = [1, n4, (n+1)/2, n+1-n4, n] sum_array = [] for e in range(5): floor = int(math.floor(d[e] - 1)) ceil = int(math.ceil(d[e] - 1)) sum_array.append(0.5 * (x[floor] + x[ceil])) return sum_array x = [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578] y = fivenum(x) print(y)
Convert the following code from F# to VB, ensuring the logic remains intact.
open System let rec last = function | hd :: [] -> hd | _ :: tl -> last tl | _ -> failwith "Empty list." let median x = for e in x do if Double.IsNaN(e) then failwith "unable to deal with lists containing NaN" let size = List.length(x) if size <= 0 then failwith "Array slice cannot be empty" let m = size / 2 if size % 2 = 1 then x.[m] else (x.[m - 1] + x.[m]) / 2.0 let fivenum x = let x2 = List.sort(x) let m = List.length(x2) / 2 let lowerEnd = if List.length(x2) % 2 = 1 then m else m - 1 [List.head x2, median x2.[..lowerEnd], median x2, median x2.[m..], last x2] [<EntryPoint>] let main _ = let x1 = [ [15.0; 6.0; 42.0; 41.0; 7.0; 36.0; 49.0; 40.0; 39.0; 47.0; 43.0]; [36.0; 40.0; 7.0; 39.0; 41.0; 15.0]; [ 0.14082834; 0.09748790; 1.73131507; 0.87636009; -1.95059594; 0.73438555; -0.03035726; 1.46675970; -0.74621349; -0.72588772; 0.63905160; 0.61501527; -0.98983780; -1.00447874; -0.62759469; 0.66206163; 1.04312009; -0.10305385; 0.75775634; 0.32566578 ] ] for a in x1 do let y = fivenum a Console.WriteLine("{0}", y); 0
#define floor(x) ((x*2.0-0.5) Shr 1) Sub rapidSort (array()As Single, l As Integer, r As Integer) Dim As Integer n, wert, nptr, rep Dim As Single arr, LoVal = array(l), HiVal = array(r) For n = l To r If LoVal > array(n) Then LoVal = array(n) If HiVal < array(n) Then HiVal = array(n) Next n Redim SortArray(LoVal To HiVal) As Single For n = l To r wert = array(n) SortArray(wert) += 1 Next n nptr = l-1 For arr = LoVal To HiVal rep = SortArray(arr) For n = 1 To rep nptr += 1 array(nptr) = arr Next n Next arr Erase SortArray End Sub Function median(tbl() As Single, lo As Integer, hi As Integer) As Single Dim As Integer l = hi-lo+1 Dim As Integer m = lo+floor(l/2) If l Mod 2 = 1 Then Return tbl(m) Return (tbl(m-1)+tbl(m))/2 End Function Sub fivenum(tbl() As Single) rapidSort(tbl(), Lbound(tbl), Ubound(tbl)) Dim As Integer l = Ubound(tbl) Dim As Single m = floor(l/2) + (l Mod 2) Dim As Single r1,r2,r3,r4,r5 r1 = tbl(1) r2 = median(tbl(),1,m) r3 = median(tbl(),1,l) r4 = median(tbl(),m+1,l) r5 = tbl(l) Print "[" & r1; ","; r2; ","; r3; ","; r4; ", "; r5 & "]" End Sub Dim As Single x1(1 To ...) = {15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43} Dim As Single x2(1 To ...) = {36, 40, 7, 39, 41, 15} Dim As Single x3(1 To ...) = {_ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, _ 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, _ 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, _ 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578} fivenum(x1()) fivenum(x2()) fivenum(x3()) Sleep
Produce a language-to-language conversion: from F# to VB, same semantics.
open System let rec last = function | hd :: [] -> hd | _ :: tl -> last tl | _ -> failwith "Empty list." let median x = for e in x do if Double.IsNaN(e) then failwith "unable to deal with lists containing NaN" let size = List.length(x) if size <= 0 then failwith "Array slice cannot be empty" let m = size / 2 if size % 2 = 1 then x.[m] else (x.[m - 1] + x.[m]) / 2.0 let fivenum x = let x2 = List.sort(x) let m = List.length(x2) / 2 let lowerEnd = if List.length(x2) % 2 = 1 then m else m - 1 [List.head x2, median x2.[..lowerEnd], median x2, median x2.[m..], last x2] [<EntryPoint>] let main _ = let x1 = [ [15.0; 6.0; 42.0; 41.0; 7.0; 36.0; 49.0; 40.0; 39.0; 47.0; 43.0]; [36.0; 40.0; 7.0; 39.0; 41.0; 15.0]; [ 0.14082834; 0.09748790; 1.73131507; 0.87636009; -1.95059594; 0.73438555; -0.03035726; 1.46675970; -0.74621349; -0.72588772; 0.63905160; 0.61501527; -0.98983780; -1.00447874; -0.62759469; 0.66206163; 1.04312009; -0.10305385; 0.75775634; 0.32566578 ] ] for a in x1 do let y = fivenum a Console.WriteLine("{0}", y); 0
#define floor(x) ((x*2.0-0.5) Shr 1) Sub rapidSort (array()As Single, l As Integer, r As Integer) Dim As Integer n, wert, nptr, rep Dim As Single arr, LoVal = array(l), HiVal = array(r) For n = l To r If LoVal > array(n) Then LoVal = array(n) If HiVal < array(n) Then HiVal = array(n) Next n Redim SortArray(LoVal To HiVal) As Single For n = l To r wert = array(n) SortArray(wert) += 1 Next n nptr = l-1 For arr = LoVal To HiVal rep = SortArray(arr) For n = 1 To rep nptr += 1 array(nptr) = arr Next n Next arr Erase SortArray End Sub Function median(tbl() As Single, lo As Integer, hi As Integer) As Single Dim As Integer l = hi-lo+1 Dim As Integer m = lo+floor(l/2) If l Mod 2 = 1 Then Return tbl(m) Return (tbl(m-1)+tbl(m))/2 End Function Sub fivenum(tbl() As Single) rapidSort(tbl(), Lbound(tbl), Ubound(tbl)) Dim As Integer l = Ubound(tbl) Dim As Single m = floor(l/2) + (l Mod 2) Dim As Single r1,r2,r3,r4,r5 r1 = tbl(1) r2 = median(tbl(),1,m) r3 = median(tbl(),1,l) r4 = median(tbl(),m+1,l) r5 = tbl(l) Print "[" & r1; ","; r2; ","; r3; ","; r4; ", "; r5 & "]" End Sub Dim As Single x1(1 To ...) = {15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43} Dim As Single x2(1 To ...) = {36, 40, 7, 39, 41, 15} Dim As Single x3(1 To ...) = {_ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, _ 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, _ 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, _ 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578} fivenum(x1()) fivenum(x2()) fivenum(x3()) Sleep
Convert the following code from F# to Go, ensuring the logic remains intact.
open System let rec last = function | hd :: [] -> hd | _ :: tl -> last tl | _ -> failwith "Empty list." let median x = for e in x do if Double.IsNaN(e) then failwith "unable to deal with lists containing NaN" let size = List.length(x) if size <= 0 then failwith "Array slice cannot be empty" let m = size / 2 if size % 2 = 1 then x.[m] else (x.[m - 1] + x.[m]) / 2.0 let fivenum x = let x2 = List.sort(x) let m = List.length(x2) / 2 let lowerEnd = if List.length(x2) % 2 = 1 then m else m - 1 [List.head x2, median x2.[..lowerEnd], median x2, median x2.[m..], last x2] [<EntryPoint>] let main _ = let x1 = [ [15.0; 6.0; 42.0; 41.0; 7.0; 36.0; 49.0; 40.0; 39.0; 47.0; 43.0]; [36.0; 40.0; 7.0; 39.0; 41.0; 15.0]; [ 0.14082834; 0.09748790; 1.73131507; 0.87636009; -1.95059594; 0.73438555; -0.03035726; 1.46675970; -0.74621349; -0.72588772; 0.63905160; 0.61501527; -0.98983780; -1.00447874; -0.62759469; 0.66206163; 1.04312009; -0.10305385; 0.75775634; 0.32566578 ] ] for a in x1 do let y = fivenum a Console.WriteLine("{0}", y); 0
package main import ( "fmt" "math" "sort" ) func fivenum(a []float64) (n5 [5]float64) { sort.Float64s(a) n := float64(len(a)) n4 := float64((len(a)+3)/2) / 2 d := []float64{1, n4, (n + 1) / 2, n + 1 - n4, n} for e, de := range d { floor := int(de - 1) ceil := int(math.Ceil(de - 1)) n5[e] = .5 * (a[floor] + a[ceil]) } return } var ( x1 = []float64{36, 40, 7, 39, 41, 15} x2 = []float64{15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43} x3 = []float64{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578, } ) func main() { fmt.Println(fivenum(x1)) fmt.Println(fivenum(x2)) fmt.Println(fivenum(x3)) }
Change the following F# code into Go without altering its purpose.
open System let rec last = function | hd :: [] -> hd | _ :: tl -> last tl | _ -> failwith "Empty list." let median x = for e in x do if Double.IsNaN(e) then failwith "unable to deal with lists containing NaN" let size = List.length(x) if size <= 0 then failwith "Array slice cannot be empty" let m = size / 2 if size % 2 = 1 then x.[m] else (x.[m - 1] + x.[m]) / 2.0 let fivenum x = let x2 = List.sort(x) let m = List.length(x2) / 2 let lowerEnd = if List.length(x2) % 2 = 1 then m else m - 1 [List.head x2, median x2.[..lowerEnd], median x2, median x2.[m..], last x2] [<EntryPoint>] let main _ = let x1 = [ [15.0; 6.0; 42.0; 41.0; 7.0; 36.0; 49.0; 40.0; 39.0; 47.0; 43.0]; [36.0; 40.0; 7.0; 39.0; 41.0; 15.0]; [ 0.14082834; 0.09748790; 1.73131507; 0.87636009; -1.95059594; 0.73438555; -0.03035726; 1.46675970; -0.74621349; -0.72588772; 0.63905160; 0.61501527; -0.98983780; -1.00447874; -0.62759469; 0.66206163; 1.04312009; -0.10305385; 0.75775634; 0.32566578 ] ] for a in x1 do let y = fivenum a Console.WriteLine("{0}", y); 0
package main import ( "fmt" "math" "sort" ) func fivenum(a []float64) (n5 [5]float64) { sort.Float64s(a) n := float64(len(a)) n4 := float64((len(a)+3)/2) / 2 d := []float64{1, n4, (n + 1) / 2, n + 1 - n4, n} for e, de := range d { floor := int(de - 1) ceil := int(math.Ceil(de - 1)) n5[e] = .5 * (a[floor] + a[ceil]) } return } var ( x1 = []float64{36, 40, 7, 39, 41, 15} x2 = []float64{15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43} x3 = []float64{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578, } ) func main() { fmt.Println(fivenum(x1)) fmt.Println(fivenum(x2)) fmt.Println(fivenum(x3)) }
Change the following Factor code into C without altering its purpose.
USING: combinators combinators.smart kernel math math.statistics prettyprint sequences sorting ; IN: rosetta-code.five-number <PRIVATE : bisect ( seq -- lower upper ) dup length even? [ halves ] [ dup midpoint@ 1 + [ head ] [ tail* ] 2bi ] if ; : (fivenum) ( seq -- summary ) natural-sort { [ infimum ] [ bisect drop median ] [ median ] [ bisect nip median ] [ supremum ] } cleave>array ; PRIVATE> ERROR: fivenum-empty data ; ERROR: fivenum-nan data ; : fivenum ( seq -- summary ) { { [ dup empty? ] [ fivenum-empty ] } { [ dup [ fp-nan? ] any? ] [ fivenum-nan ] } [ (fivenum) ] } cond ; : fivenum-demo ( -- ) { 15 6 42 41 7 36 49 40 39 47 43 } { 36 40 7 39 41 15 } { 0.14082834 0.09748790 1.73131507 0.87636009 -1.95059594 0.73438555 -0.03035726 1.46675970 -0.74621349 -0.72588772 0.63905160 0.61501527 -0.98983780 -1.00447874 -0.62759469 0.66206163 1.04312009 -0.10305385 0.75775634 0.32566578 } [ fivenum . ] tri@ ; MAIN: fivenum-demo
#include <stdio.h> #include <stdlib.h> double median(double *x, int start, int end_inclusive) { int size = end_inclusive - start + 1; if (size <= 0) { printf("Array slice cannot be empty\n"); exit(1); } int m = start + size / 2; if (size % 2) return x[m]; return (x[m - 1] + x[m]) / 2.0; } int compare (const void *a, const void *b) { double aa = *(double*)a; double bb = *(double*)b; if (aa > bb) return 1; if (aa < bb) return -1; return 0; } int fivenum(double *x, double *result, int x_len) { int i, m, lower_end; for (i = 0; i < x_len; i++) { if (x[i] != x[i]) { printf("Unable to deal with arrays containing NaN\n\n"); return 1; } } qsort(x, x_len, sizeof(double), compare); result[0] = x[0]; result[2] = median(x, 0, x_len - 1); result[4] = x[x_len - 1]; m = x_len / 2; lower_end = (x_len % 2) ? m : m - 1; result[1] = median(x, 0, lower_end); result[3] = median(x, m, x_len - 1); return 0; } int show(double *result, int places) { int i; char f[7]; sprintf(f, "%%.%dlf", places); printf("["); for (i = 0; i < 5; i++) { printf(f, result[i]); if (i < 4) printf(", "); } printf("]\n\n"); } int main() { double result[5]; double x1[11] = {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}; if (!fivenum(x1, result, 11)) show(result, 1); double x2[6] = {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}; if (!fivenum(x2, result, 6)) show(result, 1); double x3[20] = { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }; if (!fivenum(x3, result, 20)) show(result, 9); return 0; }
Preserve the algorithm and functionality while converting the code from Factor to C.
USING: combinators combinators.smart kernel math math.statistics prettyprint sequences sorting ; IN: rosetta-code.five-number <PRIVATE : bisect ( seq -- lower upper ) dup length even? [ halves ] [ dup midpoint@ 1 + [ head ] [ tail* ] 2bi ] if ; : (fivenum) ( seq -- summary ) natural-sort { [ infimum ] [ bisect drop median ] [ median ] [ bisect nip median ] [ supremum ] } cleave>array ; PRIVATE> ERROR: fivenum-empty data ; ERROR: fivenum-nan data ; : fivenum ( seq -- summary ) { { [ dup empty? ] [ fivenum-empty ] } { [ dup [ fp-nan? ] any? ] [ fivenum-nan ] } [ (fivenum) ] } cond ; : fivenum-demo ( -- ) { 15 6 42 41 7 36 49 40 39 47 43 } { 36 40 7 39 41 15 } { 0.14082834 0.09748790 1.73131507 0.87636009 -1.95059594 0.73438555 -0.03035726 1.46675970 -0.74621349 -0.72588772 0.63905160 0.61501527 -0.98983780 -1.00447874 -0.62759469 0.66206163 1.04312009 -0.10305385 0.75775634 0.32566578 } [ fivenum . ] tri@ ; MAIN: fivenum-demo
#include <stdio.h> #include <stdlib.h> double median(double *x, int start, int end_inclusive) { int size = end_inclusive - start + 1; if (size <= 0) { printf("Array slice cannot be empty\n"); exit(1); } int m = start + size / 2; if (size % 2) return x[m]; return (x[m - 1] + x[m]) / 2.0; } int compare (const void *a, const void *b) { double aa = *(double*)a; double bb = *(double*)b; if (aa > bb) return 1; if (aa < bb) return -1; return 0; } int fivenum(double *x, double *result, int x_len) { int i, m, lower_end; for (i = 0; i < x_len; i++) { if (x[i] != x[i]) { printf("Unable to deal with arrays containing NaN\n\n"); return 1; } } qsort(x, x_len, sizeof(double), compare); result[0] = x[0]; result[2] = median(x, 0, x_len - 1); result[4] = x[x_len - 1]; m = x_len / 2; lower_end = (x_len % 2) ? m : m - 1; result[1] = median(x, 0, lower_end); result[3] = median(x, m, x_len - 1); return 0; } int show(double *result, int places) { int i; char f[7]; sprintf(f, "%%.%dlf", places); printf("["); for (i = 0; i < 5; i++) { printf(f, result[i]); if (i < 4) printf(", "); } printf("]\n\n"); } int main() { double result[5]; double x1[11] = {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}; if (!fivenum(x1, result, 11)) show(result, 1); double x2[6] = {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}; if (!fivenum(x2, result, 6)) show(result, 1); double x3[20] = { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }; if (!fivenum(x3, result, 20)) show(result, 9); return 0; }
Transform the following Factor implementation into C#, maintaining the same output and logic.
USING: combinators combinators.smart kernel math math.statistics prettyprint sequences sorting ; IN: rosetta-code.five-number <PRIVATE : bisect ( seq -- lower upper ) dup length even? [ halves ] [ dup midpoint@ 1 + [ head ] [ tail* ] 2bi ] if ; : (fivenum) ( seq -- summary ) natural-sort { [ infimum ] [ bisect drop median ] [ median ] [ bisect nip median ] [ supremum ] } cleave>array ; PRIVATE> ERROR: fivenum-empty data ; ERROR: fivenum-nan data ; : fivenum ( seq -- summary ) { { [ dup empty? ] [ fivenum-empty ] } { [ dup [ fp-nan? ] any? ] [ fivenum-nan ] } [ (fivenum) ] } cond ; : fivenum-demo ( -- ) { 15 6 42 41 7 36 49 40 39 47 43 } { 36 40 7 39 41 15 } { 0.14082834 0.09748790 1.73131507 0.87636009 -1.95059594 0.73438555 -0.03035726 1.46675970 -0.74621349 -0.72588772 0.63905160 0.61501527 -0.98983780 -1.00447874 -0.62759469 0.66206163 1.04312009 -0.10305385 0.75775634 0.32566578 } [ fivenum . ] tri@ ; MAIN: fivenum-demo
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Fivenum { public static class Helper { public static string AsString<T>(this ICollection<T> c, string format = "{0}") { StringBuilder sb = new StringBuilder("["); int count = 0; foreach (var t in c) { if (count++ > 0) { sb.Append(", "); } sb.AppendFormat(format, t); } return sb.Append("]").ToString(); } } class Program { static double Median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new ArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] Fivenum(double[] x) { foreach (var d in x) { if (Double.IsNaN(d)) { throw new ArgumentException("Unable to deal with arrays containing NaN"); } } double[] result = new double[5]; Array.Sort(x); result[0] = x.First(); result[2] = Median(x, 0, x.Length - 1); result[4] = x.Last(); int m = x.Length / 2; int lowerEnd = (x.Length % 2 == 1) ? m : m - 1; result[1] = Median(x, 0, lowerEnd); result[3] = Median(x, m, x.Length - 1); return result; } static void Main(string[] args) { double[][] x1 = new double[][]{ new double[]{ 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, new double[]{ 36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, new double[]{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }, }; foreach(var x in x1) { var result = Fivenum(x); Console.WriteLine(result.AsString("{0:F8}")); } } } }
Please provide an equivalent version of this Factor code in C#.
USING: combinators combinators.smart kernel math math.statistics prettyprint sequences sorting ; IN: rosetta-code.five-number <PRIVATE : bisect ( seq -- lower upper ) dup length even? [ halves ] [ dup midpoint@ 1 + [ head ] [ tail* ] 2bi ] if ; : (fivenum) ( seq -- summary ) natural-sort { [ infimum ] [ bisect drop median ] [ median ] [ bisect nip median ] [ supremum ] } cleave>array ; PRIVATE> ERROR: fivenum-empty data ; ERROR: fivenum-nan data ; : fivenum ( seq -- summary ) { { [ dup empty? ] [ fivenum-empty ] } { [ dup [ fp-nan? ] any? ] [ fivenum-nan ] } [ (fivenum) ] } cond ; : fivenum-demo ( -- ) { 15 6 42 41 7 36 49 40 39 47 43 } { 36 40 7 39 41 15 } { 0.14082834 0.09748790 1.73131507 0.87636009 -1.95059594 0.73438555 -0.03035726 1.46675970 -0.74621349 -0.72588772 0.63905160 0.61501527 -0.98983780 -1.00447874 -0.62759469 0.66206163 1.04312009 -0.10305385 0.75775634 0.32566578 } [ fivenum . ] tri@ ; MAIN: fivenum-demo
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Fivenum { public static class Helper { public static string AsString<T>(this ICollection<T> c, string format = "{0}") { StringBuilder sb = new StringBuilder("["); int count = 0; foreach (var t in c) { if (count++ > 0) { sb.Append(", "); } sb.AppendFormat(format, t); } return sb.Append("]").ToString(); } } class Program { static double Median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new ArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] Fivenum(double[] x) { foreach (var d in x) { if (Double.IsNaN(d)) { throw new ArgumentException("Unable to deal with arrays containing NaN"); } } double[] result = new double[5]; Array.Sort(x); result[0] = x.First(); result[2] = Median(x, 0, x.Length - 1); result[4] = x.Last(); int m = x.Length / 2; int lowerEnd = (x.Length % 2 == 1) ? m : m - 1; result[1] = Median(x, 0, lowerEnd); result[3] = Median(x, m, x.Length - 1); return result; } static void Main(string[] args) { double[][] x1 = new double[][]{ new double[]{ 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, new double[]{ 36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, new double[]{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }, }; foreach(var x in x1) { var result = Fivenum(x); Console.WriteLine(result.AsString("{0:F8}")); } } } }
Port the provided Factor code into C++ while preserving the original functionality.
USING: combinators combinators.smart kernel math math.statistics prettyprint sequences sorting ; IN: rosetta-code.five-number <PRIVATE : bisect ( seq -- lower upper ) dup length even? [ halves ] [ dup midpoint@ 1 + [ head ] [ tail* ] 2bi ] if ; : (fivenum) ( seq -- summary ) natural-sort { [ infimum ] [ bisect drop median ] [ median ] [ bisect nip median ] [ supremum ] } cleave>array ; PRIVATE> ERROR: fivenum-empty data ; ERROR: fivenum-nan data ; : fivenum ( seq -- summary ) { { [ dup empty? ] [ fivenum-empty ] } { [ dup [ fp-nan? ] any? ] [ fivenum-nan ] } [ (fivenum) ] } cond ; : fivenum-demo ( -- ) { 15 6 42 41 7 36 49 40 39 47 43 } { 36 40 7 39 41 15 } { 0.14082834 0.09748790 1.73131507 0.87636009 -1.95059594 0.73438555 -0.03035726 1.46675970 -0.74621349 -0.72588772 0.63905160 0.61501527 -0.98983780 -1.00447874 -0.62759469 0.66206163 1.04312009 -0.10305385 0.75775634 0.32566578 } [ fivenum . ] tri@ ; MAIN: fivenum-demo
#include <algorithm> #include <iostream> #include <ostream> #include <vector> template<std::size_t> struct int_ {}; template <class Tuple, size_t Pos> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<Pos>) { out << std::get< std::tuple_size<Tuple>::value - Pos >(t) << ", "; return print_tuple(out, t, int_<Pos - 1>()); } template <class Tuple> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<1>) { return out << std::get<std::tuple_size<Tuple>::value - 1>(t); } template <class... Args> std::ostream& operator<<(std::ostream& out, const std::tuple<Args...>& t) { out << '('; print_tuple(out, t, int_<sizeof...(Args)>()); return out << ')'; } template <class RI> double median(RI beg, RI end) { if (beg == end) throw std::runtime_error("Range cannot be empty"); auto len = end - beg; auto m = len / 2; if (len % 2 == 1) { return *(beg + m); } return (beg[m - 1] + beg[m]) / 2.0; } template <class C> auto fivenum(C& c) { std::sort(c.begin(), c.end()); auto cbeg = c.cbegin(); auto cend = c.cend(); auto len = cend - cbeg; auto m = len / 2; auto lower = (len % 2 == 1) ? m : m - 1; double r2 = median(cbeg, cbeg + lower + 1); double r3 = median(cbeg, cend); double r4 = median(cbeg + lower + 1, cend); return std::make_tuple(*cbeg, r2, r3, r4, *(cend - 1)); } int main() { using namespace std; vector<vector<double>> cs = { { 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0 }, { 36.0, 40.0, 7.0, 39.0, 41.0, 15.0 }, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (auto & c : cs) { cout << fivenum(c) << endl; } return 0; }