WeixiangYan/CodeTransOcean huggingface dataset:
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);



VB:   Declare Function CreateFileW Lib "Kernel32" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _
        CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer
  Declare Function WriteFile Lib "Kernel32" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _
        overlapped As Ptr) As Boolean
  Declare Function GetLastError Lib "Kernel32" () As Integer
  Declare Function CloseHandle Lib "kernel32" (hObject As Integer) As Boolean
  
  Const FILE_SHARE_READ = &h00000001
  Const FILE_SHARE_WRITE = &h00000002
  Const OPEN_EXISTING = 3
  
  Dim fHandle As Integer = CreateFileW("C:\foo.txt", 0,  FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)
  If fHandle > 0 Then
    Dim mb As MemoryBlock = "Hello, World!"
    Dim bytesWritten As Integer
    If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then
      MsgBox("Error Number: " + Str(GetLastError))
    End If
    Call CloseHandle(fHandle)
  Else
    MsgBox("Error Number: " + Str(GetLastError))
  End If
Task: Command-line arguments






PHP: <?php
$program_name = $argv[0];
$second_arg = $argv[2];
$all_args_without_program_name = array_shift($argv);



VB: Function Run(args() as String) As Integer
  For each arg As String In args
    Stdout.WriteLine(arg)
  Next
End Function
Task: Array concatenation






PHP: $arr1 = array(1, 2, 3);
$arr2 = array(4, 5, 6);
$arr3 = array_merge($arr1, $arr2);



VB: DEFINT A(1 to 4) = {1, 2, 3, 4}
DEFINT B(1 to 4) = {10, 20, 30, 40}


Redim A(1 to 8) as integer
MEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)
Task: User input_Text






PHP: #!/usr/bin/php
<?php
$string = fgets(STDIN);
$integer = (int) fgets(STDIN);



VB: Public Sub text()
    Debug.Print InputBox("Input a string")
    Debug.Print InputBox("Input the integer 75000", "Input an integer", 75000, Context = "Long")
End Sub
Task: Proper divisors






PHP: <?php
function ProperDivisors($n) {
  yield 1;
  $large_divisors = [];
  for ($i = 2; $i <= sqrt($n); $i++) {
    if ($n % $i == 0) {
      yield $i;
      if ($i*$i != $n) {
        $large_divisors[] = $n / $i;
      }
    }
  }
  foreach (array_reverse($large_divisors) as $i) {
    yield $i;
  }
}

assert([1, 2, 4, 5, 10, 20, 25, 50] ==
        iterator_to_array(ProperDivisors(100)));

foreach (range(1, 10) as $n) {
  echo "$n =>";
  foreach (ProperDivisors($n) as $divisor) {
    echo " $divisor";
  }
  echo "\n";
}

$divisorsCount = [];
for ($i = 1; $i < 20000; $i++) {
  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;
}
ksort($divisorsCount);

echo "Numbers with most divisors: ", implode(", ", end($divisorsCount)), ".\n";
echo "They have ", key($divisorsCount), " divisors.\n";



VB: dim _proper_divisors(100)

sub proper_divisors(n)
	dim i
	dim _proper_divisors_count = 0
	if n <> 1 then
		for i = 1 to (n \ 2)
			if n %% i = 0 then
				_proper_divisors_count = _proper_divisors_count + 1
				_proper_divisors(_proper_divisors_count) = i 
			end if
		next
	end if
	return _proper_divisors_count
end sub

sub show_proper_divisors(n, tabbed)
	dim cnt = proper_divisors(n)
	print str$(n) + ":"; tab(4);"(" + str$(cnt) + " items) ";
	dim j 
	for j = 1 to cnt
		if tabbed then
			print str$(_proper_divisors(j)),
		else 
			print str$(_proper_divisors(j));
		end if
		if (j < cnt) then print ",";
	next
	print
end sub

dim i
for i = 1 to 10
    show_proper_divisors(i, false)
next

dim c 
dim maxindex = 0
dim maxlength = 0
for t = 1 to 20000
	c = proper_divisors(t)
	if c > maxlength then
		maxindex = t
		maxlength = c
	end if
next

print "A maximum at ";
show_proper_divisors(maxindex, false)
Task: Regular expressions






PHP: $string = 'I am a string';
# Test
if (preg_match('/string$/', $string))
{
    echo "Ends with 'string'\n";
}
# Replace
$string = preg_replace('/\ba\b/', 'another', $string);
echo "Found 'a' and replace it with 'another', resulting in this string: $string\n";



VB: text = "I need more coffee!!!"
Set regex = New RegExp
regex.Global = True
regex.Pattern = "\s"
If regex.Test(text) Then
	WScript.StdOut.Write regex.Replace(text,vbCrLf)
Else
	WScript.StdOut.Write "No matching pattern"
End If
Task: Hash from two arrays






PHP: $keys = array('a', 'b', 'c');
$values = array(1, 2, 3);
$hash = array_combine($keys, $values);



VB: Set dict = CreateObject("Scripting.Dictionary")
os = Array("Windows", "Linux", "MacOS")
owner = Array("Microsoft", "Linus Torvalds", "Apple")
For n = 0 To 2
    dict.Add os(n), owner(n)
Next
MsgBox dict.Item("Linux")
MsgBox dict.Item("MacOS")
MsgBox dict.Item("Windows")
Task: Gray code






PHP: <?php




function gray_encode($binary){
	return $binary ^ ($binary >> 1);
}


function gray_decode($gray){
	$binary = $gray;
	while($gray >>= 1) $binary ^= $gray;
	return $binary;
}

for($i=0;$i<32;$i++){
	$gray_encoded = gray_encode($i);
	printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));
}



VB: Function Encoder(ByVal n)
    Encoder = n Xor (n \ 2)
End Function

Function Decoder(ByVal n)
    Dim g : g = 0
    Do While n > 0
       g = g Xor n
       n = n \ 2
    Loop
    Decoder = g
End Function


Function Dec2bin(ByVal n, ByVal length)
    Dim i, strbin : strbin = ""
    For i = 1 to 5
        strbin = (n Mod 2) & strbin
        n = n \ 2
    Next
    Dec2Bin = strbin
End Function

WScript.StdOut.WriteLine("Binary -> Gray Code -> Binary")
For i = 0 to 31
    encoded = Encoder(i)
    decoded = Decoder(encoded)
    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & " -> " & Dec2Bin(encoded, 5) & " -> " & Dec2Bin(decoded, 5))
Next
Task: Arrays






PHP: $NumberArray = array(0, 1, 2, 3, 4, 5, 6);
$LetterArray = array("a", "b", "c", "d", "e", "f");
$simpleForm = ['apple', 'orange'];



VB: Option Base {0|1}
Task: Sierpinski carpet






PHP: <?php

function isSierpinskiCarpetPixelFilled($x, $y) {
    while (($x > 0) or ($y > 0)) {
        if (($x % 3 == 1) and ($y % 3 == 1)) {
            return false;
        }
        $x /= 3;
        $y /= 3;
    }
    return true;
}

function sierpinskiCarpet($order) {
    $size = pow(3, $order);
    for ($y = 0 ; $y < $size ; $y++) {
        for ($x = 0 ; $x < $size ; $x++) {
            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';
        }
        echo PHP_EOL;
    }
}

for ($order = 0 ; $order <= 3 ; $order++) {
    echo 'N=', $order, PHP_EOL;
    sierpinskiCarpet($order);
    echo PHP_EOL;
}



VB: Const Order = 4

Function InCarpet(ByVal x As Integer, ByVal y As Integer)
    Do While x <> 0 And y <> 0
        If x Mod 3 = 1 And y Mod 3 = 1 Then
            InCarpet = " "
            Exit Function
        End If
        x = x \ 3
        y = y \ 3
    Loop
    InCarpet = "#"
End Function
 
Public Sub sierpinski_carpet()
    Dim i As Integer, j As Integer
    For i = 0 To 3 ^ Order - 1
        For j = 0 To 3 ^ Order - 1
            Debug.Print InCarpet(i, j);
        Next j
        Debug.Print
    Next i
End Sub
Task: Sorting algorithms_Bogosort






PHP: function bogosort($l) {
    while (!in_order($l))
        shuffle($l);
    return $l;
}

function in_order($l) {
    for ($i = 1; $i < count($l); $i++)
        if ($l[$i] < $l[$i-1])
            return FALSE;
    return TRUE;
}



VB: Private Function Knuth(a As Variant) As Variant
    Dim t As Variant, i As Integer
    If Not IsMissing(a) Then
        For i = UBound(a) To LBound(a) + 1 Step -1
            j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a))
            t = a(i)
            a(i) = a(j)
            a(j) = t
        Next i
    End If
    Knuth = a
End Function

Private Function inOrder(s As Variant)
    i = 2
    Do While i <= UBound(s)
         If s(i) < s(i - 1) Then
            inOrder = False
            Exit Function
        End If
        i = i + 1
    Loop
    inOrder = True
End Function
 
Private Function bogosort(ByVal s As Variant) As Variant
    Do While Not inOrder(s)
        Debug.Print Join(s, ", ")
        s = Knuth(s)
    Loop
    bogosort = s
End Function
 
Public Sub main()
    Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), ", ")
End Sub
Task: Sequence of non-squares






PHP: <?php

	for($i=1;$i<=22;$i++){
		echo($i + floor(1/2 + sqrt($i)) . "\n");
	}

	$found_square=False;
	for($i=1;$i<=1000000;$i++){
		$non_square=$i + floor(1/2 + sqrt($i));
		if(sqrt($non_square)==intval(sqrt($non_square))){
			$found_square=True;
		}
	}
	echo("\n");
	if($found_square){
		echo("Found a square number, so the formula does not always work.");
	} else {
		echo("Up to 1000000, found no square number in the sequence!");
	}
?>



VB: Sub Main()
Dim i&, c&, j#, s$
Const N& = 1000000
   s = "values for n in the range 1 to 22 : "
   For i = 1 To 22
      s = s & ns(i) & ", "
   Next
   For i = 1 To N
      j = Sqr(ns(i))
      If j = CInt(j) Then c = c + 1
   Next
   
   Debug.Print s
   Debug.Print c & " squares less than " & N
End Sub

Private Function ns(l As Long) As Long
   ns = l + Int(1 / 2 + Sqr(l))
End Function
Task: Substring






PHP: <?php
$str = 'abcdefgh';
$n = 2;
$m = 3;
echo substr($str, $n, $m), "\n"; //cde
echo substr($str, $n), "\n"; //cdefgh
echo substr($str, 0, -1), "\n"; //abcdefg
echo substr($str, strpos($str, 'd'), $m), "\n"; //def
echo substr($str, strpos($str, 'de'), $m), "\n"; //def
?>



VB: Public Sub substring()





 
    sentence = "the last thing the man said was the"
    n = 10: m = 5
       
    
    Debug.Print Mid(sentence, n, 5)
    
    Debug.Print Right(sentence, Len(sentence) - n + 1)
    
    Debug.Print Left(sentence, Len(sentence) - 1)
    
    k = InStr(1, sentence, "m")
    Debug.Print Mid(sentence, k, 5)
    
    k = InStr(1, sentence, "aid")
    Debug.Print Mid(sentence, k, 5)
End Sub
Task: Leap year






PHP: <?php
function isLeapYear($year) {
    if ($year % 100 == 0) {
        return ($year % 400 == 0);
    }
    return ($year % 4 == 0);
}



VB: Public Function Leap_year(year As Integer) As Boolean
    Leap_year = (Month(DateSerial(year, 2, 29)) = 2)
End Function
Task: Sorting algorithms_Shell sort






PHP: function shellSort($arr)
{
	$inc = round(count($arr)/2);
	while($inc > 0)
	{
		for($i = $inc; $i < count($arr);$i++){
			$temp = $arr[$i];
			$j = $i;
			while($j >= $inc && $arr[$j-$inc] > $temp)
			{
				$arr[$j] = $arr[$j - $inc];
				$j -= $inc;
			}
			$arr[$j] = $temp;
		}
		$inc = round($inc/2.2);
	}
	return $arr;
}



VB: Sub arrShellSort(ByVal arrData As Variant)
  Dim lngHold, lngGap As Long
  Dim lngCount, lngMin, lngMax As Long
  Dim varItem As Variant
  
  lngMin = LBound(arrData)
  lngMax = UBound(arrData)
  lngGap = lngMin
  Do While (lngGap < lngMax)
    lngGap = 3 * lngGap + 1
  Loop
  Do While (lngGap > 1)
    lngGap = lngGap \ 3
    For lngCount = lngGap + lngMin To lngMax
      varItem = arrData(lngCount)
      lngHold = lngCount
      Do While ((arrData(lngHold - lngGap) > varItem))
        arrData(lngHold) = arrData(lngHold - lngGap)
        lngHold = lngHold - lngGap
        If (lngHold < lngMin + lngGap) Then Exit Do
      Loop
      arrData(lngHold) = varItem
    Next
  Loop
  arrShellSort = arrData
End Sub
Task: Increment a numerical string






PHP: $s = "12345";
$s++;



VB:     Dim s As String = "123"

    s = CStr(CInt("123") + 1)
    
    s = (CInt("123") + 1).ToString
Task: Strip a set of characters from a string






PHP: <?php
function stripchars($s, $chars) {
    return str_replace(str_split($chars), "", $s);
}

echo stripchars("She was a soul stripper. She took my heart!", "aei"), "\n";
?>



VB: Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean)
Dim i As Integer, stReplace As String
    If bSpace = True Then
        stReplace = " "
    Else
        stReplace = ""
    End If
    For i = 1 To Len(stStripChars)
        stString = Replace(stString, Mid(stStripChars, i, 1), stReplace)
    Next i
    StripChars = stString
End Function
Task: Averages_Arithmetic mean






PHP: $nums = array(3, 1, 4, 1, 5, 9);
if ($nums)
    echo array_sum($nums) / count($nums), "\n";
else
    echo "0\n";



VB: Private Function mean(v() As Double, ByVal leng As Integer) As Variant
    Dim sum As Double, i As Integer
    sum = 0: i = 0
    For i = 0 To leng - 1
        sum = sum + vv
    Next i
    If leng = 0 Then
        mean = CVErr(xlErrDiv0)
    Else
        mean = sum / leng
    End If
End Function
Public Sub main()
    Dim v(4) As Double
    Dim i As Integer, leng As Integer
    v(0) = 1#
    v(1) = 2#
    v(2) = 2.178
    v(3) = 3#
    v(4) = 3.142
    For leng = 5 To 0 Step -1
        Debug.Print "mean[";
        For i = 0 To leng - 1
            Debug.Print IIf(i, "; " & v(i), "" & v(i));
        Next i
        Debug.Print "] = "; mean(v, leng)
    Next leng
End Sub
Task: Forward difference






PHP: <?php

function forwardDiff($anArray, $times = 1) {
  if ($times <= 0) { return $anArray; }
  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { 
    $accumilation[] = $anArray[$i] - $anArray[$i - 1];
  }
  if ($times === 1) { return $accumilation; }
  return forwardDiff($accumilation, $times - 1);
}

class ForwardDiffExample extends PweExample {
  
  function _should_run_empty_array_for_single_elem() {
    $expected = array($this->rand()->int());
    $this->spec(forwardDiff($expected))->shouldEqual(array());
  }
  
  function _should_give_diff_of_two_elem_as_single_elem() {
    $twoNums = array($this->rand()->int(), $this->rand()->int());
    $expected = array($twoNums[1] - $twoNums[0]);
    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);
  }
  
  function _should_compute_correct_forward_diff_for_longer_arrays() {
    $diffInput = array(10, 2, 9, 6, 5);
    $expected  = array(-8, 7, -3, -1);
    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);
  }
  
  function _should_apply_more_than_once_if_specified() {
    $diffInput = array(4, 6, 9, 3, 4);
    $expectedAfter1 = array(2, 3, -6, 1);
    $expectedAfter2 = array(1, -9, 7);
    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);
    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);
  }
  
  function _should_return_array_unaltered_if_no_times() {
    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);
  }
  
}



VB: Module ForwardDifference

    Sub Main()
        Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73})
        For i As UInteger = 0 To 9
            Console.WriteLine(String.Join(" ", (From n In Difference(i, lNum) Select String.Format("{0,5}", n)).ToArray()))
        Next
        Console.ReadKey()
    End Sub

    Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer)
        If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException("Level", "Level must be less than number of items in Numbers")

        For i As Integer = 1 To Level
            Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _
                       Select Numbers(n + 1) - Numbers(n)).ToList()
        Next

        Return Numbers
    End Function

End Module
Task: Primality by trial division






PHP: <?php
function prime($a) {
  if (($a % 2 == 0 && $a != 2) || $a < 2)
    return false;
  $limit = sqrt($a);
  for ($i = 2; $i <= $limit; $i++)
    if ($a % $i == 0)
      return false;
  return true;
}

foreach (range(1, 100) as $x)
  if (prime($x)) echo "$x\n";

?>



VB: Option Explicit

Sub FirstTwentyPrimes()
Dim count As Integer, i As Long, t(19) As String
   Do
      i = i + 1
      If IsPrime(i) Then
         t(count) = i
         count = count + 1
      End If
   Loop While count <= UBound(t)
   Debug.Print Join(t, ", ")
End Sub

Function IsPrime(Nb As Long) As Boolean
   If Nb = 2 Then
      IsPrime = True
   ElseIf Nb < 2 Or Nb Mod 2 = 0 Then
      Exit Function
   Else
      Dim i As Long
      For i = 3 To Sqr(Nb) Step 2
         If Nb Mod i = 0 Then Exit Function
      Next
      IsPrime = True
   End If
End Function
Task: Evaluate binomial coefficients






PHP: <?php
$n=5;
$k=3;
function factorial($val){
    for($f=2;$val-1>1;$f*=$val--);
    return $f;
}
$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));
echo $binomial_coefficient;
?>



VB: Function binomial(n,k)
	binomial = factorial(n)/(factorial(n-k)*factorial(k))
End Function

Function factorial(n)
	If n = 0 Then
		factorial = 1
	Else
		For i = n To 1 Step -1
			If i = n Then
				factorial = n
			Else
				factorial = factorial * i
			End If
		Next
	End If
End Function


WScript.StdOut.Write "the binomial coefficient of 5 and 3 = " & binomial(5,3)
WScript.StdOut.WriteLine
Task: Collections






PHP: <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>



VB: Dim coll As New Collection
coll.Add "apple"
coll.Add "banana"
Task: Bitwise operations



C#: static void bitwise(int a, int b)
        {
            Console.WriteLine("a and b is {0}", a & b);
            Console.WriteLine("a or b is {0}", a | b);
            Console.WriteLine("a xor b is {0}", a ^ b);
            Console.WriteLine("not a is {0}", ~a);
            Console.WriteLine("a lshift b is {0}", a << b);
            Console.WriteLine("a arshift b is {0}", a >> b); 
                                                             
            uint c = (uint)a;
            Console.WriteLine("c rshift b is {0}", c >> b); 
                                                            
            
        }



Java: module BitwiseOps
    {
    @Inject Console console;
    void run()
        {
        for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])  
            {
            static String hex(Int64 n)   
                {
                
                return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();
                }

            console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):
                           |  {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}
                           |  {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}
                           |  {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}
                           |  NOT {hex(n1)} = {hex(~n1)}
                           |  left shift {hex(n1)} by {n2} = {hex(n1 << n2)}
                           |  right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}
                           |  right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}
                           |  left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}
                           |  right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}
                           |  leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}
                           |  rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}
                           |  leading zero count of {hex(n1)} = {n1.leadingZeroCount}
                           |  trailing zero count of {hex(n1)} = {n1.trailingZeroCount}
                           |  bit count (aka "population") of {hex(n1)} = {n1.bitCount}
                           |  reversed bits of {hex(n1)} = {hex(n1.reverseBits())}
                           |  reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}
                           |
                         );
            }
        }
    }
Task: Read a file line by line



C#: foreach (string readLine in File.ReadLines("FileName"))
  DoSomething(readLine);



Java: import java.io.BufferedReader;
import java.io.FileReader;


public class ReadFileByLines {
    private static void processLine(int lineNo, String line) {
        
    }

    public static void main(String[] args) {
        for (String filename : args) {
            BufferedReader br = null;
            FileReader fr = null;
            try {
                fr = new FileReader(filename);
                br = new BufferedReader(fr);
                String line;
                int lineNo = 0;
                while ((line = br.readLine()) != null) {
                    processLine(++lineNo, line);
                }
            }
            catch (Exception x) {
                x.printStackTrace();
            }
            finally {
                if (fr != null) {
                    try {br.close();} catch (Exception ignoreMe) {}
                    try {fr.close();} catch (Exception ignoreMe) {}
                }
            }
        }
    }
}
Task: Doubly-linked list_Element insertion



C#: static void InsertAfter(Link prev, int i)
{
    if (prev.next != null)
    {
        prev.next.prev = new Link() { item = i, prev = prev, next = prev.next };
        prev.next = prev.next.prev;
    }
    else
        prev.next = new Link() { item = i, prev = prev };
}



Java: import java.util.LinkedList;

@SuppressWarnings("serial")
public class DoublyLinkedListInsertion<T> extends LinkedList<T> {
   
    public static void main(String[] args) {
        DoublyLinkedListInsertion<String> list = new DoublyLinkedListInsertion<String>();
        list.addFirst("Add First 1");
        list.addFirst("Add First 2");
        list.addFirst("Add First 3");
        list.addFirst("Add First 4");
        list.addFirst("Add First 5");
        traverseList(list);
        
        list.addAfter("Add First 3", "Add New");
        traverseList(list);
    }
    
    
    public void addAfter(T after, T element) {
        int index = indexOf(after);
        if ( index >= 0 ) {
            add(index + 1, element);
        }
        else {
            addLast(element);
        }
    }
    
    private static void traverseList(LinkedList<String> list) {
        System.out.println("Traverse List:");
        for ( int i = 0 ; i < list.size() ; i++ ) {
            System.out.printf("Element number %d - Element value = '%s'%n", i, list.get(i));
        }
        System.out.println();
    }
    
}