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/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.
#Wren
Wren
import "/trait" for Cloneable, CloneableSeq import "/seq" for Lst   class MyMap is Cloneable { construct new (m) { if (m.type != Map) Fiber.abort("Argument must be a Map.") _m = m }   m { _m }   toString { _m.toString }   clone() { // Map keys are always immutable built-in types so we only need to worry about // their values which can be anything. var m2 = {} for (me in _m) { var v = me.value m2[me.key] = (v is List) ? Lst.clone(v) : (v is Cloneable || v is CloneableSeq) ? v.clone() : v } return MyMap.new(m2) } }   var my = MyMap.new({"a": 0, "b": 1, "c": [2, 3], "d": MyMap.new({"e": 4})}) var my2 = my.clone() System.print("Before any changes:") System.print(" my = %(my)") System.print(" my2 = %(my2)") // now change my2 my2.m["a"] = 5 my2.m["b"] = 6 my2.m["c"][0] = 7 my2.m["c"][1] = 8 my2.m["d"].m["e"] = 9 my2.m["d"].m["f"] = 10 System.print("\nAfter changes to my2:") System.print(" my = %(my)") System.print(" my2 = %(my2)")
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
#BBC_BASIC
BBC BASIC
*FLOAT 64   hand% = 617   REM Initialise card library: SYS "LoadLibrary", "CARDS.DLL" TO cards% IF cards% = 0 ERROR 100, "No CARDS library" SYS "GetProcAddress", cards%, "cdtInit" TO cdtInit% SYS "GetProcAddress", cards%, "cdtDraw" TO cdtDraw% SYS cdtInit%, ^dx%, ^dy% VDU 23,22,8*dx%;5*dy%;8,16,16,128   REM Initialise deck: DIM card&(51) FOR I% = 0 TO 51 : card&(I%) = I% : NEXT   REM Shuffle deck: dummy% = FNrng(hand%) FOR I% = 51 TO 0 STEP -1 C% = FNrng(-1) MOD (I% + 1) SWAP card&(C%), card&(I%) NEXT   REM Display deck: FOR I% = 0 TO 51 C% = card&(51 - I%) X% = (I% MOD 8) * dx% Y% = (I% DIV 8) * dy% * 2 / 3 SYS cdtDraw%, @memhdc%, X%, Y%, C%, 0, 0 NEXT SYS "InvalidateRect", @hwnd%, 0, 0 *GSAVE freecell END   DEF FNrng(seed) PRIVATE state, M% IF seed >= 0 THEN state = seed ELSE state = (state * 214013 + 2531011) FOR M% = 52 TO 31 STEP -1 IF state >= 2^M% state -= 2^M% NEXT ENDIF = state >> 16
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
#Befunge
Befunge
vutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDC >4$0" :rebmun emaG">:#,_$&>55+,>"O?+"**2+*"C4'' "**v >8%!492*+*48*\-,1-:11p0g\0p11g#^_@A23456789TJQKCDHS* ^+3:g11,g2+"/"%4,g2+g14/4:-\"v"g0:%g11+*-/2-10-1*<>+ >8#8*#4*#::#%*#*/#*:#*0#:\#*`#:8#::#*:#8*#8:#2*#+^#<
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.
#C.23
C#
using System; using System.Collections.Generic; using System.Text;   namespace DeBruijn { class Program { const string digits = "0123456789";   static string DeBruijn(int k, int n) { var alphabet = digits.Substring(0, k); var a = new byte[k * n]; var seq = new List<byte>(); void db(int t, int p) { if (t > n) { if (n % p == 0) { seq.AddRange(new ArraySegment<byte>(a, 1, p)); } } else { a[t] = a[t - p]; db(t + 1, p); var j = a[t - p] + 1; while (j < k) { a[t] = (byte)j; db(t + 1, t); j++; } } } db(1, 1); var buf = new StringBuilder(); foreach (var i in seq) { buf.Append(alphabet[i]); } var b = buf.ToString(); return b + b.Substring(0, n - 1); }   static bool AllDigits(string s) { foreach (var c in s) { if (c < '0' || '9' < c) { return false; } } return true; }   static void Validate(string db) { var le = db.Length; var found = new int[10_000]; var errs = new List<string>(); // Check all strings of 4 consecutive digits within 'db' // to see if all 10,000 combinations occur without duplication. for (int i = 0; i < le - 3; i++) { var s = db.Substring(i, 4); if (AllDigits(s)) { int.TryParse(s, out int n); found[n]++; } } for (int i = 0; i < 10_000; i++) { if (found[i] == 0) { errs.Add(string.Format(" PIN number {0,4} missing", i)); } else if (found[i] > 1) { errs.Add(string.Format(" PIN number {0,4} occurs {1} times", i, found[i])); } } var lerr = errs.Count; if (lerr == 0) { Console.WriteLine(" No errors found"); } else { var pl = lerr == 1 ? "" : "s"; Console.WriteLine(" {0} error{1} found:", lerr, pl); errs.ForEach(Console.WriteLine); } }   static string Reverse(string s) { char[] arr = s.ToCharArray(); Array.Reverse(arr); return new string(arr); }   static void Main() { var db = DeBruijn(10, 4); var le = db.Length;   Console.WriteLine("The length of the de Bruijn sequence is {0}", le); Console.WriteLine("\nThe first 130 digits of the de Bruijn sequence are: {0}", db.Substring(0, 130)); Console.WriteLine("\nThe last 130 digits of the de Bruijn sequence are: {0}", db.Substring(le - 130, 130));   Console.WriteLine("\nValidating the deBruijn sequence:"); Validate(db);   Console.WriteLine("\nValidating the reversed deBruijn sequence:"); Validate(Reverse(db));   var bytes = db.ToCharArray(); bytes[4443] = '.'; db = new string(bytes); Console.WriteLine("\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.
#Factor
Factor
PREDICATE: my-int < integer [ 0 > ] [ 11 < ] bi and ;
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.
#Forth
Forth
DECIMAL : CLIP ( n lo hi -- n') ROT MIN MAX ; : BETWEEN ( n lo hi -- flag) 1+ WITHIN ;   \ programmer chooses CLIPPED or SAFE integer assignment : CLIP! ( n addr -- ) SWAP 1 10 CLIP SWAP  ! ; : SAFE! ( n addr -- ) OVER 1 10 BETWEEN 0= ABORT" out of range!"  ! ;
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
#Delphi
Delphi
  program Death_Star;   {$APPTYPE CONSOLE}   uses Winapi.Windows, System.SysUtils, system.Math, Vcl.Graphics, Vcl.Imaging.pngimage;   type TVector = array of double;   var light: TVector = [20, -40, -10];   function ClampInt(value, amin, amax: Integer): Integer; begin Result := Max(amin, Min(amax, value)) end;   procedure Normalize(var v: TVector); begin var len := Sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); v[0] := v[0] / len; v[1] := v[1] / len; v[2] := v[2] / len; end;   function Dot(x, y: TVector): Double; begin var d := x[0] * y[0] + x[1] * y[1] + x[2] * y[2]; if d < 0 then Result := -d else Result := 0; end;   type TSphere = record cx, cy, cz, r: Double; end;   const pos: TSphere = ( cx: 0; cy: 0; cz: 0; r: 120 );   const neg: TSphere = ( cx: -90; cy: -90; cz: -30; r: 80 );   function HitSphere(sph: TSphere; x, y: double; var z1, z2: Double): Boolean; begin x := x - sph.cx; y := y - sph.cy; var zsq := sph.r * sph.r - (x * x + y * y); if (zsq < 0) then Exit(False); zsq := Sqrt(zsq); z1 := sph.cz - zsq; z2 := sph.cz + zsq; Result := True; end;   function DeathStar(pos, neg: TSphere; k, amb: Double; light: TVector): TBitmap; var w, h, yMax, xMax, s: double; zp1, zp2, zn1, zn2, b: Double; x, y: Integer; hit: Boolean; vec: TVector; intensity: Byte; ox, oy: Integer; begin w := pos.r * 4; h := pos.r * 3; ox := -trunc(pos.cx - w / 2); oy := -trunc(pos.cy - h / 2);   vec := [0, 0, 0]; Result := TBitmap.Create; Result.SetSize(trunc(w), trunc(h));   yMax := pos.cy + pos.r; for y := Trunc(pos.cy - pos.r) to Trunc(yMax) do begin xMax := pos.cx + pos.r; for x := trunc(pos.cy - pos.r) to trunc(xMax) do begin hit := HitSphere(pos, x, y, zp1, zp2); if not hit then continue;   hit := HitSphere(neg, x, y, zn1, zn2);   if hit then begin if zn1 > zp1 then hit := false else if zn2 > zp2 then continue; end;   if hit then begin vec[0] := neg.cx - x; vec[1] := neg.cy - y; vec[2] := neg.cz - zn2; end else begin vec[0] := x - pos.cx; vec[1] := y - pos.cy; vec[2] := zp1 - pos.cz; end;   Normalize(vec);   s := max(0, dot(light, vec));   b := Power(s, k) + amb;   intensity := ClampInt(round(255 * b / (1 + amb)), 0, 254);   Result.Canvas.Pixels[x + ox, y + oy] := rgb(intensity, intensity, intensity); end; end; end;   var bmp: TBitmap;   begin Normalize(light); bmp := DeathStar(pos, neg, 1.2, 0.3, light);   with TPngImage.Create do begin Assign(bmp); TransparentColor := clwhite; SaveToFile('out.png'); bmp.Free; Free; end; 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]
#PicoLisp
PicoLisp
(load "@lib/math.l")   (de deconv (G F) (let A (pop 'F) (make (for (N . H) (head (- (length F)) G) (for (I . M) (made) (dec 'H (*/ M (get F (- N I)) 1.0) ) ) (link (*/ H 1.0 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]
#Python
Python
def ToReducedRowEchelonForm( M ): if not M: return lead = 0 rowCount = len(M) columnCount = len(M[0]) for r in range(rowCount): if lead >= columnCount: return i = r while M[i][lead] == 0: i += 1 if i == rowCount: i = r lead += 1 if columnCount == lead: return M[i],M[r] = M[r],M[i] lv = M[r][lead] M[r] = [ mrx / lv for mrx in M[r]] for i in range(rowCount): if i != r: lv = M[i][lead] M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])] lead += 1 return M   def pmtx(mtx): print ('\n'.join(''.join(' %4s' % col for col in row) for row in mtx))   def convolve(f, h): g = [0] * (len(f) + len(h) - 1) for hindex, hval in enumerate(h): for findex, fval in enumerate(f): g[hindex + findex] += fval * hval return g   def deconvolve(g, f): lenh = len(g) - len(f) + 1 mtx = [[0 for x in range(lenh+1)] for y in g] for hindex in range(lenh): for findex, fval in enumerate(f): gindex = hindex + findex mtx[gindex][hindex] = fval for gindex, gval in enumerate(g): mtx[gindex][lenh] = gval ToReducedRowEchelonForm( mtx ) return [mtx[i][lenh] for i in range(lenh)] # h   if __name__ == '__main__': 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] assert convolve(f,h) == g assert deconvolve(g, f) == 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.
#Z80_Assembly
Z80 Assembly
LD HL,(&C000) LD (&D000),HL
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
#Bracmat
Bracmat
( ( createArray = array rank ranks suit suits . A 2 3 4 5 6 7 8 9 T J Q K:?ranks & :?array & whl ' ( !ranks:%?rank ?ranks & ♣ ♦ ♥ ♠:?suits & whl ' ( !suits:%?suit ?suits & !array str$(!rank !suit):?array ) ) & !array ) & ( deal = A B D L Z pick card dealt deck , i last rand row state .  !arg:(?deck:? [?L.?state) & 8:?row & :?dealt & ( pick = sep . ( -1+!row:>0:?row & " ":?sep | \n:?sep&8:?row ) & !dealt !arg !sep:?dealt ) & 2^31:?B & 2^16:?D & " 'Hard code' the numbers B and D into the rand function using macro expansion. (Gives a marginally faster execution speed.) " & ' ( . mod$(!state*214013+2531011.$B):?state & div$(!state.$D) )  : (=?rand) & !L+1:?L & whl ' ( mod$(rand$.!L+-1:?L):?i & !deck:?A [!i %?card ?Z & ( !Z:?Z %@?last&!A !last !Z | !A )  : ?deck & pick$!card ) & pick$\n & str$!dealt ) & createArray$:?deck & put$("Game #1\n","dealt.txt",NEW) & put$(deal$(!deck.1),"dealt.txt",APP) & put$("   Game #617 ","dealt.txt",APP) & put$(deal$(!deck.617),"dealt.txt",APP) & )
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
#C
C
#include <stdio.h> #include <stdlib.h> #include <locale.h>   wchar_t s_suits[] = L"♣♦♥♠", s_nums[] = L"A23456789TJQK";   #define RMAX32 ((1U << 31) - 1) static int seed = 1; int rnd(void) { return (seed = (seed * 214013 + 2531011) & RMAX32) >> 16; } void srnd(int x) { seed = x; }   void show(const int *c) { int i; for (i = 0; i < 52; c++) { printf(" \033[%dm%lc\033[m%lc", 32 - (1 + *c) % 4 / 2, s_suits[*c % 4], s_nums[*c / 4]); if (!(++i % 8) || i == 52) putchar('\n'); } }   void deal(int s, int *t) { int i, j; srnd(s);   for (i = 0; i < 52; i++) t[i] = 51 - i; for (i = 0; i < 51; i++) { j = 51 - rnd() % (52 - i); s = t[i], t[i] = t[j], t[j] = s; } }   int main(int c, char **v) { int s, card[52]; if (c < 2 || (s = atoi(v[1])) <= 0) s = 11982;   setlocale(LC_ALL, "");   deal(s, card); printf("Hand %d\n", s); show(card);   return 0; }
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.
#C.2B.2B
C++
#include <algorithm> #include <functional> #include <iostream> #include <iterator> #include <string> #include <sstream> #include <vector>   typedef unsigned char byte;   std::string deBruijn(int k, int n) { std::vector<byte> a(k * n, 0); std::vector<byte> seq;   std::function<void(int, int)> db; db = [&](int t, int p) { if (t > n) { if (n % p == 0) { for (int i = 1; i < p + 1; i++) { seq.push_back(a[i]); } } } else { a[t] = a[t - p]; db(t + 1, p); auto j = a[t - p] + 1; while (j < k) { a[t] = j & 0xFF; db(t + 1, t); j++; } } };   db(1, 1); std::string buf; for (auto i : seq) { buf.push_back('0' + i); } return buf + buf.substr(0, n - 1); }   bool allDigits(std::string s) { for (auto c : s) { if (c < '0' || '9' < c) { return false; } } return true; }   void validate(std::string db) { auto le = db.size(); std::vector<int> found(10000, 0); std::vector<std::string> errs;   // Check all strings of 4 consecutive digits within 'db' // to see if all 10,000 combinations occur without duplication. for (size_t i = 0; i < le - 3; i++) { auto s = db.substr(i, 4); if (allDigits(s)) { auto n = stoi(s); found[n]++; } }   for (int i = 0; i < 10000; i++) { if (found[i] == 0) { std::stringstream ss; ss << " PIN number " << i << " missing"; errs.push_back(ss.str()); } else if (found[i] > 1) { std::stringstream ss; ss << " PIN number " << i << " occurs " << found[i] << " times"; errs.push_back(ss.str()); } }   if (errs.empty()) { std::cout << " No errors found\n"; } else { auto pl = (errs.size() == 1) ? "" : "s"; std::cout << " " << errs.size() << " error" << pl << " found:\n"; for (auto e : errs) { std::cout << e << '\n'; } } }   int main() { std::ostream_iterator<byte> oi(std::cout, ""); auto db = deBruijn(10, 4);   std::cout << "The length of the de Bruijn sequence is " << db.size() << "\n\n"; std::cout << "The first 130 digits of the de Bruijn sequence are: "; std::copy_n(db.cbegin(), 130, oi); std::cout << "\n\nThe last 130 digits of the de Bruijn sequence are: "; std::copy(db.cbegin() + (db.size() - 130), db.cend(), oi); std::cout << "\n";   std::cout << "\nValidating the de Bruijn sequence:\n"; validate(db);   std::cout << "\nValidating the reversed de Bruijn sequence:\n"; auto rdb = db; std::reverse(rdb.begin(), rdb.end()); validate(rdb);   auto by = db; by[4443] = '.'; std::cout << "\nValidating the overlaid de Bruijn sequence:\n"; validate(by);   return 0; }
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.
#Fortran
Fortran
module Bounded implicit none   type BoundedInteger integer, private :: v ! we cannot allow direct access to this, or we integer, private :: from, to ! can't check the bounds! logical, private :: critical end type BoundedInteger   interface assignment(=) module procedure bounded_assign_bb, bounded_assign_bi !, & ! bounded_assign_ib end interface   interface operator(+) module procedure bounded_add_bbb !, bounded_add_bbi, & ! bounded_add_bib, bounded_add_ibb, & ! bounded_add_iib, bounded_add_ibi, & ! bounded_add_bii end interface   private :: bounded_assign_bb, bounded_assign_bi, & bounded_add_bbb   contains   subroutine set_bound(bi, lower, upper, critical, value) type(BoundedInteger), intent(out) :: bi integer, intent(in) :: lower, upper integer, intent(in), optional :: value logical, intent(in), optional :: critical   bi%from = min(lower, upper) bi%to = max(lower, upper) if ( present(critical) ) then bi%critical = critical else bi%critical = .false. end if if ( present(value) ) then bi = value end if end subroutine set_bound   subroutine bounded_assign_bb(a, b) type(BoundedInteger), intent(out) :: a type(BoundedInteger), intent(in) :: b   call bounded_assign_bi(a, b%v)   end subroutine bounded_assign_bb     subroutine bounded_assign_bi(a, b) type(BoundedInteger), intent(out) :: a integer, intent(in) :: b   if ( (a%from <= b) .and. (a%to >= b) ) then a%v = b else write(0,*) "BoundedInteger: out of bound assignment" if ( a%critical ) then stop else if ( b < a%from ) then a%v = a%from else a%v = a%to end if write(0,"(A,' (',I0, ')')") "BoundedInteger: set to nearest bound", a%v end if end if end subroutine bounded_assign_bi     function bounded_add_bbb(a, b) result(c) type(BoundedInteger) :: c type(BoundedInteger), intent(in) :: a, b   integer :: t   c%from = max(a%from, b%from) c%to = min(a%to, b%to) t = a%v + b%v if ( c%from <= t .and. c%to >= t ) then c%v = t else write(0,*) "BoundedInteger: out of bound sum" if ( a%critical .or. b%critical ) then stop else if ( t < c%from ) then c%v = c%from else c%v = c%to end if write(0,"(A,' (',I0,')')") "BoundedInteger: set to nearest bound", c%v end if end if end function bounded_add_bbb   end module Bounded
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
#DWScript
DWScript
const cShades = '.:!*oe&#%@';   type TVector = array [0..2] of Float;   var light : TVector = [-50.0, 30, 50];   procedure Normalize(var v : TVector); begin var len := Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; end;   function Dot(x, y : TVector) : Float; begin var d :=x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; if d<0 then Result:=-d else Result:=0; end;   type TSphere = record cx, cy, cz, r : Float; end;   const big : TSphere = (cx: 20; cy: 20; cz: 0; r: 20); const small : TSphere = (cx: 7; cy: 7; cz: -10; r: 15);   function HitSphere(sph : TSphere; x, y : Float; var z1, z2 : Float) : Boolean; begin x -= sph.cx; y -= sph.cy; var zsq = sph.r * sph.r - (x * x + y * y); if (zsq < 0) then Exit False; zsq := Sqrt(zsq); z1 := sph.cz - zsq; z2 := sph.cz + zsq; Result:=True; end;   procedure DrawSphere(k, ambient : Float); var i, j, intensity : Integer; b : Float; x, y, zb1, zb2, zs1, zs2 : Float; vec : TVector; begin for i:=Trunc(big.cy-big.r) to Trunc(big.cy+big.r)+1 do begin y := i + 0.5; for j := Trunc(big.cx-2*big.r) to Trunc(big.cx+2*big.r) do begin x := (j-big.cx)/2 + 0.5 + big.cx;   if not HitSphere(big, x, y, zb1, zb2) then begin Print(' '); continue; end; if not HitSphere(small, x, y, zs1, zs2) then begin vec[0] := x - big.cx; vec[1] := y - big.cy; vec[2] := zb1 - big.cz; end else begin if zs1 < zb1 then begin if zs2 > zb2 then begin Print(' '); continue; end; if zs2 > zb1 then begin vec[0] := small.cx - x; vec[1] := small.cy - y; vec[2] := small.cz - zs2; end else begin vec[0] := x - big.cx; vec[1] := y - big.cy; vec[2] := zb1 - big.cz; end; end else begin vec[0] := x - big.cx; vec[1] := y - big.cy; vec[2] := zb1 - big.cz; end; end;   Normalize(vec); b := Power(Dot(light, vec), k) + ambient; intensity := Round((1 - b) * Length(cShades)); Print(cShades[ClampInt(intensity+1, 1, Length(cShades))]); end; PrintLn(''); end; end;   Normalize(light);   DrawSphere(2, 0.3);
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]
#R
R
conv <- function(a, b) { p <- length(a) q <- length(b) n <- p + q - 1 r <- nextn(n, f=2) y <- fft(fft(c(a, rep(0, r-p))) * fft(c(b, rep(0, r-q))), inverse=TRUE)/r y[1:n] }   deconv <- function(a, b) { p <- length(a) q <- length(b) n <- p - q + 1 r <- nextn(max(p, q), f=2) y <- fft(fft(c(a, rep(0, r-p))) / fft(c(b, rep(0, r-q))), inverse=TRUE)/r return(y[1: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]
#Racket
Racket
  #lang racket (require math/matrix) (define T matrix-transpose)   (define (convolution-matrix f m n) (define l (matrix-num-rows f)) (for*/matrix m n ([i (in-range 0 m)] [j (in-range 0 n)]) (cond [(or (< i j) (>= i (+ j l))) 0] [(matrix-ref f (- i j) 0)])))   (define (least-square X y) (matrix-solve (matrix* (T X) X) (matrix* (T X) y)))   (define (deconvolve g f) (define lg (matrix-num-rows g)) (define lf (matrix-num-rows f)) (define lh (+ (- lg lf) 1)) (least-square (convolution-matrix f lg lh) g))  
http://rosettacode.org/wiki/Deconvolution/2D%2B
Deconvolution/2D+
This task is a straightforward generalization of Deconvolution/1D to higher dimensions. For example, the one dimensional case would be applicable to audio signals, whereas two dimensions would pertain to images. Define the discrete convolution in d {\displaystyle {\mathit {d}}} dimensions of two functions H , F : Z d → R {\displaystyle H,F:\mathbb {Z} ^{d}\rightarrow \mathbb {R} } taking d {\displaystyle {\mathit {d}}} -tuples of integers to real numbers as the function G : Z d → R {\displaystyle G:\mathbb {Z} ^{d}\rightarrow \mathbb {R} } also taking d {\displaystyle {\mathit {d}}} -tuples of integers to reals and satisfying G ( n 0 , … , n d − 1 ) = ∑ m 0 = − ∞ ∞ … ∑ m d − 1 = − ∞ ∞ F ( m 0 , … , m d − 1 ) H ( n 0 − m 0 , … , n d − 1 − m d − 1 ) {\displaystyle G(n_{0},\dots ,n_{d-1})=\sum _{m_{0}=-\infty }^{\infty }\dots \sum _{m_{d-1}=-\infty }^{\infty }F(m_{0},\dots ,m_{d-1})H(n_{0}-m_{0},\dots ,n_{d-1}-m_{d-1})} for all d {\displaystyle {\mathit {d}}} -tuples of integers ( n 0 , … , n d − 1 ) ∈ Z d {\displaystyle (n_{0},\dots ,n_{d-1})\in \mathbb {Z} ^{d}} . Assume F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} (and therefore G {\displaystyle {\mathit {G}}} ) are non-zero over only a finite domain bounded by the origin, hence possible to represent as finite multi-dimensional arrays or nested lists f {\displaystyle {\mathit {f}}} , h {\displaystyle {\mathit {h}}} , and g {\displaystyle {\mathit {g}}} . For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by solving for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . (See Deconvolution/1D for details.) The function should work for g {\displaystyle {\mathit {g}}} of arbitrary length in each dimension (i.e., not hard coded or constant) and f {\displaystyle {\mathit {f}}} of any length up to that of g {\displaystyle {\mathit {g}}} in the corresponding dimension. The deconv function will need to be parameterized by the dimension d {\displaystyle {\mathit {d}}} unless the dimension can be inferred from the data structures representing g {\displaystyle {\mathit {g}}} and f {\displaystyle {\mathit {f}}} . 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. Debug your solution using this test data, of which a portion is shown below. Be sure to verify both that the deconvolution of g {\displaystyle {\mathit {g}}} with f {\displaystyle {\mathit {f}}} is h {\displaystyle {\mathit {h}}} and that the deconvolution of g {\displaystyle {\mathit {g}}} with h {\displaystyle {\mathit {h}}} is f {\displaystyle {\mathit {f}}} . Display the results in a human readable form for the three dimensional case only. dimension 1: h: [-8, 2, -9, -2, 9, -8, -2] f: [ 6, -9, -7, -5] g: [-48, 84, -16, 95, 125, -70, 7, 29, 54, 10] dimension 2: h: [ [-8, 1, -7, -2, -9, 4], [4, 5, -5, 2, 7, -1], [-6, -3, -3, -6, 9, 5]] f: [ [-5, 2, -2, -6, -7], [9, 7, -6, 5, -7], [1, -1, 9, 2, -7], [5, 9, -9, 2, -5], [-8, 5, -2, 8, 5]] g: [ [40, -21, 53, 42, 105, 1, 87, 60, 39, -28], [-92, -64, 19, -167, -71, -47, 128, -109, 40, -21], [58, 85, -93, 37, 101, -14, 5, 37, -76, -56], [-90, -135, 60, -125, 68, 53, 223, 4, -36, -48], [78, 16, 7, -199, 156, -162, 29, 28, -103, -10], [-62, -89, 69, -61, 66, 193, -61, 71, -8, -30], [48, -6, 21, -9, -150, -22, -56, 32, 85, 25]] dimension 3: h: [ [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]], [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]] f: [ [[-9, 5, -8], [3, 5, 1]], [[-1, -7, 2], [-5, -6, 6]], [[8, 5, 8],[-2, -6, -4]]] g: [ [ [54, 42, 53, -42, 85, -72], [45, -170, 94, -36, 48, 73], [-39, 65, -112, -16, -78, -72], [6, -11, -6, 62, 49, 8]], [ [-57, 49, -23, 52, -135, 66], [-23, 127, -58, -5, -118, 64], [87, -16, 121, 23, -41, -12], [-19, 29, 35, -148, -11, 45]], [ [-55, -147, -146, -31, 55, 60], [-88, -45, -28, 46, -26, -144], [-12, -107, -34, 150, 249, 66], [11, -15, -34, 27, -78, -50]], [ [56, 67, 108, 4, 2, -48], [58, 67, 89, 32, 32, -8], [-42, -31, -103, -30, -23, -8], [6, 4, -26, -10, 26, 12]]]
#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 row_len) { 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 < ns; i++) { if (cabs(creal(h[i])) < 1e-10) h[i] = 0; }   for (int i = 0; i > lf - lg - row_len; i--) out[-i] = h[(i + ns) % ns]/32; free(g2); free(f2); }   double* unpack2(void *m, int rows, int len, int to_len) { double *buf = calloc(sizeof(double), rows * to_len); for (int i = 0; i < rows; i++) for (int j = 0; j < len; j++) buf[i * to_len + j] = ((double(*)[len])m)[i][j]; return buf; }   void pack2(double * buf, int rows, int from_len, int to_len, void *out) { for (int i = 0; i < rows; i++) for (int j = 0; j < to_len; j++) ((double(*)[to_len])out)[i][j] = buf[i * from_len + j] / 4; }   void deconv2(void *g, int row_g, int col_g, void *f, int row_f, int col_f, void *out) { double *g2 = unpack2(g, row_g, col_g, col_g); double *f2 = unpack2(f, row_f, col_f, col_g);   double ff[(row_g - row_f + 1) * col_g]; deconv(g2, row_g * col_g, f2, row_f * col_g, ff, col_g); pack2(ff, row_g - row_f + 1, col_g, col_g - col_f + 1, out);   free(g2); free(f2); }   double* unpack3(void *m, int x, int y, int z, int to_y, int to_z) { double *buf = calloc(sizeof(double), x * to_y * to_z); for (int i = 0; i < x; i++) for (int j = 0; j < y; j++) { for (int k = 0; k < z; k++) buf[(i * to_y + j) * to_z + k] = ((double(*)[y][z])m)[i][j][k]; } return buf; }   void pack3(double * buf, int x, int y, int z, int to_y, int to_z, void *out) { for (int i = 0; i < x; i++) for (int j = 0; j < to_y; j++) for (int k = 0; k < to_z; k++) ((double(*)[to_y][to_z])out)[i][j][k] = buf[(i * y + j) * z + k] / 4; }   void deconv3(void *g, int gx, int gy, int gz, void *f, int fx, int fy, int fz, void *out) { double *g2 = unpack3(g, gx, gy, gz, gy, gz); double *f2 = unpack3(f, fx, fy, fz, gy, gz);   double ff[(gx - fx + 1) * gy * gz]; deconv(g2, gx * gy * gz, f2, fx * gy * gz, ff, gy * gz); pack3(ff, gx - fx + 1, gy, gz, gy - fy + 1, gz - fz + 1, out);   free(g2); free(f2); }   int main() { PI = atan2(1,1) * 4; double h[2][3][4] = { {{-6, -8, -5, 9}, {-7, 9, -6, -8}, { 2, -7, 9, 8}}, {{ 7, 4, 4, -6}, { 9, 9, 4, -4}, {-3, 7, -2, -3}} }; int hx = 2, hy = 3, hz = 4; double f[3][2][3] = { {{-9, 5, -8}, { 3, 5, 1}}, {{-1, -7, 2}, {-5, -6, 6}}, {{ 8, 5, 8}, {-2, -6, -4}} }; int fx = 3, fy = 2, fz = 3; double g[4][4][6] = { { { 54, 42, 53, -42, 85, -72}, { 45,-170, 94, -36, 48, 73}, {-39, 65,-112, -16, -78, -72}, { 6, -11, -6, 62, 49, 8} }, { {-57, 49, -23, 52, -135, 66},{-23, 127, -58, -5, -118, 64}, { 87, -16, 121, 23, -41, -12},{-19, 29, 35,-148, -11, 45} }, { {-55, -147, -146, -31, 55, 60},{-88, -45, -28, 46, -26,-144}, {-12, -107, -34, 150, 249, 66},{ 11, -15, -34, 27, -78, -50} }, { { 56, 67, 108, 4, 2,-48},{ 58, 67, 89, 32, 32, -8}, {-42, -31,-103, -30,-23, -8},{ 6, 4, -26, -10, 26, 12} } }; int gx = 4, gy = 4, gz = 6;   double h2[gx - fx + 1][gy - fy + 1][gz - fz + 1]; deconv3(g, gx, gy, gz, f, fx, fy, fz, h2); printf("deconv3(g, f):\n"); for (int i = 0; i < gx - fx + 1; i++) { for (int j = 0; j < gy - fy + 1; j++) { for (int k = 0; k < gz - fz + 1; k++) printf("%g ", h2[i][j][k]); printf("\n"); } if (i < gx - fx) printf("\n"); }   double f2[gx - hx + 1][gy - hy + 1][gz - hz + 1]; deconv3(g, gx, gy, gz, h, hx, hy, hz, f2); printf("\ndeconv3(g, h):\n"); for (int i = 0; i < gx - hx + 1; i++) { for (int j = 0; j < gy - hy + 1; j++) { for (int k = 0; k < gz - hz + 1; k++) printf("%g ", f2[i][j][k]); printf("\n"); } if (i < gx - hx) printf("\n"); } }   /* two-D case; since task doesn't require showing it, it's commented out */ /* int main() { PI = atan2(1,1) * 4; double h[][6] = { {-8, 1, -7, -2, -9, 4}, {4, 5, -5, 2, 7, -1}, {-6, -3, -3, -6, 9, 5} }; int hr = 3, hc = 6;   double f[][5] = { {-5, 2, -2, -6, -7}, {9, 7, -6, 5, -7}, {1, -1, 9, 2, -7}, {5, 9, -9, 2, -5}, {-8, 5, -2, 8, 5} }; int fr = 5, fc = 5; double g[][10] = { {40, -21, 53, 42, 105, 1, 87, 60, 39, -28}, {-92, -64, 19, -167, -71, -47, 128, -109, 40, -21}, {58, 85, -93, 37, 101, -14, 5, 37, -76, -56}, {-90, -135, 60, -125, 68, 53, 223, 4, -36, -48}, {78, 16, 7, -199, 156, -162, 29, 28, -103, -10}, {-62, -89, 69, -61, 66, 193, -61, 71, -8, -30}, {48, -6, 21, -9, -150, -22, -56, 32, 85, 25} }; int gr = 7, gc = 10;   double h2[gr - fr + 1][gc - fc + 1]; deconv2(g, gr, gc, f, fr, fc, h2); for (int i = 0; i < gr - fr + 1; i++) { for (int j = 0; j < gc - fc + 1; j++) printf(" %g", h2[i][j]); printf("\n"); }   double f2[gr - hr + 1][gc - hc + 1]; deconv2(g, gr, gc, h, hr, hc, f2); for (int i = 0; i < gr - hr + 1; i++) { for (int j = 0; j < gc - hc + 1; j++) printf(" %g", f2[i][j]); printf("\n"); } }*/
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
#C.23
C#
using System; using System.Collections.Generic; using System.Text;   namespace FreeCellDeals { public class RNG { private int _state;   public RNG() { _state = (int)DateTime.Now.Ticks; }   public RNG(int n) { _state = n; } public int Next() { return ((_state = 214013 * _state + 2531011) & int.MaxValue) >> 16; } }   public enum Rank { Ace, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King }   public enum Suit { Clubs, Diamonds, Hearts, Spades }   public class Card { private const string Ranks = "A23456789TJQK"; private const string Suits = "CDHS";   private Rank _rank; public Rank Rank { get { return _rank; } set { if ((int)value < 0 || (int)value > 12) { throw new InvalidOperationException("Setting card rank out of range"); } _rank = value; } }   private Suit _suit; public Suit Suit { get { return _suit; } set { if ((int)value < 0 || (int)value > 3) { throw new InvalidOperationException("Setting card rank out of range"); } _suit = value; } }   public Card(Rank rank, Suit suit) { Rank = rank; Suit = suit; }   public int NRank() { return (int) Rank; }   public int NSuit() { return (int) Suit; }   public override string ToString() { return new string(new[] {Ranks[NRank()], Suits[NSuit()]}); } }   public class FreeCellDeal { public List<Card> Deck { get; private set; }   public FreeCellDeal(int iDeal) { RNG rng = new RNG(iDeal);   List<Card> rDeck = new List<Card>(); Deck = new List<Card>();   for (int rank = 0; rank < 13; rank++) { for (int suit = 0; suit < 4; suit++) { rDeck.Add(new Card((Rank)rank, (Suit)suit)); } }   // Normally we deal from the front of a deck. The algorithm "deals" from the back so we reverse the // deck here to more conventionally deal from the front/start of the array. for (int iCard = 51; iCard >= 0; iCard--) { int iSwap = rng.Next() % (iCard + 1); Deck.Add(rDeck[iSwap]); rDeck[iSwap] = rDeck[iCard]; } }   public override string ToString() { StringBuilder sb = new StringBuilder(); for (int iRow = 0; iRow < 6; iRow++ ) { for (int iCol = 0; iCol < 8; iCol++) { sb.AppendFormat("{0} ", Deck[iRow * 8 + iCol]); } sb.Append("\n"); } for (int iCard = 48; iCard < 52; iCard++) { sb.AppendFormat("{0} ", Deck[iCard]); } return sb.ToString(); } }   class Program { static void Main() { Console.WriteLine(new FreeCellDeal(1)); Console.WriteLine(); Console.WriteLine(new FreeCellDeal(617)); } } }
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.
#CLU
CLU
% Generate the De Bruijn sequence consisiting of N-digit numbers de_bruijn = cluster is generate rep = null own k: int := 0 own n: int := 0 own a: array[int] := array[int]$[] own seq: array[int] := array[int]$[]   generate = proc (k_, n_: int) returns (string) k := k_ n := n_ a := array[int]$fill(0, k*n, 0) seq := array[int]$[] db(1, 1) s: stream := stream$create_output() for i: int in array[int]$elements(seq) do stream$puts(s, int$unparse(i)) end return(stream$get_contents(s)) end generate   db = proc (t, p: int) if t>n then if n//p = 0 then for i: int in int$from_to(1, p) do array[int]$addh(seq, a[i]) end end else a[t] := a[t - p] db(t+1, p) for j: int in int$from_to(a[t - p] + 1, k-1) do a[t] := j db(t + 1, t) end end end db end de_bruijn   % Reverse a string reverse = proc (s: string) returns (string) r: array[char] := array[char]$predict(1, string$size(s)) for c: char in string$chars(s) do array[char]$addl(r, c) end return(string$ac2s(r)) end reverse   % Find all missing N-digit values find_missing = proc (db: string, n: int) returns (sequence[string]) db := db || string$substr(db, 1, n) % wrap missing: array[string] := array[string]$[] s: stream := stream$create_output() for i: int in int$from_to(0, 10**n-1) do  %s: stream := stream$create_output() stream$reset(s) stream$putzero(s, int$unparse(i), n) val: string := stream$get_contents(s) if string$indexs(val, db) = 0 then array[string]$addh(missing, val) end end return(sequence[string]$a2s(missing)) end find_missing   % Report all missing values, or 'none'. validate = proc (s: stream, db: string, n: int) stream$puts(s, "Validating...") missing: sequence[string] := find_missing(db, n) for v: string in sequence[string]$elements(missing) do stream$puts(s, " " || v) end if sequence[string]$size(missing) = 0 then stream$puts(s, " none") end stream$putl(s, " missing.") end validate   start_up = proc () po: stream := stream$primary_output()    % Generate the De Bruijn sequence for 4-digit numbers db: string := de_bruijn$generate(10, 4)    % Report length and first and last digits stream$putl(po, "Length: " || int$unparse(string$size(db))) stream$putl(po, "First 130 characters:") stream$putl(po, string$substr(db, 1, 130)) stream$putl(po, "Last 130 characters:") stream$putl(po, string$substr(db, string$size(db)-130, 130))    % See if there are any missing values in the sequence validate(po, db, 4)    % Reverse and validate again stream$putl(po, "Reversing...") validate(po, reverse(db), 4)    % Replace the 4444'th element with '.' and validate again stream$putl(po, "Setting the 4444'th character to '.'...") db := string$substr(db, 1, 4443) || "." || string$rest(db, 4445) validate(po, db, 4) end start_up
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.
#D
D
import std.array; import std.conv; import std.format; import std.range; import std.stdio;   immutable DIGITS = "0123456789";   string deBruijn(int k, int n) { auto alphabet = DIGITS[0..k]; byte[] a; a.length = k * n; byte[] seq;   void db(int t, int p) { if (t > n) { if (n % p == 0) { auto temp = a[1..p + 1]; seq ~= temp; } } else { a[t] = a[t - p]; db(t + 1, p); auto j = a[t - p] + 1; while (j < k) { a[t] = cast(byte)(j & 0xFF); db(t + 1, t); j++; } } } db(1, 1); string buf; foreach (i; seq) { buf ~= alphabet[i]; }   return buf ~ buf[0 .. n - 1]; }   bool allDigits(string s) { foreach (c; s) { if (c < '0' || '9' < c) { return false; } } return true; }   void validate(string db) { auto le = db.length; int[10_000] found; string[] errs; // Check all strings of 4 consecutive digits within 'db' // to see if all 10,000 combinations occur without duplication. foreach (i; 0 .. le - 3) { auto s = db[i .. i + 4]; if (allDigits(s)) { auto n = s.to!int; found[n]++; } } foreach (i; 0 .. 10_000) { if (found[i] == 0) { errs ~= format(" PIN number %04d missing", i); } else if (found[i] > 1) { errs ~= format(" PIN number %04d occurs %d times", i, found[i]); } } if (errs.empty) { writeln(" No errors found"); } else { auto pl = (errs.length == 1) ? "" : "s"; writeln(" ", errs.length, " error", pl, " found:"); writefln("%-(%s\n%)", errs); } }   void main() { auto db = deBruijn(10, 4);   writeln("The length of the de Bruijn sequence is ", db.length); writeln("\nThe first 130 digits of the de Bruijn sequence are: ", db[0 .. 130]); writeln("\nThe last 130 digits of the de Bruijn sequence are: ", db[$ - 130 .. $]);   writeln("\nValidating the deBruijn sequence:"); validate(db);   writeln("\nValidating the reversed deBruijn sequence:"); validate(db.retro.to!string);   auto by = db.dup; by[4443] = '.'; db = by.idup; writeln("\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.
#Free_Pascal
Free Pascal
type range = 1..10; var n: range; begin n := 10; {$rangeChecks on} n := n + 10; // will yield a run-time error end;
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
#Frink
Frink
res = 254 / in v = callJava["frink.graphics.VoxelArray", "makeSphere", [1/2 inch res]]   dish = callJava["frink.graphics.VoxelArray", "makeSphere", [1/2 inch res]] dish.translate[round[.45 inch res], round[.45 inch res], round[.45 inch res]] v.remove[dish]   v.projectX[undef].show["X"] v.projectY[undef].show["Y"] v.projectZ[undef].show["Z"]   filename = "DeathStar.stl" print["Writing $filename..."] w = new Writer[filename] w.println[v.toSTLFormat["DeathStar", 1/(res mm)]] w.close[] println["done."]  
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
#Go
Go
package main   import ( "fmt" "image" "image/color" "image/png" "math" "os" )   type vector [3]float64   func (v *vector) normalize() { invLen := 1 / math.Sqrt(dot(v, v)) v[0] *= invLen v[1] *= invLen v[2] *= invLen }   func dot(x, y *vector) float64 { return x[0]*y[0] + x[1]*y[1] + x[2]*y[2] }   type sphere struct { cx, cy, cz int r int }   func (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) { x -= s.cx y -= s.cy if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 { zsqrt := math.Sqrt(float64(zsq)) return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true } return 0, 0, false }   func deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray { w, h := pos.r*4, pos.r*3 bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2) img := image.NewGray(bounds) vec := new(vector) for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ { for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ { zb1, zb2, hit := pos.hit(x, y) if !hit { continue } zs1, zs2, hit := neg.hit(x, y) if hit { if zs1 > zb1 { hit = false } else if zs2 > zb2 { continue } } if hit { vec[0] = float64(neg.cx - x) vec[1] = float64(neg.cy - y) vec[2] = float64(neg.cz) - zs2 } else { vec[0] = float64(x - pos.cx) vec[1] = float64(y - pos.cy) vec[2] = zb1 - float64(pos.cz) } vec.normalize() s := dot(dir, vec) if s < 0 { s = 0 } lum := 255 * (math.Pow(s, k) + amb) / (1 + amb) if lum < 0 { lum = 0 } else if lum > 255 { lum = 255 } img.SetGray(x, y, color.Gray{uint8(lum)}) } } return img }   func main() { dir := &vector{20, -40, -10} dir.normalize() pos := &sphere{0, 0, 0, 120} neg := &sphere{-90, -90, -30, 100}   img := deathStar(pos, neg, 1.5, .2, dir) f, err := os.Create("dstar.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, img); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
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]
#Raku
Raku
sub deconvolve (@g, @f) { my \h = 1 + @g - @f; my @m; @m[^@g;^h] »+=» 0; @m[^@g; h] »=«  @g; for ^h -> \j { for @f.kv -> \k, \v { @m[j+k;j] = v } } (rref @m)[^h;h] }   sub convolve (@f, @h) { my @g = 0 xx + @f + @h - 1; @g[^@f X+ ^@h] »+=« (@f X× @h); @g }   # Reduced Row Echelon Form simultaneous equation solver # Can handle over-specified systems of equations (N unknowns in N + M equations) sub rref (@m) { @m = trim-system @m; my ($lead, $rows, $cols) = 0, @m, @m[0]; for ^$rows -> $r { return @m unless $lead < $cols; my $i = $r; until @m[$i;$lead] { next unless ++$i == $rows; $i = $r; return @m if ++$lead == $cols; } @m[$i, $r] = @m[$r, $i] if $r != $i; @m[$r] »/=» $ = @m[$r;$lead]; for ^$rows -> $n { next if $n == $r; @m[$n] »-=» @m[$r] »×» (@m[$n;$lead] // 0); } ++$lead; } @m }   # Reduce to N equations in N unknowns; a no-op unless rows > cols sub trim-system (@m) { return @m unless @m ≥ @m[0]; my (\vars, @t) = @m[0] - 1; for ^vars -> \lead { for ^@m -> \row { @t.append: @m.splice(row, 1) and last if @m[row;lead]; } } while @t < vars and @m { @t.push: shift @m } @t }   my @h = (-8,-9,-3,-1,-6,7); my @f = (-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1); my @g = (24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7);   .say for ~@g, ~convolve(@f, @h),''; .say for ~@h, ~deconvolve(@g, @f),''; .say for ~@f, ~deconvolve(@g, @h),'';
http://rosettacode.org/wiki/Deconvolution/2D%2B
Deconvolution/2D+
This task is a straightforward generalization of Deconvolution/1D to higher dimensions. For example, the one dimensional case would be applicable to audio signals, whereas two dimensions would pertain to images. Define the discrete convolution in d {\displaystyle {\mathit {d}}} dimensions of two functions H , F : Z d → R {\displaystyle H,F:\mathbb {Z} ^{d}\rightarrow \mathbb {R} } taking d {\displaystyle {\mathit {d}}} -tuples of integers to real numbers as the function G : Z d → R {\displaystyle G:\mathbb {Z} ^{d}\rightarrow \mathbb {R} } also taking d {\displaystyle {\mathit {d}}} -tuples of integers to reals and satisfying G ( n 0 , … , n d − 1 ) = ∑ m 0 = − ∞ ∞ … ∑ m d − 1 = − ∞ ∞ F ( m 0 , … , m d − 1 ) H ( n 0 − m 0 , … , n d − 1 − m d − 1 ) {\displaystyle G(n_{0},\dots ,n_{d-1})=\sum _{m_{0}=-\infty }^{\infty }\dots \sum _{m_{d-1}=-\infty }^{\infty }F(m_{0},\dots ,m_{d-1})H(n_{0}-m_{0},\dots ,n_{d-1}-m_{d-1})} for all d {\displaystyle {\mathit {d}}} -tuples of integers ( n 0 , … , n d − 1 ) ∈ Z d {\displaystyle (n_{0},\dots ,n_{d-1})\in \mathbb {Z} ^{d}} . Assume F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} (and therefore G {\displaystyle {\mathit {G}}} ) are non-zero over only a finite domain bounded by the origin, hence possible to represent as finite multi-dimensional arrays or nested lists f {\displaystyle {\mathit {f}}} , h {\displaystyle {\mathit {h}}} , and g {\displaystyle {\mathit {g}}} . For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by solving for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . (See Deconvolution/1D for details.) The function should work for g {\displaystyle {\mathit {g}}} of arbitrary length in each dimension (i.e., not hard coded or constant) and f {\displaystyle {\mathit {f}}} of any length up to that of g {\displaystyle {\mathit {g}}} in the corresponding dimension. The deconv function will need to be parameterized by the dimension d {\displaystyle {\mathit {d}}} unless the dimension can be inferred from the data structures representing g {\displaystyle {\mathit {g}}} and f {\displaystyle {\mathit {f}}} . 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. Debug your solution using this test data, of which a portion is shown below. Be sure to verify both that the deconvolution of g {\displaystyle {\mathit {g}}} with f {\displaystyle {\mathit {f}}} is h {\displaystyle {\mathit {h}}} and that the deconvolution of g {\displaystyle {\mathit {g}}} with h {\displaystyle {\mathit {h}}} is f {\displaystyle {\mathit {f}}} . Display the results in a human readable form for the three dimensional case only. dimension 1: h: [-8, 2, -9, -2, 9, -8, -2] f: [ 6, -9, -7, -5] g: [-48, 84, -16, 95, 125, -70, 7, 29, 54, 10] dimension 2: h: [ [-8, 1, -7, -2, -9, 4], [4, 5, -5, 2, 7, -1], [-6, -3, -3, -6, 9, 5]] f: [ [-5, 2, -2, -6, -7], [9, 7, -6, 5, -7], [1, -1, 9, 2, -7], [5, 9, -9, 2, -5], [-8, 5, -2, 8, 5]] g: [ [40, -21, 53, 42, 105, 1, 87, 60, 39, -28], [-92, -64, 19, -167, -71, -47, 128, -109, 40, -21], [58, 85, -93, 37, 101, -14, 5, 37, -76, -56], [-90, -135, 60, -125, 68, 53, 223, 4, -36, -48], [78, 16, 7, -199, 156, -162, 29, 28, -103, -10], [-62, -89, 69, -61, 66, 193, -61, 71, -8, -30], [48, -6, 21, -9, -150, -22, -56, 32, 85, 25]] dimension 3: h: [ [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]], [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]] f: [ [[-9, 5, -8], [3, 5, 1]], [[-1, -7, 2], [-5, -6, 6]], [[8, 5, 8],[-2, -6, -4]]] g: [ [ [54, 42, 53, -42, 85, -72], [45, -170, 94, -36, 48, 73], [-39, 65, -112, -16, -78, -72], [6, -11, -6, 62, 49, 8]], [ [-57, 49, -23, 52, -135, 66], [-23, 127, -58, -5, -118, 64], [87, -16, 121, 23, -41, -12], [-19, 29, 35, -148, -11, 45]], [ [-55, -147, -146, -31, 55, 60], [-88, -45, -28, 46, -26, -144], [-12, -107, -34, 150, 249, 66], [11, -15, -34, 27, -78, -50]], [ [56, 67, 108, 4, 2, -48], [58, 67, 89, 32, 32, -8], [-42, -31, -103, -30, -23, -8], [6, 4, -26, -10, 26, 12]]]
#D
D
import std.stdio, std.conv, std.algorithm, std.numeric, std.range;   class M(T) { private size_t[] dim; private size_t[] subsize; private T[] d;   this(size_t[] dimension...) pure nothrow { setDimension(dimension); d[] = 0; // init each entry to zero; }   M!T dup() { auto m = new M!T(dim); return m.set1DArray(d); }   M!T setDimension(size_t[] dimension ...) pure nothrow { foreach (const e; dimension) assert(e > 0, "no zero dimension"); dim = dimension.dup; subsize = dim.dup; foreach (immutable i; 0 .. dim.length) subsize[i] = reduce!q{a * b}(1, dim[i + 1 .. $]); immutable dlength = dim[0] * subsize[0]; if (d.length != dlength) d = new T[dlength]; return this; }   M!T set1DArray(in T[] t ...) pure nothrow @nogc { auto minLen = min(t.length, d.length); d[] = 0; d[0 .. minLen] = t[0 .. minLen]; return this; }   size_t[] seq2idx(in size_t seq) const pure nothrow { size_t acc = seq, tmp; size_t[] idx; foreach (immutable e; subsize) { idx ~= tmp = acc / e; acc = acc - tmp * e; // same as % (mod) e. } return idx; }   size_t size() const pure nothrow @nogc @property { return d.length; }   size_t rank() const pure nothrow @nogc @property { return dim.length; }   size_t[] shape() const pure nothrow @property { return dim.dup; }   T[] raw() const pure nothrow @property { return d.dup; }   bool checkBound(size_t[] idx ...) const pure nothrow @nogc { if (idx.length > dim.length) return false; foreach (immutable i, immutable dm; idx) if (dm >= dim[i]) return false; return true; }   T opIndex(size_t[] idx ...) const pure nothrow @nogc { assert(checkBound(idx), "OOPS"); return d[dotProduct(idx, subsize)]; }   T opIndexAssign(T v, size_t[] idx ...) pure nothrow @nogc { assert(checkBound(idx), "OOPS"); d[dotProduct(idx, subsize)] = v; return v; }   override bool opEquals(Object o) const pure { const rhs = to!(M!T)(o); return dim == rhs.dim && d == rhs.d; }   int opApply(int delegate(ref size_t[]) dg) const { size_t[] yieldIdx; foreach (immutable i; 0 .. d.length) { yieldIdx = seq2idx(i); if (dg(yieldIdx)) break; } return 0; }   int opApply(int delegate(ref size_t[], ref T) dg) { size_t idx1d = 0; foreach (idx; this) { if (dg(idx, d[idx1d++])) break; } return 0; }   // _this_ is h, rhs is f, output g. M!T convolute(M!T rhs) const pure nothrow { auto dm = dim.dup; dm[] += rhs.dim[] - 1; M!T m = new M!T(dm); // dm will be reused as m's idx. auto bound = m.size; foreach (immutable i; 0 .. d.length) { auto thisIdx = seq2idx(i); foreach (immutable j; 0 .. rhs.d.length) { dm[] = thisIdx[] + rhs.seq2idx(j)[]; immutable midx1d = dotProduct(dm, m.subsize); if (midx1d < bound) m.d[midx1d] += d[i] * rhs.d[j]; else break; // Bound reach, OK to break. } } return m; }   // _this_ is g, rhs is f, output is h. M!T deconvolute(M!T rhs) const pure nothrow { auto dm = dim.dup; foreach (i, e; dm) assert(e + 1 > rhs.dim[i], "deconv : dimensions is zero or negative"); dm[] -= (rhs.dim[] - 1); auto m = new M!T(dm); // dm will be reused as rhs' idx.   foreach (immutable i; 0 .. m.size) { auto idx = m.seq2idx(i); m.d[i] = this[idx]; foreach (immutable j; 0 .. i) { immutable jdx = m.seq2idx(j); dm[] = idx[] - jdx[]; if (rhs.checkBound(dm)) m.d[i] -= m.d[j] * rhs[dm]; } m.d[i] /= rhs.d[0]; } return m; }   override string toString() const pure { return d.text; } }   auto fold(T)(T[] arr, ref size_t[] d) pure { if (d.length == 0) d ~= arr.length;   static if (is(T U : U[])) { // Is arr an array of arrays? assert(arr.length > 0, "no empty dimension"); d ~= arr[0].length; foreach (e; arr) assert(e.length == arr[0].length, "Not rectangular"); return fold(arr.reduce!q{a ~ b}, d); } else { assert(arr.length == d.reduce!q{a * b}, "Not same size"); return arr; } }   auto arr2M(T)(T a) pure { size_t[] dm; auto d = fold(a, dm); alias E = ElementType!(typeof(d)); auto m = new M!E(dm); m.set1DArray(d); return m; }   void main() { alias Mi = M!int; auto hh = [[[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]], [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]]; auto ff = [[[-9, 5, -8], [3, 5, 1]],[[-1, -7, 2], [-5, -6, 6]], [[8, 5, 8],[-2, -6, -4]]]; auto h = arr2M(hh); auto f = arr2M(ff);   const g = h.convolute(f);   writeln("g == f convolute h ? ", g == f.convolute(h)); writeln("h == g deconv f  ? ", h == g.deconvolute(f)); writeln("f == g deconv h  ? ", f == g.deconvolute(h)); writeln(" f = ", f); writeln("g deconv h = ", g.deconvolute(h)); }
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
#C.2B.2B
C++
  #include <windows.h> #include <iostream>   //-------------------------------------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------------------------------------- class fc_dealer { public: void deal( int game ) { _gn = game; fillDeck(); shuffle(); display(); }   private: void fillDeck() { int p = 0; for( int c = 0; c < 13; c++ ) for( int s = 0; s < 4; s++ ) _cards[p++] = c | s << 4; }   void shuffle() { srand( _gn ); int cc = 52, nc, lc; while( cc ) { nc = rand() % cc; lc = _cards[--cc]; _cards[cc] = _cards[nc]; _cards[nc] = lc; } }   void display() { char* suit = "CDHS"; char* symb = "A23456789TJQK"; int z = 0; cout << "GAME #" << _gn << endl << "=======================" << endl; for( int c = 51; c >= 0; c-- ) { cout << symb[_cards[c] & 15] << suit[_cards[c] >> 4] << " "; if( ++z >= 8 ) { cout << endl; z = 0; } } }   int _cards[52], _gn; }; //-------------------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) { fc_dealer dealer; int gn; while( true ) { cout << endl << "Game number please ( 0 to QUIT ): "; cin >> gn; if( !gn ) break;   system( "cls" ); dealer.deal( gn ); cout << endl << endl; } return 0; } //--------------------------------------------------------------------------------------------------  
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.
#Go
Go
package main   import ( "bytes" "fmt" "strconv" "strings" )   const digits = "0123456789"   func deBruijn(k, n int) string { alphabet := digits[0:k] a := make([]byte, k*n) var seq []byte var db func(int, int) // recursive closure db = func(t, p int) { if t > n { if n%p == 0 { seq = append(seq, a[1:p+1]...) } } else { a[t] = a[t-p] db(t+1, p) for j := int(a[t-p] + 1); j < k; j++ { a[t] = byte(j) db(t+1, t) } } } db(1, 1) var buf bytes.Buffer for _, i := range seq { buf.WriteByte(alphabet[i]) } b := buf.String() return b + b[0:n-1] // as cyclic append first (n-1) digits }   func allDigits(s string) bool { for _, b := range s { if b < '0' || b > '9' { return false } } return true }   func validate(db string) { le := len(db) found := make([]int, 10000) var errs []string // Check all strings of 4 consecutive digits within 'db' // to see if all 10,000 combinations occur without duplication. for i := 0; i < le-3; i++ { s := db[i : i+4] if allDigits(s) { n, _ := strconv.Atoi(s) found[n]++ } } for i := 0; i < 10000; i++ { if found[i] == 0 { errs = append(errs, fmt.Sprintf(" PIN number %04d missing", i)) } else if found[i] > 1 { errs = append(errs, fmt.Sprintf(" PIN number %04d occurs %d times", i, found[i])) } } lerr := len(errs) if lerr == 0 { fmt.Println(" No errors found") } else { pl := "s" if lerr == 1 { pl = "" } fmt.Printf("  %d error%s found:\n", lerr, pl) fmt.Println(strings.Join(errs, "\n")) } }   func reverse(s string) string { bytes := []byte(s) for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { bytes[i], bytes[j] = bytes[j], bytes[i] } return string(bytes) }   func main() { db := deBruijn(10, 4) le := len(db) fmt.Println("The length of the de Bruijn sequence is", le) fmt.Println("\nThe first 130 digits of the de Bruijn sequence are:") fmt.Println(db[0:130]) fmt.Println("\nThe last 130 digits of the de Bruijn sequence are:") fmt.Println(db[le-130:]) fmt.Println("\nValidating the de Bruijn sequence:") validate(db)   fmt.Println("\nValidating the reversed de Bruijn sequence:") dbr := reverse(db) validate(dbr)   bytes := []byte(db) bytes[4443] = '.' db = string(bytes) fmt.Println("\nValidating the overlaid de Bruijn 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.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Type MyInteger Private: Dim i_ As Integer Public: Declare Constructor(i_ As Integer) Declare Property I() As Integer Declare Operator Cast() As Integer Declare Operator Cast() As String End Type   Constructor MyInteger(i_ As Integer) If i_ < 1 Then i_ = 1 ElseIf i_ > 10 Then i_ = 10 End If This.i_ = i_ End Constructor   Property MyInteger.I() As Integer Return i_ End Property   Operator MyInteger.Cast() As Integer Return i_ End Operator   Operator MyInteger.Cast() As String Return Str(i_) End Operator   Dim i As MyInteger = 11 ' implicit constructor call; i_ automatically limited to 10 Dim j As MyInteger = 3 ' implicit constructor call; no adjustment needed Dim k As Integer = 4 Print "i = "; i; " j = " ; j; " k = "; k; " j + 6 ="; j.I + 6; " j + k ="; j + k Print Print "Press any key to quit" Sleep
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
#Haskell
Haskell
import Data.List (genericLength)   shades = ".:!*oe%#&@" n = genericLength shades dot a b = sum $ zipWith (*) a b normalize x = (/ sqrt (x `dot` x)) <$> x   deathStar r k amb = unlines $ [ [ if x*x + y*y <= r*r then let vec = normalize $ normal x y b = (light `dot` vec) ** k + amb intensity = (1 - b)*(n - 1) in shades !! round ((0 `max` intensity) `min` n) else ' ' | y <- map (/2.12) [- 2*r - 0.5 .. 2*r + 0.5] ] | x <- [ - r - 0.5 .. r + 0.5] ] where light = normalize [-30,-30,-50] normal x y | (x+r)**2 + (y+r)**2 <= r**2 = [x+r, y+r, sph2 x y] | otherwise = [x, y, sph1 x y] sph1 x y = sqrt (r*r - x*x - y*y) sph2 x y = r - sqrt (r*r - (x+r)**2 - (y+r)**2)
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]
#REXX
REXX
/*REXX pgm performs deconvolution of two arrays: deconv(g,f)=h and deconv(g,h)=f */ call make 'H', "-8 -9 -3 -1 -6 7" call make 'F', "-3 -6 -1 8 -6 3 -1 -9 -9 3 -2 5 2 -2 -7 -1" call make 'G', "24 75 71 -34 3 22 -45 23 245 25 52 25 -67 -96 96 31 55 36 29 -43 -7" call show 'H' /*display the elements of array H. */ call show 'F' /* " " " " " F. */ call show 'G' /* " " " " " G. */ call deco 'G', "F", 'X' /*deconvolution of G and F ───► X */ call test 'X', "H" /*test: is array H equal to array X?*/ call deco 'G', "H", 'Y' /*deconvolution of G and H ───► Y */ call test 'F', "Y" /*test: is array F equal to array Y?*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ deco: parse arg $1,$2,$r; b= @.$2.# + 1; a= @.$1.# + 1 /*get sizes of array 1&2*/ @.$r.#= a - b /*size of return array. */ do n=0 to a-b /*define return array. */ @.$r.n= @.$1.n /*define RETURN element.*/ if n<b then L= 0 /*define the variable L.*/ else L= n - b + 1 /* " " " " */ if n>0 then do j=L to n-1; _= n-j /*define elements > 0. */ @.$r.n= @.$r.n - @.$r.j * @.$2._ /*compute " " " */ end /*j*/ /* [↑] subtract product.*/ @.$r.n= @.$r.n / @.$2.0 /*divide array element. */ end /*n*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ make: parse arg $,z; @.$.#= words(z) - 1 /*obtain args; set size.*/ do k=0 to @.$.#; @.$.k= word(z, k + 1) /*define array element. */ end /*k*/; return /*array starts at unity.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ show: parse arg $,z,_; do s=0 to @.$.#; _= strip(_ @.$.s) /*obtain the arguments. */ end /*s*/ /* [↑] build the list. */ say 'array' $": " _; return /*show the list; return*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ test: parse arg $1,$2; do t=0 to max(@.$1.#, @.$2.#) /*obtain the arguments. */ if @.$1.t= @.$2.t then iterate /*create array list. */ say "***error*** arrays" $1 ' and ' $2 "aren't equal." end /*t*/; return /* [↑] build the list. */
http://rosettacode.org/wiki/Deconvolution/2D%2B
Deconvolution/2D+
This task is a straightforward generalization of Deconvolution/1D to higher dimensions. For example, the one dimensional case would be applicable to audio signals, whereas two dimensions would pertain to images. Define the discrete convolution in d {\displaystyle {\mathit {d}}} dimensions of two functions H , F : Z d → R {\displaystyle H,F:\mathbb {Z} ^{d}\rightarrow \mathbb {R} } taking d {\displaystyle {\mathit {d}}} -tuples of integers to real numbers as the function G : Z d → R {\displaystyle G:\mathbb {Z} ^{d}\rightarrow \mathbb {R} } also taking d {\displaystyle {\mathit {d}}} -tuples of integers to reals and satisfying G ( n 0 , … , n d − 1 ) = ∑ m 0 = − ∞ ∞ … ∑ m d − 1 = − ∞ ∞ F ( m 0 , … , m d − 1 ) H ( n 0 − m 0 , … , n d − 1 − m d − 1 ) {\displaystyle G(n_{0},\dots ,n_{d-1})=\sum _{m_{0}=-\infty }^{\infty }\dots \sum _{m_{d-1}=-\infty }^{\infty }F(m_{0},\dots ,m_{d-1})H(n_{0}-m_{0},\dots ,n_{d-1}-m_{d-1})} for all d {\displaystyle {\mathit {d}}} -tuples of integers ( n 0 , … , n d − 1 ) ∈ Z d {\displaystyle (n_{0},\dots ,n_{d-1})\in \mathbb {Z} ^{d}} . Assume F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} (and therefore G {\displaystyle {\mathit {G}}} ) are non-zero over only a finite domain bounded by the origin, hence possible to represent as finite multi-dimensional arrays or nested lists f {\displaystyle {\mathit {f}}} , h {\displaystyle {\mathit {h}}} , and g {\displaystyle {\mathit {g}}} . For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by solving for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . (See Deconvolution/1D for details.) The function should work for g {\displaystyle {\mathit {g}}} of arbitrary length in each dimension (i.e., not hard coded or constant) and f {\displaystyle {\mathit {f}}} of any length up to that of g {\displaystyle {\mathit {g}}} in the corresponding dimension. The deconv function will need to be parameterized by the dimension d {\displaystyle {\mathit {d}}} unless the dimension can be inferred from the data structures representing g {\displaystyle {\mathit {g}}} and f {\displaystyle {\mathit {f}}} . 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. Debug your solution using this test data, of which a portion is shown below. Be sure to verify both that the deconvolution of g {\displaystyle {\mathit {g}}} with f {\displaystyle {\mathit {f}}} is h {\displaystyle {\mathit {h}}} and that the deconvolution of g {\displaystyle {\mathit {g}}} with h {\displaystyle {\mathit {h}}} is f {\displaystyle {\mathit {f}}} . Display the results in a human readable form for the three dimensional case only. dimension 1: h: [-8, 2, -9, -2, 9, -8, -2] f: [ 6, -9, -7, -5] g: [-48, 84, -16, 95, 125, -70, 7, 29, 54, 10] dimension 2: h: [ [-8, 1, -7, -2, -9, 4], [4, 5, -5, 2, 7, -1], [-6, -3, -3, -6, 9, 5]] f: [ [-5, 2, -2, -6, -7], [9, 7, -6, 5, -7], [1, -1, 9, 2, -7], [5, 9, -9, 2, -5], [-8, 5, -2, 8, 5]] g: [ [40, -21, 53, 42, 105, 1, 87, 60, 39, -28], [-92, -64, 19, -167, -71, -47, 128, -109, 40, -21], [58, 85, -93, 37, 101, -14, 5, 37, -76, -56], [-90, -135, 60, -125, 68, 53, 223, 4, -36, -48], [78, 16, 7, -199, 156, -162, 29, 28, -103, -10], [-62, -89, 69, -61, 66, 193, -61, 71, -8, -30], [48, -6, 21, -9, -150, -22, -56, 32, 85, 25]] dimension 3: h: [ [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]], [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]] f: [ [[-9, 5, -8], [3, 5, 1]], [[-1, -7, 2], [-5, -6, 6]], [[8, 5, 8],[-2, -6, -4]]] g: [ [ [54, 42, 53, -42, 85, -72], [45, -170, 94, -36, 48, 73], [-39, 65, -112, -16, -78, -72], [6, -11, -6, 62, 49, 8]], [ [-57, 49, -23, 52, -135, 66], [-23, 127, -58, -5, -118, 64], [87, -16, 121, 23, -41, -12], [-19, 29, 35, -148, -11, 45]], [ [-55, -147, -146, -31, 55, 60], [-88, -45, -28, 46, -26, -144], [-12, -107, -34, 150, 249, 66], [11, -15, -34, 27, -78, -50]], [ [56, 67, 108, 4, 2, -48], [58, 67, 89, 32, 32, -8], [-42, -31, -103, -30, -23, -8], [6, 4, -26, -10, 26, 12]]]
#Go
Go
package main   import ( "fmt" "math" "math/cmplx" )   func fft(buf []complex128, n int) { out := make([]complex128, n) copy(out, buf) fft2(buf, out, n, 1) }   func fft2(buf, out []complex128, n, step int) { if step < n { fft2(out, buf, n, step*2) fft2(out[step:], buf[step:], n, step*2) for j := 0; j < n; j += 2 * step { fj, fn := float64(j), float64(n) t := cmplx.Exp(-1i*complex(math.Pi, 0)*complex(fj, 0)/complex(fn, 0)) * out[j+step] buf[j/2] = out[j] + t buf[(j+n)/2] = out[j] - t } } }   /* pad slice length to power of two */ func padTwo(g []float64, le int, ns *int) []complex128 { n := 1 if *ns != 0 { n = *ns } else { for n < le { n *= 2 } } buf := make([]complex128, n) for i := 0; i < le; i++ { buf[i] = complex(g[i], 0) } *ns = n return buf }   func deconv(g []float64, lg int, f []float64, lf int, out []float64, rowLe int) { ns := 0 g2 := padTwo(g, lg, &ns) f2 := padTwo(f, lf, &ns) fft(g2, ns) fft(f2, ns) h := make([]complex128, ns) for i := 0; i < ns; i++ { h[i] = g2[i] / f2[i] } fft(h, ns) for i := 0; i < ns; i++ { if math.Abs(real(h[i])) < 1e-10 { h[i] = 0 } } for i := 0; i > lf-lg-rowLe; i-- { out[-i] = real(h[(i+ns)%ns] / 32) } }   func unpack2(m [][]float64, rows, le, toLe int) []float64 { buf := make([]float64, rows*toLe) for i := 0; i < rows; i++ { for j := 0; j < le; j++ { buf[i*toLe+j] = m[i][j] } } return buf }   func pack2(buf []float64, rows, fromLe, toLe int, out [][]float64) { for i := 0; i < rows; i++ { for j := 0; j < toLe; j++ { out[i][j] = buf[i*fromLe+j] / 4 } } }   func deconv2(g [][]float64, rowG, colG int, f [][]float64, rowF, colF int, out [][]float64) { g2 := unpack2(g, rowG, colG, colG) f2 := unpack2(f, rowF, colF, colG) ff := make([]float64, (rowG-rowF+1)*colG) deconv(g2, rowG*colG, f2, rowF*colG, ff, colG) pack2(ff, rowG-rowF+1, colG, colG-colF+1, out) }   func unpack3(m [][][]float64, x, y, z, toY, toZ int) []float64 { buf := make([]float64, x*toY*toZ) for i := 0; i < x; i++ { for j := 0; j < y; j++ { for k := 0; k < z; k++ { buf[(i*toY+j)*toZ+k] = m[i][j][k] } } } return buf }   func pack3(buf []float64, x, y, z, toY, toZ int, out [][][]float64) { for i := 0; i < x; i++ { for j := 0; j < toY; j++ { for k := 0; k < toZ; k++ { out[i][j][k] = buf[(i*y+j)*z+k] / 4 } } } }   func deconv3(g [][][]float64, gx, gy, gz int, f [][][]float64, fx, fy, fz int, out [][][]float64) { g2 := unpack3(g, gx, gy, gz, gy, gz) f2 := unpack3(f, fx, fy, fz, gy, gz) ff := make([]float64, (gx-fx+1)*gy*gz) deconv(g2, gx*gy*gz, f2, fx*gy*gz, ff, gy*gz) pack3(ff, gx-fx+1, gy, gz, gy-fy+1, gz-fz+1, out) }   func main() { f := [][][]float64{ {{-9, 5, -8}, {3, 5, 1}}, {{-1, -7, 2}, {-5, -6, 6}}, {{8, 5, 8}, {-2, -6, -4}}, } fx, fy, fz := len(f), len(f[0]), len(f[0][0])   g := [][][]float64{ {{54, 42, 53, -42, 85, -72}, {45, -170, 94, -36, 48, 73}, {-39, 65, -112, -16, -78, -72}, {6, -11, -6, 62, 49, 8}}, {{-57, 49, -23, 52, -135, 66}, {-23, 127, -58, -5, -118, 64}, {87, -16, 121, 23, -41, -12}, {-19, 29, 35, -148, -11, 45}}, {{-55, -147, -146, -31, 55, 60}, {-88, -45, -28, 46, -26, -144}, {-12, -107, -34, 150, 249, 66}, {11, -15, -34, 27, -78, -50}}, {{56, 67, 108, 4, 2, -48}, {58, 67, 89, 32, 32, -8}, {-42, -31, -103, -30, -23, -8}, {6, 4, -26, -10, 26, 12}, }, } gx, gy, gz := len(g), len(g[0]), len(g[0][0])   h := [][][]float64{ {{-6, -8, -5, 9}, {-7, 9, -6, -8}, {2, -7, 9, 8}}, {{7, 4, 4, -6}, {9, 9, 4, -4}, {-3, 7, -2, -3}}, } hx, hy, hz := gx-fx+1, gy-fy+1, gz-fz+1   h2 := make([][][]float64, hx) for i := 0; i < hx; i++ { h2[i] = make([][]float64, hy) for j := 0; j < hy; j++ { h2[i][j] = make([]float64, hz) } } deconv3(g, gx, gy, gz, f, fx, fy, fz, h2) fmt.Println("deconv3(g, f):\n") for i := 0; i < hx; i++ { for j := 0; j < hy; j++ { for k := 0; k < hz; k++ { fmt.Printf("% .10g ", h2[i][j][k]) } fmt.Println() } if i < hx-1 { fmt.Println() } }   kx, ky, kz := gx-hx+1, gy-hy+1, gz-hz+1 f2 := make([][][]float64, kx) for i := 0; i < kx; i++ { f2[i] = make([][]float64, ky) for j := 0; j < ky; j++ { f2[i][j] = make([]float64, kz) } } deconv3(g, gx, gy, gz, h, hx, hy, hz, f2) fmt.Println("\ndeconv(g, h):\n") for i := 0; i < kx; i++ { for j := 0; j < ky; j++ { for k := 0; k < kz; k++ { fmt.Printf("% .10g ", f2[i][j][k]) } fmt.Println() } if i < kx-1 { fmt.Println() } } }
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
#Ceylon
Ceylon
shared void freeCellDeal() {   //a function that returns a random number generating function function createRNG(variable Integer state) => () => (state = (214_013 * state + 2_531_011) % 2^31) / 2^16;   void deal(Integer num) { // create an array with a list comprehension variable value deck = Array { for(rank in "A23456789TJQK") for(suit in "CDHS") "``rank````suit``" }; value rng = createRNG(num); for(i in 1..52) { value index = rng() % deck.size; assert(exists lastIndex = deck.lastIndex); //swap the random card with the last one deck.swap(index, lastIndex); //print the last one process.write("``deck.last else "missing card"`` " ); if(i % 8 == 0) { print(""); } //and shrink the array to remove the last card deck = deck[...lastIndex - 1]; } }   deal(1); print("\n"); deal(617); }
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
#Clojure
Clojure
(def deck (into [] (for [rank "A23456789TJQK" suit "CDHS"] (str rank suit))))   (defn lcg [seed] (map #(bit-shift-right % 16) (rest (iterate #(mod (+ (* % 214013) 2531011) (bit-shift-left 1 31)) seed))))   (defn gen [seed] (map (fn [rnd rng] (into [] [(mod rnd rng) (dec rng)])) (lcg seed) (range 52 0 -1)))   (defn xchg [v [src dst]] (assoc v dst (v src) src (v dst)))   (defn show [seed] (map #(println %) (partition 8 8 "" (reverse (reduce xchg deck (gen seed))))))   (show 1)
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.
#Groovy
Groovy
import java.util.function.BiConsumer   class DeBruijn { interface Recursable<T, U> { void apply(T t, U u, Recursable<T, U> r); }   static <T, U> BiConsumer<T, U> recurse(Recursable<T, U> f) { return { t, u -> f.apply(t, u, f) } }   private static String deBruijn(int k, int n) { byte[] a = new byte[k * n] Arrays.fill(a, (byte) 0)   List<Byte> seq = new ArrayList<>()   BiConsumer<Integer, Integer> db = recurse({ int t, int p, f -> if (t > n) { if (n % p == 0) { for (int i = 1; i < p + 1; ++i) { seq.add(a[i]) } } } else { a[t] = a[t - p] f.apply(t + 1, p, f) int j = a[t - p] + 1 while (j < k) { a[t] = (byte) (j & 0xFF) f.apply(t + 1, t, f) j++ } } }) db.accept(1, 1)   StringBuilder sb = new StringBuilder() for (Byte i : seq) { sb.append("0123456789".charAt(i)) }   sb.append(sb.subSequence(0, n - 1)) return sb.toString() }   private static boolean allDigits(String s) { for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i) if (!Character.isDigit(c)) { return false } } return true }   private static void validate(String db) { int le = db.length() int[] found = new int[10_000] Arrays.fill(found, 0) List<String> errs = new ArrayList<>()   // Check all strings of 4 consecutive digits within 'db' // to see if all 10,000 combinations occur without duplication. for (int i = 0; i < le - 3; ++i) { String s = db.substring(i, i + 4) if (allDigits(s)) { int n = Integer.parseInt(s) found[n]++ } }   for (int i = 0; i < 10_000; ++i) { if (found[i] == 0) { errs.add(String.format(" PIN number %d is missing", i)) } else if (found[i] > 1) { errs.add(String.format(" PIN number %d occurs %d times", i, found[i])) } }   if (errs.isEmpty()) { System.out.println(" No errors found") } else { String pl = (errs.size() == 1) ? "" : "s" System.out.printf("  %d error%s found:\n", errs.size(), pl) errs.forEach(System.out.&println) } }   static void main(String[] args) { String db = deBruijn(10, 4)   System.out.printf("The length of the de Bruijn sequence is %d\n\n", db.length()) System.out.printf("The first 130 digits of the de Bruijn sequence are: %s\n\n", db.substring(0, 130)) System.out.printf("The last 130 digits of the de Bruijn sequence are: %s\n\n", db.substring(db.length() - 130))   System.out.println("Validating the de Bruijn sequence:") validate(db)   StringBuilder sb = new StringBuilder(db) String rdb = sb.reverse().toString() System.out.println() System.out.println("Validating the de Bruijn sequence:") validate(rdb)   sb = new StringBuilder(db) sb.setCharAt(4443, '.' as char) System.out.println() System.out.println("Validating the overlaid de Bruijn sequence:") validate(sb.toString()) } }
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.
#Frink
Frink
oneToTen[x] := isInteger[x] AND x >= 1 AND x <= 10   var y is oneToTen = 1   while (true) { println[y] y = y + 1 }
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.
#Go
Go
package main   import "fmt"   type TinyInt int   func NewTinyInt(i int) TinyInt { if i < 1 { i = 1 } else if i > 10 { i = 10 } return TinyInt(i) }   func (t1 TinyInt) Add(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) + int(t2)) }   func (t1 TinyInt) Sub(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) - int(t2)) }   func (t1 TinyInt) Mul(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) * int(t2)) }   func (t1 TinyInt) Div(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) / int(t2)) }   func (t1 TinyInt) Rem(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) % int(t2)) }   func (t TinyInt) Inc() TinyInt { return t.Add(TinyInt(1)) }   func (t TinyInt) Dec() TinyInt { return t.Sub(TinyInt(1)) }   func main() { t1 := NewTinyInt(6) t2 := NewTinyInt(3) fmt.Println("t1 =", t1) fmt.Println("t2 =", t2) fmt.Println("t1 + t2 =", t1.Add(t2)) fmt.Println("t1 - t2 =", t1.Sub(t2)) fmt.Println("t1 * t2 =", t1.Mul(t2)) fmt.Println("t1 / t2 =", t1.Div(t2)) fmt.Println("t1 % t2 =", t1.Rem(t2)) fmt.Println("t1 + 1 =", t1.Inc()) fmt.Println("t1 - 1 =", t1.Dec()) }
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
#J
J
  load'graphics/viewmat' mag =: +/&.:*:"1 norm=: %"1 0 mag dot =: +/@:*"1   NB. (pos;posr;neg;negr) getvec (x,y) getvec =: 4 :0 "1 pt =. y 'pos posr neg negr' =. x if. (dot~ pt-}:pos) > *:posr do. 0 0 0 else. zb =. ({:pos) (-,+) posr -&.:*: pt mag@:- }:pos if. (dot~ pt-}:neg) > *:negr do. (pt,{:zb) - pos else. zs =. ({:neg) (-,+) negr -&.:*: pt mag@:- }:neg if. zs >&{. zb do. (pt,{:zb) - pos elseif. zs >&{: zb do. 0 0 0 elseif. ({.zs) < ({:zb) do. neg - (pt,{.zs) elseif. do. (pt,{.zb) - pos end. end. end. )     NB. (k;ambient;light) draw_sphere (pos;posr;neg;negr) draw_sphere =: 4 :0 'pos posr neg negr' =. y 'k ambient light' =. x vec=. norm y getvec ,"0// (2{.pos) +/ i: 200 j.~ 0.5+posr   b=. (mag vec) * ambient + k * 0>. light dot vec )   togray =: 256#. 255 255 255 <.@*"1 0 (%>./@,)   env=.(2; 0.5; (norm _50 30 50)) sph=. 20 20 0; 20; 1 1 _6; 20 'rgb' viewmat togray env draw_sphere sph
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]
#Scala
Scala
object Deconvolution1D extends App { val (h, f) = (Array(-8, -9, -3, -1, -6, 7), Array(-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1)) val g = Array(24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, 96, 31, 55, 36, 29, -43, -7) val sb = new StringBuilder   private def deconv(g: Array[Int], f: Array[Int]) = { val h = Array.ofDim[Int](g.length - f.length + 1)   for (n <- h.indices) { h(n) = g(n) for (i <- math.max(n - f.length + 1, 0) until n) h(n) -= h(i) * f(n - i) h(n) /= f(0) } h }   sb.append(s"h = ${h.mkString("[", ", ", "]")}\n") .append(s"deconv(g, f) = ${deconv(g, f).mkString("[", ", ", "]")}\n") .append(s"f = ${f.mkString("[", ", ", "]")}\n") .append(s"deconv(g, h) = ${deconv(g, h).mkString("[", ", ", "]")}") println(sb.result())   }
http://rosettacode.org/wiki/Deconvolution/2D%2B
Deconvolution/2D+
This task is a straightforward generalization of Deconvolution/1D to higher dimensions. For example, the one dimensional case would be applicable to audio signals, whereas two dimensions would pertain to images. Define the discrete convolution in d {\displaystyle {\mathit {d}}} dimensions of two functions H , F : Z d → R {\displaystyle H,F:\mathbb {Z} ^{d}\rightarrow \mathbb {R} } taking d {\displaystyle {\mathit {d}}} -tuples of integers to real numbers as the function G : Z d → R {\displaystyle G:\mathbb {Z} ^{d}\rightarrow \mathbb {R} } also taking d {\displaystyle {\mathit {d}}} -tuples of integers to reals and satisfying G ( n 0 , … , n d − 1 ) = ∑ m 0 = − ∞ ∞ … ∑ m d − 1 = − ∞ ∞ F ( m 0 , … , m d − 1 ) H ( n 0 − m 0 , … , n d − 1 − m d − 1 ) {\displaystyle G(n_{0},\dots ,n_{d-1})=\sum _{m_{0}=-\infty }^{\infty }\dots \sum _{m_{d-1}=-\infty }^{\infty }F(m_{0},\dots ,m_{d-1})H(n_{0}-m_{0},\dots ,n_{d-1}-m_{d-1})} for all d {\displaystyle {\mathit {d}}} -tuples of integers ( n 0 , … , n d − 1 ) ∈ Z d {\displaystyle (n_{0},\dots ,n_{d-1})\in \mathbb {Z} ^{d}} . Assume F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} (and therefore G {\displaystyle {\mathit {G}}} ) are non-zero over only a finite domain bounded by the origin, hence possible to represent as finite multi-dimensional arrays or nested lists f {\displaystyle {\mathit {f}}} , h {\displaystyle {\mathit {h}}} , and g {\displaystyle {\mathit {g}}} . For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by solving for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . (See Deconvolution/1D for details.) The function should work for g {\displaystyle {\mathit {g}}} of arbitrary length in each dimension (i.e., not hard coded or constant) and f {\displaystyle {\mathit {f}}} of any length up to that of g {\displaystyle {\mathit {g}}} in the corresponding dimension. The deconv function will need to be parameterized by the dimension d {\displaystyle {\mathit {d}}} unless the dimension can be inferred from the data structures representing g {\displaystyle {\mathit {g}}} and f {\displaystyle {\mathit {f}}} . 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. Debug your solution using this test data, of which a portion is shown below. Be sure to verify both that the deconvolution of g {\displaystyle {\mathit {g}}} with f {\displaystyle {\mathit {f}}} is h {\displaystyle {\mathit {h}}} and that the deconvolution of g {\displaystyle {\mathit {g}}} with h {\displaystyle {\mathit {h}}} is f {\displaystyle {\mathit {f}}} . Display the results in a human readable form for the three dimensional case only. dimension 1: h: [-8, 2, -9, -2, 9, -8, -2] f: [ 6, -9, -7, -5] g: [-48, 84, -16, 95, 125, -70, 7, 29, 54, 10] dimension 2: h: [ [-8, 1, -7, -2, -9, 4], [4, 5, -5, 2, 7, -1], [-6, -3, -3, -6, 9, 5]] f: [ [-5, 2, -2, -6, -7], [9, 7, -6, 5, -7], [1, -1, 9, 2, -7], [5, 9, -9, 2, -5], [-8, 5, -2, 8, 5]] g: [ [40, -21, 53, 42, 105, 1, 87, 60, 39, -28], [-92, -64, 19, -167, -71, -47, 128, -109, 40, -21], [58, 85, -93, 37, 101, -14, 5, 37, -76, -56], [-90, -135, 60, -125, 68, 53, 223, 4, -36, -48], [78, 16, 7, -199, 156, -162, 29, 28, -103, -10], [-62, -89, 69, -61, 66, 193, -61, 71, -8, -30], [48, -6, 21, -9, -150, -22, -56, 32, 85, 25]] dimension 3: h: [ [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]], [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]] f: [ [[-9, 5, -8], [3, 5, 1]], [[-1, -7, 2], [-5, -6, 6]], [[8, 5, 8],[-2, -6, -4]]] g: [ [ [54, 42, 53, -42, 85, -72], [45, -170, 94, -36, 48, 73], [-39, 65, -112, -16, -78, -72], [6, -11, -6, 62, 49, 8]], [ [-57, 49, -23, 52, -135, 66], [-23, 127, -58, -5, -118, 64], [87, -16, 121, 23, -41, -12], [-19, 29, 35, -148, -11, 45]], [ [-55, -147, -146, -31, 55, 60], [-88, -45, -28, 46, -26, -144], [-12, -107, -34, 150, 249, 66], [11, -15, -34, 27, -78, -50]], [ [56, 67, 108, 4, 2, -48], [58, 67, 89, 32, 32, -8], [-42, -31, -103, -30, -23, -8], [6, 4, -26, -10, 26, 12]]]
#J
J
deconv3 =: 4 : 0 sz =. x >:@-&$ y NB. shape of z poi =. ,<"1 ($y) ,"0/&(,@i.) sz NB. pair of indexes t=. /: sc=: , <@(+"1)/&(#: ,@i.)/ ($y),:sz NB. order of ,y T0=. (<"0,x) ,:~ (]/:"1 {.)&.> (<, y) ({:@] ,: ({"1~ {.))&.> sc <@|:@:>/.&(t&{) poi NB. set of boxed equations T1=. (,x),.~(<0 #~ */sz) (({:@])`({.@])`[})&> {.T0 NB. set of linear equations sz $ 1e_8 round ({:"1 %. }:"1) T1 ) round=: [ * <.@%~
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
#Common_Lisp
Common Lisp
(defun make-rng (seed) #'(lambda () (ash (setf seed (mod (+ (* 214013 seed) 2531011) (expt 2 31))) -16)))   (defun split (s) (map 'list #'string s))   (defun make-deck (seed) (let ((hand (make-array 52 :fill-pointer 0)) (rng (make-rng seed))) (dolist (d (split "A23456789TJQK")) (dolist (s (split "♣♦♥♠")) (vector-push (concatenate 'string d s) hand))) (dotimes (i 52) (rotatef (aref hand (- 51 i)) (aref hand (mod (funcall rng) (- 52 i))))) (nreverse hand)))   (defun show-deck (seed) (let ((hand (make-deck seed))) (format t "~%Hand ~d~%" seed) (dotimes (i 52) (format t "~A " (aref hand i)) (if (= (mod i 8) 7) (write-line "")))))   (show-deck 1) (show-deck 617)
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.
#Haskell
Haskell
import Data.List import Data.Map ((!)) import qualified Data.Map as M   -- represents a permutation in a cycle notation cycleForm :: [Int] -> [[Int]] cycleForm p = unfoldr getCycle $ M.fromList $ zip [0..] p where getCycle p | M.null p = Nothing | otherwise = let Just ((x,y), m) = M.minViewWithKey p c = if x == y then [] else takeWhile (/= x) (iterate (m !) y) in Just (c ++ [x], foldr M.delete m c)   -- the set of Lyndon words generated by inverse Burrows—Wheeler transform lyndonWords :: Ord a => [a] -> Int -> [[a]] lyndonWords s n = map (ref !!) <$> cycleForm perm where ref = concat $ replicate (length s ^ (n - 1)) s perm = s >>= (`elemIndices` ref)   -- returns the de Bruijn sequence of order n for an alphabeth s deBruijn :: Ord a => [a] -> Int -> [a] deBruijn s n = let lw = concat $ lyndonWords n s in lw ++ take (n-1) lw
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.
#Haskell
Haskell
{-# OPTIONS -fglasgow-exts #-}   data Check a b = Check { unCheck :: b } deriving (Eq, Ord)   class Checked a b where check :: b -> Check a b   lift f x = f (unCheck x) liftc f x = check $ f (unCheck x)   lift2 f x y = f (unCheck x) (unCheck y) lift2c f x y = check $ f (unCheck x) (unCheck y) lift2p f x y = (check u, check v) where (u,v) = f (unCheck x) (unCheck y)   instance Show b => Show (Check a b) where show (Check x) = show x showsPrec p (Check x) = showsPrec p x   instance (Enum b, Checked a b) => Enum (Check a b) where succ = liftc succ pred = liftc pred toEnum = check . toEnum fromEnum = lift fromEnum   instance (Num b, Checked a b) => Num (Check a b) where (+) = lift2c (+) (-) = lift2c (-) (*) = lift2c (*) negate = liftc negate abs = liftc abs signum = liftc signum fromInteger = check . fromInteger   instance (Real b, Checked a b) => Real (Check a b) where toRational = lift toRational   instance (Integral b, Checked a b) => Integral (Check a b) where quot = lift2c quot rem = lift2c rem div = lift2c div mod = lift2c mod quotRem = lift2p quotRem divMod = lift2p divMod toInteger = lift toInteger
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
#Java
Java
import javafx.application.Application; import javafx.event.EventHandler; import javafx.geometry.Point3D; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.shape.MeshView; import javafx.scene.shape.TriangleMesh; import javafx.scene.transform.Rotate; import javafx.stage.Stage; public class DeathStar extends Application {   private static final int DIVISION = 200;// the bigger the higher resolution float radius = 300;// radius of the sphere   @Override public void start(Stage primaryStage) throws Exception { Point3D otherSphere = new Point3D(-radius, 0, -radius * 1.5); final TriangleMesh triangleMesh = createMesh(DIVISION, radius, otherSphere); MeshView a = new MeshView(triangleMesh);   a.setTranslateY(radius); a.setTranslateX(radius); a.setRotationAxis(Rotate.Y_AXIS); Scene scene = new Scene(new Group(a)); // uncomment if you want to move the other sphere   // scene.setOnKeyPressed(new EventHandler<KeyEvent>() { // Point3D sphere = otherSphere; // // @Override // public void handle(KeyEvent e) { // KeyCode code = e.getCode(); // switch (code) { // case UP: // sphere = sphere.add(0, -10, 0); // break; // case DOWN: // sphere = sphere.add(0, 10, 0); // break; // case LEFT: // sphere = sphere.add(-10, 0, 0); // break; // case RIGHT: // sphere = sphere.add(10, 0, 0); // break; // case W: // sphere = sphere.add(0, 0, 10); // break; // case S: // sphere = sphere.add(0, 0, -10); // break; // default: // return; // } // a.setMesh(createMesh(DIVISION, radius, sphere)); // // } // });   primaryStage.setScene(scene); primaryStage.show(); }   static TriangleMesh createMesh(final int division, final float radius, final Point3D centerOtherSphere) { Rotate rotate = new Rotate(180, centerOtherSphere); final int div2 = division / 2;   final int nPoints = division * (div2 - 1) + 2; final int nTPoints = (division + 1) * (div2 - 1) + division * 2; final int nFaces = division * (div2 - 2) * 2 + division * 2;   final float rDiv = 1.f / division;   float points[] = new float[nPoints * 3]; float tPoints[] = new float[nTPoints * 2]; int faces[] = new int[nFaces * 6];   int pPos = 0, tPos = 0;   for (int y = 0; y < div2 - 1; ++y) { float va = rDiv * (y + 1 - div2 / 2) * 2 * (float) Math.PI; float sin_va = (float) Math.sin(va); float cos_va = (float) Math.cos(va);   float ty = 0.5f + sin_va * 0.5f; for (int i = 0; i < division; ++i) { double a = rDiv * i * 2 * (float) Math.PI; float hSin = (float) Math.sin(a); float hCos = (float) Math.cos(a); points[pPos + 0] = hSin * cos_va * radius; points[pPos + 2] = hCos * cos_va * radius; points[pPos + 1] = sin_va * radius;   final Point3D point3D = new Point3D(points[pPos + 0], points[pPos + 1], points[pPos + 2]); double distance = centerOtherSphere.distance(point3D); if (distance <= radius) { Point3D subtract = centerOtherSphere.subtract(point3D); Point3D transform = rotate.transform(subtract); points[pPos + 0] = (float) transform.getX(); points[pPos + 1] = (float) transform.getY(); points[pPos + 2] = (float) transform.getZ();   } tPoints[tPos + 0] = 1 - rDiv * i; tPoints[tPos + 1] = ty; pPos += 3; tPos += 2; } tPoints[tPos + 0] = 0; tPoints[tPos + 1] = ty; tPos += 2; }   points[pPos + 0] = 0; points[pPos + 1] = -radius; points[pPos + 2] = 0; points[pPos + 3] = 0; points[pPos + 4] = radius; points[pPos + 5] = 0; pPos += 6;   int pS = (div2 - 1) * division;   float textureDelta = 1.f / 256; for (int i = 0; i < division; ++i) { tPoints[tPos + 0] = rDiv * (0.5f + i); tPoints[tPos + 1] = textureDelta; tPos += 2; }   for (int i = 0; i < division; ++i) { tPoints[tPos + 0] = rDiv * (0.5f + i); tPoints[tPos + 1] = 1 - textureDelta; tPos += 2; }   int fIndex = 0; for (int y = 0; y < div2 - 2; ++y) { for (int x = 0; x < division; ++x) { int p0 = y * division + x; int p1 = p0 + 1; int p2 = p0 + division; int p3 = p1 + division;   int t0 = p0 + y; int t1 = t0 + 1; int t2 = t0 + division + 1; int t3 = t1 + division + 1;   // add p0, p1, p2 faces[fIndex + 0] = p0; faces[fIndex + 1] = t0; faces[fIndex + 2] = p1 % division == 0 ? p1 - division : p1; faces[fIndex + 3] = t1; faces[fIndex + 4] = p2; faces[fIndex + 5] = t2; fIndex += 6;   // add p3, p2, p1 faces[fIndex + 0] = p3 % division == 0 ? p3 - division : p3; faces[fIndex + 1] = t3; faces[fIndex + 2] = p2; faces[fIndex + 3] = t2; faces[fIndex + 4] = p1 % division == 0 ? p1 - division : p1; faces[fIndex + 5] = t1; fIndex += 6; } }   int p0 = pS; int tB = (div2 - 1) * (division + 1); for (int x = 0; x < division; ++x) { int p2 = x, p1 = x + 1, t0 = tB + x; faces[fIndex + 0] = p0; faces[fIndex + 1] = t0; faces[fIndex + 2] = p1 == division ? 0 : p1; faces[fIndex + 3] = p1; faces[fIndex + 4] = p2; faces[fIndex + 5] = p2; fIndex += 6; }   p0 = p0 + 1; tB = tB + division; int pB = (div2 - 2) * division;   for (int x = 0; x < division; ++x) { int p1 = pB + x, p2 = pB + x + 1, t0 = tB + x; int t1 = (div2 - 2) * (division + 1) + x, t2 = t1 + 1; faces[fIndex + 0] = p0; faces[fIndex + 1] = t0; faces[fIndex + 2] = p1; faces[fIndex + 3] = t1; faces[fIndex + 4] = p2 % division == 0 ? p2 - division : p2; faces[fIndex + 5] = t2; fIndex += 6; }   TriangleMesh m = new TriangleMesh(); m.getPoints().setAll(points); m.getTexCoords().setAll(tPoints); m.getFaces().setAll(faces);   return m; }   public static void main(String[] args) {   launch(args); }   }  
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]
#Swift
Swift
func deconv(g: [Double], f: [Double]) -> [Double] { let fs = f.count var ret = [Double](repeating: 0, count: g.count - fs + 1)   for n in 0..<ret.count { ret[n] = g[n] let lower = n >= fs ? n - fs + 1 : 0   for i in lower..<n { ret[n] -= ret[i] * f[n - i] }   ret[n] /= f[0] }   return ret }   let h = [-8.0, -9.0, -3.0, -1.0, -6.0, 7.0] let f = [-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] let g = [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]   print("\(h.map({ Int($0) }))") print("\(deconv(g: g, f: f).map({ Int($0) }))\n")     print("\(f.map({ Int($0) }))") print("\(deconv(g: g, f: h).map({ Int($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]
#Tcl
Tcl
package require Tcl 8.5 namespace eval 1D { namespace ensemble create; # Will be same name as namespace namespace export convolve deconvolve # Access core language math utility commands namespace path {::tcl::mathfunc ::tcl::mathop}   # Utility for converting a matrix to Reduced Row Echelon Form # From http://rosettacode.org/wiki/Reduced_row_echelon_form#Tcl proc toRREF {m} { set lead 0 set rows [llength $m] set cols [llength [lindex $m 0]] for {set r 0} {$r < $rows} {incr r} { if {$cols <= $lead} { break } set i $r while {[lindex $m $i $lead] == 0} { incr i if {$rows == $i} { set i $r incr lead if {$cols == $lead} { # Tcl can't break out of nested loops return $m } } } # swap rows i and r foreach j [list $i $r] row [list [lindex $m $r] [lindex $m $i]] { lset m $j $row } # divide row r by m(r,lead) set val [lindex $m $r $lead] for {set j 0} {$j < $cols} {incr j} { lset m $r $j [/ [double [lindex $m $r $j]] $val] }   for {set i 0} {$i < $rows} {incr i} { if {$i != $r} { # subtract m(i,lead) multiplied by row r from row i set val [lindex $m $i $lead] for {set j 0} {$j < $cols} {incr j} { lset m $i $j \ [- [lindex $m $i $j] [* $val [lindex $m $r $j]]] } } } incr lead } return $m }   # How to apply a 1D convolution of two "functions" proc convolve {f h} { set g [lrepeat [+ [llength $f] [llength $h] -1] 0] set fi -1 foreach fv $f { incr fi set hi -1 foreach hv $h { set gi [+ $fi [incr hi]] lset g $gi [+ [lindex $g $gi] [* $fv $hv]] } } return $g }   # How to apply a 1D deconvolution of two "functions" proc deconvolve {g f} { # Compute the length of the result vector set hlen [- [llength $g] [llength $f] -1]   # Build a matrix of equations to solve set matrix {} set i -1 foreach gv $g { lappend matrix [list {*}[lrepeat $hlen 0] $gv] set j [incr i] foreach fv $f { if {$j < 0} { break } elseif {$j < $hlen} { lset matrix $i $j $fv } incr j -1 } }   # Convert to RREF, solving the system of simultaneous equations set reduced [toRREF $matrix]   # Extract the deconvolution from the last column of the reduced matrix for {set i 0} {$i<$hlen} {incr i} { lappend result [lindex $reduced $i end] } return $result } }
http://rosettacode.org/wiki/Deconvolution/2D%2B
Deconvolution/2D+
This task is a straightforward generalization of Deconvolution/1D to higher dimensions. For example, the one dimensional case would be applicable to audio signals, whereas two dimensions would pertain to images. Define the discrete convolution in d {\displaystyle {\mathit {d}}} dimensions of two functions H , F : Z d → R {\displaystyle H,F:\mathbb {Z} ^{d}\rightarrow \mathbb {R} } taking d {\displaystyle {\mathit {d}}} -tuples of integers to real numbers as the function G : Z d → R {\displaystyle G:\mathbb {Z} ^{d}\rightarrow \mathbb {R} } also taking d {\displaystyle {\mathit {d}}} -tuples of integers to reals and satisfying G ( n 0 , … , n d − 1 ) = ∑ m 0 = − ∞ ∞ … ∑ m d − 1 = − ∞ ∞ F ( m 0 , … , m d − 1 ) H ( n 0 − m 0 , … , n d − 1 − m d − 1 ) {\displaystyle G(n_{0},\dots ,n_{d-1})=\sum _{m_{0}=-\infty }^{\infty }\dots \sum _{m_{d-1}=-\infty }^{\infty }F(m_{0},\dots ,m_{d-1})H(n_{0}-m_{0},\dots ,n_{d-1}-m_{d-1})} for all d {\displaystyle {\mathit {d}}} -tuples of integers ( n 0 , … , n d − 1 ) ∈ Z d {\displaystyle (n_{0},\dots ,n_{d-1})\in \mathbb {Z} ^{d}} . Assume F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} (and therefore G {\displaystyle {\mathit {G}}} ) are non-zero over only a finite domain bounded by the origin, hence possible to represent as finite multi-dimensional arrays or nested lists f {\displaystyle {\mathit {f}}} , h {\displaystyle {\mathit {h}}} , and g {\displaystyle {\mathit {g}}} . For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by solving for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . (See Deconvolution/1D for details.) The function should work for g {\displaystyle {\mathit {g}}} of arbitrary length in each dimension (i.e., not hard coded or constant) and f {\displaystyle {\mathit {f}}} of any length up to that of g {\displaystyle {\mathit {g}}} in the corresponding dimension. The deconv function will need to be parameterized by the dimension d {\displaystyle {\mathit {d}}} unless the dimension can be inferred from the data structures representing g {\displaystyle {\mathit {g}}} and f {\displaystyle {\mathit {f}}} . 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. Debug your solution using this test data, of which a portion is shown below. Be sure to verify both that the deconvolution of g {\displaystyle {\mathit {g}}} with f {\displaystyle {\mathit {f}}} is h {\displaystyle {\mathit {h}}} and that the deconvolution of g {\displaystyle {\mathit {g}}} with h {\displaystyle {\mathit {h}}} is f {\displaystyle {\mathit {f}}} . Display the results in a human readable form for the three dimensional case only. dimension 1: h: [-8, 2, -9, -2, 9, -8, -2] f: [ 6, -9, -7, -5] g: [-48, 84, -16, 95, 125, -70, 7, 29, 54, 10] dimension 2: h: [ [-8, 1, -7, -2, -9, 4], [4, 5, -5, 2, 7, -1], [-6, -3, -3, -6, 9, 5]] f: [ [-5, 2, -2, -6, -7], [9, 7, -6, 5, -7], [1, -1, 9, 2, -7], [5, 9, -9, 2, -5], [-8, 5, -2, 8, 5]] g: [ [40, -21, 53, 42, 105, 1, 87, 60, 39, -28], [-92, -64, 19, -167, -71, -47, 128, -109, 40, -21], [58, 85, -93, 37, 101, -14, 5, 37, -76, -56], [-90, -135, 60, -125, 68, 53, 223, 4, -36, -48], [78, 16, 7, -199, 156, -162, 29, 28, -103, -10], [-62, -89, 69, -61, 66, 193, -61, 71, -8, -30], [48, -6, 21, -9, -150, -22, -56, 32, 85, 25]] dimension 3: h: [ [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]], [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]] f: [ [[-9, 5, -8], [3, 5, 1]], [[-1, -7, 2], [-5, -6, 6]], [[8, 5, 8],[-2, -6, -4]]] g: [ [ [54, 42, 53, -42, 85, -72], [45, -170, 94, -36, 48, 73], [-39, 65, -112, -16, -78, -72], [6, -11, -6, 62, 49, 8]], [ [-57, 49, -23, 52, -135, 66], [-23, 127, -58, -5, -118, 64], [87, -16, 121, 23, -41, -12], [-19, 29, 35, -148, -11, 45]], [ [-55, -147, -146, -31, 55, 60], [-88, -45, -28, 46, -26, -144], [-12, -107, -34, 150, 249, 66], [11, -15, -34, 27, -78, -50]], [ [56, 67, 108, 4, 2, -48], [58, 67, 89, 32, 32, -8], [-42, -31, -103, -30, -23, -8], [6, 4, -26, -10, 26, 12]]]
#Julia
Julia
using FFTW, DSP   const h1 = [-8, 2, -9, -2, 9, -8, -2] const f1 = [ 6, -9, -7, -5] const g1 = [-48, 84, -16, 95, 125, -70, 7, 29, 54, 10]   const h2nested = [ [-8, 1, -7, -2, -9, 4], [4, 5, -5, 2, 7, -1], [-6, -3, -3, -6, 9, 5]] const f2nested = [ [-5, 2, -2, -6, -7], [9, 7, -6, 5, -7], [1, -1, 9, 2, -7], [5, 9, -9, 2, -5], [-8, 5, -2, 8, 5]] const g2nested = [ [40, -21, 53, 42, 105, 1, 87, 60, 39, -28], [-92, -64, 19, -167, -71, -47, 128, -109, 40, -21], [58, 85, -93, 37, 101, -14, 5, 37, -76, -56], [-90, -135, 60, -125, 68, 53, 223, 4, -36, -48], [78, 16, 7, -199, 156, -162, 29, 28, -103, -10], [-62, -89, 69, -61, 66, 193, -61, 71, -8, -30], [48, -6, 21, -9, -150, -22, -56, 32, 85, 25]]   const h3nested = [ [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]], [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]] const f3nested = [ [[-9, 5, -8], [3, 5, 1]], [[-1, -7, 2], [-5, -6, 6]], [[8, 5, 8],[-2, -6, -4]]] const g3nested = [ [ [54, 42, 53, -42, 85, -72], [45, -170, 94, -36, 48, 73], [-39, 65, -112, -16, -78, -72], [6, -11, -6, 62, 49, 8]], [ [-57, 49, -23, 52, -135, 66], [-23, 127, -58, -5, -118, 64], [87, -16, 121, 23, -41, -12], [-19, 29, 35, -148, -11, 45]], [ [-55, -147, -146, -31, 55, 60], [-88, -45, -28, 46, -26, -144], [-12, -107, -34, 150, 249, 66], [11, -15, -34, 27, -78, -50]], [ [56, 67, 108, 4, 2, -48], [58, 67, 89, 32, 32, -8], [-42, -31, -103, -30, -23, -8], [6, 4, -26, -10, 26, 12]]]   function flatnested2d(a, siz) ret = zeros(Int, prod(siz)) for i in 1:length(a), j in 1:length(a[1]) ret[siz[2] * (i - 1) + j] = a[i][j] end Float64.(ret) end   function flatnested3d(a, siz) ret = zeros(Int, prod(siz)) for i in 1:length(a), j in 1:length(a[1]), k in 1:length(a[1][1]) ret[siz[2] * siz[3] * (i - 1) + siz[3] * (j - 1) + k] = a[i][j][k] end Float64.(ret) end   topow2(siz) = map(x -> nextpow(2, x), siz) deconv1d(f1, g1) = Int.(round.(deconv(Float64.(g1), Float64.(f1))))   function deconv2d(f2, g2, xd2) siz = topow2([length(g2), length(g2[1])]) h2 = Int.(round.(real.(ifft(fft(flatnested2d(g2, siz)) ./ fft(flatnested2d(f2, siz)))))) [[h2[siz[2] * (i - 1) + j] for j in 1:xd2[2]] for i in 1:xd2[1]] end   function deconv3d(f3, g3, xd3) siz = topow2([length(g3), length(g3[1]), length(g3[1][1])]) h3 = Int.(round.(real.(ifft(fft(flatnested3d(g3, siz)) ./ fft(flatnested3d(f3, siz)))))) [[[h3[siz[2] * siz[3] *(i - 1) + siz[3] * (j - 1) + k] for k in 1:xd3[3]] for j in 1:xd3[2]] for i in 1:xd3[1]] end   deconvn(f, g, tup=()) = length(tup) < 2 ? deconv1d(f, g) : length(tup) == 2 ? deconv2d(f, g, tup) : length(tup) == 3 ? deconv3d(f, g, tup) : println("Array nesting > 3D not supported")   deconvn(f1, g1) # 1D deconvn(f2nested, g2nested, (length(h2nested), length(h2nested[1]))) # 2D println(deconvn(f3nested, g3nested, (length(h3nested), length(h3nested[1]), length(h3nested[1][1])))) # 3D  
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
#D
D
import std.stdio, std.conv, std.algorithm, std.range;   struct RandomGenerator { uint seed = 1;   @property uint next() pure nothrow @safe @nogc { seed = (seed * 214_013 + 2_531_011) & int.max; return seed >> 16; } }   struct Deck { int[52] cards;   void deal(in uint seed) pure nothrow @safe @nogc { enum int nc = cards.length; // Must be signed for iota. nc.iota.retro.copy(cards[]);   auto rnd = RandomGenerator(seed); foreach (immutable i, ref c; cards) c.swap(cards[(nc - 1) - rnd.next % (nc - i)]); }   void show() const @safe { writefln("%(%-( %s%)\n%)", cards[] .chunks(8) .map!(row => row.map!(c => only("A23456789TJQK"[c / 4], "CDHS"[c % 4])))); } }   void main(in string[] args) @safe { immutable seed = (args.length == 2) ? args[1].to!uint : 11_982; writeln("Hand ", seed); Deck cards; cards.deal(seed); cards.show; }
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.
#J
J
NB. implement inverse Burrows—Wheeler transform sequence method   repeat_alphabet=: [: , [: i.&> (^ <:) # [ assert 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 -: 2 repeat_alphabet 4   de_bruijn=: ({~ ([: ; [: C. /:^:2))@:repeat_alphabet NB. K de_bruijn N   pins=: #&10 #: [: i. 10&^ NB. pins y generates all y digit PINs groups=: [ ]\ ] , ({.~ <:)~ NB. length x infixes of sequence y cyclically extended by x-1 verify_PINs=: (/:~@:groups -: pins@:[) NB. LENGTH verify_PINs 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.
#Java
Java
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.BiConsumer;   public class DeBruijn { public interface Recursable<T, U> { void apply(T t, U u, Recursable<T, U> r); }   public static <T, U> BiConsumer<T, U> recurse(Recursable<T, U> f) { return (t, u) -> f.apply(t, u, f); }   private static String deBruijn(int k, int n) { byte[] a = new byte[k * n]; Arrays.fill(a, (byte) 0);   List<Byte> seq = new ArrayList<>();   BiConsumer<Integer, Integer> db = recurse((t, p, f) -> { if (t > n) { if (n % p == 0) { for (int i = 1; i < p + 1; ++i) { seq.add(a[i]); } } } else { a[t] = a[t - p]; f.apply(t + 1, p, f); int j = a[t - p] + 1; while (j < k) { a[t] = (byte) (j & 0xFF); f.apply(t + 1, t, f); j++; } } }); db.accept(1, 1);   StringBuilder sb = new StringBuilder(); for (Byte i : seq) { sb.append("0123456789".charAt(i)); }   sb.append(sb.subSequence(0, n - 1)); return sb.toString(); }   private static boolean allDigits(String s) { for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); if (!Character.isDigit(c)) { return false; } } return true; }   private static void validate(String db) { int le = db.length(); int[] found = new int[10_000]; Arrays.fill(found, 0); List<String> errs = new ArrayList<>();   // Check all strings of 4 consecutive digits within 'db' // to see if all 10,000 combinations occur without duplication. for (int i = 0; i < le - 3; ++i) { String s = db.substring(i, i + 4); if (allDigits(s)) { int n = Integer.parseInt(s); found[n]++; } }   for (int i = 0; i < 10_000; ++i) { if (found[i] == 0) { errs.add(String.format(" PIN number %d is missing", i)); } else if (found[i] > 1) { errs.add(String.format(" PIN number %d occurs %d times", i, found[i])); } }   if (errs.isEmpty()) { System.out.println(" No errors found"); } else { String pl = (errs.size() == 1) ? "" : "s"; System.out.printf("  %d error%s found:\n", errs.size(), pl); errs.forEach(System.out::println); } }   public static void main(String[] args) { String db = deBruijn(10, 4);   System.out.printf("The length of the de Bruijn sequence is %d\n\n", db.length()); System.out.printf("The first 130 digits of the de Bruijn sequence are: %s\n\n", db.substring(0, 130)); System.out.printf("The last 130 digits of the de Bruijn sequence are: %s\n\n", db.substring(db.length() - 130));   System.out.println("Validating the de Bruijn sequence:"); validate(db);   StringBuilder sb = new StringBuilder(db); String rdb = sb.reverse().toString(); System.out.println(); System.out.println("Validating the de Bruijn sequence:"); validate(rdb);   sb = new StringBuilder(db); sb.setCharAt(4443, '.'); System.out.println(); System.out.println("Validating the overlaid de Bruijn sequence:"); validate(sb.toString()); } }
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.
#J
J
  NB. z locale by default on path. type_z_=: 3!:0 nameClass_z_=: 4!:0 signalError_z_=: 13!:8   NB. create a restricted object from an appropriate integer create_restrict_ =: monad define 'Domain error: expected integer' assert 1 4 e.~ type y NB. or Boolean 'Domain error: not on [1,10]' assert (0 -.@:e. [: , (0&<*.<&11)) y value=: y )   add_restrict_=: monad define if. 0 = nameClass<'value__y' do. (value + value__y) conew 0{::coname'' else. 'value unavailable'signalError 21 end. )  
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
#JavaScript
JavaScript
  <!DOCTYPE html> <html> <body style="margin:0"> <canvas id="myCanvas" width="250" height="250" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML5 canvas tag. </canvas> <script> var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); //Fill the canvas with a dark gray background ctx.fillStyle = "#222222"; ctx.fillRect(0,0,250,250);   // Create radial gradient for large base circle var grd = ctx.createRadialGradient(225,175,190,225,150,130); grd.addColorStop(0,"#EEEEEE"); grd.addColorStop(1,"black"); //Apply gradient and fill circle ctx.fillStyle = grd; ctx.beginPath(); ctx.arc(125,125,105,0,2*Math.PI); ctx.fill();   // Create linear gradient for small inner circle var grd = ctx.createLinearGradient(75,90,102,90); grd.addColorStop(0,"black"); grd.addColorStop(1,"gray"); //Apply gradient and fill circle ctx.fillStyle = grd; ctx.beginPath(); ctx.arc(90,90,30,0,2*Math.PI); ctx.fill();   //Add another small circle on top of the previous one to enhance the "shadow" ctx.fillStyle = "black"; ctx.beginPath(); ctx.arc(80,90,17,0,2*Math.PI); ctx.fill(); </script> </body> </html>    
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]
#Ursala
Ursala
#import std #import nat   band = pad0+ ~&rSS+ zipt^*D(~&r,^lrrSPT/~&ltK33tx zipt^/~&r ~&lSNyCK33+ zipp0)^/~&rx ~&B->NlNSPC ~&bt   deconv = lapack..dgelsd^\~&l ~&||0.!**+ band  
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]
#Vlang
Vlang
fn main() { h := [f64(-8), -9, -3, -1, -6, 7] f := [f64(-3), -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1] g := [f64(24), 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, 96, 31, 55, 36, 29, -43, -7] println(h) println(deconv(g, f)) println(f) println(deconv(g, h)) }   fn deconv(g []f64, f []f64) []f64 { mut h := []f64{len: g.len-f.len+1} for n in 0..h.len { h[n] = g[n] mut lower := 0 if n >= f.len { lower = n - f.len + 1 } for i in lower..n { h[n] -= h[i] * f[n-i] } h[n] /= f[0] } return h }
http://rosettacode.org/wiki/Deconvolution/2D%2B
Deconvolution/2D+
This task is a straightforward generalization of Deconvolution/1D to higher dimensions. For example, the one dimensional case would be applicable to audio signals, whereas two dimensions would pertain to images. Define the discrete convolution in d {\displaystyle {\mathit {d}}} dimensions of two functions H , F : Z d → R {\displaystyle H,F:\mathbb {Z} ^{d}\rightarrow \mathbb {R} } taking d {\displaystyle {\mathit {d}}} -tuples of integers to real numbers as the function G : Z d → R {\displaystyle G:\mathbb {Z} ^{d}\rightarrow \mathbb {R} } also taking d {\displaystyle {\mathit {d}}} -tuples of integers to reals and satisfying G ( n 0 , … , n d − 1 ) = ∑ m 0 = − ∞ ∞ … ∑ m d − 1 = − ∞ ∞ F ( m 0 , … , m d − 1 ) H ( n 0 − m 0 , … , n d − 1 − m d − 1 ) {\displaystyle G(n_{0},\dots ,n_{d-1})=\sum _{m_{0}=-\infty }^{\infty }\dots \sum _{m_{d-1}=-\infty }^{\infty }F(m_{0},\dots ,m_{d-1})H(n_{0}-m_{0},\dots ,n_{d-1}-m_{d-1})} for all d {\displaystyle {\mathit {d}}} -tuples of integers ( n 0 , … , n d − 1 ) ∈ Z d {\displaystyle (n_{0},\dots ,n_{d-1})\in \mathbb {Z} ^{d}} . Assume F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} (and therefore G {\displaystyle {\mathit {G}}} ) are non-zero over only a finite domain bounded by the origin, hence possible to represent as finite multi-dimensional arrays or nested lists f {\displaystyle {\mathit {f}}} , h {\displaystyle {\mathit {h}}} , and g {\displaystyle {\mathit {g}}} . For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by solving for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . (See Deconvolution/1D for details.) The function should work for g {\displaystyle {\mathit {g}}} of arbitrary length in each dimension (i.e., not hard coded or constant) and f {\displaystyle {\mathit {f}}} of any length up to that of g {\displaystyle {\mathit {g}}} in the corresponding dimension. The deconv function will need to be parameterized by the dimension d {\displaystyle {\mathit {d}}} unless the dimension can be inferred from the data structures representing g {\displaystyle {\mathit {g}}} and f {\displaystyle {\mathit {f}}} . 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. Debug your solution using this test data, of which a portion is shown below. Be sure to verify both that the deconvolution of g {\displaystyle {\mathit {g}}} with f {\displaystyle {\mathit {f}}} is h {\displaystyle {\mathit {h}}} and that the deconvolution of g {\displaystyle {\mathit {g}}} with h {\displaystyle {\mathit {h}}} is f {\displaystyle {\mathit {f}}} . Display the results in a human readable form for the three dimensional case only. dimension 1: h: [-8, 2, -9, -2, 9, -8, -2] f: [ 6, -9, -7, -5] g: [-48, 84, -16, 95, 125, -70, 7, 29, 54, 10] dimension 2: h: [ [-8, 1, -7, -2, -9, 4], [4, 5, -5, 2, 7, -1], [-6, -3, -3, -6, 9, 5]] f: [ [-5, 2, -2, -6, -7], [9, 7, -6, 5, -7], [1, -1, 9, 2, -7], [5, 9, -9, 2, -5], [-8, 5, -2, 8, 5]] g: [ [40, -21, 53, 42, 105, 1, 87, 60, 39, -28], [-92, -64, 19, -167, -71, -47, 128, -109, 40, -21], [58, 85, -93, 37, 101, -14, 5, 37, -76, -56], [-90, -135, 60, -125, 68, 53, 223, 4, -36, -48], [78, 16, 7, -199, 156, -162, 29, 28, -103, -10], [-62, -89, 69, -61, 66, 193, -61, 71, -8, -30], [48, -6, 21, -9, -150, -22, -56, 32, 85, 25]] dimension 3: h: [ [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]], [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]] f: [ [[-9, 5, -8], [3, 5, 1]], [[-1, -7, 2], [-5, -6, 6]], [[8, 5, 8],[-2, -6, -4]]] g: [ [ [54, 42, 53, -42, 85, -72], [45, -170, 94, -36, 48, 73], [-39, 65, -112, -16, -78, -72], [6, -11, -6, 62, 49, 8]], [ [-57, 49, -23, 52, -135, 66], [-23, 127, -58, -5, -118, 64], [87, -16, 121, 23, -41, -12], [-19, 29, 35, -148, -11, 45]], [ [-55, -147, -146, -31, 55, 60], [-88, -45, -28, 46, -26, -144], [-12, -107, -34, 150, 249, 66], [11, -15, -34, 27, -78, -50]], [ [56, 67, 108, 4, 2, -48], [58, 67, 89, 32, 32, -8], [-42, -31, -103, -30, -23, -8], [6, 4, -26, -10, 26, 12]]]
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Round[ListDeconvolve[{6, -9, -7, -5}, {-48, 84, -16, 95, 125, -70, 7, 29, 54, 10}, Method -> "Wiener"]]   Round[ListDeconvolve[{{-5, 2, -2, -6, -7}, {9, 7, -6, 5, -7}, {1, -1, 9, 2, -7}, {5, 9, -9, 2, -5}, {-8, 5, -2, 8, 5}}, {{40, -21, 53, 42, 105, 1, 87, 60, 39, -28}, {-92, -64, 19, -167, -71, -47, 128, -109, 40, -21}, {58, 85, -93, 37, 101, -14, 5, 37, -76, -56}, {-90, -135, 60, -125, 68, 53, 223, 4, -36, -48}, {78, 16, 7, -199, 156, -162, 29, 28, -103, -10}, {-62, -89, 69, -61, 66, 193, -61, 71, -8, -30}, {48, -6, 21, -9, -150, -22, -56, 32, 85, 25}}, Method -> "Wiener"]]   Round[ListDeconvolve [{{{-9, 5, -8}, {3, 5, 1}}, {{-1, -7, 2}, {-5, -6, 6}}, {{8, 5, 8}, {-2, -6, -4}}}, {{{54, 42, 53, -42, 85, -72}, {45, -170, 94, -36, 48, 73}, {-39, 65, -112, -16, -78, -72}, {6, -11, -6, 62, 49, 8}}, {{-57, 49, -23, 52, -135, 66}, {-23, 127, -58, -5, -118, 64}, {87, -16, 121, 23, -41, -12}, {-19, 29, 35, -148, -11, 45}}, {{-55, -147, -146, -31, 55, 60}, {-88, -45, -28, 46, -26, -144}, {-12, -107, -34, 150, 249, 66}, {11, -15, -34, 27, -78, -50}}, {{56, 67, 108, 4, 2, -48}, {58, 67, 89, 32, 32, -8}, {-42, -31, -103, -30, -23, -8}, {6, 4, -26, -10, 26, 12}}}, Method -> "Wiener"]]
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
#Delphi
Delphi
  program Deal_cards_for_FreeCell;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type TRandom = record Seed: Int64; function Next: Integer; end;   TCard = record const kSuits = '♣♦♥♠'; kValues = 'A23456789TJQK'; var Value: Integer; Suit: Integer; procedure Create(rawvalue: Integer); overload; procedure Create(value, suit: Integer); overload; procedure Assign(other: TCard); function ToString: string; end;   TDeck = record Cards: TArray<TCard>; procedure Create(Seed: Integer); function ToString: string; end;   { TRandom }   function TRandom.Next: Integer; begin Seed := ((Seed * 214013 + 2531011) and Integer.MaxValue); Result := Seed shr 16; end;   { TCard }   procedure TCard.Create(rawvalue: Integer); begin Create(rawvalue div 4, rawvalue mod 4); end;   procedure TCard.Assign(other: TCard); begin Create(other.Value, other.Suit); end;   procedure TCard.Create(value, suit: Integer); begin self.Value := value; self.Suit := suit; end;   function TCard.ToString: string; begin result := format('%s%s', [kValues[value + 1], kSuits[suit + 1]]); end;   { TDeck }   procedure TDeck.Create(Seed: Integer); var r: TRandom; i, j: integer; tmp: Tcard; begin r.Seed := Seed; SetLength(Cards, 52); for i := 0 to 51 do Cards[i].Create(51 - i); for i := 0 to 50 do begin j := 51 - (r.Next mod (52 - i)); tmp.Assign(Cards[i]); Cards[i].Assign(Cards[j]); Cards[j].Assign(tmp); end; end;   function TDeck.ToString: string; var i: Integer; begin Result := ''; for i := 0 to length(Cards) - 1 do begin Result := Result + Cards[i].ToString; if i mod 8 = 7 then Result := Result + #10 else Result := Result + ' '; end; end;   var Deck: TDeck;   begin Deck.Create(1); Writeln('Deck 1'#10, Deck.ToString, #10); Deck.Create(617); Writeln('Deck 617'#10, Deck.ToString); readln; end.
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.
#Julia
Julia
function debruijn(k::Integer, n::Integer) alphabet = b"0123456789abcdefghijklmnopqrstuvwxyz"[1:k] a = zeros(UInt8, k * n) seq = UInt8[]   function db(t, p) if t > n if n % p == 0 append!(seq, a[2:p+1]) end else a[t + 1] = a[t - p + 1] db(t + 1, p) for j in a[t-p+1]+1:k-1 a[t + 1] = j db(t + 1, t) end end end   db(1, 1) return String([alphabet[i + 1] for i in vcat(seq, seq[1:n-1])]) end   function verifyallPIN(str, k, n, deltaposition=0) if deltaposition != 0 str = str[1:deltaposition-1] * "." * str[deltaposition+1:end] end result = true for i in 1:k^n-1 pin = string(i, pad=n) if !occursin(pin, str) println("PIN $pin does not occur in the sequence.") result = false end end println("The sequence does ", result ? "" : "not ", "contain all PINs.") end   const s = debruijn(10, 4) println("The length of the sequence is $(length(s)). The first 130 digits are:\n", s[1:130], "\nand the last 130 digits are:\n", s[end-130:end]) print("Testing sequence: "), verifyallPIN(s, 10, 4) print("Testing the reversed sequence: "), verifyallPIN(reverse(s), 10, 4) println("\nAfter replacing 4444th digit with \'.\':"), verifyallPIN(s, 10, 4, 4444)  
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.
#Kotlin
Kotlin
const val digits = "0123456789"   fun deBruijn(k: Int, n: Int): String { val alphabet = digits.substring(0, k) val a = ByteArray(k * n) val seq = mutableListOf<Byte>() fun db(t: Int, p: Int) { if (t > n) { if (n % p == 0) { seq.addAll(a.sliceArray(1..p).asList()) } } else { a[t] = a[t - p] db(t + 1, p) var j = a[t - p] + 1 while (j < k) { a[t] = j.toByte() db(t + 1, t) j++ } } } db(1, 1) val buf = StringBuilder() for (i in seq) { buf.append(alphabet[i.toInt()]) } val b = buf.toString() return b + b.subSequence(0, n - 1) }   fun allDigits(s: String): Boolean { for (c in s) { if (c < '0' || '9' < c) { return false } } return true }   fun validate(db: String) { val le = db.length val found = MutableList(10_000) { 0 } val errs = mutableListOf<String>() // Check all strings of 4 consecutive digits within 'db' // to see if all 10,000 combinations occur without duplication. for (i in 0 until le - 3) { val s = db.substring(i, i + 4) if (allDigits(s)) { val n = s.toInt() found[n]++ } } for (i in 0 until 10_000) { if (found[i] == 0) { errs.add(" PIN number %04d missing".format(i)) } else if (found[i] > 1) { errs.add(" PIN number %04d occurs %d times".format(i, found[i])) } } val lerr = errs.size if (lerr == 0) { println(" No errors found") } else { val pl = if (lerr == 1) { "" } else { "s" } println(" $lerr error$pl found:") println(errs.joinToString("\n")) } }   fun main() { var db = deBruijn(10, 4) val le = db.length   println("The length of the de Bruijn sequence is $le") println("\nThe first 130 digits of the de Bruijn sequence are: ${db.subSequence(0, 130)}") println("\nThe last 130 digits of the de Bruijn sequence are: ${db.subSequence(le - 130, le)}")   println("\nValidating the deBruijn sequence:") validate(db)   println("\nValidating the reversed deBruijn sequence:") validate(db.reversed())   val bytes = db.toCharArray() bytes[4443] = '.' db = String(bytes) println("\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.
#Java
Java
class BoundedIntOutOfBoundsException extends Exception { public BoundedIntOutOfBoundsException(int v, int l, int u) { super("value " + v + " is out of bounds [" + l + "," + u + "]"); } }   class BoundedInt { private int value; private int lower; private int upper;   public BoundedInt(int l, int u) { lower = Math.min(l, u); upper = Math.max(l, u); }   private boolean checkBounds(int v) { return (v >= this.lower) && (v <= this.upper); }   public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{ assign(i.value()); //could still throw Exception if the other BoundedInt has different bounds }   public void assign(int v) throws BoundedIntOutOfBoundsException { if ( checkBounds(v) ) { this.value = v; } else { throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper); } }   public int add(BoundedInt i) throws BoundedIntOutOfBoundsException { return add(i.value()); }   public int add(int i) throws BoundedIntOutOfBoundsException { if ( checkBounds(this.value + i) ) { this.value += i; } else { throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper); } return this.value; }   public int value() { return this.value; } }     public class Bounded { public static void main(String[] args) throws BoundedIntOutOfBoundsException { BoundedInt a = new BoundedInt(1, 10); BoundedInt b = new BoundedInt(1, 10);   a.assign(6); try { b.assign(12); } catch (Exception e) { System.out.println(e.getMessage()); } b.assign(9); try { a.add(b.value()); } catch (Exception e) { System.out.println(e.getMessage()); } } }
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
#Julia
Julia
# run in REPL using GLMakie   function deathstar() n = 60 θ = [0; (0.5: n - 0.5) / n; 1] φ = [(0: 2n - 2) * 2 / (2n - 1); 2] # if x is +0.9 radius units, replace it with the coordinates of sphere surface # at (1.2,0,0) center, radius 0.5 units x = [(x1 = cospi(φ)*sinpi(θ)) > 0.9 ? 1.2 - x1 * 0.5 : x1 for θ in θ, φ in φ] y = [sinpi(φ)*sinpi(θ) for θ in θ, φ in φ] z = [cospi(θ) for θ in θ, φ in φ] scene = Scene(backgroundcolor=:black) surface!(scene, x, y, z, color = rand(RGBAf0, 124, 124), show_axis=false) return scene end   scene = deathstar()  
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
#LSL
LSL
default { state_entry() { llSetPrimitiveParams([PRIM_NAME, "RosettaCode DeathStar"]); llSetPrimitiveParams([PRIM_DESC, llGetObjectName()]); llSetPrimitiveParams([PRIM_TYPE, PRIM_TYPE_SPHERE, PRIM_HOLE_CIRCLE, <0.0, 1.0, 0.0>, 0.0, <0.0, 0.0, 0.0>, <0.12, 1.0, 0.0>]); llSetPrimitiveParams([PRIM_ROTATION, <-0.586217, 0.395411, -0.586217, 0.395411>]); llSetPrimitiveParams([PRIM_TEXTURE, ALL_SIDES, TEXTURE_BLANK, ZERO_VECTOR, ZERO_VECTOR, 0.0]); llSetPrimitiveParams([PRIM_TEXT, llGetObjectName(), <1.0, 1.0, 1.0>, 1.0]); llSetPrimitiveParams([PRIM_COLOR, ALL_SIDES, <0.5, 0.5, 0.5>, 1.0]); llSetPrimitiveParams([PRIM_BUMP_SHINY, ALL_SIDES, PRIM_SHINY_HIGH, PRIM_BUMP_NONE]); llSetPrimitiveParams([PRIM_SIZE, <10.0, 10.0, 10.0>]); llSetPrimitiveParams([PRIM_OMEGA, <0.0, 0.0, 1.0>, 1.0, 1.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]
#Wren
Wren
var deconv = Fn.new { |g, f| var h = List.filled(g.count - f.count + 1, 0) for (n in 0...h.count) { h[n] = g[n] var lower = (n >= f.count) ? n - f.count + 1 : 0 var i = lower while (i < n) { h[n] = h[n] - h[i]*f[n-i] i = i + 1 } h[n] = h[n] / f[0] } return h }   var h = [-8, -9, -3, -1, -6, 7] var f = [-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1] var g = [24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, 96, 31, 55, 36, 29, -43, -7] System.print(h) System.print(deconv.call(g, f)) System.print(f) System.print(deconv.call(g, h))
http://rosettacode.org/wiki/Deconvolution/2D%2B
Deconvolution/2D+
This task is a straightforward generalization of Deconvolution/1D to higher dimensions. For example, the one dimensional case would be applicable to audio signals, whereas two dimensions would pertain to images. Define the discrete convolution in d {\displaystyle {\mathit {d}}} dimensions of two functions H , F : Z d → R {\displaystyle H,F:\mathbb {Z} ^{d}\rightarrow \mathbb {R} } taking d {\displaystyle {\mathit {d}}} -tuples of integers to real numbers as the function G : Z d → R {\displaystyle G:\mathbb {Z} ^{d}\rightarrow \mathbb {R} } also taking d {\displaystyle {\mathit {d}}} -tuples of integers to reals and satisfying G ( n 0 , … , n d − 1 ) = ∑ m 0 = − ∞ ∞ … ∑ m d − 1 = − ∞ ∞ F ( m 0 , … , m d − 1 ) H ( n 0 − m 0 , … , n d − 1 − m d − 1 ) {\displaystyle G(n_{0},\dots ,n_{d-1})=\sum _{m_{0}=-\infty }^{\infty }\dots \sum _{m_{d-1}=-\infty }^{\infty }F(m_{0},\dots ,m_{d-1})H(n_{0}-m_{0},\dots ,n_{d-1}-m_{d-1})} for all d {\displaystyle {\mathit {d}}} -tuples of integers ( n 0 , … , n d − 1 ) ∈ Z d {\displaystyle (n_{0},\dots ,n_{d-1})\in \mathbb {Z} ^{d}} . Assume F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} (and therefore G {\displaystyle {\mathit {G}}} ) are non-zero over only a finite domain bounded by the origin, hence possible to represent as finite multi-dimensional arrays or nested lists f {\displaystyle {\mathit {f}}} , h {\displaystyle {\mathit {h}}} , and g {\displaystyle {\mathit {g}}} . For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by solving for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . (See Deconvolution/1D for details.) The function should work for g {\displaystyle {\mathit {g}}} of arbitrary length in each dimension (i.e., not hard coded or constant) and f {\displaystyle {\mathit {f}}} of any length up to that of g {\displaystyle {\mathit {g}}} in the corresponding dimension. The deconv function will need to be parameterized by the dimension d {\displaystyle {\mathit {d}}} unless the dimension can be inferred from the data structures representing g {\displaystyle {\mathit {g}}} and f {\displaystyle {\mathit {f}}} . 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. Debug your solution using this test data, of which a portion is shown below. Be sure to verify both that the deconvolution of g {\displaystyle {\mathit {g}}} with f {\displaystyle {\mathit {f}}} is h {\displaystyle {\mathit {h}}} and that the deconvolution of g {\displaystyle {\mathit {g}}} with h {\displaystyle {\mathit {h}}} is f {\displaystyle {\mathit {f}}} . Display the results in a human readable form for the three dimensional case only. dimension 1: h: [-8, 2, -9, -2, 9, -8, -2] f: [ 6, -9, -7, -5] g: [-48, 84, -16, 95, 125, -70, 7, 29, 54, 10] dimension 2: h: [ [-8, 1, -7, -2, -9, 4], [4, 5, -5, 2, 7, -1], [-6, -3, -3, -6, 9, 5]] f: [ [-5, 2, -2, -6, -7], [9, 7, -6, 5, -7], [1, -1, 9, 2, -7], [5, 9, -9, 2, -5], [-8, 5, -2, 8, 5]] g: [ [40, -21, 53, 42, 105, 1, 87, 60, 39, -28], [-92, -64, 19, -167, -71, -47, 128, -109, 40, -21], [58, 85, -93, 37, 101, -14, 5, 37, -76, -56], [-90, -135, 60, -125, 68, 53, 223, 4, -36, -48], [78, 16, 7, -199, 156, -162, 29, 28, -103, -10], [-62, -89, 69, -61, 66, 193, -61, 71, -8, -30], [48, -6, 21, -9, -150, -22, -56, 32, 85, 25]] dimension 3: h: [ [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]], [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]] f: [ [[-9, 5, -8], [3, 5, 1]], [[-1, -7, 2], [-5, -6, 6]], [[8, 5, 8],[-2, -6, -4]]] g: [ [ [54, 42, 53, -42, 85, -72], [45, -170, 94, -36, 48, 73], [-39, 65, -112, -16, -78, -72], [6, -11, -6, 62, 49, 8]], [ [-57, 49, -23, 52, -135, 66], [-23, 127, -58, -5, -118, 64], [87, -16, 121, 23, -41, -12], [-19, 29, 35, -148, -11, 45]], [ [-55, -147, -146, -31, 55, 60], [-88, -45, -28, 46, -26, -144], [-12, -107, -34, 150, 249, 66], [11, -15, -34, 27, -78, -50]], [ [56, 67, 108, 4, 2, -48], [58, 67, 89, 32, 32, -8], [-42, -31, -103, -30, -23, -8], [6, 4, -26, -10, 26, 12]]]
#Nim
Nim
import sequtils, typetraits   type Size = uint64   type M[T: SomeNumber] = object dims: seq[Size] subsizes: seq[Size] data: seq[T]   #################################################################################################### # Miscellaneous.   func dotProduct[T: SomeNumber](a, b: openArray[T]): T = assert a.len == b.len for i in 0..a.high: result += a[i] * b[i]     #################################################################################################### # Operations on M objects.   func setDimensions(m: var M; dimensions: varargs[Size]) =   for dim in dimensions: if dim == 0: raise newException(IndexDefect, "wrong dimension: 0")   m.dims = @dimensions m.subsizes = m.dims for i in 0..dimensions.high: m.subsizes[i] = m.dims[(i+1)..^1].foldl(a * b, Size(1))   let dlength = m.dims[0] * m.subsizes[0] if Size(m.data.len) != dlength: m.data.setLen(dlength)   #---------------------------------------------------------------------------------------------------   func initM(m: var M; dimensions: varargs[Size]) = m.setDimensions(dimensions)   #---------------------------------------------------------------------------------------------------   func set1DArray(m: var M; t: varargs[m.T]) =   let minLen = min(m.data.len, t.len) m.data.setLen(minLen) m.data[0..<minLen] = t[0..<minLen]   #---------------------------------------------------------------------------------------------------   func seqToIdx(m: M; s: Size): seq[Size] =   var acc = s for subsize in m.subsizes: result.add(acc div subsize) acc = acc mod subsize   #---------------------------------------------------------------------------------------------------   template size(m: M): Size = Size(m.data.len)   #---------------------------------------------------------------------------------------------------   func checkBounds(m: M; indexes: varargs[Size]): bool =   if indexes.len > m.dims.len: return false   for i, dim in indexes: if dim >= m.dims[i]: return false   result = true   #---------------------------------------------------------------------------------------------------   func `[]`(m: M; indexes: varargs[Size]): m.T =   if not m.checkBounds(indexes): raise newException(IndexDefect, "index out of range: " & $indexes)   m.data[dotProduct(indexes, m.subsizes)]   #---------------------------------------------------------------------------------------------------   func `[]=`(m: M; indexes: varargs[int]; val: m.T) =   if not m.checkBounds(indexes): raise newException(IndexDefect, "index out of range: " & $indexes)   m.data[dotProduct(indexes, m.subsizes)] = val   #---------------------------------------------------------------------------------------------------   func `==`(a, b: M): bool = a.dims == b.dims and a.data == b.data   #---------------------------------------------------------------------------------------------------   func `$`(m: M): string = $m.data     #################################################################################################### # Convolution/deconvolution.   func convolute(h, f: M): M = ## Result is "g".   var dims = h.dims for i in 0..dims.high: dims[i] += f.dims[i] - 1 result.initM(dims)   let bound = result.size for i in 0..<h.size: let hIndexes = h.seqToIdx(i)   for j in 0..<f.size: let fIndexes = f.seqToIdx(j) for k in 0..dims.high: dims[k] = hIndexes[k] + fIndexes[k] let idx1d = dotProduct(dims, result.subsizes) if idx1d < bound: result.data[idx1d] += h.data[i] * f.data[j] else: break # Bound reached.   #---------------------------------------------------------------------------------------------------   func deconvolute(g, f: M): M = ## Result is "h".   var dims = g.dims for i, d in dims: if d + 1 <= f.dims[i]: raise newException(IndexDefect, "a dimension is zero or negative")   for i in 0..dims.high: dims[i] -= f.dims[i] - 1 result.initM(dims)   for i in 0..<result.size: let iIndexes = result.seqToIdx(i) result.data[i] = g[iIndexes]   for j in 0..<i: let jIndexes = result.seqToIdx(j) for k in 0..dims.high: dims[k] = iIndexes[k] - jIndexes[k] if f.checkBounds(dims): result.data[i] -= result.data[j] * f[dims]   when result.T is SomeInteger: result.data[i] = result.data[i] div f.data[0] else: result.data[i] /= f.data[0]     #################################################################################################### # Transformation of a sequence into an M object.   func fold[T](a: seq[T]; d: var seq[Size]): auto =   if d.len == 0: d.add(Size(a.len))   when a.elementType is seq: if a.len == 0: raise newException(ValueError, "empty dimension") d.add(Size(a[0].len)) for elem in a: if elem.len != a[0].len: raise newException(ValueError, "not rectangular") result = fold(a.foldl(a & b), d)   else: if Size(a.len) != d.foldl(a * b): raise newException(ValueError, "not same size") result = a   #---------------------------------------------------------------------------------------------------   func arrtoM[T](a: T): auto =   var dims: seq[Size] let d = fold(a, dims) var res: M[d.elementType] res.initM(dims) res.set1DArray(d) return res     #———————————————————————————————————————————————————————————————————————————————————————————————————   const H = @[ @[ @[-6, -8, -5, 9], @[-7, 9, -6, -8], @[ 2, -7, 9, 8] ], @[ @[ 7, 4, 4, -6], @[ 9, 9, 4, -4], @[-3, 7, -2, -3] ] ]   const F = @[ @[ @[-9, 5, -8], @[ 3, 5, 1] ], @[ @[-1, -7, 2], @[-5, -6, 6] ], @[ @[ 8, 5, 8], @[-2, -6, -4] ] ]   let h = arrToM(H) let f = arrToM(F)   let g = h.convolute(f)   echo "g == f convolute h ? ", g == f.convolute(h) echo "h == g deconv f  ? ", h == g.deconvolute(f) echo "f == g deconv h  ? ", f == g.deconvolute(h) echo " f = ", f echo "g deconv f = ", g.deconvolute(h)
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
#Elixir
Elixir
defmodule FreeCell do import Bitwise   @suits ~w( C D H S ) @pips ~w( A 2 3 4 5 6 7 8 9 T J Q K ) @orig_deck for pip <- @pips, suit <- @suits, do: pip <> suit   def deal(games) do games = if length(games) == 0, do: [Enum.random(1..32000)], else: games Enum.each(games, fn seed -> IO.puts "Game ##{seed}" Enum.reduce(52..2, {seed,@orig_deck}, fn len,{state,deck} -> state = ((214013 * state) + 2531011) &&& 0x7fff_ffff index = rem(state >>> 16, len) last = len - 1 {a, b} = {Enum.at(deck, index), Enum.at(deck, last)} {state, deck |> List.replace_at(index, b) |> List.replace_at(last, a)} end) |> elem(1) |> Enum.reverse |> Enum.chunk(8,8,[]) |> Enum.each(fn row -> Enum.join(row, " ") |> IO.puts end) IO.puts "" end) end end   System.argv |> Enum.map(&String.to_integer/1) |> FreeCell.deal
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
#ERRE
ERRE
  PROGRAM FREECELL   !$DOUBLE   DIM CARDS%[52]   PROCEDURE XRANDOM(SEED->XRND) POW31=2^31 POW16=2^16 SEED=SEED*214013+2531011 SEED=SEED-POW31*INT(SEED/POW31) XRND=INT(SEED/POW16) END PROCEDURE   PROCEDURE DEAL(CARDS%[],GAME_NUM) LOCAL I%,J%,S% SEED=GAME_NUM FOR I%=1 TO 52 DO CARDS%[I%]=52-I% END FOR FOR I%=1 TO 51 DO XRANDOM(SEED->XRND) J%=52-XRND MOD (53-I%) S%=CARDS%[I%] CARDS%[I%]=CARDS%[J%] CARDS%[J%]=S% END FOR END PROCEDURE   PROCEDURE SHOW(CARDS%[]) LOCAL INDEX% FOR INDEX%=1 TO 52 DO PRINT(MID$(SUITS$,CARDS%[INDEX%] MOD 4+1,1);MID$(NUMS$,CARDS%[INDEX%] DIV 4+1,1);" ";) IF INDEX% MOD 8=0 OR INDEX%=52 THEN PRINT END IF END FOR END PROCEDURE   BEGIN PRINT(CHR$(12);) SUITS$="♣♦♥♠" NUMS$="A23456789TJQK" GAME_NUM=1982  ! if missing command line IF CMDLINE$<>"" THEN GAME_NUM=VAL(CMDLINE$) END IF SEED=1 DEAL(CARDS%[],GAME_NUM) PRINT("Hand ";GAME_NUM) SHOW(CARDS%[]) END PROGRAM  
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.
#Lua
Lua
function tprint(tbl) for i,v in pairs(tbl) do print(v) end end   function deBruijn(k, n) local a = {} for i=1, k*n do table.insert(a, 0) end   local seq = {} function db(t, p) if t > n then if n % p == 0 then for i=1, p do table.insert(seq, a[i + 1]) end end else a[t + 1] = a[t - p + 1] db(t + 1, p)   local j = a[t - p + 1] + 1 while j < k do a[t + 1] = j % 256 db(t + 1, t) j = j + 1 end end end   db(1, 1)   local buf = "" for i,v in pairs(seq) do buf = buf .. tostring(v) end return buf .. buf:sub(1, n - 1) end   function allDigits(s) return s:match('[0-9]+') == s end   function validate(db) local le = string.len(db) local found = {} local errs = {}   for i=1, 10000 do table.insert(found, 0) end   -- Check all strings of 4 consecutive digits within 'db' -- to see if all 10,000 combinations occur without duplication. for i=1, le - 3 do local s = db:sub(i, i + 3) if allDigits(s) then local n = tonumber(s) found[n + 1] = found[n + 1] + 1 end end   local count = 0 for i=1, 10000 do if found[i] == 0 then table.insert(errs, " PIN number " .. (i - 1) .. " missing") count = count + 1 elseif found[i] > 1 then table.insert(errs, " PIN number " .. (i - 1) .. " occurs " .. found[i] .. " times") count = count + 1 end end   if count == 0 then print(" No errors found") else tprint(errs) end end   function main() local db = deBruijn(10,4)   print("The length of the de Bruijn sequence is " .. string.len(db)) print()   io.write("The first 130 digits of the de Bruijn sequence are: ") print(db:sub(0, 130)) print()   io.write("The last 130 digits of the de Bruijn sequence are: ") print(db:sub(-130)) print()   print("Validating the de Bruijn sequence:") validate(db) print()   print("Validating the reversed de Bruijn sequence:") validate(db:reverse()) print()   db = db:sub(1,4443) .. "." .. db:sub(4445) print("Validating the overlaid de Bruijn sequence:") validate(db) print() end   main()
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.
#JavaScript
JavaScript
function Num(n){ n = Math.floor(n); if(isNaN(n)) throw new TypeError("Not a Number"); if(n < 1 || n > 10) throw new TypeError("Out of range"); this._value = n; } Num.prototype.valueOf = function() { return this._value; } Num.prototype.toString = function () { return this._value.toString();}   var w = new Num(3), x = new Num(4);   WScript.Echo(w + x); //7 WScript.Echo(x - w); //1 WScript.Echo(w * x); //12 WScript.Echo(w / x); //0.75 WScript.Echo(w < x); //true WScript.Echo(x < w); //false   var y = new Num(0); //TypeError var z = new Num(11); //TypeError  
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
#Lua
Lua
function V3(x,y,z) return {x=x,y=y,z=z} end function dot(v,w) return v.x*w.x + v.y*w.y + v.z*w.z end function norm(v) local m=math.sqrt(dot(v,v)) return V3(v.x/m, v.y/m, v.z/m) end function clamp(n,lo,hi) return math.floor(math.min(math.max(lo,n),hi)) end function hittest(s, x, y) local z = s.r^2 - (x-s.x)^2 - (y-s.y)^2 if z >= 0 then z = math.sqrt(z) return true, s.z-z, s.z+z end return false, 0, 0 end   function deathstar(pos, neg, sun, k, amb) shades = {[0]=" ",".",":","!","*","o","e","&","#","%","@"} for y = pos.x-pos.r-0.5, pos.x+pos.r+0.5 do for x = pos.x-pos.r-0.5, pos.x+pos.r+0.5, 0.5 do local hitpos, pz1, pz2 = hittest(pos, x, y) local result, hitneg, nz1, nz2 = 0 if hitpos then hitneg, nz1, nz2 = hittest(neg, x, y) if not hitneg or nz1 > pz1 then result = 1 elseif nz2 > pz2 then result = 0 elseif nz2 > pz1 then result = 2 else result = 1 end end local shade = 0 if result > 0 then if result == 1 then shade = clamp((1-dot(sun, norm(V3(x-pos.x, y-pos.y, pz1-pos.z)))^k+amb) * #shades, 1, #shades) else shade = clamp((1-dot(sun, norm(V3(neg.x-x, neg.y-y, neg.z-nz2)))^k+amb) * #shades, 1, #shades) end end io.write(shades[shade]) end io.write("\n") end end   deathstar({x=20, y=20, z=0, r=20}, {x=10, y=10, z=-15, r=10}, norm(V3(-2,1,3)), 2, 0.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]
#zkl
zkl
var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) fcn dconv1D(f,g){ fsz,hsz:=f.len(), g.len() - fsz +1; A:=GSL.Matrix(g.len(),hsz); foreach n,fn in ([0..].zip(f)){ foreach rc in (hsz){ A[rc+n,rc]=fn } } h:=A.AxEQb(g); h }
http://rosettacode.org/wiki/Deconvolution/2D%2B
Deconvolution/2D+
This task is a straightforward generalization of Deconvolution/1D to higher dimensions. For example, the one dimensional case would be applicable to audio signals, whereas two dimensions would pertain to images. Define the discrete convolution in d {\displaystyle {\mathit {d}}} dimensions of two functions H , F : Z d → R {\displaystyle H,F:\mathbb {Z} ^{d}\rightarrow \mathbb {R} } taking d {\displaystyle {\mathit {d}}} -tuples of integers to real numbers as the function G : Z d → R {\displaystyle G:\mathbb {Z} ^{d}\rightarrow \mathbb {R} } also taking d {\displaystyle {\mathit {d}}} -tuples of integers to reals and satisfying G ( n 0 , … , n d − 1 ) = ∑ m 0 = − ∞ ∞ … ∑ m d − 1 = − ∞ ∞ F ( m 0 , … , m d − 1 ) H ( n 0 − m 0 , … , n d − 1 − m d − 1 ) {\displaystyle G(n_{0},\dots ,n_{d-1})=\sum _{m_{0}=-\infty }^{\infty }\dots \sum _{m_{d-1}=-\infty }^{\infty }F(m_{0},\dots ,m_{d-1})H(n_{0}-m_{0},\dots ,n_{d-1}-m_{d-1})} for all d {\displaystyle {\mathit {d}}} -tuples of integers ( n 0 , … , n d − 1 ) ∈ Z d {\displaystyle (n_{0},\dots ,n_{d-1})\in \mathbb {Z} ^{d}} . Assume F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} (and therefore G {\displaystyle {\mathit {G}}} ) are non-zero over only a finite domain bounded by the origin, hence possible to represent as finite multi-dimensional arrays or nested lists f {\displaystyle {\mathit {f}}} , h {\displaystyle {\mathit {h}}} , and g {\displaystyle {\mathit {g}}} . For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by solving for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . (See Deconvolution/1D for details.) The function should work for g {\displaystyle {\mathit {g}}} of arbitrary length in each dimension (i.e., not hard coded or constant) and f {\displaystyle {\mathit {f}}} of any length up to that of g {\displaystyle {\mathit {g}}} in the corresponding dimension. The deconv function will need to be parameterized by the dimension d {\displaystyle {\mathit {d}}} unless the dimension can be inferred from the data structures representing g {\displaystyle {\mathit {g}}} and f {\displaystyle {\mathit {f}}} . 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. Debug your solution using this test data, of which a portion is shown below. Be sure to verify both that the deconvolution of g {\displaystyle {\mathit {g}}} with f {\displaystyle {\mathit {f}}} is h {\displaystyle {\mathit {h}}} and that the deconvolution of g {\displaystyle {\mathit {g}}} with h {\displaystyle {\mathit {h}}} is f {\displaystyle {\mathit {f}}} . Display the results in a human readable form for the three dimensional case only. dimension 1: h: [-8, 2, -9, -2, 9, -8, -2] f: [ 6, -9, -7, -5] g: [-48, 84, -16, 95, 125, -70, 7, 29, 54, 10] dimension 2: h: [ [-8, 1, -7, -2, -9, 4], [4, 5, -5, 2, 7, -1], [-6, -3, -3, -6, 9, 5]] f: [ [-5, 2, -2, -6, -7], [9, 7, -6, 5, -7], [1, -1, 9, 2, -7], [5, 9, -9, 2, -5], [-8, 5, -2, 8, 5]] g: [ [40, -21, 53, 42, 105, 1, 87, 60, 39, -28], [-92, -64, 19, -167, -71, -47, 128, -109, 40, -21], [58, 85, -93, 37, 101, -14, 5, 37, -76, -56], [-90, -135, 60, -125, 68, 53, 223, 4, -36, -48], [78, 16, 7, -199, 156, -162, 29, 28, -103, -10], [-62, -89, 69, -61, 66, 193, -61, 71, -8, -30], [48, -6, 21, -9, -150, -22, -56, 32, 85, 25]] dimension 3: h: [ [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]], [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]] f: [ [[-9, 5, -8], [3, 5, 1]], [[-1, -7, 2], [-5, -6, 6]], [[8, 5, 8],[-2, -6, -4]]] g: [ [ [54, 42, 53, -42, 85, -72], [45, -170, 94, -36, 48, 73], [-39, 65, -112, -16, -78, -72], [6, -11, -6, 62, 49, 8]], [ [-57, 49, -23, 52, -135, 66], [-23, 127, -58, -5, -118, 64], [87, -16, 121, 23, -41, -12], [-19, 29, 35, -148, -11, 45]], [ [-55, -147, -146, -31, 55, 60], [-88, -45, -28, 46, -26, -144], [-12, -107, -34, 150, 249, 66], [11, -15, -34, 27, -78, -50]], [ [56, 67, 108, 4, 2, -48], [58, 67, 89, 32, 32, -8], [-42, -31, -103, -30, -23, -8], [6, 4, -26, -10, 26, 12]]]
#Perl
Perl
use feature 'say'; use ntheory qw/forsetproduct/;   # Deconvolution of N dimensional matrices sub deconvolve_N { our @g; local *g = shift; our @f; local *f = shift; my @df = shape(@f); my @dg = shape(@g); my @hsize; push @hsize, $dg[$_] - $df[$_] + 1 for 0..$#df; my @toSolve = map { [row(\@g, \@f, \@hsize, $_)] } coords(shape(@g)); rref( \@toSolve );   my @h; my $n = 0; for (coords(@hsize)) { my($k,$j,$i) = split ' ', $_; $h[$i][$j][$k] = $toSolve[$n++][-1]; } @h; }   sub row { our @g; local *g = shift; our @f; local *f = shift; our @hsize; local *hsize = shift; my @gc = reverse split ' ', shift;   my @row; my @fdim = shape(@f); for (coords(@hsize)) { my @hc = reverse split ' ', $_; my @fc; for my $i (0..$#hc) { my $window = $gc[$i] - $hc[$i]; push(@fc, $window), next if 0 <= $window && $window < $fdim[$i]; } push @row, $#fc == $#hc ? $f [$fc[0]] [$fc[1]] [$fc[2]] : 0; } push @row, $g [$gc[0]] [$gc[1]] [$gc[2]]; return @row; }   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;} }   # Constructs an AoA of coordinates to all elements of N dimensional array sub coords { my(@dimensions) = reverse @_; my(@ranges,@coords); push @ranges, [0..$_-1] for @dimensions; forsetproduct { push @coords, "@_" } @ranges; @coords; }   sub shape { my(@dim); push @dim, scalar @_; push @dim, shape(@{$_[0]}) if 'ARRAY' eq ref $_[0]; @dim; }   # Pretty printer for N dimensional arrays # Assumes if first element in level is an array, then all are sub pretty_print { my($i, @a) = @_; if ('ARRAY' eq ref $a[0]) { say ' 'x$i, '['; pretty_print($i+2, @$_) for @a; say ' 'x$i, ']', $i ? ',' : ''; } else { say ' 'x$i, '[', sprintf("@{['%5s'x@a]}",@a), ']', $i ? ',' : ''; } }   my @f = ( [ [ -9, 5, -8 ], [ 3, 5, 1 ], ], [ [ -1, -7, 2 ], [ -5, -6, 6 ], ], [ [ 8, 5, 8 ], [ -2, -6, -4 ], ] );   my @g = ( [ [ 54, 42, 53, -42, 85, -72 ], [ 45,-170, 94, -36, 48, 73 ], [ -39, 65,-112, -16, -78, -72 ], [ 6, -11, -6, 62, 49, 8 ], ], [ [ -57, 49, -23, 52,-135, 66 ], [ -23, 127, -58, -5,-118, 64 ], [ 87, -16, 121, 23, -41, -12 ], [ -19, 29, 35,-148, -11, 45 ], ], [ [ -55,-147,-146, -31, 55, 60 ], [ -88, -45, -28, 46, -26,-144 ], [ -12,-107, -34, 150, 249, 66 ], [ 11, -15, -34, 27, -78, -50 ], ], [ [ 56, 67, 108, 4, 2, -48 ], [ 58, 67, 89, 32, 32, -8 ], [ -42, -31,-103, -30, -23, -8 ], [ 6, 4, -26, -10, 26, 12 ], ] );   my @h = deconvolve_N( \@g, \@f ); my @ff = deconvolve_N( \@g, \@h );   my $d = scalar shape(@g); print "${d}D arrays:\n"; print "h =\n"; pretty_print(0,@h); print "\nff =\n"; pretty_print(0,@ff);
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
#F.23
F#
  let msKindaRand seed = let state = ref seed (fun (_:unit) -> state := (214013 * !state + 2531011) &&& System.Int32.MaxValue !state / (1<<<16))   let unshuffledDeck = [0..51] |> List.map(fun n->sprintf "%c%c" "A23456789TJQK".[n / 4] "CDHS".[n % 4])   let deal boot idx = let (last,rest) = boot |> List.rev |> fun xs->(List.head xs),(xs |> List.tail |> List.rev) if idx=((List.length boot) - 1) then last, rest else rest |> List.mapi (fun i x -> i,x) |> List.partition (fst >> ((>) idx)) |> fun (xs,ys) -> (List.map snd xs),(List.map snd ys) |> fun (xs,ys) -> (List.head ys),(xs @ last::(List.tail ys))   let game gameNo = let rnd = msKindaRand gameNo [52..-1..1] |> List.map (fun i->rnd() % i) |> List.fold (fun (dealt, boot) idx->deal boot idx |> fun (x,xs) -> (x::dealt, xs)) ([],unshuffledDeck) |> fst |> List.rev |> List.chunkBySize 8 |> List.map (String.concat " ") |> String.concat "\n" |> printfn "Game #%d\n%s\n" gameNo     [1; 617] |> List.iter game  
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
seq = DeBruijnSequence[Range[0, 9], 4]; seq = seq~Join~Take[seq, 3]; Length[seq] {seq[[;; 130]], seq[[-130 ;;]]} Complement[ StringDrop[ToString[NumberForm[#, 4, NumberPadding -> {"0", "0"}]], 1] & /@ Range[0, 9999], Union[StringJoin /@ Partition[ToString /@ seq, 4, 1]]] seq = Reverse[seq]; Complement[ StringDrop[ToString[NumberForm[#, 4, NumberPadding -> {"0", "0"}]], 1] & /@ Range[0, 9999], Union[StringJoin /@ Partition[ToString /@ seq, 4, 1]]] seq[[4444]] = "."; Complement[ StringDrop[ToString[NumberForm[#, 4, NumberPadding -> {"0", "0"}]], 1] & /@ Range[0, 9999], Union[StringJoin /@ Partition[ToString /@ seq, 4, 1]]]
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.
#Nim
Nim
import algorithm, parseutils, strformat, strutils   const Digits = "0123456789"   #---------------------------------------------------------------------------------------------------   func deBruijn(k, n: int): string = let alphabet = Digits[0..<k] var a = newSeq[byte](k * n) var sequence: seq[byte]   #.................................................................................................   func db(t, p: int) = if t > n: if n mod p == 0: sequence &= a[1..p] else: a[t] = a[t - p] db(t + 1, p) var j = a[t - p] + 1 while j < k.uint: a[t] = j db(t + 1, t) inc j   #...............................................................................................   db(1, 1) for i in sequence: result &= alphabet[i] result &= result[0..(n-2)]   #---------------------------------------------------------------------------------------------------   proc validate(db: string) =   var found: array[10_000, int] var errs: seq[string]   ## Check all strings of 4 consecutive digits within 'db' ## to see if all 10,000 combinations occur without duplication. for i in 0..(db.len - 4): let s = db[i..(i+3)] var n: int if s.parseInt(n) == 4: inc found[n]   for n, count in found: if count == 0: errs &= fmt" PIN number {n:04d} missing" elif count > 1: errs &= fmt" PIN number {n:04d} occurs {count} times"   if errs.len == 0: echo " No errors found" else: let plural = if errs.len == 1: "" else: "s" echo fmt" {errs.len} error{plural} found" for err in errs: echo err   #———————————————————————————————————————————————————————————————————————————————————————————————————   var db = deBruijn(10, 4)   echo fmt"The length of the de Bruijn sequence is {db.len}" echo "" echo fmt"The first 130 digits of the de Bruijn sequence are: {db[0..129]}" echo "" echo fmt"The last 130 digits of the de Bruijn sequence are: {db[^130..^1]}" echo ""   echo "Validating the deBruijn sequence:" db.validate() echo "" echo "Validating the reversed deBruijn sequence:" reversed(db).join().validate() echo ""   db[4443] = '.' echo "Validating the overlaid deBruijn sequence:" db.validate()
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.
#jq
jq
def typeof: if type == "object" and has("type") then .type else type end;
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.
#Julia
Julia
struct LittleInt <: Integer val::Int8 function LittleInt(n::Real) 1 ≤ n ≤ 10 || throw(ArgumentError("LittleInt number must be in [1, 10]")) return new(Int8(n)) end end Base.show(io::IO, x::LittleInt) = print(io, x.val) Base.convert(::Type{T}, x::LittleInt) where T<:Number = convert(T, x.val) Base.promote_rule(::Type{LittleInt}, ::Type{T}) where T<:Number = T   for op in (:+, :*, :÷, :-, :&, :|, :$, :<, :>, :(==)) @eval (Base.$op)(a::LittleInt, b::LittleInt) = LittleInt(($op)(a.val, b.val)) end   # Test a = LittleInt(3) b = LittleInt(4.0) @show a b @show a + b @show b - a @show a * LittleInt(2) @show b ÷ LittleInt(2) @show a * b
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
#Maple
Maple
with(plots): with(plottools): plots:-display( implicitplot3d(x^2 + y^2 + z^2 = 1, x = -1..0.85, y = -1..1, z = -1..1, style = surface, grid = [50,50,50]), translate(rotate(implicitplot3d(x^2 + y^2 + z^2 = 1, x = 0.85..1, y = -1..1, z = -1..1, style = surface, grid = [50,50,50]), 0, Pi, 0), 1.70, 0, 0), axes = none, scaling = constrained, color = gray)
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
RegionPlot3D[x^2 + y^2 + z^2 < 1 && (x + 1.7)^2 + y^2 + z^2 > 1, {x, -1, 1}, {y, -1, 1}, {z, -1, 1}, Boxed -> False, Mesh -> False, Axes -> False, Background -> Black, PlotPoints -> 100]
http://rosettacode.org/wiki/Deconvolution/2D%2B
Deconvolution/2D+
This task is a straightforward generalization of Deconvolution/1D to higher dimensions. For example, the one dimensional case would be applicable to audio signals, whereas two dimensions would pertain to images. Define the discrete convolution in d {\displaystyle {\mathit {d}}} dimensions of two functions H , F : Z d → R {\displaystyle H,F:\mathbb {Z} ^{d}\rightarrow \mathbb {R} } taking d {\displaystyle {\mathit {d}}} -tuples of integers to real numbers as the function G : Z d → R {\displaystyle G:\mathbb {Z} ^{d}\rightarrow \mathbb {R} } also taking d {\displaystyle {\mathit {d}}} -tuples of integers to reals and satisfying G ( n 0 , … , n d − 1 ) = ∑ m 0 = − ∞ ∞ … ∑ m d − 1 = − ∞ ∞ F ( m 0 , … , m d − 1 ) H ( n 0 − m 0 , … , n d − 1 − m d − 1 ) {\displaystyle G(n_{0},\dots ,n_{d-1})=\sum _{m_{0}=-\infty }^{\infty }\dots \sum _{m_{d-1}=-\infty }^{\infty }F(m_{0},\dots ,m_{d-1})H(n_{0}-m_{0},\dots ,n_{d-1}-m_{d-1})} for all d {\displaystyle {\mathit {d}}} -tuples of integers ( n 0 , … , n d − 1 ) ∈ Z d {\displaystyle (n_{0},\dots ,n_{d-1})\in \mathbb {Z} ^{d}} . Assume F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} (and therefore G {\displaystyle {\mathit {G}}} ) are non-zero over only a finite domain bounded by the origin, hence possible to represent as finite multi-dimensional arrays or nested lists f {\displaystyle {\mathit {f}}} , h {\displaystyle {\mathit {h}}} , and g {\displaystyle {\mathit {g}}} . For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by solving for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . (See Deconvolution/1D for details.) The function should work for g {\displaystyle {\mathit {g}}} of arbitrary length in each dimension (i.e., not hard coded or constant) and f {\displaystyle {\mathit {f}}} of any length up to that of g {\displaystyle {\mathit {g}}} in the corresponding dimension. The deconv function will need to be parameterized by the dimension d {\displaystyle {\mathit {d}}} unless the dimension can be inferred from the data structures representing g {\displaystyle {\mathit {g}}} and f {\displaystyle {\mathit {f}}} . 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. Debug your solution using this test data, of which a portion is shown below. Be sure to verify both that the deconvolution of g {\displaystyle {\mathit {g}}} with f {\displaystyle {\mathit {f}}} is h {\displaystyle {\mathit {h}}} and that the deconvolution of g {\displaystyle {\mathit {g}}} with h {\displaystyle {\mathit {h}}} is f {\displaystyle {\mathit {f}}} . Display the results in a human readable form for the three dimensional case only. dimension 1: h: [-8, 2, -9, -2, 9, -8, -2] f: [ 6, -9, -7, -5] g: [-48, 84, -16, 95, 125, -70, 7, 29, 54, 10] dimension 2: h: [ [-8, 1, -7, -2, -9, 4], [4, 5, -5, 2, 7, -1], [-6, -3, -3, -6, 9, 5]] f: [ [-5, 2, -2, -6, -7], [9, 7, -6, 5, -7], [1, -1, 9, 2, -7], [5, 9, -9, 2, -5], [-8, 5, -2, 8, 5]] g: [ [40, -21, 53, 42, 105, 1, 87, 60, 39, -28], [-92, -64, 19, -167, -71, -47, 128, -109, 40, -21], [58, 85, -93, 37, 101, -14, 5, 37, -76, -56], [-90, -135, 60, -125, 68, 53, 223, 4, -36, -48], [78, 16, 7, -199, 156, -162, 29, 28, -103, -10], [-62, -89, 69, -61, 66, 193, -61, 71, -8, -30], [48, -6, 21, -9, -150, -22, -56, 32, 85, 25]] dimension 3: h: [ [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]], [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]] f: [ [[-9, 5, -8], [3, 5, 1]], [[-1, -7, 2], [-5, -6, 6]], [[8, 5, 8],[-2, -6, -4]]] g: [ [ [54, 42, 53, -42, 85, -72], [45, -170, 94, -36, 48, 73], [-39, 65, -112, -16, -78, -72], [6, -11, -6, 62, 49, 8]], [ [-57, 49, -23, 52, -135, 66], [-23, 127, -58, -5, -118, 64], [87, -16, 121, 23, -41, -12], [-19, 29, 35, -148, -11, 45]], [ [-55, -147, -146, -31, 55, 60], [-88, -45, -28, 46, -26, -144], [-12, -107, -34, 150, 249, 66], [11, -15, -34, 27, -78, -50]], [ [56, 67, 108, 4, 2, -48], [58, 67, 89, 32, 32, -8], [-42, -31, -103, -30, -23, -8], [6, 4, -26, -10, 26, 12]]]
#Phix
Phix
-- demo\rosetta\Deconvolution.exw with javascript_semantics function m_size(sequence m) -- -- returns the size of a matrix as a list of lengths -- sequence res = {} object me = m while sequence(me) do res &= length(me) me = me[1] end while return res end function function make_coordset(sequence size) -- -- returns all points in the matrix, in zero-based indexes, -- eg {{0,0,0}..{3,3,5}} for a 4x4x6 matrix [96 in total] -- sequence res = {} integer count = product(size) for i=0 to count-1 do sequence coords = {} integer j = i for s=length(size) to 1 by -1 do integer dimension = size[s] coords &= mod(j,dimension) j = floor(j/dimension) end for coords = reverse(coords) res = append(res,coords) end for return res end function function row(sequence g, f, gs, gc, fs, hs) -- --# Assembles a row, which is one of the simultaneous equations that needs --# to be solved by reducing the whole set to reduced row echelon form. Note --# that each row describes the equation for a single cell of the 'g' function. --# --# Arguments: --# g The "result" matrix of the convolution being undone. --# h The known "input" matrix of the convolution being undone. --# gs The size descriptor of 'g', passed as argument for efficiency. --# gc The coordinate in 'g' that we are generating the equation for. --# fs The size descriptor of 'f', passed as argument for efficiency. --# hs The size descriptor of 'h' (the unknown "input" matrix), passed --# as argument for efficiency. -- sequence row = {}, coords = make_coordset(hs) for i=1 to length(coords) do sequence hc = coords[i] object fn = f for k=1 to length(gc) do integer d = gc[k]-hc[k] if d<0 or d>=fs[k] then fn = 0 exit end if fn = fn[d+1] end for row = append(row,fn) end for object gn = g for i=1 to length(gc) do gn = gn[gc[i]+1] end for row = append(row,gn) return row end function function toRREF(sequence m) -- -- [renamed] copy of Reduced_row_echelon_form.htm#Phix -- plus one small tweak, as noted below, exit->return, -- not that said seems to make any actual difference. -- integer lead = 1, rows = length(m), cols = length(m[1]) m = deep_copy(m) for r=1 to rows do if lead>=cols then exit end if integer i = r while m[i][lead]=0 do i += 1 if i=rows then i = r lead += 1 -- if lead=cols then exit end if if lead=cols then return m end if end if end while sequence mi = deep_copy(m[r]), mr = sq_div(m[i],m[i][lead]) m[i] = mi m[r] = mr for j=1 to rows do if j!=r then m[j] = sq_sub(m[j],sq_mul(m[j][lead],m[r])) end if end for lead += 1 end for return m end function function lset(sequence h, sequence idx, object v) -- helper routine: store v somewhere deep inside h h = deep_copy(h) integer i1 = idx[1]+1 if length(idx)=1 then h[i1] = v else h[i1] = lset(h[i1],idx[2..$],v) end if return h end function function deconvolve(sequence g, f) -- --# Deconvolve a pair of matrixes. Solves for 'h' such that 'g = f convolve h'. --# --# Arguments: --# g The matrix of data to be deconvolved. --# f The matrix describing the convolution to be removed. -- -- Compute the sizes of the various matrixes involved. sequence gsize = m_size(g), fsize = m_size(f), hsize = sq_add(sq_sub(gsize,fsize),1) -- Prepare the set of simultaneous equations to solve sequence toSolve = {}, coords = make_coordset(gsize) for i=1 to length(coords) do toSolve = append(toSolve,row(g,f,gsize,coords[i],fsize,hsize)) end for -- Solve the equations sequence solved = toRREF(toSolve) -- Create a result matrix of the right size object h = 0 for i=length(hsize) to 1 by -1 do h = repeat(h,hsize[i]) end for -- Fill the results from the equations into the result matrix coords = make_coordset(hsize) for i=1 to length(coords) do h = lset(h,coords[i],solved[i][$]) end for return h end function constant f1 = { 6, -9, -7, -5}, g1 = {-48, 84, -16, 95, 125, -70, 7, 29, 54, 10}, h1 = {-8, 2, -9, -2, 9, -8, -2} if deconvolve(g1, f1)!=h1 then ?9/0 end if if deconvolve(g1, h1)!=f1 then ?9/0 end if constant f2 = {{-5, 2,-2,-6,-7}, { 9, 7,-6, 5,-7}, { 1,-1, 9, 2,-7}, { 5, 9,-9, 2,-5}, {-8, 5,-2, 8, 5}}, g2 = {{ 40, -21, 53, 42, 105, 1, 87, 60, 39, -28}, {-92, -64, 19,-167, -71, -47, 128,-109, 40, -21}, { 58, 85,-93, 37, 101, -14, 5, 37, -76, -56}, {-90,-135, 60,-125, 68, 53, 223, 4, -36, -48}, { 78, 16, 7,-199, 156,-162, 29, 28,-103, -10}, {-62, -89, 69, -61, 66, 193, -61, 71, -8, -30}, { 48, -6, 21, -9,-150, -22, -56, 32, 85, 25}}, h2 = {{-8, 1,-7,-2,-9, 4}, { 4, 5,-5, 2, 7,-1}, {-6,-3,-3,-6, 9, 5}} if deconvolve(g2, f2)!=h2 then ?9/0 end if if deconvolve(g2, h2)!=f2 then ?9/0 end if constant f3 = {{{-9, 5, -8}, { 3, 5, 1}}, {{-1, -7, 2}, {-5, -6, 6}}, {{ 8, 5, 8}, {-2, -6, -4}}}, g3 = {{{ 54, 42, 53, -42, 85, -72}, { 45,-170, 94, -36, 48, 73}, {-39, 65,-112, -16, -78, -72}, { 6, -11, -6, 62, 49, 8}}, {{-57, 49, -23, 52,-135, 66}, {-23, 127, -58, -5,-118, 64}, { 87, -16, 121, 23, -41, -12}, {-19, 29, 35,-148, -11, 45}}, {{-55,-147,-146, -31, 55, 60}, {-88, -45, -28, 46, -26,-144}, {-12,-107, -34, 150, 249, 66}, { 11, -15, -34, 27, -78, -50}}, {{ 56, 67, 108, 4, 2, -48}, { 58, 67, 89, 32, 32, -8}, {-42, -31,-103, -30, -23, -8}, { 6, 4, -26, -10, 26, 12}}}, h3 = {{{ -6, -8, -5, 9}, { -7, 9, -6, -8}, { 2, -7, 9, 8}}, {{ 7, 4, 4, -6}, { 9, 9, 4, -4}, { -3, 7, -2, -3}}} if deconvolve(g3, f3)!=h3 then ?9/0 end if if deconvolve(g3, h3)!=f3 then ?9/0 end if ppOpt({pp_Nest,2,pp_IntFmt,"%3d"}) pp(deconvolve(g3, f3)) pp(deconvolve(g3, h3))
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
#Factor
Factor
USING: formatting grouping io kernel literals make math math.functions namespaces qw sequences sequences.extras ; IN: rosetta-code.freecell   CONSTANT: max-rand-ms $[ 1 15 shift 1 - ] CONSTANT: suits qw{ C D H S } CONSTANT: ranks qw{ A 2 3 4 5 6 7 8 9 T J Q K } SYMBOL: seed   : (random) ( n1 n2 -- n3 ) seed get * + dup seed set ;   : rand-ms ( -- n ) max-rand-ms 2531011 214013 (random) -16 shift bitand ;   : init-deck ( -- seq ) ranks suits [ append ] cartesian-map concat V{ } like ;   : swap-cards ( seq -- seq' ) rand-ms over length [ mod ] [ 1 - ] bi pick exchange ;   : (deal) ( seq -- seq' ) [ [ swap-cards dup pop , ] until-empty ] { } make ;   : deal ( game# -- seq ) seed set init-deck (deal) ;   : .cards ( seq -- ) 8 group [ [ write bl ] each nl ] each nl ;   : .game ( game# -- ) dup "Game #%d\n" printf deal .cards ;   : freecell ( -- ) 1 617 [ .game ] bi@ ;   MAIN: 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.
#Pascal
Pascal
  program deBruijnSequence; uses SysUtils;   // Create a de Bruijn sequence for the given word length and alphabet. function deBruijn( const n : integer; // word length const alphabet : string) : string; var d, k, m, s, t, seqLen : integer; w : array of integer; begin k := Length( alphabet); // de Bruijn sequence will have length k^n seqLen := 1; for t := 1 to n do seqLen := seqLen*k; SetLength( result, seqLen); d := 0; // index into de Bruijn sequence (will be pre-inc'd) // Work through Lyndon words of length <= n, in lexicographic order. SetLength( w, n); // w holds array of indices into the alphabet w[0] := 1; // first Lyndon word m := 1; // m = length of Lyndon word repeat // If m divides n, append the current Lyndon word to the output if (m = n) or (m = 1) or (n mod m = 0) then begin for t := 0 to m - 1 do begin inc(d); result[d] := alphabet[w[t]]; end; end; // Get next Lyndon word using Duval's algorithm: // (1) Fill w with repetitions of current word s := 0; t := m; while (t < n) do begin w[t] := w[s]; inc(t); inc(s); if s = m then s := 0; end; // (2) Repeatedly delete highest index k from end of w, if present m := n; while (m > 0) and (w[m - 1] = k) do dec(m); // (3) If word is now null, stop; else increment end value if m > 0 then inc( w[m - 1]); until m = 0; Assert( d = seqLen); // check that the sequence is exactly filled in end;   // Check a de Bruijn sequence, assuming that its alphabet consists // of the digits '0'..'9' (in any order); procedure CheckDecimal( const n : integer; // word length const deB : string); var count : array of integer; j, L, pin, nrErrors : integer; wrap : string; begin L := Length( deB); // The de Bruijn sequence is cyclic; make an array to handle wrapround. SetLength( wrap, 2*n - 2); for j := 1 to n - 1 do wrap[j] := deB[L + j - n + 1]; for j := n to 2*n - 2 do wrap[j] := deB[j - n + 1]; // Count occurrences of each PIN. // PIN = -1 if character is not a decimal digit. SetLength( count, L); for j := 0 to L - 1 do count[L] := 0; for j := 1 to L - n + 1 do begin pin := SysUtils.StrToIntDef( Copy( deB, j, n), -1); if pin >= 0 then inc( count[pin]); end; for j := 1 to n - 1 do begin pin := SysUtils.StrToIntDef( Copy( wrap, j, n), -1); if pin >= 0 then inc( count[pin]); end; // Check that all counts are 1 nrErrors := 0; for j := 0 to L - 1 do begin if count[j] <> 1 then begin inc( nrErrors); WriteLn( SysUtils.Format( ' PIN %d has count %d', [j, count[j]])); end; end; WriteLn( SysUtils.Format( ' Number of errors = %d', [nrErrors])); end;   // Main routine var deB, rev : string; L, j : integer; begin deB := deBruijn( 4, '0123456789'); // deB := deBruijn( 4, '7368290514'); // any permutation would do L := Length( deB); WriteLn( SysUtils.Format( 'Length of de Bruijn sequence = %d', [L])); if L >= 260 then begin WriteLn; WriteLn( 'First and last 130 characters are:'); WriteLn( Copy( deB, 1, 65)); WriteLn( Copy( deb, 66, 65)); WriteLn( '...'); WriteLn( Copy( deB, L - 129, 65)); WriteLn( Copy( deB, L - 64, 65)); end; WriteLn; WriteLn( 'Checking de Bruijn sequence:'); CheckDecimal( 4, deB); // Check reversed sequence SetLength( rev, L); for j := 1 to L do rev[j] := deB[L + 1 - j]; WriteLn( 'Checking reversed sequence:'); CheckDecimal( 4, rev); // Check sequence with '.' instad of decimal digit if L >= 4444 then begin deB[4444] := '.'; WriteLn( 'Checking vandalized sequence:'); CheckDecimal( 4, deB); end; end.  
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.
#Kotlin
Kotlin
// version 1.1   class TinyInt(i: Int) { private val value = makeTiny(i)   operator fun plus (other: TinyInt): TinyInt = TinyInt(this.value + other.value) operator fun minus(other: TinyInt): TinyInt = TinyInt(this.value - other.value) operator fun times(other: TinyInt): TinyInt = TinyInt(this.value * other.value) operator fun div (other: TinyInt): TinyInt = TinyInt(this.value / other.value) operator fun rem (other: TinyInt): TinyInt = TinyInt(this.value % other.value)   operator fun inc() = TinyInt(this.value + 1) operator fun dec() = TinyInt(this.value - 1)   private fun makeTiny(i: Int): Int = when { i < 1 -> 1 i > 10 -> 10 else -> i }   override fun toString(): String = value.toString() }   fun main(args: Array<String>) { var t1 = TinyInt(6) var t2 = TinyInt(3) println("t1 = $t1") println("t2 = $t2") println("t1 + t2 = ${t1 + t2}") println("t1 - t2 = ${t1 - t2}") println("t1 * t2 = ${t1 * t2}") println("t1 / t2 = ${t1 / t2}") println("t1 % t2 = ${t1 % t2}") println("t1 + 1 = ${++t1}") println("t2 - 1 = ${--t2}") }
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
#Nim
Nim
import math   import bitmap, grayscale_image, nimPNG   type   Vector = array[3, float]   Sphere = object cx, cy, cz: int r: int   #---------------------------------------------------------------------------------------------------   func dot(x, y: Vector): float {.inline.} = x[0] * y[0] + x[1] * y[1] + x[2] * y[2]   #---------------------------------------------------------------------------------------------------   func normalize(v: var Vector) = let invLen = 1 / sqrt(dot(v, v)) v[0] *= invLen v[1] *= invLen v[2] *= invLen   #---------------------------------------------------------------------------------------------------   func hit(s: Sphere; x, y: int): tuple[z1, z2: float; hit: bool] = let x = x - s.cx let y = y - s.cy let zsq = s.r * s.r - (x * x + y * y) if zsq >= 0: let zsqrt = sqrt(zsq.toFloat) result = (s.cz.toFloat - zsqrt, s.cz.toFloat, true) else: result = (0.0, 0.0, false)   #---------------------------------------------------------------------------------------------------   func deathStar(pos, neg: Sphere; k, amb: float; dir: Vector): GrayImage =   let w = pos.r * 4 let h = pos.r * 3 result = newGrayImage(w, h) var vect: Vector let deltaX = pos.cx - w div 2 let deltaY = pos.cy - h div 2   let xMax = pos.cx + pos.r let yMax = pos.cy + pos.r for y in (pos.cy - pos.r)..yMax: for x in (pos.cx - pos.r)..xMax: let (zb1, zb2, posHit) = pos.hit(x, y) if not posHit: continue var (zs1, zs2, negHit) = neg.hit(x, y) if negHit: if zs1 > zb1: negHit = false elif zs2 > zb2: continue if negHit: vect[0] = (neg.cx - x).toFloat vect[1] = (neg.cy - y).toFloat vect[2] = neg.cz.toFloat - zs2 else: vect[0] = (x - pos.cx).toFloat vect[1] = (y - pos.cy).toFloat vect[2] = zb1 - pos.cz.toFloat vect.normalize() var s = dot(dir, vect) if s < 0: s = 0 var lum = (255 * (s.pow(k) + amb) / (1 + amb)).toInt if lum < 0: lum = 0 elif lum > 255: lum = 255 result[x - deltaX, y - deltaY] = Luminance(lum)   #———————————————————————————————————————————————————————————————————————————————————————————————————   var dir: Vector = [float 20, -40, -10] dir.normalize() let pos = Sphere(cx: 0, cy: 0, cz: 0, r: 120) let neg = Sphere(cx: -90, cy: -90, cz: -30, r: 100)   let grayImage = deathStar(pos, neg, 1.5, 0.2, dir)   # Save to PNG. We convert to an RGB image then transform the pixels # in a sequence of bytes (actually a copy) in order to call "savePNG24". let rgbImage = grayImage.toImage var data = newSeqOfCap[byte](rgbImage.pixels.len * 3) for color in rgbImage.pixels: data.add([color.r, color.g, color.b]) echo savePNG24("death_star.png", data, rgbImage.w, rgbImage.h)
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
#Openscad
Openscad
// We are performing geometric subtraction   difference() {   // Create the primary sphere of radius 60 centred at the origin   translate(v = [0,0,0]) { sphere(60); }   /*Subtract an overlapping sphere with a radius of 40 The resultant hole will be smaller than this, because we only only catch the edge */   translate(v = [0,90,0]) { sphere(40); } }
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of December be a Sunday? Using any standard date handling libraries of your programming language; compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to   y2k   type problems.
#11l
11l
print((2008..2121).filter(y -> Time(y, 12, 25).strftime(‘%w’) == ‘0’))
http://rosettacode.org/wiki/Deconvolution/2D%2B
Deconvolution/2D+
This task is a straightforward generalization of Deconvolution/1D to higher dimensions. For example, the one dimensional case would be applicable to audio signals, whereas two dimensions would pertain to images. Define the discrete convolution in d {\displaystyle {\mathit {d}}} dimensions of two functions H , F : Z d → R {\displaystyle H,F:\mathbb {Z} ^{d}\rightarrow \mathbb {R} } taking d {\displaystyle {\mathit {d}}} -tuples of integers to real numbers as the function G : Z d → R {\displaystyle G:\mathbb {Z} ^{d}\rightarrow \mathbb {R} } also taking d {\displaystyle {\mathit {d}}} -tuples of integers to reals and satisfying G ( n 0 , … , n d − 1 ) = ∑ m 0 = − ∞ ∞ … ∑ m d − 1 = − ∞ ∞ F ( m 0 , … , m d − 1 ) H ( n 0 − m 0 , … , n d − 1 − m d − 1 ) {\displaystyle G(n_{0},\dots ,n_{d-1})=\sum _{m_{0}=-\infty }^{\infty }\dots \sum _{m_{d-1}=-\infty }^{\infty }F(m_{0},\dots ,m_{d-1})H(n_{0}-m_{0},\dots ,n_{d-1}-m_{d-1})} for all d {\displaystyle {\mathit {d}}} -tuples of integers ( n 0 , … , n d − 1 ) ∈ Z d {\displaystyle (n_{0},\dots ,n_{d-1})\in \mathbb {Z} ^{d}} . Assume F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} (and therefore G {\displaystyle {\mathit {G}}} ) are non-zero over only a finite domain bounded by the origin, hence possible to represent as finite multi-dimensional arrays or nested lists f {\displaystyle {\mathit {f}}} , h {\displaystyle {\mathit {h}}} , and g {\displaystyle {\mathit {g}}} . For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by solving for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . (See Deconvolution/1D for details.) The function should work for g {\displaystyle {\mathit {g}}} of arbitrary length in each dimension (i.e., not hard coded or constant) and f {\displaystyle {\mathit {f}}} of any length up to that of g {\displaystyle {\mathit {g}}} in the corresponding dimension. The deconv function will need to be parameterized by the dimension d {\displaystyle {\mathit {d}}} unless the dimension can be inferred from the data structures representing g {\displaystyle {\mathit {g}}} and f {\displaystyle {\mathit {f}}} . 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. Debug your solution using this test data, of which a portion is shown below. Be sure to verify both that the deconvolution of g {\displaystyle {\mathit {g}}} with f {\displaystyle {\mathit {f}}} is h {\displaystyle {\mathit {h}}} and that the deconvolution of g {\displaystyle {\mathit {g}}} with h {\displaystyle {\mathit {h}}} is f {\displaystyle {\mathit {f}}} . Display the results in a human readable form for the three dimensional case only. dimension 1: h: [-8, 2, -9, -2, 9, -8, -2] f: [ 6, -9, -7, -5] g: [-48, 84, -16, 95, 125, -70, 7, 29, 54, 10] dimension 2: h: [ [-8, 1, -7, -2, -9, 4], [4, 5, -5, 2, 7, -1], [-6, -3, -3, -6, 9, 5]] f: [ [-5, 2, -2, -6, -7], [9, 7, -6, 5, -7], [1, -1, 9, 2, -7], [5, 9, -9, 2, -5], [-8, 5, -2, 8, 5]] g: [ [40, -21, 53, 42, 105, 1, 87, 60, 39, -28], [-92, -64, 19, -167, -71, -47, 128, -109, 40, -21], [58, 85, -93, 37, 101, -14, 5, 37, -76, -56], [-90, -135, 60, -125, 68, 53, 223, 4, -36, -48], [78, 16, 7, -199, 156, -162, 29, 28, -103, -10], [-62, -89, 69, -61, 66, 193, -61, 71, -8, -30], [48, -6, 21, -9, -150, -22, -56, 32, 85, 25]] dimension 3: h: [ [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]], [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]] f: [ [[-9, 5, -8], [3, 5, 1]], [[-1, -7, 2], [-5, -6, 6]], [[8, 5, 8],[-2, -6, -4]]] g: [ [ [54, 42, 53, -42, 85, -72], [45, -170, 94, -36, 48, 73], [-39, 65, -112, -16, -78, -72], [6, -11, -6, 62, 49, 8]], [ [-57, 49, -23, 52, -135, 66], [-23, 127, -58, -5, -118, 64], [87, -16, 121, 23, -41, -12], [-19, 29, 35, -148, -11, 45]], [ [-55, -147, -146, -31, 55, 60], [-88, -45, -28, 46, -26, -144], [-12, -107, -34, 150, 249, 66], [11, -15, -34, 27, -78, -50]], [ [56, 67, 108, 4, 2, -48], [58, 67, 89, 32, 32, -8], [-42, -31, -103, -30, -23, -8], [6, 4, -26, -10, 26, 12]]]
#Python
Python
  """   https://rosettacode.org/wiki/Deconvolution/2D%2B   Working on 3 dimensional example using test data from the RC task.   Python fft:   https://docs.scipy.org/doc/numpy/reference/routines.fft.html   """   import numpy import pprint   h = [ [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]], [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]] f = [ [[-9, 5, -8], [3, 5, 1]], [[-1, -7, 2], [-5, -6, 6]], [[8, 5, 8],[-2, -6, -4]]] g = [ [ [54, 42, 53, -42, 85, -72], [45, -170, 94, -36, 48, 73], [-39, 65, -112, -16, -78, -72], [6, -11, -6, 62, 49, 8]], [ [-57, 49, -23, 52, -135, 66], [-23, 127, -58, -5, -118, 64], [87, -16, 121, 23, -41, -12], [-19, 29, 35, -148, -11, 45]], [ [-55, -147, -146, -31, 55, 60], [-88, -45, -28, 46, -26, -144], [-12, -107, -34, 150, 249, 66], [11, -15, -34, 27, -78, -50]], [ [56, 67, 108, 4, 2, -48], [58, 67, 89, 32, 32, -8], [-42, -31, -103, -30, -23, -8], [6, 4, -26, -10, 26, 12]]]   def trim_zero_empty(x): """   Takes a structure that represents an n dimensional example. For a 2 dimensional example it will be a list of lists. For a 3 dimensional one it will be a list of list of lists. etc.   Actually these are multidimensional numpy arrays but I was thinking in terms of lists.   Returns the same structure without trailing zeros in the inner lists and leaves out inner lists with all zeros.   """   if len(x) > 0: if type(x[0]) != numpy.ndarray: # x is 1d array return list(numpy.trim_zeros(x)) else: # x is a multidimentional array new_x = [] for l in x: tl = trim_zero_empty(l) if len(tl) > 0: new_x.append(tl) return new_x else: # x is empty list return x   def deconv(a, b): """   Returns function c such that b * c = a.   https://en.wikipedia.org/wiki/Deconvolution   """   # Convert larger polynomial using fft   ffta = numpy.fft.fftn(a)   # Get it's shape so fftn will expand # smaller polynomial to fit.   ashape = numpy.shape(a)   # Convert smaller polynomial with fft # using the shape of the larger one   fftb = numpy.fft.fftn(b,ashape)   # Divide the two in frequency domain   fftquotient = ffta / fftb   # Convert back to polynomial coefficients using ifft # Should give c but with some small extra components   c = numpy.fft.ifftn(fftquotient)   # Get rid of imaginary part and round up to 6 decimals # to get rid of small real components   trimmedc = numpy.around(numpy.real(c),decimals=6)   # Trim zeros and eliminate # empty rows of coefficients   cleanc = trim_zero_empty(trimmedc)   return cleanc   print("deconv(g,h)=")   pprint.pprint(deconv(g,h))   print(" ")   print("deconv(g,f)=")   pprint.pprint(deconv(g,f))  
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
#Fortran
Fortran
module Freecell use lcgs implicit none   character(4) :: suit = "CDHS" character(13) :: rank = "A23456789TJQK" character(2) :: deck(0:51)   contains   subroutine Createdeck() integer :: i, j, n   n = 0 do i = 1, 13 do j = 1, 4 deck(n) = rank(i:i) // suit(j:j) n = n + 1 end do end do   end subroutine   subroutine Freecelldeal(game) integer, intent(in) :: game integer(i64) :: rnum integer :: i, n character(2) :: tmp   call Createdeck() rnum = msrand(game)   do i = 51, 1, -1 n = mod(rnum, i+1) tmp = deck(n) deck(n) = deck(i) deck(i) = tmp rnum = msrand() end do   write(*, "(a, i0)") "Game #", game write(*, "(8(a, tr1))") deck(51:0:-1) write(*,*)   end subroutine end module Freecell   program Freecell_test use Freecell implicit none   call Freecelldeal(1) call Freecelldeal(617)   end program
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.
#Perl
Perl
use strict; use warnings; use feature 'say';   my $seq; for my $x (0..99) { my $a = sprintf '%02d', $x; next if substr($a,1,1) < substr($a,0,1); $seq .= (substr($a,0,1) == substr($a,1,1)) ? substr($a,0,1) : $a; for ($a+1 .. 99) { next if substr(sprintf('%02d', $_), 1,1) <= substr($a,0,1); $seq .= sprintf "%s%02d", $a, $_; } } $seq .= '000';   sub check { my($seq) = @_; my %chk; for (0.. -1 + length $seq) { $chk{substr($seq, $_, 4)}++ } say 'Missing: ' . join ' ', grep { ! $chk{ sprintf('%04d',$_) } } 0..9999; say 'Extra: ' . join ' ', sort grep { $chk{$_} > 1 } keys %chk; }   my $n = 130; say "de Bruijn sequence length: " . length $seq; say "\nFirst $n characters:\n" . substr($seq, 0, $n ); say "\nLast $n characters:\n" . substr($seq, -$n, $n); say "\nIncorrect 4 digit PINs in this sequence:"; check $seq;   say "\nIncorrect 4 digit PINs in the reversed sequence:"; check(reverse $seq);   say "\nReplacing the 4444th digit, '@{[substr($seq,4443,1)]}', with '5'"; substr $seq, 4443, 1, 5; say "Incorrect 4 digit PINs in the revised sequence:"; check $seq;
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.
#Lasso
Lasso
define dint => type { data private value   public oncreate(value::integer) => { fail_if(#value < 1,#value+' less than 1 ') fail_if(#value > 10,#value+' greater than 10') .value = #value }   public +(rhs::integer) => dint(.value + #rhs) public -(rhs::integer) => dint(.value - #rhs) public *(rhs::integer) => dint(.value * #rhs) public /(rhs::integer) => dint(.value / #rhs) public %(rhs::integer) => dint(.value % #rhs)   public asstring() => string(.value)   }   dint(1) // 1 dint(10) // 10   dint(0) // Error: 0 less than 1 dint(2) - 5 // Error: -3 less than 1   dint(11) // Error: 11 greater than 10 dint(10) + 1 // Error: 11 greater than 10 dint(10) * 2 // Error: 20 greater than 10  
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.
#Lua
Lua
BI = { -- Bounded Integer new = function(self, v) return setmetatable({v = self:_limit(v)}, BI_mt) end, _limit = function(self,v) return math.max(1, math.min(math.floor(v), 10)) end, } BI_mt = { __index = BI, __call = function(self,v) return self:new(v) end, __unm = function(self) return BI(-self.v) end, __add = function(self,other) return BI(self.v+other.v) end, __sub = function(self,other) return BI(self.v-other.v) end, __mul = function(self,other) return BI(self.v*other.v) end, __div = function(self,other) return BI(self.v/other.v) end, __mod = function(self,other) return BI(self.v%other.v) end, __pow = function(self,other) return BI(self.v^other.v) end, __eq = function(self,other) return self.v==other.v end, __lt = function(self,other) return self.v<other.v end, __le = function(self,other) return self.v<=other.v end, __tostring = function(self) return tostring(self.v) end } setmetatable(BI, BI_mt)
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
#Perl
Perl
use strict;   sub sq { my $s = 0; $s += $_ ** 2 for @_; $s; }   sub hit { my ($sph, $x, $y) = @_; $x -= $sph->[0]; $y -= $sph->[1];   my $z = sq($sph->[3]) - sq($x, $y); return if $z < 0;   $z = sqrt $z; return $sph->[2] - $z, $sph->[2] + $z; }   sub normalize { my $v = shift; my $n = sqrt sq(@$v); $_ /= $n for @$v; $v; }   sub dot { my ($x, $y) = @_; my $s = $x->[0] * $y->[0] + $x->[1] * $y->[1] + $x->[2] * $y->[2]; $s > 0 ? $s : 0; }   my $pos = [ 120, 120, 0, 120 ]; my $neg = [ -77, -33, -100, 190 ]; my $light = normalize([ -12, 13, -10 ]); sub draw { my ($k, $amb) = @_; binmode STDOUT, ":raw"; print "P5\n", $pos->[0] * 2 + 3, " ", $pos->[1] * 2 + 3, "\n255\n"; for my $y (($pos->[1] - $pos->[3] - 1) .. ($pos->[1] + $pos->[3] + 1)) { my @row = (); for my $x (($pos->[0] - $pos->[3] - 1) .. ($pos->[0] + $pos->[3] + 1)) { my ($hit, @hs) = 0; my @h = hit($pos, $x, $y);   if (!@h) { $hit = 0 } elsif (!(@hs = hit($neg, $x, $y))) { $hit = 1 } elsif ($hs[0] > $h[0]) { $hit = 1 } elsif ($hs[1] > $h[0]) { $hit = $hs[1] > $h[1] ? 0 : 2 } else { $hit = 1 }   my ($val, $v); if ($hit == 0) { $val = 0 } elsif ($hit == 1) { $v = [ $x - $pos->[0], $y - $pos->[1], $h[0] - $pos->[2] ]; } else { $v = [ $neg->[0] - $x, $neg->[1] - $y, $neg->[2] - $hs[1] ]; } if ($v) { normalize($v); $val = int((dot($v, $light) ** $k + $amb) * 255); $val = ($val > 255) ? 255 : ($val < 0) ? 0 : $val; } push @row, $val; } print pack("C*", @row); } }   draw(2, 0.2);
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of December be a Sunday? Using any standard date handling libraries of your programming language; compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to   y2k   type problems.
#360_Assembly
360 Assembly
* Day of the week 06/07/2016 DOW CSECT USING DOW,R15 base register LA R6,2008 year=2008 LOOP C R6,=F'2121' do year=2008 to 2121 BH ELOOP . LR R7,R6 y=year LA R8,12 m=12 LA R9,25 d=25 C R8,=F'3' if m<3 BNL MGE3 then LA R8,12(R8) m=m+12 BCTR R7,0 y=y-1 MGE3 LR R10,R7 y SRDA R10,32 . D R10,=F'100' r=y//100 ; l=y/100 LR R3,R8 m LA R3,1(R3) m+1 M R2,=F'26' *26 D R2,=F'10' /10 AR R3,R9 +d AR R3,R10 +r LR R2,R10 r SRA R2,2 /4 AR R2,R3 (d+(m+1)*26/10+r+r/4 LR R3,R11 l SRA R3,2 /4 AR R2,R3 (d+(m+1)*26/10+r+r/4+l/4 LA R5,5 5 MR R4,R11 *l AR R2,R5 (d+(m+1)*26/10+r+r/4+l/4+5*l) SRDA R2,32 . D R2,=F'7' w=(d+(m+1)*26/10+r+r/4+l/4+5*l)//7 C R2,=F'1' if w=1 (sunday) BNE WNE1 then XDECO R6,PG edit year XPRNT PG,12 print year WNE1 LA R6,1(R6) year=year+1 B LOOP next year ELOOP BR R14 exit PG DS CL12 buffer YREGS END DOW
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of December be a Sunday? Using any standard date handling libraries of your programming language; compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to   y2k   type problems.
#ABAP
ABAP
report zday_of_week data: lv_start type i value 2007, lv_n type i value 114, lv_date type sy-datum, lv_weekday type string, lv_day type c, lv_year type n length 4.   write 'December 25 is a Sunday in: '. do lv_n times. lv_year = lv_start + sy-index. concatenate lv_year '12' '25' into lv_date. call function 'DATE_COMPUTE_DAY' exporting date = lv_date importing day = lv_day.   select single langt from t246 into lv_weekday where sprsl = sy-langu and wotnr = lv_day.   if lv_weekday eq 'Sunday'. write / lv_year. endif. enddo.  
http://rosettacode.org/wiki/Deconvolution/2D%2B
Deconvolution/2D+
This task is a straightforward generalization of Deconvolution/1D to higher dimensions. For example, the one dimensional case would be applicable to audio signals, whereas two dimensions would pertain to images. Define the discrete convolution in d {\displaystyle {\mathit {d}}} dimensions of two functions H , F : Z d → R {\displaystyle H,F:\mathbb {Z} ^{d}\rightarrow \mathbb {R} } taking d {\displaystyle {\mathit {d}}} -tuples of integers to real numbers as the function G : Z d → R {\displaystyle G:\mathbb {Z} ^{d}\rightarrow \mathbb {R} } also taking d {\displaystyle {\mathit {d}}} -tuples of integers to reals and satisfying G ( n 0 , … , n d − 1 ) = ∑ m 0 = − ∞ ∞ … ∑ m d − 1 = − ∞ ∞ F ( m 0 , … , m d − 1 ) H ( n 0 − m 0 , … , n d − 1 − m d − 1 ) {\displaystyle G(n_{0},\dots ,n_{d-1})=\sum _{m_{0}=-\infty }^{\infty }\dots \sum _{m_{d-1}=-\infty }^{\infty }F(m_{0},\dots ,m_{d-1})H(n_{0}-m_{0},\dots ,n_{d-1}-m_{d-1})} for all d {\displaystyle {\mathit {d}}} -tuples of integers ( n 0 , … , n d − 1 ) ∈ Z d {\displaystyle (n_{0},\dots ,n_{d-1})\in \mathbb {Z} ^{d}} . Assume F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} (and therefore G {\displaystyle {\mathit {G}}} ) are non-zero over only a finite domain bounded by the origin, hence possible to represent as finite multi-dimensional arrays or nested lists f {\displaystyle {\mathit {f}}} , h {\displaystyle {\mathit {h}}} , and g {\displaystyle {\mathit {g}}} . For this task, implement a function (or method, procedure, subroutine, etc.) deconv to perform deconvolution (i.e., the inverse of convolution) by solving for h {\displaystyle {\mathit {h}}} given f {\displaystyle {\mathit {f}}} and g {\displaystyle {\mathit {g}}} . (See Deconvolution/1D for details.) The function should work for g {\displaystyle {\mathit {g}}} of arbitrary length in each dimension (i.e., not hard coded or constant) and f {\displaystyle {\mathit {f}}} of any length up to that of g {\displaystyle {\mathit {g}}} in the corresponding dimension. The deconv function will need to be parameterized by the dimension d {\displaystyle {\mathit {d}}} unless the dimension can be inferred from the data structures representing g {\displaystyle {\mathit {g}}} and f {\displaystyle {\mathit {f}}} . 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. Debug your solution using this test data, of which a portion is shown below. Be sure to verify both that the deconvolution of g {\displaystyle {\mathit {g}}} with f {\displaystyle {\mathit {f}}} is h {\displaystyle {\mathit {h}}} and that the deconvolution of g {\displaystyle {\mathit {g}}} with h {\displaystyle {\mathit {h}}} is f {\displaystyle {\mathit {f}}} . Display the results in a human readable form for the three dimensional case only. dimension 1: h: [-8, 2, -9, -2, 9, -8, -2] f: [ 6, -9, -7, -5] g: [-48, 84, -16, 95, 125, -70, 7, 29, 54, 10] dimension 2: h: [ [-8, 1, -7, -2, -9, 4], [4, 5, -5, 2, 7, -1], [-6, -3, -3, -6, 9, 5]] f: [ [-5, 2, -2, -6, -7], [9, 7, -6, 5, -7], [1, -1, 9, 2, -7], [5, 9, -9, 2, -5], [-8, 5, -2, 8, 5]] g: [ [40, -21, 53, 42, 105, 1, 87, 60, 39, -28], [-92, -64, 19, -167, -71, -47, 128, -109, 40, -21], [58, 85, -93, 37, 101, -14, 5, 37, -76, -56], [-90, -135, 60, -125, 68, 53, 223, 4, -36, -48], [78, 16, 7, -199, 156, -162, 29, 28, -103, -10], [-62, -89, 69, -61, 66, 193, -61, 71, -8, -30], [48, -6, 21, -9, -150, -22, -56, 32, 85, 25]] dimension 3: h: [ [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]], [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]] f: [ [[-9, 5, -8], [3, 5, 1]], [[-1, -7, 2], [-5, -6, 6]], [[8, 5, 8],[-2, -6, -4]]] g: [ [ [54, 42, 53, -42, 85, -72], [45, -170, 94, -36, 48, 73], [-39, 65, -112, -16, -78, -72], [6, -11, -6, 62, 49, 8]], [ [-57, 49, -23, 52, -135, 66], [-23, 127, -58, -5, -118, 64], [87, -16, 121, 23, -41, -12], [-19, 29, 35, -148, -11, 45]], [ [-55, -147, -146, -31, 55, 60], [-88, -45, -28, 46, -26, -144], [-12, -107, -34, 150, 249, 66], [11, -15, -34, 27, -78, -50]], [ [56, 67, 108, 4, 2, -48], [58, 67, 89, 32, 32, -8], [-42, -31, -103, -30, -23, -8], [6, 4, -26, -10, 26, 12]]]
#Raku
Raku
# Deconvolution of N dimensional matrices. sub deconvolve-N ( @g, @f ) { my @hsize = @g.shape »-« @f.shape »+» 1;   my @toSolve = coords(@g.shape).map: { [row(@g, @f, $^coords, @hsize)] };   my @solved = rref( @toSolve );   my @h; for flat coords(@hsize) Z @solved[*;*-1] -> $_, $v { @h.AT-POS(|$_) = $v; } @h }   # Construct a row for each value in @g to be sent to the simultaneous equation solver sub row ( @g, @f, @gcoord, $hsize ) { my @row; @gcoord = @gcoord[(^@f.shape)]; # clip extraneous values for coords( $hsize ) -> @hc { my @fcoord; for ^@hc -> $i { my $window = @gcoord[$i] - @hc[$i]; @fcoord.push($window) and next if 0 ≤ $window < @f.shape[$i]; last; } @row.push: @fcoord == @hc ?? @f.AT-POS(|@fcoord) !! 0; } @row.push: @g.AT-POS(|@gcoord); @row }   # Constructs an AoA of coordinates to all elements of N dimensional array sub coords ( @dim ) { @[reverse $_ for [X] ([^$_] for reverse @dim)] }   # Reduced Row Echelon Form simultaneous equation solver # Can handle over-specified systems (N unknowns in N + M equations) sub rref (@m) { @m = trim-system @m; my ($lead, $rows, $cols) = 0, @m, @m[0]; for ^$rows -> $r { return @m unless $lead < $cols; my $i = $r; until @m[$i;$lead] { next unless ++$i == $rows; $i = $r; return @m if ++$lead == $cols; } @m[$i, $r] = @m[$r, $i] if $r != $i; @m[$r] »/=» $ = @m[$r;$lead]; for ^$rows -> $n { next if $n == $r; @m[$n] »-=» @m[$r] »×» (@m[$n;$lead] // 0); } ++$lead; } @m }   # Reduce to N equations in N unknowns; a no-op unless rows > cols sub trim-system (@m) { return @m unless @m ≥ @m[0]; my (\vars, @t) = @m[0] - 1; for ^vars -> \lead { for ^@m -> \row { @t.append: @m.splice(row, 1) and last if @m[row;lead]; } } while @t < vars and @m { @t.push: shift @m } @t }   # Pretty printer for N dimensional arrays # Assumes if first element in level is an array, then all are sub pretty-print ( @array, $indent = 0 ) { if @array[0] ~~ Array { say ' ' x $indent,"["; pretty-print( $_, $indent + 2 ) for @array; say ' ' x $indent, "]{$indent??','!!''}"; } else { say ' ' x $indent, "[{say_it(@array)} ]{$indent??','!!''}"; }   sub say_it ( @array ) { return join ",", @array».fmt("%4s"); } }   my @f[3;2;3] = ( [ [ -9, 5, -8 ], [ 3, 5, 1 ], ], [ [ -1, -7, 2 ], [ -5, -6, 6 ], ], [ [ 8, 5, 8 ], [ -2, -6, -4 ], ] );   my @g[4;4;6] = ( [ [ 54, 42, 53, -42, 85, -72 ], [ 45,-170, 94, -36, 48, 73 ], [ -39, 65,-112, -16, -78, -72 ], [ 6, -11, -6, 62, 49, 8 ], ], [ [ -57, 49, -23, 52,-135, 66 ], [ -23, 127, -58, -5,-118, 64 ], [ 87, -16, 121, 23, -41, -12 ], [ -19, 29, 35,-148, -11, 45 ], ], [ [ -55,-147,-146, -31, 55, 60 ], [ -88, -45, -28, 46, -26,-144 ], [ -12,-107, -34, 150, 249, 66 ], [ 11, -15, -34, 27, -78, -50 ], ], [ [ 56, 67, 108, 4, 2, -48 ], [ 58, 67, 89, 32, 32, -8 ], [ -42, -31,-103, -30, -23, -8 ], [ 6, 4, -26, -10, 26, 12 ], ] );   say "# {[email protected]}D array:"; my @h = deconvolve-N( @g, @f ); say "h ="; pretty-print( @h ); my @h-shaped[2;3;4] = @(deconvolve-N( @g, @f )); my @ff = deconvolve-N( @g, @h-shaped ); say "\nff ="; pretty-print( @ff );
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
#FreeBASIC
FreeBASIC
' version 04-11-2016 ' compile with: fbc -s console   ' to seed ms_lcg(seed > -1) ' to get random number ms_lcg(-1) or ms_lcg() or just ms_lcg Function ms_lcg(seed As Integer = -1) As UInteger   Static As UInteger ms_state   If seed <> -1 Then ms_state = seed Mod 2 ^ 31 Else ms_state = (214013 * ms_state + 2531011) Mod 2 ^ 31 End If   Return ms_state Shr 16   End Function   ' ------=< MAIN >=------   Dim As UByte card(51) Dim As String suit = "CDHS", value = "A23456789TJQK" Dim As Long i, c, s, v, game = 1 Dim As ULong game_nr(1 To 2) = { 1, 617}   Do   ms_lcg(game_nr(game)) ' seed generator Print "game #"; game_nr(game) game = game + 1   For i = 0 To 51 ' set up the cards card(i) = i Next   For i = 51 To 0 Step -1 ' shuffle c = ms_lcg Mod (i +1) Swap card(i), card(c) Next   c = 0 Do For i = 0 To 7 s = card(51 - c) Mod 4 v = card(51 - c) \ 4 Print Chr(value[v]); Chr(suit[s]); " "; c = c +1 If c > 51 Then Exit Do Next Print Loop Print : Print   Loop Until game > UBound(game_nr)     ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep End
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.
#Phix
Phix
string deBruijn = "" for n=0 to 99 do string a = sprintf("%02d",n) integer a1 = a[1], a2 = a[2] if a2>=a1 then deBruijn &= iff(a1=a2?a1:a) for m=n+1 to 99 do string ms = sprintf("%02d",m) if ms[2]>a1 then deBruijn &= a&ms end if end for end if end for deBruijn &= "000" printf(1,"de Bruijn sequence length: %d\n\n",length(deBruijn)) printf(1,"First 130 characters:\n%s\n\n",deBruijn[1..130]) printf(1,"Last 130 characters:\n%s\n\n",deBruijn[-130..-1]) function check(string text) sequence res = {} sequence found = repeat(0,10000) integer k for i=1 to length(text)-3 do k = to_integer(text[i..i+3],-1)+1 if k!=0 then found[k] += 1 end if end for for i=1 to 10000 do k = found[i] if k!=1 then string e = sprintf("Pin number %04d ",i-1) e &= iff(k=0?"missing":sprintf("occurs %d times",k)) res = append(res,e) end if end for k = length(res) if k=0 then res = "No errors found" else string s = iff(k=1?"":"s") res = sprintf("%d error%s found:\n ",{k,s})&join(res,"\n ") end if return res end function printf(1,"Missing 4 digit PINs in this sequence: %s\n", check(deBruijn)) printf(1,"Missing 4 digit PINs in the reversed sequence: %s\n",check(reverse(deBruijn))) printf(1,"4444th digit in the sequence: %c (setting it to .)\n", deBruijn[4444]) deBruijn[4444] = '.' printf(1,"Re-running checks: %s\n",check(deBruijn))
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.
#M2000_Interpreter
M2000 Interpreter
  Module CheckDataType { Module CheckThis { Class typeA { Private: mval as currency Public: Property min {value}=-1 Property max {value}=0 Operator "++" { if .mval=.[max] then Error "Number bigger than Max Value" .mval++ } Operator "--" { if .mval=.[min] then Error "Number lower than Min Value" .mval-- } Operator "+=" (x){ if .mval>.[max]+x then Error "Number bigger than Max Value" .mval+=x } Operator "-=" (x) { if .mval<.[min]-x then Error "Number lower than Min Value" .mval-=x } Value { =.mval } Set (x) { if x>.[max] then Error "Number bigger than Max Value" if x<.[min] then Error "Number lower than Min Value" .mval<=int(x) } Class: Module typeA (.[min], .[max]) { .mval<=.[min] } } K=typeA(1, 10) K=5 Def TypeExp$(x)=Type$(x) Print Type$(K)="Group", TypeExp$(K)="Currency" K-- Print K K=K+1 Print K, K.Max, K.Min K+=4 Print K, K.Max, K.Min Print -K*4=-36 Try Ok { K=400 } If Error or Not Ok then Print Error$ \\ make a new K as K with name Z Z=Group(K) Print Z.Max, Z.Min, Z K++ Z=Group(K) Print Z=K K-=5 \\ We make M as pointer to K M->K Print Eval(M), K For M {This++} Print Eval(M), K For M {This=8} Print Eval(M), K Push Group(M), Group(M) } CheckThis \\ Read Group from stack of values and place a copy in each item in A() Dim A(4)=Group \\ We have one more group in stack, so we read it to new variable What \\ What isn't a pointer to object, is the object (internal is a pointer to objet but isn't usable for M2000) Read What What++ Print What.Max=10, What.Min=1, What=9 ' True True True Print A(2).Max=10, A(2).Min=1, A(2)=8 ' True True True } CheckDataType  
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.
#MATLAB
MATLAB
classdef RingInt   properties value end   methods   %RingInt constructor function theInt = RingInt(varargin) if numel(varargin) == 0 theInt.value = 1; elseif numel(varargin) > 1 error 'The RingInt constructor can''''t take more than 1 argument.'; else   %Makes sure any doubles are coerced to ints if not(isinteger(varargin{1})) varargin{1} = int32(varargin{1}); end   %Maps out of bound values to the proper range if varargin{1} > 10 theInt.value = varargin{1} - (10 * (idivide(varargin{1},10,'ceil') - 1)); elseif varargin{1} < 1 theInt.value = varargin{1} + (10 * (idivide(abs(varargin{1}),10,'floor') + 1)); else theInt.value = varargin{1}; end end end %constructor   %Overload the "+" operator function sum = plus(firstNumber,secondNumber)   if isa(firstNumber,'RingInt') && isa(secondNumber,'RingInt') sum = firstNumber.value + secondNumber.value; elseif isa(firstNumber,'RingInt') && not(isa(secondNumber,'RingInt')) sum = firstNumber.value + secondNumber; else sum = secondNumber.value + firstNumber; end   sum = RingInt(sum);   end %+   %Overload the "-" operator function difference = minus(firstNumber,secondNumber)   if isa(firstNumber,'RingInt') && isa(secondNumber,'RingInt') difference = firstNumber.value - secondNumber.value; elseif isa(firstNumber,'RingInt') && not(isa(secondNumber,'RingInt')) difference = firstNumber.value - secondNumber; else difference = firstNumber - secondNumber.value; end   difference = RingInt(difference);   end %-   %Overload the "==" operator function trueFalse = eq(firstNumber,secondNumber)   if isa(firstNumber,'RingInt') && isa(secondNumber,'RingInt') trueFalse = firstNumber.value == secondNumber.value; else error 'You can only compare a RingInt to another RingInt'; end   end %==     %Overload the display() function function display(ringInt) disp(ringInt); end   %Overload the disp() function function disp(ringInt) disp(sprintf('\nans =\n\n\t %d\n',ringInt.value)); end   end %methods end %classdef    
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
#Phix
Phix
-- -- demo\rosetta\DeathStar.exw -- ========================== -- -- Translated from Go. -- with javascript_semantics include pGUI.e constant title = "Death Star" Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas function dot(sequence x, sequence y) return sum(sq_mul(x,y)) end function function normalize(sequence v) atom len = sqrt(dot(v, v)) if len=0 then return {0,0,0} end if return sq_mul(v,1/len) end function enum X,Y,Z function hit(sequence s, atom x, y, r) x -= s[X] y -= s[Y] atom zsq := r*r - (x*x + y*y) if zsq >= 0 then atom zsqrt := sqrt(zsq) return {s[Z] - zsqrt, s[Z] + zsqrt, true} end if return {0, 0, false} end function procedure deathStar(integer width, height, atom k, atom amb, sequence direction) atom t0 = time()+1, t1 = t0, lmul = 255/(1+amb) integer r = floor((min(width,height)-40)/2), cx = floor(width/2), cy = floor(height/2) sequence pos = {0,0,0}, neg = {r*-3/4,r*-3/4,r*-1/4} for y = -r to +r do if time()>t1 then -- Let the user know we aren't completely dead just yet IupSetStrAttribute(dlg,"TITLE","%s - drawing (%d%%)",{title,100*(y+r)/(2*r)}) t1 = time()+1 -- -- Hmm, not entirely sure why this is needed, but without it -- after ~7 seconds the window gets a "(Not Responding)" and -- then something decides to force a full repaint, which at -- fullscreen will never finish in < 7s on this ancient box. -- I suppose this is the corrollary to the above, this time -- letting Windows 10 know the process is not quite dead... -- Currently and possibly forever neither of these routines -- exist in pGUI.js, the browser is more forgiving anyway. -- if platform()!=JS then if IupLoopStep()=IUP_CLOSE then IupExitLoop() exit end if end if end if for x = -r to +r do atom {zb1, zb2, hit1} := hit(pos, x, y, r) if hit1 then atom {zs1, zs2, hit2} := hit(neg, x, y, r/2) if not hit2 or zs2<=zb2 then bool dish = hit2 and zs1<=zb1 sequence vec = iff(dish?sq_sub(neg,{x,y,zs2}):{x,y,zb1}) atom s = dot(direction, normalize(vec)), l = iff(s<=0?0:power(s,k)) integer lum = and_bits(#FF,lmul*(l+amb)) cdCanvasPixel(cddbuffer, cx+x, cy-y, lum*#10101) end if end if end for end for if t1!=t0 then IupSetStrAttribute(dlg,"TITLE",title) end if end procedure function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/) integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE") cdCanvasActivate(cddbuffer) cdCanvasClear(cddbuffer) deathStar(width, height, 1.5, 0.2, normalize({20, -40, -10})) cdCanvasFlush(cddbuffer) return IUP_DEFAULT end function function map_cb(Ihandle ih) cdcanvas = cdCreateCanvas(CD_IUP, ih) cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) cdCanvasSetBackground(cddbuffer, CD_BLACK) return IUP_DEFAULT end function procedure main() IupOpen() canvas = IupCanvas("RASTERSIZE=340x340") IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"), "ACTION", Icallback("redraw_cb")}) dlg = IupDialog(canvas,`TITLE="%s"`,{title}) IupMap(dlg) IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation IupShow(dlg) if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of December be a Sunday? Using any standard date handling libraries of your programming language; compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to   y2k   type problems.
#Action.21
Action!
  Byte FUNC DayOfWeek(BYTE day, month CARD year BYTE century) CARD weekday BYTE ARRAY index=[0 3 2 5 0 3 5 1 4 6 2 4]   IF year < 100 THEN year = year + century * 100 FI   IF year < 1753 THEN RETURN(7) FI   IF month < 3 THEN year==-1 FI   month = index(month-1) weekday=year + year/4 - year/100 + year/400 + month + day weekday = weekday MOD 7 RETURN (weekday)   PROC main() CARD y PrintE("December 25 is a Sunday in:") FOR y = 2008 to 2121 DO IF DayOfWeek(25, 12, y)=0 THEN PrintCE(y) FI OD RETURN  
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of December be a Sunday? Using any standard date handling libraries of your programming language; compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to   y2k   type problems.
#Ada
Ada
with Ada.Calendar.Formatting; use Ada.Calendar.Formatting; with Ada.Text_IO; use Ada.Text_IO;   procedure Yuletide is begin for Year in 2008..2121 loop if Day_Of_Week (Time_Of (Year, 12, 25)) = Sunday then Put_Line (Image (Time_Of (Year, 12, 25))); end if; end loop; end Yuletide;