WeixiangYan/CodeTransOcean huggingface dataset:
Task: Permutations_Derangements







Python: from itertools import permutations
import math


def derangements(n):
    'All deranged permutations of the integers 0..n-1 inclusive'
    return ( perm for perm in permutations(range(n))
             if all(indx != p for indx, p in enumerate(perm)) )

def subfact(n):
    if n == 2 or n == 0:
        return 1
    elif n == 1:
        return 0
    elif  1 <= n <=18:
        return round(math.factorial(n) / math.e)
    elif n.imag == 0 and n.real == int(n.real) and n > 0:
        return (n-1) * ( subfact(n - 1) + subfact(n - 2) )
    else:
        raise ValueError()

def _iterlen(iter):
    'length of an iterator without taking much memory'
    l = 0
    for x in iter:
        l += 1
    return l

if __name__ == '__main__':
    n = 4
    print("Derangements of %s" % (tuple(range(n)),))
    for d in derangements(n):
        print("  %s" % (d,))

    print("\nTable of n vs counted vs calculated derangements")
    for n in range(10):
        print("%2i %-5i %-5i" %
              (n, _iterlen(derangements(n)), subfact(n)))

    n = 20
    print("\n!%i = %i" % (n, subfact(n)))





Ada: with Ada.Text_IO; use Ada.Text_IO;
procedure DePermute is
   type U64 is mod 2**64;
   type Num is range 0 .. 20;
   type NumList is array (Natural range <>) of Num;
   type PtNumList is access all NumList;
   package IO is new Ada.Text_IO.Integer_IO (Num);
   package UIO is new Ada.Text_IO.Modular_IO (U64);
   
   function deranged (depth : Natural; list : PtNumList;
      show : Boolean) return U64 is
      tmp : Num;  count : U64 := 0;
   begin
      if depth = list'Length then
         if show then
            for i in list'Range loop IO.Put (list (i), 2); end loop;
            New_Line;
         end if;  return 1;
      end if;
      for i in reverse depth .. list'Last loop
         if Num (i + 1) /= list (depth) then
            tmp := list (i); list (i) := list (depth); list (depth) := tmp;
            count := count + deranged (depth + 1, list, show);
            tmp := list (i); list (i) := list (depth); list (depth) := tmp;
         end if;
      end loop;
      return count;
   end deranged;

   function gen_n (len : Natural; show : Boolean) return U64 is
      list : PtNumList;
   begin
      list := new NumList (0 .. len - 1);
      for i in list'Range loop list (i) := Num (i + 1); end loop;
      return deranged (0, list, show);
   end gen_n;

   function sub_fact (n : Natural) return U64 is begin
      if n < 2 then return U64 (1 - n);
      else return (sub_fact (n - 1) + sub_fact (n - 2)) * U64 (n - 1);
      end if;
   end sub_fact;

   count : U64;
begin
   Put_Line ("Deranged 4:");
   count := gen_n (4, True);
   Put_Line ("List vs. calc:");
   for i in Natural range 0 .. 9 loop
      IO.Put (Num (i), 1);  UIO.Put (gen_n (i, False), 7);
      UIO.Put (sub_fact (i), 7);  New_Line;
   end loop;
   Put_Line ("!20 = " & U64'Image (sub_fact (20)));
end DePermute;
Task: Permutations_Derangements

C: #include <stdio.h>
typedef unsigned long long LONG;

LONG deranged(int depth, int len, int *d, int show)
{
        int i;
        char tmp;
        LONG count = 0;

        if (depth == len) {
                if (show) {
                        for (i = 0; i < len; i++) putchar(d[i] + 'a');
                        putchar('\n');
                }
                return 1;
        }
        for (i = len - 1; i >= depth; i--) {
                if (i == d[depth]) continue;

                tmp = d[i]; d[i] = d[depth]; d[depth] = tmp;
                count += deranged(depth + 1, len, d, show);
                tmp = d[i]; d[i] = d[depth]; d[depth] = tmp;
        }
        return count;
}

LONG gen_n(int n, int show)
{
        LONG i;
        int a[1024]; 

        for (i = 0; i < n; i++) a[i] = i;
        return deranged(0, n, a, show);
}

LONG sub_fact(int n)
{
        return n < 2 ? 1 - n : (sub_fact(n - 1) + sub_fact(n - 2)) * (n - 1);
}

int main()
{
        int i;

        printf("Deranged Four:\n");
        gen_n(4, 1);

        printf("\nCompare list vs calc:\n");
        for (i = 0; i < 10; i++)
                printf("%d:\t%llu\t%llu\n", i, gen_n(i, 0), sub_fact(i));

        printf("\nfurther calc:\n");
        for (i = 10; i <= 20; i++)
                printf("%d: %llu\n", i, sub_fact(i));

        return 0;
}
Task: Permutations_Derangements



C#: using System;
class Derangements
{
  static int n = 4;
  static int [] buf = new int [n];
  static bool [] used = new bool [n];

  static void Main()
  {
    for (int i = 0; i < n; i++) used [i] = false;
    rec(0);
  }

  static void rec(int ind)
  {
    for (int i = 0; i < n; i++)
    {
      if (!used [i] && i != ind)
      {
        used [i] = true;
        buf [ind] = i;
	if (ind + 1 < n) rec(ind + 1);
        else Console.WriteLine(string.Join(",", buf));
	used [i] = false;
      }
    }
  }
}
Task: Permutations_Derangements





Java: import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Derangement {

    public static void main(String[] args) {
        System.out.println("derangements for n = 4\n");
        for (Object d  : (ArrayList)(derangements(4, false)[0])) {
            System.out.println(Arrays.toString((int[])d));
        }
        
        System.out.println("\ntable of n vs counted vs calculated derangements\n");
        for (int i = 0; i < 10; i++) {
            int d = ((Integer)derangements(i, true)[1]).intValue();
            System.out.printf("%d  %-7d %-7d\n", i, d, subfact(i));
        }
        
        System.out.printf ("\n!20 = %20d\n", subfact(20L));
    }

    static Object[] derangements(int n, boolean countOnly) {
        int[] seq = iota(n);
        int[] ori = Arrays.copyOf(seq, n);
        long tot = fact(n);

        List<int[]> all = new ArrayList<int[]>();
        int cnt = n == 0 ? 1 : 0;

        while (--tot > 0) {
            int j = n - 2;
            while (seq[j] > seq[j + 1]) {
                j--;
            }
            int k = n - 1;
            while (seq[j] > seq[k]) {
                k--;
            }
            swap(seq, k, j);

            int r = n - 1;
            int s = j + 1;
            while (r > s) {
                swap(seq, s, r);
                r--;
                s++;
            }

            j = 0;
            while (j < n && seq[j] != ori[j]) {
                j++;
            }
            if (j == n) {
                if (countOnly) {
                    cnt++;
                } else {
                    all.add(Arrays.copyOf(seq, n));
                }
            }
        }
        return new Object[]{all, cnt};
    }

    static long fact(long n) {
        long result = 1;
        for (long i = 2; i <= n; i++) {
            result *= i;
        }
        return result;
    }

    static long subfact(long n) {
        if (0 <= n && n <= 2) {
            return n != 1 ? 1 : 0;
        }
        return (n - 1) * (subfact(n - 1) + subfact(n - 2));
    }

    static void swap(int[] arr, int lhs, int rhs) {
        int tmp = arr[lhs];
        arr[lhs] = arr[rhs];
        arr[rhs] = tmp;
    }

    static int[] iota(int n) {
        if (n < 0) {
            throw new IllegalArgumentException("iota cannot accept < 0");
        }
        int[] r = new int[n];
        for (int i = 0; i < n; i++) {
            r[i] = i;
        }
        return r;
    }
}
Task: Permutations_Derangements







Python: from itertools import permutations
import math


def derangements(n):
    'All deranged permutations of the integers 0..n-1 inclusive'
    return ( perm for perm in permutations(range(n))
             if all(indx != p for indx, p in enumerate(perm)) )

def subfact(n):
    if n == 2 or n == 0:
        return 1
    elif n == 1:
        return 0
    elif  1 <= n <=18:
        return round(math.factorial(n) / math.e)
    elif n.imag == 0 and n.real == int(n.real) and n > 0:
        return (n-1) * ( subfact(n - 1) + subfact(n - 2) )
    else:
        raise ValueError()

def _iterlen(iter):
    'length of an iterator without taking much memory'
    l = 0
    for x in iter:
        l += 1
    return l

if __name__ == '__main__':
    n = 4
    print("Derangements of %s" % (tuple(range(n)),))
    for d in derangements(n):
        print("  %s" % (d,))

    print("\nTable of n vs counted vs calculated derangements")
    for n in range(10):
        print("%2i %-5i %-5i" %
              (n, _iterlen(derangements(n)), subfact(n)))

    n = 20
    print("\n!%i = %i" % (n, subfact(n)))
Task: Permutations_Derangements




Go: package main

import (
    "fmt"
    "math/big"
)


func dList(n int) (r [][]int) {
    a := make([]int, n)
    for i := range a {
        a[i] = i
    }
    
    var recurse func(last int)
    recurse = func(last int) {
        if last == 0 {
            
            
            for j, v := range a {
                if j == v {
                    return 
                }
            }
            
            r = append(r, append([]int{}, a...))
            return
        }
        for i := last; i >= 0; i-- {
            a[i], a[last] = a[last], a[i]
            recurse(last - 1)
            a[i], a[last] = a[last], a[i]
        }
    }
    recurse(n - 1)
    return
}


func subFact(n int) *big.Int {
    if n == 0 {
        return big.NewInt(1)
    } else if n == 1 {
        return big.NewInt(0)
    }
    d0 := big.NewInt(1)
    d1 := big.NewInt(0)
    f := new(big.Int)
    for i, n64 := int64(1), int64(n); i < n64; i++ {
        d0, d1 = d1, d0.Mul(f.SetInt64(i), d0.Add(d0, d1))
    }
    return d1
}

func main() {
    
    fmt.Println("Derangements of 4 integers")
    for _, d := range dList(4) {
        fmt.Println(d)
    }

    
    fmt.Println("\nNumber of derangements")
    fmt.Println("N  Counted  Calculated")
    for n := 0; n <= 9; n++ {
        fmt.Printf("%d %8d %11s\n", n, len(dList(n)), subFact(n).String())
    }

    
    fmt.Println("\n!20 =", subFact(20))
}
Task: String interpolation (included)



C#: class Program
{
    static void Main()
    {
        string extra = "little";
        string formatted = $"Mary had a {extra} lamb.";
        System.Console.WriteLine(formatted);
    }
}









Ada: with Ada.Strings.Fixed, Ada.Text_IO;
use  Ada.Strings, Ada.Text_IO;
procedure String_Replace is
   Original : constant String := "Mary had a @__@ lamb.";
   Tbr : constant String := "@__@";
   New_Str : constant String := "little";
   Index : Natural := Fixed.Index (Original, Tbr);
begin
   Put_Line (Fixed.Replace_Slice (
     Original, Index, Index + Tbr'Length - 1, New_Str));
end String_Replace;
Task: String interpolation (included)

C: #include <stdio.h>

int main() {
  const char *extra = "little";
  printf("Mary had a %s lamb.\n", extra);
  return 0;
}











Ada: with Ada.Strings.Fixed, Ada.Text_IO;
use  Ada.Strings, Ada.Text_IO;
procedure String_Replace is
   Original : constant String := "Mary had a @__@ lamb.";
   Tbr : constant String := "@__@";
   New_Str : constant String := "little";
   Index : Natural := Fixed.Index (Original, Tbr);
begin
   Put_Line (Fixed.Replace_Slice (
     Original, Index, Index + Tbr'Length - 1, New_Str));
end String_Replace;
Task: String interpolation (included)


C++: #include <string>
#include <iostream>

int main( ) {
   std::string original( "Mary had a X lamb." ) , toBeReplaced( "X" ) ,
      replacement ( "little" ) ;
   std::string newString = original.replace( original.find( "X" ) ,
	 toBeReplaced.length( ) , replacement ) ;
   std::cout << "String after replacement: " << newString << " \n" ;
   return 0 ;
}










Ada: with Ada.Strings.Fixed, Ada.Text_IO;
use  Ada.Strings, Ada.Text_IO;
procedure String_Replace is
   Original : constant String := "Mary had a @__@ lamb.";
   Tbr : constant String := "@__@";
   New_Str : constant String := "little";
   Index : Natural := Fixed.Index (Original, Tbr);
begin
   Put_Line (Fixed.Replace_Slice (
     Original, Index, Index + Tbr'Length - 1, New_Str));
end String_Replace;
Task: String interpolation (included)




Go: package main

import (
    "fmt"
)

func main() {
    str := "Mary had a %s lamb"
    txt := "little"
    out := fmt.Sprintf(str, txt)
    fmt.Println(out)
}








Ada: with Ada.Strings.Fixed, Ada.Text_IO;
use  Ada.Strings, Ada.Text_IO;
procedure String_Replace is
   Original : constant String := "Mary had a @__@ lamb.";
   Tbr : constant String := "@__@";
   New_Str : constant String := "little";
   Index : Natural := Fixed.Index (Original, Tbr);
begin
   Put_Line (Fixed.Replace_Slice (
     Original, Index, Index + Tbr'Length - 1, New_Str));
end String_Replace;
Task: String interpolation (included)





Java: String original = "Mary had a X lamb";
String little = "little";
String replaced = original.replace("X", little); 
System.out.println(replaced);

System.out.printf("Mary had a %s lamb.", little);

String formatted = String.format("Mary had a %s lamb.", little);
System.out.println(formatted);







Ada: with Ada.Strings.Fixed, Ada.Text_IO;
use  Ada.Strings, Ada.Text_IO;
procedure String_Replace is
   Original : constant String := "Mary had a @__@ lamb.";
   Tbr : constant String := "@__@";
   New_Str : constant String := "little";
   Index : Natural := Fixed.Index (Original, Tbr);
begin
   Put_Line (Fixed.Replace_Slice (
     Original, Index, Index + Tbr'Length - 1, New_Str));
end String_Replace;
Task: String interpolation (included)







Python: >>> original = 'Mary had a %s lamb.'
>>> extra = 'little'
>>> original % extra
'Mary had a little lamb.'





Ada: with Ada.Strings.Fixed, Ada.Text_IO;
use  Ada.Strings, Ada.Text_IO;
procedure String_Replace is
   Original : constant String := "Mary had a @__@ lamb.";
   Tbr : constant String := "@__@";
   New_Str : constant String := "little";
   Index : Natural := Fixed.Index (Original, Tbr);
begin
   Put_Line (Fixed.Replace_Slice (
     Original, Index, Index + Tbr'Length - 1, New_Str));
end String_Replace;
Task: String interpolation (included)








VB: Dim name as String = "J. Doe"
Dim balance as Double = 123.45
Dim prompt as String = String.Format("Hello {0}, your balance is {1}.", name, balance)
Console.WriteLine(prompt)




Ada: with Ada.Strings.Fixed, Ada.Text_IO;
use  Ada.Strings, Ada.Text_IO;
procedure String_Replace is
   Original : constant String := "Mary had a @__@ lamb.";
   Tbr : constant String := "@__@";
   New_Str : constant String := "little";
   Index : Natural := Fixed.Index (Original, Tbr);
begin
   Put_Line (Fixed.Replace_Slice (
     Original, Index, Index + Tbr'Length - 1, New_Str));
end String_Replace;
Task: String interpolation (included)

C: #include <stdio.h>

int main() {
  const char *extra = "little";
  printf("Mary had a %s lamb.\n", extra);
  return 0;
}
Task: String interpolation (included)



C#: class Program
{
    static void Main()
    {
        string extra = "little";
        string formatted = $"Mary had a {extra} lamb.";
        System.Console.WriteLine(formatted);
    }
}
Task: String interpolation (included)


C++: #include <string>
#include <iostream>

int main( ) {
   std::string original( "Mary had a X lamb." ) , toBeReplaced( "X" ) ,
      replacement ( "little" ) ;
   std::string newString = original.replace( original.find( "X" ) ,
	 toBeReplaced.length( ) , replacement ) ;
   std::cout << "String after replacement: " << newString << " \n" ;
   return 0 ;
}
Task: String interpolation (included)





Java: String original = "Mary had a X lamb";
String little = "little";
String replaced = original.replace("X", little); 
System.out.println(replaced);

System.out.printf("Mary had a %s lamb.", little);

String formatted = String.format("Mary had a %s lamb.", little);
System.out.println(formatted);
Task: String interpolation (included)







Python: >>> original = 'Mary had a %s lamb.'
>>> extra = 'little'
>>> original % extra
'Mary had a little lamb.'
Task: String interpolation (included)








VB: Dim name as String = "J. Doe"
Dim balance as Double = 123.45
Dim prompt as String = String.Format("Hello {0}, your balance is {1}.", name, balance)
Console.WriteLine(prompt)
Task: String interpolation (included)




Go: package main

import (
    "fmt"
)

func main() {
    str := "Mary had a %s lamb"
    txt := "little"
    out := fmt.Sprintf(str, txt)
    fmt.Println(out)
}
Task: String interpolation (included)



C#: class Program
{
    static void Main()
    {
        string extra = "little";
        string formatted = $"Mary had a {extra} lamb.";
        System.Console.WriteLine(formatted);
    }
}








Fortran: program interpolate

  write (*,*) trim(inter("Mary had a X lamb.","X","little"))

contains

  elemental function inter(string,place,ins) result(new)
    character(len=*), intent(in)                          :: string,place,ins
    character(len=len(string)+max(0,len(ins)-len(place))) :: new
    integer                                               :: idx
    idx = index(string,place)
    if ( idx == 0 ) then
      new = string
    else
      new = string(1:idx-1)//ins//string(idx+len(place):len(string))
    end if
  end function inter
  
end program interpolate
Task: String interpolation (included)


C++: #include <string>
#include <iostream>

int main( ) {
   std::string original( "Mary had a X lamb." ) , toBeReplaced( "X" ) ,
      replacement ( "little" ) ;
   std::string newString = original.replace( original.find( "X" ) ,
	 toBeReplaced.length( ) , replacement ) ;
   std::cout << "String after replacement: " << newString << " \n" ;
   return 0 ;
}









Fortran: program interpolate

  write (*,*) trim(inter("Mary had a X lamb.","X","little"))

contains

  elemental function inter(string,place,ins) result(new)
    character(len=*), intent(in)                          :: string,place,ins
    character(len=len(string)+max(0,len(ins)-len(place))) :: new
    integer                                               :: idx
    idx = index(string,place)
    if ( idx == 0 ) then
      new = string
    else
      new = string(1:idx-1)//ins//string(idx+len(place):len(string))
    end if
  end function inter
  
end program interpolate
Task: String interpolation (included)

C: #include <stdio.h>

int main() {
  const char *extra = "little";
  printf("Mary had a %s lamb.\n", extra);
  return 0;
}










Fortran: program interpolate

  write (*,*) trim(inter("Mary had a X lamb.","X","little"))

contains

  elemental function inter(string,place,ins) result(new)
    character(len=*), intent(in)                          :: string,place,ins
    character(len=len(string)+max(0,len(ins)-len(place))) :: new
    integer                                               :: idx
    idx = index(string,place)
    if ( idx == 0 ) then
      new = string
    else
      new = string(1:idx-1)//ins//string(idx+len(place):len(string))
    end if
  end function inter
  
end program interpolate
Task: String interpolation (included)




Go: package main

import (
    "fmt"
)

func main() {
    str := "Mary had a %s lamb"
    txt := "little"
    out := fmt.Sprintf(str, txt)
    fmt.Println(out)
}







Fortran: program interpolate

  write (*,*) trim(inter("Mary had a X lamb.","X","little"))

contains

  elemental function inter(string,place,ins) result(new)
    character(len=*), intent(in)                          :: string,place,ins
    character(len=len(string)+max(0,len(ins)-len(place))) :: new
    integer                                               :: idx
    idx = index(string,place)
    if ( idx == 0 ) then
      new = string
    else
      new = string(1:idx-1)//ins//string(idx+len(place):len(string))
    end if
  end function inter
  
end program interpolate
Task: String interpolation (included)





Java: String original = "Mary had a X lamb";
String little = "little";
String replaced = original.replace("X", little); 
System.out.println(replaced);

System.out.printf("Mary had a %s lamb.", little);

String formatted = String.format("Mary had a %s lamb.", little);
System.out.println(formatted);






Fortran: program interpolate

  write (*,*) trim(inter("Mary had a X lamb.","X","little"))

contains

  elemental function inter(string,place,ins) result(new)
    character(len=*), intent(in)                          :: string,place,ins
    character(len=len(string)+max(0,len(ins)-len(place))) :: new
    integer                                               :: idx
    idx = index(string,place)
    if ( idx == 0 ) then
      new = string
    else
      new = string(1:idx-1)//ins//string(idx+len(place):len(string))
    end if
  end function inter
  
end program interpolate
Task: String interpolation (included)







Python: >>> original = 'Mary had a %s lamb.'
>>> extra = 'little'
>>> original % extra
'Mary had a little lamb.'




Fortran: program interpolate

  write (*,*) trim(inter("Mary had a X lamb.","X","little"))

contains

  elemental function inter(string,place,ins) result(new)
    character(len=*), intent(in)                          :: string,place,ins
    character(len=len(string)+max(0,len(ins)-len(place))) :: new
    integer                                               :: idx
    idx = index(string,place)
    if ( idx == 0 ) then
      new = string
    else
      new = string(1:idx-1)//ins//string(idx+len(place):len(string))
    end if
  end function inter
  
end program interpolate
Task: String interpolation (included)








VB: Dim name as String = "J. Doe"
Dim balance as Double = 123.45
Dim prompt as String = String.Format("Hello {0}, your balance is {1}.", name, balance)
Console.WriteLine(prompt)



Fortran: program interpolate

  write (*,*) trim(inter("Mary had a X lamb.","X","little"))

contains

  elemental function inter(string,place,ins) result(new)
    character(len=*), intent(in)                          :: string,place,ins
    character(len=len(string)+max(0,len(ins)-len(place))) :: new
    integer                                               :: idx
    idx = index(string,place)
    if ( idx == 0 ) then
      new = string
    else
      new = string(1:idx-1)//ins//string(idx+len(place):len(string))
    end if
  end function inter
  
end program interpolate
Task: String interpolation (included)






PHP: <?php
$extra = 'little';
echo "Mary had a $extra lamb.\n";
printf("Mary had a %s lamb.\n", $extra);
?>





Fortran: program interpolate

  write (*,*) trim(inter("Mary had a X lamb.","X","little"))

contains

  elemental function inter(string,place,ins) result(new)
    character(len=*), intent(in)                          :: string,place,ins
    character(len=len(string)+max(0,len(ins)-len(place))) :: new
    integer                                               :: idx
    idx = index(string,place)
    if ( idx == 0 ) then
      new = string
    else
      new = string(1:idx-1)//ins//string(idx+len(place):len(string))
    end if
  end function inter
  
end program interpolate
Task: String interpolation (included)

C: #include <stdio.h>

int main() {
  const char *extra = "little";
  printf("Mary had a %s lamb.\n", extra);
  return 0;
}









COBOL:        IDENTIFICATION DIVISION.
       PROGRAM-ID. interpolation-included.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  extra PIC X(6) VALUE "little".

       PROCEDURE DIVISION.
           DISPLAY FUNCTION SUBSTITUTE("Mary had a X lamb.", "X", extra)

           GOBACK
           .
Task: String interpolation (included)



C#: class Program
{
    static void Main()
    {
        string extra = "little";
        string formatted = $"Mary had a {extra} lamb.";
        System.Console.WriteLine(formatted);
    }
}







COBOL:        IDENTIFICATION DIVISION.
       PROGRAM-ID. interpolation-included.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  extra PIC X(6) VALUE "little".

       PROCEDURE DIVISION.
           DISPLAY FUNCTION SUBSTITUTE("Mary had a X lamb.", "X", extra)

           GOBACK
           .