WeixiangYan/CodeTransOcean huggingface dataset:
Task: Validate International Securities Identification Number



C#: using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace ValidateIsin
{
    public static class IsinValidator
    {
        public static bool IsValidIsin(string isin) => 
            IsinRegex.IsMatch(isin) && LuhnTest(Digitize(isin));

        private static readonly Regex IsinRegex = 
            new Regex("^[A-Z]{2}[A-Z0-9]{9}\\d$", RegexOptions.Compiled);

        private static string Digitize(string isin) =>
            string.Join("", isin.Select(c => $"{DigitValue(c)}"));

        private static bool LuhnTest(string number) => 
            number.Reverse().Select(DigitValue).Select(Summand).Sum() % 10 == 0;

        private static int Summand(int digit, int i) =>
            digit + (i % 2) * (digit - digit / 5 * 9);

        private static int DigitValue(char c) =>
            c >= '0' && c <= '9' 
                ? c - '0' 
                : c - 'A' + 10;
   }
	
   public class Program
   {
        public static void Main() 
        {
            string[] isins = 
            {
                "US0378331005",
                "US0373831005",
                "U50378331005",
                "US03378331005",
                "AU0000XVGZA3",
                "AU0000VXGZA3",
                "FR0000988040"
            };

            foreach (string isin in isins) {
                string validOrNot = IsinValidator.IsValidIsin(isin) ? "valid" : "not valid";
                Console.WriteLine($"{isin} is {validOrNot}");
            }
        }
    }
}








Fortran: program isin
    use ctype
    implicit none
    character(20) :: test(7) = ["US0378331005        ", &
                                "US0373831005        ", &
                                "U50378331005        ", &
                                "US03378331005       ", &
                                "AU0000XVGZA3        ", &
                                "AU0000VXGZA3        ", &
                                "FR0000988040        "]
    print *, check_isin(test)
contains
    elemental logical function check_isin(a)
        character(*), intent(in) :: a
        integer :: s(24)
        integer :: i, j, k, n, v

        check_isin = .false.

        n = len_trim(a)
        if (n /= 12) return
        
        
        j = 0
        do i = 1, n
            k = iachar(a(i:i))
            if (k >= 48 .and. k <= 57) then
                if (i < 3) return
                k = k - 48
                j = j + 1
                s(j) = k
            else if (k >= 65 .and. k <= 90) then
                if (i == 12) return
                k = k - 65 + 10
                j = j + 1
                s(j) = k / 10
                j = j + 1
                s(j) = mod(k, 10)
            else
                return
            end if
        end do

        
        v = 0
        do i = j - 1, 1, -2
            k = 2 * s(i)
            if (k > 9) k = k - 9
            v = v + k
        end do
        do i = j, 1, -2
            v = v + s(i)
        end do
        
        check_isin = 0 == mod(v, 10)
    end function
end program
Task: Input_Output for pairs of numbers



C#: using System;
using static System.Linq.Enumerable;

public class Program
{
    static void Main(string[] args)
    {
	int count = Convert.ToInt32(Console.ReadLine());
	for (int line = 0; line < count; line++) {
            Console.WriteLine(Console.ReadLine().Split(' ').Sum(i => Convert.ToInt32(i)));
	}
    }
}








Fortran: program i_o_pairs
  implicit none

  integer :: npairs
  integer :: i
  integer, allocatable :: pairs(:,:)

  read(*,*) npairs
  allocate(pairs(npairs,2))
 
  do i = 1, npairs
    read(*,*) pairs(i,:)
  end do
  write(*, "(i0)") sum(pairs, 2)

end program
Task: Kahan summation



C#: using System;

namespace KahanSummation {
    class Program {
        static float KahanSum(params float[] fa) {
            float sum = 0.0f;
            float c = 0.0f;
            foreach (float f in fa) {
                float y = f - c;
                float t = sum + y;
                c = (t - sum) - y;
                sum = t;
            }

            return sum;
        }

        static float Epsilon() {
            float eps = 1.0f;
            while (1.0f + eps != 1.0f) eps /= 2.0f;
            return eps;
        }

        static void Main(string[] args) {
            float a = 1.0f;
            float b = Epsilon();
            float c = -b;
            Console.WriteLine("Epsilon      = {0}", b);
            Console.WriteLine("(a + b) + c  = {0}", (a + b) + c);
            Console.WriteLine("Kahan sum    = {0}", KahanSum(a, b, c));
        }
    }
}








Fortran:       FUNCTION SUMC(A,N)
COMPENSATED SUMMATION. C WILL NOT STAY ZERO, DESPITE MATHEMATICS.
       DIMENSION A(12345)
        S = 0.0
        C = 0.0
        DO 1 I = 1,N
          Y = A(I) - C
          T = S + Y
          C = (T - S) - Y
          S = T
    1   CONTINUE
        SUMC = S
      END
      DIMENSION A(3)
      A(1) = 10000.0
      A(2) = 3.14159
      A(3) = 2.71828
      TYPE 1, A(1) + A(2) + A(3)
      TYPE 1, SUMC(A,3)
    1 FORMAT (6HSUM = ,F12.1)
      END
Task: Two identical strings



C#: using System; using static System.Console;
class Program { static void Main() { int c = 0, lmt = 1000;
    for (int n = 1, p = 2, k; n <= lmt; n++)
      if ((k = n + n * (p += n >= p ? p : 0)) > lmt) break;
      else Console.Write("{0,3} ({1,-10})  {2}", k,
          Convert.ToString(k, 2), ++c % 5 == 0 ? "\n" : "");
    Write("\nFound {0} numbers whose base 2 representation is the " +
      "concatenation of two identical binary strings.", c); } }








Fortran:       program IdentStr
          implicit none
          integer n, concat, bits
          
          n = 1
  100     if (concat(n) .lt. 1000) then
              write (*,'(I3,2X,I11)') concat(n), bits(concat(n))
              n = n + 1
              goto 100
          end if
          stop
      end

C     Concatenate binary representation of number with itself      
      integer function concat(num)
          integer num, sl, sr
          sl = num
          sr = num
  100     if (sr .gt. 0) then
              sl = sl * 2
              sr = sr / 2
              goto 100
          end if
          concat = num + sl
      end

C     Calculate binary representation of number
      integer function bits(num)
          integer num, n, bx
          n = num
          bits = 0
          bx = 1
  100     if (n .gt. 0) then
              bits = bits + bx * mod(n,2)
              bx = bx * 10
              n = n / 2
              goto 100
          end if
      end
Task: Flow-control structures



C#: int GetNumber() {
    return 5;
}








Fortran:       ...
      ASSIGN 1101 to WHENCE   
      GO TO 1000              
 1101 CONTINUE                
      ... 
      ASSIGN 1102 to WHENCE   
      GO TO 1000              
 1102 CONTINUE                
      ...
Common code, far away.
 1000 do something            
      GO TO WHENCE
Task: Boolean values



C#: bool? value = null








Fortran:       TYPE MIXED
       LOGICAL*1 LIVE
       REAL*8    VALUE
      END TYPE MIXED
      TYPE(MIXED) STUFF(100)
Task: Address of a variable



C#: int i = 5;
int* p = &i;








Fortran: program test_loc
  implicit none

  integer :: i
  real    :: r

  i = loc(r)
  print *, i
end program
Task: Loops_Infinite



C#: while (true)
{
    Console.WriteLine("SPAM");
}








Fortran:       
   10 WRITE(*,*) 'SPAM'
      GO TO 10
      END
Task: CSV to HTML translation


C++: #include <string>
#include <boost/regex.hpp>
#include <iostream>

std::string csvToHTML( const std::string & ) ;

int main( ) {
   std::string text = "Character,Speech\n" 
                            "The multitude,The messiah! Show us the messiah!\n" 
			    "Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n" 
	                    "The multitude,Who are you?\n" 
		            "Brians mother,I'm his mother; that's who!\n" 
		            "The multitude,Behold his mother! Behold his mother!\n" ;
  std::cout << csvToHTML( text ) ;
  return 0 ;
}

std::string csvToHTML( const std::string & csvtext ) {
   
   std::string regexes[ 5 ] = { "<" , ">" , "^(.+?)\\b" , "," , "\n" } ;
   const char* replacements [ 5 ] = { "&lt;" , "&gt;" , "    <TR><TD>$1" , "</TD><TD>", "</TD></TR>\n"  } ;  
   boost::regex e1( regexes[ 0 ] ) ; 
   std::string tabletext = boost::regex_replace( csvtext , e1 ,
     replacements[ 0 ] , boost::match_default | boost::format_all ) ;
   for ( int i = 1 ; i < 5 ; i++ ) {
      e1.assign( regexes[ i ] ) ;
      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;
   }
   tabletext = std::string( "<TABLE>\n" ) + tabletext ;
   tabletext.append( "</TABLE>\n" ) ;
   return tabletext ;
}
Task: Gray code


C++: #include <bitset>
#include <iostream>
#include <string>
#include <assert.h>

uint32_t gray_encode(uint32_t b)
{
    return b ^ (b >> 1);
}

uint32_t gray_decode(uint32_t g)
{
    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)
    {
        if (g & bit) g ^= bit >> 1;
    }
    return g;
}

std::string to_binary(int value) 
{
    const std::bitset<32> bs(value);
    const std::string str(bs.to_string());
    const size_t pos(str.find('1'));
    return pos == std::string::npos ? "0" : str.substr(pos);
}

int main()
{
    std::cout << "Number\tBinary\tGray\tDecoded\n";
    for (uint32_t n = 0; n < 32; ++n)
    {
        uint32_t g = gray_encode(n);
        assert(gray_decode(g) == n);

        std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n";
    }
}
Task: Return multiple values


C++: #include <algorithm>
#include <array>
#include <cstdint>
#include <iostream>
#include <tuple>

std::tuple<int, int> minmax(const int * numbers, const std::size_t num) {
   const auto maximum = std::max_element(numbers, numbers + num);
   const auto minimum = std::min_element(numbers, numbers + num);
   return std::make_tuple(*minimum, *maximum) ;
}

int main( ) {
   const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}};
   int min{};
   int max{};
   std::tie(min, max) = minmax(numbers.data(), numbers.size());
   std::cout << "The smallest number is " << min << ", the biggest " << max << "!\n" ;
}
Task: Fractran


C++: #include <iostream>
#include <sstream>
#include <iterator>
#include <vector>
#include <cmath>

using namespace std;

class fractran
{
public:
    void run( std::string p, int s, int l  )
    {
        start = s; limit = l;
        istringstream iss( p ); vector<string> tmp;
        copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) );

        string item; vector< pair<float, float> > v;
	pair<float, float> a;
	for( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ )
	{
	    string::size_type pos = ( *i ).find( '/', 0 );
	    if( pos != std::string::npos )
	    {
		a = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) );
		v.push_back( a );
	    }
	}
		
	exec( &v );
    }

private:
    void exec( vector< pair<float, float> >* v )
    {
	int cnt = 0;
	while( cnt < limit )
	{
	    cout << cnt << " : " << start << "\n";
	    cnt++;
	    vector< pair<float, float> >::iterator it = v->begin();
	    bool found = false; float r;
	    while( it != v->end() )
	    {
		r  = start * ( ( *it ).first / ( *it ).second );
		if( r == floor( r ) )
		{
		    found = true;
		    break;
		}
		++it;
	    }

	    if( found ) start = ( int )r;
	    else break;
	}
    }
    int start, limit;
};
int main( int argc, char* argv[] )
{
    fractran f; f.run( "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2, 15 );
    cin.get();
    return 0;
}
Task: LZW compression


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




template <typename Iterator>
Iterator compress(const std::string &uncompressed, Iterator result) {
  
  int dictSize = 256;
  std::map<std::string,int> dictionary;
  for (int i = 0; i < 256; i++)
    dictionary[std::string(1, i)] = i;
  
  std::string w;
  for (std::string::const_iterator it = uncompressed.begin();
       it != uncompressed.end(); ++it) {
    char c = *it;
    std::string wc = w + c;
    if (dictionary.count(wc))
      w = wc;
    else {
      *result++ = dictionary[w];
      
      dictionary[wc] = dictSize++;
      w = std::string(1, c);
    }
  }
  
  
  if (!w.empty())
    *result++ = dictionary[w];
  return result;
}



template <typename Iterator>
std::string decompress(Iterator begin, Iterator end) {
  
  int dictSize = 256;
  std::map<int,std::string> dictionary;
  for (int i = 0; i < 256; i++)
    dictionary[i] = std::string(1, i);
  
  std::string w(1, *begin++);
  std::string result = w;
  std::string entry;
  for ( ; begin != end; begin++) {
    int k = *begin;
    if (dictionary.count(k))
      entry = dictionary[k];
    else if (k == dictSize)
      entry = w + w[0];
    else
      throw "Bad compressed k";
    
    result += entry;
    
    
    dictionary[dictSize++] = w + entry[0];
    
    w = entry;
  }
  return result;
}

#include <iostream>
#include <iterator>
#include <vector>

int main() {
  std::vector<int> compressed;
  compress("TOBEORNOTTOBEORTOBEORNOT", std::back_inserter(compressed));
  copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, ", "));
  std::cout << std::endl;
  std::string decompressed = decompress(compressed.begin(), compressed.end());
  std::cout << decompressed << std::endl;
  
  return 0;
}
Task: Text processing_1


C++: #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iomanip>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>

using std::cout;
using std::endl;
const int NumFlags = 24;

int main()
{
    std::fstream file("readings.txt");

    int badCount = 0;
    std::string badDate;
    int badCountMax = 0;
    while(true)
    {
        std::string line;
        getline(file, line);
        if(!file.good())
            break;

        std::vector<std::string> tokens;
        boost::algorithm::split(tokens, line, boost::is_space());

        if(tokens.size() != NumFlags * 2 + 1)
        {
            cout << "Bad input file." << endl;
            return 0;
        }

        double total = 0.0;
        int accepted = 0;
        for(size_t i = 1; i < tokens.size(); i += 2)
        {
            double val = boost::lexical_cast<double>(tokens[i]);
            int flag = boost::lexical_cast<int>(tokens[i+1]);
            if(flag > 0)
            {
                total += val;
                ++accepted;
                badCount = 0;
            }
            else
            {
                ++badCount;
                if(badCount > badCountMax)
                {
                    badCountMax = badCount;
                    badDate = tokens[0];
                }
            }
        }

        cout << tokens[0];
        cout << "  Reject: " << std::setw(2) << (NumFlags - accepted);
        cout << "  Accept: " << std::setw(2) << accepted;
        cout << "  Average: " << std::setprecision(5) << total / accepted << endl;
    }
    cout << endl;
    cout << "Maximum number of consecutive bad readings is " << badCountMax << endl;
    cout << "Ends on date " << badDate << endl;
}
Task: Entropy_Narcissist


C++: #include <iostream>
#include <fstream>
#include <cmath>

using namespace std;

string readFile (string path) {
    string contents;
    string line;
    ifstream inFile(path);
    while (getline (inFile, line)) {
        contents.append(line);
        contents.append("\n");
    }
    inFile.close();
    return contents;
}

double entropy (string X) {
    const int MAXCHAR = 127;
    int N = X.length();
    int count[MAXCHAR];
    double count_i;
    char ch;
    double sum = 0.0;
    for (int i = 0; i < MAXCHAR; i++) count[i] = 0;
    for (int pos = 0; pos < N; pos++) {
        ch = X[pos];
        count[(int)ch]++;
    }
    for (int n_i = 0; n_i < MAXCHAR; n_i++) {
        count_i = count[n_i];
        if (count_i > 0) sum -= count_i / N * log2(count_i / N);
    }
    return sum;
}

int main () {
    cout<<entropy(readFile("entropy.cpp"));
    return 0;
}
Task: MAC vendor lookup






PHP: <?php
$apiRoot = "https://api.macvendors.com";
$macList = array("88:53:2E:67:07:BE", "D4:F4:6F:C9:EF:8D", 
		 "FC:FB:FB:01:FA:21", "4c:72:b9:56:fe:bc", "00-14-22-01-23-45");

$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
foreach ($macList as $burger) {
  curl_setopt($curl, CURLOPT_URL, "$apiRoot/$burger");
  echo(curl_exec($curl));
  echo("\n");
  sleep(2);
}
curl_close($curl);
?>
Task: Kahan summation






PHP: <?php





function kahansum($input) {
    $sum = $c = 0;
    foreach($input as $item) {
        $y = $item + $c;
        $t = $sum + $y;
        $c = ($t - $sum) - $y;
        $sum = $t;
    }
    return $sum;
}


$input = array(10000.0, 3.14159, 2.71828);
list($a, $b, $c) = $input;


$sumabc = ($a + $b) + $c;
echo "Main task - Left to right summation: ";
echo sprintf("%6.1f", $sumabc).PHP_EOL;



echo "Main task - Kahan summation: ";
echo sprintf("%6.1f", kahansum($input)).PHP_EOL;


$epsilon = 1.0;
while ((1.0 + $epsilon) != 1.0) {
    $epsilon /= 2.0;
}
echo "Trying the subtask".PHP_EOL."epsilon: ";
echo $epsilon.PHP_EOL;


$a = 1.0;
$b = $epsilon;
$c = -$epsilon;

$input = array($a, $b, $c);

$sumabc = ($a + $b) + $c;
echo "Sub task - Left to right summation: ";
echo sprintf("%.1f", $sumabc).PHP_EOL;

echo "Sub task - Kahan summation: ";
echo sprintf("%.1f", kahansum($input)).PHP_EOL;

echo "Are the results the same?".PHP_EOL;
var_dump((($a + $b) + $c) === kahansum($input));

echo "Difference between the operations: ";
$diff = (($a + $b) + $c) - kahansum($input);
echo $diff.PHP_EOL;
Task: Text between






PHP: <?php
function text_between($string, $start, $end)
{

    $startIndex = strpos($string,$start);
    
    if ($start == "start")
    {
    	$startIndex = 0;
    } else {
    	if ($startIndex == 0)
    	{
    		return "Start text not found";
    	}
    }
    
    if ($end == "end")
    {
    	$endIndex=strlen($string);
    	$resultLength = $endIndex - $startIndex;
    } else {
	    $resultLength = strpos($string,$end,$startIndex) - $startIndex;
	}
    
    if ($start != "start")
    {
		$startIndex += strlen($start);
	}

    if ($resultLength <= 0)
    {
    	return "End text not found";
    }
    
    return substr($string,$startIndex,$resultLength);
}

$thisText=$_GET["thisText"];
$startDelimiter=$_GET["start"];
$endDelimiter=$_GET["end"];

$returnText = text_between($thisText, $startDelimiter, $endDelimiter);

print_r($returnText);
?>
Task: Calendar - for _REAL_ programmers






PHP: <?PHP
ECHO <<<REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT
       JANUARY               FEBRUARY               MARCH                 APRIL                  MAY                   JUNE
 MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO
        1  2  3  4  5                  1  2                  1  2      1  2  3  4  5  6            1  2  3  4                     1
  6  7  8  9 10 11 12   3  4  5  6  7  8  9   3  4  5  6  7  8  9   7  8  9 10 11 12 13   5  6  7  8  9 10 11   2  3  4  5  6  7  8
 13 14 15 16 17 18 19  10 11 12 13 14 15 16  10 11 12 13 14 15 16  14 15 16 17 18 19 20  12 13 14 15 16 17 18   9 10 11 12 13 14 15
 20 21 22 23 24 25 26  17 18 19 20 21 22 23  17 18 19 20 21 22 23  21 22 23 24 25 26 27  19 20 21 22 23 24 25  16 17 18 19 20 21 22
 27 28 29 30 31        24 25 26 27 28        24 25 26 27 28 29 30  28 29 30              26 27 28 29 30 31     23 24 25 26 27 28 29
                                             31                                                                30 

         JULY                 AUGUST               SEPTEMBER              OCTOBER              NOVEMBER              DECEMBER
 MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO
     1  2  3  4  5  6               1  2  3   1  2  3  4  5  6  7         1  2  3  4  5                  1  2   1  2  3  4  5  6  7
  7  8  9 10 11 12 13   4  5  6  7  8  9 10   8  9 10 11 12 13 14   6  7  8  9 10 11 12   3  4  5  6  7  8  9   8  9 10 11 12 13 14
 14 15 16 17 18 19 20  11 12 13 14 15 16 17  15 16 17 18 19 20 21  13 14 15 16 17 18 19  10 11 12 13 14 15 16  15 16 17 18 19 20 21
 21 22 23 24 25 26 27  18 19 20 21 22 23 24  22 23 24 25 26 27 28  20 21 22 23 24 25 26  17 18 19 20 21 22 23  22 23 24 25 26 27 28
 28 29 30 31           25 26 27 28 29 30 31  29 30                 27 28 29 30 31        24 25 26 27 28 29 30  29 30 31
REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT
                                                                                                             ; // MAGICAL SEMICOLON
Task: Call a foreign-language function






PHP: $ffi = FFI::cdef("char *_strdup(const char *strSource);", "msvcrt.dll");

$cstr = $ffi->_strdup("success");
$str = FFI::string($cstr);
echo $str;
FFI::free($cstr);
Task: Sorting algorithms_Patience sort






PHP: <?php
class PilesHeap extends SplMinHeap {
    public function compare($pile1, $pile2) {
        return parent::compare($pile1->top(), $pile2->top());
    }
}

function patience_sort(&$n) {
    $piles = array();

    foreach ($n as $x) {

        $low = 0; $high = count($piles)-1;
        while ($low <= $high) {
            $mid = (int)(($low + $high) / 2);
            if ($piles[$mid]->top() >= $x)
                $high = $mid - 1;
            else
                $low = $mid + 1;
        }
        $i = $low;
        if ($i == count($piles))
            $piles[] = new SplStack();
        $piles[$i]->push($x);
    }

    $heap = new PilesHeap();
    foreach ($piles as $pile)
        $heap->insert($pile);
    for ($c = 0; $c < count($n); $c++) {
        $smallPile = $heap->extract();
        $n[$c] = $smallPile->pop();
        if (!$smallPile->isEmpty())
        $heap->insert($smallPile);
    }
    assert($heap->isEmpty());
}

$a = array(4, 65, 2, -31, 0, 99, 83, 782, 1);
patience_sort($a);
print_r($a);
?>
Task: File extension is in extensions list






PHP: $allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];
$lc_allowed = array_map('strtolower', $allowed);

$tests = [
    ['MyData.a##',true],
    ['MyData.tar.Gz',true],
    ['MyData.gzip',false],
    ['MyData.7z.backup',false],
    ['MyData...',false],
    ['MyData',false],
    ['archive.tar.gz', true]
];

foreach ($tests as $test) {
    $ext = pathinfo($test[0], PATHINFO_EXTENSION);
    if (in_array(strtolower($ext), $lc_allowed)) {
        $result = 'true';
    } else {
        $result = 'false';
    }
    printf("%20s : %s \n", $test[0],$result);
}
Task: Knuth's algorithm S






PHP: <?php
function s_of_n_creator($n) {
    $sample = array();
    $i = 0;
    return function($item) use (&$sample, &$i, $n) {
        $i++;
        if ($i <= $n) {

            $sample[] = $item;
        } else if (rand(0, $i-1) < $n) {

            $sample[rand(0, $n-1)] = $item;
        }
        return $sample;
    };
}

$items = range(0, 9);

for ($trial = 0; $trial < 100000; $trial++) {
    $s_of_n = s_of_n_creator(3);
    foreach ($items as $item)
        $sample = $s_of_n($item);
    foreach ($sample as $s)
        $bin[$s]++;
}
print_r($bin);
?>
Task: Flow-control structures






PHP: <?php
goto a;
echo 'Foo';
 
a:
echo 'Bar';
?>