WeixiangYan/CodeTransOcean huggingface dataset:
Task: Break OO privacy




Go: package main

import (
	"bufio"
	"errors"
	"fmt"
	"os"
	"reflect"
	"unsafe"
)

type foobar struct {
	Exported   int 
	unexported int 
}

func main() {
	obj := foobar{12, 42}
	fmt.Println("obj:", obj)

	examineAndModify(&obj)
	fmt.Println("obj:", obj)

	anotherExample()
}





func examineAndModify(any interface{}) {
	v := reflect.ValueOf(any) 
	v = v.Elem()              
	fmt.Println(" v:", v, "=", v.Interface())
	t := v.Type()
	
	fmt.Printf("    %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet")
	for i := 0; i < v.NumField(); i++ {
		f := v.Field(i) 
		fmt.Printf("    %2d: %-10s %-4s %t\n", i,
			t.Field(i).Name, f.Type(), f.CanSet())
	}

	
	v.Field(0).SetInt(16)
	
	
	
	

	
	
	
	vp := v.Field(1).Addr()            
	up := unsafe.Pointer(vp.Pointer()) 
	p := (*int)(up)                    
	fmt.Printf("  vp has type %-14T = %v\n", vp, vp)
	fmt.Printf("  up has type %-14T = %#0x\n", up, up)
	fmt.Printf("   p has type %-14T = %v pointing at %v\n", p, p, *p)
	*p = 43 
	
	*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++

	
	
	
	
	
	
	
}






func anotherExample() {
	r := bufio.NewReader(os.Stdin)

	
	errp := (*error)(unsafe.Pointer(
		reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer()))
	*errp = errors.New("unsafely injected error value into bufio inner workings")

	_, err := r.ReadByte()
	fmt.Println("bufio.ReadByte returned error:", err)
}





VB: Imports System.Reflection


Public Class MyClazz
    Private answer As Integer = 42
End Class

Public Class Program
    Public Shared Sub Main()
        Dim myInstance = New MyClazz()
        Dim fieldInfo = GetType(MyClazz).GetField("answer", BindingFlags.NonPublic Or BindingFlags.Instance)
        Dim answer = fieldInfo.GetValue(myInstance)
        Console.WriteLine(answer)
    End Sub
End Class
Task: Long year




Go: package main

import (
    "fmt"
    "time"
)

func main() {
    centuries := []string{"20th", "21st", "22nd"}
    starts := []int{1900, 2000, 2100} 
    for i := 0; i < len(centuries); i++ {
        var longYears []int
        fmt.Printf("\nLong years in the %s century:\n", centuries[i])
        for j := starts[i]; j < starts[i] + 100; j++ {
            t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)
            if _, week := t.ISOWeek(); week == 53 {
                longYears = append(longYears, j)
            }
        }
        fmt.Println(longYears)
    }
}





VB: DEFINT A-Z

DECLARE FUNCTION p% (Yr AS INTEGER)
DECLARE FUNCTION LongYear% (Yr AS INTEGER)

DIM iYi, iYf, i

CLS
PRINT "This program calculates which are 53-week years in a range."
PRINT
INPUT "Initial year"; iYi
INPUT "Final year (could be the same)"; iYf
IF iYf >= iYi THEN
  FOR i = iYi TO iYf
    IF LongYear(i) THEN
      PRINT i; " ";
    END IF
  NEXT i
END IF
PRINT
PRINT
PRINT "End of program."
END

FUNCTION LongYear% (Yr AS INTEGER)
  LongYear% = (p%(Yr) = 4) OR (p%(Yr - 1) = 3)
END FUNCTION

FUNCTION p% (Yr AS INTEGER)
  p% = (Yr + INT(Yr / 4) - INT(Yr / 100) + INT(Yr / 400)) MOD 7
END FUNCTION
Task: Associative array_Merging




Go: package main

import "fmt"

type assoc map[string]interface{}

func merge(base, update assoc) assoc {
    result := make(assoc)
    for k, v := range base {
        result[k] = v
    }
    for k, v := range update {
        result[k] = v
    }
    return result
}

func main() {
    base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"}
    update := assoc{"price": 15.25, "color": "red", "year": 1974}
    result := merge(base, update)
    fmt.Println(result)
}





VB: Private Type Associative
    Key As String
    Value As Variant
End Type
Sub Main_Array_Associative()
Dim BaseArray(2) As Associative, UpdateArray(2) As Associative
    FillArrays BaseArray, UpdateArray
    ReDim Result(UBound(BaseArray)) As Associative
    MergeArray Result, BaseArray, UpdateArray
    PrintOut Result
End Sub
Private Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)
Dim i As Long, Respons As Long
    Res = Base
    For i = LBound(Update) To UBound(Update)
        If Exist(Respons, Base, Update(i).Key) Then
            Res(Respons).Value = Update(i).Value
        Else
            ReDim Preserve Res(UBound(Res) + 1)
            Res(UBound(Res)).Key = Update(i).Key
            Res(UBound(Res)).Value = Update(i).Value
        End If
    Next
End Sub
Private Function Exist(R As Long, B() As Associative, K As String) As Boolean
Dim i As Long
    Do
        If B(i).Key = K Then
            Exist = True
            R = i
        End If
        i = i + 1
    Loop While i <= UBound(B) And Not Exist
End Function
Private Sub FillArrays(B() As Associative, U() As Associative)
    B(0).Key = "name"
    B(0).Value = "Rocket Skates"
    B(1).Key = "price"
    B(1).Value = 12.75
    B(2).Key = "color"
    B(2).Value = "yellow"
    U(0).Key = "price"
    U(0).Value = 15.25
    U(1).Key = "color"
    U(1).Value = "red"
    U(2).Key = "year"
    U(2).Value = 1974
End Sub
Private Sub PrintOut(A() As Associative)
Dim i As Long
    Debug.Print "Key", "Value"
    For i = LBound(A) To UBound(A)
        Debug.Print A(i).Key, A(i).Value
    Next i
    Debug.Print "-----------------------------"
End Sub
Task: Associative array_Iteration




Go: myMap := map[string]int {
	   "hello": 13,
	   "world": 31,
	   "!"    : 71 }


for key, value := range myMap {
    fmt.Printf("key = %s, value = %d\n", key, value)
}


for key := range myMap {
    fmt.Printf("key = %s\n", key)
}


for _, value := range myMap {
    fmt.Printf("value = %d\n", value)
}





VB: Option Explicit
Sub Test()
    Dim h As Object, i As Long, u, v, s
    Set h = CreateObject("Scripting.Dictionary")
    h.Add "A", 1
    h.Add "B", 2
    h.Add "C", 3

    
    For Each s In h.Keys
        Debug.Print s
    Next

    
    For Each s In h.Items
        Debug.Print s
    Next

    
    u = h.Keys
    v = h.Items
    For i = 0 To h.Count - 1
        Debug.Print u(i), v(i)
    Next
End Sub
Task: Define a primitive data type




Go: package main

import "fmt"

type TinyInt int

func NewTinyInt(i int) TinyInt {
    if i < 1 {
        i = 1
    } else if i > 10 {
        i = 10
    }
    return TinyInt(i)
}

func (t1 TinyInt) Add(t2 TinyInt) TinyInt {
    return NewTinyInt(int(t1) + int(t2))
}

func (t1 TinyInt) Sub(t2 TinyInt) TinyInt {
    return NewTinyInt(int(t1) - int(t2))
}

func (t1 TinyInt) Mul(t2 TinyInt) TinyInt {
    return NewTinyInt(int(t1) * int(t2))
}

func (t1 TinyInt) Div(t2 TinyInt) TinyInt {
    return NewTinyInt(int(t1) / int(t2))
}

func (t1 TinyInt) Rem(t2 TinyInt) TinyInt {
    return NewTinyInt(int(t1) % int(t2))
}

func (t TinyInt) Inc() TinyInt {
    return t.Add(TinyInt(1))
}

func (t TinyInt) Dec() TinyInt {
    return t.Sub(TinyInt(1))
}

func main() {
    t1 := NewTinyInt(6)
    t2 := NewTinyInt(3)
    fmt.Println("t1      =", t1)
    fmt.Println("t2      =", t2)
    fmt.Println("t1 + t2 =", t1.Add(t2))
    fmt.Println("t1 - t2 =", t1.Sub(t2))
    fmt.Println("t1 * t2 =", t1.Mul(t2))
    fmt.Println("t1 / t2 =", t1.Div(t2))
    fmt.Println("t1 % t2 =", t1.Rem(t2))
    fmt.Println("t1 + 1  =", t1.Inc())
    fmt.Println("t1 - 1  =", t1.Dec())
}





VB: Private mvarValue As Integer

Public Property Let Value(ByVal vData As Integer)
    If (vData > 10) Or (vData < 1) Then
        Error 380   
    Else
        mvarValue = vData
    End If
End Property

Public Property Get Value() As Integer
    Value = mvarValue
End Property

Private Sub Class_Initialize()
    
    mvarValue = 1
End Sub
Task: Hash join




Go: package main

import "fmt"

func main() {
    tableA := []struct {
        value int
        key   string
    }{
        {27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"},
        {28, "Alan"},
    }
    tableB := []struct {
        key   string
        value string
    }{
        {"Jonah", "Whales"}, {"Jonah", "Spiders"},
        {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"},
    }
    
    h := map[string][]int{}
    for i, r := range tableA {
        h[r.key] = append(h[r.key], i)
    }
    
    for _, x := range tableB {
        for _, a := range h[x.key] {
            fmt.Println(tableA[a], x)
        }
    }
}





VB: Dim t_age(4,1)
t_age(0,0) = 27 : t_age(0,1) = "Jonah"
t_age(1,0) = 18 : t_age(1,1) = "Alan"
t_age(2,0) = 28 : t_age(2,1) = "Glory"
t_age(3,0) = 18 : t_age(3,1) = "Popeye"
t_age(4,0) = 28 : t_age(4,1) = "Alan"

Dim t_nemesis(4,1)
t_nemesis(0,0) = "Jonah" : t_nemesis(0,1) = "Whales"
t_nemesis(1,0) = "Jonah" : t_nemesis(1,1) = "Spiders"
t_nemesis(2,0) = "Alan" : t_nemesis(2,1) = "Ghosts"
t_nemesis(3,0) = "Alan" : t_nemesis(3,1) = "Zombies"
t_nemesis(4,0) = "Glory" : t_nemesis(4,1) = "Buffy"

Call hash_join(t_age,1,t_nemesis,0)

Sub hash_join(table_1,index_1,table_2,index_2)
	Set hash = CreateObject("Scripting.Dictionary")
	For i = 0 To UBound(table_1)
		hash.Add i,Array(table_1(i,0),table_1(i,1))
	Next
	For j = 0 To UBound(table_2)
		For Each key In hash.Keys
			If hash(key)(index_1) = table_2(j,index_2) Then
				WScript.StdOut.WriteLine hash(key)(0) & "," & hash(key)(1) &_
					" = " & table_2(j,0) & "," & table_2(j,1)
			End If
		Next
	Next
End Sub
Task: Find words whose first and last three letters are equal




Go: package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "log"
    "unicode/utf8"
)

func main() {
    wordList := "unixdict.txt"
    b, err := ioutil.ReadFile(wordList)
    if err != nil {
        log.Fatal("Error reading file")
    }
    bwords := bytes.Fields(b)
    count := 0
    for _, bword := range bwords {
        s := string(bword)
        if utf8.RuneCountInString(s) > 5 && (s[0:3] == s[len(s)-3:]) {
            count++
            fmt.Printf("%d: %s\n", count, s)
        }
    }
}





VB: with createobject("ADODB.Stream")
  .charset ="UTF-8"
  .open
  .loadfromfile("unixdict.txt")
  s=.readtext
end with  
a=split (s,vblf)

set d= createobject("Scripting.Dictionary")
for each aa in a
  x=trim(aa)
  l=len(x)
  if l>5 then
   d.removeall
   for i=1 to 3
     m=mid(x,i,1)
     if not d.exists(m) then d.add m,null
   next
   res=true
   for i=l-2 to l
     m=mid(x,i,1)
     if not d.exists(m) then 
       res=false:exit for 
      else
        d.remove(m)
      end if        
   next 
   if res then 
     wscript.stdout.write left(x & space(15),15)
     if left(x,3)=right(x,3) then  wscript.stdout.write "*"
     wscript.stdout.writeline
    end if 
  end if
next
Task: Closest-pair problem




Go: package main

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

type xy struct {
    x, y float64
}

const n = 1000
const scale = 100.

func d(p1, p2 xy) float64 {
    return math.Hypot(p2.x-p1.x, p2.y-p1.y)
}

func main() {
    rand.Seed(time.Now().Unix())
    points := make([]xy, n)
    for i := range points {
        points[i] = xy{rand.Float64() * scale, rand.Float64() * scale}
    }
    p1, p2 := closestPair(points)
    fmt.Println(p1, p2)
    fmt.Println("distance:", d(p1, p2))
}

func closestPair(points []xy) (p1, p2 xy) {
    if len(points) < 2 {
        panic("at least two points expected")
    }
    min := 2 * scale
    for i, q1 := range points[:len(points)-1] {
        for _, q2 := range points[i+1:] {
            if dq := d(q1, q2); dq < min {
                p1, p2 = q1, q2
                min = dq
            }
        }
    }
    return
}





VB: Option Explicit

Private Type MyPoint
    X As Single
    Y As Single
End Type

Private Type MyPair
    p1 As MyPoint
    p2 As MyPoint
End Type

Sub Main()
Dim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long
Dim T#
Randomize Timer
    Nb = 10
    Do
        ReDim points(1 To Nb)
        For i = 1 To Nb
            points(i).X = Rnd * Nb
            points(i).Y = Rnd * Nb
        Next
        d = 1000000000000#
T = Timer
        BF = BruteForce(points, d)
        Debug.Print "For " & Nb & " points, runtime : " & Timer - T & " sec."
        Debug.Print "point 1 : X:" & BF.p1.X & " Y:" & BF.p1.Y
        Debug.Print "point 2 : X:" & BF.p2.X & " Y:" & BF.p2.Y
        Debug.Print "dist : " & d
        Debug.Print "--------------------------------------------------"
        Nb = Nb * 10
    Loop While Nb <= 10000
End Sub

Private Function BruteForce(p() As MyPoint, mindist As Single) As MyPair
Dim i As Long, j As Long, d As Single, ClosestPair As MyPair
    For i = 1 To UBound(p) - 1
        For j = i + 1 To UBound(p)
            d = Dist(p(i), p(j))
            If d < mindist Then
                mindist = d
                ClosestPair.p1 = p(i)
                ClosestPair.p2 = p(j)
            End If
        Next
    Next
    BruteForce = ClosestPair
End Function

Private Function Dist(p1 As MyPoint, p2 As MyPoint) As Single
    Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2)
End Function
Task: Address of a variable




Go: package main

import (
	"fmt"
	"unsafe"
)

func main() {
	myVar := 3.14
	myPointer := &myVar
	fmt.Println("Address:", myPointer, &myVar)
	fmt.Printf("Address: %p %p\n", myPointer, &myVar)

	var addr64 int64
	var addr32 int32
	ptr := unsafe.Pointer(myPointer)
	if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) {
		addr64 = int64(uintptr(ptr))
		fmt.Printf("Pointer stored in   int64: %#016x\n", addr64)
	}
	if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) {
		
		addr32 = int32(uintptr(ptr))
		fmt.Printf("Pointer stored in   int32: %#08x\n", addr32)
	}
	addr := uintptr(ptr)
	fmt.Printf("Pointer stored in uintptr: %#08x\n", addr)

	fmt.Println("value as float:", myVar)
	i := (*int32)(unsafe.Pointer(&myVar))
	fmt.Printf("value as int32: %#08x\n", *i)
}





VB: Dim TheAddress as long
Dim SecVar as byte
Dim MyVar as byte
    MyVar = 10


TheAddress = varptr(MyVar)


MEMSET(TheAddress, 102, SizeOf(byte))


showmessage "MyVar = " + str$(MyVar)


MEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))


showmessage "SecVar = " + str$(SecVar)
Task: Inheritance_Single




Go: package main

type animal struct {
    alive bool
}

type dog struct {
    animal
    obedienceTrained bool
}

type cat struct {
    animal
    litterBoxTrained bool
}

type lab struct {
    dog
    color string
}

type collie struct {
    dog
    catchesFrisbee bool
}

func main() {
    var pet lab
    pet.alive = true
    pet.obedienceTrained = false
    pet.color = "yellow"
}





VB: Class Animal
  
End Class

Class Dog
  Inherits Animal
  
End Class

Class Lab
  Inherits Dog
  
End Class

Class Collie
  Inherits Dog
  
End Class

Class Cat
  Inherits Animal
  
End Class
Task: Associative array_Creation




Go: 
var x map[string]int


x = make(map[string]int)


x = make(map[string]int, 42)


x["foo"] = 3


y1 := x["bar"]     
y2, ok := x["bar"] 


delete(x, "foo")


x = map[string]int{
	"foo": 2, "bar": 42, "baz": -1,
}





VB: Option Explicit
Sub Test()
    Dim h As Object
    Set h = CreateObject("Scripting.Dictionary")
    h.Add "A", 1
    h.Add "B", 2
    h.Add "C", 3
    Debug.Print h.Item("A")
    h.Item("C") = 4
    h.Key("C") = "D"
    Debug.Print h.exists("C")
    h.Remove "B"
    Debug.Print h.Count
    h.RemoveAll
    Debug.Print h.Count
End Sub
Task: Find words which contain the most consonants




Go: package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "log"
    "unicode/utf8"
)

func contains(list []int, value int) bool {
    for _, v := range list {
        if v == value {
            return true
        }
    }
    return false
}

func main() {
    wordList := "unixdict.txt"
    b, err := ioutil.ReadFile(wordList)
    if err != nil {
        log.Fatal("Error reading file")
    }
    bwords := bytes.Fields(b)
    var words []string
    for _, bword := range bwords {
        s := string(bword)
        if utf8.RuneCountInString(s) > 10 {
            words = append(words, s)
        }
    }
    vowelIndices := []int{0, 4, 8, 14, 20}
    wordGroups := make([][]string, 12)
    for _, word := range words {
        letters := make([]int, 26)
        for _, c := range word {
            index := c - 97
            if index >= 0 && index < 26 {
                letters[index]++
            }
        }
        eligible := true
        uc := 0 
        for i := 0; i < 26; i++ {
            if !contains(vowelIndices, i) {
                if letters[i] > 1 {
                    eligible = false
                    break
                } else if letters[i] == 1 {
                    uc++
                }
            }
        }
        if eligible {
            wordGroups[uc] = append(wordGroups[uc], word)
        }
    }

    for i := 11; i >= 0; i-- {
        count := len(wordGroups[i])
        if count > 0 {
            s := "s"
            if count == 1 {
                s = ""
            }
            fmt.Printf("%d word%s found with %d unique consonants:\n", count, s, i)
            for j := 0; j < count; j++ {
                fmt.Printf("%-15s", wordGroups[i][j])
                if j > 0 && (j+1)%5 == 0 {
                    fmt.Println()
                }
            }
            fmt.Println()
            if count%5 != 0 {
                fmt.Println()
            }
        }
    }
}





VB: with createobject("ADODB.Stream")
  .charset ="UTF-8"
  .open
  .loadfromfile("unixdict.txt")
  s=.readtext
end with  
a=split (s,vblf)

dim b(25)  
dim c(128) 

with new regexp
  .pattern="([^aeiou])"
  .global=true
for each i in a
  if len(trim(i))>10 then
   set matches= .execute(i)   
   rep=false
   for each m in matches  
     x=asc(m)  
     c(x)=c(x)+1
     if c(x)>1 then rep=true :exit for
   next
   erase c
   if not rep then   
     x1=matches.count
     b(x1)=b(x1)&" "&i  
   end if    
  end if
next
end with 


for i=25 to 0 step -1
  if b(i)<>"" then  wscript.echo i & "  "& b(i) & vbcrlf
next
Task: Square root by hand




Go: package main

import (
    "fmt"
    "math/big"
)

var one = big.NewInt(1)
var ten = big.NewInt(10)
var twenty = big.NewInt(20)
var hundred = big.NewInt(100)

func sqrt(n float64, limit int) {
    if n < 0 {
        log.Fatal("Number cannot be negative")
    }
    count := 0
    for n != math.Trunc(n) {
        n *= 100
        count--
    }
    i := big.NewInt(int64(n))
    j := new(big.Int).Sqrt(i)
    count += len(j.String())
    k := new(big.Int).Set(j)
    d := new(big.Int).Set(j)
    t := new(big.Int)
    digits := 0
    var sb strings.Builder
    for digits < limit {
        sb.WriteString(d.String())
        t.Mul(k, d)
        i.Sub(i, t)
        i.Mul(i, hundred)
        k.Mul(j, twenty)
        d.Set(one)
        for d.Cmp(ten) <= 0 {
            t.Add(k, d)
            t.Mul(t, d)
            if t.Cmp(i) > 0 {
                d.Sub(d, one)
                break
            }
            d.Add(d, one)
        }
        j.Mul(j, ten)
        j.Add(j, d)
        k.Add(k, d)
        digits = digits + 1
    }
    root := strings.TrimRight(sb.String(), "0")
    if len(root) == 0 {
        root = "0"
    }
    if count > 0 {
        root = root[0:count] + "." + root[count:]
    } else if count == 0 {
        root = "0." + root
    } else {
        root = "0." + strings.Repeat("0", -count) + root
    }
    root = strings.TrimSuffix(root, ".")
    fmt.Println(root)
}

func main() {
    numbers := []float64{2, 0.2, 10.89, 625, 0.0001}
    digits := []int{500, 80, 8, 8, 8}
    for i, n := range numbers {
        fmt.Printf("First %d significant digits (at most) of the square root of %g:\n", digits[i], n)
        sqrt(n, digits[i])
        fmt.Println()
    }
}





VB: Imports System.Math, System.Console, BI = System.Numerics.BigInteger

Module Module1

    Sub Main(ByVal args As String())
        Dim i, j, k, d As BI : i = 2
        j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j
        Dim n As Integer = -1, n0 As Integer = -1,
            st As DateTime = DateTime.Now
        If args.Length > 0 Then Integer.TryParse(args(0), n)
        If n > 0 Then n0 = n Else n = 1
        Do
            Write(d) : i = (i - k * d) * 100 : k = 20 * j
            For d = 1 To 10
                If (k + d) * d > i Then d -= 1 : Exit For
            Next
            j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1
        Loop While n > 0
        If n0 > 0 Then WriteLine (VbLf & "Time taken for {0} digits: {1}", n0, DateTime.Now - st)
    End Sub
End Module
Task: Primes with digits in nondecreasing order




Go: package main

import (
    "fmt"
    "rcu"
)

func nonDescending(p int) bool {
    var digits []int
    for p > 0 {
        digits = append(digits, p%10)
        p = p / 10
    }
    for i := 0; i < len(digits)-1; i++ {
        if digits[i+1] > digits[i] {
            return false
        }
    }
    return true
}

func main() {
    primes := rcu.Primes(999)
    var nonDesc []int
    for _, p := range primes {
        if nonDescending(p) {
            nonDesc = append(nonDesc, p)
        }
    }
    fmt.Println("Primes below 1,000 with digits in non-decreasing order:")
    for i, n := range nonDesc {
        fmt.Printf("%3d ", n)
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
    fmt.Printf("\n%d such primes found.\n", len(nonDesc))
}





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

Module Module1
    Dim ba As Integer
    Dim chars As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

    Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer)
        Dim flags(lim) As Boolean, j As Integer : Yield 2
        For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3
        Dim d As Integer = 8, sq As Integer = 9
        While sq <= lim
            If Not flags(j) Then
                Yield j : Dim i As Integer = j << 1
                For k As Integer = sq To lim step i : flags(k) = True : Next
            End If
            j += 2 : d += 8 : sq += d : End While
        While j <= lim
            If Not flags(j) Then Yield j
            j += 2 : End While
    End Function

    
    Function from10(ByVal b As Integer) As String
        Dim res As String = "", re As Integer
        While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res
    End Function

    
    Function to10(ByVal s As String) As Integer
        Dim res As Integer = 0
        For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res
    End Function

    
    Function nd(ByVal s As String) As Boolean
        If s.Length < 2 Then Return True
        Dim l As Char = s(0)
        For i As Integer = 1 To s.Length - 1
            If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i)
        Next : Return True
    End Function

    Sub Main(ByVal args As String())
        Dim c As Integer, lim As Integer = 1000, s As String
        For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }
            ba = b : c = 0 : For Each a As Integer In Primes(lim)
                s = from10(a) : If nd(s) Then c += 1 : Write("{0,4} {1}", s, If(c Mod 20 = 0, vbLf, ""))
            Next
            WriteLine(vbLf & "Base {0}: found {1} non-decreasing primes under {2:n0}" & vbLf, b, c, from10(lim))
        Next
    End Sub
End Module