task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Deceptive_numbers
Deceptive numbers
Repunits are numbers that consist entirely of repetitions of the digit one (unity). The notation Rn symbolizes the repunit made up of n ones. Every prime p larger than 5, evenly divides the repunit Rp-1. E.G. The repunit R6 is evenly divisible by 7. 111111 / 7 = 15873 The repunit R42 is evenly divisible by 43. 111111111111111111111111111111111111111111 / 43 = 2583979328165374677002583979328165374677 And so on. There are composite numbers that also have this same property. They are often referred to as deceptive non-primes or deceptive numbers. The repunit R90 is evenly divisible by the composite number 91 (=7*13). 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 / 91 = 1221001221001221001221001221001221001221001221001221001221001221001221001221001221001221 Task Find and show at least the first 10 deceptive numbers; composite numbers n that evenly divide the repunit Rn-1 See also Numbers Aplenty - Deceptive numbers OEIS:A000864 - Deceptive nonprimes: composite numbers k that divide the repunit R_{k-1}
#Pascal
Pascal
program DeceptiveNumbers; {$IfDef FPC} {$Optimization ON,ALL} {$ENDIF} {$IfDef Windows} {$APPTYPE CONSOLE} {$ENDIF} uses sysutils; const LIMIT = 100000;//1E6 at home takes over (5 min) now 1m10s RepInitLen = 13; //Uint64 19 decimal digits -> max 6 digits divisor DecimalDigits = 10*1000*1000*1000*1000;//1E13 RepLimit = (DecimalDigits-1)DIV 9;//RepInitLen '1'   type tmyUint64 = array[0..Limit DIV RepInitLen+1] of Uint64; var {$Align 32} K: tmyUint64; {$Align 32} MaxKIdx : Int32;   procedure OutK(const K:tmyUint64); var i : Uint32; begin For i := MaxKidx downto 0 do begin write(k[i]:13); end; writeln; end;   function isPrime(n: UInt64):boolean; var p: Uint64; begin if n in [2,3,5,7,11,13,17,19,23,29] then EXIT(true);   if Not ODD(n) OR ( n MOD 3 = 0) then EXIT(false); p := 5; repeat if (n mod p=0)or(n mod(p+2)=0) then EXIT(false); p +=6; until p*p>n; Exit(true); end;   procedure ExtendRep(var K:tmyUint64;n:NativeUint); var q : Uint64; i : Int32; begin n -= MaxKidx*RepInitLen; i := MaxKidx; while RepInitLen<=n do begin K[i] := RepLimit; inc(i); dec(n,RepInitLen); end; if n = 0 then Exit; MaxKidx := i; q := 1; while n<RepInitLen do begin q *= 10; inc(n); end; K[i] := RepLimit DIV q; end;   function GetModK(const K:tmyUint64;n:Uint64):NativeUint; var r,q : Uint64; i : Uint32; Begin r := 0; For i := MaxKidx downto 0 do begin q := K[i]+r*DecimalDigits; r := q MOD n; end; Exit(r) end;   const NextNotMulOF35 : array[0..7] of byte = (6,4,2,4,2,4,6,2); var i,cnt,idx35 : UInt64; BEGIN fillchar(K,SizeOF(K),#0); MaxKIdx:= 0; cnt := 0; i := 1; idx35 := 0; repeat inc(i,NextNotMulOF35[idx35]); IF i > LIMIT then BREAK; idx35 := (idx35+1) AND 7; if isprime(i) then continue; ExtendRep(k,i-1); IF GetModK(K,i)=0 then Begin inc(cnt); write(i:6,','); if cnt Mod 10 = 0 then writeln; end; until false; {$IfDef Windows} readln; {$ENDIF} END.  
http://rosettacode.org/wiki/Deceptive_numbers
Deceptive numbers
Repunits are numbers that consist entirely of repetitions of the digit one (unity). The notation Rn symbolizes the repunit made up of n ones. Every prime p larger than 5, evenly divides the repunit Rp-1. E.G. The repunit R6 is evenly divisible by 7. 111111 / 7 = 15873 The repunit R42 is evenly divisible by 43. 111111111111111111111111111111111111111111 / 43 = 2583979328165374677002583979328165374677 And so on. There are composite numbers that also have this same property. They are often referred to as deceptive non-primes or deceptive numbers. The repunit R90 is evenly divisible by the composite number 91 (=7*13). 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 / 91 = 1221001221001221001221001221001221001221001221001221001221001221001221001221001221001221 Task Find and show at least the first 10 deceptive numbers; composite numbers n that evenly divide the repunit Rn-1 See also Numbers Aplenty - Deceptive numbers OEIS:A000864 - Deceptive nonprimes: composite numbers k that divide the repunit R_{k-1}
#Perl
Perl
use strict; use warnings; use Math::AnyNum qw(imod is_prime);   my($x,@D) = 2; while ($x++) { push @D, $x if 1 == $x%2 and !is_prime $x and 0 == imod(1x($x-1),$x); last if 25 == @D } print "@D\n";
http://rosettacode.org/wiki/Deceptive_numbers
Deceptive numbers
Repunits are numbers that consist entirely of repetitions of the digit one (unity). The notation Rn symbolizes the repunit made up of n ones. Every prime p larger than 5, evenly divides the repunit Rp-1. E.G. The repunit R6 is evenly divisible by 7. 111111 / 7 = 15873 The repunit R42 is evenly divisible by 43. 111111111111111111111111111111111111111111 / 43 = 2583979328165374677002583979328165374677 And so on. There are composite numbers that also have this same property. They are often referred to as deceptive non-primes or deceptive numbers. The repunit R90 is evenly divisible by the composite number 91 (=7*13). 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 / 91 = 1221001221001221001221001221001221001221001221001221001221001221001221001221001221001221 Task Find and show at least the first 10 deceptive numbers; composite numbers n that evenly divide the repunit Rn-1 See also Numbers Aplenty - Deceptive numbers OEIS:A000864 - Deceptive nonprimes: composite numbers k that divide the repunit R_{k-1}
#Phix
Phix
with javascript_semantics constant limit = 70 atom t0 = time() include mpfr.e mpz repunit = mpz_init(0) integer n = 1, count = 0 printf(1,"The first %d deceptive numbers are:\n",limit) while count<limit do -- No repunit is ever divisible by 2 or 5 since it ends in 1. -- If n is 3*k, sum(digits(repunit))=3*k-1, not divisible by 3. -- Hence only check odd and hop any multiples of 3 or 5. n += 2 mpz_mul_si(repunit,repunit,100) mpz_add_si(repunit,repunit,11) if gcd(n,3*5)=1 and not is_prime(n) and mpz_divisible_ui_p(repunit,n) then count += 1 printf(1," %7d%n",{n,remainder(count,10)=0}) end if end while printf(1,"%s\n",elapsed(time()-t0))
http://rosettacode.org/wiki/Deceptive_numbers
Deceptive numbers
Repunits are numbers that consist entirely of repetitions of the digit one (unity). The notation Rn symbolizes the repunit made up of n ones. Every prime p larger than 5, evenly divides the repunit Rp-1. E.G. The repunit R6 is evenly divisible by 7. 111111 / 7 = 15873 The repunit R42 is evenly divisible by 43. 111111111111111111111111111111111111111111 / 43 = 2583979328165374677002583979328165374677 And so on. There are composite numbers that also have this same property. They are often referred to as deceptive non-primes or deceptive numbers. The repunit R90 is evenly divisible by the composite number 91 (=7*13). 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 / 91 = 1221001221001221001221001221001221001221001221001221001221001221001221001221001221001221 Task Find and show at least the first 10 deceptive numbers; composite numbers n that evenly divide the repunit Rn-1 See also Numbers Aplenty - Deceptive numbers OEIS:A000864 - Deceptive nonprimes: composite numbers k that divide the repunit R_{k-1}
#Raku
Raku
my \R = [\+] 1, 10, 100 … *; put (2..∞).grep( {$_ % 2 && $_ % 3 && $_ % 5 && !.is-prime} ).grep( { R[$_-2] %% $_ } )[^25];
http://rosettacode.org/wiki/Deceptive_numbers
Deceptive numbers
Repunits are numbers that consist entirely of repetitions of the digit one (unity). The notation Rn symbolizes the repunit made up of n ones. Every prime p larger than 5, evenly divides the repunit Rp-1. E.G. The repunit R6 is evenly divisible by 7. 111111 / 7 = 15873 The repunit R42 is evenly divisible by 43. 111111111111111111111111111111111111111111 / 43 = 2583979328165374677002583979328165374677 And so on. There are composite numbers that also have this same property. They are often referred to as deceptive non-primes or deceptive numbers. The repunit R90 is evenly divisible by the composite number 91 (=7*13). 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 / 91 = 1221001221001221001221001221001221001221001221001221001221001221001221001221001221001221 Task Find and show at least the first 10 deceptive numbers; composite numbers n that evenly divide the repunit Rn-1 See also Numbers Aplenty - Deceptive numbers OEIS:A000864 - Deceptive nonprimes: composite numbers k that divide the repunit R_{k-1}
#Rust
Rust
// [dependencies] // primal = "0.3" // rug = "1.15.0"   fn main() { println!("First 100 deceptive numbers:"); use rug::Integer; let mut repunit = Integer::from(11); let mut n: u32 = 3; let mut count = 0; while count != 100 { if n % 3 != 0 && n % 5 != 0 && !primal::is_prime(n as u64) && repunit.is_divisible_u(n) { print!("{:6}", n); count += 1; if count % 10 == 0 { println!(); } else { print!(" "); } } n += 2; repunit *= 100; repunit += 11; } }
http://rosettacode.org/wiki/Deceptive_numbers
Deceptive numbers
Repunits are numbers that consist entirely of repetitions of the digit one (unity). The notation Rn symbolizes the repunit made up of n ones. Every prime p larger than 5, evenly divides the repunit Rp-1. E.G. The repunit R6 is evenly divisible by 7. 111111 / 7 = 15873 The repunit R42 is evenly divisible by 43. 111111111111111111111111111111111111111111 / 43 = 2583979328165374677002583979328165374677 And so on. There are composite numbers that also have this same property. They are often referred to as deceptive non-primes or deceptive numbers. The repunit R90 is evenly divisible by the composite number 91 (=7*13). 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 / 91 = 1221001221001221001221001221001221001221001221001221001221001221001221001221001221001221 Task Find and show at least the first 10 deceptive numbers; composite numbers n that evenly divide the repunit Rn-1 See also Numbers Aplenty - Deceptive numbers OEIS:A000864 - Deceptive nonprimes: composite numbers k that divide the repunit R_{k-1}
#Sidef
Sidef
say 100.by {|n| n.is_composite && (divmod(powmod(10, n-1, n)-1, 9, n) == 0) }.join(' ')
http://rosettacode.org/wiki/Deceptive_numbers
Deceptive numbers
Repunits are numbers that consist entirely of repetitions of the digit one (unity). The notation Rn symbolizes the repunit made up of n ones. Every prime p larger than 5, evenly divides the repunit Rp-1. E.G. The repunit R6 is evenly divisible by 7. 111111 / 7 = 15873 The repunit R42 is evenly divisible by 43. 111111111111111111111111111111111111111111 / 43 = 2583979328165374677002583979328165374677 And so on. There are composite numbers that also have this same property. They are often referred to as deceptive non-primes or deceptive numbers. The repunit R90 is evenly divisible by the composite number 91 (=7*13). 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 / 91 = 1221001221001221001221001221001221001221001221001221001221001221001221001221001221001221 Task Find and show at least the first 10 deceptive numbers; composite numbers n that evenly divide the repunit Rn-1 See also Numbers Aplenty - Deceptive numbers OEIS:A000864 - Deceptive nonprimes: composite numbers k that divide the repunit R_{k-1}
#Vlang
Vlang
import math.big   fn is_prime(n int) bool { if n < 2 { return false } else if n%2 == 0 { return n == 2 } else if n%3 == 0 { return n == 3 } else { mut d := 5 for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } }   fn main() { mut count := 0 limit := 25 mut n := i64(17) mut repunit := big.integer_from_i64(1111111111111111) mut t := big.integer_from_int(0) zero := big.integer_from_int(0) eleven := big.integer_from_int(11) hundred := big.integer_from_int(100) mut deceptive := []i64{} for count < limit { if !is_prime(int(n)) && n%3 != 0 && n%5 != 0 { bn := big.integer_from_i64(n) t = repunit % bn if t == zero { deceptive << n count++ } } n += 2 repunit = repunit * hundred repunit = repunit + eleven } println("The first $limit deceptive numbers are:") println(deceptive) }  
http://rosettacode.org/wiki/Deceptive_numbers
Deceptive numbers
Repunits are numbers that consist entirely of repetitions of the digit one (unity). The notation Rn symbolizes the repunit made up of n ones. Every prime p larger than 5, evenly divides the repunit Rp-1. E.G. The repunit R6 is evenly divisible by 7. 111111 / 7 = 15873 The repunit R42 is evenly divisible by 43. 111111111111111111111111111111111111111111 / 43 = 2583979328165374677002583979328165374677 And so on. There are composite numbers that also have this same property. They are often referred to as deceptive non-primes or deceptive numbers. The repunit R90 is evenly divisible by the composite number 91 (=7*13). 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 / 91 = 1221001221001221001221001221001221001221001221001221001221001221001221001221001221001221 Task Find and show at least the first 10 deceptive numbers; composite numbers n that evenly divide the repunit Rn-1 See also Numbers Aplenty - Deceptive numbers OEIS:A000864 - Deceptive nonprimes: composite numbers k that divide the repunit R_{k-1}
#Wren
Wren
/* deceptive_numbers.wren */   import "./gmp" for Mpz import "./math" for Int   var count = 0 var limit = 25 var n = 17 var repunit = Mpz.from(1111111111111111) var deceptive = [] while (count < limit) { if (!Int.isPrime(n) && n % 3 != 0 && n % 5 != 0) { if (repunit.isDivisibleUi(n)) { deceptive.add(n) count = count + 1 } } n = n + 2 repunit.mul(100).add(11) } System.print("The first %(limit) deceptive numbers are:") System.print(deceptive)
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#6502_Assembly
6502 Assembly
LDA $00  ;read the byte at memory address $00 STA $20  ;store it at memory address $20
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Aime
Aime
list L1, L2;   # Lists are heterogeneous: l_append(L1, 3); l_append(L1, "deep");   # and may contain self references. # A self references in the last position: l_link(L1, -1, L1);   # List may also contain mutual references. # Create a new list in the last position: l_n_list(L1, -1); # Add a reference to the top level list to the nested list: l_link(l_q_list(L1, -1), -1, L1);   # There are no limitations to the deep copy method: l_copy(L2, L1);   # Modify the string in the original list, # via the self reference in the 3rd position l_r_text(l_q_list(L1, 2), 1, "copy");   # Show the string in the two lists: o_text(l_query(L2, 1)); o_text(l_query(L1, 1)); o_byte('\n');   # And again, via the included self references: o_text(l_query(l_query(L2, 2), 1)); o_text(l_query(l_query(L1, 2), 1)); o_byte('\n');
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Arturo
Arturo
x: #[ name: "John" surname: "Doe" age: 34 hobbies: [ "Cycling", "History", "Programming", "Languages", "Psychology", "Buddhism" ] sayHello: function [][ print "Hello there!" ] ]   print ["Name of first person:" x\name]   y: new x y\name: "Jane"   print ["Name of first person:" x\name] print ["Name of second person:" y\name]
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#AutoHotkey
AutoHotkey
DeepCopy(Array, Objs=0) { If !Objs Objs := Object() Obj := Array.Clone() ; produces a shallow copy in that any sub-objects are not cloned Objs[&Array] := Obj ; Save this new array - & returns the address of Array in memory For Key, Val in Obj If (IsObject(Val)) ; If it is a subarray Obj[Key] := Objs[&Val] ; If we already know of a reference to this array  ? Objs[&Val] ; Then point it to the new array (to prevent infinite recursion on self-references  : DeepCopy(Val,Objs) ; Otherwise, clone this sub-array Return Obj }
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#AWK
AWK
BEGIN { for (elem in original) copied[elem] = original[elem] }
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Babel
Babel
babel> [1 2 3] dup dup 0 7 0 1 move sd ! ---TOS--- [val 0x7 0x2 0x3 ] [val 0x7 0x2 0x3 ] ---BOS---
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#C
C
  #include<stdio.h>   typedef struct{ int a; }layer1;   typedef struct{ layer1 l1; float b,c; }layer2;   typedef struct{ layer2 l2; layer1 l1; int d,e; }layer3;   void showCake(layer3 cake){ printf("\ncake.d = %d",cake.d); printf("\ncake.e = %d",cake.e); printf("\ncake.l1.a = %d",cake.l1.a); printf("\ncake.l2.b = %f",cake.l2.b); printf("\ncake.l2.l1.a = %d",cake.l2.l1.a); }   int main() { layer3 cake1,cake2;   cake1.d = 1; cake1.e = 2; cake1.l1.a = 3; cake1.l2.b = 4; cake1.l2.l1.a = 5;   printf("Cake 1 is : "); showCake(cake1);   cake2 = cake1;   cake2.l2.b += cake2.l2.l1.a;   printf("\nCake 2 is : "); showCake(cake2);   return 0; }  
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#C.23
C#
using System;   namespace prog { class MainClass { class MyClass : ICloneable { public MyClass() { f = new int[3]{2,3,5}; c = '1'; }   public object Clone() { MyClass cpy = (MyClass) this.MemberwiseClone(); cpy.f = (int[]) this.f.Clone(); return cpy; }   public char c; public int[] f; }   public static void Main( string[] args ) { MyClass c1 = new MyClass(); MyClass c2 = (MyClass) c1.Clone(); } } }
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#C.2B.2B
C++
  #include <array> #include <iostream> #include <list> #include <map> #include <vector>   int main() { // make a nested structure to copy - a map of arrays containing vectors of strings auto myNumbers = std::vector<std::string>{"one", "two", "three", "four"}; auto myColors = std::vector<std::string>{"red", "green", "blue"}; auto myArray = std::array<std::vector<std::string>, 2>{myNumbers, myColors}; auto myMap = std::map<int, decltype(myArray)> {{3, myArray}, {7, myArray}};   // make a deep copy of the map auto mapCopy = myMap;   // modify the copy mapCopy[3][0][1] = "2"; mapCopy[7][1][2] = "purple";   std::cout << "the original values:\n"; std::cout << myMap[3][0][1] << "\n"; std::cout << myMap[7][1][2] << "\n\n";   std::cout << "the modified copy:\n"; std::cout << mapCopy[3][0][1] << "\n"; std::cout << mapCopy[7][1][2] << "\n"; }
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Common_Lisp
Common Lisp
$ clisp -q [1]> (setf *print-circle* t) T [2]> (let ((a (cons 1 nil))) (setf (cdr a) a)) ;; create circular list #1=(1 . #1#) [3]> (read-from-string "#1=(1 . #1#)") ;; read it from a string #1=(1 . #1#) ;; a similar circular list is returned
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#D.C3.A9j.C3.A0_Vu
Déjà Vu
local :(copy-action) {}   (copy-action)!list obj cache: local :new [] set-to cache obj new for i range 0 -- len obj: push-to new (deepcopy) @obj! i cache return new   (copy-action)!dict obj cache: local :new {} set-to cache obj new for key in keys obj: set-to new (deepcopy) @key cache (deepcopy) @obj! @key cache return new   labda obj cache: set-to cache @obj dup copy @obj set-default (copy-action)   (deepcopy) obj cache: if has cache obj: return @cache! @obj (copy-action)! type @obj @obj cache   deepcopy obj: (deepcopy) obj {}   #example usage: #a reasonably complicated object: set :A { :foo [ "bar" ] [] [ & 1 2 & 3 4 ] } set :B deepcopy A   !. A !. B   push-to get-from B :foo "HODOR"   !. A !. B   #it works with cycles: set :C push-through dup [] set :D deepcopy C   !. C !. D   push-to C 7   !. C !. D
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Delphi
Delphi
  program DeepCopyApp;   {$APPTYPE CONSOLE}   uses System.TypInfo;   type TTypeA = record value1: integer; value2: char; value3: string[10]; value4: Boolean; function DeepCopy: TTypeA; end;   { TTypeA }   function TTypeA.DeepCopy: TTypeA; begin CopyRecord(@result, @self, TypeInfo(TTypeA)); end;   var a, b: TTypeA;   begin a.value1 := 10; a.value2 := 'A'; a.value3 := 'OK'; a.value4 := True;   b := a.DeepCopy; a.value1 := 20; a.value2 := 'B'; a.value3 := 'NOK'; a.value4 := False;   Writeln('Value of "a":'); Writeln(a.value1); Writeln(a.value2); Writeln(a.value3); Writeln(a.value4);   Writeln(#10'Value of "b":'); Writeln(b.value1); Writeln(b.value2); Writeln(b.value3); Writeln(b.value4); readln; end.
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#E
E
def deSubgraphKit := <elib:serial.deSubgraphKit> def deepcopy(x) { return deSubgraphKit.recognize(x, deSubgraphKit.makeBuilder()) }
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Erlang
Erlang
1> A = <<"abcdefghijklmnopqrstuvwxyz">>. <<"abcdefghijklmnopqrstuvwxyz">> 2> B = <<A/binary, A/binary, A/binary, A/binary>>. <<"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz">> 3> <<_:10/binary, C:80/binary, _/binary>> = B. <<"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz">> 4> C. <<"klmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl">> 5> byte_size(C). 80 6> binary:referenced_byte_size(C). 104 7> C2 = binary:copy(C). <<"klmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl">> 8> C2 == C. true 9> binary:referenced_byte_size(C2). 80
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Factor
Factor
USING: accessors arrays io kernel named-tuples prettyprint sequences sequences.deep ;   ! Define a simple class TUPLE: foo bar baz ;   ! Allow instances of foo to be modified like an array INSTANCE: foo named-tuple   ! Create a foo object composed of mutable objects V{ 1 2 3 } V{ 4 5 6 } [ clone ] bi@ foo boa   ! create a copy of the reference to the object dup   ! create a deep copy from this copy >array [ clone ] deep-map T{ foo } like   ! print them both "Before modification:" print [ [ . ] bi@ ] 2keep nl   ! modify the deep copy [ -1 suffix! ] change-bar   ! print them both again "After modification:" print [ . ] bi@
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#FreeBASIC
FreeBASIC
  Type DeepCopy value1 As Integer value2 As String * 1 value3 As String value4 As Boolean value5 As Double End Type Dim As DeepCopy a, b   a.value1 = 10 a.value2 = "A" a.value3 = "OK" a.value4 = True a.value5 = 1.985766472453666   b = a a.value1 = 20 a.value2 = "B" a.value3 = "NOK" a.value4 = False a.value5 = 3.148556644245367   Print !"Valor de \"a\":" Print a.value1 Print a.value2 Print a.value3 Print a.value4 Print a.value5   Print !"\nValor \"b\":" With b Print .value1 Print .value2 Print .value3 Print .value4 Print .value5 End With Sleep  
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Go
Go
package main   import "fmt"   // a complex data structure type cds struct { i int // no special handling needed for deep copy s string // no special handling b []byte // copied easily with append function m map[int]bool // deep copy requires looping }   // a method func (c cds) deepcopy() *cds { // copy what you can in one line r := &cds{c.i, c.s, append([]byte{}, c.b...), make(map[int]bool)} // populate map with a loop for k, v := range c.m { r.m[k] = v } return r }   // demo func main() { // create and populate a structure c1 := &cds{1, "one", []byte("unit"), map[int]bool{1: true}} fmt.Println(c1) // show it c2 := c1.deepcopy() // copy it fmt.Println(c2) // show copy c1.i = 0 // change original c1.s = "nil" copy(c1.b, "zero") c1.m[1] = false fmt.Println(c1) // show changes fmt.Println(c2) // show copy unaffected }
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Icon_and_Unicon
Icon and Unicon
procedure deepcopy(A, cache) #: return a deepcopy of A local k   /cache := table() # used to handle multireferenced objects if \cache[A] then return cache[A]   case type(A) of { "table"|"list": { cache[A] := copy(A) every cache[A][k := key(A)] := deepcopy(A[k], cache) } "set": { cache[A] := set() every insert(cache[A], deepcopy(!A, cache)) } default: { # records and objects (encoded as records) cache[A] := copy(A) if match("record ",image(A)) then { every cache[A][k := key(A)] := deepcopy(A[k], cache) } } } return .cache[A] end
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#J
J
a=:b=: 2 2 2 2 2 NB. two copies of the same array b=: 3 (2)} b NB. modify one of the arrays b 2 2 3 2 2 a 2 2 2 2 2
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Java
Java
  import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable;   public class DeepCopy {   public static void main(String[] args) { Person p1 = new Person("Clark", "Kent", new Address("1 World Center", "Metropolis", "NY", "010101")); Person p2 = p1;   System.out.printf("Demonstrate shallow copy. Both are the same object.%n"); System.out.printf("Person p1 = %s%n", p1); System.out.printf("Person p2 = %s%n", p2); System.out.printf("Set city on person 2. City on both objects is changed.%n"); p2.getAddress().setCity("New York"); System.out.printf("Person p1 = %s%n", p1); System.out.printf("Person p2 = %s%n", p2);   p1 = new Person("Clark", "Kent", new Address("1 World Center", "Metropolis", "NY", "010101")); p2 = new Person(p1); System.out.printf("%nDemonstrate copy constructor. Object p2 is a deep copy of p1.%n"); System.out.printf("Person p1 = %s%n", p1); System.out.printf("Person p2 = %s%n", p2); System.out.printf("Set city on person 2. City on objects is different.%n"); p2.getAddress().setCity("New York"); System.out.printf("Person p1 = %s%n", p1); System.out.printf("Person p2 = %s%n", p2);   p2 = (Person) deepCopy(p1); System.out.printf("%nDemonstrate serialization. Object p2 is a deep copy of p1.%n"); System.out.printf("Person p1 = %s%n", p1); System.out.printf("Person p2 = %s%n", p2); System.out.printf("Set city on person 2. City on objects is different.%n"); p2.getAddress().setCity("New York"); System.out.printf("Person p1 = %s%n", p1); System.out.printf("Person p2 = %s%n", p2);   p2 = (Person) p1.clone(); System.out.printf("%nDemonstrate cloning. Object p2 is a deep copy of p1.%n"); System.out.printf("Person p1 = %s%n", p1); System.out.printf("Person p2 = %s%n", p2); System.out.printf("Set city on person 2. City on objects is different.%n"); p2.getAddress().setCity("New York"); System.out.printf("Person p1 = %s%n", p1); System.out.printf("Person p2 = %s%n", p2); }   /** * Makes a deep copy of any Java object that is passed. */ private static Object deepCopy(Object object) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutputStream outputStrm = new ObjectOutputStream(outputStream); outputStrm.writeObject(object); ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); ObjectInputStream objInputStream = new ObjectInputStream(inputStream); return objInputStream.readObject(); } catch (Exception e) { e.printStackTrace(); return null; } }   public static class Address implements Serializable, Cloneable {   private static final long serialVersionUID = -7073778041809445593L;   private String street; private String city; private String state; private String postalCode; public String getStreet() { return street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public String getPostalCode() { return postalCode; }   @Override public String toString() { return "[street=" + street + ", city=" + city + ", state=" + state + ", code=" + postalCode + "]"; }   public Address(String s, String c, String st, String p) { street = s; city = c; state = st; postalCode = p; }   // Copy constructor public Address(Address add) { street = add.street; city = add.city; state = add.state; postalCode = add.postalCode; }   // Support Cloneable @Override public Object clone() { return new Address(this); }   }   public static class Person implements Serializable, Cloneable { private static final long serialVersionUID = -521810583786595050L; private String firstName; private String lastName; private Address address; public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public Address getAddress() { return address; }   @Override public String toString() { return "[first name=" + firstName + ", last name=" + lastName + ", address=" + address + "]"; }   public Person(String fn, String ln, Address add) { firstName = fn; lastName = ln; address = add; }   // Copy Constructor public Person(Person person) { firstName = person.firstName; lastName = person.lastName; address = new Address(person.address); // Invoke copy constructor of mutable sub-objects. }   // Support Cloneable @Override public Object clone() { return new Person(this); } } }  
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\infty }^{\infty }F(m)H(n-m)} for all integers n {\displaystyle {\mathit {n}}} . Assume F ( n ) {\displaystyle F(n)} can be non-zero only for 0 {\displaystyle 0} ≤ n {\displaystyle {\mathit {n}}} ≤ | F | {\displaystyle |{\mathit {F}}|} , where | F | {\displaystyle |{\mathit {F}}|} is the "length" of F {\displaystyle {\mathit {F}}} , and similarly for G {\displaystyle {\mathit {G}}} and H {\displaystyle {\mathit {H}}} , so that the functions can be modeled as finite sequences by identifying f 0 , f 1 , f 2 , … {\displaystyle f_{0},f_{1},f_{2},\dots } with F ( 0 ) , F ( 1 ) , F ( 2 ) , … {\displaystyle F(0),F(1),F(2),\dots } , etc. Then for example, values of | F | = 6 {\displaystyle |{\mathit {F}}|=6} and | H | = 5 {\displaystyle |{\mathit {H}}|=5} would determine the following value of g {\displaystyle {\mathit {g}}} by definition. g 0 = f 0 h 0 g 1 = f 1 h 0 + f 0 h 1 g 2 = f 2 h 0 + f 1 h 1 + f 0 h 2 g 3 = f 3 h 0 + f 2 h 1 + f 1 h 2 + f 0 h 3 g 4 = f 4 h 0 + f 3 h 1 + f 2 h 2 + f 1 h 3 + f 0 h 4 g 5 = f 5 h 0 + f 4 h 1 + f 3 h 2 + f 2 h 3 + f 1 h 4 g 6 = f 5 h 1 + f 4 h 2 + f 3 h 3 + f 2 h 4 g 7 = f 5 h 2 + f 4 h 3 + f 3 h 4 g 8 = f 5 h 3 + f 4 h 4 g 9 = f 5 h 4 {\displaystyle {\begin{array}{lllllllllll}g_{0}&=&f_{0}h_{0}\\g_{1}&=&f_{1}h_{0}&+&f_{0}h_{1}\\g_{2}&=&f_{2}h_{0}&+&f_{1}h_{1}&+&f_{0}h_{2}\\g_{3}&=&f_{3}h_{0}&+&f_{2}h_{1}&+&f_{1}h_{2}&+&f_{0}h_{3}\\g_{4}&=&f_{4}h_{0}&+&f_{3}h_{1}&+&f_{2}h_{2}&+&f_{1}h_{3}&+&f_{0}h_{4}\\g_{5}&=&f_{5}h_{0}&+&f_{4}h_{1}&+&f_{3}h_{2}&+&f_{2}h_{3}&+&f_{1}h_{4}\\g_{6}&=&&&f_{5}h_{1}&+&f_{4}h_{2}&+&f_{3}h_{3}&+&f_{2}h_{4}\\g_{7}&=&&&&&f_{5}h_{2}&+&f_{4}h_{3}&+&f_{3}h_{4}\\g_{8}&=&&&&&&&f_{5}h_{3}&+&f_{4}h_{4}\\g_{9}&=&&&&&&&&&f_{5}h_{4}\end{array}}} We can write this in matrix form as: ( g 0 g 1 g 2 g 3 g 4 g 5 g 6 g 7 g 8 g 9 ) = ( f 0 f 1 f 0 f 2 f 1 f 0 f 3 f 2 f 1 f 0 f 4 f 3 f 2 f 1 f 0 f 5 f 4 f 3 f 2 f 1 f 5 f 4 f 3 f 2 f 5 f 4 f 3 f 5 f 4 f 5 ) ( h 0 h 1 h 2 h 3 h 4 ) {\displaystyle \left({\begin{array}{l}g_{0}\\g_{1}\\g_{2}\\g_{3}\\g_{4}\\g_{5}\\g_{6}\\g_{7}\\g_{8}\\g_{9}\\\end{array}}\right)=\left({\begin{array}{lllll}f_{0}\\f_{1}&f_{0}\\f_{2}&f_{1}&f_{0}\\f_{3}&f_{2}&f_{1}&f_{0}\\f_{4}&f_{3}&f_{2}&f_{1}&f_{0}\\f_{5}&f_{4}&f_{3}&f_{2}&f_{1}\\&f_{5}&f_{4}&f_{3}&f_{2}\\&&f_{5}&f_{4}&f_{3}\\&&&f_{5}&f_{4}\\&&&&f_{5}\end{array}}\right)\;\left({\begin{array}{l}h_{0}\\h_{1}\\h_{2}\\h_{3}\\h_{4}\\\end{array}}\right)} or g = A h {\displaystyle g=A\;h} For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by constructing and solving such a system of equations represented by the above matrix A {\displaystyle A} for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . The function should work for G {\displaystyle {\mathit {G}}} of arbitrary length (i.e., not hard coded or constant) and F {\displaystyle {\mathit {F}}} of any length up to that of G {\displaystyle {\mathit {G}}} . Note that | H | {\displaystyle |{\mathit {H}}|} will be given by | G | − | F | + 1 {\displaystyle |{\mathit {G}}|-|{\mathit {F}}|+1} . There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task. Test your solution on the following data. Be sure to verify both that deconv ( g , f ) = h {\displaystyle (g,f)=h} and deconv ( g , h ) = f {\displaystyle (g,h)=f} and display the results in a human readable form. h = [-8,-9,-3,-1,-6,7] f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
#11l
11l
F deconv(g, f) V result = [0]*(g.len - f.len + 1) L(&e) result V n = L.index e = g[n] V lower_bound = I n >= f.len {n - f.len + 1} E 0 L(i) lower_bound .< n e -= result[i] * f[n - i] e /= f[0] R result   V h = [-8,-9,-3,-1,-6,7] V f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] V g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7] print(deconv(g, f)) print(deconv(g, h))
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#JavaScript
JavaScript
  var deepcopy = function(o){ return JSON.parse(JSON.stringify(src)); };   var src = {foo:0,bar:[0,1]}; print(JSON.stringify(src)); var dst = deepcopy(src); print(JSON.stringify(src));  
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#jq
jq
[1,2] | . as $x | . as $y
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\infty }^{\infty }F(m)H(n-m)} for all integers n {\displaystyle {\mathit {n}}} . Assume F ( n ) {\displaystyle F(n)} can be non-zero only for 0 {\displaystyle 0} ≤ n {\displaystyle {\mathit {n}}} ≤ | F | {\displaystyle |{\mathit {F}}|} , where | F | {\displaystyle |{\mathit {F}}|} is the "length" of F {\displaystyle {\mathit {F}}} , and similarly for G {\displaystyle {\mathit {G}}} and H {\displaystyle {\mathit {H}}} , so that the functions can be modeled as finite sequences by identifying f 0 , f 1 , f 2 , … {\displaystyle f_{0},f_{1},f_{2},\dots } with F ( 0 ) , F ( 1 ) , F ( 2 ) , … {\displaystyle F(0),F(1),F(2),\dots } , etc. Then for example, values of | F | = 6 {\displaystyle |{\mathit {F}}|=6} and | H | = 5 {\displaystyle |{\mathit {H}}|=5} would determine the following value of g {\displaystyle {\mathit {g}}} by definition. g 0 = f 0 h 0 g 1 = f 1 h 0 + f 0 h 1 g 2 = f 2 h 0 + f 1 h 1 + f 0 h 2 g 3 = f 3 h 0 + f 2 h 1 + f 1 h 2 + f 0 h 3 g 4 = f 4 h 0 + f 3 h 1 + f 2 h 2 + f 1 h 3 + f 0 h 4 g 5 = f 5 h 0 + f 4 h 1 + f 3 h 2 + f 2 h 3 + f 1 h 4 g 6 = f 5 h 1 + f 4 h 2 + f 3 h 3 + f 2 h 4 g 7 = f 5 h 2 + f 4 h 3 + f 3 h 4 g 8 = f 5 h 3 + f 4 h 4 g 9 = f 5 h 4 {\displaystyle {\begin{array}{lllllllllll}g_{0}&=&f_{0}h_{0}\\g_{1}&=&f_{1}h_{0}&+&f_{0}h_{1}\\g_{2}&=&f_{2}h_{0}&+&f_{1}h_{1}&+&f_{0}h_{2}\\g_{3}&=&f_{3}h_{0}&+&f_{2}h_{1}&+&f_{1}h_{2}&+&f_{0}h_{3}\\g_{4}&=&f_{4}h_{0}&+&f_{3}h_{1}&+&f_{2}h_{2}&+&f_{1}h_{3}&+&f_{0}h_{4}\\g_{5}&=&f_{5}h_{0}&+&f_{4}h_{1}&+&f_{3}h_{2}&+&f_{2}h_{3}&+&f_{1}h_{4}\\g_{6}&=&&&f_{5}h_{1}&+&f_{4}h_{2}&+&f_{3}h_{3}&+&f_{2}h_{4}\\g_{7}&=&&&&&f_{5}h_{2}&+&f_{4}h_{3}&+&f_{3}h_{4}\\g_{8}&=&&&&&&&f_{5}h_{3}&+&f_{4}h_{4}\\g_{9}&=&&&&&&&&&f_{5}h_{4}\end{array}}} We can write this in matrix form as: ( g 0 g 1 g 2 g 3 g 4 g 5 g 6 g 7 g 8 g 9 ) = ( f 0 f 1 f 0 f 2 f 1 f 0 f 3 f 2 f 1 f 0 f 4 f 3 f 2 f 1 f 0 f 5 f 4 f 3 f 2 f 1 f 5 f 4 f 3 f 2 f 5 f 4 f 3 f 5 f 4 f 5 ) ( h 0 h 1 h 2 h 3 h 4 ) {\displaystyle \left({\begin{array}{l}g_{0}\\g_{1}\\g_{2}\\g_{3}\\g_{4}\\g_{5}\\g_{6}\\g_{7}\\g_{8}\\g_{9}\\\end{array}}\right)=\left({\begin{array}{lllll}f_{0}\\f_{1}&f_{0}\\f_{2}&f_{1}&f_{0}\\f_{3}&f_{2}&f_{1}&f_{0}\\f_{4}&f_{3}&f_{2}&f_{1}&f_{0}\\f_{5}&f_{4}&f_{3}&f_{2}&f_{1}\\&f_{5}&f_{4}&f_{3}&f_{2}\\&&f_{5}&f_{4}&f_{3}\\&&&f_{5}&f_{4}\\&&&&f_{5}\end{array}}\right)\;\left({\begin{array}{l}h_{0}\\h_{1}\\h_{2}\\h_{3}\\h_{4}\\\end{array}}\right)} or g = A h {\displaystyle g=A\;h} For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by constructing and solving such a system of equations represented by the above matrix A {\displaystyle A} for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . The function should work for G {\displaystyle {\mathit {G}}} of arbitrary length (i.e., not hard coded or constant) and F {\displaystyle {\mathit {F}}} of any length up to that of G {\displaystyle {\mathit {G}}} . Note that | H | {\displaystyle |{\mathit {H}}|} will be given by | G | − | F | + 1 {\displaystyle |{\mathit {G}}|-|{\mathit {F}}|+1} . There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task. Test your solution on the following data. Be sure to verify both that deconv ( g , f ) = h {\displaystyle (g,f)=h} and deconv ( g , h ) = f {\displaystyle (g,h)=f} and display the results in a human readable form. h = [-8,-9,-3,-1,-6,7] f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Main is package real_io is new Float_IO (Long_Float); use real_io;   type Vector is array (Natural range <>) of Long_Float;   function deconv (g, f : Vector) return Vector is len : Positive := Integer'Max ((g'Length - f'length), (f'length - g'length)); h  : Vector (0 .. len); Lower : Natural := 0; begin for n in h'range loop h (n) := g (n); if n >= f'length then Lower := n - f'length + 1; end if; for i in Lower .. n - 1 loop h (n) := h (n) - (h (i) * f (n - i)); end loop; h (n) := h (n) / f (0); end loop; return h; end deconv;   procedure print (v : Vector) is begin Put ("("); for I in v'range loop Put (Item => v (I), Fore => 1, Aft => 1, Exp => 0); if I < v'Last then Put (" "); else Put_Line (")"); end if; end loop; end print;   h : Vector := (-8.0, -9.0, -3.0, -1.0, -6.0, 7.0); f : Vector := (-3.0, -6.0, -1.0, 8.0, -6.0, 3.0, -1.0, -9.0, -9.0, 3.0, -2.0, 5.0, 2.0, -2.0, -7.0, -1.0); g : Vector := (24.0, 75.0, 71.0, -34.0, 3.0, 22.0, -45.0, 23.0, 245.0, 25.0, 52.0, 25.0, -67.0, -96.0, 96.0, 31.0, 55.0, 36.0, 29.0, -43.0, -7.0); begin print (h); print (deconv (g, f)); print (f); print (deconv (g, h)); end Main;  
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Julia
Julia
# v0.6.0   cp = deepcopy(obj)
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Kotlin
Kotlin
// Version 1.2.31   import java.io.Serializable import java.io.ByteArrayOutputStream import java.io.ByteArrayInputStream import java.io.ObjectOutputStream import java.io.ObjectInputStream   fun <T : Serializable> deepCopy(obj: T?): T? { if (obj == null) return null val baos = ByteArrayOutputStream() val oos = ObjectOutputStream(baos) oos.writeObject(obj) oos.close() val bais = ByteArrayInputStream(baos.toByteArray()) val ois = ObjectInputStream(bais) @Suppress("unchecked_cast") return ois.readObject() as T }   class Person( val name: String, var age: Int, val sex: Char, var income: Double, var partner: Person? ) : Serializable   fun printDetails(p1: Person, p2: Person?, p3: Person, p4: Person?) { with (p3) { println("Name  : $name") println("Age  : $age") println("Sex  : $sex") println("Income  : $income") if (p4 == null) { println("Partner : None") } else { println("Partner :-") with (p4) { println(" Name  : $name") println(" Age  : $age") println(" Sex  : $sex") println(" Income : $income") } } println("\nSame person as original '$name' == ${p1 === p3}") if (p4 != null) { println("Same person as original '${p2!!.name}' == ${p2 === p4}") } } println() }   fun main(args: Array<String>) { var p1 = Person("John", 35, 'M', 50000.0, null) val p2 = Person("Jane", 32, 'F', 25000.0, p1) p1.partner = p2 var p3 = deepCopy(p1) val p4 = p3!!.partner printDetails(p1, p2, p3, p4)   println("..or, say, after 2 years have elapsed:-\n") with (p1) { age = 37 income = 55000.0 partner = null } p3 = deepCopy(p1) printDetails(p1, null, p3!!, null) }
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\infty }^{\infty }F(m)H(n-m)} for all integers n {\displaystyle {\mathit {n}}} . Assume F ( n ) {\displaystyle F(n)} can be non-zero only for 0 {\displaystyle 0} ≤ n {\displaystyle {\mathit {n}}} ≤ | F | {\displaystyle |{\mathit {F}}|} , where | F | {\displaystyle |{\mathit {F}}|} is the "length" of F {\displaystyle {\mathit {F}}} , and similarly for G {\displaystyle {\mathit {G}}} and H {\displaystyle {\mathit {H}}} , so that the functions can be modeled as finite sequences by identifying f 0 , f 1 , f 2 , … {\displaystyle f_{0},f_{1},f_{2},\dots } with F ( 0 ) , F ( 1 ) , F ( 2 ) , … {\displaystyle F(0),F(1),F(2),\dots } , etc. Then for example, values of | F | = 6 {\displaystyle |{\mathit {F}}|=6} and | H | = 5 {\displaystyle |{\mathit {H}}|=5} would determine the following value of g {\displaystyle {\mathit {g}}} by definition. g 0 = f 0 h 0 g 1 = f 1 h 0 + f 0 h 1 g 2 = f 2 h 0 + f 1 h 1 + f 0 h 2 g 3 = f 3 h 0 + f 2 h 1 + f 1 h 2 + f 0 h 3 g 4 = f 4 h 0 + f 3 h 1 + f 2 h 2 + f 1 h 3 + f 0 h 4 g 5 = f 5 h 0 + f 4 h 1 + f 3 h 2 + f 2 h 3 + f 1 h 4 g 6 = f 5 h 1 + f 4 h 2 + f 3 h 3 + f 2 h 4 g 7 = f 5 h 2 + f 4 h 3 + f 3 h 4 g 8 = f 5 h 3 + f 4 h 4 g 9 = f 5 h 4 {\displaystyle {\begin{array}{lllllllllll}g_{0}&=&f_{0}h_{0}\\g_{1}&=&f_{1}h_{0}&+&f_{0}h_{1}\\g_{2}&=&f_{2}h_{0}&+&f_{1}h_{1}&+&f_{0}h_{2}\\g_{3}&=&f_{3}h_{0}&+&f_{2}h_{1}&+&f_{1}h_{2}&+&f_{0}h_{3}\\g_{4}&=&f_{4}h_{0}&+&f_{3}h_{1}&+&f_{2}h_{2}&+&f_{1}h_{3}&+&f_{0}h_{4}\\g_{5}&=&f_{5}h_{0}&+&f_{4}h_{1}&+&f_{3}h_{2}&+&f_{2}h_{3}&+&f_{1}h_{4}\\g_{6}&=&&&f_{5}h_{1}&+&f_{4}h_{2}&+&f_{3}h_{3}&+&f_{2}h_{4}\\g_{7}&=&&&&&f_{5}h_{2}&+&f_{4}h_{3}&+&f_{3}h_{4}\\g_{8}&=&&&&&&&f_{5}h_{3}&+&f_{4}h_{4}\\g_{9}&=&&&&&&&&&f_{5}h_{4}\end{array}}} We can write this in matrix form as: ( g 0 g 1 g 2 g 3 g 4 g 5 g 6 g 7 g 8 g 9 ) = ( f 0 f 1 f 0 f 2 f 1 f 0 f 3 f 2 f 1 f 0 f 4 f 3 f 2 f 1 f 0 f 5 f 4 f 3 f 2 f 1 f 5 f 4 f 3 f 2 f 5 f 4 f 3 f 5 f 4 f 5 ) ( h 0 h 1 h 2 h 3 h 4 ) {\displaystyle \left({\begin{array}{l}g_{0}\\g_{1}\\g_{2}\\g_{3}\\g_{4}\\g_{5}\\g_{6}\\g_{7}\\g_{8}\\g_{9}\\\end{array}}\right)=\left({\begin{array}{lllll}f_{0}\\f_{1}&f_{0}\\f_{2}&f_{1}&f_{0}\\f_{3}&f_{2}&f_{1}&f_{0}\\f_{4}&f_{3}&f_{2}&f_{1}&f_{0}\\f_{5}&f_{4}&f_{3}&f_{2}&f_{1}\\&f_{5}&f_{4}&f_{3}&f_{2}\\&&f_{5}&f_{4}&f_{3}\\&&&f_{5}&f_{4}\\&&&&f_{5}\end{array}}\right)\;\left({\begin{array}{l}h_{0}\\h_{1}\\h_{2}\\h_{3}\\h_{4}\\\end{array}}\right)} or g = A h {\displaystyle g=A\;h} For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by constructing and solving such a system of equations represented by the above matrix A {\displaystyle A} for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . The function should work for G {\displaystyle {\mathit {G}}} of arbitrary length (i.e., not hard coded or constant) and F {\displaystyle {\mathit {F}}} of any length up to that of G {\displaystyle {\mathit {G}}} . Note that | H | {\displaystyle |{\mathit {H}}|} will be given by | G | − | F | + 1 {\displaystyle |{\mathit {G}}|-|{\mathit {F}}|+1} . There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task. Test your solution on the following data. Be sure to verify both that deconv ( g , f ) = h {\displaystyle (g,f)=h} and deconv ( g , h ) = f {\displaystyle (g,h)=f} and display the results in a human readable form. h = [-8,-9,-3,-1,-6,7] f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
#BBC_BASIC
BBC BASIC
*FLOAT 64 DIM h(5), f(15), g(20) h() = -8,-9,-3,-1,-6,7 f() = -3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1 g() = 24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7   PROCdeconv(g(), f(), x()) PRINT "deconv(g,f) = " FNprintarray(x()) x() -= h() : IF SUM(x()) <> 0 PRINT "Error!"   PROCdeconv(g(), h(), y()) PRINT "deconv(g,h) = " FNprintarray(y()) y() -= f() : IF SUM(y()) <> 0 PRINT "Error!" END   DEF PROCdeconv(g(), f(), RETURN h()) LOCAL f%, g%, i%, l%, n% f% = DIM(f(),1) + 1 g% = DIM(g(),1) + 1 DIM h(g% - f%) FOR n% = 0 TO g% - f% h(n%) = g(n%) IF n% < f% THEN l% = 0 ELSE l% = n% - f% + 1 IF n% THEN FOR i% = l% TO n% - 1 h(n%) -= h(i%) * f(n% - i%) NEXT ENDIF h(n%) /= f(0) NEXT n% ENDPROC   DEF FNprintarray(a()) LOCAL i%, a$ FOR i% = 0 TO DIM(a(),1) a$ += STR$(a(i%)) + ", " NEXT = LEFT$(LEFT$(a$))
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\infty }^{\infty }F(m)H(n-m)} for all integers n {\displaystyle {\mathit {n}}} . Assume F ( n ) {\displaystyle F(n)} can be non-zero only for 0 {\displaystyle 0} ≤ n {\displaystyle {\mathit {n}}} ≤ | F | {\displaystyle |{\mathit {F}}|} , where | F | {\displaystyle |{\mathit {F}}|} is the "length" of F {\displaystyle {\mathit {F}}} , and similarly for G {\displaystyle {\mathit {G}}} and H {\displaystyle {\mathit {H}}} , so that the functions can be modeled as finite sequences by identifying f 0 , f 1 , f 2 , … {\displaystyle f_{0},f_{1},f_{2},\dots } with F ( 0 ) , F ( 1 ) , F ( 2 ) , … {\displaystyle F(0),F(1),F(2),\dots } , etc. Then for example, values of | F | = 6 {\displaystyle |{\mathit {F}}|=6} and | H | = 5 {\displaystyle |{\mathit {H}}|=5} would determine the following value of g {\displaystyle {\mathit {g}}} by definition. g 0 = f 0 h 0 g 1 = f 1 h 0 + f 0 h 1 g 2 = f 2 h 0 + f 1 h 1 + f 0 h 2 g 3 = f 3 h 0 + f 2 h 1 + f 1 h 2 + f 0 h 3 g 4 = f 4 h 0 + f 3 h 1 + f 2 h 2 + f 1 h 3 + f 0 h 4 g 5 = f 5 h 0 + f 4 h 1 + f 3 h 2 + f 2 h 3 + f 1 h 4 g 6 = f 5 h 1 + f 4 h 2 + f 3 h 3 + f 2 h 4 g 7 = f 5 h 2 + f 4 h 3 + f 3 h 4 g 8 = f 5 h 3 + f 4 h 4 g 9 = f 5 h 4 {\displaystyle {\begin{array}{lllllllllll}g_{0}&=&f_{0}h_{0}\\g_{1}&=&f_{1}h_{0}&+&f_{0}h_{1}\\g_{2}&=&f_{2}h_{0}&+&f_{1}h_{1}&+&f_{0}h_{2}\\g_{3}&=&f_{3}h_{0}&+&f_{2}h_{1}&+&f_{1}h_{2}&+&f_{0}h_{3}\\g_{4}&=&f_{4}h_{0}&+&f_{3}h_{1}&+&f_{2}h_{2}&+&f_{1}h_{3}&+&f_{0}h_{4}\\g_{5}&=&f_{5}h_{0}&+&f_{4}h_{1}&+&f_{3}h_{2}&+&f_{2}h_{3}&+&f_{1}h_{4}\\g_{6}&=&&&f_{5}h_{1}&+&f_{4}h_{2}&+&f_{3}h_{3}&+&f_{2}h_{4}\\g_{7}&=&&&&&f_{5}h_{2}&+&f_{4}h_{3}&+&f_{3}h_{4}\\g_{8}&=&&&&&&&f_{5}h_{3}&+&f_{4}h_{4}\\g_{9}&=&&&&&&&&&f_{5}h_{4}\end{array}}} We can write this in matrix form as: ( g 0 g 1 g 2 g 3 g 4 g 5 g 6 g 7 g 8 g 9 ) = ( f 0 f 1 f 0 f 2 f 1 f 0 f 3 f 2 f 1 f 0 f 4 f 3 f 2 f 1 f 0 f 5 f 4 f 3 f 2 f 1 f 5 f 4 f 3 f 2 f 5 f 4 f 3 f 5 f 4 f 5 ) ( h 0 h 1 h 2 h 3 h 4 ) {\displaystyle \left({\begin{array}{l}g_{0}\\g_{1}\\g_{2}\\g_{3}\\g_{4}\\g_{5}\\g_{6}\\g_{7}\\g_{8}\\g_{9}\\\end{array}}\right)=\left({\begin{array}{lllll}f_{0}\\f_{1}&f_{0}\\f_{2}&f_{1}&f_{0}\\f_{3}&f_{2}&f_{1}&f_{0}\\f_{4}&f_{3}&f_{2}&f_{1}&f_{0}\\f_{5}&f_{4}&f_{3}&f_{2}&f_{1}\\&f_{5}&f_{4}&f_{3}&f_{2}\\&&f_{5}&f_{4}&f_{3}\\&&&f_{5}&f_{4}\\&&&&f_{5}\end{array}}\right)\;\left({\begin{array}{l}h_{0}\\h_{1}\\h_{2}\\h_{3}\\h_{4}\\\end{array}}\right)} or g = A h {\displaystyle g=A\;h} For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by constructing and solving such a system of equations represented by the above matrix A {\displaystyle A} for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . The function should work for G {\displaystyle {\mathit {G}}} of arbitrary length (i.e., not hard coded or constant) and F {\displaystyle {\mathit {F}}} of any length up to that of G {\displaystyle {\mathit {G}}} . Note that | H | {\displaystyle |{\mathit {H}}|} will be given by | G | − | F | + 1 {\displaystyle |{\mathit {G}}|-|{\mathit {F}}|+1} . There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task. Test your solution on the following data. Be sure to verify both that deconv ( g , f ) = h {\displaystyle (g,f)=h} and deconv ( g , h ) = f {\displaystyle (g,h)=f} and display the results in a human readable form. h = [-8,-9,-3,-1,-6,7] f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
#C
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <complex.h>   double PI; typedef double complex cplx;   void _fft(cplx buf[], cplx out[], int n, int step) { if (step < n) { _fft(out, buf, n, step * 2); _fft(out + step, buf + step, n, step * 2);   for (int i = 0; i < n; i += 2 * step) { cplx t = cexp(-I * PI * i / n) * out[i + step]; buf[i / 2] = out[i] + t; buf[(i + n)/2] = out[i] - t; } } }   void fft(cplx buf[], int n) { cplx out[n]; for (int i = 0; i < n; i++) out[i] = buf[i]; _fft(buf, out, n, 1); }   /* pad array length to power of two */ cplx *pad_two(double g[], int len, int *ns) { int n = 1; if (*ns) n = *ns; else while (n < len) n *= 2;   cplx *buf = calloc(sizeof(cplx), n); for (int i = 0; i < len; i++) buf[i] = g[i]; *ns = n; return buf; }   void deconv(double g[], int lg, double f[], int lf, double out[]) { int ns = 0; cplx *g2 = pad_two(g, lg, &ns); cplx *f2 = pad_two(f, lf, &ns);   fft(g2, ns); fft(f2, ns);   cplx h[ns]; for (int i = 0; i < ns; i++) h[i] = g2[i] / f2[i]; fft(h, ns);   for (int i = 0; i >= lf - lg; i--) out[-i] = h[(i + ns) % ns]/32; free(g2); free(f2); }   int main() { PI = atan2(1,1) * 4; double g[] = {24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7}; double f[] = { -3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1 }; double h[] = { -8,-9,-3,-1,-6,7 };   int lg = sizeof(g)/sizeof(double); int lf = sizeof(f)/sizeof(double); int lh = sizeof(h)/sizeof(double);   double h2[lh]; double f2[lf];   printf("f[] data is : "); for (int i = 0; i < lf; i++) printf(" %g", f[i]); printf("\n");   printf("deconv(g, h): "); deconv(g, lg, h, lh, f2); for (int i = 0; i < lf; i++) printf(" %g", f2[i]); printf("\n");   printf("h[] data is : "); for (int i = 0; i < lh; i++) printf(" %g", h[i]); printf("\n");   printf("deconv(g, f): "); deconv(g, lg, f, lf, h2); for (int i = 0; i < lh; i++) printf(" %g", h2[i]); printf("\n"); }
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Lasso
Lasso
local(copy) = #myobject->ascopydeep
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Lingo
Lingo
-- Supports lists, property lists, images, script instances and scalar values (integer, float, string, symbol). on deepcopy (var, cycleCheck) case ilk(var) of #list, #propList, #image: return var.duplicate() #instance: if string(var) starts "<Xtra " then return var -- deep copy makes no sense for Xtra instances if voidP(cycleCheck) then cycleCheck = [:] if not voidP(cycleCheck[var]) then return cycleCheck[var] copy = var.script.rawNew() cycleCheck[var] = copy repeat with i = 1 to var.count copy.setProp(var.getPropAt(i), deepcopy(var[i], cycleCheck)) end repeat return copy otherwise: return var end case end
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\infty }^{\infty }F(m)H(n-m)} for all integers n {\displaystyle {\mathit {n}}} . Assume F ( n ) {\displaystyle F(n)} can be non-zero only for 0 {\displaystyle 0} ≤ n {\displaystyle {\mathit {n}}} ≤ | F | {\displaystyle |{\mathit {F}}|} , where | F | {\displaystyle |{\mathit {F}}|} is the "length" of F {\displaystyle {\mathit {F}}} , and similarly for G {\displaystyle {\mathit {G}}} and H {\displaystyle {\mathit {H}}} , so that the functions can be modeled as finite sequences by identifying f 0 , f 1 , f 2 , … {\displaystyle f_{0},f_{1},f_{2},\dots } with F ( 0 ) , F ( 1 ) , F ( 2 ) , … {\displaystyle F(0),F(1),F(2),\dots } , etc. Then for example, values of | F | = 6 {\displaystyle |{\mathit {F}}|=6} and | H | = 5 {\displaystyle |{\mathit {H}}|=5} would determine the following value of g {\displaystyle {\mathit {g}}} by definition. g 0 = f 0 h 0 g 1 = f 1 h 0 + f 0 h 1 g 2 = f 2 h 0 + f 1 h 1 + f 0 h 2 g 3 = f 3 h 0 + f 2 h 1 + f 1 h 2 + f 0 h 3 g 4 = f 4 h 0 + f 3 h 1 + f 2 h 2 + f 1 h 3 + f 0 h 4 g 5 = f 5 h 0 + f 4 h 1 + f 3 h 2 + f 2 h 3 + f 1 h 4 g 6 = f 5 h 1 + f 4 h 2 + f 3 h 3 + f 2 h 4 g 7 = f 5 h 2 + f 4 h 3 + f 3 h 4 g 8 = f 5 h 3 + f 4 h 4 g 9 = f 5 h 4 {\displaystyle {\begin{array}{lllllllllll}g_{0}&=&f_{0}h_{0}\\g_{1}&=&f_{1}h_{0}&+&f_{0}h_{1}\\g_{2}&=&f_{2}h_{0}&+&f_{1}h_{1}&+&f_{0}h_{2}\\g_{3}&=&f_{3}h_{0}&+&f_{2}h_{1}&+&f_{1}h_{2}&+&f_{0}h_{3}\\g_{4}&=&f_{4}h_{0}&+&f_{3}h_{1}&+&f_{2}h_{2}&+&f_{1}h_{3}&+&f_{0}h_{4}\\g_{5}&=&f_{5}h_{0}&+&f_{4}h_{1}&+&f_{3}h_{2}&+&f_{2}h_{3}&+&f_{1}h_{4}\\g_{6}&=&&&f_{5}h_{1}&+&f_{4}h_{2}&+&f_{3}h_{3}&+&f_{2}h_{4}\\g_{7}&=&&&&&f_{5}h_{2}&+&f_{4}h_{3}&+&f_{3}h_{4}\\g_{8}&=&&&&&&&f_{5}h_{3}&+&f_{4}h_{4}\\g_{9}&=&&&&&&&&&f_{5}h_{4}\end{array}}} We can write this in matrix form as: ( g 0 g 1 g 2 g 3 g 4 g 5 g 6 g 7 g 8 g 9 ) = ( f 0 f 1 f 0 f 2 f 1 f 0 f 3 f 2 f 1 f 0 f 4 f 3 f 2 f 1 f 0 f 5 f 4 f 3 f 2 f 1 f 5 f 4 f 3 f 2 f 5 f 4 f 3 f 5 f 4 f 5 ) ( h 0 h 1 h 2 h 3 h 4 ) {\displaystyle \left({\begin{array}{l}g_{0}\\g_{1}\\g_{2}\\g_{3}\\g_{4}\\g_{5}\\g_{6}\\g_{7}\\g_{8}\\g_{9}\\\end{array}}\right)=\left({\begin{array}{lllll}f_{0}\\f_{1}&f_{0}\\f_{2}&f_{1}&f_{0}\\f_{3}&f_{2}&f_{1}&f_{0}\\f_{4}&f_{3}&f_{2}&f_{1}&f_{0}\\f_{5}&f_{4}&f_{3}&f_{2}&f_{1}\\&f_{5}&f_{4}&f_{3}&f_{2}\\&&f_{5}&f_{4}&f_{3}\\&&&f_{5}&f_{4}\\&&&&f_{5}\end{array}}\right)\;\left({\begin{array}{l}h_{0}\\h_{1}\\h_{2}\\h_{3}\\h_{4}\\\end{array}}\right)} or g = A h {\displaystyle g=A\;h} For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by constructing and solving such a system of equations represented by the above matrix A {\displaystyle A} for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . The function should work for G {\displaystyle {\mathit {G}}} of arbitrary length (i.e., not hard coded or constant) and F {\displaystyle {\mathit {F}}} of any length up to that of G {\displaystyle {\mathit {G}}} . Note that | H | {\displaystyle |{\mathit {H}}|} will be given by | G | − | F | + 1 {\displaystyle |{\mathit {G}}|-|{\mathit {F}}|+1} . There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task. Test your solution on the following data. Be sure to verify both that deconv ( g , f ) = h {\displaystyle (g,f)=h} and deconv ( g , h ) = f {\displaystyle (g,h)=f} and display the results in a human readable form. h = [-8,-9,-3,-1,-6,7] f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
#Common_Lisp
Common Lisp
;; Assemble the mxn matrix A from the 2D row vector x. (defun make-conv-matrix (x m n) (let ((lx (cadr (array-dimensions x))) (A (make-array `(,m ,n) :initial-element 0)))   (loop for j from 0 to (- n 1) do (loop for i from 0 to (- m 1) do (setf (aref A i j) (cond ((or (< i j) (>= i (+ j lx))) 0) ((and (>= i j) (< i (+ j lx))) (aref x 0 (- i j))))))) A))   ;; Solve the overdetermined system A(f)*h=g by linear least squares. (defun deconv (g f) (let* ((lg (cadr (array-dimensions g))) (lf (cadr (array-dimensions f))) (lh (+ (- lg lf) 1)) (A (make-conv-matrix f lg lh)))   (lsqr A (mtp g))))
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Lua
Lua
function _deepcopy(o, tables)   if type(o) ~= 'table' then return o end   if tables[o] ~= nil then return tables[o] end   local new_o = {} tables[o] = new_o   for k, v in next, o, nil do local new_k = _deepcopy(k, tables) local new_v = _deepcopy(v, tables) new_o[new_k] = new_v end   return new_o end   function deepcopy(o) return _deepcopy(o, {}) end
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
a = {"foo", \[Pi], {<| "deep" -> {# + 1 &, {{"Mathematica"}, {{"is"}, {"a"}}, {{{"cool"}}}, \ {{"programming"}, {"language!"}}}}|>}}; b = a; a[[2]] -= 3; a[[3, 1, 1, 1]] = #^2 &; Print[a]; Print[b];
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\infty }^{\infty }F(m)H(n-m)} for all integers n {\displaystyle {\mathit {n}}} . Assume F ( n ) {\displaystyle F(n)} can be non-zero only for 0 {\displaystyle 0} ≤ n {\displaystyle {\mathit {n}}} ≤ | F | {\displaystyle |{\mathit {F}}|} , where | F | {\displaystyle |{\mathit {F}}|} is the "length" of F {\displaystyle {\mathit {F}}} , and similarly for G {\displaystyle {\mathit {G}}} and H {\displaystyle {\mathit {H}}} , so that the functions can be modeled as finite sequences by identifying f 0 , f 1 , f 2 , … {\displaystyle f_{0},f_{1},f_{2},\dots } with F ( 0 ) , F ( 1 ) , F ( 2 ) , … {\displaystyle F(0),F(1),F(2),\dots } , etc. Then for example, values of | F | = 6 {\displaystyle |{\mathit {F}}|=6} and | H | = 5 {\displaystyle |{\mathit {H}}|=5} would determine the following value of g {\displaystyle {\mathit {g}}} by definition. g 0 = f 0 h 0 g 1 = f 1 h 0 + f 0 h 1 g 2 = f 2 h 0 + f 1 h 1 + f 0 h 2 g 3 = f 3 h 0 + f 2 h 1 + f 1 h 2 + f 0 h 3 g 4 = f 4 h 0 + f 3 h 1 + f 2 h 2 + f 1 h 3 + f 0 h 4 g 5 = f 5 h 0 + f 4 h 1 + f 3 h 2 + f 2 h 3 + f 1 h 4 g 6 = f 5 h 1 + f 4 h 2 + f 3 h 3 + f 2 h 4 g 7 = f 5 h 2 + f 4 h 3 + f 3 h 4 g 8 = f 5 h 3 + f 4 h 4 g 9 = f 5 h 4 {\displaystyle {\begin{array}{lllllllllll}g_{0}&=&f_{0}h_{0}\\g_{1}&=&f_{1}h_{0}&+&f_{0}h_{1}\\g_{2}&=&f_{2}h_{0}&+&f_{1}h_{1}&+&f_{0}h_{2}\\g_{3}&=&f_{3}h_{0}&+&f_{2}h_{1}&+&f_{1}h_{2}&+&f_{0}h_{3}\\g_{4}&=&f_{4}h_{0}&+&f_{3}h_{1}&+&f_{2}h_{2}&+&f_{1}h_{3}&+&f_{0}h_{4}\\g_{5}&=&f_{5}h_{0}&+&f_{4}h_{1}&+&f_{3}h_{2}&+&f_{2}h_{3}&+&f_{1}h_{4}\\g_{6}&=&&&f_{5}h_{1}&+&f_{4}h_{2}&+&f_{3}h_{3}&+&f_{2}h_{4}\\g_{7}&=&&&&&f_{5}h_{2}&+&f_{4}h_{3}&+&f_{3}h_{4}\\g_{8}&=&&&&&&&f_{5}h_{3}&+&f_{4}h_{4}\\g_{9}&=&&&&&&&&&f_{5}h_{4}\end{array}}} We can write this in matrix form as: ( g 0 g 1 g 2 g 3 g 4 g 5 g 6 g 7 g 8 g 9 ) = ( f 0 f 1 f 0 f 2 f 1 f 0 f 3 f 2 f 1 f 0 f 4 f 3 f 2 f 1 f 0 f 5 f 4 f 3 f 2 f 1 f 5 f 4 f 3 f 2 f 5 f 4 f 3 f 5 f 4 f 5 ) ( h 0 h 1 h 2 h 3 h 4 ) {\displaystyle \left({\begin{array}{l}g_{0}\\g_{1}\\g_{2}\\g_{3}\\g_{4}\\g_{5}\\g_{6}\\g_{7}\\g_{8}\\g_{9}\\\end{array}}\right)=\left({\begin{array}{lllll}f_{0}\\f_{1}&f_{0}\\f_{2}&f_{1}&f_{0}\\f_{3}&f_{2}&f_{1}&f_{0}\\f_{4}&f_{3}&f_{2}&f_{1}&f_{0}\\f_{5}&f_{4}&f_{3}&f_{2}&f_{1}\\&f_{5}&f_{4}&f_{3}&f_{2}\\&&f_{5}&f_{4}&f_{3}\\&&&f_{5}&f_{4}\\&&&&f_{5}\end{array}}\right)\;\left({\begin{array}{l}h_{0}\\h_{1}\\h_{2}\\h_{3}\\h_{4}\\\end{array}}\right)} or g = A h {\displaystyle g=A\;h} For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by constructing and solving such a system of equations represented by the above matrix A {\displaystyle A} for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . The function should work for G {\displaystyle {\mathit {G}}} of arbitrary length (i.e., not hard coded or constant) and F {\displaystyle {\mathit {F}}} of any length up to that of G {\displaystyle {\mathit {G}}} . Note that | H | {\displaystyle |{\mathit {H}}|} will be given by | G | − | F | + 1 {\displaystyle |{\mathit {G}}|-|{\mathit {F}}|+1} . There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task. Test your solution on the following data. Be sure to verify both that deconv ( g , f ) = h {\displaystyle (g,f)=h} and deconv ( g , h ) = f {\displaystyle (g,h)=f} and display the results in a human readable form. h = [-8,-9,-3,-1,-6,7] f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
#D
D
T[] deconv(T)(in T[] g, in T[] f) pure nothrow { int flen = f.length; int glen = g.length; auto result = new T[glen - flen + 1]; foreach (int n, ref e; result) { e = g[n]; immutable lowerBound = (n >= flen) ? n - flen + 1 : 0; foreach (i; lowerBound .. n) e -= result[i] * f[n - i]; e /= f[0]; } return result; }   void main() { import std.stdio; immutable h = [-8,-9,-3,-1,-6,7]; immutable f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1]; immutable g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67, -96,96,31,55,36,29,-43,-7]; writeln(deconv(g, f) == h, " ", deconv(g, f)); writeln(deconv(g, h) == f, " ", deconv(g, h)); }
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Nim
Nim
deepCopy(newObj, obj)
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#OCaml
OCaml
let rec copy t = if Obj.is_int t then t else let tag = Obj.tag t in if tag = Obj.double_tag then t else if tag = Obj.closure_tag then t else if tag = Obj.string_tag then Obj.repr (String.copy (Obj.obj t)) else if tag = 0 || tag = Obj.double_array_tag then begin let size = Obj.size t in let r = Obj.new_block tag size in for i = 0 to pred size do Obj.set_field r i (copy (Obj.field t i)) done; r end else failwith "copy" ;;   let copy (v : 'a) : 'a = Obj.obj (copy (Obj.repr v))
http://rosettacode.org/wiki/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#Ada
Ada
type My_Type is range 1..10;
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\infty }^{\infty }F(m)H(n-m)} for all integers n {\displaystyle {\mathit {n}}} . Assume F ( n ) {\displaystyle F(n)} can be non-zero only for 0 {\displaystyle 0} ≤ n {\displaystyle {\mathit {n}}} ≤ | F | {\displaystyle |{\mathit {F}}|} , where | F | {\displaystyle |{\mathit {F}}|} is the "length" of F {\displaystyle {\mathit {F}}} , and similarly for G {\displaystyle {\mathit {G}}} and H {\displaystyle {\mathit {H}}} , so that the functions can be modeled as finite sequences by identifying f 0 , f 1 , f 2 , … {\displaystyle f_{0},f_{1},f_{2},\dots } with F ( 0 ) , F ( 1 ) , F ( 2 ) , … {\displaystyle F(0),F(1),F(2),\dots } , etc. Then for example, values of | F | = 6 {\displaystyle |{\mathit {F}}|=6} and | H | = 5 {\displaystyle |{\mathit {H}}|=5} would determine the following value of g {\displaystyle {\mathit {g}}} by definition. g 0 = f 0 h 0 g 1 = f 1 h 0 + f 0 h 1 g 2 = f 2 h 0 + f 1 h 1 + f 0 h 2 g 3 = f 3 h 0 + f 2 h 1 + f 1 h 2 + f 0 h 3 g 4 = f 4 h 0 + f 3 h 1 + f 2 h 2 + f 1 h 3 + f 0 h 4 g 5 = f 5 h 0 + f 4 h 1 + f 3 h 2 + f 2 h 3 + f 1 h 4 g 6 = f 5 h 1 + f 4 h 2 + f 3 h 3 + f 2 h 4 g 7 = f 5 h 2 + f 4 h 3 + f 3 h 4 g 8 = f 5 h 3 + f 4 h 4 g 9 = f 5 h 4 {\displaystyle {\begin{array}{lllllllllll}g_{0}&=&f_{0}h_{0}\\g_{1}&=&f_{1}h_{0}&+&f_{0}h_{1}\\g_{2}&=&f_{2}h_{0}&+&f_{1}h_{1}&+&f_{0}h_{2}\\g_{3}&=&f_{3}h_{0}&+&f_{2}h_{1}&+&f_{1}h_{2}&+&f_{0}h_{3}\\g_{4}&=&f_{4}h_{0}&+&f_{3}h_{1}&+&f_{2}h_{2}&+&f_{1}h_{3}&+&f_{0}h_{4}\\g_{5}&=&f_{5}h_{0}&+&f_{4}h_{1}&+&f_{3}h_{2}&+&f_{2}h_{3}&+&f_{1}h_{4}\\g_{6}&=&&&f_{5}h_{1}&+&f_{4}h_{2}&+&f_{3}h_{3}&+&f_{2}h_{4}\\g_{7}&=&&&&&f_{5}h_{2}&+&f_{4}h_{3}&+&f_{3}h_{4}\\g_{8}&=&&&&&&&f_{5}h_{3}&+&f_{4}h_{4}\\g_{9}&=&&&&&&&&&f_{5}h_{4}\end{array}}} We can write this in matrix form as: ( g 0 g 1 g 2 g 3 g 4 g 5 g 6 g 7 g 8 g 9 ) = ( f 0 f 1 f 0 f 2 f 1 f 0 f 3 f 2 f 1 f 0 f 4 f 3 f 2 f 1 f 0 f 5 f 4 f 3 f 2 f 1 f 5 f 4 f 3 f 2 f 5 f 4 f 3 f 5 f 4 f 5 ) ( h 0 h 1 h 2 h 3 h 4 ) {\displaystyle \left({\begin{array}{l}g_{0}\\g_{1}\\g_{2}\\g_{3}\\g_{4}\\g_{5}\\g_{6}\\g_{7}\\g_{8}\\g_{9}\\\end{array}}\right)=\left({\begin{array}{lllll}f_{0}\\f_{1}&f_{0}\\f_{2}&f_{1}&f_{0}\\f_{3}&f_{2}&f_{1}&f_{0}\\f_{4}&f_{3}&f_{2}&f_{1}&f_{0}\\f_{5}&f_{4}&f_{3}&f_{2}&f_{1}\\&f_{5}&f_{4}&f_{3}&f_{2}\\&&f_{5}&f_{4}&f_{3}\\&&&f_{5}&f_{4}\\&&&&f_{5}\end{array}}\right)\;\left({\begin{array}{l}h_{0}\\h_{1}\\h_{2}\\h_{3}\\h_{4}\\\end{array}}\right)} or g = A h {\displaystyle g=A\;h} For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by constructing and solving such a system of equations represented by the above matrix A {\displaystyle A} for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . The function should work for G {\displaystyle {\mathit {G}}} of arbitrary length (i.e., not hard coded or constant) and F {\displaystyle {\mathit {F}}} of any length up to that of G {\displaystyle {\mathit {G}}} . Note that | H | {\displaystyle |{\mathit {H}}|} will be given by | G | − | F | + 1 {\displaystyle |{\mathit {G}}|-|{\mathit {F}}|+1} . There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task. Test your solution on the following data. Be sure to verify both that deconv ( g , f ) = h {\displaystyle (g,f)=h} and deconv ( g , h ) = f {\displaystyle (g,h)=f} and display the results in a human readable form. h = [-8,-9,-3,-1,-6,7] f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
#Fortran
Fortran
  ! Build ! Windows: ifort /I "%IFORT_COMPILER11%\mkl\include\ia32" deconv1d.f90 "%IFORT_COMPILER11%\mkl\ia32\lib\*.lib" ! Linux:   program deconv ! Use gelsd from LAPACK95. use mkl95_lapack, only : gelsd   implicit none real(8), allocatable :: g(:), href(:), A(:,:), f(:) real(8), pointer :: h(:), r(:) integer :: N character(len=16) :: cbuff integer :: i intrinsic :: nint   ! Allocate data arrays allocate(g(21),f(16)) g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7] f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1]   ! Calculate deconvolution h => deco(f, g)   ! Check result against reference N = size(h) allocate(href(N)) href = [-8,-9,-3,-1,-6,7] cbuff = ' ' write(cbuff,'(a,i0,a)') '(a,',N,'(i0,a),i0)' if (any(abs(h-href) > 1.0d-4)) then write(*,'(a)') 'deconv(f, g) - FAILED' else write(*,cbuff) 'deconv(f, g) = ',(nint(h(i)),', ',i=1,N-1),nint(h(N)) end if   ! Calculate deconvolution r => deco(h, g)   cbuff = ' ' N = size(r) write(cbuff,'(a,i0,a)') '(a,',N,'(i0,a),i0)' if (any(abs(r-f) > 1.0d-4)) then write(*,'(a)') 'deconv(h, g) - FAILED' else write(*,cbuff) 'deconv(h, g) = ',(nint(r(i)),', ',i=1,N-1),nint(r(N)) end if   contains function deco(p, q) real(8), pointer :: deco(:) real(8), intent(in) :: p(:), q(:)   real(8), allocatable, target :: r(:) real(8), allocatable :: A(:,:) integer :: N   ! Construct derived arrays N = size(q) - size(p) + 1 allocate(A(size(q),N),r(size(q))) A = 0.0d0 do i=1,N A(i:i+size(p)-1,i) = p end do   ! Invoke the LAPACK routine to do the work r = q call gelsd(A, r)   deco => r(1:N) end function deco   end program deconv  
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#OxygenBasic
OxygenBasic
  'DEEP COPY FOR A RECURSIVE TREE STRUCTURE   uses console   class branches ' static int count int level int a,b,c branches*branch1 branches*branch2 ' method constructor(int n) ========================= level=n count++ output count tab level cr if level>0 new branches n1(n-1) new branches n2(n-1) @branch1=@n1 @branch2=@n2 endif ... end method ' method destructor ================= if level>0 del branch1 del branch2 endif ... end method ' method RecurseCopy(int n, branches *dc, *sc) ============================================ dc.level=sc.level dc.a=sc.a dc.b=sc.b dc.c=sc.c if n>0 RecurseCopy n-1, byval @dc.branch1, byval @sc.branch1 RecurseCopy n-1, byval @dc.branch2, byval @sc.branch2 endif end method ' method DeepCopy() as branches* ============================== new branches dc(level) RecurseCopy level,dc,this return @dc end method ' end class   output "count" tab "level" tab "(original)" cr new branches br(3) output "count" tab "level" tab "(copy)" cr branches *bc = br.DeepCopy pause del bc del br  
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#PARI.2FGP
PARI/GP
  #!/usr/bin/perl use strict; use warnings; use Storable; use Data::Dumper;   my $src = { foo => 0, bar => [0, 1] }; $src->{baz} = $src; my $dst = Storable::dclone($src); print Dumper($src); print Dumper($dst);  
http://rosettacode.org/wiki/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#ALGOL_68
ALGOL 68
# assume max int <= ABS - max negative int # INT max bounded = ( LENG max int * max int > long max int | ENTIER sqrt(max int) | max int );   MODE RANGE = STRUCT(INT lwb, upb); MODE BOUNDED = STRUCT(INT value, RANGE range); FORMAT bounded repr = $g"["g(-0)":"g(-0)"]"$;   # Define some useful operators for looping over ranges # OP LWB = (RANGE range)INT: lwb OF range, UPB = (RANGE range)INT: upb OF range, LWB = (BOUNDED bounded)INT: lwb OF range OF bounded, UPB = (BOUNDED bounded)INT: upb OF range OF bounded;   PROC raise exception = ([]STRING args)VOID: ( put(stand error, ("exception: ",args, newline)); stop );   PROC raise not implemented error := ([]STRING args)VOID: raise exception(args); PROC raise bounds error := ([]STRING args)VOID: raise exception(args);   PRIO MIN=9, MAX=9; OP MIN = ([]INT list)INT: ( INT out:= list[LWB list]; FOR index FROM LWB list+1 TO UPB list DO IF list[index]<out THEN out :=list[index] FI OD; out ); OP MAX = ([]INT list)INT: ( INT out:= list[LWB list]; FOR index FROM LWB list+1 TO UPB list DO IF list[index]>out THEN out :=list[index] FI OD; out );   PRIO ASSERTIN = 6; OP ASSERTIN = (INT result, []RANGE range)BOUNDED: ( BOUNDED out = (result, (MAX lwb OF range, MIN upb OF range)); IF value OF out < lwb OF range OF out THEN raise bounds error(("out of bounds", whole(result, int width)," < [",whole(MAX lwb OF range, int width),":]")) ELIF value OF out > upb OF range OF out THEN raise bounds error(("out of bounds", whole(result, int width)," > [:",whole(MIN upb OF range, int width),"]")) FI; out ), ASSERTIN = (LONG INT result, []RANGE range)BOUNDED: ( STRUCT (LONG INT value, RANGE range) out = (result, (MAX lwb OF range, MIN upb OF range)); IF value OF out < lwb OF range OF out THEN raise bounds error(("out of bounds", whole(result, long int width)," < [",whole(MAX lwb OF range, int width),":]")) ELIF value OF out > upb OF range OF out THEN raise bounds error(("out of bounds", whole(result, long int width)," > [:",whole(MIN upb OF range, int width),"]")) FI; (SHORTEN value OF out, range OF out) ), ASSERTIN = (INT result, []BOUNDED bounds)BOUNDED: result ASSERTIN range OF bounds, ASSERTIN = (LONG INT result, []BOUNDED bounds)BOUNDED: result ASSERTIN range OF bounds;   INT half max int = max int OVER 2; INT sqrt max int = ENTIER sqrt (max int);   OP + = (BOUNDED a, b)BOUNDED: IF ABS value OF a < half max int AND ABS value OF b < half max int THEN value OF a + value OF b ASSERTIN []BOUNDED(a,b) ELSE LENG value OF a + value OF b ASSERTIN []BOUNDED(a,b) FI, - = (BOUNDED a, b)BOUNDED: value OF a + -value OF b ASSERTIN []BOUNDED(a,b), * = (BOUNDED a, b)BOUNDED: IF ABS value OF a < sqrt max int AND ABS value OF b < sqrt max int THEN value OF a * value OF b ASSERTIN []BOUNDED(a,b) ELSE LENG value OF a * value OF b ASSERTIN []BOUNDED(a,b) FI, / = (BOUNDED a, b)REAL: value OF a / value OF b, % = (BOUNDED a, b)BOUNDED: value OF a % value OF b ASSERTIN []BOUNDED(a,b), %* = (BOUNDED a, b)BOUNDED: value OF a %* value OF b ASSERTIN []BOUNDED(a,b), ** = (BOUNDED a, INT exponent)BOUNDED: value OF a ** exponent ASSERTIN []BOUNDED(a);   OP OVER = (INT value, RANGE range)BOUNDED: IF ABS lwb OF range > max bounded THEN raise bounds error(("out of bounds, ABS", whole(lwb OF range, int width)," > [:",whole(max bounded, int width),"]")); SKIP ELIF ABS upb OF range > max bounded THEN raise bounds error(("out of bounds, ABS", whole(upb OF range, int width)," > [:",whole(max bounded, int width),"]")); SKIP ELSE value ASSERTIN []RANGE(range) FI;   OP INTINIT = (BOUNDED range)REAL: value OF range;   OP < = (BOUNDED a, b)BOOL: value OF a < value OF b, > = (BOUNDED a, b)BOOL: value OF a > value OF b, <= = (BOUNDED a, b)BOOL: NOT ( value OF a > value OF b ), >= = (BOUNDED a, b)BOOL: NOT ( value OF a < value OF b ), = = (BOUNDED a, b)BOOL: value OF a = value OF b, /= = (BOUNDED a, b)BOOL: NOT (a = b);   # Monadic operators # OP - = (BOUNDED range)BOUNDED: -value OF range ASSERTIN []BOUNDED(range), ABS = (BOUNDED range)BOUNDED: ABS value OF range ASSERTIN []BOUNDED(range);   COMMENT Operators for extended characters set, and increment/decrement: OP +:= = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a := a + b ), +=: = (BOUNDED a, REF BOUNDED b)REF BOUNDED: ( b := a + b ), -:= = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a := a - b ), *:= = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a := a * b ), %:= = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a := a % b ), %*:= = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a := a %* b );   # OP aliases for extended character sets (eg: Unicode, APL, ALCOR and GOST 10859) # OP × = (BOUNDED a, b)BOUNDED: a * b, ÷ = (BOUNDED a, b)INT: a OVER b, ÷× = (BOUNDED a, b)BOUNDED: a MOD b, ÷* = (BOUNDED a, b)BOUNDED: a MOD b, %× = (BOUNDED a, b)BOUNDED: a MOD b, ≤ = (BOUNDED a, b)BOUNDED: a <= b, ≥ = (BOUNDED a, b)BOUNDED: a >= b, ≠ = (BOUNDED a, b)BOOL: a /= b, ↑ = (BOUNDED range, INT exponent)BOUNDED: value OF range ** exponent,   ÷×:= = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a := a MOD b ), %×:= = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a := a MOD b ), ÷*:= = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a := a MOD b );   # BOLD aliases for CPU that only support uppercase for 6-bit bytes - wrist watches # OP OVER = (BOUNDED a, b)INT: a % b, MOD = (BOUNDED a, b)BOUNDED: a %*b, LT = (BOUNDED a, b)BOOL: a < b, GT = (BOUNDED a, b)BOOL: a > b, LE = (BOUNDED a, b)BOOL: a <= b, GE = (BOUNDED a, b)BOOL: a >= b, EQ = (BOUNDED a, b)BOOL: a = b, NE = (BOUNDED a, b)BOOL: a /= b, UP = (BOUNDED range, INT exponent)BOUNDED: range**exponent;   # the required standard assignment operators # OP PLUSAB = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a +:= b ), # PLUS # PLUSTO = (BOUNDED a, REF BOUNDED b)REF BOUNDED: ( a +=: b ), # PRUS # MINUSAB = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a *:= b ), DIVAB = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a /:= b ), OVERAB = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a %:= b ), MODAB = (REF BOUNDED a, BOUNDED b)REF BOUNDED: ( a %*:= b );   END COMMENT Test: RANGE range = RANGE(0, 10000);   # override the default exception # raise bounds error := ([]STRING args)VOID: ( putf(stand error, ($g$, args, $"- exiting to except bounds error"l$)); except bounds error );   BOUNDED a, b := 0 OVER range; FOR step FROM 4 BY 4 TO UPB range DO # something for pythagoras # b := b + step OVER range; a := ENTIER sqrt( 1.5 + 2 * value OF b ) OVER range OF b; printf(($"Sum of "$, bounded repr, a * a, b * b, $" is "$, bounded repr, a * a + b * b, $l$)) OD; except bounds error: SKIP
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\infty }^{\infty }F(m)H(n-m)} for all integers n {\displaystyle {\mathit {n}}} . Assume F ( n ) {\displaystyle F(n)} can be non-zero only for 0 {\displaystyle 0} ≤ n {\displaystyle {\mathit {n}}} ≤ | F | {\displaystyle |{\mathit {F}}|} , where | F | {\displaystyle |{\mathit {F}}|} is the "length" of F {\displaystyle {\mathit {F}}} , and similarly for G {\displaystyle {\mathit {G}}} and H {\displaystyle {\mathit {H}}} , so that the functions can be modeled as finite sequences by identifying f 0 , f 1 , f 2 , … {\displaystyle f_{0},f_{1},f_{2},\dots } with F ( 0 ) , F ( 1 ) , F ( 2 ) , … {\displaystyle F(0),F(1),F(2),\dots } , etc. Then for example, values of | F | = 6 {\displaystyle |{\mathit {F}}|=6} and | H | = 5 {\displaystyle |{\mathit {H}}|=5} would determine the following value of g {\displaystyle {\mathit {g}}} by definition. g 0 = f 0 h 0 g 1 = f 1 h 0 + f 0 h 1 g 2 = f 2 h 0 + f 1 h 1 + f 0 h 2 g 3 = f 3 h 0 + f 2 h 1 + f 1 h 2 + f 0 h 3 g 4 = f 4 h 0 + f 3 h 1 + f 2 h 2 + f 1 h 3 + f 0 h 4 g 5 = f 5 h 0 + f 4 h 1 + f 3 h 2 + f 2 h 3 + f 1 h 4 g 6 = f 5 h 1 + f 4 h 2 + f 3 h 3 + f 2 h 4 g 7 = f 5 h 2 + f 4 h 3 + f 3 h 4 g 8 = f 5 h 3 + f 4 h 4 g 9 = f 5 h 4 {\displaystyle {\begin{array}{lllllllllll}g_{0}&=&f_{0}h_{0}\\g_{1}&=&f_{1}h_{0}&+&f_{0}h_{1}\\g_{2}&=&f_{2}h_{0}&+&f_{1}h_{1}&+&f_{0}h_{2}\\g_{3}&=&f_{3}h_{0}&+&f_{2}h_{1}&+&f_{1}h_{2}&+&f_{0}h_{3}\\g_{4}&=&f_{4}h_{0}&+&f_{3}h_{1}&+&f_{2}h_{2}&+&f_{1}h_{3}&+&f_{0}h_{4}\\g_{5}&=&f_{5}h_{0}&+&f_{4}h_{1}&+&f_{3}h_{2}&+&f_{2}h_{3}&+&f_{1}h_{4}\\g_{6}&=&&&f_{5}h_{1}&+&f_{4}h_{2}&+&f_{3}h_{3}&+&f_{2}h_{4}\\g_{7}&=&&&&&f_{5}h_{2}&+&f_{4}h_{3}&+&f_{3}h_{4}\\g_{8}&=&&&&&&&f_{5}h_{3}&+&f_{4}h_{4}\\g_{9}&=&&&&&&&&&f_{5}h_{4}\end{array}}} We can write this in matrix form as: ( g 0 g 1 g 2 g 3 g 4 g 5 g 6 g 7 g 8 g 9 ) = ( f 0 f 1 f 0 f 2 f 1 f 0 f 3 f 2 f 1 f 0 f 4 f 3 f 2 f 1 f 0 f 5 f 4 f 3 f 2 f 1 f 5 f 4 f 3 f 2 f 5 f 4 f 3 f 5 f 4 f 5 ) ( h 0 h 1 h 2 h 3 h 4 ) {\displaystyle \left({\begin{array}{l}g_{0}\\g_{1}\\g_{2}\\g_{3}\\g_{4}\\g_{5}\\g_{6}\\g_{7}\\g_{8}\\g_{9}\\\end{array}}\right)=\left({\begin{array}{lllll}f_{0}\\f_{1}&f_{0}\\f_{2}&f_{1}&f_{0}\\f_{3}&f_{2}&f_{1}&f_{0}\\f_{4}&f_{3}&f_{2}&f_{1}&f_{0}\\f_{5}&f_{4}&f_{3}&f_{2}&f_{1}\\&f_{5}&f_{4}&f_{3}&f_{2}\\&&f_{5}&f_{4}&f_{3}\\&&&f_{5}&f_{4}\\&&&&f_{5}\end{array}}\right)\;\left({\begin{array}{l}h_{0}\\h_{1}\\h_{2}\\h_{3}\\h_{4}\\\end{array}}\right)} or g = A h {\displaystyle g=A\;h} For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by constructing and solving such a system of equations represented by the above matrix A {\displaystyle A} for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . The function should work for G {\displaystyle {\mathit {G}}} of arbitrary length (i.e., not hard coded or constant) and F {\displaystyle {\mathit {F}}} of any length up to that of G {\displaystyle {\mathit {G}}} . Note that | H | {\displaystyle |{\mathit {H}}|} will be given by | G | − | F | + 1 {\displaystyle |{\mathit {G}}|-|{\mathit {F}}|+1} . There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task. Test your solution on the following data. Be sure to verify both that deconv ( g , f ) = h {\displaystyle (g,f)=h} and deconv ( g , h ) = f {\displaystyle (g,h)=f} and display the results in a human readable form. h = [-8,-9,-3,-1,-6,7] f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
#Go
Go
package main   import "fmt"   func main() { h := []float64{-8, -9, -3, -1, -6, 7} f := []float64{-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1} g := []float64{24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, 96, 31, 55, 36, 29, -43, -7} fmt.Println(h) fmt.Println(deconv(g, f)) fmt.Println(f) fmt.Println(deconv(g, h)) }   func deconv(g, f []float64) []float64 { h := make([]float64, len(g)-len(f)+1) for n := range h { h[n] = g[n] var lower int if n >= len(f) { lower = n - len(f) + 1 } for i := lower; i < n; i++ { h[n] -= h[i] * f[n-i] } h[n] /= f[0] } return h }
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Perl
Perl
  #!/usr/bin/perl use strict; use warnings; use Storable; use Data::Dumper;   my $src = { foo => 0, bar => [0, 1] }; $src->{baz} = $src; my $dst = Storable::dclone($src); print Dumper($src); print Dumper($dst);  
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Phix
Phix
object a, b a = {1,{2,3},"four",{5.6,7,{8.9}}} b = a b[3] = 4 ?a ?b
http://rosettacode.org/wiki/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#ATS
ATS
(*   Here is the type:   *)   typedef rosetta_code_primitive_type = [i : int | 1 <= i; i <= 10] int i   (*   You do not have to insert bounds checking, and the compiler inserts no bounds checking. You simply *cannot* assign an out-of-range value.   (Proviso: unless you do some serious cheating.)   *)   implement main0 (argc, argv) = let var n : rosetta_code_primitive_type in n := 1; n := 10; n := 11 end   (*   An attempt to compile this program *will fail* when it typechecks ‘n := 11’:   $ patscc primitive_type-postiats.dats /path/to/primitive_type-postiats.dats: 282(line=21, offs=3) -- 373(line=27, offs=6): error(3): unsolved constraint: C3NSTRprop(C3TKmain(); S2Eapp(S2Ecst(<=); S2EVar(0->S2Eintinf(11)), S2Eintinf(10))) /path/to/primitive_type-postiats.dats: 282(line=21, offs=3) -- 373(line=27, offs=6): error(3): unsolved constraint for lvar preservation typechecking has failed: there are some unsolved constraints: please inspect the above reported error message(s) for information. exit(ATS): uncaught exception: _2tmp_2ATS_2dPostiats_2src_2pats_error_2esats__FatalErrorExn(1025)   *)
http://rosettacode.org/wiki/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#C.23
C#
using System; using System.Globalization;   struct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable { const int MIN_VALUE = 1; const int MAX_VALUE = 10;   public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE); public static readonly LimitedInt MaxValue = new LimitedInt(MAX_VALUE);   static bool IsValidValue(int value) => value >= MIN_VALUE && value <= MAX_VALUE;   readonly int _value; public int Value => this._value == 0 ? MIN_VALUE : this._value; // Treat the default, 0, as being the minimum value.   public LimitedInt(int value) { if (!IsValidValue(value)) throw new ArgumentOutOfRangeException(nameof(value), value, $"Value must be between {MIN_VALUE} and {MAX_VALUE}."); this._value = value; }   #region IComparable public int CompareTo(object obj) { if (obj is LimitedInt l) return this.Value.CompareTo(l); throw new ArgumentException("Object must be of type " + nameof(LimitedInt), nameof(obj)); } #endregion   #region IComparable<LimitedInt> public int CompareTo(LimitedInt other) => this.Value.CompareTo(other.Value); #endregion   #region IConvertible public TypeCode GetTypeCode() => this.Value.GetTypeCode(); bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)this.Value).ToBoolean(provider); byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)this.Value).ToByte(provider); char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)this.Value).ToChar(provider); DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)this.Value).ToDateTime(provider); decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)this.Value).ToDecimal(provider); double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)this.Value).ToDouble(provider); short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToInt16(provider); int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToInt32(provider); long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToInt64(provider); sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)this.Value).ToSByte(provider); float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)this.Value).ToSingle(provider); string IConvertible.ToString(IFormatProvider provider) => this.Value.ToString(provider); object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)this.Value).ToType(conversionType, provider); ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt16(provider); uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt32(provider); ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt64(provider); #endregion   #region IEquatable<LimitedInt> public bool Equals(LimitedInt other) => this == other; #endregion   #region IFormattable public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider); #endregion   #region operators public static bool operator ==(LimitedInt left, LimitedInt right) => left.Value == right.Value; public static bool operator !=(LimitedInt left, LimitedInt right) => left.Value != right.Value; public static bool operator <(LimitedInt left, LimitedInt right) => left.Value < right.Value; public static bool operator >(LimitedInt left, LimitedInt right) => left.Value > right.Value; public static bool operator <=(LimitedInt left, LimitedInt right) => left.Value <= right.Value; public static bool operator >=(LimitedInt left, LimitedInt right) => left.Value >= right.Value;   public static LimitedInt operator ++(LimitedInt left) => (LimitedInt)(left.Value + 1); public static LimitedInt operator --(LimitedInt left) => (LimitedInt)(left.Value - 1);   public static LimitedInt operator +(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value + right.Value); public static LimitedInt operator -(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value - right.Value); public static LimitedInt operator *(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value * right.Value); public static LimitedInt operator /(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value / right.Value); public static LimitedInt operator %(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value % right.Value);   public static LimitedInt operator &(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value & right.Value); public static LimitedInt operator |(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value | right.Value); public static LimitedInt operator ^(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value ^ right.Value); public static LimitedInt operator ~(LimitedInt left) => (LimitedInt)~left.Value;   public static LimitedInt operator >>(LimitedInt left, int right) => (LimitedInt)(left.Value >> right); public static LimitedInt operator <<(LimitedInt left, int right) => (LimitedInt)(left.Value << right);   public static implicit operator int(LimitedInt value) => value.Value; public static explicit operator LimitedInt(int value) { if (!IsValidValue(value)) throw new OverflowException(); return new LimitedInt(value); } #endregion   public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null) => this.Value.TryFormat(destination, out charsWritten, format, provider);   public override int GetHashCode() => this.Value.GetHashCode(); public override bool Equals(object obj) => obj is LimitedInt l && this.Equals(l); public override string ToString() => this.Value.ToString();   #region static methods public static bool TryParse(ReadOnlySpan<char> s, out int result) => int.TryParse(s, out result); public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) => int.TryParse(s, style, provider, out result); public static int Parse(string s, IFormatProvider provider) => int.Parse(s, provider); public static int Parse(string s, NumberStyles style, IFormatProvider provider) => int.Parse(s, style, provider); public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, ref int result) => int.TryParse(s, style, provider, out result); public static int Parse(string s) => int.Parse(s); public static int Parse(string s, NumberStyles style) => int.Parse(s, style); public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) => int.Parse(s, style, provider); public static bool TryParse(string s, ref int result) => int.TryParse(s, out result); #endregion }
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\infty }^{\infty }F(m)H(n-m)} for all integers n {\displaystyle {\mathit {n}}} . Assume F ( n ) {\displaystyle F(n)} can be non-zero only for 0 {\displaystyle 0} ≤ n {\displaystyle {\mathit {n}}} ≤ | F | {\displaystyle |{\mathit {F}}|} , where | F | {\displaystyle |{\mathit {F}}|} is the "length" of F {\displaystyle {\mathit {F}}} , and similarly for G {\displaystyle {\mathit {G}}} and H {\displaystyle {\mathit {H}}} , so that the functions can be modeled as finite sequences by identifying f 0 , f 1 , f 2 , … {\displaystyle f_{0},f_{1},f_{2},\dots } with F ( 0 ) , F ( 1 ) , F ( 2 ) , … {\displaystyle F(0),F(1),F(2),\dots } , etc. Then for example, values of | F | = 6 {\displaystyle |{\mathit {F}}|=6} and | H | = 5 {\displaystyle |{\mathit {H}}|=5} would determine the following value of g {\displaystyle {\mathit {g}}} by definition. g 0 = f 0 h 0 g 1 = f 1 h 0 + f 0 h 1 g 2 = f 2 h 0 + f 1 h 1 + f 0 h 2 g 3 = f 3 h 0 + f 2 h 1 + f 1 h 2 + f 0 h 3 g 4 = f 4 h 0 + f 3 h 1 + f 2 h 2 + f 1 h 3 + f 0 h 4 g 5 = f 5 h 0 + f 4 h 1 + f 3 h 2 + f 2 h 3 + f 1 h 4 g 6 = f 5 h 1 + f 4 h 2 + f 3 h 3 + f 2 h 4 g 7 = f 5 h 2 + f 4 h 3 + f 3 h 4 g 8 = f 5 h 3 + f 4 h 4 g 9 = f 5 h 4 {\displaystyle {\begin{array}{lllllllllll}g_{0}&=&f_{0}h_{0}\\g_{1}&=&f_{1}h_{0}&+&f_{0}h_{1}\\g_{2}&=&f_{2}h_{0}&+&f_{1}h_{1}&+&f_{0}h_{2}\\g_{3}&=&f_{3}h_{0}&+&f_{2}h_{1}&+&f_{1}h_{2}&+&f_{0}h_{3}\\g_{4}&=&f_{4}h_{0}&+&f_{3}h_{1}&+&f_{2}h_{2}&+&f_{1}h_{3}&+&f_{0}h_{4}\\g_{5}&=&f_{5}h_{0}&+&f_{4}h_{1}&+&f_{3}h_{2}&+&f_{2}h_{3}&+&f_{1}h_{4}\\g_{6}&=&&&f_{5}h_{1}&+&f_{4}h_{2}&+&f_{3}h_{3}&+&f_{2}h_{4}\\g_{7}&=&&&&&f_{5}h_{2}&+&f_{4}h_{3}&+&f_{3}h_{4}\\g_{8}&=&&&&&&&f_{5}h_{3}&+&f_{4}h_{4}\\g_{9}&=&&&&&&&&&f_{5}h_{4}\end{array}}} We can write this in matrix form as: ( g 0 g 1 g 2 g 3 g 4 g 5 g 6 g 7 g 8 g 9 ) = ( f 0 f 1 f 0 f 2 f 1 f 0 f 3 f 2 f 1 f 0 f 4 f 3 f 2 f 1 f 0 f 5 f 4 f 3 f 2 f 1 f 5 f 4 f 3 f 2 f 5 f 4 f 3 f 5 f 4 f 5 ) ( h 0 h 1 h 2 h 3 h 4 ) {\displaystyle \left({\begin{array}{l}g_{0}\\g_{1}\\g_{2}\\g_{3}\\g_{4}\\g_{5}\\g_{6}\\g_{7}\\g_{8}\\g_{9}\\\end{array}}\right)=\left({\begin{array}{lllll}f_{0}\\f_{1}&f_{0}\\f_{2}&f_{1}&f_{0}\\f_{3}&f_{2}&f_{1}&f_{0}\\f_{4}&f_{3}&f_{2}&f_{1}&f_{0}\\f_{5}&f_{4}&f_{3}&f_{2}&f_{1}\\&f_{5}&f_{4}&f_{3}&f_{2}\\&&f_{5}&f_{4}&f_{3}\\&&&f_{5}&f_{4}\\&&&&f_{5}\end{array}}\right)\;\left({\begin{array}{l}h_{0}\\h_{1}\\h_{2}\\h_{3}\\h_{4}\\\end{array}}\right)} or g = A h {\displaystyle g=A\;h} For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by constructing and solving such a system of equations represented by the above matrix A {\displaystyle A} for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . The function should work for G {\displaystyle {\mathit {G}}} of arbitrary length (i.e., not hard coded or constant) and F {\displaystyle {\mathit {F}}} of any length up to that of G {\displaystyle {\mathit {G}}} . Note that | H | {\displaystyle |{\mathit {H}}|} will be given by | G | − | F | + 1 {\displaystyle |{\mathit {G}}|-|{\mathit {F}}|+1} . There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task. Test your solution on the following data. Be sure to verify both that deconv ( g , f ) = h {\displaystyle (g,f)=h} and deconv ( g , h ) = f {\displaystyle (g,h)=f} and display the results in a human readable form. h = [-8,-9,-3,-1,-6,7] f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
#Haskell
Haskell
deconv1d :: [Double] -> [Double] -> [Double] deconv1d xs ys = takeWhile (/= 0) $ deconv xs ys where [] `deconv` _ = [] (0:xs) `deconv` (0:ys) = xs `deconv` ys (x:xs) `deconv` (y:ys) = let q = x / y in q : zipWith (-) xs (scale q ys ++ repeat 0) `deconv` (y : ys)   scale :: Double -> [Double] -> [Double] scale = map . (*)   h, f, g :: [Double] h = [-8, -9, -3, -1, -6, 7]   f = [-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1]   g = [ 24 , 75 , 71 , -34 , 3 , 22 , -45 , 23 , 245 , 25 , 52 , 25 , -67 , -96 , 96 , 31 , 55 , 36 , 29 , -43 , -7 ]   main :: IO () main = print $ (h == deconv1d g f) && (f == deconv1d g h)
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#PHP
PHP
<?php class Foo { public function __clone() { $this->child = clone $this->child; } }   $object = new Foo; $object->some_value = 1; $object->child = new stdClass; $object->child->some_value = 1;   $deepcopy = clone $object; $deepcopy->some_value++; $deepcopy->child->some_value++;   echo "Object contains {$object->some_value}, child contains {$object->child->some_value}\n", "Clone of object contains {$deepcopy->some_value}, child contains {$deepcopy->child->some_value}\n"; ?>
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#PicoLisp
PicoLisp
(mapcar copy List)
http://rosettacode.org/wiki/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#C.2B.2B
C++
#include <stdexcept>   class tiny_int { public: tiny_int(int i): value(i) { if (value < 1) throw std::out_of_range("tiny_int: value smaller than 1"); if (value > 10) throw std::out_of_range("tiny_int: value larger than 10"); } operator int() const { return value; } tiny_int& operator+=(int i) { // by assigning to *this instead of directly modifying value, the // constructor is called and thus the check is enforced *this = value + i; return *this; } tiny_int& operator-=(int i) { *this = value - i; return *this; } tiny_int& operator*=(int i) { *this = value * i; return *this; } tiny_int& operator/=(int i) { *this = value / i; return *this; } tiny_int& operator<<=(int i) { *this = value << i; return *this; } tiny_int& operator>>=(int i) { *this = value >> i; return *this; } tiny_int& operator&=(int i) { *this = value & i; return *this; } tiny_int& operator|=(int i) { *this = value | i; return *this; } private: unsigned char value; // we don't need more space };
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\infty }^{\infty }F(m)H(n-m)} for all integers n {\displaystyle {\mathit {n}}} . Assume F ( n ) {\displaystyle F(n)} can be non-zero only for 0 {\displaystyle 0} ≤ n {\displaystyle {\mathit {n}}} ≤ | F | {\displaystyle |{\mathit {F}}|} , where | F | {\displaystyle |{\mathit {F}}|} is the "length" of F {\displaystyle {\mathit {F}}} , and similarly for G {\displaystyle {\mathit {G}}} and H {\displaystyle {\mathit {H}}} , so that the functions can be modeled as finite sequences by identifying f 0 , f 1 , f 2 , … {\displaystyle f_{0},f_{1},f_{2},\dots } with F ( 0 ) , F ( 1 ) , F ( 2 ) , … {\displaystyle F(0),F(1),F(2),\dots } , etc. Then for example, values of | F | = 6 {\displaystyle |{\mathit {F}}|=6} and | H | = 5 {\displaystyle |{\mathit {H}}|=5} would determine the following value of g {\displaystyle {\mathit {g}}} by definition. g 0 = f 0 h 0 g 1 = f 1 h 0 + f 0 h 1 g 2 = f 2 h 0 + f 1 h 1 + f 0 h 2 g 3 = f 3 h 0 + f 2 h 1 + f 1 h 2 + f 0 h 3 g 4 = f 4 h 0 + f 3 h 1 + f 2 h 2 + f 1 h 3 + f 0 h 4 g 5 = f 5 h 0 + f 4 h 1 + f 3 h 2 + f 2 h 3 + f 1 h 4 g 6 = f 5 h 1 + f 4 h 2 + f 3 h 3 + f 2 h 4 g 7 = f 5 h 2 + f 4 h 3 + f 3 h 4 g 8 = f 5 h 3 + f 4 h 4 g 9 = f 5 h 4 {\displaystyle {\begin{array}{lllllllllll}g_{0}&=&f_{0}h_{0}\\g_{1}&=&f_{1}h_{0}&+&f_{0}h_{1}\\g_{2}&=&f_{2}h_{0}&+&f_{1}h_{1}&+&f_{0}h_{2}\\g_{3}&=&f_{3}h_{0}&+&f_{2}h_{1}&+&f_{1}h_{2}&+&f_{0}h_{3}\\g_{4}&=&f_{4}h_{0}&+&f_{3}h_{1}&+&f_{2}h_{2}&+&f_{1}h_{3}&+&f_{0}h_{4}\\g_{5}&=&f_{5}h_{0}&+&f_{4}h_{1}&+&f_{3}h_{2}&+&f_{2}h_{3}&+&f_{1}h_{4}\\g_{6}&=&&&f_{5}h_{1}&+&f_{4}h_{2}&+&f_{3}h_{3}&+&f_{2}h_{4}\\g_{7}&=&&&&&f_{5}h_{2}&+&f_{4}h_{3}&+&f_{3}h_{4}\\g_{8}&=&&&&&&&f_{5}h_{3}&+&f_{4}h_{4}\\g_{9}&=&&&&&&&&&f_{5}h_{4}\end{array}}} We can write this in matrix form as: ( g 0 g 1 g 2 g 3 g 4 g 5 g 6 g 7 g 8 g 9 ) = ( f 0 f 1 f 0 f 2 f 1 f 0 f 3 f 2 f 1 f 0 f 4 f 3 f 2 f 1 f 0 f 5 f 4 f 3 f 2 f 1 f 5 f 4 f 3 f 2 f 5 f 4 f 3 f 5 f 4 f 5 ) ( h 0 h 1 h 2 h 3 h 4 ) {\displaystyle \left({\begin{array}{l}g_{0}\\g_{1}\\g_{2}\\g_{3}\\g_{4}\\g_{5}\\g_{6}\\g_{7}\\g_{8}\\g_{9}\\\end{array}}\right)=\left({\begin{array}{lllll}f_{0}\\f_{1}&f_{0}\\f_{2}&f_{1}&f_{0}\\f_{3}&f_{2}&f_{1}&f_{0}\\f_{4}&f_{3}&f_{2}&f_{1}&f_{0}\\f_{5}&f_{4}&f_{3}&f_{2}&f_{1}\\&f_{5}&f_{4}&f_{3}&f_{2}\\&&f_{5}&f_{4}&f_{3}\\&&&f_{5}&f_{4}\\&&&&f_{5}\end{array}}\right)\;\left({\begin{array}{l}h_{0}\\h_{1}\\h_{2}\\h_{3}\\h_{4}\\\end{array}}\right)} or g = A h {\displaystyle g=A\;h} For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by constructing and solving such a system of equations represented by the above matrix A {\displaystyle A} for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . The function should work for G {\displaystyle {\mathit {G}}} of arbitrary length (i.e., not hard coded or constant) and F {\displaystyle {\mathit {F}}} of any length up to that of G {\displaystyle {\mathit {G}}} . Note that | H | {\displaystyle |{\mathit {H}}|} will be given by | G | − | F | + 1 {\displaystyle |{\mathit {G}}|-|{\mathit {F}}|+1} . There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task. Test your solution on the following data. Be sure to verify both that deconv ( g , f ) = h {\displaystyle (g,f)=h} and deconv ( g , h ) = f {\displaystyle (g,h)=f} and display the results in a human readable form. h = [-8,-9,-3,-1,-6,7] f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
#J
J
Ai=: (i.@] =/ i.@[ -/ i.@>:@-)&# divide=: [ +/ .*~ [:%.&.x: ] +/ .* Ai
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\infty }^{\infty }F(m)H(n-m)} for all integers n {\displaystyle {\mathit {n}}} . Assume F ( n ) {\displaystyle F(n)} can be non-zero only for 0 {\displaystyle 0} ≤ n {\displaystyle {\mathit {n}}} ≤ | F | {\displaystyle |{\mathit {F}}|} , where | F | {\displaystyle |{\mathit {F}}|} is the "length" of F {\displaystyle {\mathit {F}}} , and similarly for G {\displaystyle {\mathit {G}}} and H {\displaystyle {\mathit {H}}} , so that the functions can be modeled as finite sequences by identifying f 0 , f 1 , f 2 , … {\displaystyle f_{0},f_{1},f_{2},\dots } with F ( 0 ) , F ( 1 ) , F ( 2 ) , … {\displaystyle F(0),F(1),F(2),\dots } , etc. Then for example, values of | F | = 6 {\displaystyle |{\mathit {F}}|=6} and | H | = 5 {\displaystyle |{\mathit {H}}|=5} would determine the following value of g {\displaystyle {\mathit {g}}} by definition. g 0 = f 0 h 0 g 1 = f 1 h 0 + f 0 h 1 g 2 = f 2 h 0 + f 1 h 1 + f 0 h 2 g 3 = f 3 h 0 + f 2 h 1 + f 1 h 2 + f 0 h 3 g 4 = f 4 h 0 + f 3 h 1 + f 2 h 2 + f 1 h 3 + f 0 h 4 g 5 = f 5 h 0 + f 4 h 1 + f 3 h 2 + f 2 h 3 + f 1 h 4 g 6 = f 5 h 1 + f 4 h 2 + f 3 h 3 + f 2 h 4 g 7 = f 5 h 2 + f 4 h 3 + f 3 h 4 g 8 = f 5 h 3 + f 4 h 4 g 9 = f 5 h 4 {\displaystyle {\begin{array}{lllllllllll}g_{0}&=&f_{0}h_{0}\\g_{1}&=&f_{1}h_{0}&+&f_{0}h_{1}\\g_{2}&=&f_{2}h_{0}&+&f_{1}h_{1}&+&f_{0}h_{2}\\g_{3}&=&f_{3}h_{0}&+&f_{2}h_{1}&+&f_{1}h_{2}&+&f_{0}h_{3}\\g_{4}&=&f_{4}h_{0}&+&f_{3}h_{1}&+&f_{2}h_{2}&+&f_{1}h_{3}&+&f_{0}h_{4}\\g_{5}&=&f_{5}h_{0}&+&f_{4}h_{1}&+&f_{3}h_{2}&+&f_{2}h_{3}&+&f_{1}h_{4}\\g_{6}&=&&&f_{5}h_{1}&+&f_{4}h_{2}&+&f_{3}h_{3}&+&f_{2}h_{4}\\g_{7}&=&&&&&f_{5}h_{2}&+&f_{4}h_{3}&+&f_{3}h_{4}\\g_{8}&=&&&&&&&f_{5}h_{3}&+&f_{4}h_{4}\\g_{9}&=&&&&&&&&&f_{5}h_{4}\end{array}}} We can write this in matrix form as: ( g 0 g 1 g 2 g 3 g 4 g 5 g 6 g 7 g 8 g 9 ) = ( f 0 f 1 f 0 f 2 f 1 f 0 f 3 f 2 f 1 f 0 f 4 f 3 f 2 f 1 f 0 f 5 f 4 f 3 f 2 f 1 f 5 f 4 f 3 f 2 f 5 f 4 f 3 f 5 f 4 f 5 ) ( h 0 h 1 h 2 h 3 h 4 ) {\displaystyle \left({\begin{array}{l}g_{0}\\g_{1}\\g_{2}\\g_{3}\\g_{4}\\g_{5}\\g_{6}\\g_{7}\\g_{8}\\g_{9}\\\end{array}}\right)=\left({\begin{array}{lllll}f_{0}\\f_{1}&f_{0}\\f_{2}&f_{1}&f_{0}\\f_{3}&f_{2}&f_{1}&f_{0}\\f_{4}&f_{3}&f_{2}&f_{1}&f_{0}\\f_{5}&f_{4}&f_{3}&f_{2}&f_{1}\\&f_{5}&f_{4}&f_{3}&f_{2}\\&&f_{5}&f_{4}&f_{3}\\&&&f_{5}&f_{4}\\&&&&f_{5}\end{array}}\right)\;\left({\begin{array}{l}h_{0}\\h_{1}\\h_{2}\\h_{3}\\h_{4}\\\end{array}}\right)} or g = A h {\displaystyle g=A\;h} For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by constructing and solving such a system of equations represented by the above matrix A {\displaystyle A} for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . The function should work for G {\displaystyle {\mathit {G}}} of arbitrary length (i.e., not hard coded or constant) and F {\displaystyle {\mathit {F}}} of any length up to that of G {\displaystyle {\mathit {G}}} . Note that | H | {\displaystyle |{\mathit {H}}|} will be given by | G | − | F | + 1 {\displaystyle |{\mathit {G}}|-|{\mathit {F}}|+1} . There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task. Test your solution on the following data. Be sure to verify both that deconv ( g , f ) = h {\displaystyle (g,f)=h} and deconv ( g , h ) = f {\displaystyle (g,h)=f} and display the results in a human readable form. h = [-8,-9,-3,-1,-6,7] f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
#Java
Java
import java.util.Arrays;   public class Deconvolution1D { public static int[] deconv(int[] g, int[] f) { int[] h = new int[g.length - f.length + 1]; for (int n = 0; n < h.length; n++) { h[n] = g[n]; int lower = Math.max(n - f.length + 1, 0); for (int i = lower; i < n; i++) h[n] -= h[i] * f[n - i]; h[n] /= f[0]; } return h; }   public static void main(String[] args) { int[] h = { -8, -9, -3, -1, -6, 7 }; int[] f = { -3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1 }; int[] g = { 24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, 96, 31, 55, 36, 29, -43, -7 };   StringBuilder sb = new StringBuilder(); sb.append("h = " + Arrays.toString(h) + "\n"); sb.append("deconv(g, f) = " + Arrays.toString(deconv(g, f)) + "\n"); sb.append("f = " + Arrays.toString(f) + "\n"); sb.append("deconv(g, h) = " + Arrays.toString(deconv(g, h)) + "\n"); System.out.println(sb.toString()); } }
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#PureBasic
PureBasic
Macro PrintStruc(StrucVal) PrintN(Str(StrucVal#\value1)) PrintN(Chr(StrucVal#\value2)) PrintN(StrucVal#\value3) If StrucVal#\value4 PrintN("TRUE") Else PrintN("FALSE") EndIf PrintN("") EndMacro   Structure TTypeA value1.i value2.c value3.s[10] value4.b EndStructure   Define.TTypeA a, b   a\value1=10 a\value2='A' a\value3="OK" a\value4=#True   b=a   a\value1=20 a\value2='B' a\value3="NOK" a\value4=#False   If OpenConsole("") PrintN("Value of 'a':") : PrintStruc(a) PrintN("Value of 'b':") : PrintStruc(b) Input() EndIf
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Python
Python
import copy deepcopy_of_obj = copy.deepcopy(obj)
http://rosettacode.org/wiki/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#Clojure
Clojure
(defn tinyint [^long value] (if (<= 1 value 10) (proxy [Number] [] (doubleValue [] value) (longValue [] value)) (throw (ArithmeticException. "integer overflow"))))
http://rosettacode.org/wiki/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#Common_Lisp
Common Lisp
(deftype one-to-ten () '(integer 1 10))
http://rosettacode.org/wiki/Death_Star
Death Star
Task Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction. (This will basically produce a shape like a "death star".) Related tasks draw a sphere draw a cuboid draw a rotating cube write language name in 3D ASCII
#11l
11l
T Sphere Float cx, cy, cz, r F (cx, cy, cz, r) .cx = cx .cy = cy .cz = cz .r = r   F dotp(v1, v2) V d = dot(v1, v2) R I d < 0 {-d} E 0.0   F hit_sphere(sph, x0, y0) V x = x0 - sph.cx V y = y0 - sph.cy V zsq = sph.r ^ 2 - (x ^ 2 + y ^ 2) I zsq < 0 R (0B, 0.0, 0.0) V szsq = sqrt(zsq) R (1B, sph.cz - szsq, sph.cz + szsq)   F draw_sphere(k, ambient, light) V shades = ‘.:!*oe&#%@’ V pos = Sphere(20.0, 20.0, 0.0, 20.0) V neg = Sphere(1.0, 1.0, -6.0, 20.0)   L(i) Int(floor(pos.cy - pos.r)) .< Int(ceil(pos.cy + pos.r) + 1) V y = i + 0.5 L(j) Int(floor(pos.cx - 2 * pos.r)) .< Int(ceil(pos.cx + 2 * pos.r) + 1) V x = (j - pos.cx) / 2.0 + 0.5 + pos.cx   V (h, zb1, zb2) = hit_sphere(pos, x, y) Int hit_result Float zs2 I !h hit_result = 0 E (h, V zs1, zs2) = hit_sphere(neg, x, y) I !h hit_result = 1 E I zs1 > zb1 hit_result = 1 E I zs2 > zb2 hit_result = 0 E I zs2 > zb1 hit_result = 2 E hit_result = 1   V vec = (0.0, 0.0, 0.0) I hit_result == 0 print(‘ ’, end' ‘’) L.continue E I hit_result == 1 vec = (x - pos.cx, y - pos.cy, zb1 - pos.cz) E I hit_result == 2 vec = (neg.cx - x, neg.cy - y, neg.cz - zs2) vec = normalize(vec)   V b = dotp(light, vec) ^ k + ambient V intensity = Int((1 - b) * shades.len) intensity = min(shades.len, max(0, intensity)) print(shades[intensity], end' ‘’) print()   V light = normalize((-50.0, 30.0, 50.0)) draw_sphere(2, 0.5, light)
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\infty }^{\infty }F(m)H(n-m)} for all integers n {\displaystyle {\mathit {n}}} . Assume F ( n ) {\displaystyle F(n)} can be non-zero only for 0 {\displaystyle 0} ≤ n {\displaystyle {\mathit {n}}} ≤ | F | {\displaystyle |{\mathit {F}}|} , where | F | {\displaystyle |{\mathit {F}}|} is the "length" of F {\displaystyle {\mathit {F}}} , and similarly for G {\displaystyle {\mathit {G}}} and H {\displaystyle {\mathit {H}}} , so that the functions can be modeled as finite sequences by identifying f 0 , f 1 , f 2 , … {\displaystyle f_{0},f_{1},f_{2},\dots } with F ( 0 ) , F ( 1 ) , F ( 2 ) , … {\displaystyle F(0),F(1),F(2),\dots } , etc. Then for example, values of | F | = 6 {\displaystyle |{\mathit {F}}|=6} and | H | = 5 {\displaystyle |{\mathit {H}}|=5} would determine the following value of g {\displaystyle {\mathit {g}}} by definition. g 0 = f 0 h 0 g 1 = f 1 h 0 + f 0 h 1 g 2 = f 2 h 0 + f 1 h 1 + f 0 h 2 g 3 = f 3 h 0 + f 2 h 1 + f 1 h 2 + f 0 h 3 g 4 = f 4 h 0 + f 3 h 1 + f 2 h 2 + f 1 h 3 + f 0 h 4 g 5 = f 5 h 0 + f 4 h 1 + f 3 h 2 + f 2 h 3 + f 1 h 4 g 6 = f 5 h 1 + f 4 h 2 + f 3 h 3 + f 2 h 4 g 7 = f 5 h 2 + f 4 h 3 + f 3 h 4 g 8 = f 5 h 3 + f 4 h 4 g 9 = f 5 h 4 {\displaystyle {\begin{array}{lllllllllll}g_{0}&=&f_{0}h_{0}\\g_{1}&=&f_{1}h_{0}&+&f_{0}h_{1}\\g_{2}&=&f_{2}h_{0}&+&f_{1}h_{1}&+&f_{0}h_{2}\\g_{3}&=&f_{3}h_{0}&+&f_{2}h_{1}&+&f_{1}h_{2}&+&f_{0}h_{3}\\g_{4}&=&f_{4}h_{0}&+&f_{3}h_{1}&+&f_{2}h_{2}&+&f_{1}h_{3}&+&f_{0}h_{4}\\g_{5}&=&f_{5}h_{0}&+&f_{4}h_{1}&+&f_{3}h_{2}&+&f_{2}h_{3}&+&f_{1}h_{4}\\g_{6}&=&&&f_{5}h_{1}&+&f_{4}h_{2}&+&f_{3}h_{3}&+&f_{2}h_{4}\\g_{7}&=&&&&&f_{5}h_{2}&+&f_{4}h_{3}&+&f_{3}h_{4}\\g_{8}&=&&&&&&&f_{5}h_{3}&+&f_{4}h_{4}\\g_{9}&=&&&&&&&&&f_{5}h_{4}\end{array}}} We can write this in matrix form as: ( g 0 g 1 g 2 g 3 g 4 g 5 g 6 g 7 g 8 g 9 ) = ( f 0 f 1 f 0 f 2 f 1 f 0 f 3 f 2 f 1 f 0 f 4 f 3 f 2 f 1 f 0 f 5 f 4 f 3 f 2 f 1 f 5 f 4 f 3 f 2 f 5 f 4 f 3 f 5 f 4 f 5 ) ( h 0 h 1 h 2 h 3 h 4 ) {\displaystyle \left({\begin{array}{l}g_{0}\\g_{1}\\g_{2}\\g_{3}\\g_{4}\\g_{5}\\g_{6}\\g_{7}\\g_{8}\\g_{9}\\\end{array}}\right)=\left({\begin{array}{lllll}f_{0}\\f_{1}&f_{0}\\f_{2}&f_{1}&f_{0}\\f_{3}&f_{2}&f_{1}&f_{0}\\f_{4}&f_{3}&f_{2}&f_{1}&f_{0}\\f_{5}&f_{4}&f_{3}&f_{2}&f_{1}\\&f_{5}&f_{4}&f_{3}&f_{2}\\&&f_{5}&f_{4}&f_{3}\\&&&f_{5}&f_{4}\\&&&&f_{5}\end{array}}\right)\;\left({\begin{array}{l}h_{0}\\h_{1}\\h_{2}\\h_{3}\\h_{4}\\\end{array}}\right)} or g = A h {\displaystyle g=A\;h} For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by constructing and solving such a system of equations represented by the above matrix A {\displaystyle A} for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . The function should work for G {\displaystyle {\mathit {G}}} of arbitrary length (i.e., not hard coded or constant) and F {\displaystyle {\mathit {F}}} of any length up to that of G {\displaystyle {\mathit {G}}} . Note that | H | {\displaystyle |{\mathit {H}}|} will be given by | G | − | F | + 1 {\displaystyle |{\mathit {G}}|-|{\mathit {F}}|+1} . There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task. Test your solution on the following data. Be sure to verify both that deconv ( g , f ) = h {\displaystyle (g,f)=h} and deconv ( g , h ) = f {\displaystyle (g,h)=f} and display the results in a human readable form. h = [-8,-9,-3,-1,-6,7] f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
#Julia
Julia
h = [-8, -9, -3, -1, -6, 7] g = [24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, 96, 31, 55, 36, 29, -43, -7] f = [-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1]   hanswer = deconv(float.(g), float.(f)) println("The deconvolution deconv(g, f) is $hanswer, which is the same as h = $h\n")   fanswer = deconv(float.(g), float.(h)) println("The deconvolution deconv(g, h) is $fanswer, which is the same as f = $f\n")
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\infty }^{\infty }F(m)H(n-m)} for all integers n {\displaystyle {\mathit {n}}} . Assume F ( n ) {\displaystyle F(n)} can be non-zero only for 0 {\displaystyle 0} ≤ n {\displaystyle {\mathit {n}}} ≤ | F | {\displaystyle |{\mathit {F}}|} , where | F | {\displaystyle |{\mathit {F}}|} is the "length" of F {\displaystyle {\mathit {F}}} , and similarly for G {\displaystyle {\mathit {G}}} and H {\displaystyle {\mathit {H}}} , so that the functions can be modeled as finite sequences by identifying f 0 , f 1 , f 2 , … {\displaystyle f_{0},f_{1},f_{2},\dots } with F ( 0 ) , F ( 1 ) , F ( 2 ) , … {\displaystyle F(0),F(1),F(2),\dots } , etc. Then for example, values of | F | = 6 {\displaystyle |{\mathit {F}}|=6} and | H | = 5 {\displaystyle |{\mathit {H}}|=5} would determine the following value of g {\displaystyle {\mathit {g}}} by definition. g 0 = f 0 h 0 g 1 = f 1 h 0 + f 0 h 1 g 2 = f 2 h 0 + f 1 h 1 + f 0 h 2 g 3 = f 3 h 0 + f 2 h 1 + f 1 h 2 + f 0 h 3 g 4 = f 4 h 0 + f 3 h 1 + f 2 h 2 + f 1 h 3 + f 0 h 4 g 5 = f 5 h 0 + f 4 h 1 + f 3 h 2 + f 2 h 3 + f 1 h 4 g 6 = f 5 h 1 + f 4 h 2 + f 3 h 3 + f 2 h 4 g 7 = f 5 h 2 + f 4 h 3 + f 3 h 4 g 8 = f 5 h 3 + f 4 h 4 g 9 = f 5 h 4 {\displaystyle {\begin{array}{lllllllllll}g_{0}&=&f_{0}h_{0}\\g_{1}&=&f_{1}h_{0}&+&f_{0}h_{1}\\g_{2}&=&f_{2}h_{0}&+&f_{1}h_{1}&+&f_{0}h_{2}\\g_{3}&=&f_{3}h_{0}&+&f_{2}h_{1}&+&f_{1}h_{2}&+&f_{0}h_{3}\\g_{4}&=&f_{4}h_{0}&+&f_{3}h_{1}&+&f_{2}h_{2}&+&f_{1}h_{3}&+&f_{0}h_{4}\\g_{5}&=&f_{5}h_{0}&+&f_{4}h_{1}&+&f_{3}h_{2}&+&f_{2}h_{3}&+&f_{1}h_{4}\\g_{6}&=&&&f_{5}h_{1}&+&f_{4}h_{2}&+&f_{3}h_{3}&+&f_{2}h_{4}\\g_{7}&=&&&&&f_{5}h_{2}&+&f_{4}h_{3}&+&f_{3}h_{4}\\g_{8}&=&&&&&&&f_{5}h_{3}&+&f_{4}h_{4}\\g_{9}&=&&&&&&&&&f_{5}h_{4}\end{array}}} We can write this in matrix form as: ( g 0 g 1 g 2 g 3 g 4 g 5 g 6 g 7 g 8 g 9 ) = ( f 0 f 1 f 0 f 2 f 1 f 0 f 3 f 2 f 1 f 0 f 4 f 3 f 2 f 1 f 0 f 5 f 4 f 3 f 2 f 1 f 5 f 4 f 3 f 2 f 5 f 4 f 3 f 5 f 4 f 5 ) ( h 0 h 1 h 2 h 3 h 4 ) {\displaystyle \left({\begin{array}{l}g_{0}\\g_{1}\\g_{2}\\g_{3}\\g_{4}\\g_{5}\\g_{6}\\g_{7}\\g_{8}\\g_{9}\\\end{array}}\right)=\left({\begin{array}{lllll}f_{0}\\f_{1}&f_{0}\\f_{2}&f_{1}&f_{0}\\f_{3}&f_{2}&f_{1}&f_{0}\\f_{4}&f_{3}&f_{2}&f_{1}&f_{0}\\f_{5}&f_{4}&f_{3}&f_{2}&f_{1}\\&f_{5}&f_{4}&f_{3}&f_{2}\\&&f_{5}&f_{4}&f_{3}\\&&&f_{5}&f_{4}\\&&&&f_{5}\end{array}}\right)\;\left({\begin{array}{l}h_{0}\\h_{1}\\h_{2}\\h_{3}\\h_{4}\\\end{array}}\right)} or g = A h {\displaystyle g=A\;h} For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by constructing and solving such a system of equations represented by the above matrix A {\displaystyle A} for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . The function should work for G {\displaystyle {\mathit {G}}} of arbitrary length (i.e., not hard coded or constant) and F {\displaystyle {\mathit {F}}} of any length up to that of G {\displaystyle {\mathit {G}}} . Note that | H | {\displaystyle |{\mathit {H}}|} will be given by | G | − | F | + 1 {\displaystyle |{\mathit {G}}|-|{\mathit {F}}|+1} . There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task. Test your solution on the following data. Be sure to verify both that deconv ( g , f ) = h {\displaystyle (g,f)=h} and deconv ( g , h ) = f {\displaystyle (g,h)=f} and display the results in a human readable form. h = [-8,-9,-3,-1,-6,7] f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
#Kotlin
Kotlin
// version 1.1.3   fun deconv(g: DoubleArray, f: DoubleArray): DoubleArray { val fs = f.size val h = DoubleArray(g.size - fs + 1) for (n in h.indices) { h[n] = g[n] val lower = if (n >= fs) n - fs + 1 else 0 for (i in lower until n) h[n] -= h[i] * f[n -i] h[n] /= f[0] } return h }   fun main(args: Array<String>) { val h = doubleArrayOf(-8.0, -9.0, -3.0, -1.0, -6.0, 7.0) val f = doubleArrayOf(-3.0, -6.0, -1.0, 8.0, -6.0, 3.0, -1.0, -9.0, -9.0, 3.0, -2.0, 5.0, 2.0, -2.0, -7.0, -1.0) val g = doubleArrayOf(24.0, 75.0, 71.0, -34.0, 3.0, 22.0, -45.0, 23.0, 245.0, 25.0, 52.0, 25.0, -67.0, -96.0, 96.0, 31.0, 55.0, 36.0, 29.0, -43.0, -7.0) println("${h.map { it.toInt() }}") println("${deconv(g, f).map { it.toInt() }}") println() println("${f.map { it.toInt() }}") println("${deconv(g, h).map { it.toInt() }}") }
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Racket
Racket
  #lang racket   (define (deepcopy x)  ;; make sure that all sharings are shown (parameterize ([print-graph #t]) (read (open-input-string (format "~s" x)))))   (define (try x)  ;; use the same setting to see that it worked (parameterize ([print-graph #t]) (printf "original: ~s\n" x) (printf "deepcopy: ~s\n" (deepcopy x))  ;; print both also, which shows that they are indeed different (printf "both: ~s\n" (list x (deepcopy x))))) (try (shared ([x (cons 1 x)]) (list x x)))  
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Raku
Raku
my %x = foo => 0, bar => [0, 1]; my %y = %x.deepmap(*.clone);   %x<bar>[1]++; say %x; say %y;
http://rosettacode.org/wiki/De_Bruijn_sequences
de Bruijn sequences
The sequences are named after the Dutch mathematician   Nicolaas Govert de Bruijn. A note on Dutch capitalization:   Nicolaas' last name is   de Bruijn,   the   de   isn't normally capitalized unless it's the first word in a sentence.   Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be capitalized. In combinatorial mathematics,   a   de Bruijn sequence   of order   n   on a   size-k   alphabet (computer science)   A   is a cyclic sequence in which every possible   length-n   string (computer science, formal theory)   on   A   occurs exactly once as a contiguous substring. Such a sequence is denoted by   B(k, n)   and has length   kn,   which is also the number of distinct substrings of length   n   on   A;     de Bruijn sequences are therefore optimally short. There are: (k!)k(n-1)   ÷   kn distinct de Bruijn sequences   B(k, n). Task For this Rosetta Code task,   a   de Bruijn   sequence is to be generated that can be used to shorten a brute-force attack on a   PIN-like   code lock that does not have an "enter" key and accepts the last   n   digits entered. Note:   automated teller machines (ATMs)   used to work like this,   but their software has been updated to not allow a brute-force attack. Example A   digital door lock   with a 4-digit code would have B (10, 4) solutions,   with a length of   10,000   (digits). Therefore, only at most     10,000 + 3     (as the solutions are cyclic or wrap-around)   presses are needed to open the lock. Trying all 4-digit codes separately would require   4 × 10,000   or   40,000   presses. Task requirements   Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.   Show the length of the generated de Bruijn sequence.   (There are many possible de Bruijn sequences that solve this task,   one solution is shown on the discussion page).   Show the first and last   130   digits of the de Bruijn sequence.   Verify that all four-digit (decimal)   1,000   PIN codes are contained within the de Bruijn sequence.   0000, 0001, 0002, 0003,   ...   9996, 9997, 9998, 9999   (note the leading zeros).   Reverse the de Bruijn sequence.   Again, perform the (above) verification test.   Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.   Perform the verification test (again).   There should be four PIN codes missing. (The last requirement is to ensure that the verification tests performs correctly.   The verification processes should list any and all missing PIN codes.) Show all output here, on this page. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet References   Wikipedia entry:   de Bruijn sequence.   MathWorld entry:   de Bruijn sequence.   An  OEIS  entry:   A166315 lexicographically earliest binary de Bruijn sequences, B(2,n)     --- Not B(10,4),   but possibly relevant.
#11l
11l
V digits = ‘0123456789’   F deBruijn(k, n) V alphabet = :digits[0 .< k] V a = [Byte(0)] * (k * n) [Byte] seq   F db(Int t, Int p) -> N I t > @n I @n % p == 0 @seq.extend(@a[1 .< p + 1]) E @a[t] = @a[t - p] @db(t + 1, p) V j = @a[t - p] + 1 L j < @k @a[t] = j [&] F'F @db(t + 1, t) j++   db(1, 1) V buf = ‘’ L(i) seq buf ‘’= alphabet[i]   R buf‘’buf[0 .< n - 1]   F validate(db) V found = [0] * 10'000 [String] errs   L(i) 0 .< db.len - 3 V s = db[i .< i + 4] I s.is_digit() found[Int(s)]++   L(i) 10'000 I found[i] == 0 errs [+]= ‘ PIN number #04 missing’.format(i) E I found[i] > 1 errs [+]= ‘ PIN number #04 occurs #. times’.format(i, found[i])   I errs.empty print(‘ No errors found’) E V pl = I errs.len == 1 {‘’} E ‘s’ print(‘ ’String(errs.len)‘ error’pl‘ found:’) L(err) errs print(err)   V db = deBruijn(10, 4)   print(‘The length of the de Bruijn sequence is ’db.len) print("\nThe first 130 digits of the de Bruijn sequence are: "db[0.<130]) print("\nThe last 130 digits of the de Bruijn sequence are: "db[(len)-130..])   print("\nValidating the deBruijn sequence:") validate(db)   print("\nValidating the reversed deBruijn sequence:") validate(reversed(db))   db[4443] = ‘.’ print("\nValidating the overlaid deBruijn sequence:") validate(db)
http://rosettacode.org/wiki/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#D
D
import std.exception, std.string, std.traits;   /++ A bounded integral type template. Template params: - min: the minimal value - max: the maximal value - I: the type used to store the value internally +/ struct BoundedInt(alias min, alias max, I = int) { // Static checks static assert(isIntegral!(typeof(min))); static assert(isIntegral!(typeof(max))); static assert(isIntegral!I); static assert(min < max); static assert(cast(I) max == max, "Type " ~ I.stringof ~ " cannot hold values up to " ~ max.stringof);   /// The actual value stored in this struct private I _value;   /// Getter for the internal value @property I internalValue() { return _value; }   /// 'alias this' to make this struct look like a built-in integer alias internalValue this;   /// Constructor this(T)(T value) { opAssign(value); }   /// Assignment operator void opAssign(T)(T value) if (isIntegral!T) { _value = checked(value); }   /// Unary operators auto opUnary(string op)() const { return checked(mixin(op ~ "_value")); }   /// Binary operators auto opBinary(string op, T)(T other) const { return checked(mixin("_value" ~ op ~ "other")); }   /// ditto auto opBinaryRight(string op, T)(T other) const if (isIntegral!T) { return checked(mixin("_value" ~ op ~ "other")); }   // Bounds enforcement private I checked(T)(T value) const { enforce(value >= min && value <= max, format("Value %s is out of bounds (%s to %s).", value, min, max)); return cast(I) value; } }   unittest { alias MyInt = BoundedInt!(1, 10); // alias BoundInt!(1, 10) MyInt; // D < 2.061   MyInt i = 4; MyInt j = i + i; assert(j / 2 == 4); assert(2 + j == 10); assert(i < 5); assert(j > i); }
http://rosettacode.org/wiki/Death_Star
Death Star
Task Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction. (This will basically produce a shape like a "death star".) Related tasks draw a sphere draw a cuboid draw a rotating cube write language name in 3D ASCII
#Ada
Ada
with Ada.Numerics.Elementary_Functions; with Ada.Numerics.Generic_Real_Arrays;   with SDL.Video.Windows.Makers; with SDL.Video.Renderers.Makers; with SDL.Video.Palettes; with SDL.Events.Events;   procedure Death_Star is   Width  : constant := 400; Height  : constant := 400;   package Float_Arrays is new Ada.Numerics.Generic_Real_Arrays (Float); use Ada.Numerics.Elementary_Functions; use Float_Arrays;   Window  : SDL.Video.Windows.Window; Renderer : SDL.Video.Renderers.Renderer;   subtype Vector_3 is Real_Vector (1 .. 3);   type Sphere_Type is record Cx, Cy, Cz : Integer; R  : Integer; end record;   function Normalize (V : Vector_3) return Vector_3 is (V / Sqrt (V * V));   procedure Hit (S  : Sphere_Type; X, Y  : Integer; Z1, Z2 : out Float; Is_Hit : out Boolean) is NX  : constant Integer := X - S.Cx; NY  : constant Integer := Y - S.Cy; Zsq  : constant Integer := S.R * S.R - (NX * NX + NY * NY); Zsqrt : Float; begin if Zsq >= 0 then Zsqrt  := Sqrt (Float (Zsq)); Z1  := Float (S.Cz) - Zsqrt; Z2  := Float (S.Cz) + Zsqrt; Is_Hit := True; return; end if; Z1  := 0.0; Z2  := 0.0; Is_Hit := False; end Hit;   procedure Draw_Death_Star (Pos, Neg : Sphere_Type; K, Amb  : Float; Dir  : Vector_3) is Vec  : Vector_3; ZB1, ZB2 : Float; ZS1, ZS2 : Float; Is_Hit  : Boolean; S  : Float; Lum  : Integer; begin for Y in Pos.Cy - Pos.R .. Pos.Cy + Pos.R loop for X in Pos.Cx - Pos.R .. Pos.Cx + Pos.R loop Hit (Pos, X, Y, ZB1, ZB2, Is_Hit); if not Is_Hit then goto Continue; end if; Hit (Neg, X, Y, ZS1, ZS2, Is_Hit); if Is_Hit then if ZS1 > ZB1 then Is_Hit := False; elsif ZS2 > ZB2 then goto Continue; end if; end if;   if Is_Hit then Vec := (Float (Neg.Cx - X), Float (Neg.Cy - Y), Float (Neg.Cz) - ZS2); else Vec := (Float (X - Pos.Cx), Float (Y - Pos.Cy), ZB1 - Float (Pos.Cz)); end if; S := Float'Max (0.0, Dir * Normalize (Vec));   Lum := Integer (255.0 * (S ** K + Amb) / (1.0 + Amb)); Lum := Integer'Max (0, Lum); Lum := Integer'Min (Lum, 255);   Renderer.Set_Draw_Colour ((SDL.Video.Palettes.Colour_Component (Lum), SDL.Video.Palettes.Colour_Component (Lum), SDL.Video.Palettes.Colour_Component (Lum), 255)); Renderer.Draw (Point => (SDL.C.int (X + Width / 2), SDL.C.int (Y + Height / 2))); <<Continue>> end loop; end loop; end Draw_Death_Star;   procedure Wait is use type SDL.Events.Event_Types; Event : SDL.Events.Events.Events; begin loop while SDL.Events.Events.Poll (Event) loop if Event.Common.Event_Type = SDL.Events.Quit then return; end if; end loop; delay 0.100; end loop; end Wait;   Direction : constant Vector_3  := Normalize ((20.0, -40.0, -10.0)); Positive  : constant Sphere_Type := (0, 0, 0, 120); Negative  : constant Sphere_Type := (-90, -90, -30, 100); begin if not SDL.Initialise (Flags => SDL.Enable_Screen) then return; end if;   SDL.Video.Windows.Makers.Create (Win => Window, Title => "Death star", Position => SDL.Natural_Coordinates'(X => 10, Y => 10), Size => SDL.Positive_Sizes'(Width, Height), Flags => 0); SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface); Renderer.Set_Draw_Colour ((0, 0, 0, 255)); Renderer.Fill (Rectangle => (0, 0, Width, Height));   Draw_Death_Star (Positive, Negative, 1.5, 0.2, Direction); Window.Update_Surface;   Wait; Window.Finalize; SDL.Finalise; end Death_Star;
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\infty }^{\infty }F(m)H(n-m)} for all integers n {\displaystyle {\mathit {n}}} . Assume F ( n ) {\displaystyle F(n)} can be non-zero only for 0 {\displaystyle 0} ≤ n {\displaystyle {\mathit {n}}} ≤ | F | {\displaystyle |{\mathit {F}}|} , where | F | {\displaystyle |{\mathit {F}}|} is the "length" of F {\displaystyle {\mathit {F}}} , and similarly for G {\displaystyle {\mathit {G}}} and H {\displaystyle {\mathit {H}}} , so that the functions can be modeled as finite sequences by identifying f 0 , f 1 , f 2 , … {\displaystyle f_{0},f_{1},f_{2},\dots } with F ( 0 ) , F ( 1 ) , F ( 2 ) , … {\displaystyle F(0),F(1),F(2),\dots } , etc. Then for example, values of | F | = 6 {\displaystyle |{\mathit {F}}|=6} and | H | = 5 {\displaystyle |{\mathit {H}}|=5} would determine the following value of g {\displaystyle {\mathit {g}}} by definition. g 0 = f 0 h 0 g 1 = f 1 h 0 + f 0 h 1 g 2 = f 2 h 0 + f 1 h 1 + f 0 h 2 g 3 = f 3 h 0 + f 2 h 1 + f 1 h 2 + f 0 h 3 g 4 = f 4 h 0 + f 3 h 1 + f 2 h 2 + f 1 h 3 + f 0 h 4 g 5 = f 5 h 0 + f 4 h 1 + f 3 h 2 + f 2 h 3 + f 1 h 4 g 6 = f 5 h 1 + f 4 h 2 + f 3 h 3 + f 2 h 4 g 7 = f 5 h 2 + f 4 h 3 + f 3 h 4 g 8 = f 5 h 3 + f 4 h 4 g 9 = f 5 h 4 {\displaystyle {\begin{array}{lllllllllll}g_{0}&=&f_{0}h_{0}\\g_{1}&=&f_{1}h_{0}&+&f_{0}h_{1}\\g_{2}&=&f_{2}h_{0}&+&f_{1}h_{1}&+&f_{0}h_{2}\\g_{3}&=&f_{3}h_{0}&+&f_{2}h_{1}&+&f_{1}h_{2}&+&f_{0}h_{3}\\g_{4}&=&f_{4}h_{0}&+&f_{3}h_{1}&+&f_{2}h_{2}&+&f_{1}h_{3}&+&f_{0}h_{4}\\g_{5}&=&f_{5}h_{0}&+&f_{4}h_{1}&+&f_{3}h_{2}&+&f_{2}h_{3}&+&f_{1}h_{4}\\g_{6}&=&&&f_{5}h_{1}&+&f_{4}h_{2}&+&f_{3}h_{3}&+&f_{2}h_{4}\\g_{7}&=&&&&&f_{5}h_{2}&+&f_{4}h_{3}&+&f_{3}h_{4}\\g_{8}&=&&&&&&&f_{5}h_{3}&+&f_{4}h_{4}\\g_{9}&=&&&&&&&&&f_{5}h_{4}\end{array}}} We can write this in matrix form as: ( g 0 g 1 g 2 g 3 g 4 g 5 g 6 g 7 g 8 g 9 ) = ( f 0 f 1 f 0 f 2 f 1 f 0 f 3 f 2 f 1 f 0 f 4 f 3 f 2 f 1 f 0 f 5 f 4 f 3 f 2 f 1 f 5 f 4 f 3 f 2 f 5 f 4 f 3 f 5 f 4 f 5 ) ( h 0 h 1 h 2 h 3 h 4 ) {\displaystyle \left({\begin{array}{l}g_{0}\\g_{1}\\g_{2}\\g_{3}\\g_{4}\\g_{5}\\g_{6}\\g_{7}\\g_{8}\\g_{9}\\\end{array}}\right)=\left({\begin{array}{lllll}f_{0}\\f_{1}&f_{0}\\f_{2}&f_{1}&f_{0}\\f_{3}&f_{2}&f_{1}&f_{0}\\f_{4}&f_{3}&f_{2}&f_{1}&f_{0}\\f_{5}&f_{4}&f_{3}&f_{2}&f_{1}\\&f_{5}&f_{4}&f_{3}&f_{2}\\&&f_{5}&f_{4}&f_{3}\\&&&f_{5}&f_{4}\\&&&&f_{5}\end{array}}\right)\;\left({\begin{array}{l}h_{0}\\h_{1}\\h_{2}\\h_{3}\\h_{4}\\\end{array}}\right)} or g = A h {\displaystyle g=A\;h} For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by constructing and solving such a system of equations represented by the above matrix A {\displaystyle A} for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . The function should work for G {\displaystyle {\mathit {G}}} of arbitrary length (i.e., not hard coded or constant) and F {\displaystyle {\mathit {F}}} of any length up to that of G {\displaystyle {\mathit {G}}} . Note that | H | {\displaystyle |{\mathit {H}}|} will be given by | G | − | F | + 1 {\displaystyle |{\mathit {G}}|-|{\mathit {F}}|+1} . There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task. Test your solution on the following data. Be sure to verify both that deconv ( g , f ) = h {\displaystyle (g,f)=h} and deconv ( g , h ) = f {\displaystyle (g,h)=f} and display the results in a human readable form. h = [-8,-9,-3,-1,-6,7] f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
#Lua
Lua
function deconvolve(f, g) local h = setmetatable({}, {__index = function(self, n) if n == 1 then self[1] = g[1] / f[1] else self[n] = g[n] for i = 1, n - 1 do self[n] = self[n] - self[i] * (f[n - i + 1] or 0) end self[n] = self[n] / f[1] end return self[n] end}) local _ = h[#g - #f + 1] return setmetatable(h, nil) end
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Ruby
Ruby
# _orig_ is a Hash that contains an Array. orig = { :num => 1, :ary => [2, 3] } orig[:cycle] = orig # _orig_ also contains itself.   # _copy_ becomes a deep copy of _orig_. copy = Marshal.load(Marshal.dump orig)   # These changes to _orig_ never affect _copy_, # because _orig_ and _copy_ are disjoint structures. orig[:ary] << 4 orig[:rng] = (5..6)   # Because of deep copy, orig[:ary] and copy[:ary] # refer to different Arrays. p orig # => {:num=>1, :ary=>[2, 3, 4], :cycle=>{...}, :rng=>5..6} p copy # => {:num=>1, :ary=>[2, 3], :cycle=>{...}}   # The original contains itself, and the copy contains itself, # but the original and the copy are not the same object. p [(orig.equal? orig[:cycle]), (copy.equal? copy[:cycle]), (not orig.equal? copy)] # => [true, true, true]
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Rust
Rust
// The compiler can automatically implement Clone on structs (assuming all members have implemented Clone). #[derive(Clone)] struct Tree<T> { left: Leaf<T>, data: T, right: Leaf<T>, }   type Leaf<T> = Option<Box<Tree<T>>>;   impl<T> Tree<T> { fn root(data: T) -> Self { Self { left: None, data, right: None } }   fn leaf(d: T) -> Leaf<T> { Some(Box::new(Self::root(d))) } }   fn main() { let mut tree = Tree::root([4, 5, 6]); tree.right = Tree::leaf([1, 2, 3]); tree.left = Tree::leaf([7, 8, 9]);   let newtree = tree.clone(); }
http://rosettacode.org/wiki/Deal_cards_for_FreeCell
Deal cards for FreeCell
Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows. This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.) As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals. These deals are numbered from 1 to 32000. Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range. The algorithm uses this linear congruential generator from Microsoft C: s t a t e n + 1 ≡ 214013 × s t a t e n + 2531011 ( mod 2 31 ) {\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}} r a n d n = s t a t e n ÷ 2 16 {\displaystyle rand_{n}=state_{n}\div 2^{16}} r a n d n {\displaystyle rand_{n}} is in range 0 to 32767. Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages. The algorithm follows: Seed the RNG with the number of the deal. Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51. Until the array is empty: Choose a random card at index ≡ next random number (mod array length). Swap this random card with the last card of the array. Remove this random card from the array. (Array length goes down by 1.) Deal this random card. Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on. Order to deal cards Game #1 Game #617 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 JD 2D 9H JC 5D 7H 7C 5H KD KC 9S 5S AD QC KH 3H 2S KS 9D QD JS AS AH 3C 4C 5C TS QH 4H AC 4D 7S 3S TD 4S TH 8H 2C JH 7D 6D 8S 8D QS 6C 3D 8C TC 6S 9C 2H 6H 7D AD 5C 3S 5S 8C 2D AH TD 7S QD AC 6D 8H AS KH TH QC 3H 9D 6S 8D 3D TC KD 5H 9S 3C 8S 7H 4D JS 4C QS 9C 9H 7C 6H 2C 2S 4S TS 2H 5D JC 6C JH QH JD KS KC 4H Deals can also be checked against FreeCell solutions to 1000000 games. (Summon a video solution, and it displays the initial deal.) Write a program to take a deal number and deal cards in the same order as this algorithm. The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way. Related tasks: Playing cards Card shuffles War Card_Game Poker hand_analyser Go Fish
#11l
11l
F randomGenerator(=seed, n) [Int] r -V max_int32 = 7FFF'FFFF seed = seed [&] max_int32   L r.len < n seed = (seed * 214013 + 2531011) [&] max_int32 r [+]= seed >> 16   R r   F deal(seed) V nc = 52 V cards = Array((nc - 1 .< -1).step(-1)) V rnd = randomGenerator(seed, nc) L(r) rnd V j = (nc - 1) - r % (nc - L.index) swap(&cards[L.index], &cards[j]) R cards   F show(cards) V l = cards.map(c -> ‘A23456789TJQK’[Int(c / 4)]‘’‘CDHS’[c % 4]) L(i) (0 .< cards.len).step(8) print((l[i .< i + 8]).join(‘ ’))   :start: V seed = I :argv.len == 2 {Int(:argv[1])} E 11982 print(‘Hand #.’.format(seed)) V deck = deal(seed) show(deck)
http://rosettacode.org/wiki/De_Bruijn_sequences
de Bruijn sequences
The sequences are named after the Dutch mathematician   Nicolaas Govert de Bruijn. A note on Dutch capitalization:   Nicolaas' last name is   de Bruijn,   the   de   isn't normally capitalized unless it's the first word in a sentence.   Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be capitalized. In combinatorial mathematics,   a   de Bruijn sequence   of order   n   on a   size-k   alphabet (computer science)   A   is a cyclic sequence in which every possible   length-n   string (computer science, formal theory)   on   A   occurs exactly once as a contiguous substring. Such a sequence is denoted by   B(k, n)   and has length   kn,   which is also the number of distinct substrings of length   n   on   A;     de Bruijn sequences are therefore optimally short. There are: (k!)k(n-1)   ÷   kn distinct de Bruijn sequences   B(k, n). Task For this Rosetta Code task,   a   de Bruijn   sequence is to be generated that can be used to shorten a brute-force attack on a   PIN-like   code lock that does not have an "enter" key and accepts the last   n   digits entered. Note:   automated teller machines (ATMs)   used to work like this,   but their software has been updated to not allow a brute-force attack. Example A   digital door lock   with a 4-digit code would have B (10, 4) solutions,   with a length of   10,000   (digits). Therefore, only at most     10,000 + 3     (as the solutions are cyclic or wrap-around)   presses are needed to open the lock. Trying all 4-digit codes separately would require   4 × 10,000   or   40,000   presses. Task requirements   Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.   Show the length of the generated de Bruijn sequence.   (There are many possible de Bruijn sequences that solve this task,   one solution is shown on the discussion page).   Show the first and last   130   digits of the de Bruijn sequence.   Verify that all four-digit (decimal)   1,000   PIN codes are contained within the de Bruijn sequence.   0000, 0001, 0002, 0003,   ...   9996, 9997, 9998, 9999   (note the leading zeros).   Reverse the de Bruijn sequence.   Again, perform the (above) verification test.   Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.   Perform the verification test (again).   There should be four PIN codes missing. (The last requirement is to ensure that the verification tests performs correctly.   The verification processes should list any and all missing PIN codes.) Show all output here, on this page. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet References   Wikipedia entry:   de Bruijn sequence.   MathWorld entry:   de Bruijn sequence.   An  OEIS  entry:   A166315 lexicographically earliest binary de Bruijn sequences, B(2,n)     --- Not B(10,4),   but possibly relevant.
#8080_Assembly
8080 Assembly
bdos: equ 5 ; BDOS entry point putch: equ 2 ; Write character to console puts: equ 9 ; Write string to console org 100h lhld bdos+1 ; Put stack at highest usable address sphl ;;; Generate de_bruijn(10,4) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; mvi c,40 ; Zero out a[] xra a lxi d,arr zloop: stax d inx d dcr c jnz zloop lxi h,seq ; H = start of sequence lxi b,0101h ; db(1,1) call db_ lxi d,seq ; Allow wrap-around by appending first 3 digits mvi c,3 wrap: ldax d ; get one of first digits mov m,a ; store after last digit inx d ; advance pointers inx h dcr c ; do this 3 times jnz wrap push h ; store end of data ;;; Print length ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; lxi d,slen ; print "Length: " call pstr lxi d,-seq ; calculate length (-seq+seqEnd) dad d call puthl ; print length call pnl ; print newline ;;; Print first and last 130 digits ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; lxi d,sfrst ; print "First 130: " call pstr lxi h,seq ; print first 130 digits call p130 call pnl ; print newline lxi d,slast ; print "Last 130: " call pstr pop h ; Get end of sequence push h lxi d,-130 ; 130th last digit dad d call p130 ; print last 130 digits call pnl call verify ; verify that all numbers are there ;;; Reverse and verify ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; lxi d,srev ; Print "reversing..." call pstr pop h ; HL = address of last digit dcx h push h ; stack = address of last digit lxi d,seq ; DE = address of first digit call rvrs ; Reverse call verify ; Verify that all numbers are there lxi d,seq ; Then reverse again (restoring it) pop h call rvrs ;;; Replace 4444th digit with '.' and verify ;;;;;;;;;;;;;;;;;;;;;; lxi d,s4444 call pstr mvi a,'.' sta seq+4444 call verify rst 0 ;;; db(t,p); t,p in B,C; end of sequence in HL ;;;;;;;;;;;;;;;;;;;; db_: mov a,b ; if t>n (n=4) cpi 5 ; t >= n+1 jc dbelse mov a,c ; 4%p==0, for p in {1,2,3,4}, is false iff p=3 cpi 3 rz ; stop if p=3, i.e. 4%p<>0 lxi d,arr+1 ; copy P elements to seq forom arr[1..] dbextn: ldax d ; take from a[] mov m,a ; store in sequence inx h ; advance pointers inx d dcr c ; and do this P times jnz dbextn ret dbelse: mov a,b ; t - p sub c mvi d,arr/256 mov e,a ; a[] is page-aligned for easier indexing ldax d ; get a[t-p] mov e,b ; store in a[t] stax d push b ; keep T and P inr b ; db(t+1, p) call db_ pop b ; restore T and P mov a,b ; get a[t-p] sub c mvi d,arr/256 mov e,a ldax d ; j = a[t-p] dbloop: inr a ; j++ cpi 10 ; reached K = 10? rnc ; then stop mvi d,arr/256 mov e,b stax d ; a[t] = j push psw ; keep j push b ; keep t and p mov c,b inr b call db_ ; db(t+1, t) pop b ; restore t and p pop psw ; restore j jmp dbloop ;;; Verify that all numbers are there ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; verify: lxi d,sver ; print "Verifying... " call pstr mvi d,0 ; Zero out the flag array lxi b,10000 lxi h,val vzero: mov m,d inx h dcx b mov a,b ora c jnz vzero lxi h,seq ; Sequence pointer donum: push h ; Store sequence pointer push h ; Push two copies lxi h,0 ; Current 4-digit number mvi c,4 ; Number has 4 digits dgtadd: mov d,h ; HL *= 10 mov e,l dad h dad h dad d dad h xthl ; Get sequence pointer mov a,m ; Get digit inx h ; Advance pointer cpi 10 ; Valid digit? jnc dinval ; If not, go do next 4-digit number xthl ; Back to number mov e,a mvi d,0 dad d ; Add digit to number dcr c ; More digits? jnz dgtadd ; Then get digit lxi d,val ; HL is now the current 4-digit number dad d inr m ; val[HL]++ (we've seen it) dinval: pop h ; Pointer to after last valid digit pop h ; Pointer to start of current number inx h ; Get 4-digit number that starts at next digit mov d,h ; Next pointer in DE mov e,l lxi b,-(seq+10000) ; Are we there yet? dad b mov a,h ora l xchg ; Next pointer back in HL jnz donum ; If not done, do next number. lxi h,val ; Done - get start of validation array mvi b,0 ; B will be set if one is missing vnum: mov a,m ; Have we seen HL-val? ana a jnz vnext ; If so, do the next number push h ; Otherwise, keep current address, lxi d,-val ; Subtract val (to get the number) dad d call puthl ; Print this number as being missing mvi b,1 ; Set B, pop h ; and then restore the address vnext: inx h ; Increment the number push h lxi d,-(val+10000) ; Are we there yet? dad d mov a,h ora l pop h jnz vnum ; If not, check next number. dcr b ; At the end, if B was not set, lxi d,snone ; print "none missing", jnz pstr lxi d,smiss ; otherwise, print "missing" jmp pstr ;;; Subroutines ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; reverse memory starting at DE and ending at HL rvrs: mov b,m ; Load [HL] ldax d ; Load [DE] mov m,a ; [HL] = old [DE] mov a,b stax d ; [DE] = old [HL] inx d ; Move bottom pointer upwards, dcx h ; Move top pointer downwards, mov a,d ; D<H = not there yet cmp h jc rvrs mov a,e ; E<L = not there yet cmp l jc rvrs ret ;;; print number in HL, saving registers puthl: push h ; save registers push d push b lxi b,nbuf ; number buffer pointer push b ; keep it on the stack dgt: lxi b,-10 lxi d,-1 dgtdiv: inx d ; calculate digit dad b jc dgtdiv mvi a,'0'+10 add l pop h ; get pointer from stack dcx h ; go to previous digit mov m,a ; store digit push h ; put pointer back xchg ; are there any more digits? mov a,h ora l jnz dgt ; if so, calculate next digit pop d ; otherwise, get pointer to first digit jmp pstr_ ; and print the resulting string ;;; print 130 digits from the sequence, starting at HL p130: push h push d push b mvi b,130 ; 130 digits p130l: mov a,m ; get current digit adi '0' ; make ASCII inx h ; advance pointer push b ; save pointer and counter push h mvi c,putch ; print character mov e,a call bdos pop h ; restore pointer and counter pop b dcr b ; one fewer character left jnz p130l ; if characters left, print next jmp rsreg ; otherwise, restore registers and return ;;; print newline pnl: lxi d,snl ;;; print string in DE, saving registers pstr: push h ; store registers push d push b pstr_: mvi c,puts ; print string using CP/M call bdos rsreg: pop b ; restore registers pop d pop h ret snl: db 13,10,'$' slen: db 'Length: $' sfrst: db 'First 130: $' slast: db 'Last 130: $' srev: db 'Reversing...',13,10,'$' s4444: db 'Set seq[4444] to `.`...',13,10,'$' sver: db 'Verifying... $' snone: db 'none ' smiss: db 'missing',13,10,'$' db '00000' ; number output buffer nbuf: db ' $' arr: equ ($/256+1)*256 ; Place to store a[] (page-aligned) val: equ arr+40 ; Place to store validation flags seq: equ val+10000 ; Place to store De Bruijn sequence
http://rosettacode.org/wiki/De_Bruijn_sequences
de Bruijn sequences
The sequences are named after the Dutch mathematician   Nicolaas Govert de Bruijn. A note on Dutch capitalization:   Nicolaas' last name is   de Bruijn,   the   de   isn't normally capitalized unless it's the first word in a sentence.   Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be capitalized. In combinatorial mathematics,   a   de Bruijn sequence   of order   n   on a   size-k   alphabet (computer science)   A   is a cyclic sequence in which every possible   length-n   string (computer science, formal theory)   on   A   occurs exactly once as a contiguous substring. Such a sequence is denoted by   B(k, n)   and has length   kn,   which is also the number of distinct substrings of length   n   on   A;     de Bruijn sequences are therefore optimally short. There are: (k!)k(n-1)   ÷   kn distinct de Bruijn sequences   B(k, n). Task For this Rosetta Code task,   a   de Bruijn   sequence is to be generated that can be used to shorten a brute-force attack on a   PIN-like   code lock that does not have an "enter" key and accepts the last   n   digits entered. Note:   automated teller machines (ATMs)   used to work like this,   but their software has been updated to not allow a brute-force attack. Example A   digital door lock   with a 4-digit code would have B (10, 4) solutions,   with a length of   10,000   (digits). Therefore, only at most     10,000 + 3     (as the solutions are cyclic or wrap-around)   presses are needed to open the lock. Trying all 4-digit codes separately would require   4 × 10,000   or   40,000   presses. Task requirements   Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.   Show the length of the generated de Bruijn sequence.   (There are many possible de Bruijn sequences that solve this task,   one solution is shown on the discussion page).   Show the first and last   130   digits of the de Bruijn sequence.   Verify that all four-digit (decimal)   1,000   PIN codes are contained within the de Bruijn sequence.   0000, 0001, 0002, 0003,   ...   9996, 9997, 9998, 9999   (note the leading zeros).   Reverse the de Bruijn sequence.   Again, perform the (above) verification test.   Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.   Perform the verification test (again).   There should be four PIN codes missing. (The last requirement is to ensure that the verification tests performs correctly.   The verification processes should list any and all missing PIN codes.) Show all output here, on this page. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet References   Wikipedia entry:   de Bruijn sequence.   MathWorld entry:   de Bruijn sequence.   An  OEIS  entry:   A166315 lexicographically earliest binary de Bruijn sequences, B(2,n)     --- Not B(10,4),   but possibly relevant.
#8086_Assembly
8086 Assembly
putch: equ 2 ; Print character puts: equ 9 ; Print string cpu 8086 bits 16 section .text org 100h ;;; Calculate de_bruijn(10, 4) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; xor ax,ax ; zero a[] mov di,arr mov cx,20 ; 20 words = 40 bytes rep stosw mov di,seq ; start of sequence mov dx,0101h ; db(1,1) call db_ mov si,seq ; Add first 3 to end for wrapping mov cx,3 rep movsb lea bp,[di-1] ; Store pointer to last digit in BP ;;; Print length ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; mov ah,puts ; Print "Length:" mov dx,slen int 21h mov ax,di ; Length = end - start sub ax,seq call putax ; Print length ;;; Print first and last 130 characters and verify ;;;;;;;;;;;;;;;; mov ah,puts ; Print "First 130..." mov dx,sfrst int 21h mov si,seq ; print first 130 digits call p130 mov ah,puts ; Print "Last 130..." mov dx,slast int 21h mov si,di ; print last 130 digit sub si,130 call p130 call verify ;;;; Reverse the sequence and verify ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; mov ah,puts ; Print "Reversing..." mov dx,srev int 21h mov si,seq ; SI = first digit in sequence mov di,bp ; DI = last digit in sequence call rvrs ; Reverse call verify ; Verify mov si,seq ; Reverse again, putting it back mov di,bp call rvrs ;;; Set seq[4444] to '.' and verify ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; mov ah,puts ; Print "set seq[4444] to '.'" mov dx,s4444 int 21h mov [seq+4444],byte '.' call verify ; Verify ret ;;; db(t, p); t=dh p=dl, di=seq ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; db_: cmp dh,4 ; t>n? (n=4) jbe .els cmp dl,3 ; for p in {1,2,3,4}, 4%p==0 iff p=3 je .out mov si,arr+1 ; add DL=P bytes from a[1..] to sequence mov cl,dl xor ch,ch rep movsb jmp .out .els: xor bh,bh mov bl,dh sub bl,dl ; t - p mov al,[arr+bx] ; al = a[t-p] mov bl,dh ; t mov [arr+bx],al ; a[t] = al push dx ; keep arguments inc dh ; db(++t,p) call db_ pop dx ; restore arguments mov bl,dh ; al = a[t-p] sub bl,dl mov al,[arr+bx] .loop: inc al ; al++ cmp al,10 ; when al>=k, jae .out ; then stop. mov bl,dh mov [arr+bx],al ; a[t] = j push ax ; keep state push dx mov dl,dh ; db(t+1, t) inc dh call db_ pop dx pop ax jmp .loop .out: ret ;;; Verify that all numbers are there ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; verify: mov ah,puts ; Print "verifying..." mov dx,sver int 21h mov di,val ; Zero validation array mov cx,5000 ; 10000 bytes = 5000 words xor ax,ax rep stosw mov di,val mov si,seq ; Pointer to start of sequence mov cx,6409h ; CH=100 (multiplier), CL=9 (highest digit) .num: mov ax,[si] ; Read first two digits cmp ah,cl ; Check that they are valid ja .inval cmp al,cl ja .inval xchg al,ah ; High digit * 10 + low digit aad mul ch ; Multiply by 100 (to add in next two) mov bx,ax mov ax,[si+2] ; Read last two digits cmp ah,cl ; Check that they are valid ja .inval cmp al,cl ja .inval xchg al,ah ; High digit * 10 + low digit aad add bx,ax ; BX = final 4-digit number inc byte [di+bx] ; Mark this 4-digit number as seen .inval: inc si ; Next digit cmp si,seq+10000 ; Are we at the end yet? jne .num ; If not, do next number mov si,val ; For each number < 10000, check if it's there xor cl,cl ; Will be set if a number is missing .test: lodsb ; Do we have this number? test al,al jnz .tnext ; If so, try next number mov ax,si ; Otherwise, print the missing number sub ax,val call putax mov cl,1 ; And set CL .tnext: cmp si,val+10000 ; Are we at the end yet? jne .test test cl,cl mov dx,smiss ; Print "... missing" jnz .print ; if CL is set mov dx,snone ; or "none missing" otherwise. .print: mov ah,puts int 21h ret ;;; Subroutines ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Print number in AX putax: push ax ; Keep registers we're changing push dx push bx push di mov di,numbuf ; Pointer to number buffer mov bx,10 ; Divisor .digit: xor dx,dx ; Divide AX by 10 div bx add dl,'0' ; Add '0' to remainder (digit) dec di ; Store digit in buffer mov [di],dl test ax,ax ; Any more digits? jnz .digit ; If so, do next digits mov dx,di ; At the end, print the string mov ah,puts int 21h pop di ; Restore registers pop bx pop dx pop ax ret ;;; Print 130 digits starting at SI p130: mov cx,130 ; 130 characters mov ah,putch ; Print characters .loop: lodsb ; Get digit add al,'0' ; Make ASCII mov dl,al ; Print digit int 21h loop .loop ret ;;; Reverse memory starting at SI and ending at DI rvrs: mov al,[si] ; Load [SI], mov ah,[di] ; Load [DI], mov [di],al ; Set [DI] = old [SI] mov [si],ah ; Set [SI] = old [DI] inc si ; Increment bottom pointer dec di ; Decrement top pointer cmp si,di ; If SI >= DI, we're done jb rvrs ret section .data slen: db 'Length: $' sfrst: db 13,10,'First 130: $' slast: db 13,10,'Last 130: $' srev: db 13,10,'Reversing... $' s4444: db 13,10,'Set seq[4444] to `.`...$' sver: db 13,10,'Verifying... $' snone: db 'none ' smiss: db 'missing.$' db '00000' numbuf: db ' $' section .bss arr: resb 40 ; a[] val: resb 10000 ; validation array seq: equ $
http://rosettacode.org/wiki/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#Delphi
Delphi
type TinyInt(Integer value) { throw @Overflow(value) when value is <1 or >10 } with Lookup, Show   func TinyInt as Integer => this.value   func TinyInt + (other) => TinyInt(this.value + other as Integer)   func TinyInt * (other) => TinyInt(this.value * other as Integer)   func TinyInt - (other) => TinyInt(this.value - other as Integer)   func TinyInt / (other) => TinyInt(this.value / other as Integer)
http://rosettacode.org/wiki/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#Dyalect
Dyalect
type TinyInt(Integer value) { throw @Overflow(value) when value is <1 or >10 } with Lookup, Show   func TinyInt as Integer => this.value   func TinyInt + (other) => TinyInt(this.value + other as Integer)   func TinyInt * (other) => TinyInt(this.value * other as Integer)   func TinyInt - (other) => TinyInt(this.value - other as Integer)   func TinyInt / (other) => TinyInt(this.value / other as Integer)
http://rosettacode.org/wiki/Death_Star
Death Star
Task Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction. (This will basically produce a shape like a "death star".) Related tasks draw a sphere draw a cuboid draw a rotating cube write language name in 3D ASCII
#AutoHotkey
AutoHotkey
#NoEnv SetBatchLines, -1 #SingleInstance, Force   ; Uncomment if Gdip.ahk is not in your standard library #Include, Gdip.ahk   ; Settings X := 200, Y := 200, Width := 200, Height := 200 ; Location and size of sphere rotation := 60 ; degrees ARGB := 0xFFFF0000 ; Color=Solid Red   If !pToken := Gdip_Startup() ; Start gdi+ { MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system ExitApp } OnExit, Exit   Gui, -Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs ; Create GUI Gui, Show, NA ; Show GUI hwnd1 := WinExist() ; Get a handle to this window we have created in order to update it later hbm := CreateDIBSection(A_ScreenWidth, A_ScreenHeight) ; Create a gdi bitmap drawing area hdc := CreateCompatibleDC() ; Get a device context compatible with the screen obm := SelectObject(hdc, hbm) ; Select the bitmap into the device context pGraphics := Gdip_GraphicsFromHDC(hdc) ; Get a pointer to the graphics of the bitmap, for use with drawing functions Gdip_SetSmoothingMode(pGraphics, 4) ; Set the smoothing mode to antialias = 4 to make shapes appear smother   Gdip_TranslateWorldTransform(pGraphics, X, Y) Gdip_RotateWorldTransform(pGraphics, rotation)   ; Base ellipse pBrush := Gdip_CreateLineBrushFromRect(0, 0, Width, Height, ARGB, 0xFF000000) Gdip_FillEllipse(pGraphics, pBrush, 0, 0, Width, Height)   ; First highlight ellipse pBrush := Gdip_CreateLineBrushFromRect(Width*0.1, Height*0.01, Width*0.8, Height*0.6, 0x33FFFFFF, 0x00FFFFFF) Gdip_FillEllipse(pGraphics, pBrush, Width*0.1, Height*0.01, Width*0.8, Height*0.6)   ; Second highlight ellipse pBrush := Gdip_CreateLineBrushFromRect(Width*0.3, Height*0.02, Width*0.3, Height*0.2, 0xBBFFFFFF, 0x00FFFFFF) Gdip_FillEllipse(pGraphics, pBrush, Width*0.3, Height*0.02, Width*0.3, Height*0.2)     ; Reset variables for smaller subtracted sphere X-=150 Y-=10 Width*=0.5 Height*=0.4 rotation-=180   Gdip_TranslateWorldTransform(pGraphics, X, Y) Gdip_RotateWorldTransform(pGraphics, rotation)   ; Base ellipse pBrush := Gdip_CreateLineBrushFromRect(0, 0, Width, Height, ARGB, 0xFF000000) Gdip_FillEllipse(pGraphics, pBrush, 0, 0, Width, Height)   ; First highlight ellipse pBrush := Gdip_CreateLineBrushFromRect(Width*0.1, Height*0.01, Width*0.8, Height*0.6, 0x33FFFFFF, 0x00FFFFFF) Gdip_FillEllipse(pGraphics, pBrush, Width*0.1, Height*0.01, Width*0.8, Height*0.6)   ; Second highlight ellipse pBrush := Gdip_CreateLineBrushFromRect(Width*0.3, Height*0.02, Width*0.3, Height*0.2, 0xBBFFFFFF, 0x00FFFFFF) Gdip_FillEllipse(pGraphics, pBrush, Width*0.3, Height*0.02, Width*0.3, Height*0.2)     UpdateLayeredWindow(hwnd1, hdc, 0, 0, A_ScreenWidth, A_ScreenHeight) SelectObject(hdc, obm) ; Select the object back into the hdc Gdip_DeletePath(Path) Gdip_DeleteBrush(pBrush) DeleteObject(hbm) ; Now the bitmap may be deleted DeleteDC(hdc) ; Also the device context related to the bitmap may be deleted Gdip_DeleteGraphics(G) ; The graphics may now be deleted Return   Exit: ; gdi+ may now be shutdown on exiting the program Gdip_Shutdown(pToken) ExitApp
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\infty }^{\infty }F(m)H(n-m)} for all integers n {\displaystyle {\mathit {n}}} . Assume F ( n ) {\displaystyle F(n)} can be non-zero only for 0 {\displaystyle 0} ≤ n {\displaystyle {\mathit {n}}} ≤ | F | {\displaystyle |{\mathit {F}}|} , where | F | {\displaystyle |{\mathit {F}}|} is the "length" of F {\displaystyle {\mathit {F}}} , and similarly for G {\displaystyle {\mathit {G}}} and H {\displaystyle {\mathit {H}}} , so that the functions can be modeled as finite sequences by identifying f 0 , f 1 , f 2 , … {\displaystyle f_{0},f_{1},f_{2},\dots } with F ( 0 ) , F ( 1 ) , F ( 2 ) , … {\displaystyle F(0),F(1),F(2),\dots } , etc. Then for example, values of | F | = 6 {\displaystyle |{\mathit {F}}|=6} and | H | = 5 {\displaystyle |{\mathit {H}}|=5} would determine the following value of g {\displaystyle {\mathit {g}}} by definition. g 0 = f 0 h 0 g 1 = f 1 h 0 + f 0 h 1 g 2 = f 2 h 0 + f 1 h 1 + f 0 h 2 g 3 = f 3 h 0 + f 2 h 1 + f 1 h 2 + f 0 h 3 g 4 = f 4 h 0 + f 3 h 1 + f 2 h 2 + f 1 h 3 + f 0 h 4 g 5 = f 5 h 0 + f 4 h 1 + f 3 h 2 + f 2 h 3 + f 1 h 4 g 6 = f 5 h 1 + f 4 h 2 + f 3 h 3 + f 2 h 4 g 7 = f 5 h 2 + f 4 h 3 + f 3 h 4 g 8 = f 5 h 3 + f 4 h 4 g 9 = f 5 h 4 {\displaystyle {\begin{array}{lllllllllll}g_{0}&=&f_{0}h_{0}\\g_{1}&=&f_{1}h_{0}&+&f_{0}h_{1}\\g_{2}&=&f_{2}h_{0}&+&f_{1}h_{1}&+&f_{0}h_{2}\\g_{3}&=&f_{3}h_{0}&+&f_{2}h_{1}&+&f_{1}h_{2}&+&f_{0}h_{3}\\g_{4}&=&f_{4}h_{0}&+&f_{3}h_{1}&+&f_{2}h_{2}&+&f_{1}h_{3}&+&f_{0}h_{4}\\g_{5}&=&f_{5}h_{0}&+&f_{4}h_{1}&+&f_{3}h_{2}&+&f_{2}h_{3}&+&f_{1}h_{4}\\g_{6}&=&&&f_{5}h_{1}&+&f_{4}h_{2}&+&f_{3}h_{3}&+&f_{2}h_{4}\\g_{7}&=&&&&&f_{5}h_{2}&+&f_{4}h_{3}&+&f_{3}h_{4}\\g_{8}&=&&&&&&&f_{5}h_{3}&+&f_{4}h_{4}\\g_{9}&=&&&&&&&&&f_{5}h_{4}\end{array}}} We can write this in matrix form as: ( g 0 g 1 g 2 g 3 g 4 g 5 g 6 g 7 g 8 g 9 ) = ( f 0 f 1 f 0 f 2 f 1 f 0 f 3 f 2 f 1 f 0 f 4 f 3 f 2 f 1 f 0 f 5 f 4 f 3 f 2 f 1 f 5 f 4 f 3 f 2 f 5 f 4 f 3 f 5 f 4 f 5 ) ( h 0 h 1 h 2 h 3 h 4 ) {\displaystyle \left({\begin{array}{l}g_{0}\\g_{1}\\g_{2}\\g_{3}\\g_{4}\\g_{5}\\g_{6}\\g_{7}\\g_{8}\\g_{9}\\\end{array}}\right)=\left({\begin{array}{lllll}f_{0}\\f_{1}&f_{0}\\f_{2}&f_{1}&f_{0}\\f_{3}&f_{2}&f_{1}&f_{0}\\f_{4}&f_{3}&f_{2}&f_{1}&f_{0}\\f_{5}&f_{4}&f_{3}&f_{2}&f_{1}\\&f_{5}&f_{4}&f_{3}&f_{2}\\&&f_{5}&f_{4}&f_{3}\\&&&f_{5}&f_{4}\\&&&&f_{5}\end{array}}\right)\;\left({\begin{array}{l}h_{0}\\h_{1}\\h_{2}\\h_{3}\\h_{4}\\\end{array}}\right)} or g = A h {\displaystyle g=A\;h} For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by constructing and solving such a system of equations represented by the above matrix A {\displaystyle A} for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . The function should work for G {\displaystyle {\mathit {G}}} of arbitrary length (i.e., not hard coded or constant) and F {\displaystyle {\mathit {F}}} of any length up to that of G {\displaystyle {\mathit {G}}} . Note that | H | {\displaystyle |{\mathit {H}}|} will be given by | G | − | F | + 1 {\displaystyle |{\mathit {G}}|-|{\mathit {F}}|+1} . There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task. Test your solution on the following data. Be sure to verify both that deconv ( g , f ) = h {\displaystyle (g,f)=h} and deconv ( g , h ) = f {\displaystyle (g,h)=f} and display the results in a human readable form. h = [-8,-9,-3,-1,-6,7] f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
  deconv[f_List, g_List] := Module[{A = SparseArray[ Table[Band[{n, 1}] -> f[[n]], {n, 1, Length[f]}], {Length[g], Length[f] - 1}]}, Take[LinearSolve[A, g], Length[g] - Length[f] + 1]]  
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\infty }^{\infty }F(m)H(n-m)} for all integers n {\displaystyle {\mathit {n}}} . Assume F ( n ) {\displaystyle F(n)} can be non-zero only for 0 {\displaystyle 0} ≤ n {\displaystyle {\mathit {n}}} ≤ | F | {\displaystyle |{\mathit {F}}|} , where | F | {\displaystyle |{\mathit {F}}|} is the "length" of F {\displaystyle {\mathit {F}}} , and similarly for G {\displaystyle {\mathit {G}}} and H {\displaystyle {\mathit {H}}} , so that the functions can be modeled as finite sequences by identifying f 0 , f 1 , f 2 , … {\displaystyle f_{0},f_{1},f_{2},\dots } with F ( 0 ) , F ( 1 ) , F ( 2 ) , … {\displaystyle F(0),F(1),F(2),\dots } , etc. Then for example, values of | F | = 6 {\displaystyle |{\mathit {F}}|=6} and | H | = 5 {\displaystyle |{\mathit {H}}|=5} would determine the following value of g {\displaystyle {\mathit {g}}} by definition. g 0 = f 0 h 0 g 1 = f 1 h 0 + f 0 h 1 g 2 = f 2 h 0 + f 1 h 1 + f 0 h 2 g 3 = f 3 h 0 + f 2 h 1 + f 1 h 2 + f 0 h 3 g 4 = f 4 h 0 + f 3 h 1 + f 2 h 2 + f 1 h 3 + f 0 h 4 g 5 = f 5 h 0 + f 4 h 1 + f 3 h 2 + f 2 h 3 + f 1 h 4 g 6 = f 5 h 1 + f 4 h 2 + f 3 h 3 + f 2 h 4 g 7 = f 5 h 2 + f 4 h 3 + f 3 h 4 g 8 = f 5 h 3 + f 4 h 4 g 9 = f 5 h 4 {\displaystyle {\begin{array}{lllllllllll}g_{0}&=&f_{0}h_{0}\\g_{1}&=&f_{1}h_{0}&+&f_{0}h_{1}\\g_{2}&=&f_{2}h_{0}&+&f_{1}h_{1}&+&f_{0}h_{2}\\g_{3}&=&f_{3}h_{0}&+&f_{2}h_{1}&+&f_{1}h_{2}&+&f_{0}h_{3}\\g_{4}&=&f_{4}h_{0}&+&f_{3}h_{1}&+&f_{2}h_{2}&+&f_{1}h_{3}&+&f_{0}h_{4}\\g_{5}&=&f_{5}h_{0}&+&f_{4}h_{1}&+&f_{3}h_{2}&+&f_{2}h_{3}&+&f_{1}h_{4}\\g_{6}&=&&&f_{5}h_{1}&+&f_{4}h_{2}&+&f_{3}h_{3}&+&f_{2}h_{4}\\g_{7}&=&&&&&f_{5}h_{2}&+&f_{4}h_{3}&+&f_{3}h_{4}\\g_{8}&=&&&&&&&f_{5}h_{3}&+&f_{4}h_{4}\\g_{9}&=&&&&&&&&&f_{5}h_{4}\end{array}}} We can write this in matrix form as: ( g 0 g 1 g 2 g 3 g 4 g 5 g 6 g 7 g 8 g 9 ) = ( f 0 f 1 f 0 f 2 f 1 f 0 f 3 f 2 f 1 f 0 f 4 f 3 f 2 f 1 f 0 f 5 f 4 f 3 f 2 f 1 f 5 f 4 f 3 f 2 f 5 f 4 f 3 f 5 f 4 f 5 ) ( h 0 h 1 h 2 h 3 h 4 ) {\displaystyle \left({\begin{array}{l}g_{0}\\g_{1}\\g_{2}\\g_{3}\\g_{4}\\g_{5}\\g_{6}\\g_{7}\\g_{8}\\g_{9}\\\end{array}}\right)=\left({\begin{array}{lllll}f_{0}\\f_{1}&f_{0}\\f_{2}&f_{1}&f_{0}\\f_{3}&f_{2}&f_{1}&f_{0}\\f_{4}&f_{3}&f_{2}&f_{1}&f_{0}\\f_{5}&f_{4}&f_{3}&f_{2}&f_{1}\\&f_{5}&f_{4}&f_{3}&f_{2}\\&&f_{5}&f_{4}&f_{3}\\&&&f_{5}&f_{4}\\&&&&f_{5}\end{array}}\right)\;\left({\begin{array}{l}h_{0}\\h_{1}\\h_{2}\\h_{3}\\h_{4}\\\end{array}}\right)} or g = A h {\displaystyle g=A\;h} For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by constructing and solving such a system of equations represented by the above matrix A {\displaystyle A} for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . The function should work for G {\displaystyle {\mathit {G}}} of arbitrary length (i.e., not hard coded or constant) and F {\displaystyle {\mathit {F}}} of any length up to that of G {\displaystyle {\mathit {G}}} . Note that | H | {\displaystyle |{\mathit {H}}|} will be given by | G | − | F | + 1 {\displaystyle |{\mathit {G}}|-|{\mathit {F}}|+1} . There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task. Test your solution on the following data. Be sure to verify both that deconv ( g , f ) = h {\displaystyle (g,f)=h} and deconv ( g , h ) = f {\displaystyle (g,h)=f} and display the results in a human readable form. h = [-8,-9,-3,-1,-6,7] f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
#MATLAB
MATLAB
>> h = [-8,-9,-3,-1,-6,7]; >> g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]; >> f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1]; >> deconv(g,f)   ans =   -8.0000 -9.0000 -3.0000 -1.0000 -6.0000 7.0000   >> deconv(g,h)   ans =   -3 -6 -1 8 -6 3 -1 -9 -9 3 -2 5 2 -2 -7 -1
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Scheme
Scheme
  (define (deep-copy-1 exp) ;; basic version that copies an arbitrary tree made up of pairs (cond ((pair? exp) (cons (deep-copy-1 (car exp)) (deep-copy-1 (cdr exp)))) ;; cases for extra container data types can be ;; added here, like vectors and so on (else ;; atomic objects (if (string? exp) (string-copy exp) exp))))   (define (deep-copy-2 exp) (let ((sharing (make-hash-table))) (let loop ((exp exp)) (cond ((pair? exp) (cond ((get-hash-table sharing exp #f) => (lambda (copy) copy)) (else (let ((res (cons #f #f))) (put-hash-table! sharing exp res) (set-car! res (loop (car exp))) (set-cdr! res (loop (cdr exp))) res)))) (else (if (string? exp) (string-copy exp) exp))))))   (define t1 '(a b c d)) (define t2 (list #f)) (set-car! t2 t2) (define t2b (list #f)) (set-car! t2b t2b) (define t3 (list #f #f)) (set-car! t3 t3) (set-car! (cdr t3) t3) (define t4 (list t2 t2b))   ;> (print-graph #t) ;> (deep-copy-2 t1) ;(a b c d) ;> (deep-copy-2 t2) ;#0=(#0#) ;> (deep-copy-2 t3) ;#0=(#0# #0#) ;> (deep-copy-2 t4) ;(#0=(#0#) #1=(#1#))  
http://rosettacode.org/wiki/Deal_cards_for_FreeCell
Deal cards for FreeCell
Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows. This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.) As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals. These deals are numbered from 1 to 32000. Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range. The algorithm uses this linear congruential generator from Microsoft C: s t a t e n + 1 ≡ 214013 × s t a t e n + 2531011 ( mod 2 31 ) {\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}} r a n d n = s t a t e n ÷ 2 16 {\displaystyle rand_{n}=state_{n}\div 2^{16}} r a n d n {\displaystyle rand_{n}} is in range 0 to 32767. Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages. The algorithm follows: Seed the RNG with the number of the deal. Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51. Until the array is empty: Choose a random card at index ≡ next random number (mod array length). Swap this random card with the last card of the array. Remove this random card from the array. (Array length goes down by 1.) Deal this random card. Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on. Order to deal cards Game #1 Game #617 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 JD 2D 9H JC 5D 7H 7C 5H KD KC 9S 5S AD QC KH 3H 2S KS 9D QD JS AS AH 3C 4C 5C TS QH 4H AC 4D 7S 3S TD 4S TH 8H 2C JH 7D 6D 8S 8D QS 6C 3D 8C TC 6S 9C 2H 6H 7D AD 5C 3S 5S 8C 2D AH TD 7S QD AC 6D 8H AS KH TH QC 3H 9D 6S 8D 3D TC KD 5H 9S 3C 8S 7H 4D JS 4C QS 9C 9H 7C 6H 2C 2S 4S TS 2H 5D JC 6C JH QH JD KS KC 4H Deals can also be checked against FreeCell solutions to 1000000 games. (Summon a video solution, and it displays the initial deal.) Write a program to take a deal number and deal cards in the same order as this algorithm. The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way. Related tasks: Playing cards Card shuffles War Card_Game Poker hand_analyser Go Fish
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; procedure FreeCell is type State is mod 2**31; type Deck is array (0..51) of String(1..2);   package Random is procedure Init(Seed: State); function Rand return State; end Random; package body Random is S : State := State'First; procedure Init(Seed: State) is begin S := Seed; end Init; function Rand return State is begin S := S * 214013 + 2531011; return S / 2**16; end Rand; end Random;   procedure Deal (num : State) is thedeck : Deck; pick : State; Chars : constant String := "A23456789TJQKCDHS"; begin for i in thedeck'Range loop thedeck(i):= Chars(i/4+1) & Chars(i mod 4 + 14); end loop; Random.Init(num); for i in 0..51 loop pick := Random.Rand mod State(52-i); Put(thedeck(Natural(pick))&' '); if (i+1) mod 8 = 0 then New_Line; end if; thedeck(Natural(pick)) := thedeck(51-i); end loop; New_Line; end Deal;   begin Deal(1); New_Line; Deal(617); end FreeCell;
http://rosettacode.org/wiki/De_Bruijn_sequences
de Bruijn sequences
The sequences are named after the Dutch mathematician   Nicolaas Govert de Bruijn. A note on Dutch capitalization:   Nicolaas' last name is   de Bruijn,   the   de   isn't normally capitalized unless it's the first word in a sentence.   Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be capitalized. In combinatorial mathematics,   a   de Bruijn sequence   of order   n   on a   size-k   alphabet (computer science)   A   is a cyclic sequence in which every possible   length-n   string (computer science, formal theory)   on   A   occurs exactly once as a contiguous substring. Such a sequence is denoted by   B(k, n)   and has length   kn,   which is also the number of distinct substrings of length   n   on   A;     de Bruijn sequences are therefore optimally short. There are: (k!)k(n-1)   ÷   kn distinct de Bruijn sequences   B(k, n). Task For this Rosetta Code task,   a   de Bruijn   sequence is to be generated that can be used to shorten a brute-force attack on a   PIN-like   code lock that does not have an "enter" key and accepts the last   n   digits entered. Note:   automated teller machines (ATMs)   used to work like this,   but their software has been updated to not allow a brute-force attack. Example A   digital door lock   with a 4-digit code would have B (10, 4) solutions,   with a length of   10,000   (digits). Therefore, only at most     10,000 + 3     (as the solutions are cyclic or wrap-around)   presses are needed to open the lock. Trying all 4-digit codes separately would require   4 × 10,000   or   40,000   presses. Task requirements   Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.   Show the length of the generated de Bruijn sequence.   (There are many possible de Bruijn sequences that solve this task,   one solution is shown on the discussion page).   Show the first and last   130   digits of the de Bruijn sequence.   Verify that all four-digit (decimal)   1,000   PIN codes are contained within the de Bruijn sequence.   0000, 0001, 0002, 0003,   ...   9996, 9997, 9998, 9999   (note the leading zeros).   Reverse the de Bruijn sequence.   Again, perform the (above) verification test.   Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.   Perform the verification test (again).   There should be four PIN codes missing. (The last requirement is to ensure that the verification tests performs correctly.   The verification processes should list any and all missing PIN codes.) Show all output here, on this page. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet References   Wikipedia entry:   de Bruijn sequence.   MathWorld entry:   de Bruijn sequence.   An  OEIS  entry:   A166315 lexicographically earliest binary de Bruijn sequences, B(2,n)     --- Not B(10,4),   but possibly relevant.
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Fixed; use Ada.Strings; with Ada.Strings.Unbounded;   procedure De_Bruijn_Sequences is   function De_Bruijn (K, N : Positive) return String is use Ada.Strings.Unbounded;   Alphabet : constant String := "0123456789";   subtype Decimal is Integer range 0 .. 9; type Decimal_Array is array (Natural range <>) of Decimal;   A  : Decimal_Array (0 .. K * N - 1) := (others => 0); Seq : Unbounded_String;   procedure Db (T, P : Positive) is begin if T > N then if N mod P = 0 then for E of A (1 .. P) loop Append (Seq, Alphabet (Alphabet'First + E)); end loop; end if; else A (T) := A (T - P); Db (T + 1, P); for J in A (T - P) + 1 .. K - 1 loop A (T) := J; Db (T + 1, T); end loop; end if; end Db;   begin Db (1, 1); return To_String (Seq) & Slice (Seq, 1, N - 1); end De_Bruijn;   function Image (Value : Integer) return String is (Fixed.Trim (Value'Image, Left));   function PIN_Image (Value : Integer) return String is (Fixed.Tail (Image (Value), Count => 4, Pad => '0'));   procedure Validate (Db : String) is Found  : array (0 .. 9_999) of Natural := (others => 0); Errors : Natural := 0; begin   -- Check all strings of 4 consecutive digits within 'db' -- to see if all 10,000 combinations occur without duplication. for A in Db'First .. Db'Last - 3 loop declare PIN : String renames Db (A .. A + 4 - 1); begin if (for all Char of PIN => Char in '0' .. '9') then declare N : constant Integer := Integer'Value (PIN); F : Natural renames Found (N); begin F := F + 1; end; end if; end; end loop;   for I in 0_000 .. 9_999 loop if Found (I) = 0 then Put_Line (" PIN number " & PIN_Image (I) & " missing"); Errors := Errors + 1; elsif Found (I) > 1 then Put_Line (" PIN number " & PIN_Image (I) & " occurs " & Image (Found (I)) & " times"); Errors := Errors + 1; end if; end loop;   case Errors is when 0 => Put_Line (" No errors found"); when 1 => Put_Line (" 1 error found"); when others => Put_Line (" " & Image (Errors) & " errors found"); end case; end Validate;   function Backwards (S : String) return String is R : String (S'Range); begin for A in 0 .. S'Length - 1 loop R (R'Last - A) := S (S'First + A); end loop; return R; end Backwards;   DB  : constant String := De_Bruijn (K => 10, N => 4); Rev : constant String := Backwards (DB); Ovl : String := DB; begin Put_Line ("The length of the de Bruijn sequence is " & DB'Length'Image); New_Line;   Put_Line ("The first 130 digits of the de Bruijn sequence are: "); Put_Line (" " & Fixed.Head (DB, 130)); New_Line;   Put_Line ("The last 130 digits of the de Bruijn sequence are: "); Put_Line (" " & Fixed.Tail (DB, 130)); New_Line;   Put_Line ("Validating the deBruijn sequence:"); Validate (DB); New_Line;   Put_Line ("Validating the reversed deBruijn sequence:"); Validate (Rev); New_Line;   Ovl (4444) := '.'; Put_Line ("Validating the overlaid deBruijn sequence:"); Validate (Ovl); New_Line; end De_Bruijn_Sequences;
http://rosettacode.org/wiki/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#E
E
def MyNumber := 1..10   for i :MyNumber in [0, 5, 10, 15, 20, 25] { println(i) }
http://rosettacode.org/wiki/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#EchoLisp
EchoLisp
  (require 'types) (require 'math)   ;; type defined by a predicate (define (one-ten? x) (in-interval? x 1 10)) (type One-ten [Integer & one-ten?])   ;; OR by an enumeration (type One-ten [ 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 ])   ;; EXPLICIT type checking ;; type-of? returns a Boolean   (type-of? 5 One-ten) → #t (type-of? 'Albert One-ten) → #f   ;; type-check raises an error (type-check 6 One-ten) → #t (type-check 88 One-ten) ⛔ error: One-ten : type-check failure : 88 → 'one-ten?'     ;; IMPLICIT type checking ;; declare a function signature (define (f10 x y) (+ x y)) (signature f10 One-ten -> One-ten -> Integer)   (f10 6 7) → 13 (f10 42 666) ❗ error: One-ten : type-check failure : 42 → 'f10:x'  
http://rosettacode.org/wiki/Death_Star
Death Star
Task Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction. (This will basically produce a shape like a "death star".) Related tasks draw a sphere draw a cuboid draw a rotating cube write language name in 3D ASCII
#Brlcad
Brlcad
# We need a database to hold the objects opendb deathstar.g y   # We will be measuring in kilometers units km   # Create a sphere of radius 60km centred at the origin in sph1.s sph 0 0 0 60   # We will be subtracting an overlapping sphere with a radius of 40km # The resultant hole will be smaller than this, because we only # only catch the edge in sph2.s sph 0 90 0 40   # Create a region named deathstar.r which consists of big minus small sphere r deathstar.r u sph1.s - sph2.s   # We will use a plastic material texture with rgb colour 224,224,224 # with specular lighting value of 0.1 and no inheritance mater deathstar.r "plastic sp=0.1" 224 224 224 0   # Clear the wireframe display and draw the deathstar B deathstar.r   # We now trigger the raytracer to see our finished product rt
http://rosettacode.org/wiki/Death_Star
Death Star
Task Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction. (This will basically produce a shape like a "death star".) Related tasks draw a sphere draw a cuboid draw a rotating cube write language name in 3D ASCII
#C
C
#include <stdio.h> #include <math.h> #include <unistd.h>   const char *shades = ".:!*oe&#%@";   double light[3] = { -50, 0, 50 }; void normalize(double * v) { double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; }   double dot(double *x, double *y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; }   typedef struct { double cx, cy, cz, r; } sphere_t;   /* positive shpere and negative sphere */ sphere_t pos = { 20, 20, 0, 20 }, neg = { 1, 1, -6, 20 };   /* check if a ray (x,y, -inf)->(x, y, inf) hits a sphere; if so, return the intersecting z values. z1 is closer to the eye */ int hit_sphere(sphere_t *sph, double x, double y, double *z1, double *z2) { double zsq; x -= sph->cx; y -= sph->cy; zsq = sph->r * sph->r - (x * x + y * y); if (zsq < 0) return 0; zsq = sqrt(zsq); *z1 = sph->cz - zsq; *z2 = sph->cz + zsq; return 1; }   void draw_sphere(double k, double ambient) { int i, j, intensity, hit_result; double b; double vec[3], x, y, zb1, zb2, zs1, zs2; for (i = floor(pos.cy - pos.r); i <= ceil(pos.cy + pos.r); i++) { y = i + .5; for (j = floor(pos.cx - 2 * pos.r); j <= ceil(pos.cx + 2 * pos.r); j++) { x = (j - pos.cx) / 2. + .5 + pos.cx;   /* ray lands in blank space, draw bg */ if (!hit_sphere(&pos, x, y, &zb1, &zb2)) hit_result = 0;   /* ray hits pos sphere but not neg, draw pos sphere surface */ else if (!hit_sphere(&neg, x, y, &zs1, &zs2)) hit_result = 1;   /* ray hits both, but pos front surface is closer */ else if (zs1 > zb1) hit_result = 1;   /* pos sphere surface is inside neg sphere, show bg */ else if (zs2 > zb2) hit_result = 0;   /* back surface on neg sphere is inside pos sphere, the only place where neg sphere surface will be shown */ else if (zs2 > zb1) hit_result = 2; else hit_result = 1;   switch(hit_result) { case 0: putchar('+'); continue; case 1: vec[0] = x - pos.cx; vec[1] = y - pos.cy; vec[2] = zb1 - pos.cz; break; default: vec[0] = neg.cx - x; vec[1] = neg.cy - y; vec[2] = neg.cz - zs2; }   normalize(vec); b = pow(dot(light, vec), k) + ambient; intensity = (1 - b) * (sizeof(shades) - 1); if (intensity < 0) intensity = 0; if (intensity >= sizeof(shades) - 1) intensity = sizeof(shades) - 2; putchar(shades[intensity]); } putchar('\n'); } }   int main() { double ang = 0;   while (1) { printf("\033[H"); light[1] = cos(ang * 2); light[2] = cos(ang); light[0] = sin(ang); normalize(light); ang += .05;   draw_sphere(2, .3); usleep(100000); } return 0; }
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\infty }^{\infty }F(m)H(n-m)} for all integers n {\displaystyle {\mathit {n}}} . Assume F ( n ) {\displaystyle F(n)} can be non-zero only for 0 {\displaystyle 0} ≤ n {\displaystyle {\mathit {n}}} ≤ | F | {\displaystyle |{\mathit {F}}|} , where | F | {\displaystyle |{\mathit {F}}|} is the "length" of F {\displaystyle {\mathit {F}}} , and similarly for G {\displaystyle {\mathit {G}}} and H {\displaystyle {\mathit {H}}} , so that the functions can be modeled as finite sequences by identifying f 0 , f 1 , f 2 , … {\displaystyle f_{0},f_{1},f_{2},\dots } with F ( 0 ) , F ( 1 ) , F ( 2 ) , … {\displaystyle F(0),F(1),F(2),\dots } , etc. Then for example, values of | F | = 6 {\displaystyle |{\mathit {F}}|=6} and | H | = 5 {\displaystyle |{\mathit {H}}|=5} would determine the following value of g {\displaystyle {\mathit {g}}} by definition. g 0 = f 0 h 0 g 1 = f 1 h 0 + f 0 h 1 g 2 = f 2 h 0 + f 1 h 1 + f 0 h 2 g 3 = f 3 h 0 + f 2 h 1 + f 1 h 2 + f 0 h 3 g 4 = f 4 h 0 + f 3 h 1 + f 2 h 2 + f 1 h 3 + f 0 h 4 g 5 = f 5 h 0 + f 4 h 1 + f 3 h 2 + f 2 h 3 + f 1 h 4 g 6 = f 5 h 1 + f 4 h 2 + f 3 h 3 + f 2 h 4 g 7 = f 5 h 2 + f 4 h 3 + f 3 h 4 g 8 = f 5 h 3 + f 4 h 4 g 9 = f 5 h 4 {\displaystyle {\begin{array}{lllllllllll}g_{0}&=&f_{0}h_{0}\\g_{1}&=&f_{1}h_{0}&+&f_{0}h_{1}\\g_{2}&=&f_{2}h_{0}&+&f_{1}h_{1}&+&f_{0}h_{2}\\g_{3}&=&f_{3}h_{0}&+&f_{2}h_{1}&+&f_{1}h_{2}&+&f_{0}h_{3}\\g_{4}&=&f_{4}h_{0}&+&f_{3}h_{1}&+&f_{2}h_{2}&+&f_{1}h_{3}&+&f_{0}h_{4}\\g_{5}&=&f_{5}h_{0}&+&f_{4}h_{1}&+&f_{3}h_{2}&+&f_{2}h_{3}&+&f_{1}h_{4}\\g_{6}&=&&&f_{5}h_{1}&+&f_{4}h_{2}&+&f_{3}h_{3}&+&f_{2}h_{4}\\g_{7}&=&&&&&f_{5}h_{2}&+&f_{4}h_{3}&+&f_{3}h_{4}\\g_{8}&=&&&&&&&f_{5}h_{3}&+&f_{4}h_{4}\\g_{9}&=&&&&&&&&&f_{5}h_{4}\end{array}}} We can write this in matrix form as: ( g 0 g 1 g 2 g 3 g 4 g 5 g 6 g 7 g 8 g 9 ) = ( f 0 f 1 f 0 f 2 f 1 f 0 f 3 f 2 f 1 f 0 f 4 f 3 f 2 f 1 f 0 f 5 f 4 f 3 f 2 f 1 f 5 f 4 f 3 f 2 f 5 f 4 f 3 f 5 f 4 f 5 ) ( h 0 h 1 h 2 h 3 h 4 ) {\displaystyle \left({\begin{array}{l}g_{0}\\g_{1}\\g_{2}\\g_{3}\\g_{4}\\g_{5}\\g_{6}\\g_{7}\\g_{8}\\g_{9}\\\end{array}}\right)=\left({\begin{array}{lllll}f_{0}\\f_{1}&f_{0}\\f_{2}&f_{1}&f_{0}\\f_{3}&f_{2}&f_{1}&f_{0}\\f_{4}&f_{3}&f_{2}&f_{1}&f_{0}\\f_{5}&f_{4}&f_{3}&f_{2}&f_{1}\\&f_{5}&f_{4}&f_{3}&f_{2}\\&&f_{5}&f_{4}&f_{3}\\&&&f_{5}&f_{4}\\&&&&f_{5}\end{array}}\right)\;\left({\begin{array}{l}h_{0}\\h_{1}\\h_{2}\\h_{3}\\h_{4}\\\end{array}}\right)} or g = A h {\displaystyle g=A\;h} For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by constructing and solving such a system of equations represented by the above matrix A {\displaystyle A} for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . The function should work for G {\displaystyle {\mathit {G}}} of arbitrary length (i.e., not hard coded or constant) and F {\displaystyle {\mathit {F}}} of any length up to that of G {\displaystyle {\mathit {G}}} . Note that | H | {\displaystyle |{\mathit {H}}|} will be given by | G | − | F | + 1 {\displaystyle |{\mathit {G}}|-|{\mathit {F}}|+1} . There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task. Test your solution on the following data. Be sure to verify both that deconv ( g , f ) = h {\displaystyle (g,f)=h} and deconv ( g , h ) = f {\displaystyle (g,h)=f} and display the results in a human readable form. h = [-8,-9,-3,-1,-6,7] f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
#Nim
Nim
proc deconv(g, f: openArray[float]): seq[float] = var h: seq[float] = newSeq[float](len(g) - len(f) + 1) for n in 0..<len(h): h[n] = g[n] var lower: int if n >= len(f): lower = n - len(f) + 1 for i in lower..<n: h[n] -= h[i] * f[n - i] h[n] /= f[0] h   let h = [-8'f64, -9, -3, -1, -6, 7] let f = [-3'f64, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1] let g = [24'f64, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, 96, 31, 55, 36, 29, -43, -7] echo h echo deconv(g, f) echo f echo deconv(g, h)
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\infty }^{\infty }F(m)H(n-m)} for all integers n {\displaystyle {\mathit {n}}} . Assume F ( n ) {\displaystyle F(n)} can be non-zero only for 0 {\displaystyle 0} ≤ n {\displaystyle {\mathit {n}}} ≤ | F | {\displaystyle |{\mathit {F}}|} , where | F | {\displaystyle |{\mathit {F}}|} is the "length" of F {\displaystyle {\mathit {F}}} , and similarly for G {\displaystyle {\mathit {G}}} and H {\displaystyle {\mathit {H}}} , so that the functions can be modeled as finite sequences by identifying f 0 , f 1 , f 2 , … {\displaystyle f_{0},f_{1},f_{2},\dots } with F ( 0 ) , F ( 1 ) , F ( 2 ) , … {\displaystyle F(0),F(1),F(2),\dots } , etc. Then for example, values of | F | = 6 {\displaystyle |{\mathit {F}}|=6} and | H | = 5 {\displaystyle |{\mathit {H}}|=5} would determine the following value of g {\displaystyle {\mathit {g}}} by definition. g 0 = f 0 h 0 g 1 = f 1 h 0 + f 0 h 1 g 2 = f 2 h 0 + f 1 h 1 + f 0 h 2 g 3 = f 3 h 0 + f 2 h 1 + f 1 h 2 + f 0 h 3 g 4 = f 4 h 0 + f 3 h 1 + f 2 h 2 + f 1 h 3 + f 0 h 4 g 5 = f 5 h 0 + f 4 h 1 + f 3 h 2 + f 2 h 3 + f 1 h 4 g 6 = f 5 h 1 + f 4 h 2 + f 3 h 3 + f 2 h 4 g 7 = f 5 h 2 + f 4 h 3 + f 3 h 4 g 8 = f 5 h 3 + f 4 h 4 g 9 = f 5 h 4 {\displaystyle {\begin{array}{lllllllllll}g_{0}&=&f_{0}h_{0}\\g_{1}&=&f_{1}h_{0}&+&f_{0}h_{1}\\g_{2}&=&f_{2}h_{0}&+&f_{1}h_{1}&+&f_{0}h_{2}\\g_{3}&=&f_{3}h_{0}&+&f_{2}h_{1}&+&f_{1}h_{2}&+&f_{0}h_{3}\\g_{4}&=&f_{4}h_{0}&+&f_{3}h_{1}&+&f_{2}h_{2}&+&f_{1}h_{3}&+&f_{0}h_{4}\\g_{5}&=&f_{5}h_{0}&+&f_{4}h_{1}&+&f_{3}h_{2}&+&f_{2}h_{3}&+&f_{1}h_{4}\\g_{6}&=&&&f_{5}h_{1}&+&f_{4}h_{2}&+&f_{3}h_{3}&+&f_{2}h_{4}\\g_{7}&=&&&&&f_{5}h_{2}&+&f_{4}h_{3}&+&f_{3}h_{4}\\g_{8}&=&&&&&&&f_{5}h_{3}&+&f_{4}h_{4}\\g_{9}&=&&&&&&&&&f_{5}h_{4}\end{array}}} We can write this in matrix form as: ( g 0 g 1 g 2 g 3 g 4 g 5 g 6 g 7 g 8 g 9 ) = ( f 0 f 1 f 0 f 2 f 1 f 0 f 3 f 2 f 1 f 0 f 4 f 3 f 2 f 1 f 0 f 5 f 4 f 3 f 2 f 1 f 5 f 4 f 3 f 2 f 5 f 4 f 3 f 5 f 4 f 5 ) ( h 0 h 1 h 2 h 3 h 4 ) {\displaystyle \left({\begin{array}{l}g_{0}\\g_{1}\\g_{2}\\g_{3}\\g_{4}\\g_{5}\\g_{6}\\g_{7}\\g_{8}\\g_{9}\\\end{array}}\right)=\left({\begin{array}{lllll}f_{0}\\f_{1}&f_{0}\\f_{2}&f_{1}&f_{0}\\f_{3}&f_{2}&f_{1}&f_{0}\\f_{4}&f_{3}&f_{2}&f_{1}&f_{0}\\f_{5}&f_{4}&f_{3}&f_{2}&f_{1}\\&f_{5}&f_{4}&f_{3}&f_{2}\\&&f_{5}&f_{4}&f_{3}\\&&&f_{5}&f_{4}\\&&&&f_{5}\end{array}}\right)\;\left({\begin{array}{l}h_{0}\\h_{1}\\h_{2}\\h_{3}\\h_{4}\\\end{array}}\right)} or g = A h {\displaystyle g=A\;h} For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by constructing and solving such a system of equations represented by the above matrix A {\displaystyle A} for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . The function should work for G {\displaystyle {\mathit {G}}} of arbitrary length (i.e., not hard coded or constant) and F {\displaystyle {\mathit {F}}} of any length up to that of G {\displaystyle {\mathit {G}}} . Note that | H | {\displaystyle |{\mathit {H}}|} will be given by | G | − | F | + 1 {\displaystyle |{\mathit {G}}|-|{\mathit {F}}|+1} . There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task. Test your solution on the following data. Be sure to verify both that deconv ( g , f ) = h {\displaystyle (g,f)=h} and deconv ( g , h ) = f {\displaystyle (g,h)=f} and display the results in a human readable form. h = [-8,-9,-3,-1,-6,7] f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
#Perl
Perl
use Math::Cartesian::Product;   sub deconvolve { our @g; local *g = shift; our @f; local *f = shift; my(@m,@d);   my $h = 1 + @g - @f; push @m, [(0) x $h, $g[$_]] for 0..$#g; for my $j (0..$h-1) { for my $k (0..$#f) { $m[$j + $k][$j] = $f[$k] } } rref(\@m); push @d, @{ $m[$_] }[$h] for 0..$h-1; @d; }   sub convolve { our @f; local *f = shift; our @h; local *h = shift; my @i; for my $x (cartesian {@_} [0..$#f], [0..$#h]) { push @i, @$x[0]+@$x[1]; } my $cnt = 0; my @g = (0) x (@f + @h - 1); for my $x (cartesian {@_} [@f], [@h]) { $g[$i[$cnt++]] += @$x[0]*@$x[1]; } @g; }   sub rref { our @m; local *m = shift; @m or return; my ($lead, $rows, $cols) = (0, scalar(@m), scalar(@{$m[0]}));   foreach my $r (0 .. $rows - 1) { $lead < $cols or return; my $i = $r;   until ($m[$i][$lead]) {++$i == $rows or next; $i = $r; ++$lead == $cols and return;}   @m[$i, $r] = @m[$r, $i]; my $lv = $m[$r][$lead]; $_ /= $lv foreach @{ $m[$r] };   my @mr = @{ $m[$r] }; foreach my $i (0 .. $rows - 1) {$i == $r and next; ($lv, my $n) = ($m[$i][$lead], -1); $_ -= $lv * $mr[++$n] foreach @{ $m[$i] };}   ++$lead;} }   my @h = qw<-8 -9 -3 -1 -6 7>; my @f = qw<-3 -6 -1 8 -6 3 -1 -9 -9 3 -2 5 2 -2 -7 -1>; print ' conv(f,h) = g = ' . join(' ', my @g = convolve(\@f, \@h)) . "\n"; print 'deconv(g,f) = h = ' . join(' ', deconvolve(\@g, \@f)) . "\n"; print 'deconv(g,h) = f = ' . join(' ', deconvolve(\@g, \@h)) . "\n";
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Sidef
Sidef
var src = Hash(foo => 0, bar => [0,1])   # Add a cyclic reference src{:baz} = src   # Make a deep clone var dst = src.dclone   # The address of src say src.object_id say src{:baz}.object_id   # The address of dst say dst.object_id say dst{:baz}.object_id
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. Any limitations of the method. That the structure and its copy are different. Suitable links to external documentation for common libraries.
#Tcl
Tcl
set deepCopy [string range ${valueToCopy}x 0 end-1]
http://rosettacode.org/wiki/Deal_cards_for_FreeCell
Deal cards for FreeCell
Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows. This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.) As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals. These deals are numbered from 1 to 32000. Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range. The algorithm uses this linear congruential generator from Microsoft C: s t a t e n + 1 ≡ 214013 × s t a t e n + 2531011 ( mod 2 31 ) {\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}} r a n d n = s t a t e n ÷ 2 16 {\displaystyle rand_{n}=state_{n}\div 2^{16}} r a n d n {\displaystyle rand_{n}} is in range 0 to 32767. Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages. The algorithm follows: Seed the RNG with the number of the deal. Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51. Until the array is empty: Choose a random card at index ≡ next random number (mod array length). Swap this random card with the last card of the array. Remove this random card from the array. (Array length goes down by 1.) Deal this random card. Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on. Order to deal cards Game #1 Game #617 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 JD 2D 9H JC 5D 7H 7C 5H KD KC 9S 5S AD QC KH 3H 2S KS 9D QD JS AS AH 3C 4C 5C TS QH 4H AC 4D 7S 3S TD 4S TH 8H 2C JH 7D 6D 8S 8D QS 6C 3D 8C TC 6S 9C 2H 6H 7D AD 5C 3S 5S 8C 2D AH TD 7S QD AC 6D 8H AS KH TH QC 3H 9D 6S 8D 3D TC KD 5H 9S 3C 8S 7H 4D JS 4C QS 9C 9H 7C 6H 2C 2S 4S TS 2H 5D JC 6C JH QH JD KS KC 4H Deals can also be checked against FreeCell solutions to 1000000 games. (Summon a video solution, and it displays the initial deal.) Write a program to take a deal number and deal cards in the same order as this algorithm. The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way. Related tasks: Playing cards Card shuffles War Card_Game Poker hand_analyser Go Fish
#AutoHotkey
AutoHotkey
FreeCell(num){ cards := "A23456789TJQK", suits := "♣♦♥♠", card := [], Counter := 0 loop, parse, cards { ThisCard := A_LoopField loop, parse, suits Card[Counter++] := ThisCard . A_LoopField } loop, 52 { a := MS(num) num:=a[1] MyCardNo := mod(a[2],53-A_Index) MyCard := Card[MyCardNo] Card[MyCardNo] := Card[52-A_Index] Card.Remove(52-A_Index) Res .= MyCard (Mod(A_Index,8)?" ":"`n") } return Res } MS(Seed) { Seed := Mod(214013 * Seed + 2531011, 2147483648) return, [Seed, Seed // 65536] }
http://rosettacode.org/wiki/De_Bruijn_sequences
de Bruijn sequences
The sequences are named after the Dutch mathematician   Nicolaas Govert de Bruijn. A note on Dutch capitalization:   Nicolaas' last name is   de Bruijn,   the   de   isn't normally capitalized unless it's the first word in a sentence.   Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be capitalized. In combinatorial mathematics,   a   de Bruijn sequence   of order   n   on a   size-k   alphabet (computer science)   A   is a cyclic sequence in which every possible   length-n   string (computer science, formal theory)   on   A   occurs exactly once as a contiguous substring. Such a sequence is denoted by   B(k, n)   and has length   kn,   which is also the number of distinct substrings of length   n   on   A;     de Bruijn sequences are therefore optimally short. There are: (k!)k(n-1)   ÷   kn distinct de Bruijn sequences   B(k, n). Task For this Rosetta Code task,   a   de Bruijn   sequence is to be generated that can be used to shorten a brute-force attack on a   PIN-like   code lock that does not have an "enter" key and accepts the last   n   digits entered. Note:   automated teller machines (ATMs)   used to work like this,   but their software has been updated to not allow a brute-force attack. Example A   digital door lock   with a 4-digit code would have B (10, 4) solutions,   with a length of   10,000   (digits). Therefore, only at most     10,000 + 3     (as the solutions are cyclic or wrap-around)   presses are needed to open the lock. Trying all 4-digit codes separately would require   4 × 10,000   or   40,000   presses. Task requirements   Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.   Show the length of the generated de Bruijn sequence.   (There are many possible de Bruijn sequences that solve this task,   one solution is shown on the discussion page).   Show the first and last   130   digits of the de Bruijn sequence.   Verify that all four-digit (decimal)   1,000   PIN codes are contained within the de Bruijn sequence.   0000, 0001, 0002, 0003,   ...   9996, 9997, 9998, 9999   (note the leading zeros).   Reverse the de Bruijn sequence.   Again, perform the (above) verification test.   Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.   Perform the verification test (again).   There should be four PIN codes missing. (The last requirement is to ensure that the verification tests performs correctly.   The verification processes should list any and all missing PIN codes.) Show all output here, on this page. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet References   Wikipedia entry:   de Bruijn sequence.   MathWorld entry:   de Bruijn sequence.   An  OEIS  entry:   A166315 lexicographically earliest binary de Bruijn sequences, B(2,n)     --- Not B(10,4),   but possibly relevant.
#BASIC
BASIC
10 DEFINT A-Z 20 K = 10: N = 4 30 DIM A(K*N), S(K^N+N), T(5), P(5), V(K^N\8) 40 GOSUB 200 50 PRINT "Length: ",S 60 PRINT "First 130:" 70 FOR I=0 TO 129: PRINT USING "#";S(I);: NEXT 80 PRINT: PRINT "Last 130:" 90 FOR I=S-130 TO S-1: PRINT USING "#";S(I);: NEXT 100 PRINT 110 GOSUB 600 120 PRINT "Reversing...": GOSUB 500: GOSUB 600: GOSUB 500 130 PRINT USING "Replacing 4444'th element (#):";S(4443) 140 S(4443) = -1 : REM 0-indexed, and using integers 150 GOSUB 600 160 END 200 REM Generate De Bruijn sequence given K and N 210 T(R) = 1: P(R) = 1 220 IF T(R) > N GOTO 380 230 A(T(R)) = A(T(R)-P(R)) 240 R = R+1 250 T(R) = T(R-1)+1 260 P(R) = P(R-1) 270 GOSUB 220 280 R = R-1 290 FOR J = A(T(R)-P(R))+1 TO K-1 300 A(T(R)) = J 310 R = R+1 320 T(R) = T(R-1)+1 330 P(R) = T(R-1) 340 GOSUB 220 350 R = R-1 355 J = A(T(R)) 360 NEXT 370 RETURN 380 IF N MOD P(R) THEN RETURN 390 FOR I = 1 TO P(R) 400 S(S) = A(I) 410 S = S+1 420 NEXT 430 RETURN 500 REM Reverse the sequence 510 FOR I=0 TO S\2 520 J = S(I) 530 S(I) = S(S-I) 540 S(S-I) = J 550 NEXT 560 RETURN 600 REM Validate the sequence (uses bit packing to save memory) 610 PRINT "Validating..."; 620 FOR I=0 TO N-1: S(S+I)=S(I): NEXT 630 FOR I=0 TO K^N\8-1: V(I)=0: NEXT 640 FOR I=0 TO S 650 P=0 660 FOR J=0 TO N-1 662 D=S(I+J) 663 IF D<0 GOTO 690 665 P=K*P+D 669 NEXT J 670 X=P\8 680 V(X) = V(X) OR 2^(P AND 7) 690 NEXT I 700 M=1 710 FOR I=0 TO K^N\8-1 720 IF V(I)=255 GOTO 760 730 FOR J=0 TO 7 740 IF (V(I) AND 2^J)=0 THEN M=0: PRINT USING " ####";I*8+J; 750 NEXT 760 NEXT 770 IF M THEN PRINT " none"; 780 PRINT " missing." 790 RETURN
http://rosettacode.org/wiki/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#Elena
Elena
import extensions;   sealed struct TinyInt : BaseNumber { int value;   int cast() = value;   constructor(int n) { if (n <= 1 || n >= 10) { InvalidArgumentException.raise() };   value := n }   cast t(string s) { value := s.toInt();   if (value <= 1 || value >= 10) { InvalidArgumentException.raise() } }   TinyInt add(TinyInt t) = value + (cast int(t));   TinyInt subtract(TinyInt t) = value - (cast int(t));   TinyInt multiply(TinyInt t) = value * (cast int(t));   TinyInt divide(TinyInt t) = value / (cast int(t));   bool equal(TinyInt t) = value == (cast int(t));   bool less(TinyInt t) = value == (cast int(t)); }   public program() { TinyInt i := 4t; TinyInt j := i + i;   try { i + j } catch(InvalidArgumentException e) { console.printLine("A value is out of range") } }
http://rosettacode.org/wiki/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#Euphoria
Euphoria
type My_Type(integer i) return i >= 1 and i <= 10 end type
http://rosettacode.org/wiki/Death_Star
Death Star
Task Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction. (This will basically produce a shape like a "death star".) Related tasks draw a sphere draw a cuboid draw a rotating cube write language name in 3D ASCII
#D
D
import std.stdio, std.math, std.numeric, std.algorithm;   struct V3 { double[3] v;   @property V3 normalize() pure nothrow const @nogc { immutable double len = dotProduct(v, v).sqrt; return [v[0] / len, v[1] / len, v[2] / len].V3; }   double dot(in ref V3 y) pure nothrow const @nogc { immutable double d = dotProduct(v, y.v); return d < 0 ? -d : 0; } }     const struct Sphere { double cx, cy, cz, r; }   void drawSphere(in double k, in double ambient, in V3 light) nothrow { /** Check if a ray (x,y, -inf).(x, y, inf) hits a sphere; if so, return the intersecting z values. z1 is closer to the eye.*/ static bool hitSphere(in ref Sphere sph, in double x0, in double y0, out double z1, out double z2) pure nothrow @nogc { immutable double x = x0 - sph.cx; immutable double y = y0 - sph.cy; immutable double zsq = sph.r ^^ 2 - (x ^^ 2 + y ^^ 2); if (zsq < 0) return false; immutable double szsq = zsq.sqrt; z1 = sph.cz - szsq; z2 = sph.cz + szsq; return true; }   immutable shades = ".:!*oe&#%@"; // Positive and negative spheres. immutable pos = Sphere(20, 20, 0, 20); immutable neg = Sphere(1, 1, -6, 20);   foreach (immutable int i; cast(int)floor(pos.cy - pos.r) .. cast(int)ceil(pos.cy + pos.r) + 1) { immutable double y = i + 0.5; JLOOP: foreach (int j; cast(int)floor(pos.cx - 2 * pos.r) .. cast(int)ceil(pos.cx + 2 * pos.r) + 1) { immutable double x = (j - pos.cx) / 2.0 + 0.5 + pos.cx;   enum Hit { background, posSphere, negSphere }   double zb1, zs2; immutable Hit hitResult = { double zb2, zs1;   if (!hitSphere(pos, x, y, zb1, zb2)) { // Ray lands in blank space, draw bg. return Hit.background; } else if (!hitSphere(neg, x, y, zs1, zs2)) { // Ray hits pos sphere but not neg one, // draw pos sphere surface. return Hit.posSphere; } else if (zs1 > zb1) { // ray hits both, but pos front surface is closer. return Hit.posSphere; } else if (zs2 > zb2) { // pos sphere surface is inside neg sphere, // show bg. return Hit.background; } else if (zs2 > zb1) { // Back surface on neg sphere is inside pos // sphere, the only place where neg sphere // surface will be shown. return Hit.negSphere; } else { return Hit.posSphere; } }();   V3 vec_; final switch (hitResult) { case Hit.background: ' '.putchar; continue JLOOP; case Hit.posSphere: vec_ = [x - pos.cx, y - pos.cy, zb1 - pos.cz].V3; break; case Hit.negSphere: vec_ = [neg.cx - x, neg.cy - y, neg.cz - zs2].V3; break; } immutable nvec = vec_.normalize;   immutable double b = light.dot(nvec) ^^ k + ambient; immutable intensity = cast(int)((1 - b) * shades.length); immutable normInt = min(shades.length, max(0, intensity)); shades[normInt].putchar; }   '\n'.putchar; } }     void main() { immutable light = [-50, 30, 50].V3.normalize; drawSphere(2, 0.5, light); }
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\infty }^{\infty }F(m)H(n-m)} for all integers n {\displaystyle {\mathit {n}}} . Assume F ( n ) {\displaystyle F(n)} can be non-zero only for 0 {\displaystyle 0} ≤ n {\displaystyle {\mathit {n}}} ≤ | F | {\displaystyle |{\mathit {F}}|} , where | F | {\displaystyle |{\mathit {F}}|} is the "length" of F {\displaystyle {\mathit {F}}} , and similarly for G {\displaystyle {\mathit {G}}} and H {\displaystyle {\mathit {H}}} , so that the functions can be modeled as finite sequences by identifying f 0 , f 1 , f 2 , … {\displaystyle f_{0},f_{1},f_{2},\dots } with F ( 0 ) , F ( 1 ) , F ( 2 ) , … {\displaystyle F(0),F(1),F(2),\dots } , etc. Then for example, values of | F | = 6 {\displaystyle |{\mathit {F}}|=6} and | H | = 5 {\displaystyle |{\mathit {H}}|=5} would determine the following value of g {\displaystyle {\mathit {g}}} by definition. g 0 = f 0 h 0 g 1 = f 1 h 0 + f 0 h 1 g 2 = f 2 h 0 + f 1 h 1 + f 0 h 2 g 3 = f 3 h 0 + f 2 h 1 + f 1 h 2 + f 0 h 3 g 4 = f 4 h 0 + f 3 h 1 + f 2 h 2 + f 1 h 3 + f 0 h 4 g 5 = f 5 h 0 + f 4 h 1 + f 3 h 2 + f 2 h 3 + f 1 h 4 g 6 = f 5 h 1 + f 4 h 2 + f 3 h 3 + f 2 h 4 g 7 = f 5 h 2 + f 4 h 3 + f 3 h 4 g 8 = f 5 h 3 + f 4 h 4 g 9 = f 5 h 4 {\displaystyle {\begin{array}{lllllllllll}g_{0}&=&f_{0}h_{0}\\g_{1}&=&f_{1}h_{0}&+&f_{0}h_{1}\\g_{2}&=&f_{2}h_{0}&+&f_{1}h_{1}&+&f_{0}h_{2}\\g_{3}&=&f_{3}h_{0}&+&f_{2}h_{1}&+&f_{1}h_{2}&+&f_{0}h_{3}\\g_{4}&=&f_{4}h_{0}&+&f_{3}h_{1}&+&f_{2}h_{2}&+&f_{1}h_{3}&+&f_{0}h_{4}\\g_{5}&=&f_{5}h_{0}&+&f_{4}h_{1}&+&f_{3}h_{2}&+&f_{2}h_{3}&+&f_{1}h_{4}\\g_{6}&=&&&f_{5}h_{1}&+&f_{4}h_{2}&+&f_{3}h_{3}&+&f_{2}h_{4}\\g_{7}&=&&&&&f_{5}h_{2}&+&f_{4}h_{3}&+&f_{3}h_{4}\\g_{8}&=&&&&&&&f_{5}h_{3}&+&f_{4}h_{4}\\g_{9}&=&&&&&&&&&f_{5}h_{4}\end{array}}} We can write this in matrix form as: ( g 0 g 1 g 2 g 3 g 4 g 5 g 6 g 7 g 8 g 9 ) = ( f 0 f 1 f 0 f 2 f 1 f 0 f 3 f 2 f 1 f 0 f 4 f 3 f 2 f 1 f 0 f 5 f 4 f 3 f 2 f 1 f 5 f 4 f 3 f 2 f 5 f 4 f 3 f 5 f 4 f 5 ) ( h 0 h 1 h 2 h 3 h 4 ) {\displaystyle \left({\begin{array}{l}g_{0}\\g_{1}\\g_{2}\\g_{3}\\g_{4}\\g_{5}\\g_{6}\\g_{7}\\g_{8}\\g_{9}\\\end{array}}\right)=\left({\begin{array}{lllll}f_{0}\\f_{1}&f_{0}\\f_{2}&f_{1}&f_{0}\\f_{3}&f_{2}&f_{1}&f_{0}\\f_{4}&f_{3}&f_{2}&f_{1}&f_{0}\\f_{5}&f_{4}&f_{3}&f_{2}&f_{1}\\&f_{5}&f_{4}&f_{3}&f_{2}\\&&f_{5}&f_{4}&f_{3}\\&&&f_{5}&f_{4}\\&&&&f_{5}\end{array}}\right)\;\left({\begin{array}{l}h_{0}\\h_{1}\\h_{2}\\h_{3}\\h_{4}\\\end{array}}\right)} or g = A h {\displaystyle g=A\;h} For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by constructing and solving such a system of equations represented by the above matrix A {\displaystyle A} for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . The function should work for G {\displaystyle {\mathit {G}}} of arbitrary length (i.e., not hard coded or constant) and F {\displaystyle {\mathit {F}}} of any length up to that of G {\displaystyle {\mathit {G}}} . Note that | H | {\displaystyle |{\mathit {H}}|} will be given by | G | − | F | + 1 {\displaystyle |{\mathit {G}}|-|{\mathit {F}}|+1} . There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task. Test your solution on the following data. Be sure to verify both that deconv ( g , f ) = h {\displaystyle (g,f)=h} and deconv ( g , h ) = f {\displaystyle (g,h)=f} and display the results in a human readable form. h = [-8,-9,-3,-1,-6,7] f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
#Phix
Phix
with javascript_semantics function deconv(sequence g, f) integer lf = length(f), lg = length(g), lh = lg-lf+1 sequence h = repeat(0,lh) for n=1 to lh do atom e = g[n] for i=max(n-lf,0) to n-2 do e -= h[i+1] * f[n-i] end for h[n] = e/f[1] end for return h end function function conv(sequence f, h) integer lf = length(f), lh = length(h), lg = lf+lh-1 sequence g = repeat(0,lg) for i=1 to lh do for j=1 to lf do integer k = i+j-1 g[k] += f[j] * h[i] end for end for return g end function constant h = {-8,-9,-3,-1,-6,7}, f = {-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1}, g = {24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7} procedure test(string desc, eq, sequence r, e) printf(1,"%s (%ssame as %s): %V\n",{desc,iff(r==e?"":"**NOT** "),eq,r}) end procedure test(" conv(h,f)","g", conv(h,f),g) test("deconv(g,f)","h",deconv(g,f),h) test("deconv(g,h)","f",deconv(g,h),f)