WeixiangYan/CodeTransOcean huggingface dataset:
Task: Polynomial long division

C: #include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <assert.h>
#include <gsl/gsl_vector.h>

#define MAX(A,B) (((A)>(B))?(A):(B))

void reoshift(gsl_vector *v, int h)
{
  if ( h > 0 ) {
    gsl_vector *temp = gsl_vector_alloc(v->size);
    gsl_vector_view p = gsl_vector_subvector(v, 0, v->size - h);
    gsl_vector_view p1 = gsl_vector_subvector(temp, h, v->size - h);
    gsl_vector_memcpy(&p1.vector, &p.vector);
    p = gsl_vector_subvector(temp, 0, h);
    gsl_vector_set_zero(&p.vector);
    gsl_vector_memcpy(v, temp);
    gsl_vector_free(temp);
  }
}

gsl_vector *poly_long_div(gsl_vector *n, gsl_vector *d, gsl_vector **r)
{
  gsl_vector *nt = NULL, *dt = NULL, *rt = NULL, *d2 = NULL, *q = NULL;
  int gn, gt, gd;

  if ( (n->size >= d->size) && (d->size > 0) && (n->size > 0) ) {
    nt = gsl_vector_alloc(n->size); assert(nt != NULL);
    dt = gsl_vector_alloc(n->size); assert(dt != NULL);
    rt = gsl_vector_alloc(n->size); assert(rt != NULL);
    d2 = gsl_vector_alloc(n->size); assert(d2 != NULL);
    gsl_vector_memcpy(nt, n);
    gsl_vector_set_zero(dt); gsl_vector_set_zero(rt);
    gsl_vector_view p = gsl_vector_subvector(dt, 0, d->size);
    gsl_vector_memcpy(&p.vector, d);
    gsl_vector_memcpy(d2, dt);
    gn = n->size - 1;
    gd = d->size - 1;
    gt = 0;

    while( gsl_vector_get(d, gd) == 0 ) gd--;
    
    while ( gn >= gd ) {
      reoshift(dt, gn-gd);
      double v = gsl_vector_get(nt, gn)/gsl_vector_get(dt, gn);
      gsl_vector_set(rt, gn-gd, v);
      gsl_vector_scale(dt, v);
      gsl_vector_sub(nt, dt);
      gt = MAX(gt, gn-gd);
      while( (gn>=0) && (gsl_vector_get(nt, gn) == 0.0) ) gn--;
      gsl_vector_memcpy(dt, d2);
    }

    q = gsl_vector_alloc(gt+1); assert(q != NULL);
    p = gsl_vector_subvector(rt, 0, gt+1);
    gsl_vector_memcpy(q, &p.vector);
    if ( r != NULL ) {
      if ( (gn+1) > 0 ) {
	*r = gsl_vector_alloc(gn+1); assert( *r != NULL );
	p = gsl_vector_subvector(nt, 0, gn+1);
	gsl_vector_memcpy(*r, &p.vector);
      } else {
	*r = gsl_vector_alloc(1); assert( *r != NULL );
	gsl_vector_set_zero(*r);
      }
    }
    gsl_vector_free(nt); gsl_vector_free(dt);
    gsl_vector_free(rt); gsl_vector_free(d2);
    return q;
  } else {
    q = gsl_vector_alloc(1); assert( q != NULL );
    gsl_vector_set_zero(q);
    if ( r != NULL ) {
      *r = gsl_vector_alloc(n->size); assert( *r != NULL );
      gsl_vector_memcpy(*r, n);
    }
    return q;
  } 
}

void poly_print(gsl_vector *p)
{
  int i;
  for(i=p->size-1; i >= 0; i--) {
    if ( i > 0 ) 
      printf("%lfx^%d + ", 
	     gsl_vector_get(p, i), i);
    else
      printf("%lf\n", gsl_vector_get(p, i));
  }
}

gsl_vector *create_poly(int d, ...)
{
  va_list al;
  int i;
  gsl_vector *r = NULL;

  va_start(al, d);
  r = gsl_vector_alloc(d); assert( r != NULL );
  
  for(i=0; i < d; i++)
    gsl_vector_set(r, i, va_arg(al, double));

  return r;
}
Task: Polynomial long division


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

using namespace std;
typedef vector<double> Poly;




void Print(char name, const Poly &A) {
	cout << name << "(" << A.size()-1 << ") = [ ";
	copy(A.begin(), A.end(), ostream_iterator<decltype(A[0])>(cout, " "));
	cout << "]\n";
}

int main() {
	Poly N, D, d, q, r;        
	size_t dN, dD, dd, dq, dr; 
	size_t i;                  

	
	cout << "Enter the degree of N: ";
	cin >> dN;
	cout << "Enter the degree of D: "; 
	cin >> dD;
	dq = dN-dD;  
	dr = dN-dD;

	if( dD < 1 || dN < 1 ) {
		cerr << "Error: degree of D and N must be positive.\n";
		return 1;
	}

	
	N.resize(dN+1);
	cout << "Enter the coefficients of N:"<<endl;  
	for ( i = 0; i <= dN; i++ ) {
		cout << "N[" << i << "]= ";
		cin >> N[i];
	}

	D.resize(dN+1);
	cout << "Enter the coefficients of D:"<<endl;	
	for ( i = 0; i <= dD; i++ ) {
		cout << "D[" << i << "]= ";
		cin >> D[i];
	}

	d.resize(dN+1);
	q.resize(dq+1);
	r.resize(dr+1);

	cout << "-- Procedure --" << endl << endl;
	if( dN >= dD ) {
		while(dN >= dD) {
			
			d.assign(d.size(), 0);

			for( i = 0 ; i <= dD ; i++ )
				d[i+dN-dD] = D[i];
			dd = dN;

			Print( 'd', d );

			
			q[dN-dD] = N[dN]/d[dd];

			Print( 'q', q );

			
			for( i = 0 ; i < dq + 1 ; i++ )
				d[i] = d[i] * q[dN-dD];

			Print( 'd', d );

			
			for( i = 0 ; i < dN + 1 ; i++ )
				N[i] = N[i] - d[i];
			dN--;

			Print( 'N', N );
			cout << "-----------------------" << endl << endl;

		}
	}

	
	for( i = 0 ; i <= dN ; i++ )
		r[i] = N[i];

	cout << "=========================" << endl << endl;
	cout << "-- Result --" << endl << endl;

	Print( 'q', q );
	Print( 'r', r );
}
Task: Polynomial long division







Python: 

from itertools import izip

def degree(poly):
    while poly and poly[-1] == 0:
        poly.pop()   
    return len(poly)-1

def poly_div(N, D):
    dD = degree(D)
    dN = degree(N)
    if dD < 0: raise ZeroDivisionError
    if dN >= dD:
        q = [0] * dN
        while dN >= dD:
            d = [0]*(dN - dD) + D
            mult = q[dN - dD] = N[-1] / float(d[-1])
            d = [coeff*mult for coeff in d]
            N = [coeffN - coeffd for coeffN, coeffd in izip(N, d)]
            dN = degree(N)
        r = N
    else:
        q = [0]
        r = N
    return q, r

if __name__ == '__main__':
    print "POLYNOMIAL LONG DIVISION"
    N = [-42, 0, -12, 1]
    D = [-3, 1, 0, 0]
    print "  %s / %s =" % (N,D),
    print " %s remainder %s" % poly_div(N, D)
Task: Polynomial long division








VB: Option Base 1
Function degree(p As Variant)
    For i = UBound(p) To 1 Step -1
        If p(i) <> 0 Then
            degree = i
            Exit Function
        End If
    Next i
    degree = -1
End Function
 
Function poly_div(ByVal n As Variant, ByVal d As Variant) As Variant
    If UBound(d) < UBound(n) Then
        ReDim Preserve d(UBound(n))
    End If
    Dim dn As Integer: dn = degree(n)
    Dim dd As Integer: dd = degree(d)
    If dd < 0 Then
        poly_div = CVErr(xlErrDiv0)
        Exit Function
    End If
    Dim quot() As Integer
    ReDim quot(dn)
    Do While dn >= dd
        Dim k As Integer: k = dn - dd
        Dim qk As Integer: qk = n(dn) / d(dd)
        quot(k + 1) = qk
        Dim d2() As Variant
        d2 = d
        ReDim Preserve d2(UBound(d) - k)
        For i = 1 To UBound(d2)
            n(UBound(n) + 1 - i) = n(UBound(n) + 1 - i) - d2(UBound(d2) + 1 - i) * qk
        Next i
        dn = degree(n)
    Loop
    poly_div = Array(quot, n) 
End Function
 
Function poly(si As Variant) As String

    Dim r As String
    For t = UBound(si) To 1 Step -1
        Dim sit As Integer: sit = si(t)
        If sit <> 0 Then
            If sit = 1 And t > 1 Then
                r = r & IIf(r = "", "", " + ")
            Else
                If sit = -1 And t > 1 Then
                    r = r & IIf(r = "", "-", " - ")
                Else
                    If r <> "" Then
                        r = r & IIf(sit < 0, " - ", " + ")
                        sit = Abs(sit)
                    End If
                    r = r & CStr(sit)
                End If
            End If
            r = r & IIf(t > 1, "x" & IIf(t > 2, t - 1, ""), "")
        End If
    Next t
    If r = "" Then r = "0"
    poly = r
End Function
 
Function polyn(s As Variant) As String
    Dim t() As String
    ReDim t(2 * UBound(s))
    For i = 1 To 2 * UBound(s) Step 2
        t(i) = poly(s((i + 1) / 2))
    Next i
    t(1) = String$(45 - Len(t(1)) - Len(t(3)), " ") & t(1)
    t(2) = "/"
    t(4) = "="
    t(6) = "rem"
    polyn = Join(t, " ")
End Function
 
Public Sub main()
    Dim tests(7) As Variant
    tests(1) = Array(Array(-42, 0, -12, 1), Array(-3, 1))
    tests(2) = Array(Array(-3, 1), Array(-42, 0, -12, 1))
    tests(3) = Array(Array(-42, 0, -12, 1), Array(-3, 1, 1))
    tests(4) = Array(Array(2, 3, 1), Array(1, 1))
    tests(5) = Array(Array(3, 5, 6, -4, 1), Array(1, 2, 1))
    tests(6) = Array(Array(3, 0, 7, 0, 0, 0, 0, 0, 3, 0, 0, 1), Array(1, 0, 0, 5, 0, 0, 0, 1))
    tests(7) = Array(Array(-56, 87, -94, -55, 22, -7), Array(2, 0, 1))
    Dim num As Variant, denom As Variant, quot As Variant, rmdr As Variant
    For i = 1 To 7
        num = tests(i)(1)
        denom = tests(i)(2)
        tmp = poly_div(num, denom)
        quot = tmp(1)
        rmdr = tmp(2)
        Debug.Print polyn(Array(num, denom, quot, rmdr))
    Next i
End Sub
Task: Polynomial long division




Go: package main

import "fmt"

func main() {
    n := []float64{-42, 0, -12, 1}
    d := []float64{-3, 1}
    fmt.Println("N:", n)
    fmt.Println("D:", d)
    q, r, ok := pld(n, d)
    if ok {
        fmt.Println("Q:", q)
        fmt.Println("R:", r)
    } else {
        fmt.Println("error")
    }
}

func degree(p []float64) int {
    for d := len(p) - 1; d >= 0; d-- {
        if p[d] != 0 {
            return d
        }
    }
    return -1
}

func pld(nn, dd []float64) (q, r []float64, ok bool) {
    if degree(dd) < 0 {
        return
    }
    nn = append(r, nn...)
    if degree(nn) >= degree(dd) {
        q = make([]float64, degree(nn)-degree(dd)+1)
        for degree(nn) >= degree(dd) {
            d := make([]float64, degree(nn)+1)
            copy(d[degree(nn)-degree(dd):], dd)
            q[degree(nn)-degree(dd)] = nn[degree(nn)] / d[degree(d)]
            for i := range d {
                d[i] *= q[degree(nn)-degree(dd)]
                nn[i] -= d[i]
            }
        }
    }
    return q, nn, true
}
Task: Polynomial long division







Python: 

from itertools import izip

def degree(poly):
    while poly and poly[-1] == 0:
        poly.pop()   
    return len(poly)-1

def poly_div(N, D):
    dD = degree(D)
    dN = degree(N)
    if dD < 0: raise ZeroDivisionError
    if dN >= dD:
        q = [0] * dN
        while dN >= dD:
            d = [0]*(dN - dD) + D
            mult = q[dN - dD] = N[-1] / float(d[-1])
            d = [coeff*mult for coeff in d]
            N = [coeffN - coeffd for coeffN, coeffd in izip(N, d)]
            dN = degree(N)
        r = N
    else:
        q = [0]
        r = N
    return q, r

if __name__ == '__main__':
    print "POLYNOMIAL LONG DIVISION"
    N = [-42, 0, -12, 1]
    D = [-3, 1, 0, 0]
    print "  %s / %s =" % (N,D),
    print " %s remainder %s" % poly_div(N, D)




Fortran: module Polynom
  implicit none

contains

  subroutine poly_long_div(n, d, q, r)
    real, dimension(:), intent(in) :: n, d
    real, dimension(:), intent(out), allocatable :: q
    real, dimension(:), intent(out), allocatable, optional :: r

    real, dimension(:), allocatable :: nt, dt, rt
    integer :: gn, gt, gd

    if ( (size(n) >= size(d)) .and. (size(d) > 0) .and. (size(n) > 0) ) then  
       allocate(nt(size(n)), dt(size(n)), rt(size(n)))

       nt = n
       dt = 0
       dt(1:size(d)) = d
       rt = 0
       gn = size(n)-1
       gd = size(d)-1
       gt = 0

       do while ( d(gd+1) == 0 )
          gd = gd - 1
       end do

       do while( gn >= gd )
          dt = eoshift(dt, -(gn-gd))
          rt(gn-gd+1) = nt(gn+1) / dt(gn+1)
          nt = nt - dt * rt(gn-gd+1)
          gt = max(gt, gn-gd)
          do
             gn = gn - 1
             if ( nt(gn+1) /= 0 ) exit
          end do
          dt = 0
          dt(1:size(d)) = d
       end do

       allocate(q(gt+1))
       q = rt(1:gt+1)
       if ( present(r) ) then
          if ( (gn+1) > 0 ) then
             allocate(r(gn+1))
             r = nt(1:gn+1)
          else
             allocate(r(1))
             r = 0.0
          end if
       end if
       deallocate(nt, dt, rt)
    else
       allocate(q(1))
       q = 0
       if ( present(r) ) then
          allocate(r(size(n)))
          r = n
       end if
    end if

  end subroutine poly_long_div

  subroutine poly_print(p)
    real, dimension(:), intent(in) :: p

    integer :: i

    do i = size(p), 1, -1
       if ( i > 1 ) then
          write(*, '(F0.2,"x^",I0," + ")', advance="no") p(i), i-1
       else
          write(*, '(F0.2)') p(i)
       end if
    end do

  end subroutine poly_print

end module Polynom
Task: Visualize a tree



C#: using System;

public static class VisualizeTree
{
    public static void Main() {
        "A".t(
            "B0".t(
                "C1",
                "C2".t(
                    "D".t("E1", "E2", "E3")),
                "C3".t(
                    "F1",
                    "F2",
                    "F3".t("G"),
                    "F4".t("H1", "H2"))),
            "B1".t(
                "K1",
                "K2".t(
                    "L1".t("M"),
                    "L2",
                    "L3"),
                "K3")
        ).Print();
    }

    private static Tree t(this string value, params Tree[] children) => new Tree(value, children);

    private static void Print(this Tree tree) => tree.Print(true, "");

    private static void Print(this Tree tree, bool last, string prefix) {
        (string current, string next) = last
            ? (prefix + "└─" + tree.Value, prefix + "  ")
            : (prefix + "├─" + tree.Value, prefix + "| ");
        Console.WriteLine(current[2..]);
        for (int c = 0; c < tree.Children.Length; c++) {
            tree.Children[c].Print(c == tree.Children.Length - 1, next);
        }
    }

    class Tree
    {
        public Tree(string value, params Tree[] children) => (Value, Children) = (value, children);
        public static implicit operator Tree(string value) => new Tree(value);
        public string Value { get; }
        public Tree[] Children { get; }
    }
    
}









Ada: with Ada.Text_IO, Ada.Directories; 

procedure Directory_Tree is
   
   procedure Print_Tree(Current: String; Indention: Natural := 0) is
      
      function Spaces(N: Natural) return String is
	 (if N= 0 then "" else " " & Spaces(N-1));
      
      use Ada.Directories;
      Search: Search_Type;
      Found: Directory_Entry_Type;
      
   begin
      Start_Search(Search, Current, "");
      while More_Entries(Search) loop
	 Get_Next_Entry(Search, Found);
	 declare
	    Name: String := Simple_Name(Found);
	    Dir: Boolean := Kind(Found) = Directory;
	 begin
	    if Name(Name'First) /= '.' then
               
	       Ada.Text_IO.Put_Line(Spaces(2*Indention) & Simple_Name(Found) 
		  & (if Dir then " (dir)" else ""));
	       if Dir then
		  Print_Tree(Full_Name(Found), Indention + 1);
	       end if;
	    end if;
	 end;	  
     end loop;
   end Print_Tree;
   
begin
   Print_Tree(Ada.Directories.Current_Directory);
end Directory_Tree;
Task: Visualize a tree

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

typedef struct stem_t *stem;
struct stem_t { const char *str; stem next; };

void tree(int root, stem head)
{
	static const char *sdown = "  |", *slast = "  `", *snone = "   ";
	struct stem_t col = {0, 0}, *tail;

	for (tail = head; tail; tail = tail->next) {
		printf("%s", tail->str);
		if (!tail->next) break;
	}

	printf("--%d\n", root);

	if (root <= 1) return;

	if (tail && tail->str == slast)
		tail->str = snone;

	if (!tail)	tail = head = &col;
	else		tail->next = &col;

	while (root) { 
		int r = 1 + (rand() % root);
		root -= r;
		col.str = root ? sdown : slast;

		tree(r, head);
	}

	tail->next = 0;
}

int main(int c, char**v)
{
	int n;
	if (c < 2 || (n = atoi(v[1])) < 0) n = 8;

	tree(n, 0);
	return 0;
}











Ada: with Ada.Text_IO, Ada.Directories; 

procedure Directory_Tree is
   
   procedure Print_Tree(Current: String; Indention: Natural := 0) is
      
      function Spaces(N: Natural) return String is
	 (if N= 0 then "" else " " & Spaces(N-1));
      
      use Ada.Directories;
      Search: Search_Type;
      Found: Directory_Entry_Type;
      
   begin
      Start_Search(Search, Current, "");
      while More_Entries(Search) loop
	 Get_Next_Entry(Search, Found);
	 declare
	    Name: String := Simple_Name(Found);
	    Dir: Boolean := Kind(Found) = Directory;
	 begin
	    if Name(Name'First) /= '.' then
               
	       Ada.Text_IO.Put_Line(Spaces(2*Indention) & Simple_Name(Found) 
		  & (if Dir then " (dir)" else ""));
	       if Dir then
		  Print_Tree(Full_Name(Found), Indention + 1);
	       end if;
	    end if;
	 end;	  
     end loop;
   end Print_Tree;
   
begin
   Print_Tree(Ada.Directories.Current_Directory);
end Directory_Tree;
Task: Visualize a tree


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

class BinarySearchTree {
private:
    struct Node {
        int key;
        Node *left, *right;

        Node(int k) : key(k), left(nullptr), right(nullptr) {
            
        }
    } *root;

public:
    BinarySearchTree() : root(nullptr) {
        
    }

    bool insert(int key) {
        if (root == nullptr) {
            root = new Node(key);
        } else {
            auto n = root;
            Node *parent;
            while (true) {
                if (n->key == key) {
                    return false;
                }

                parent = n;

                bool goLeft = key < n->key;
                n = goLeft ? n->left : n->right;

                if (n == nullptr) {
                    if (goLeft) {
                        parent->left = new Node(key);
                    } else {
                        parent->right = new Node(key);
                    }
                    break;
                }
            }
        }
        return true;
    }

    friend std::ostream &operator<<(std::ostream &, const BinarySearchTree &);
};

template<typename T>
void display(std::ostream &os, const T *n) {
    if (n != nullptr) {
        os << "Node(";

        display(os, n->left);

        os << ',' << n->key << ',';

        display(os, n->right);

        os << ")";
    } else {
        os << '-';
    }
}

std::ostream &operator<<(std::ostream &os, const BinarySearchTree &bst) {
    display(os, bst.root);
    return os;
}

int main() {
    std::default_random_engine generator;
    std::uniform_int_distribution<int> distribution(0, 200);
    auto rng = std::bind(distribution, generator);

    BinarySearchTree tree;

    tree.insert(100);
    for (size_t i = 0; i < 20; i++) {
        tree.insert(rng());
    }
    std::cout << tree << '\n';

    return 0;
}










Ada: with Ada.Text_IO, Ada.Directories; 

procedure Directory_Tree is
   
   procedure Print_Tree(Current: String; Indention: Natural := 0) is
      
      function Spaces(N: Natural) return String is
	 (if N= 0 then "" else " " & Spaces(N-1));
      
      use Ada.Directories;
      Search: Search_Type;
      Found: Directory_Entry_Type;
      
   begin
      Start_Search(Search, Current, "");
      while More_Entries(Search) loop
	 Get_Next_Entry(Search, Found);
	 declare
	    Name: String := Simple_Name(Found);
	    Dir: Boolean := Kind(Found) = Directory;
	 begin
	    if Name(Name'First) /= '.' then
               
	       Ada.Text_IO.Put_Line(Spaces(2*Indention) & Simple_Name(Found) 
		  & (if Dir then " (dir)" else ""));
	       if Dir then
		  Print_Tree(Full_Name(Found), Indention + 1);
	       end if;
	    end if;
	 end;	  
     end loop;
   end Print_Tree;
   
begin
   Print_Tree(Ada.Directories.Current_Directory);
end Directory_Tree;
Task: Visualize a tree




Go: package main

import (
    "encoding/json"
    "fmt"
    "log"
)

type Node struct {
    Name     string
    Children []*Node
}

func main() {
    tree := &Node{"root", []*Node{
        &Node{"a", []*Node{
            &Node{"d", nil},
            &Node{"e", []*Node{
                &Node{"f", nil},
            }}}},
        &Node{"b", nil},
        &Node{"c", nil},
    }}
    b, err := json.MarshalIndent(tree, "", "   ")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(b))
}








Ada: with Ada.Text_IO, Ada.Directories; 

procedure Directory_Tree is
   
   procedure Print_Tree(Current: String; Indention: Natural := 0) is
      
      function Spaces(N: Natural) return String is
	 (if N= 0 then "" else " " & Spaces(N-1));
      
      use Ada.Directories;
      Search: Search_Type;
      Found: Directory_Entry_Type;
      
   begin
      Start_Search(Search, Current, "");
      while More_Entries(Search) loop
	 Get_Next_Entry(Search, Found);
	 declare
	    Name: String := Simple_Name(Found);
	    Dir: Boolean := Kind(Found) = Directory;
	 begin
	    if Name(Name'First) /= '.' then
               
	       Ada.Text_IO.Put_Line(Spaces(2*Indention) & Simple_Name(Found) 
		  & (if Dir then " (dir)" else ""));
	       if Dir then
		  Print_Tree(Full_Name(Found), Indention + 1);
	       end if;
	    end if;
	 end;	  
     end loop;
   end Print_Tree;
   
begin
   Print_Tree(Ada.Directories.Current_Directory);
end Directory_Tree;
Task: Visualize a tree





Java: public class VisualizeTree {
    public static void main(String[] args) {
        BinarySearchTree tree = new BinarySearchTree();

        tree.insert(100);
        for (int i = 0; i < 20; i++)
            tree.insert((int) (Math.random() * 200));
        tree.display();
    }
}

class BinarySearchTree {
    private Node root;

    private class Node {
        private int key;
        private Node left, right;

        Node(int k) {
            key = k;
        }
    }

    public boolean insert(int key) {
        if (root == null)
            root = new Node(key);
        else {
            Node n = root;
            Node parent;
            while (true) {
                if (n.key == key)
                    return false;

                parent = n;

                boolean goLeft = key < n.key;
                n = goLeft ? n.left : n.right;

                if (n == null) {
                    if (goLeft) {
                        parent.left = new Node(key);
                    } else {
                        parent.right = new Node(key);
                    }
                    break;
                }
            }
        }
        return true;
    }

    public void display() {
        final int height = 5, width = 64;

        int len = width * height * 2 + 2;
        StringBuilder sb = new StringBuilder(len);
        for (int i = 1; i <= len; i++)
            sb.append(i < len - 2 && i % width == 0 ? "\n" : ' ');

        displayR(sb, width / 2, 1, width / 4, width, root, " ");
        System.out.println(sb);
    }

    private void displayR(StringBuilder sb, int c, int r, int d, int w, Node n,
            String edge) {
        if (n != null) {
            displayR(sb, c - d, r + 2, d / 2, w, n.left, " /");

            String s = String.valueOf(n.key);
            int idx1 = r * w + c - (s.length() + 1) / 2;
            int idx2 = idx1 + s.length();
            int idx3 = idx1 - w;
            if (idx2 < sb.length())
                sb.replace(idx1, idx2, s).replace(idx3, idx3 + 2, edge);

            displayR(sb, c + d, r + 2, d / 2, w, n.right, "\\ ");
        }
    }
}







Ada: with Ada.Text_IO, Ada.Directories; 

procedure Directory_Tree is
   
   procedure Print_Tree(Current: String; Indention: Natural := 0) is
      
      function Spaces(N: Natural) return String is
	 (if N= 0 then "" else " " & Spaces(N-1));
      
      use Ada.Directories;
      Search: Search_Type;
      Found: Directory_Entry_Type;
      
   begin
      Start_Search(Search, Current, "");
      while More_Entries(Search) loop
	 Get_Next_Entry(Search, Found);
	 declare
	    Name: String := Simple_Name(Found);
	    Dir: Boolean := Kind(Found) = Directory;
	 begin
	    if Name(Name'First) /= '.' then
               
	       Ada.Text_IO.Put_Line(Spaces(2*Indention) & Simple_Name(Found) 
		  & (if Dir then " (dir)" else ""));
	       if Dir then
		  Print_Tree(Full_Name(Found), Indention + 1);
	       end if;
	    end if;
	 end;	  
     end loop;
   end Print_Tree;
   
begin
   Print_Tree(Ada.Directories.Current_Directory);
end Directory_Tree;