WeixiangYan/CodeTransOcean huggingface dataset:
Task: Break OO privacy


C++: #include <iostream>

class CWidget; 

class CFactory
{
  friend class CWidget;
private:
  unsigned int m_uiCount;
public:
  CFactory();
  ~CFactory();
  CWidget* GetWidget();
};

class CWidget
{
private:
  CFactory& m_parent;

private:
  CWidget(); 
  CWidget(const CWidget&); 
  CWidget& operator=(const CWidget&); 
public:
  CWidget(CFactory& parent);
  ~CWidget();
};


CFactory::CFactory() : m_uiCount(0) {}
CFactory::~CFactory() {}


CWidget* CFactory::GetWidget()
{
  
  return new CWidget(*this);
}


CWidget::CWidget(CFactory& parent) : m_parent(parent)
{
  ++m_parent.m_uiCount;

  std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}

CWidget::~CWidget()
{
  --m_parent.m_uiCount;

  std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}

int main()
{
  CFactory factory;

  CWidget* pWidget1 = factory.GetWidget();
  CWidget* pWidget2 = factory.GetWidget();
  delete pWidget1;

  CWidget* pWidget3 = factory.GetWidget();
  delete pWidget3;
  delete pWidget2;
}







VB: Imports System.Reflection


Public Class MyClazz
    Private answer As Integer = 42
End Class

Public Class Program
    Public Shared Sub Main()
        Dim myInstance = New MyClazz()
        Dim fieldInfo = GetType(MyClazz).GetField("answer", BindingFlags.NonPublic Or BindingFlags.Instance)
        Dim answer = fieldInfo.GetValue(myInstance)
        Console.WriteLine(answer)
    End Sub
End Class
Task: Long year


C++: #include <stdio.h>
#include <math.h>



int p(int year) {
	return (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7;
}

int is_long_year(int year) {
	return p(year) == 4 || p(year - 1) == 3;
}

void print_long_years(int from, int to) {
	for (int year = from; year <= to; ++year) {
		if (is_long_year(year)) {
			printf("%d ", year);
		}
	}
}

int main() {

	printf("Long (53 week) years between 1800 and 2100\n\n");
	print_long_years(1800, 2100);
	printf("\n");
	return 0;
}







VB: DEFINT A-Z

DECLARE FUNCTION p% (Yr AS INTEGER)
DECLARE FUNCTION LongYear% (Yr AS INTEGER)

DIM iYi, iYf, i

CLS
PRINT "This program calculates which are 53-week years in a range."
PRINT
INPUT "Initial year"; iYi
INPUT "Final year (could be the same)"; iYf
IF iYf >= iYi THEN
  FOR i = iYi TO iYf
    IF LongYear(i) THEN
      PRINT i; " ";
    END IF
  NEXT i
END IF
PRINT
PRINT
PRINT "End of program."
END

FUNCTION LongYear% (Yr AS INTEGER)
  LongYear% = (p%(Yr) = 4) OR (p%(Yr - 1) = 3)
END FUNCTION

FUNCTION p% (Yr AS INTEGER)
  p% = (Yr + INT(Yr / 4) - INT(Yr / 100) + INT(Yr / 400)) MOD 7
END FUNCTION
Task: Associative array_Merging


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

template<typename map_type>
map_type merge(const map_type& original, const map_type& update) {
    map_type result(update);
    result.insert(original.begin(), original.end());
    return result;
}

int main() {
    typedef std::map<std::string, std::string> map;
    map original{
        {"name", "Rocket Skates"},
        {"price", "12.75"},
        {"color", "yellow"}
    };
    map update{
        {"price", "15.25"},
        {"color", "red"},
        {"year", "1974"}
    };
    map merged(merge(original, update));
    for (auto&& i : merged)
        std::cout << "key: " << i.first << ", value: " << i.second << '\n';
    return 0;
}







VB: Private Type Associative
    Key As String
    Value As Variant
End Type
Sub Main_Array_Associative()
Dim BaseArray(2) As Associative, UpdateArray(2) As Associative
    FillArrays BaseArray, UpdateArray
    ReDim Result(UBound(BaseArray)) As Associative
    MergeArray Result, BaseArray, UpdateArray
    PrintOut Result
End Sub
Private Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)
Dim i As Long, Respons As Long
    Res = Base
    For i = LBound(Update) To UBound(Update)
        If Exist(Respons, Base, Update(i).Key) Then
            Res(Respons).Value = Update(i).Value
        Else
            ReDim Preserve Res(UBound(Res) + 1)
            Res(UBound(Res)).Key = Update(i).Key
            Res(UBound(Res)).Value = Update(i).Value
        End If
    Next
End Sub
Private Function Exist(R As Long, B() As Associative, K As String) As Boolean
Dim i As Long
    Do
        If B(i).Key = K Then
            Exist = True
            R = i
        End If
        i = i + 1
    Loop While i <= UBound(B) And Not Exist
End Function
Private Sub FillArrays(B() As Associative, U() As Associative)
    B(0).Key = "name"
    B(0).Value = "Rocket Skates"
    B(1).Key = "price"
    B(1).Value = 12.75
    B(2).Key = "color"
    B(2).Value = "yellow"
    U(0).Key = "price"
    U(0).Value = 15.25
    U(1).Key = "color"
    U(1).Value = "red"
    U(2).Key = "year"
    U(2).Value = 1974
End Sub
Private Sub PrintOut(A() As Associative)
Dim i As Long
    Debug.Print "Key", "Value"
    For i = LBound(A) To UBound(A)
        Debug.Print A(i).Key, A(i).Value
    Next i
    Debug.Print "-----------------------------"
End Sub
Task: Associative array_Iteration


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

int main() {
  std::map<std::string, int> dict {
    {"One", 1},
    {"Two", 2},
    {"Three", 7}
  };

  dict["Three"] = 3;

  std::cout << "One: " << dict["One"] << std::endl;
  std::cout << "Key/Value pairs: " << std::endl;
  for(auto& kv: dict) {
    std::cout << "  " << kv.first << ": " << kv.second << std::endl;
  }

  return 0;
}







VB: Option Explicit
Sub Test()
    Dim h As Object, i As Long, u, v, s
    Set h = CreateObject("Scripting.Dictionary")
    h.Add "A", 1
    h.Add "B", 2
    h.Add "C", 3

    
    For Each s In h.Keys
        Debug.Print s
    Next

    
    For Each s In h.Items
        Debug.Print s
    Next

    
    u = h.Keys
    v = h.Items
    For i = 0 To h.Count - 1
        Debug.Print u(i), v(i)
    Next
End Sub
Task: Define a primitive data type


C++: #include <stdexcept>

class tiny_int
{
public:
  tiny_int(int i):
    value(i)
  {
    if (value < 1)
      throw std::out_of_range("tiny_int: value smaller than 1");
    if (value > 10)
      throw std::out_of_range("tiny_int: value larger than 10");
  }
  operator int() const
  {
    return value;
  }
  tiny_int& operator+=(int i)
  {
    
    
    *this = value + i;
    return *this;
  }
  tiny_int& operator-=(int i)
  {
    *this = value - i;
    return *this;
  }
  tiny_int& operator*=(int i)
  {
    *this = value * i;
    return *this;
  }
  tiny_int& operator/=(int i)
  {
    *this = value / i;
    return *this;
  }
  tiny_int& operator<<=(int i)
  {
    *this = value << i;
    return *this;
  }
  tiny_int& operator>>=(int i)
  {
    *this = value >> i;
    return *this;
  }
  tiny_int& operator&=(int i)
  {
    *this = value & i;
    return *this;
  }
  tiny_int& operator|=(int i)
  {
    *this = value | i;
    return *this;
  }
private:
  unsigned char value; 
};







VB: Private mvarValue As Integer

Public Property Let Value(ByVal vData As Integer)
    If (vData > 10) Or (vData < 1) Then
        Error 380   
    Else
        mvarValue = vData
    End If
End Property

Public Property Get Value() As Integer
    Value = mvarValue
End Property

Private Sub Class_Initialize()
    
    mvarValue = 1
End Sub
Task: Hash join


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

using tab_t = std::vector<std::vector<std::string>>;
tab_t tab1 {

  {"27", "Jonah"}
, {"18", "Alan"}
, {"28", "Glory"}
, {"18", "Popeye"}
, {"28", "Alan"}
};

tab_t tab2 {

  {"Jonah", "Whales"}
, {"Jonah", "Spiders"}
, {"Alan", "Ghosts"}
, {"Alan", "Zombies"}
, {"Glory", "Buffy"}
};

std::ostream& operator<<(std::ostream& o, const tab_t& t) {
  for(size_t i = 0; i < t.size(); ++i) {
    o << i << ":";
    for(const auto& e : t[i]) 
      o << '\t' << e;
    o << std::endl;
  }
  return o;
}

tab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {
  std::unordered_multimap<std::string, size_t> hashmap;
  
  for(size_t i = 0; i < a.size(); ++i) {
    hashmap.insert(std::make_pair(a[i][columna], i));
  }
  
  tab_t result;
  for(size_t i = 0; i < b.size(); ++i) {
    auto range = hashmap.equal_range(b[i][columnb]);
    for(auto it = range.first; it != range.second; ++it) {
      tab_t::value_type row;
      row.insert(row.end() , a[it->second].begin() , a[it->second].end());
      row.insert(row.end() , b[i].begin()          , b[i].end());
      result.push_back(std::move(row));
    }
  }
  return result;
}

int main(int argc, char const *argv[])
{
  using namespace std;
  int ret = 0;
  cout << "Table A: "       << endl << tab1 << endl;
  cout << "Table B: "       << endl << tab2 << endl;
  auto tab3 = Join(tab1, 1, tab2, 0);
  cout << "Joined tables: " << endl << tab3 << endl;
  return ret;
}







VB: Dim t_age(4,1)
t_age(0,0) = 27 : t_age(0,1) = "Jonah"
t_age(1,0) = 18 : t_age(1,1) = "Alan"
t_age(2,0) = 28 : t_age(2,1) = "Glory"
t_age(3,0) = 18 : t_age(3,1) = "Popeye"
t_age(4,0) = 28 : t_age(4,1) = "Alan"

Dim t_nemesis(4,1)
t_nemesis(0,0) = "Jonah" : t_nemesis(0,1) = "Whales"
t_nemesis(1,0) = "Jonah" : t_nemesis(1,1) = "Spiders"
t_nemesis(2,0) = "Alan" : t_nemesis(2,1) = "Ghosts"
t_nemesis(3,0) = "Alan" : t_nemesis(3,1) = "Zombies"
t_nemesis(4,0) = "Glory" : t_nemesis(4,1) = "Buffy"

Call hash_join(t_age,1,t_nemesis,0)

Sub hash_join(table_1,index_1,table_2,index_2)
	Set hash = CreateObject("Scripting.Dictionary")
	For i = 0 To UBound(table_1)
		hash.Add i,Array(table_1(i,0),table_1(i,1))
	Next
	For j = 0 To UBound(table_2)
		For Each key In hash.Keys
			If hash(key)(index_1) = table_2(j,index_2) Then
				WScript.StdOut.WriteLine hash(key)(0) & "," & hash(key)(1) &_
					" = " & table_2(j,0) & "," & table_2(j,1)
			End If
		Next
	Next
End Sub
Task: Find words whose first and last three letters are equal


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

int main(int argc, char** argv) {
    const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
    std::ifstream in(filename);
    if (!in) {
        std::cerr << "Cannot open file '" << filename << "'.\n";
        return EXIT_FAILURE;
    }
    std::string word;
    int n = 0;
    while (getline(in, word)) {
        const size_t len = word.size();
        if (len > 5 && word.compare(0, 3, word, len - 3) == 0)
            std::cout << ++n << ": " << word << '\n';
    }
    return EXIT_SUCCESS;
}







VB: with createobject("ADODB.Stream")
  .charset ="UTF-8"
  .open
  .loadfromfile("unixdict.txt")
  s=.readtext
end with  
a=split (s,vblf)

set d= createobject("Scripting.Dictionary")
for each aa in a
  x=trim(aa)
  l=len(x)
  if l>5 then
   d.removeall
   for i=1 to 3
     m=mid(x,i,1)
     if not d.exists(m) then d.add m,null
   next
   res=true
   for i=l-2 to l
     m=mid(x,i,1)
     if not d.exists(m) then 
       res=false:exit for 
      else
        d.remove(m)
      end if        
   next 
   if res then 
     wscript.stdout.write left(x & space(15),15)
     if left(x,3)=right(x,3) then  wscript.stdout.write "*"
     wscript.stdout.writeline
    end if 
  end if
next
Task: Address of a variable


C++: int i;
void* address_of_i = &i;







VB: Dim TheAddress as long
Dim SecVar as byte
Dim MyVar as byte
    MyVar = 10


TheAddress = varptr(MyVar)


MEMSET(TheAddress, 102, SizeOf(byte))


showmessage "MyVar = " + str$(MyVar)


MEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))


showmessage "SecVar = " + str$(SecVar)
Task: Inheritance_Single


C++: class Animal
{
  
};

class Dog: public Animal
{
  
};

class Lab: public Dog
{
  
};

class Collie: public Dog
{
  
};

class Cat: public Animal
{
  
};







VB: Class Animal
  
End Class

Class Dog
  Inherits Animal
  
End Class

Class Lab
  Inherits Dog
  
End Class

Class Collie
  Inherits Dog
  
End Class

Class Cat
  Inherits Animal
  
End Class
Task: Associative array_Creation


C++: #include <map>







VB: Option Explicit
Sub Test()
    Dim h As Object
    Set h = CreateObject("Scripting.Dictionary")
    h.Add "A", 1
    h.Add "B", 2
    h.Add "C", 3
    Debug.Print h.Item("A")
    h.Item("C") = 4
    h.Key("C") = "D"
    Debug.Print h.exists("C")
    h.Remove "B"
    Debug.Print h.Count
    h.RemoveAll
    Debug.Print h.Count
End Sub
Task: Find words which contain the most consonants


C++: #include <bitset>
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
#include <vector>



size_t consonants(const std::string& word) {
    std::bitset<26> bits;
    size_t bit = 0;
    for (char ch : word) {
        ch = std::tolower(static_cast<unsigned char>(ch));
        if (ch < 'a' || ch > 'z')
            continue;
        switch (ch) {
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
            break;
        default:
            bit = ch - 'a';
            if (bits.test(bit))
                return 0;
            bits.set(bit);
            break;
        }
    }
    return bits.count();
}

int main(int argc, char** argv) {
    const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
    std::ifstream in(filename);
    if (!in) {
        std::cerr << "Cannot open file '" << filename << "'.\n";
        return EXIT_FAILURE;
    }
    std::string word;
    std::map<size_t, std::vector<std::string>, std::greater<int>> map;
    while (getline(in, word)) {
        if (word.size() <= 10)
            continue;
        size_t count = consonants(word);
        if (count != 0)
            map[count].push_back(word);
    }
    const int columns = 4;
    for (const auto& p : map) {
        std::cout << p.first << " consonants (" << p.second.size() << "):\n";
        int n = 0;
        for (const auto& word : p.second) {
            std::cout << std::left << std::setw(18) << word;
            ++n;
            if (n % columns == 0)
                std::cout << '\n';
        }
        if (n % columns != 0)
            std::cout << '\n';
        std::cout << '\n';
    }
    return EXIT_SUCCESS;
}







VB: with createobject("ADODB.Stream")
  .charset ="UTF-8"
  .open
  .loadfromfile("unixdict.txt")
  s=.readtext
end with  
a=split (s,vblf)

dim b(25)  
dim c(128) 

with new regexp
  .pattern="([^aeiou])"
  .global=true
for each i in a
  if len(trim(i))>10 then
   set matches= .execute(i)   
   rep=false
   for each m in matches  
     x=asc(m)  
     c(x)=c(x)+1
     if c(x)>1 then rep=true :exit for
   next
   erase c
   if not rep then   
     x1=matches.count
     b(x1)=b(x1)&" "&i  
   end if    
  end if
next
end with 


for i=25 to 0 step -1
  if b(i)<>"" then  wscript.echo i & "  "& b(i) & vbcrlf
next
Task: Nested templated data


C++: #include <iostream>
#include <set>
#include <tuple>
#include <vector>

using namespace std;


template<typename P>
void PrintPayloads(const P &payloads, int index, bool isLast)
{
    if(index < 0 || index >= (int)size(payloads)) cout << "null";        
    else cout << "'" << payloads[index] << "'";
    if (!isLast) cout << ", ";  
}


template<typename P, typename... Ts>
void PrintPayloads(const P &payloads, tuple<Ts...> const& nestedTuple, bool isLast = true)
{
    std::apply  
    (
        [&payloads, isLast](Ts const&... tupleArgs)
        {
            size_t n{0};
            cout << "[";
            (PrintPayloads(payloads, tupleArgs, (++n == sizeof...(Ts)) ), ...);
            cout << "]";
            cout << (isLast ? "\n" : ",\n");
        }, nestedTuple
    );
}


void FindUniqueIndexes(set<int> &indexes, int index)
{
    indexes.insert(index);
}


template<typename... Ts>
void FindUniqueIndexes(set<int> &indexes, std::tuple<Ts...> const& nestedTuple)
{
    std::apply
    (
        [&indexes](Ts const&... tupleArgs)
        {
            (FindUniqueIndexes(indexes, tupleArgs),...);
        }, nestedTuple
    );
}


template<typename P>
void PrintUnusedPayloads(const set<int> &usedIndexes, const P &payloads)
{
    for(size_t i = 0; i < size(payloads); i++)
    {
        if(usedIndexes.find(i) == usedIndexes.end() ) cout << payloads[i] << "\n";
    }
}

int main()
{
    
    vector payloads {"Payload#0", "Payload#1", "Payload#2", "Payload#3", "Payload#4", "Payload#5", "Payload#6"};
    const char *shortPayloads[] {"Payload#0", "Payload#1", "Payload#2", "Payload#3"}; 

    
    auto tpl = make_tuple(make_tuple(
        make_tuple(1, 2),
        make_tuple(3, 4, 1),
        5));

    cout << "Mapping indexes to payloads:\n";
    PrintPayloads(payloads, tpl);      

    cout << "\nFinding unused payloads:\n";
    set<int> usedIndexes;
    FindUniqueIndexes(usedIndexes, tpl);
    PrintUnusedPayloads(usedIndexes, payloads);

    cout << "\nMapping to some out of range payloads:\n";
    PrintPayloads(shortPayloads, tpl);      
    
    return 0;
}







VB: Public Sub test()
    Dim t(2) As Variant
    t(0) = [{1,2}]
    t(1) = [{3,4,1}]
    t(2) = 5
    p = [{"Payload#0","Payload#1","Payload#2","Payload#3","Payload#4","Payload#5","Payload#6"}]
    Dim q(6) As Boolean
    For i = LBound(t) To UBound(t)
        If IsArray(t(i)) Then
            For j = LBound(t(i)) To UBound(t(i))
                q(t(i)(j)) = True
                t(i)(j) = p(t(i)(j) + 1)
            Next j
        Else
            q(t(i)) = True
            t(i) = p(t(i) + 1)
        End If
    Next i
    For i = LBound(t) To UBound(t)
        If IsArray(t(i)) Then
            Debug.Print Join(t(i), ", ")
        Else
            Debug.Print t(i)
        End If
    Next i
    For i = LBound(q) To UBound(q)
        If Not q(i) Then Debug.Print p(i + 1); " is not used"
    Next i
End Sub
Task: Delete a file



C#: using System;
using System.IO;

namespace DeleteFile {
  class Program {
    static void Main() {
      File.Delete("input.txt");
      Directory.Delete("docs");
      File.Delete("/input.txt");
      Directory.Delete("/docs");
    }
  }
}




PHP: <?php
unlink('input.txt');
unlink('/input.txt');
rmdir('docs');
rmdir('/docs');
?>
Task: String interpolation (included)



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




PHP: <?php
$extra = 'little';
echo "Mary had a $extra lamb.\n";
printf("Mary had a %s lamb.\n", $extra);
?>
Task: Take notes on the command line



C#: using System;
using System.IO;
using System.Text;

namespace RosettaCode
{
  internal class Program
  {
    private const string FileName = "NOTES.TXT";

    private static void Main(string[] args)
    {
      if (args.Length==0)
      {
        string txt = File.ReadAllText(FileName);
        Console.WriteLine(txt);
      }
      else
      {
        var sb = new StringBuilder();
        sb.Append(DateTime.Now).Append("\n\t");
        foreach (string s in args)
          sb.Append(s).Append(" ");
        sb.Append("\n");

        if (File.Exists(FileName))
          File.AppendAllText(FileName, sb.ToString());
        else
          File.WriteAllText(FileName, sb.ToString());
      }
    }
  }
}




PHP: #!/usr/bin/php
<?php
if ($argc > 1)
    file_put_contents(
        'notes.txt', 
        date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n",
        FILE_APPEND
    );
else
    @readfile('notes.txt');
Task: Find common directory path



C#: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RosettaCodeTasks
{

	class Program
	{
		static void Main ( string[ ] args )
		{
			FindCommonDirectoryPath.Test ( );
		}

	}

	class FindCommonDirectoryPath
	{
		public static void Test ( )
		{
			Console.WriteLine ( "Find Common Directory Path" );
			Console.WriteLine ( );
			List<string> PathSet1 = new List<string> ( );
			PathSet1.Add ( "/home/user1/tmp/coverage/test" );
			PathSet1.Add ( "/home/user1/tmp/covert/operator" );
			PathSet1.Add ( "/home/user1/tmp/coven/members" );
			Console.WriteLine("Path Set 1 (All Absolute Paths):");
			foreach ( string path in PathSet1 )
			{
				Console.WriteLine ( path );
			}
			Console.WriteLine ( "Path Set 1 Common Path: {0}", FindCommonPath ( "/", PathSet1 ) );
		}
		public static string FindCommonPath ( string Separator, List<string> Paths )
		{
			string CommonPath = String.Empty;
			List<string> SeparatedPath = Paths
				.First ( str => str.Length == Paths.Max ( st2 => st2.Length ) )
				.Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries )
				.ToList ( );

			foreach ( string PathSegment in SeparatedPath.AsEnumerable ( ) )
			{
				if ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) )
				{
					CommonPath = PathSegment;
				}
				else if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) )
				{
					CommonPath += Separator + PathSegment;
				}
				else
				{
					break;
				}
			}
			
			return CommonPath;
		}
	}
}




PHP: <?php



function _commonPath($dirList)
{
	$arr = array();
	foreach($dirList as $i => $path)
	{
		$dirList[$i]	= explode('/', $path);
		unset($dirList[$i][0]);
		
		$arr[$i] = count($dirList[$i]);
	}
	
	$min = min($arr);
	
	for($i = 0; $i < count($dirList); $i++)
	{
		while(count($dirList[$i]) > $min)
		{
			array_pop($dirList[$i]);
		}
		
		$dirList[$i] = '/' . implode('/' , $dirList[$i]);
	}
	
	$dirList = array_unique($dirList);
	while(count($dirList) !== 1)
	{
		$dirList = array_map('dirname', $dirList);
		$dirList = array_unique($dirList);
	}
	reset($dirList);
	
	return current($dirList);
}

 

$dirs = array(
 '/home/user1/tmp/coverage/test',
 '/home/user1/tmp/covert/operator',
 '/home/user1/tmp/coven/members',
);


if('/home/user1/tmp' !== common_path($dirs))
{
  echo 'test fail';
} else {
  echo 'test success';
}

?>
Task: Recaman's sequence



C#: using System;
using System.Collections.Generic;

namespace RecamanSequence {
    class Program {
        static void Main(string[] args) {
            List<int> a = new List<int>() { 0 };
            HashSet<int> used = new HashSet<int>() { 0 };
            HashSet<int> used1000 = new HashSet<int>() { 0 };
            bool foundDup = false;
            int n = 1;
            while (n <= 15 || !foundDup || used1000.Count < 1001) {
                int next = a[n - 1] - n;
                if (next < 1 || used.Contains(next)) {
                    next += 2 * n;
                }
                bool alreadyUsed = used.Contains(next);
                a.Add(next);
                if (!alreadyUsed) {
                    used.Add(next);
                    if (0 <= next && next <= 1000) {
                        used1000.Add(next);
                    }
                }
                if (n == 14) {
                    Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a));
                }
                if (!foundDup && alreadyUsed) {
                    Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next);
                    foundDup = true;
                }
                if (used1000.Count == 1001) {
                    Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n);
                }
                n++;
            }
        }
    }
}




PHP: <?php
$a = array();
array_push($a, 0);

$used = array();
array_push($used, 0);

$used1000 = array();
array_push($used1000, 0);

$foundDup = false;
$n = 1;

while($n <= 15 || !$foundDup || count($used1000) < 1001) {
	$next = $a[$n - 1] - $n;
	if ($next < 1 || in_array($next, $used)) {
		$next += 2 * $n;
	}
	$alreadyUsed = in_array($next, $used);
	array_push($a, $next);
	if (!$alreadyUsed) {
		array_push($used, $next);
		if (0 <= $next && $next <= 1000) {
			array_push($used1000, $next);
		}
	}
	if ($n == 14) {
		echo "The first 15 terms of the Recaman sequence are : [";
		foreach($a as $i => $v) {
			if ( $i == count($a) - 1)
				echo "$v";
			else
				echo "$v, ";
		}
		echo "]\n";
	}
	if (!$foundDup && $alreadyUsed) {
		printf("The first duplicate term is a[%d] = %d\n", $n, $next);
		$foundDup = true;
	}
	if (count($used1000) == 1001) {
		printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n);
	}
	$n++;
}