WeixiangYan/CodeTransOcean huggingface dataset:
Task: Bulls and cows


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

bool contains_duplicates(std::string s)
{
  std::sort(s.begin(), s.end());
  return std::adjacent_find(s.begin(), s.end()) != s.end();
}

void game()
{
  typedef std::string::size_type index;

  std::string symbols = "0123456789";
  unsigned int const selection_length = 4;

  std::random_shuffle(symbols.begin(), symbols.end());
  std::string selection = symbols.substr(0, selection_length);
  std::string guess;
  while (std::cout << "Your guess? ", std::getline(std::cin, guess))
  {
    if (guess.length() != selection_length
        || guess.find_first_not_of(symbols) != std::string::npos
        || contains_duplicates(guess))
    {
      std::cout << guess << " is not a valid guess!";
      continue;
    }

    unsigned int bulls = 0;
    unsigned int cows = 0;
    for (index i = 0; i != selection_length; ++i)
    {
      index pos = selection.find(guess[i]);
      if (pos == i)
        ++bulls;
      else if (pos != std::string::npos)
        ++cows;
    }
    std::cout << bulls << " bulls, " << cows << " cows.\n";
    if (bulls == selection_length)
    {
      std::cout << "Congratulations! You have won!\n";
      return;
    }
  }
  std::cerr << "Oops! Something went wrong with input, or you've entered end-of-file!\nExiting ...\n";
  std::exit(EXIT_FAILURE);
}

int main()
{
  std::cout << "Welcome to bulls and cows!\nDo you want to play? ";
  std::string answer;
  while (true)
  {
    while (true)
    {
      if (!std::getline(std::cin, answer))
      {
        std::cout << "I can't get an answer. Exiting.\n";
        return EXIT_FAILURE;
      }
      if (answer == "yes" || answer == "Yes" || answer == "y" || answer == "Y")
        break;
      if (answer == "no" || answer == "No" || answer == "n" || answer == "N")
      {
        std::cout << "Ok. Goodbye.\n";
        return EXIT_SUCCESS;
      }
      std::cout << "Please answer yes or no: ";
    }
    game(); 
    std::cout << "Another game? ";
  }
}





PHP: <?php
$size = 4;

$chosen = implode(array_rand(array_flip(range(1,9)), $size));

echo "I've chosen a number from $size unique digits from 1 to 9; you need
to input $size unique digits to guess my number\n";

for ($guesses = 1; ; $guesses++) {
    while (true) {
        echo "\nNext guess [$guesses]: ";
        $guess = rtrim(fgets(STDIN));
        if (!checkguess($guess))
            echo "$size digits, no repetition, no 0... retry\n";
        else
            break;
    }
    if ($guess == $chosen) {
        echo "You did it in $guesses attempts!\n";
        break;
    } else {
        $bulls = 0;
        $cows = 0;
        foreach (range(0, $size-1) as $i) {
            if ($guess[$i] == $chosen[$i])
                $bulls++;
            else if (strpos($chosen, $guess[$i]) !== FALSE)
                $cows++;
        }
        echo "$cows cows, $bulls bulls\n";
    }
}

function checkguess($g)
{
  global $size;
  return count(array_unique(str_split($g))) == $size &&
    preg_match("/^[1-9]{{$size}}$/", $g);
}
?>
Task: Sorting algorithms_Bubble sort


C++: #include <algorithm>
#include <iostream>
#include <iterator>

template <typename RandomAccessIterator>
void bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) {
  bool swapped = true;
  while (begin != end-- && swapped) {
    swapped = false;
    for (auto i = begin; i != end; ++i) {
      if (*(i + 1) < *i) {
        std::iter_swap(i, i + 1);
        swapped = true;
      }
    }
  }
}

int main() {
  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
  bubble_sort(std::begin(a), std::end(a));
  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
  std::cout << "\n";
}





PHP: function bubbleSort(array $array){
    foreach($array as $i => &$val){
        foreach($array as $k => &$val2){
            if($k <= $i)
                continue;
            if($val > $val2) {
                list($val, $val2) = [$val2, $val];
                break;
            }
        }
    }
    return $array;
}
Task: File input_output


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

using namespace std;

int main() {
    string line;
    ifstream input ( "input.txt" );
    ofstream output ("output.txt");
    
    if (output.is_open()) {
        if (input.is_open()){
            while (getline (input,line)) {
                output << line << endl;
            }
            input.close(); 
        }
        else {
            cout << "input.txt cannot be opened!\n";
        }
        output.close(); 
    }
    else {
        cout << "output.txt cannot be written to!\n";
    }
    return 0;
}





PHP: <?php

if (!$in = fopen('input.txt', 'r')) {
    die('Could not open input file.');
}

if (!$out = fopen('output.txt', 'w')) {
    die('Could not open output file.');
}

while (!feof($in)) {
    $data = fread($in, 512);
    fwrite($out, $data);
}

fclose($out);
fclose($in);
?>
Task: Arithmetic_Integer


C++: #include <iostream>

int main()
{
  int a, b;
  std::cin >> a >> b;
  std::cout << "a+b = " << a+b << "\n";
  std::cout << "a-b = " << a-b << "\n";
  std::cout << "a*b = " << a*b << "\n";
  std::cout << "a/b = " << a/b << ", remainder " << a%b << "\n";
  return 0;
}





PHP: <?php
$a = fgets(STDIN);
$b = fgets(STDIN);

echo
    "sum:                 ", $a + $b, "\n",
    "difference:          ", $a - $b, "\n",
    "product:             ", $a * $b, "\n",
    "truncating quotient: ", (int)($a / $b), "\n",
    "flooring quotient:   ", floor($a / $b), "\n",
    "remainder:           ", $a % $b, "\n",
    "power:               ", $a ** $b, "\n"; // PHP 5.6+ only
?>
Task: Matrix transposition


C++: #include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>

int main()
{
  using namespace boost::numeric::ublas;

  matrix<double> m(3,3);

  for(int i=0; i!=m.size1(); ++i)
    for(int j=0; j!=m.size2(); ++j)
      m(i,j)=3*i+j;

  std::cout << trans(m) << std::endl;
}





PHP: function transpose($m) {
  if (count($m) == 0) // special case: empty matrix
    return array();
  else if (count($m) == 1) // special case: row matrix
    return array_chunk($m[0], 1);

  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value
  return call_user_func_array('array_map', $m);
}
Task: Man or boy test


C++: #include <iostream>
#include <tr1/memory>
using std::tr1::shared_ptr;
using std::tr1::enable_shared_from_this;

struct Arg {
  virtual int run() = 0;
  virtual ~Arg() { };
};

int A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,
      shared_ptr<Arg>, shared_ptr<Arg>);

class B : public Arg, public enable_shared_from_this<B> {
private:
  int k;
  const shared_ptr<Arg> x1, x2, x3, x4;

public:
  B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,
    shared_ptr<Arg> _x4)
    : k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }
  int run() {
    return A(--k, shared_from_this(), x1, x2, x3, x4);
  }
};

class Const : public Arg {
private:
  const int x;
public:
  Const(int _x) : x(_x) { }
  int run () { return x; }
};

int A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,
      shared_ptr<Arg> x4, shared_ptr<Arg> x5) {
  if (k <= 0)
    return x4->run() + x5->run();
  else {
    shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));
    return b->run();
  }
}

int main() {
  std::cout << A(10, shared_ptr<Arg>(new Const(1)),
                 shared_ptr<Arg>(new Const(-1)),
                 shared_ptr<Arg>(new Const(-1)),
                 shared_ptr<Arg>(new Const(1)),
                 shared_ptr<Arg>(new Const(0))) << std::endl;
  return 0;
}





PHP: <?php
function A($k,$x1,$x2,$x3,$x4,$x5) {
    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {
        return A(--$k,$b,$x1,$x2,$x3,$x4);
    };
    return $k <= 0 ? $x4() + $x5() : $b();
}  

echo A(10, function () { return  1; },
           function () { return -1; },
           function () { return -1; },
           function () { return  1; }, 
           function () { return  0; }) . "\n";
?>
Task: Find limit of recursion


C++: #include <iostream>
 
void recurse(unsigned int i)
{
  std::cout<<i<<"\n";
  recurse(i+1);
}
 
int main()
{
  recurse(0);
}





PHP: <?php
function a() {
    static $i = 0;
    print ++$i . "\n";
    a();
}
a();
Task: Perfect numbers


C++: #include <iostream>
using namespace std ;

int divisor_sum( int number ) { 
   int sum = 0 ; 
   for ( int i = 1 ; i < number ; i++ ) 
      if ( number % i == 0 ) 
         sum += i ; 
   return sum; 
}

int main( ) { 
   cout << "Perfect numbers from 1 to 33550337:\n" ;
   for ( int num = 1 ; num < 33550337 ; num++ ) { 
      if (divisor_sum(num) == num) 
         cout << num << '\n' ;
   }   
   return 0 ; 
}





PHP: function is_perfect($number)
{
    $sum = 0;
    for($i = 1; $i < $number; $i++)
    {
        if($number % $i == 0)
            $sum += $i;
    }
    return $sum == $number;
}

echo "Perfect numbers from 1 to 33550337:" . PHP_EOL;
for($num = 1; $num < 33550337; $num++)
{
    if(is_perfect($num))
        echo $num . PHP_EOL;
}
Task: Sorting algorithms_Bead sort


C++: 



#include <iostream>
#include <vector>

using std::cout;
using std::vector;

void distribute(int dist, vector<int> &List) {
	
    if (dist > List.size() )
        List.resize(dist); 

    for (int i=0; i < dist; i++)
        List[i]++;
}

vector<int> beadSort(int *myints, int n) {
    vector<int> list, list2, fifth (myints, myints + n);

    cout << "#1 Beads falling down: ";
    for (int i=0; i < fifth.size(); i++)
        distribute (fifth[i], list);
    cout << '\n';

    cout << "\nBeads on their sides: ";
    for (int i=0; i < list.size(); i++)
        cout << " " << list[i];
    cout << '\n';

    

    cout << "#2 Beads right side up: ";
    for (int i=0; i < list.size(); i++)
        distribute (list[i], list2);
    cout << '\n';

    return list2;
}

int main() {
    int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1};
	vector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int));
	cout << "Sorted list/array: ";
	for(unsigned int i=0; i<sorted.size(); i++)
		cout << sorted[i] << ' ';
}





PHP: <?php
function columns($arr) {
    if (count($arr) == 0)
        return array();
    else if (count($arr) == 1)
        return array_chunk($arr[0], 1);

    array_unshift($arr, NULL);

    $transpose = call_user_func_array('array_map', $arr);
    return array_map('array_filter', $transpose);
}

function beadsort($arr) {
    foreach ($arr as $e)
        $poles []= array_fill(0, $e, 1);
    return array_map('count', columns(columns($poles)));
}

print_r(beadsort(array(5,3,1,7,4,1,1)));
?>
Task: Arbitrary-precision integers (included)


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

namespace mp = boost::multiprecision;

int main(int argc, char const *argv[])
{
    
    
    
    
    uint64_t tmpres = mp::pow(mp::mpz_int(4)
                            , mp::pow(mp::mpz_int(3)
                                    , 2).convert_to<uint64_t>()
                                      ).convert_to<uint64_t>();
    mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres);
    std::string s = res.str();
    std::cout << s.substr(0, 20) 
              << "..."
              << s.substr(s.length() - 20, 20) << std::endl;
    return 0;
}





PHP: <?php
$y = bcpow('5', bcpow('4', bcpow('3', '2')));
printf("5**4**3**2 = %s...%s and has %d digits\n", substr($y,0,20), substr($y,-20), strlen($y));
?>
Task: Least common multiple


C++: #include <boost/math/common_factor.hpp>
#include <iostream>

int main( ) {
   std::cout << "The least common multiple of 12 and 18 is " << 
      boost::math::lcm( 12 , 18 ) << " ,\n"
      << "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ;
   return 0 ;
}





PHP: echo lcm(12, 18) == 36;

function lcm($m, $n) {
    if ($m == 0 || $n == 0) return 0;
    $r = ($m * $n) / gcd($m, $n);
    return abs($r);
}

function gcd($a, $b) {
    while ($b != 0) {
        $t = $b;
        $b = $a % $b;
        $a = $t;
    }
    return $a;
}
Task: Loops_Break


C++: #include <iostream>
#include <ctime>
#include <cstdlib>

int main(){
	srand(time(NULL)); 
	while(true){
		const int a = rand() % 20; 
		std::cout << a << std::endl;
		if(a == 10)
			break;
		const int b = rand() % 20;
		std::cout << b << std::endl;
	}
	return 0;
}





PHP: while (true) {
    $a = rand(0,19);
    echo "$a\n";
    if ($a == 10)
        break;
    $b = rand(0,19);
    echo "$b\n";
}
Task: Hello world_Line printer


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

int main(){
  std::ofstream lprFile;
  lprFile.open( "/dev/lp0" );
  lprFile << "Hello World!\n";
  lprFile.close();
  return 0;
}





PHP: <?php
file_put_contents('/dev/lp0', 'Hello world!');
?>
Task: Trabb Pardo–Knuth algorithm


C++: #include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <iomanip>

int main( ) {
   std::vector<double> input( 11 ) , results( 11 ) ;
   std::cout << "Please enter 11 numbers!\n" ;
   for ( int i = 0 ; i < input.size( ) ; i++ ) 
      std::cin >> input[i];
      
   std::transform( input.begin( ) , input.end( ) , results.begin( ) ,
	 [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ;
   for ( int i = 10 ; i > -1 ; i-- ) {
      std::cout << "f( " << std::setw( 3 ) << input[ i ] << " ) : " ; 
      if ( results[ i ] > 400 ) 
	 std::cout << "too large!" ;
      else 
	 std::cout << results[ i ] << " !" ;
      std::cout << std::endl ;
   }
   return 0 ;
}





PHP: <?php



function f($n)
{
    return sqrt(abs($n)) + 5 * $n * $n * $n;
}

$sArray = [];
echo "Enter 11 numbers.\n";
for ($i = 0; $i <= 10; $i++) {
    echo $i + 1, " - Enter number: "; 
    array_push($sArray, (float)fgets(STDIN)); 
}
echo PHP_EOL;

$sArray = array_reverse($sArray);

foreach ($sArray as $s) {
    $r = f($s);
    echo "f(", $s, ") = ";
    if ($r > 400) 
        echo "overflow\n";
    else
        echo $r, PHP_EOL;
}
?>
Task: Middle three digits


C++: #include <iostream>

std::string middleThreeDigits(int n)
{
    auto number = std::to_string(std::abs(n));
    auto length = number.size();

    if (length < 3) {
        return "less than three digits";
    } else if (length % 2 == 0) {
        return "even number of digits";
    } else {
        return number.substr(length / 2 - 1, 3);
    }
}

int main()
{
    auto values {123, 12345, 1234567, 987654321, 10001,
                 -10001, -123, -100, 100, -12345,
                 1, 2, -1, -10, 2002, -2002, 0};

    for (auto&& v : values) {
        std::cout << "middleThreeDigits(" << v << "): " <<
                     middleThreeDigits(v) << "\n";
    }
}





PHP: 


function middlethree($integer)
{
	$int 	= (int)str_replace('-','',$integer);
	$length = strlen($int);

	if(is_int($int))
	{
		if($length >= 3)
		{
			if($length % 2 == 1)
			{
				$middle = floor($length / 2) - 1;
				return substr($int,$middle, 3);
			}
			else
			{
				return 'The value must contain an odd amount of digits...';	
			}
		}
		else
		{
			return 'The value must contain at least three digits...';	
		}
	}
	else
	{
		return 'The value does not appear to be an integer...';
	}
}

$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);

foreach($numbers as $nums)
{
	echo $nums.' : '.middlethree($nums). '<br>';
}
Task: Odd word problem


C++: #include <iostream>
#include <cctype>
#include <functional>

using namespace std;

bool odd()
{
  function<void ()> prev = []{};
  while(true) {
    int c = cin.get();
    if (!isalpha(c)) {
      prev();
      cout.put(c);
      return c != '.';
    }
    prev = [=] { cout.put(c); prev();  };
  }
}

bool even() 
{
  while(true) {
    int c;
    cout.put(c = cin.get());
    if (!isalpha(c)) return c != '.';
  }
}


int main()
{
  bool e = false;
  while( e ? odd() : even() ) e = !e;
  return 0;
}





PHP: $odd = function ($prev) use ( &$odd ) {
	$a = fgetc(STDIN);
	if (!ctype_alpha($a)) {
		$prev();
		fwrite(STDOUT, $a);
		return $a != '.';
	}
	$clos = function () use ($a , $prev) {
		fwrite(STDOUT, $a);
		$prev();
	};
	return $odd($clos);
};
$even = function () {
	while (true) {
		$c = fgetc(STDIN);
		fwrite(STDOUT, $c);
		if (!ctype_alpha($c)) {
			return $c != ".";
		}
	}
};
$prev = function(){};
$e = false;
while ($e ? $odd($prev) : $even()) {
	$e = !$e;
}
Task: Literals_String


C++: auto strA = R"(this is
a newline-separated
raw string)";





PHP: 'c';                      # character
'hello';                  # these two strings are the same
"hello";
'Hi $name. How are you?'; # result: "Hi $name. How are you?"
"Hi $name. How are you?"; # result: "Hi Bob. How are you?"
'\n';                     # 2-character string with a backslash and "n"
"\n";                     # newline character
`ls`;                     # runs a command in the shell and returns the output as a string
<<END                     # Here-Document
Hi, whatever goes here gets put into the string,
including newlines and $variables,
until the label we put above
END;
<<'END'                   # Here-Document like single-quoted
Same as above, but no interpolation of $variables.
END;
Task: Enumerations


C++: enum fruits { apple, banana, cherry };

enum fruits { apple = 0, banana = 1, cherry = 2 };





PHP: 
$fruits = array( "apple", "banana", "cherry" );
$fruits = array( "apple" => 0, "banana" => 1, "cherry" => 2 );

class Fruit {
  const APPLE = 0;
  const BANANA = 1;
  const CHERRY = 2;
}

$value = Fruit::APPLE;

define("FRUIT_APPLE", 0);
define("FRUIT_BANANA", 1);
define("FRUIT_CHERRY", 2);
Task: Modulinos


C++: int meaning_of_life();





PHP: <?php
function meaning_of_life() {
	return 42;
}

function main($args) {
	echo "Main: The meaning of life is " . meaning_of_life() . "\n";
}

if (preg_match("/scriptedmain/", $_SERVER["SCRIPT_NAME"])) {
	main($argv);
}
?>
Task: Unix_ls


C++: #include <iostream>
#include <set>
#include <boost/filesystem.hpp>

namespace fs = boost::filesystem;

int main(void)
{
    fs::path p(fs::current_path());
    std::set<std::string> tree;

    for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it)
        tree.insert(it->path().filename().native());

    for (auto entry : tree)
        std::cout << entry << '\n';
}





PHP: <?php
foreach(scandir('.') as $fileName){
    echo $fileName."\n";
}
Task: Move-to-front algorithm


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

using namespace std;

class MTF
{
public:
    string encode( string str )
    {
	fillSymbolTable();
	vector<int> output;
	for( string::iterator it = str.begin(); it != str.end(); it++ )
	{
	    for( int i = 0; i < 26; i++ )
	    {
		if( *it == symbolTable[i] )
		{
		    output.push_back( i );
		    moveToFront( i );
		    break;
		}
	    }
	}
	string r;
	for( vector<int>::iterator it = output.begin(); it != output.end(); it++ )
	{
	    ostringstream ss;
	    ss << *it;
	    r += ss.str() + " ";
	}
	return r;
    }

    string decode( string str )
    {
	fillSymbolTable();
	istringstream iss( str ); vector<int> output;
	copy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );
	string r;
	for( vector<int>::iterator it = output.begin(); it != output.end(); it++ )
	{
	    r.append( 1, symbolTable[*it] );
	    moveToFront( *it );
	}
	return r;
    }

private:
    void moveToFront( int i )
    {
	char t = symbolTable[i];
	for( int z = i - 1; z >= 0; z-- )
	    symbolTable[z + 1] = symbolTable[z];

        symbolTable[0] = t;
    }

    void fillSymbolTable()
    {
        for( int x = 0; x < 26; x++ )
	    symbolTable[x] = x + 'a';
    }

    char symbolTable[26];
};

int main()
{
    MTF mtf;
    string a, str[] = { "broood", "bananaaa", "hiphophiphop" };
    for( int x = 0; x < 3; x++ )
    {
        a = str[x];
        cout << a << " -> encoded = ";
        a = mtf.encode( a );
        cout << a << "; decoded = " << mtf.decode( a ) << endl;
    }
    return 0;
}





PHP: <?php

function symbolTable() {
    $symbol = array();
    for ($c = ord('a') ; $c <= ord('z') ; $c++) {
        $symbol[$c - ord('a')] = chr($c);
    }
    return $symbol;
}

function mtfEncode($original, $symbol) {
    $encoded = array();
    for ($i = 0 ; $i < strlen($original) ; $i++) {
        $char = $original[$i];
        $position = array_search($char, $symbol);
        $encoded[] = $position;
        $mtf = $symbol[$position];
        unset($symbol[$position]);
        array_unshift($symbol, $mtf);
    }
    return $encoded;
}

function mtfDecode($encoded, $symbol) {
    $decoded = '';
    foreach ($encoded AS $position) {
        $char = $symbol[$position];
        $decoded .= $char;
        unset($symbol[$position]);
        array_unshift($symbol, $char);
    }
    return $decoded;
}

foreach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {
    $encoded = mtfEncode($original, symbolTable());
    $decoded = mtfDecode($encoded, symbolTable());
    echo
        $original,
        ' -> [', implode(',', $encoded), ']',
        ' -> ', $decoded,
        ' : ', ($original === $decoded ? 'OK' : 'Error'),
        PHP_EOL;
}
Task: Longest increasing subsequence


C++: #include <vector>
#include <list>
#include <algorithm>
#include <iostream>

template <typename T>
struct Node {
    T value;
    Node* prev_node;
};

template <typename Container>
Container lis(const Container& values) {
    using E = typename Container::value_type;
    using NodePtr = Node<E>*;
    using ConstNodePtr = const NodePtr;

    std::vector<NodePtr> pileTops;
    std::vector<Node<E>> nodes(values.size());

    
    auto cur_node = std::begin(nodes);
    for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node)
    {
        auto node = &*cur_node;
        node->value = *cur_value;

        
        auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node,
            [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; });

        if (lb != pileTops.begin())
            node->prev_node = *std::prev(lb);

        if (lb == pileTops.end())
            pileTops.push_back(node);
        else
            *lb = node;
    }

    
    
    Container result(pileTops.size());
    auto r = std::rbegin(result);

    for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r)
        *r = node->value;

    return result;
}

template <typename Container>
void show_lis(const Container& values)
{
    auto&& result = lis(values);
    for (auto& r : result) {
        std::cout << r << ' ';
    }
    std::cout << std::endl;
}

int main() 
{
    show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 });
    show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 });
}





PHP: <?php
class Node {
    public $val;
    public $back = NULL;
}

function lis($n) {
    $pileTops = array();

    foreach ($n as $x) {

        $low = 0; $high = count($pileTops)-1;
        while ($low <= $high) {
            $mid = (int)(($low + $high) / 2);
            if ($pileTops[$mid]->val >= $x)
                $high = $mid - 1;
            else
                $low = $mid + 1;
        }
        $i = $low;
        $node = new Node();
        $node->val = $x;
        if ($i != 0)
            $node->back = $pileTops[$i-1];
        $pileTops[$i] = $node;
    }
    $result = array();
    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;
         $node != NULL; $node = $node->back)
        $result[] = $node->val;

    return array_reverse($result);
}

print_r(lis(array(3, 2, 6, 4, 5, 1)));
print_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));
?>