WeixiangYan/CodeTransOcean huggingface dataset:
Task: Extract file extension







Python: import re
def extractExt(url):
  m = re.search(r'\.[A-Za-z0-9]+$', url)
  return m.group(0) if m else ""


VB: Function fileExt(fname)
	Set fso = CreateObject("Scripting.FileSystemObject")
	Set regex = new regExp
        Dim ret

	regex.pattern = "^[A-Za-z0-9]+$"	
	If regex.test(fso.GetExtensionName(fname)) = False Then
		ret = ""
	Else
		ret = "." & fso.GetExtensionName(fname)
	End If
	fileExt = ret
End Function
 

arr_t = Array("http://example.com/download.tar.gz",	_
	      "CharacterModel.3DS",			_
	      ".desktop",				_
	      "document",				_
	      "document.txt_backup",			_
	      "/etc/pam.d/login")
 
For Each name In arr_t
	Wscript.Echo "NAME:",name
	Wscript.Echo " EXT:","<" & fileExt(name) & ">"
Next
Task: Extract file extension




Go: package main

import "fmt"

func Ext(path string) string {
	for i := len(path) - 1; i >= 0; i-- {
		c := path[i]
		switch {
		case c == '.':
			return path[i:]
		case '0' <= c && c <= '9':
		case 'A' <= c && c <= 'Z':
		case 'a' <= c && c <= 'z':
		default:
			return ""
		}
	}
	return ""
}

func main() {
	type testcase struct {
		input  string
		output string
	}

	tests := []testcase{
		{"http:
		{"CharacterModel.3DS", ".3DS"},
		{".desktop", ".desktop"},
		{"document", ""},
		{"document.txt_backup", ""},
		{"/etc/pam.d/login", ""},
	}

	for _, testcase := range tests {
		ext := Ext(testcase.input)
		if ext != testcase.output {
			panic(fmt.Sprintf("expected %q for %q, got %q",
				testcase.output, testcase.input, ext))
		}
	}
}




Python: import re
def extractExt(url):
  m = re.search(r'\.[A-Za-z0-9]+$', url)
  return m.group(0) if m else ""
Task: Extract file extension





Java: public class Test {
 
    public static void main(String[] args) {
        String[] filenames = { "http:
                               "CharacterModel.3DS",
                               ".desktop",
                               "document",
                               "document.txt_backup",
                               "/etc/pam.d/login"
        };

        for (String filename : filenames) {
            String ext = "null";
            int idx = filename.lastIndexOf('.');
            if (idx != -1) {
                String tmp = filename.substring(idx);
                if (tmp.matches("\\.[a-zA-Z0-9]+")) {
                    ext = tmp;
                }
            }
            System.out.println(filename + " -> " + ext);
        }
    }
}



Python: import re
def extractExt(url):
  m = re.search(r'\.[A-Za-z0-9]+$', url)
  return m.group(0) if m else ""
Task: Extract file extension

C: #include <assert.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>


char* file_ext(const char *string)
{
    assert(string != NULL);
    char *ext = strrchr(string, '.');

    if (ext == NULL)
        return (char*) string + strlen(string);

    for (char *iter = ext + 1; *iter != '\0'; iter++) {
        if (!isalnum((unsigned char)*iter))
            return (char*) string + strlen(string);
    }

    return ext;
}

int main(void)
{
    const char *testcases[][2] = {
        {"http:
        {"CharacterModel.3DS", ".3DS"},
        {".desktop", ".desktop"},
        {"document", ""},
        {"document.txt_backup", ""},
        {"/etc/pam.d/login", ""}
    };

    int exitcode = 0;
    for (size_t i = 0; i < sizeof(testcases) / sizeof(testcases[0]); i++) {
        const char *ext = file_ext(testcases[i][0]);
        if (strcmp(ext, testcases[i][1]) != 0) {
            fprintf(stderr, "expected '%s' for '%s', got '%s'\n",
                testcases[i][1], testcases[i][0], ext);
            exitcode = 1;
        }
    }
    return exitcode;
}






PHP: $tests = [
    ['input'=>'http://example.com/download.tar.gz', 'expect'=>'.gz'],
    ['input'=>'CharacterModel.3DS', 'expect'=>'.3DS'],
    ['input'=>'.desktop', 'expect'=>'.desktop'],
    ['input'=>'document', 'expect'=>''],
    ['input'=>'document.txt_backup', 'expect'=>''],
    ['input'=>'/etc/pam.d/login', 'expect'=>'']
];

foreach ($tests as $key=>$test) {
    $ext = pathinfo($test['input'], PATHINFO_EXTENSION);


    if (ctype_alnum($ext)) {

        $tests[$key]['actual'] = '.'.$ext;
    } else {
        $tests[$key]['actual'] = '';
    }
}
foreach ($tests as $test) {
    printf("%35s -> %s \n", $test['input'],$test['actual']);
}
Task: Extract file extension


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

std::string findExtension ( const std::string & filename ) {
   auto position = filename.find_last_of ( '.' ) ;
   if ( position == std::string::npos )
      return "" ;
   else {
      std::string extension ( filename.substr( position + 1 ) ) ;
      if (std::regex_search (extension, std::regex("[^A-Za-z0-9]") ))
         return "" ;
      else
         return extension ;
   }
}

int main( ) {
   std::vector<std::string> filenames {"picture.jpg" , "http:
      "myuniquefile.longextension" , "IAmAFileWithoutExtension" , "/path/to.my/file" ,
      "file.odd_one", "thisismine." } ;
   std::vector<std::string> extensions( filenames.size( ) ) ;
   std::transform( filenames.begin( ) , filenames.end( ) , extensions.begin( ) , findExtension ) ;
   for ( int i = 0 ; i < filenames.size( ) ; i++ )
      std::cout << filenames[i] << " has extension : " << extensions[i] << " !\n" ;
   return 0 ;
}





PHP: $tests = [
    ['input'=>'http://example.com/download.tar.gz', 'expect'=>'.gz'],
    ['input'=>'CharacterModel.3DS', 'expect'=>'.3DS'],
    ['input'=>'.desktop', 'expect'=>'.desktop'],
    ['input'=>'document', 'expect'=>''],
    ['input'=>'document.txt_backup', 'expect'=>''],
    ['input'=>'/etc/pam.d/login', 'expect'=>'']
];

foreach ($tests as $key=>$test) {
    $ext = pathinfo($test['input'], PATHINFO_EXTENSION);


    if (ctype_alnum($ext)) {

        $tests[$key]['actual'] = '.'.$ext;
    } else {
        $tests[$key]['actual'] = '';
    }
}
foreach ($tests as $test) {
    printf("%35s -> %s \n", $test['input'],$test['actual']);
}
Task: Extract file extension




Go: package main

import "fmt"

func Ext(path string) string {
	for i := len(path) - 1; i >= 0; i-- {
		c := path[i]
		switch {
		case c == '.':
			return path[i:]
		case '0' <= c && c <= '9':
		case 'A' <= c && c <= 'Z':
		case 'a' <= c && c <= 'z':
		default:
			return ""
		}
	}
	return ""
}

func main() {
	type testcase struct {
		input  string
		output string
	}

	tests := []testcase{
		{"http:
		{"CharacterModel.3DS", ".3DS"},
		{".desktop", ".desktop"},
		{"document", ""},
		{"document.txt_backup", ""},
		{"/etc/pam.d/login", ""},
	}

	for _, testcase := range tests {
		ext := Ext(testcase.input)
		if ext != testcase.output {
			panic(fmt.Sprintf("expected %q for %q, got %q",
				testcase.output, testcase.input, ext))
		}
	}
}



PHP: $tests = [
    ['input'=>'http://example.com/download.tar.gz', 'expect'=>'.gz'],
    ['input'=>'CharacterModel.3DS', 'expect'=>'.3DS'],
    ['input'=>'.desktop', 'expect'=>'.desktop'],
    ['input'=>'document', 'expect'=>''],
    ['input'=>'document.txt_backup', 'expect'=>''],
    ['input'=>'/etc/pam.d/login', 'expect'=>'']
];

foreach ($tests as $key=>$test) {
    $ext = pathinfo($test['input'], PATHINFO_EXTENSION);


    if (ctype_alnum($ext)) {

        $tests[$key]['actual'] = '.'.$ext;
    } else {
        $tests[$key]['actual'] = '';
    }
}
foreach ($tests as $test) {
    printf("%35s -> %s \n", $test['input'],$test['actual']);
}
Task: Extract file extension





Java: public class Test {
 
    public static void main(String[] args) {
        String[] filenames = { "http:
                               "CharacterModel.3DS",
                               ".desktop",
                               "document",
                               "document.txt_backup",
                               "/etc/pam.d/login"
        };

        for (String filename : filenames) {
            String ext = "null";
            int idx = filename.lastIndexOf('.');
            if (idx != -1) {
                String tmp = filename.substring(idx);
                if (tmp.matches("\\.[a-zA-Z0-9]+")) {
                    ext = tmp;
                }
            }
            System.out.println(filename + " -> " + ext);
        }
    }
}


PHP: $tests = [
    ['input'=>'http://example.com/download.tar.gz', 'expect'=>'.gz'],
    ['input'=>'CharacterModel.3DS', 'expect'=>'.3DS'],
    ['input'=>'.desktop', 'expect'=>'.desktop'],
    ['input'=>'document', 'expect'=>''],
    ['input'=>'document.txt_backup', 'expect'=>''],
    ['input'=>'/etc/pam.d/login', 'expect'=>'']
];

foreach ($tests as $key=>$test) {
    $ext = pathinfo($test['input'], PATHINFO_EXTENSION);


    if (ctype_alnum($ext)) {

        $tests[$key]['actual'] = '.'.$ext;
    } else {
        $tests[$key]['actual'] = '';
    }
}
foreach ($tests as $test) {
    printf("%35s -> %s \n", $test['input'],$test['actual']);
}
Task: Extract file extension






PHP: $tests = [
    ['input'=>'http://example.com/download.tar.gz', 'expect'=>'.gz'],
    ['input'=>'CharacterModel.3DS', 'expect'=>'.3DS'],
    ['input'=>'.desktop', 'expect'=>'.desktop'],
    ['input'=>'document', 'expect'=>''],
    ['input'=>'document.txt_backup', 'expect'=>''],
    ['input'=>'/etc/pam.d/login', 'expect'=>'']
];

foreach ($tests as $key=>$test) {
    $ext = pathinfo($test['input'], PATHINFO_EXTENSION);


    if (ctype_alnum($ext)) {

        $tests[$key]['actual'] = '.'.$ext;
    } else {
        $tests[$key]['actual'] = '';
    }
}
foreach ($tests as $test) {
    printf("%35s -> %s \n", $test['input'],$test['actual']);
}


Python: import re
def extractExt(url):
  m = re.search(r'\.[A-Za-z0-9]+$', url)
  return m.group(0) if m else ""
Task: Extract file extension






PHP: $tests = [
    ['input'=>'http://example.com/download.tar.gz', 'expect'=>'.gz'],
    ['input'=>'CharacterModel.3DS', 'expect'=>'.3DS'],
    ['input'=>'.desktop', 'expect'=>'.desktop'],
    ['input'=>'document', 'expect'=>''],
    ['input'=>'document.txt_backup', 'expect'=>''],
    ['input'=>'/etc/pam.d/login', 'expect'=>'']
];

foreach ($tests as $key=>$test) {
    $ext = pathinfo($test['input'], PATHINFO_EXTENSION);


    if (ctype_alnum($ext)) {

        $tests[$key]['actual'] = '.'.$ext;
    } else {
        $tests[$key]['actual'] = '';
    }
}
foreach ($tests as $test) {
    printf("%35s -> %s \n", $test['input'],$test['actual']);
}



VB: Function fileExt(fname)
	Set fso = CreateObject("Scripting.FileSystemObject")
	Set regex = new regExp
        Dim ret

	regex.pattern = "^[A-Za-z0-9]+$"	
	If regex.test(fso.GetExtensionName(fname)) = False Then
		ret = ""
	Else
		ret = "." & fso.GetExtensionName(fname)
	End If
	fileExt = ret
End Function
 

arr_t = Array("http://example.com/download.tar.gz",	_
	      "CharacterModel.3DS",			_
	      ".desktop",				_
	      "document",				_
	      "document.txt_backup",			_
	      "/etc/pam.d/login")
 
For Each name In arr_t
	Wscript.Echo "NAME:",name
	Wscript.Echo " EXT:","<" & fileExt(name) & ">"
Next
Task: Floyd's triangle


C++: #include <windows.h>
#include <sstream>
#include <iostream>


using namespace std;


class floyds_tri
{
public:
    floyds_tri()  { lastLineLen = 0; }
    ~floyds_tri() { killArray(); }

    void create( int rows )
    {
	_rows = rows;
	calculateLastLineLen();
	display();
    }

private:
    void killArray()
    {
	if( lastLineLen ) 
	    delete [] lastLineLen;
    }

    void calculateLastLineLen()
    {
	killArray();
	lastLineLen = new BYTE[_rows];

	int s = 1 + ( _rows * ( _rows - 1 ) ) / 2;

	for( int x = s, ix = 0; x < s + _rows; x++, ix++ )
	{
	    ostringstream cvr;
	    cvr << x;
	    lastLineLen[ix] = static_cast<BYTE>( cvr.str().size() );
	}
    }

    void display()
    {
	cout << endl << "Floyd\'s Triangle - " << _rows << " rows" << endl << "===============================================" << endl;
	int number = 1;
	for( int r = 0; r < _rows; r++ )
	{
	    for( int c = 0; c <= r; c++ )
	    {
		ostringstream cvr;
		cvr << number++;
		string str = cvr.str();
		while( str.length() < lastLineLen[c] )
		    str = " " + str;
		cout << str << " ";
	    }
	    cout << endl;
	}
    }

    int _rows;
    BYTE* lastLineLen;
};

int main( int argc, char* argv[] )
{
    floyds_tri t;
    int s;
    while( true )
    {
	cout << "Enter the size of the triangle ( 0 to QUIT ): "; cin >> s;
	if( !s ) return 0;
	if( s > 0 ) t.create( s );

	cout << endl << endl;
	system( "pause" );
    }

    return 0;
}




Go: package main

import "fmt"

func main() {
    floyd(5)
    floyd(14)
}

func floyd(n int) {
    fmt.Printf("Floyd %d:\n", n)
    lowerLeftCorner := n*(n-1)/2 + 1
    lastInColumn := lowerLeftCorner
    lastInRow := 1
    for i, row := 1, 1; row <= n; i++ {
        w := len(fmt.Sprint(lastInColumn))
        if i < lastInRow {
            fmt.Printf("%*d ", w, i)
            lastInColumn++
        } else {
            fmt.Printf("%*d\n", w, i)
            row++
            lastInRow += row
            lastInColumn = lowerLeftCorner
        }
    }
}
Task: Floyd's triangle


C++: #include <windows.h>
#include <sstream>
#include <iostream>


using namespace std;


class floyds_tri
{
public:
    floyds_tri()  { lastLineLen = 0; }
    ~floyds_tri() { killArray(); }

    void create( int rows )
    {
	_rows = rows;
	calculateLastLineLen();
	display();
    }

private:
    void killArray()
    {
	if( lastLineLen ) 
	    delete [] lastLineLen;
    }

    void calculateLastLineLen()
    {
	killArray();
	lastLineLen = new BYTE[_rows];

	int s = 1 + ( _rows * ( _rows - 1 ) ) / 2;

	for( int x = s, ix = 0; x < s + _rows; x++, ix++ )
	{
	    ostringstream cvr;
	    cvr << x;
	    lastLineLen[ix] = static_cast<BYTE>( cvr.str().size() );
	}
    }

    void display()
    {
	cout << endl << "Floyd\'s Triangle - " << _rows << " rows" << endl << "===============================================" << endl;
	int number = 1;
	for( int r = 0; r < _rows; r++ )
	{
	    for( int c = 0; c <= r; c++ )
	    {
		ostringstream cvr;
		cvr << number++;
		string str = cvr.str();
		while( str.length() < lastLineLen[c] )
		    str = " " + str;
		cout << str << " ";
	    }
	    cout << endl;
	}
    }

    int _rows;
    BYTE* lastLineLen;
};

int main( int argc, char* argv[] )
{
    floyds_tri t;
    int s;
    while( true )
    {
	cout << "Enter the size of the triangle ( 0 to QUIT ): "; cin >> s;
	if( !s ) return 0;
	if( s > 0 ) t.create( s );

	cout << endl << endl;
	system( "pause" );
    }

    return 0;
}





Java: public class Floyd {
	public static void main(String[] args){
		printTriangle(5);
		printTriangle(14);
	}
	
	private static void printTriangle(int n){
		System.out.println(n + " rows:");
		for(int rowNum = 1, printMe = 1, numsPrinted = 0;
				rowNum <= n; printMe++){
			int cols = (int)Math.ceil(Math.log10(n*(n-1)/2 + numsPrinted + 2));
			System.out.printf("%"+cols+"d ", printMe);
			if(++numsPrinted == rowNum){
				System.out.println();
				rowNum++;
				numsPrinted = 0;
			}
		}
	}
}
Task: Floyd's triangle


C++: #include <windows.h>
#include <sstream>
#include <iostream>


using namespace std;


class floyds_tri
{
public:
    floyds_tri()  { lastLineLen = 0; }
    ~floyds_tri() { killArray(); }

    void create( int rows )
    {
	_rows = rows;
	calculateLastLineLen();
	display();
    }

private:
    void killArray()
    {
	if( lastLineLen ) 
	    delete [] lastLineLen;
    }

    void calculateLastLineLen()
    {
	killArray();
	lastLineLen = new BYTE[_rows];

	int s = 1 + ( _rows * ( _rows - 1 ) ) / 2;

	for( int x = s, ix = 0; x < s + _rows; x++, ix++ )
	{
	    ostringstream cvr;
	    cvr << x;
	    lastLineLen[ix] = static_cast<BYTE>( cvr.str().size() );
	}
    }

    void display()
    {
	cout << endl << "Floyd\'s Triangle - " << _rows << " rows" << endl << "===============================================" << endl;
	int number = 1;
	for( int r = 0; r < _rows; r++ )
	{
	    for( int c = 0; c <= r; c++ )
	    {
		ostringstream cvr;
		cvr << number++;
		string str = cvr.str();
		while( str.length() < lastLineLen[c] )
		    str = " " + str;
		cout << str << " ";
	    }
	    cout << endl;
	}
    }

    int _rows;
    BYTE* lastLineLen;
};

int main( int argc, char* argv[] )
{
    floyds_tri t;
    int s;
    while( true )
    {
	cout << "Enter the size of the triangle ( 0 to QUIT ): "; cin >> s;
	if( !s ) return 0;
	if( s > 0 ) t.create( s );

	cout << endl << endl;
	system( "pause" );
    }

    return 0;
}







Python: >>> def floyd(rowcount=5):
	rows = [[1]]
	while len(rows) < rowcount:
		n = rows[-1][-1] + 1
		rows.append(list(range(n, n + len(rows[-1]) + 1)))
	return rows

>>> floyd()
[[1], [2, 3], [4, 5, 6], [7, 8, 9, 10], [11, 12, 13, 14, 15]]
>>> def pfloyd(rows=[[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]]):
	colspace = [len(str(n)) for n in rows[-1]]
	for row in rows:
		print( ' '.join('%*i' % space_n for space_n in zip(colspace, row)))

		
>>> pfloyd()
1
2 3
4 5 6
7 8 9 10
>>> pfloyd(floyd(5))
 1
 2  3
 4  5  6
 7  8  9 10
11 12 13 14 15
>>> pfloyd(floyd(14))
 1
 2  3
 4  5  6
 7  8  9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44  45
46 47 48 49 50 51 52 53  54  55
56 57 58 59 60 61 62 63  64  65  66
67 68 69 70 71 72 73 74  75  76  77  78
79 80 81 82 83 84 85 86  87  88  89  90  91
92 93 94 95 96 97 98 99 100 101 102 103 104 105
>>>
Task: Floyd's triangle


C++: #include <windows.h>
#include <sstream>
#include <iostream>


using namespace std;


class floyds_tri
{
public:
    floyds_tri()  { lastLineLen = 0; }
    ~floyds_tri() { killArray(); }

    void create( int rows )
    {
	_rows = rows;
	calculateLastLineLen();
	display();
    }

private:
    void killArray()
    {
	if( lastLineLen ) 
	    delete [] lastLineLen;
    }

    void calculateLastLineLen()
    {
	killArray();
	lastLineLen = new BYTE[_rows];

	int s = 1 + ( _rows * ( _rows - 1 ) ) / 2;

	for( int x = s, ix = 0; x < s + _rows; x++, ix++ )
	{
	    ostringstream cvr;
	    cvr << x;
	    lastLineLen[ix] = static_cast<BYTE>( cvr.str().size() );
	}
    }

    void display()
    {
	cout << endl << "Floyd\'s Triangle - " << _rows << " rows" << endl << "===============================================" << endl;
	int number = 1;
	for( int r = 0; r < _rows; r++ )
	{
	    for( int c = 0; c <= r; c++ )
	    {
		ostringstream cvr;
		cvr << number++;
		string str = cvr.str();
		while( str.length() < lastLineLen[c] )
		    str = " " + str;
		cout << str << " ";
	    }
	    cout << endl;
	}
    }

    int _rows;
    BYTE* lastLineLen;
};

int main( int argc, char* argv[] )
{
    floyds_tri t;
    int s;
    while( true )
    {
	cout << "Enter the size of the triangle ( 0 to QUIT ): "; cin >> s;
	if( !s ) return 0;
	if( s > 0 ) t.create( s );

	cout << endl << endl;
	system( "pause" );
    }

    return 0;
}








VB: Option Explicit
Dim o As String
Sub floyd(L As Integer)
    Dim r, c, m, n As Integer
    n = L * (L - 1) / 2
    m = 1
    For r = 1 To L
        o = o & vbCrLf
        For c = 1 To r
            o = o & Space(Len(CStr(n + c)) - Len(CStr(m))) & m & " "
            m = m + 1
        Next
    Next
End Sub
Sub triangle()
    o = "5 lines"
    Call floyd(5)
    o = o & vbCrLf & "14 lines"
    Call floyd(14)
    With Selection
        .Font.Name = "Courier New"
        .TypeText Text:=o
    End With
End Sub
Task: Floyd's triangle




Go: package main

import "fmt"

func main() {
    floyd(5)
    floyd(14)
}

func floyd(n int) {
    fmt.Printf("Floyd %d:\n", n)
    lowerLeftCorner := n*(n-1)/2 + 1
    lastInColumn := lowerLeftCorner
    lastInRow := 1
    for i, row := 1, 1; row <= n; i++ {
        w := len(fmt.Sprint(lastInColumn))
        if i < lastInRow {
            fmt.Printf("%*d ", w, i)
            lastInColumn++
        } else {
            fmt.Printf("%*d\n", w, i)
            row++
            lastInRow += row
            lastInColumn = lowerLeftCorner
        }
    }
}


Java: public class Floyd {
	public static void main(String[] args){
		printTriangle(5);
		printTriangle(14);
	}
	
	private static void printTriangle(int n){
		System.out.println(n + " rows:");
		for(int rowNum = 1, printMe = 1, numsPrinted = 0;
				rowNum <= n; printMe++){
			int cols = (int)Math.ceil(Math.log10(n*(n-1)/2 + numsPrinted + 2));
			System.out.printf("%"+cols+"d ", printMe);
			if(++numsPrinted == rowNum){
				System.out.println();
				rowNum++;
				numsPrinted = 0;
			}
		}
	}
}
Task: Floyd's triangle





Java: public class Floyd {
	public static void main(String[] args){
		printTriangle(5);
		printTriangle(14);
	}
	
	private static void printTriangle(int n){
		System.out.println(n + " rows:");
		for(int rowNum = 1, printMe = 1, numsPrinted = 0;
				rowNum <= n; printMe++){
			int cols = (int)Math.ceil(Math.log10(n*(n-1)/2 + numsPrinted + 2));
			System.out.printf("%"+cols+"d ", printMe);
			if(++numsPrinted == rowNum){
				System.out.println();
				rowNum++;
				numsPrinted = 0;
			}
		}
	}
}



Python: >>> def floyd(rowcount=5):
	rows = [[1]]
	while len(rows) < rowcount:
		n = rows[-1][-1] + 1
		rows.append(list(range(n, n + len(rows[-1]) + 1)))
	return rows

>>> floyd()
[[1], [2, 3], [4, 5, 6], [7, 8, 9, 10], [11, 12, 13, 14, 15]]
>>> def pfloyd(rows=[[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]]):
	colspace = [len(str(n)) for n in rows[-1]]
	for row in rows:
		print( ' '.join('%*i' % space_n for space_n in zip(colspace, row)))

		
>>> pfloyd()
1
2 3
4 5 6
7 8 9 10
>>> pfloyd(floyd(5))
 1
 2  3
 4  5  6
 7  8  9 10
11 12 13 14 15
>>> pfloyd(floyd(14))
 1
 2  3
 4  5  6
 7  8  9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44  45
46 47 48 49 50 51 52 53  54  55
56 57 58 59 60 61 62 63  64  65  66
67 68 69 70 71 72 73 74  75  76  77  78
79 80 81 82 83 84 85 86  87  88  89  90  91
92 93 94 95 96 97 98 99 100 101 102 103 104 105
>>>
Task: Floyd's triangle





Java: public class Floyd {
	public static void main(String[] args){
		printTriangle(5);
		printTriangle(14);
	}
	
	private static void printTriangle(int n){
		System.out.println(n + " rows:");
		for(int rowNum = 1, printMe = 1, numsPrinted = 0;
				rowNum <= n; printMe++){
			int cols = (int)Math.ceil(Math.log10(n*(n-1)/2 + numsPrinted + 2));
			System.out.printf("%"+cols+"d ", printMe);
			if(++numsPrinted == rowNum){
				System.out.println();
				rowNum++;
				numsPrinted = 0;
			}
		}
	}
}




VB: Option Explicit
Dim o As String
Sub floyd(L As Integer)
    Dim r, c, m, n As Integer
    n = L * (L - 1) / 2
    m = 1
    For r = 1 To L
        o = o & vbCrLf
        For c = 1 To r
            o = o & Space(Len(CStr(n + c)) - Len(CStr(m))) & m & " "
            m = m + 1
        Next
    Next
End Sub
Sub triangle()
    o = "5 lines"
    Call floyd(5)
    o = o & vbCrLf & "14 lines"
    Call floyd(14)
    With Selection
        .Font.Name = "Courier New"
        .TypeText Text:=o
    End With
End Sub
Task: Floyd's triangle




Go: package main

import "fmt"

func main() {
    floyd(5)
    floyd(14)
}

func floyd(n int) {
    fmt.Printf("Floyd %d:\n", n)
    lowerLeftCorner := n*(n-1)/2 + 1
    lastInColumn := lowerLeftCorner
    lastInRow := 1
    for i, row := 1, 1; row <= n; i++ {
        w := len(fmt.Sprint(lastInColumn))
        if i < lastInRow {
            fmt.Printf("%*d ", w, i)
            lastInColumn++
        } else {
            fmt.Printf("%*d\n", w, i)
            row++
            lastInRow += row
            lastInColumn = lowerLeftCorner
        }
    }
}




Python: >>> def floyd(rowcount=5):
	rows = [[1]]
	while len(rows) < rowcount:
		n = rows[-1][-1] + 1
		rows.append(list(range(n, n + len(rows[-1]) + 1)))
	return rows

>>> floyd()
[[1], [2, 3], [4, 5, 6], [7, 8, 9, 10], [11, 12, 13, 14, 15]]
>>> def pfloyd(rows=[[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]]):
	colspace = [len(str(n)) for n in rows[-1]]
	for row in rows:
		print( ' '.join('%*i' % space_n for space_n in zip(colspace, row)))

		
>>> pfloyd()
1
2 3
4 5 6
7 8 9 10
>>> pfloyd(floyd(5))
 1
 2  3
 4  5  6
 7  8  9 10
11 12 13 14 15
>>> pfloyd(floyd(14))
 1
 2  3
 4  5  6
 7  8  9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44  45
46 47 48 49 50 51 52 53  54  55
56 57 58 59 60 61 62 63  64  65  66
67 68 69 70 71 72 73 74  75  76  77  78
79 80 81 82 83 84 85 86  87  88  89  90  91
92 93 94 95 96 97 98 99 100 101 102 103 104 105
>>>