WeixiangYan/CodeTransOcean huggingface dataset:
Task: XML validation




Go: package main

import (
    "fmt"
    "github.com/lestrrat-go/libxml2"
    "github.com/lestrrat-go/libxml2/xsd"
    "io/ioutil"
    "log"
    "os"
)

func check(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    xsdfile := "shiporder.xsd"
    f, err := os.Open(xsdfile)
    check(err)
    defer f.Close()

    buf, err := ioutil.ReadAll(f)
    check(err)

    s, err := xsd.Parse(buf)
    check(err)
    defer s.Free()

    xmlfile := "shiporder.xml"
    f2, err := os.Open(xmlfile)
    check(err)
    defer f2.Close()

    buf2, err := ioutil.ReadAll(f2)
    check(err)

    d, err := libxml2.Parse(buf2)
    check(err)

    if err := s.Validate(d); err != nil {
        for _, e := range err.(xsd.SchemaValidationError).Errors() {
            log.Printf("error: %s", e.Error())
        }
        return
    }

    fmt.Println("Validation of", xmlfile, "against", xsdfile, "successful!")
}





VB: Option explicit

Function fileexists(fn) 
  fileexists= CreateObject("Scripting.FileSystemObject").FileExists(fn)
End Function

Function xmlvalid(strfilename)
  Dim xmldoc,xmldoc2,objSchemas 
  Set xmlDoc = CreateObject("Msxml2.DOMDocument.6.0")
  
  If fileexists(Replace(strfilename,".xml",".dtd")) Then
    xmlDoc.setProperty "ProhibitDTD", False
    xmlDoc.setProperty "ResolveExternals", True 
    xmlDoc.validateOnParse = True
    xmlDoc.async = False
    xmlDoc.load(strFileName)
  ElseIf fileexists(Replace(strfilename,".xml",".xsd")) Then
    xmlDoc.setProperty "ProhibitDTD", True
    xmlDoc.setProperty "ResolveExternals", True 
    xmlDoc.validateOnParse = True
    xmlDoc.async = False
    xmlDoc.load(strFileName)
    
    
    Set xmlDoc2 = CreateObject("Msxml2.DOMDocument.6.0")
    xmlDoc2.validateOnParse = True
    xmlDoc2.async = False
    xmlDoc2.load(Replace (strfilename,".xml",".xsd"))
    
    
    Set objSchemas = CreateObject("MSXML2.XMLSchemaCache.6.0")
    objSchemas.Add "", xmlDoc2
  Else 
    Set xmlvalid= Nothing:Exit Function
  End If
  
  Set xmlvalid=xmldoc.parseError 
End Function



Sub displayerror (parserr) 
  Dim strresult
  If parserr is Nothing Then 
    strresult= "could not find dtd or xsd for " & strFileName
  Else   
    With parserr
     Select Case .errorcode
      Case 0 
        strResult = "Valid: " & strFileName & vbCr
      Case Else
        strResult = vbCrLf & "ERROR! Failed to validate " & _
        strFileName & vbCrLf &.reason & vbCr & _
        "Error code: " & .errorCode & ", Line: " & _
        .line & ", Character: " & _
        .linepos & ", Source: """ & _
        .srcText &  """ - " & vbCrLf 
 
      End Select
    End With
  End If
  WScript.Echo strresult
End Sub


Dim strfilename






strfilename="shiporder.xml"
displayerror xmlvalid (strfilename)
Task: Longest increasing subsequence




Go: package main

import (
  "fmt"
  "sort"
)

type Node struct {
    val int
    back *Node
}

func lis (n []int) (result []int) {
  var pileTops []*Node
  
  for _, x := range n {
    j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })
    node := &Node{ x, nil }
    if j != 0 { node.back = pileTops[j-1] }
    if j != len(pileTops) {
      pileTops[j] = node
    } else {
      pileTops = append(pileTops, node)
    }
  }

  if len(pileTops) == 0 { return []int{} }
  for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {
    result = append(result, node.val)
  }
  
  for i := 0; i < len(result)/2; i++ {
    result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]
  }
  return
}

func main() {
    for _, d := range [][]int{{3, 2, 6, 4, 5, 1},
            {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {
        fmt.Printf("an L.I.S. of %v is %v\n", d, lis(d))
    }
}





VB: Function LIS(arr)
	n = UBound(arr)
	Dim p()
	ReDim p(n)
	Dim m()
	ReDim m(n)
	l = 0
	For i = 0 To n
		lo = 1
		hi = l
		Do While lo <= hi
			middle = Int((lo+hi)/2)
			If arr(m(middle)) < arr(i) Then
				lo = middle + 1
			Else
				hi = middle - 1
			End If
		Loop
		newl = lo
		p(i) = m(newl-1)
		m(newl) = i
		If newL > l Then
			l = newl
		End If
	Next
	Dim s()
	ReDim s(l)
	k = m(l)
	For i = l-1 To 0 Step - 1
		s(i) = arr(k)
		k = p(k)
	Next
	LIS = Join(s,",")
End Function

WScript.StdOut.WriteLine LIS(Array(3,2,6,4,5,1))
WScript.StdOut.WriteLine LIS(Array(0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15))
Task: Call a function




Go: import (
	"image"
	"image/gif"
	"io/ioutil"
	"strings"
	"unicode"
)

func f() (int, float64)  { return 0, 0 }
func g(int, float64) int { return 0 }
func h(string, ...int)   {}





VB: 


Function no_arguments() As String
    no_arguments = "ok"
End Function


Function fixed_number(argument1 As Integer, argument2 As Integer)
    fixed_number = argument1 + argument2
End Function


Function optional_parameter(Optional argument1 = 1) As Integer
    
    optional_parameter = argument1
End Function


Function variable_number(arguments As Variant) As Integer
    variable_number = UBound(arguments)
End Function


Function named_arguments(argument1 As Integer, argument2 As Integer) As Integer
    named_arguments = argument1 + argument2
End Function


Function statement() As String
    Debug.Print "function called as statement"
    statement = "ok"
End Function





Function return_value() As String
    return_value = "ok"
End Function






Sub foo()
    Debug.Print "subroutine",
End Sub

Function bar() As String
    bar = "function"
End Function


Function passed_by_value(ByVal s As String) As String
    s = "written over"
    passed_by_value = "passed by value"
End Function

Function passed_by_reference(ByRef s As String) As String
    s = "written over"
    passed_by_reference = "passed by reference"
End Function





Sub no_parentheses(myargument As String)
    Debug.Print myargument,
End Sub


Public Sub calling_a_function()
    
    Debug.Print "no arguments", , no_arguments
    Debug.Print "no arguments", , no_arguments()
    
    
    
    Debug.Print "fixed_number", , fixed_number(1, 1)
    
    
    Debug.Print "optional parameter", optional_parameter
    Debug.Print "optional parameter", optional_parameter(2)
    
    
    Debug.Print "variable number", variable_number([{"hello", "there"}])
    
    
    
    Debug.Print "named arguments", named_arguments(argument2:=1, argument1:=1)
    
    
    statement
    
    
    s = "no_arguments"
    Debug.Print "first-class context", Application.Run(s)
    
    
    
    returnvalue = return_value
    Debug.Print "obtained return value", returnvalue
    
    
    
    
    foo
    Debug.Print , bar
    
    
    Dim t As String
    t = "unaltered"
    Debug.Print passed_by_value(t), t
    Debug.Print passed_by_reference(t), t
    
    
    
    
    
    no_parentheses "calling a subroutine"
    Debug.Print "does not require parentheses"
    Call no_parentheses("deprecated use")
    Debug.Print "of parentheses"
    
End Sub
Task: One of n lines in a file




Go: package main

import (
    "bufio"
    "fmt"
    "io"
    "math/rand"
    "time"
)







func choseLineRandomly(r io.Reader) (s string, ln int, err error) {
    br := bufio.NewReader(r)
    s, err = br.ReadString('\n')
    if err != nil {
        return
    }
    ln = 1
    lnLast := 1.
    var sLast string
    for {
        
        
        sLast, err = br.ReadString('\n')
        if err == io.EOF {
            return s, ln, nil 
        }
        if err != nil {
            break
        }
        lnLast++
        if rand.Float64() < 1/lnLast {
            s = sLast
            ln = int(lnLast)
        }
    }
    return 
}





func oneOfN(n int, file io.Reader) int {
    _, ln, err := choseLineRandomly(file)
    if err != nil {
        panic(err)
    }
    return ln
}


type simReader int

func (r *simReader) Read(b []byte) (int, error) {
    if *r <= 0 {
        return 0, io.EOF
    }
    b[0] = '\n'
    *r--
    return 1, nil
}

func main() {
    
    
    n := 10
    freq := make([]int, n)
    rand.Seed(time.Now().UnixNano())
    for times := 0; times < 1e6; times++ {
        sr := simReader(n)
        freq[oneOfN(n, &sr)-1]++
    }

    
    fmt.Println(freq)
}





VB: Dim chosen(10)

For j = 1 To 1000000
	c = one_of_n(10)
	chosen(c) = chosen(c) + 1
Next

For k = 1 To 10
	WScript.StdOut.WriteLine k & ". " & chosen(k)
Next 

Function one_of_n(n)
	Randomize
	For i = 1 To n
		If Rnd(1) < 1/i Then
			one_of_n = i
		End If
	Next
End Function
Task: Spelling of ordinal numbers




Go: import (
	"fmt"
	"strings"
)

func main() {
	for _, n := range []int64{
		1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,
	} {
		fmt.Println(sayOrdinal(n))
	}
}

var irregularOrdinals = map[string]string{
	"one":    "first",
	"two":    "second",
	"three":  "third",
	"five":   "fifth",
	"eight":  "eighth",
	"nine":   "ninth",
	"twelve": "twelfth",
}

func sayOrdinal(n int64) string {
	s := say(n)
	i := strings.LastIndexAny(s, " -")
	i++
	
	
	
	
	if x, ok := irregularOrdinals[s[i:]]; ok {
		s = s[:i] + x
	} else if s[len(s)-1] == 'y' {
		s = s[:i] + s[i:len(s)-1] + "ieth"
	} else {
		s = s[:i] + s[i:] + "th"
	}
	return s
}



var small = [...]string{"zero", "one", "two", "three", "four", "five", "six",
	"seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
	"fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}
var tens = [...]string{"", "", "twenty", "thirty", "forty",
	"fifty", "sixty", "seventy", "eighty", "ninety"}
var illions = [...]string{"", " thousand", " million", " billion",
	" trillion", " quadrillion", " quintillion"}

func say(n int64) string {
	var t string
	if n < 0 {
		t = "negative "
		
		n = -n
	}
	switch {
	case n < 20:
		t += small[n]
	case n < 100:
		t += tens[n/10]
		s := n % 10
		if s > 0 {
			t += "-" + small[s]
		}
	case n < 1000:
		t += small[n/100] + " hundred"
		s := n % 100
		if s > 0 {
			t += " " + say(s)
		}
	default:
		
		sx := ""
		for i := 0; n > 0; i++ {
			p := n % 1000
			n /= 1000
			if p > 0 {
				ix := say(p) + illions[i]
				if sx != "" {
					ix += " " + sx
				}
				sx = ix
			}
		}
		t += sx
	}
	return t
}





VB: Private Function ordinal(s As String) As String
    Dim irregs As New Collection
    irregs.Add "first", "one"
    irregs.Add "second", "two"
    irregs.Add "third", "three"
    irregs.Add "fifth", "five"
    irregs.Add "eighth", "eight"
    irregs.Add "ninth", "nine"
    irregs.Add "twelfth", "twelve"
    Dim i As Integer
    For i = Len(s) To 1 Step -1
        ch = Mid(s, i, 1)
        If ch = " " Or ch = "-" Then Exit For
    Next i
    On Error GoTo 1
    ord = irregs(Right(s, Len(s) - i))
    ordinal = Left(s, i) & ord
    Exit Function
1:
    If Right(s, 1) = "y" Then
        s = Left(s, Len(s) - 1) & "ieth"
    Else
        s = s & "th"
    End If
    ordinal = s
End Function
Public Sub ordinals()
    tests = [{1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123, 00123.0, 1.23E2}]
    init
    For i = 1 To UBound(tests)
        Debug.Print ordinal(spell(tests(i)))
    Next i
End Sub
Task: Self-describing numbers




Go: package main

import (
    "fmt"
    "strconv"
    "strings"
)


func sdn(n int64) bool {
    if n >= 1e10 {
        return false
    }
    s := strconv.FormatInt(n, 10)
    for d, p := range s {
        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {
            return false
        }
    }
    return true
}


func main() {
    for n := int64(0); n < 1e10; n++ {
        if sdn(n) {
            fmt.Println(n)
        }
    }
}





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




Go: package main

import "fmt"

func repeat(n int, f func()) {
  for i := 0; i < n; i++ {
    f()
  }
}

func fn() {
  fmt.Println("Example")
}

func main() {
  repeat(4, fn)
}





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: Modular inverse




Go: package main

import (
	"fmt"
	"math/big"
)

func main() {
	a := big.NewInt(42)
	m := big.NewInt(2017)
	k := new(big.Int).ModInverse(a, m)
	fmt.Println(k)
}





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




Go: package main

import (
  "fmt"
  "log"
  "net/http"
)

func main() {
  http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
    fmt.Fprintln(w, "Goodbye, World!")
  })
  log.Fatal(http.ListenAndServe(":8080", nil))
}





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




Go: package main

import "fmt"

func main() {
    list := pancake{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
    fmt.Println("unsorted:", list)

    list.sort()
    fmt.Println("sorted!  ", list)
}

type pancake []int

func (a pancake) sort() {
    for uns := len(a) - 1; uns > 0; uns-- {
        
        lx, lg := 0, a[0]
        for i := 1; i <= uns; i++ {
            if a[i] > lg {
                lx, lg = i, a[i]
            }
        }
        
        a.flip(lx)
        a.flip(uns)
    }
}

func (a pancake) flip(r int) {
    for l := 0; l < r; l, r = l+1, r-1 {
        a[l], a[r] = a[r], a[l]
    }
}





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




Go: package main

import "fmt"

const (
    N = 2200
    N2 = N * N * 2
)

func main() {
    s  := 3 
    var s1, s2 int    
    var r  [N + 1]bool
    var ab [N2 + 1]bool

    for a := 1; a <= N; a++ {
        a2 := a * a
        for b := a; b <= N; b++ {
            ab[a2 + b * b] = true
        }
    }

    for c := 1; c <= N; c++ {
        s1 = s
        s += 2
        s2 = s
        for d := c + 1; d <= N; d++ {
            if ab[s1] {
                r[d] = true
            }
            s1 += s2
            s2 += 2
        }
    }

    for d := 1; d <= N; d++ {
        if !r[d] {
            fmt.Printf("%d ", d)
        }       
    }
    fmt.Println()
}





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




Go: package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rand.Seed(time.Now().UnixNano())
    totalSecs := 0
    totalSteps := 0
    fmt.Println("Seconds    steps behind    steps ahead")
    fmt.Println("-------    ------------    -----------")
    for trial := 1; trial < 10000; trial++ {
        sbeh := 0
        slen := 100
        secs := 0
        for sbeh < slen {
            sbeh++
            for wiz := 1; wiz < 6; wiz++ {
                if rand.Intn(slen) < sbeh {
                    sbeh++
                }
                slen++
            }
            secs++
            if trial == 1 && secs > 599 && secs < 610 {
                fmt.Printf("%d        %d            %d\n", secs, sbeh, slen-sbeh)
            }
        }
        totalSecs += secs
        totalSteps += slen
    }
    fmt.Println("\nAverage secs taken:", float64(totalSecs)/10000)
    fmt.Println("Average final length of staircase:", float64(totalSteps)/10000)
}





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




Go: package main

import "fmt"

func random(seed int) int {
    return seed * seed / 1e3 % 1e6
}

func main() {
    seed := 675248
    for i := 1; i <= 5; i++ {
        seed = random(seed)
        fmt.Println(seed)
    }
}





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: Practical numbers




Go: package main

import (
    "fmt"
    "rcu"
)

func powerset(set []int) [][]int {
    if len(set) == 0 {
        return [][]int{{}}
    }
    head := set[0]
    tail := set[1:]
    p1 := powerset(tail)
    var p2 [][]int
    for _, s := range powerset(tail) {
        h := []int{head}
        h = append(h, s...)
        p2 = append(p2, h)
    }
    return append(p1, p2...)
}

func isPractical(n int) bool {
    if n == 1 {
        return true
    }
    divs := rcu.ProperDivisors(n)
    subsets := powerset(divs)
    found := make([]bool, n) 
    count := 0
    for _, subset := range subsets {
        sum := rcu.SumInts(subset)
        if sum > 0 && sum < n && !found[sum] {
            found[sum] = true
            count++
            if count == n-1 {
                return true
            }
        }
    }
    return false
}

func main() {
    fmt.Println("In the range 1..333, there are:")
    var practical []int
    for i := 1; i <= 333; i++ {
        if isPractical(i) {
            practical = append(practical, i)
        }
    }
    fmt.Println(" ", len(practical), "practical numbers")
    fmt.Println("  The first ten are", practical[0:10])
    fmt.Println("  The final ten are", practical[len(practical)-10:])
    fmt.Println("\n666 is practical:", isPractical(666))
}





VB: Imports System.Collections.Generic, System.Linq, System.Console

Module Module1
    Function soas(ByVal n As Integer, ByVal f As IEnumerable(Of Integer)) As Boolean
        If n <= 0 Then Return False Else If f.Contains(n) Then Return True
        Select Case n.CompareTo(f.Sum())
            Case 1 : Return False : Case 0 : Return True
            Case -1 : Dim rf As List(Of Integer) = f.Reverse().ToList() : Dim D as Integer = n - rf(0) 
                rf.RemoveAt(0) : Return soas(d, rf) OrElse soas(n, rf)
        End Select : Return true
    End Function

    Function ip(ByVal n As Integer) As Boolean
        Dim f As IEnumerable(Of Integer) = Enumerable.Range(1, n >> 1).Where(Function(d) n Mod d = 0).ToList()
        Return Enumerable.Range(1, n - 1).ToList().TrueForAll(Function(i) soas(i, f))
    End Function

    Sub Main()
        Dim c As Integer = 0, m As Integer = 333, i As Integer = 1 : While i <= m
            If ip(i) OrElse i = 1 Then c += 1 : Write("{0,3} {1}", i, If(c Mod 10 = 0, vbLf, ""))
            i += If(i = 1, 1, 2) : End While
        Write(vbLf & "Found {0} practical numbers between 1 and {1} inclusive." & vbLf, c, m)
        Do : m = If(m < 500, m << 1, m * 10 + 6)
            Write(vbLf & "{0,5} is a{1}practical number.", m, If(ip(m), " ", "n im")) : Loop While m < 1e4
    End Sub
End Module