WeixiangYan/CodeTransOcean huggingface dataset:
Task: Self-describing numbers

C: #include <stdio.h>

inline int self_desc(unsigned long long xx)
{
	register unsigned int d, x;
	unsigned char cnt[10] = {0}, dig[10] = {0};
 
	for (d = 0; xx > ~0U; xx /= 10)
		cnt[ dig[d++] = xx % 10 ]++;
 
	for (x = xx; x; x /= 10)
		cnt[ dig[d++] = x % 10 ]++;
 
	while(d-- && dig[x++] == cnt[d]);
 
	return d == -1;
}
 
int main()
{
	int i;
	for (i = 1; i < 100000000; i++) 
		if (self_desc(i)) printf("%d\n", i);
 
	return 0;
}








VB: Function IsSelfDescribing(n)
	IsSelfDescribing = False
	Set digit = CreateObject("Scripting.Dictionary")
	For i = 1 To Len(n)
		k = Mid(n,i,1)
		If digit.Exists(k) Then
			digit.Item(k) = digit.Item(k) + 1
		Else
			digit.Add k,1
		End If	
	Next
	c = 0
	For j = 0 To Len(n)-1
		l = Mid(n,j+1,1)
		If digit.Exists(CStr(j)) Then
			If digit.Item(CStr(j)) = CInt(l) Then
				c = c + 1
			End If
		ElseIf l = 0 Then
			c = c + 1
		Else
			Exit For
		End If
	Next
	If c = Len(n) Then
		IsSelfDescribing = True
	End If
End Function


start_time = Now
s = ""
For m = 1 To 100000000
	If 	IsSelfDescribing(m) Then
		WScript.StdOut.WriteLine m
	End If
Next
end_time = Now
WScript.StdOut.WriteLine "Elapse Time: " & DateDiff("s",start_time,end_time) & " seconds"
Task: Repeat

C: #include <stdio.h>

void repeat(void (*f)(void), unsigned int n) {
 while (n-->0)
  (*f)(); 
}

void example() {
 printf("Example\n");
}

int main(int argc, char *argv[]) {
 repeat(example, 4);
 return 0;
}








VB: Private Sub Repeat(rid As String, n As Integer)
    For i = 1 To n
        Application.Run rid
    Next i
End Sub
 
Private Sub Hello()
    Debug.Print "Hello"
End Sub
 
Public Sub main()
    Repeat "Hello", 5
End Sub
Task: Sparkline in unicode

C: #include<string.h>
#include<stdlib.h>
#include<locale.h>
#include<stdio.h>
#include<wchar.h>
#include<math.h>

int main(int argC,char* argV[])
{
	double* arr,min,max;
	char* str;
	int i,len;
	if(argC == 1)
		printf("Usage : %s <data points separated by spaces or commas>",argV[0]);
	else{
		arr = (double*)malloc((argC-1)*sizeof(double));
		for(i=1;i<argC;i++){
			len = strlen(argV[i]);
			
			if(argV[i][len-1]==','){
				str = (char*)malloc(len*sizeof(char));
				strncpy(str,argV[i],len-1);
				arr[i-1] = atof(str);
				free(str);
			}
			else
				arr[i-1] = atof(argV[i]);
			if(i==1){
				min = arr[i-1];
				max = arr[i-1];
			}
			else{
				min=(min<arr[i-1]?min:arr[i-1]);
				max=(max>arr[i-1]?max:arr[i-1]);
			}
		}
		
		printf("\n%Max : %lf,Min : %lf,Range : %lf\n",max,min,max-min);
		
		setlocale(LC_ALL, "");
		
		for(i=1;i<argC;i++){
			printf("%lc", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7)));
		}
	}
	return 0;
}








VB: 

sub ensure_cscript()
if instrrev(ucase(WScript.FullName),"WSCRIPT.EXE")then
   createobject("wscript.shell").run "CSCRIPT //nologo """ &_
     WScript.ScriptFullName &"""" ,,0
   wscript.quit
 end if
end sub 

class bargraph
  private bar,mn,mx,nn,cnt

  Private sub class_initialize()
     bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_
     chrw(&h2586)&chrw(&h2587)&chrw(&h2588)
     nn=8
  end sub


  public function bg (s)
    a=split(replace(replace(s,","," "),"  "," ")," ")

    mn=999999:mx=-999999:cnt=ubound(a)+1
    for i=0 to ubound(a)
       a(i)=cdbl(trim(a(i)))
       if a(i)>mx then mx=a(i) 
       if a(i)<mn then mn=a(i) 
    next
   
    ss="Data:    "
    for i=0 to ubound(a) :ss=ss & right ("     "& a(i),6) :next
    
    ss=ss+vbcrlf + "sparkline: "  
    
    for i=0 to ubound(a)
       x=scale(a(i))
       
       ss=ss & string(6,mid(bar,x,1))
    next
    bg=ss &vbcrlf & "min: "&mn & "  max: "& mx & _
      " cnt: "& ubound(a)+1 &vbcrlf
  end function   

  private function scale(x)
    if x=<mn then 
      scale=1
    elseif x>=mx then
      scale=nn
    else
      scale=int(nn* (x-mn)/(mx-mn)+1)
    end if  
  end function    

end class

ensure_cscript

set b=new bargraph
wscript.stdout.writeblanklines 2
wscript.echo b.bg("1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1")
wscript.echo b.bg("1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5")
wscript.echo b.bg("0, 1, 19, 20")
wscript.echo b.bg("0, 999, 4000, 4999, 7000, 7999")
set b=nothing

wscript.echo "If bars don
"font to DejaVu Sans Mono or any other that has the bargrph characters" & _
vbcrlf

wscript.stdout.write "Press any key.." : wscript.stdin.read 1
Task: Modular inverse

C: #include <stdio.h>

int mul_inv(int a, int b)
{
	int b0 = b, t, q;
	int x0 = 0, x1 = 1;
	if (b == 1) return 1;
	while (a > 1) {
		q = a / b;
		t = b, b = a % b, a = t;
		t = x0, x0 = x1 - q * x0, x1 = t;
	}
	if (x1 < 0) x1 += b0;
	return x1;
}

int main(void) {
	printf("%d\n", mul_inv(42, 2017));
	return 0;
}








VB: Private Function mul_inv(a As Long, n As Long) As Variant
    If n < 0 Then n = -n
    If a < 0 Then a = n - ((-a) Mod n)
    Dim t As Long: t = 0
    Dim nt As Long: nt = 1
    Dim r As Long: r = n
    Dim nr As Long: nr = a
    Dim q As Long
    Do While nr <> 0
        q = r \ nr
        tmp = t
        t = nt
        nt = tmp - q * nt
        tmp = r
        r = nr
        nr = tmp - q * nr
    Loop
    If r > 1 Then
        mul_inv = "a is not invertible"
    Else
        If t < 0 Then t = t + n
        mul_inv = t
    End If
End Function
Public Sub mi()
    Debug.Print mul_inv(42, 2017)
    Debug.Print mul_inv(40, 1)
    Debug.Print mul_inv(52, -217) 
    Debug.Print mul_inv(-486, 217)
    Debug.Print mul_inv(40, 2018)
End Sub
Task: Hello world_Web server

C: #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <err.h>

char response[] = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n\r\n"
"<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>"
"<style>body { background-color: #111 }"
"h1 { font-size:4cm; text-align: center; color: black;"
" text-shadow: 0 0 2mm red}</style></head>"
"<body><h1>Goodbye, world!</h1></body></html>\r\n";

int main()
{
  int one = 1, client_fd;
  struct sockaddr_in svr_addr, cli_addr;
  socklen_t sin_len = sizeof(cli_addr);

  int sock = socket(AF_INET, SOCK_STREAM, 0);
  if (sock < 0)
    err(1, "can't open socket");

  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));

  int port = 8080;
  svr_addr.sin_family = AF_INET;
  svr_addr.sin_addr.s_addr = INADDR_ANY;
  svr_addr.sin_port = htons(port);

  if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {
    close(sock);
    err(1, "Can't bind");
  }

  listen(sock, 5);
  while (1) {
    client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);
    printf("got connection\n");

    if (client_fd == -1) {
      perror("Can't accept");
      continue;
    }

    write(client_fd, response, sizeof(response) - 1); 
    close(client_fd);
  }
}








VB: Class HTTPSock
Inherits TCPSocket
  Event Sub DataAvailable()
    Dim headers As New InternetHeaders
    headers.AppendHeader("Content-Length", Str(LenB("Goodbye, World!")))
    headers.AppendHeader("Content-Type", "text/plain")
    headers.AppendHeader("Content-Encoding", "identity")
    headers.AppendHeader("Connection", "close")
    Dim data As String = "HTTP/1.1 200 OK" + EndOfLine.Windows + headers.Source + EndOfLine.Windows + EndOfLine.Windows + "Goodbye, World!"
    Me.Write(data)
    Me.Close
  End Sub
End Class

Class HTTPServ
Inherits ServerSocket
  Event Sub AddSocket() As TCPSocket
    Return New HTTPSock
  End Sub
End Class

Class App
Inherits Application
  Event Sub Run(Args() As String)
    Dim sock As New HTTPServ
    sock.Port = 8080
    sock.Listen()
    While True
      App.DoEvents
    Wend
  End Sub
End Class
Task: Sorting algorithms_Pancake sort

C: int pancake_sort(int *list, unsigned int length)
{
    
    if(length<2)
        return 0;

    int i,a,max_num_pos,moves;
    moves=0;

    for(i=length;i>1;i--)
    {
        
        max_num_pos=0;
        for(a=0;a<i;a++)
        {
            if(list[a]>list[max_num_pos])
                max_num_pos=a;
        }

        if(max_num_pos==i-1)
            
            continue;


        
        if(max_num_pos)
        {
            moves++;
            do_flip(list, length, max_num_pos+1);
        }


        
        moves++;
        do_flip(list, length, i);

        

    }

    return moves;
}








VB: 


Public Sub printarray(A)
  For i = LBound(A) To UBound(A)
    Debug.Print A(i),
  Next
  Debug.Print
End Sub

Public Sub Flip(ByRef A, p1, p2, trace)

 If trace Then Debug.Print "we
 Cut = Int((p2 - p1 + 1) / 2)
 For i = 0 To Cut - 1
   
   temp = A(i)
   A(i) = A(p2 - i)
   A(p2 - i) = temp
 Next
End Sub

Public Sub pancakesort(ByRef A(), Optional trace As Boolean = False)


lb = LBound(A)
ub = UBound(A)
Length = ub - lb + 1
If Length <= 1 Then 
  Exit Sub
End If

For i = ub To lb + 1 Step -1
  
  P = lb
  Maximum = A(P)
  For j = lb + 1 To i
    If A(j) > Maximum Then
      P = j
      Maximum = A(j)
    End If
  Next j
  
  If P < i Then
    
    If P > 1 Then
      Flip A, lb, P, trace
      If trace Then printarray A
    End If
    
    Flip A, lb, i, trace
    If trace Then printarray A
  End If
Next i
End Sub


Public Sub TestPancake(Optional trace As Boolean = False)
Dim A()
A = Array(5, 7, 8, 3, 1, 10, 9, 23, 50, 0)
Debug.Print "Initial array:"
printarray A
pancakesort A, trace
Debug.Print "Final array:"
printarray A
End Sub
Task: Pythagorean quadruples

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

#define N 2200

int main(int argc, char **argv){
   int a,b,c,d;
   int r[N+1];
   memset(r,0,sizeof(r));	
   for(a=1; a<=N; a++){
      for(b=a; b<=N; b++){
	 int aabb;
	 if(a&1 && b&1) continue;  
	 aabb=a*a + b*b;
	 for(c=b; c<=N; c++){
	    int aabbcc=aabb + c*c;
	    d=(int)sqrt((float)aabbcc);
	    if(aabbcc == d*d && d<=N) r[d]=1;	
	 }
      }
   }
   for(a=1; a<=N; a++)
      if(!r[a]) printf("%d ",a);	
   printf("\n");
}








VB: Const n = 2200
Public Sub pq()
    Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3
    Dim l(n) As Boolean, l_add(9680000) As Boolean 
    For x = 1 To n
        x2 = x * x
        For y = x To n
            l_add(x2 + y * y) = True
        Next y
    Next x
    For x = 1 To n
        s1 = s
        s = s + 2
        s2 = s
        For y = x + 1 To n
            If l_add(s1) Then l(y) = True
            s1 = s1 + s2
            s2 = s2 + 2
        Next
    Next
    For x = 1 To n
        If Not l(x) Then Debug.Print x;
    Next
    Debug.Print
End Sub
Task: Long stairs

C: #include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) {
    int trial, secs_tot=0, steps_tot=0;     
    int sbeh, slen, wiz, secs;              
    time_t t;
    srand((unsigned) time(&t));             
    printf( "Seconds    steps behind    steps ahead\n" );
    for( trial=1;trial<=10000;trial++ ) {   
        sbeh = 0; slen = 100; secs = 0;     
        while(sbeh<slen) {                  
            sbeh+=1;                        
            for(wiz=1;wiz<=5;wiz++) {       
                if(rand()%slen < sbeh)
                    sbeh+=1;                
                slen+=1;                    
            }
            secs+=1;                        
            if(trial==1&&599<secs&&secs<610)
                printf("%d        %d            %d\n", secs, sbeh, slen-sbeh );
            
        }
        secs_tot+=secs;
        steps_tot+=slen;
    }
    printf( "Average secs taken: %f\n", secs_tot/10000.0 );
    printf( "Average final length of staircase: %f\n", steps_tot/10000.0 ); 
    return 0;
}








VB: Option Explicit
Randomize Timer

Function pad(s,n) 
  If n<0 Then pad= right(space(-n) & s ,-n) Else  pad= left(s& space(n),n) End If 
End Function

Sub print(s)
  On Error Resume Next
  WScript.stdout.WriteLine (s)  
  If  err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit
End Sub

Function Rounds(maxsecs,wiz,a)
  Dim mystep,maxstep,toend,j,i,x,d 
  If IsArray(a) Then d=True: print "seconds behind pending"   
  maxstep=100
  For j=1 To maxsecs
    For i=1 To wiz
      If Int(Rnd*maxstep)<=mystep Then mystep=mystep+1
      maxstep=maxstep+1  
    Next 
    mystep=mystep+1 
    If mystep=maxstep Then Rounds=Array(j,maxstep) :Exit Function
    If d Then
      If j>=a(0) And j<=a(1) Then print pad(j,-7) & pad (mystep,-7) & pad (maxstep-mystep,-8)
    End If     
  Next 
  Rounds=Array(maxsecs,maxstep)
End Function


Dim n,r,a,sumt,sums,ntests,t,maxsecs
ntests=10000
maxsecs=7000
t=timer
a=Array(600,609)
For n=1 To ntests
  r=Rounds(maxsecs,5,a)
  If r(0)<>maxsecs Then 
    sumt=sumt+r(0)
    sums=sums+r(1)
  End if  
  a=""
Next  

print vbcrlf & "Done " & ntests & " tests in " & Timer-t & " seconds" 
print "escaped in " & sumt/ntests  & " seconds with " & sums/ntests & " stairs"
Task: Pseudo-random numbers_Middle-square method

C: #include<stdio.h>
long long seed;
long long random(){
        seed = seed * seed / 1000 % 1000000;
        return seed;
}
int main(){
        seed = 675248;
        for(int i=1;i<=5;i++)
                printf("%lld\n",random());
        return 0;
}








VB: Option Explicit
Dim seed As Long
Sub Main()
    Dim i As Integer
    seed = 675248
    For i = 1 To 5
        Debug.Print Rand
    Next i
End Sub
Function Rand() As Variant
    Dim s As String
    s = CStr(seed ^ 2)
    Do While Len(s) <> 12
        s = "0" + s
    Loop
    seed = Val(Mid(s, 4, 6))
    Rand = seed
End Function
Task: Numbers with prime digits whose sum is 13


C++: #include <cstdio>
#include <vector>
#include <bits/stdc++.h>

using namespace std;

int main() { 
  vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum;
  for (int x : lst) w.push_back({x, x});
  while (w.size() > 0) { auto i = w[0]; w.erase(w.begin());
    for (int x : lst) if ((sum = get<1>(i) + x) == 13)
        printf("%d%d ", get<0>(i), x);
      else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); }
  return 0; }




Java: public class PrimeDigits {
    private static boolean primeDigitsSum13(int n) {
        int sum = 0;
        while (n > 0) {
            int r = n % 10;
            if (r != 2 && r != 3 && r != 5 && r != 7) {
                return false;
            }
            n /= 10;
            sum += r;
        }
        return sum == 13;
    }

    public static void main(String[] args) {
        
        int c = 0;
        for (int i = 1; i < 1_000_000; i++) {
            if (primeDigitsSum13(i)) {
                System.out.printf("%6d ", i);
                if (c++ == 10) {
                    c = 0;
                    System.out.println();
                }
            }
        }
        System.out.println();
    }
}
Task: String comparison


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

template <typename T>
void demo_compare(const T &a, const T &b, const std::string &semantically) {
    std::cout << a << " and " << b << " are " << ((a == b) ? "" : "not ")
              << "exactly " << semantically << " equal." << std::endl;

    std::cout << a << " and " << b << " are " << ((a != b) ? "" : "not ")
              << semantically << "inequal." << std::endl;

    std::cout << a << " is " << ((a < b) ? "" : "not ") << semantically
              << " ordered before " << b << '.' << std::endl;

    std::cout << a << " is " << ((a > b) ? "" : "not ") << semantically
              << " ordered after " << b << '.' << std::endl;
}

int main(int argc, char *argv[]) {
    
    std::string a((argc > 1) ? argv[1] : "1.2.Foo");
    std::string b((argc > 2) ? argv[2] : "1.3.Bar");
    demo_compare<std::string>(a, b, "lexically");

    
    std::transform(a.begin(), a.end(), a.begin(), ::tolower);
    std::transform(b.begin(), b.end(), b.begin(), ::tolower);
    demo_compare<std::string>(a, b, "lexically");

    
    
    double numA, numB;
    std::istringstream(a) >> numA;
    std::istringstream(b) >> numB;
    demo_compare<double>(numA, numB, "numerically");
    return (a == b);
}




Java: public class Compare
{
	
    
    public static void compare (String A, String B)
    {
        if (A.equals(B))
            System.debug(A + ' and  ' + B + ' are lexically equal.');
        else
            System.debug(A + ' and  ' + B + ' are not lexically equal.');

        if (A.equalsIgnoreCase(B))
            System.debug(A + ' and  ' + B + ' are case-insensitive lexically equal.');
        else
            System.debug(A + ' and  ' + B + ' are not case-insensitive lexically equal.');
 
        if (A.compareTo(B) < 0)
            System.debug(A + ' is lexically before ' + B);
        else if (A.compareTo(B) > 0)
            System.debug(A + ' is lexically after ' + B);
 
        if (A.compareTo(B) >= 0)
            System.debug(A + ' is not lexically before ' + B);
        if (A.compareTo(B) <= 0)
            System.debug(A + ' is not lexically after ' + B);
 
        System.debug('The lexical relationship is: ' + A.compareTo(B));
    }
}
Task: Take notes on the command line


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

#define note_file "NOTES.TXT"

int main(int argc, char **argv)
{
	if(argc>1)
	{
		ofstream Notes(note_file, ios::app);
		time_t timer = time(NULL);
		if(Notes.is_open())
		{
			Notes << asctime(localtime(&timer)) << '\t';
			for(int i=1;i<argc;i++)
				Notes << argv[i] << ' ';
			Notes << endl;
			Notes.close();
		}
	}
	else
	{
		ifstream Notes(note_file, ios::in);
		string line;
		if(Notes.is_open())
		{
			while(!Notes.eof())
			{
				getline(Notes, line);
				cout << line << endl;
			}
			Notes.close();
		}
	}
}




Java: import java.io.*;
import java.nio.channels.*;
import java.util.Date;

public class TakeNotes {
    public static void main(String[] args) throws IOException {
        if (args.length > 0) {
            PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true));
            ps.println(new Date());
            ps.print("\t" + args[0]);
            for (int i = 1; i < args.length; i++)
                ps.print(" " + args[i]);
            ps.println();
            ps.close();
        } else {
            FileChannel fc = new FileInputStream("notes.txt").getChannel();
            fc.transferTo(0, fc.size(), Channels.newChannel(System.out));
            fc.close();
        }
    }
}
Task: Fibonacci word


C++: #include <string>
#include <map>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <iomanip>

double log2( double number ) {
   return ( log( number ) / log( 2 ) ) ;
}

double find_entropy( std::string & fiboword ) {
   std::map<char , int> frequencies ;
   std::for_each( fiboword.begin( ) , fiboword.end( ) ,
	 [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; 
   int numlen = fiboword.length( ) ;
   double infocontent = 0 ;
   for ( std::pair<char , int> p : frequencies ) {
      double freq = static_cast<double>( p.second ) / numlen ;
      infocontent += freq * log2( freq ) ;
   }
   infocontent *= -1 ;
   return infocontent ;
}

void printLine( std::string &fiboword , int n ) {
   std::cout << std::setw( 5 ) << std::left << n ;
   std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ;
   std::cout << "  " << std::setw( 16 ) << std::setprecision( 13 ) 
      << std::left << find_entropy( fiboword ) ;
   std::cout << "\n" ;
}

int main( ) {
   std::cout << std::setw( 5 ) << std::left << "N" ;
   std::cout << std::setw( 12 ) << std::right << "length" ;
   std::cout << "  " << std::setw( 16 ) << std::left << "entropy" ; 
   std::cout << "\n" ;
   std::string firststring ( "1" ) ;
   int n = 1 ;
   printLine( firststring , n ) ;
   std::string secondstring( "0" ) ;
   n++ ;
   printLine( secondstring , n ) ;
   while ( n < 37 ) {
      std::string resultstring = firststring + secondstring ;
      firststring.assign( secondstring ) ;
      secondstring.assign( resultstring ) ;
      n++ ;
      printLine( resultstring , n ) ;
   }
   return 0 ;
}




Java: import java.util.*;

public class FWord {
    private  String fWord0 = "";
    private  String fWord1 = "";

    private String nextFWord () {
        final String result;
        
        if ( "".equals ( fWord1 ) )      result = "1";
        else if ( "".equals ( fWord0 ) ) result = "0";
        else                             result = fWord1 + fWord0;

        fWord0 = fWord1;
        fWord1 = result;

        return result;
    }

    public static double entropy ( final String source ) {
        final int                        length = source.length ();
        final Map < Character, Integer > counts = new HashMap < Character, Integer > ();
         double                     result = 0.0;
 
        for ( int i = 0; i < length; i++ ) {
            final char c = source.charAt ( i );

            if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 );
            else                            counts.put ( c, 1 );
        }

        for ( final int count : counts.values () ) {
            final double proportion = ( double ) count / length;

            result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) );
        }

        return result;
    }

    public static void main ( final String [] args ) {
        final FWord fWord = new FWord ();

        for ( int i = 0; i < 37;  ) {
            final String word = fWord.nextFWord ();

            System.out.printf ( "%3d %10d %s %n", ++i, word.length (), entropy ( word ) );
        }
    }
}
Task: Find common directory path


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

std::string longestPath( const std::vector<std::string> & , char ) ;

int main( ) {
   std::string dirs[ ] = {
      "/home/user1/tmp/coverage/test" ,
      "/home/user1/tmp/covert/operator" ,
      "/home/user1/tmp/coven/members" } ;
   std::vector<std::string> myDirs ( dirs , dirs + 3 ) ;
   std::cout << "The longest common path of the given directories is "
             << longestPath( myDirs , '/' ) << "!\n" ;
   return 0 ;
}

std::string longestPath( const std::vector<std::string> & dirs , char separator ) {
   std::vector<std::string>::const_iterator vsi = dirs.begin( ) ;
   int maxCharactersCommon = vsi->length( ) ;
   std::string compareString = *vsi ;
   for ( vsi = dirs.begin( ) + 1 ; vsi != dirs.end( ) ; vsi++ ) {
      std::pair<std::string::const_iterator , std::string::const_iterator> p = 
	 std::mismatch( compareString.begin( ) , compareString.end( ) , vsi->begin( ) ) ;
      if (( p.first - compareString.begin( ) ) < maxCharactersCommon ) 
	 maxCharactersCommon = p.first - compareString.begin( ) ;
   }
   std::string::size_type found = compareString.rfind( separator , maxCharactersCommon ) ;
   return compareString.substr( 0 , found ) ;
}




Java: public class CommonPath {
	public static String commonPath(String... paths){
		String commonPath = "";
		String[][] folders = new String[paths.length][];
		for(int i = 0; i < paths.length; i++){
			folders[i] = paths[i].split("/"); 
		}
		for(int j = 0; j < folders[0].length; j++){
			String thisFolder = folders[0][j]; 
			boolean allMatched = true; 
			for(int i = 1; i < folders.length && allMatched; i++){ 
				if(folders[i].length < j){ 
					allMatched = false; 
					break; 
				}
				
				allMatched &= folders[i][j].equals(thisFolder); 
			}
			if(allMatched){ 
				commonPath += thisFolder + "/"; 
			}else{
				break;
			}
		}
		return commonPath;
	}
	
	public static void main(String[] args){
		String[] paths = { "/home/user1/tmp/coverage/test",
				 "/home/user1/tmp/covert/operator",
				 "/home/user1/tmp/coven/members"};
		System.out.println(commonPath(paths));
		
		String[] paths2 = { "/hame/user1/tmp/coverage/test",
				 "/home/user1/tmp/covert/operator",
				 "/home/user1/tmp/coven/members"};
		System.out.println(commonPath(paths2));
	}
}