WeixiangYan/CodeTransOcean huggingface dataset:
Task: Monads_Writer monad




Go: package main

import (
    "fmt"
    "math"
)

type mwriter struct {
    value float64
    log   string
}

func (m mwriter) bind(f func(v float64) mwriter) mwriter {
    n := f(m.value)
    n.log = m.log + n.log
    return n
}

func unit(v float64, s string) mwriter {
    return mwriter{v, fmt.Sprintf("  %-17s: %g\n", s, v)}
}

func root(v float64) mwriter {
    return unit(math.Sqrt(v), "Took square root")
}

func addOne(v float64) mwriter {
    return unit(v+1, "Added one")
}

func half(v float64) mwriter {
    return unit(v/2, "Divided by two")
}

func main() {
    mw1 := unit(5, "Initial value")
    mw2 := mw1.bind(root).bind(addOne).bind(half)
    fmt.Println("The Golden Ratio is", mw2.value)
    fmt.Println("\nThis was derived as follows:-")
    fmt.Println(mw2.log)
}



PHP: class WriterMonad {

	
	private $value;
	
	private $logs;

	private function __construct($value, array $logs = []) {
		$this->value = $value;
		$this->logs = $logs;
	}

	public static function unit($value, string $log): WriterMonad {
		return new WriterMonad($value, ["{$log}: {$value}"]);
	}

	public function bind(callable $mapper): WriterMonad  {
		$mapped = $mapper($this->value);
		assert($mapped instanceof WriterMonad);
		return new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);
	}

	public function value() {
		return $this->value;
	}

	public function logs(): array {
		return $this->logs;
	}
}

$root = fn(float $i): float => sqrt($i);
$addOne = fn(float $i): float => $i + 1;
$half = fn(float $i): float => $i / 2;

$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);

$result = WriterMonad::unit(5, "Initial value")
	->bind($m($root, "square root"))
	->bind($m($addOne, "add one"))
	->bind($m($half, "half"));

print "The Golden Ratio is: {$result->value()}\n";
print join("\n", $result->logs());
Task: Canny edge detector




Go: package main

import (
    ed "github.com/Ernyoke/Imger/edgedetection"
    "github.com/Ernyoke/Imger/imgio"
    "log"
)

func main() {
    img, err := imgio.ImreadRGBA("Valve_original_(1).png")
    if err != nil {
        log.Fatal("Could not read image", err)
    }

    cny, err := ed.CannyRGBA(img, 15, 45, 5)
    if err != nil {
        log.Fatal("Could not perform Canny Edge detection")
    }

    err = imgio.Imwrite(cny, "Valve_canny_(1).png")
    if err != nil {
        log.Fatal("Could not write Canny image to disk")
    }
}



PHP: 
function RGBtoHSV($r, $g, $b) {
	$r = $r/255.; // convert to range 0..1
	$g = $g/255.;
	$b = $b/255.;
	$cols = array("r" => $r, "g" => $g, "b" => $b);
	asort($cols, SORT_NUMERIC);
	$min = key(array_slice($cols, 1)); // "r", "g" or "b"
	$max = key(array_slice($cols, -1)); // "r", "g" or "b"

	if($cols[$min] == $cols[$max]) {
		$h = 0;
	} else {
		if($max == "r") {
			$h = 60. * ( 0 + ( ($cols["g"]-$cols["b"]) / ($cols[$max]-$cols[$min]) ) );
		} elseif ($max == "g") {
			$h = 60. * ( 2 + ( ($cols["b"]-$cols["r"]) / ($cols[$max]-$cols[$min]) ) );
		} elseif ($max == "b") {
			$h = 60. * ( 4 + ( ($cols["r"]-$cols["g"]) / ($cols[$max]-$cols[$min]) ) );
		}
		if($h < 0) {
			$h += 360;
		}
	}

	if($cols[$max] == 0) {
		$s = 0;
	} else {
		$s = ( ($cols[$max]-$cols[$min])/$cols[$max] );
		$s = $s * 255;
	}

	$v = $cols[$max];
	$v = $v * 255;

	return(array($h, $s, $v));
}

$filename = "image.png";
$dimensions = getimagesize($filename);
$w = $dimensions[0]; // width
$h = $dimensions[1]; // height

$im = imagecreatefrompng($filename);

for($hi=0; $hi < $h; $hi++) {

	for($wi=0; $wi < $w; $wi++) {
		$rgb = imagecolorat($im, $wi, $hi);

		$r = ($rgb >> 16) & 0xFF;
		$g = ($rgb >> 8) & 0xFF;
		$b = $rgb & 0xFF;
		$hsv = RGBtoHSV($r, $g, $b);

		$brgb = imagecolorat($im, $wi, $hi+1);
		$br = ($brgb >> 16) & 0xFF;
		$bg = ($brgb >> 8) & 0xFF;
		$bb = $brgb & 0xFF;
		$bhsv = RGBtoHSV($br, $bg, $bb);

		if($hsv[2]-$bhsv[2] > 20) { 
                    imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 255, 0, 0));
		} 
                else {
		    imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 0, 0, 0));
		}
			
        }
        
}

header('Content-Type: image/jpeg');
imagepng($im);
imagedestroy($im);
Task: Add a variable to a class instance at runtime




Go: package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
)

type SomeStruct struct {
    runtimeFields map[string]string
}

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

func main() {
    ss := SomeStruct{make(map[string]string)}
    scanner := bufio.NewScanner(os.Stdin)
    fmt.Println("Create two fields at runtime: ")
    for i := 1; i <= 2; i++ {
        fmt.Printf("  Field #%d:\n", i)
        fmt.Print("       Enter name  : ")
        scanner.Scan()
        name := scanner.Text()
        fmt.Print("       Enter value : ")
        scanner.Scan()
        value := scanner.Text()
        check(scanner.Err())
        ss.runtimeFields[name] = value
        fmt.Println()
    }
    for {
        fmt.Print("Which field do you want to inspect ? ")
        scanner.Scan()
        name := scanner.Text()
        check(scanner.Err())
        value, ok := ss.runtimeFields[name]
        if !ok {
            fmt.Println("There is no field of that name, try again")
        } else {
            fmt.Printf("Its value is '%s'\n", value)
            return
        }
    }
}



PHP: class E {};

$e=new E();

$e->foo=1;

$e->{"foo"} = 1; // using a runtime name
$x = "foo";
$e->$x = 1; // using a runtime name in a variable
Task: Find URI in text




Go: package main

import (
    "fmt"
    "github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre"
)

var pattern = 
    "(*UTF)(*UCP)" +                    
    "[a-z][-a-z0-9+.]*:" +              
    "(?=[/\\w])" +                      
    "(?:
    "[-\\w.~/%!$&'()*+,;=]*" +          
    "(?:\\?[-\\w.~%!$&'()*+,;=/?]*)?" + 
    "(?:\\#[-\\w.~%!$&'()*+,;=/?]*)?"   

func main() {
    text := `
this URI contains an illegal character, parentheses and a misplaced full stop:
http:
and another one just to confuse the parser: http:
")" is handled the wrong way by the mediawiki parser.
ftp:
ftp:
ftp:
leading junk ftp:
leading junk ftp:
if you have other interesting URIs for testing, please add them here:
http:
http:
`
    descs := []string{"URIs:-", "IRIs:-"}
    patterns := []string{pattern[12:], pattern}
    for i := 0; i <= 1; i++ {
        fmt.Println(descs[i])
        re := pcre.MustCompile(patterns[i], 0)
        t := text
        for {
            se := re.FindIndex([]byte(t), 0)
            if se == nil {
                break
            }
            fmt.Println(t[se[0]:se[1]])
            t = t[se[1]:]
        }
        fmt.Println()
    }
}



PHP: $tests = array(
    'this URI contains an illegal character, parentheses and a misplaced full stop:',
    'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).',
    'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)',
    '")" is handled the wrong way by the mediawiki parser.',
    'ftp://domain.name/path(balanced_brackets)/foo.html',
    'ftp://domain.name/path(balanced_brackets)/ending.in.dot.',
    'ftp://domain.name/path(unbalanced_brackets/ending.in.dot.',
    'leading junk ftp://domain.name/path/embedded?punct/uation.',
    'leading junk ftp://domain.name/dangling_close_paren)',
    'if you have other interesting URIs for testing, please add them here:',
    'http://www.example.org/foo.html#includes_fragment',
    'http://www.example.org/foo.html#enthält_Unicode-Fragment',
    ' http://192.168.0.1/admin/?hackme=%%%%%%%%%true',
    'blah (foo://domain.hld/))))',
    'https://haxor.ur:4592/~mama/####&?foo'
);

foreach ( $tests as $test ) {
    foreach( explode( ' ', $test ) as $uri ) {
        if ( filter_var( $uri, FILTER_VALIDATE_URL ) )
            echo $uri, PHP_EOL;
    }
}
Task: Verify distribution uniformity_Naive







Python: from collections import Counter
from pprint import pprint as pp

def distcheck(fn, repeats, delta):
    
    bin = Counter(fn() for i in range(repeats))
    target = repeats // len(bin)
    deltacount = int(delta / 100. * target)
    assert all( abs(target - count) < deltacount
                for count in bin.values() ), "Bin distribution skewed from %i +/- %i: %s" % (
                    target, deltacount, [ (key, target - count)
                                          for key, count in sorted(bin.items()) ]
                    )
    pp(dict(bin))


VB: Option Explicit

sub verifydistribution(calledfunction, samples, delta)
	Dim i, n, maxdiff
	
	Dim d : Set d = CreateObject("Scripting.Dictionary")
	wscript.echo "Running """ & calledfunction & """ " & samples & " times..."
	for i = 1 to samples
		Execute "n = " & calledfunction
		d(n) = d(n) + 1
	next
	n = d.Count
	maxdiff = 0
	wscript.echo "Expected average count is " & Int(samples/n) & " across " & n & " buckets."
	for each i in d.Keys
		dim diff : diff = abs(1 - d(i) / (samples/n))
		if diff > maxdiff then maxdiff = diff
		wscript.echo "Bucket " & i & " had " & d(i) & " occurences" _
		& vbTab & " difference from expected=" & FormatPercent(diff, 2)
	next
	wscript.echo "Maximum found variation is " & FormatPercent(maxdiff, 2) _
		& ", desired limit is " & FormatPercent(delta, 2) & "."
	if maxdiff > delta then wscript.echo "Skewed!" else wscript.echo "Smooth!"
end sub
Task: Stirling numbers of the second kind







Python: computed = {}

def sterling2(n, k):
	key = str(n) + "," + str(k)

	if key in computed.keys():
		return computed[key]
	if n == k == 0:
		return 1
	if (n > 0 and k == 0) or (n == 0 and k > 0):
		return 0
	if n == k:
		return 1
	if k > n:
		return 0
	result = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)
	computed[key] = result
	return result

print("Stirling numbers of the second kind:")
MAX = 12
print("n/k".ljust(10), end="")
for n in range(MAX + 1):
	print(str(n).rjust(10), end="")
print()
for n in range(MAX + 1):
	print(str(n).ljust(10), end="")
	for k in range(n + 1):
		print(str(sterling2(n, k)).rjust(10), end="")
	print()
print("The maximum value of S2(100, k) = ")
previous = 0
for k in range(1, 100 + 1):
	current = sterling2(100, k)
	if current > previous:
		previous = current
	else:
		print("{0}\n({1} digits, k = {2})\n".format(previous, len(str(previous)), k - 1))
		break


VB: Imports System.Numerics

Module Module1

    Class Sterling
        Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger)

        Private Shared Function CacheKey(n As Integer, k As Integer) As String
            Return String.Format("{0}:{1}", n, k)
        End Function

        Private Shared Function Impl(n As Integer, k As Integer) As BigInteger
            If n = 0 AndAlso k = 0 Then
                Return 1
            End If
            If (n > 0 AndAlso k = 0) OrElse (n = 0 AndAlso k > 0) Then
                Return 0
            End If
            If n = k Then
                Return 1
            End If
            If k > n Then
                Return 0
            End If

            Return k * Sterling2(n - 1, k) + Sterling2(n - 1, k - 1)
        End Function

        Public Shared Function Sterling2(n As Integer, k As Integer) As BigInteger
            Dim key = CacheKey(n, k)
            If COMPUTED.ContainsKey(key) Then
                Return COMPUTED(key)
            End If

            Dim result = Impl(n, k)
            COMPUTED.Add(key, result)
            Return result
        End Function
    End Class

    Sub Main()
        Console.WriteLine("Stirling numbers of the second kind:")
        Dim max = 12
        Console.Write("n/k")
        For n = 0 To max
            Console.Write("{0,10}", n)
        Next
        Console.WriteLine()
        For n = 0 To max
            Console.Write("{0,3}", n)
            For k = 0 To n
                Console.Write("{0,10}", Sterling.Sterling2(n, k))
            Next
            Console.WriteLine()
        Next
        Console.WriteLine("The maximum value of S2(100, k) = ")
        Dim previous = BigInteger.Zero
        For k = 1 To 100
            Dim current = Sterling.Sterling2(100, k)
            If current > previous Then
                previous = current
            Else
                Console.WriteLine(previous)
                Console.WriteLine("({0} digits, k = {1})", previous.ToString().Length, k - 1)
                Exit For
            End If
        Next
    End Sub

End Module
Task: Recaman's sequence







Python: from itertools import islice

class Recamans():
    "Recamán's sequence generator callable class"
    def __init__(self):
        self.a = None   
        self.n = None   
    
    def __call__(self):
        "Recamán's sequence  generator"
        nxt = 0
        a, n = {nxt}, 0
        self.a = a
        self.n = n
        yield nxt
        while True:
            an1, n = nxt, n + 1
            nxt = an1 - n
            if nxt < 0 or nxt in a:
                nxt = an1 + n
            a.add(nxt)
            self.n = n
            yield nxt

if __name__ == '__main__':
    recamans = Recamans()
    print("First fifteen members of Recamans sequence:", 
          list(islice(recamans(), 15)))

    so_far = set()
    for term in recamans():
        if term in so_far:
            print(f"First duplicate number in series is: a({recamans.n}) = {term}")
            break
        so_far.add(term)
    
    n = 1_000
    setn = set(range(n + 1))    
    for _ in recamans():
        if setn.issubset(recamans.a):
            print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})")
            break


VB: 
	nx=15
	h=1000
	Wscript.StdOut.WriteLine "Recaman
	Wscript.StdOut.WriteLine recaman("seq",nx)
	Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0)
	Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h)
	Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine()
	
function recaman(op,nn)
	Dim b,d,h
	Set b = CreateObject("Scripting.Dictionary")
	Set d = CreateObject("Scripting.Dictionary")
    list="0" : firstdup=0
	if op="firstdup" then
		nn=1000 : firstdup=1
	end if
	if op="numterm" then
		h=nn : nn=10000000 : numterm=1
	end if
	ax=0  
	b.Add 0,1  
	s=0
	for n=1 to nn-1
        an=ax-n
		if an<=0 then 
			an=ax+n
		elseif b.Exists(an) then 
			an=ax+n
		end if
		ax=an  
		if not b.Exists(an) then b.Add an,1  
		if op="seq" then
			list=list&" "&an
		end if
		if firstdup then
			if d.Exists(an) then
				recaman="a("&n&")="&an
				exit function
			else
				d.Add an,1  
			end if
		end if
		if numterm then
			if an<=h then
				if not d.Exists(an) then
					s=s+1
					d.Add an,1  
				end if
				if s>=h then
					recaman=n
					exit function
				end if
			end if
		end if
	next 
	recaman=list
end function
Task: Integer sequence







Python: i=1
while i:
    print(i)
    i += 1


VB:     For i As Integer = 0 To Integer.MaxValue
      Console.WriteLine(i)
    Next
Task: DNS query







Python: >>> import socket
>>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80))
>>> for ip in ips: print ip
...
2001:200:dff:fff1:216:3eff:feb1:44d7
203.178.141.194


VB: Function dns_query(url,ver)
	Set r = New RegExp
	r.Pattern = "Pinging.+?\[(.+?)\].+"
	Set objshell = CreateObject("WScript.Shell")
	Set objexec = objshell.Exec("%comspec% /c " & "ping -" & ver & " " & url)
	WScript.StdOut.WriteLine "URL: " & url
	Do Until objexec.StdOut.AtEndOfStream
		line = objexec.StdOut.ReadLine
		If r.Test(line) Then
			WScript.StdOut.WriteLine "IP Version " &_
				ver & ": " & r.Replace(line,"$1")
		End If
	Loop
End Function

Call dns_query(WScript.Arguments(0),WScript.Arguments(1))
Task: Peano curve







Python: import turtle as tt
import inspect

stack = [] 
def peano(iterations=1):
    global stack

    
    ivan = tt.Turtle(shape = "classic", visible = True)


    
    screen = tt.Screen()
    screen.title("Desenhin do Peano")
    screen.bgcolor("
    screen.delay(0) 
    screen.setup(width=0.95, height=0.9)

    
    walk = 1

    def screenlength(k):
        
        
        if k != 0:
            length = screenlength(k-1)
            return 2*length + 1
        else: return 0

    kkkj = screenlength(iterations)
    screen.setworldcoordinates(-1, -1, kkkj + 1, kkkj + 1)
    ivan.color("


    
    def step1(k):
        global stack
        stack.append(len(inspect.stack()))
        if k != 0:
            ivan.left(90)
            step2(k - 1)
            ivan.forward(walk)
            ivan.right(90)
            step1(k - 1)
            ivan.forward(walk)
            step1(k - 1)
            ivan.right(90)
            ivan.forward(walk)
            step2(k - 1)
            ivan.left(90)
    def step2(k):
        global stack
        stack.append(len(inspect.stack()))
        if k != 0:
            ivan.right(90)
            step1(k - 1)
            ivan.forward(walk)
            ivan.left(90)
            step2(k - 1)
            ivan.forward(walk)
            step2(k - 1)
            ivan.left(90)
            ivan.forward(walk)
            step1(k - 1)
            ivan.right(90)

    
    ivan.left(90)
    step2(iterations)

    tt.done()

if __name__ == "__main__":
    peano(4)
    import pylab as P 
    P.plot(stack)
    P.show()


VB: Const WIDTH = 243 
Dim n As Long
Dim points() As Single
Dim flag As Boolean












Private Sub lineto(x As Integer, y As Integer)
    If flag Then
        points(n, 1) = x
        points(n, 2) = y
    End If
    n = n + 1
End Sub
Private Sub Peano(ByVal x As Integer, ByVal y As Integer, ByVal lg As Integer, _
    ByVal i1 As Integer, ByVal i2 As Integer)
    If (lg = 1) Then
        Call lineto(x * 3, y * 3)
        Exit Sub
    End If
    lg = lg / 3
    Call Peano(x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2)
    Call Peano(x + ((i1 - i2 + 1) * lg), y + ((i1 + i2) * lg), lg, i1, 1 - i2)
    Call Peano(x + lg, y + lg, lg, i1, 1 - i2)
    Call Peano(x + ((i1 + i2) * lg), y + ((i1 - i2 + 1) * lg), lg, 1 - i1, 1 - i2)
    Call Peano(x + (2 * i2 * lg), y + (2 * (1 - i2) * lg), lg, i1, i2)
    Call Peano(x + ((1 + i2 - i1) * lg), y + ((2 - i1 - i2) * lg), lg, i1, i2)
    Call Peano(x + (2 * (1 - i1) * lg), y + (2 * (1 - i1) * lg), lg, i1, i2)
    Call Peano(x + ((2 - i1 - i2) * lg), y + ((1 + i2 - i1) * lg), lg, 1 - i1, i2)
    Call Peano(x + (2 * (1 - i2) * lg), y + (2 * i2 * lg), lg, 1 - i1, i2)
End Sub
Sub main()
    n = 1: flag = False
    Call Peano(0, 0, WIDTH, 0, 0) 
    ReDim points(1 To n - 1, 1 To 2)
    n = 1: flag = True
    Call Peano(0, 0, WIDTH, 0, 0) 
    ActiveSheet.Shapes.AddPolyline points 
End Sub
Task: Seven-sided dice from five-sided dice







Python: from random import randint

def dice5():
    return randint(1, 5)

def dice7():
    r = dice5() + dice5() * 5 - 6
    return (r % 7) + 1 if r < 21 else dice7()


VB: Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean
    
    Dim Total As Long, Ei As Long, i As Integer
    Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double
    Debug.Print "[1] ""Data set:"" ";
    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)
        Total = Total + ObservationFrequencies(i)
        Debug.Print ObservationFrequencies(i); " ";
    Next i
    DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)
    
    Ei = Total / (DegreesOfFreedom + 1)
    For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)
        ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei
    Next i
    p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)
    Debug.Print
    Debug.Print "Chi-squared test for given frequencies"
    Debug.Print "X-squared ="; Format(ChiSquared, "0.0000"); ", ";
    Debug.Print "df ="; DegreesOfFreedom; ", ";
    Debug.Print "p-value = "; Format(p_value, "0.0000")
    Test4DiscreteUniformDistribution = p_value > Significance
End Function
Private Function Dice5() As Integer
    Dice5 = Int(5 * Rnd + 1)
End Function
Private Function Dice7() As Integer
    Dim i As Integer
    Do
        i = 5 * (Dice5 - 1) + Dice5
    Loop While i > 21
    Dice7 = i Mod 7 + 1
End Function
Sub TestDice7()
    Dim i As Long, roll As Integer
    Dim Bins(1 To 7) As Variant
    For i = 1 To 1000000
        roll = Dice7
        Bins(roll) = Bins(roll) + 1
    Next i
    Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(Bins, 0.05); """"
End Sub
Task: Extensible prime generator







Python: islice(count(7), 0, None, 2)


VB: Option Explicit

Sub Main()
Dim Primes() As Long, n As Long, temp$
Dim t As Single
    t = Timer
    
    n = 133218295 
    Primes = ListPrimes(n)
    Debug.Print "For N = " & Format(n, "#,##0") & ", execution time : " & _
        Format(Timer - t, "0.000 s") & ", " & _
        Format(UBound(Primes) + 1, "#,##0") & " primes numbers."
    
    
    For n = 0 To 19
        temp = temp & ", " & Primes(n)
    Next
    Debug.Print "First twenty primes : "; Mid(temp, 3)
    
    n = 0: temp = vbNullString
    Do While Primes(n) < 100
        n = n + 1
    Loop
    Do While Primes(n) < 150
        temp = temp & ", " & Primes(n)
        n = n + 1
    Loop
    Debug.Print "Primes between 100 and 150 : " & Mid(temp, 3)
    
    Dim ccount As Long
    n = 0
    Do While Primes(n) < 7700
        n = n + 1
    Loop
    Do While Primes(n) < 8000
        ccount = ccount + 1
        n = n + 1
    Loop
    Debug.Print "Number of primes between 7,700 and 8,000 : " & ccount
    
    n = 1
    Do While n <= 100000
        n = n * 10
        Debug.Print "The " & n & "th prime: "; Format(Primes(n - 1), "#,##0")
    Loop
    Debug.Print "VBA has a limit in array
    Debug.Print "With my computer, the limit for an array of Long is : 133 218 295"
    Debug.Print "The last prime I could find is the : " & _
        Format(UBound(Primes), "#,##0") & "th, Value : " & _
        Format(Primes(UBound(Primes)), "#,##0")
End Sub

Function ListPrimes(MAX As Long) As Long()
Dim t() As Boolean, L() As Long, c As Long, s As Long, i As Long, j As Long
    ReDim t(2 To MAX)
    ReDim L(MAX \ 2)
    s = Sqr(MAX)
    For i = 3 To s Step 2
        If t(i) = False Then
            For j = i * i To MAX Step i
                t(j) = True
            Next
        End If
    Next i
    L(0) = 2
    For i = 3 To MAX Step 2
        If t(i) = False Then
            c = c + 1
            L(c) = i
        End If
    Next i
    ReDim Preserve L(c)
    ListPrimes = L
End Function
Task: Create a two-dimensional array at runtime







Python: width = int(raw_input("Width of myarray: "))
height = int(raw_input("Height of Array: "))
myarray = [[0] * width for i in range(height)]
myarray[0][0] = 3.5
print (myarray[0][0])


VB: Module Program
    Sub Main()
        Console.WriteLine("Enter two space-delimited integers:")
        Dim input = Console.ReadLine().Split()
        Dim rows = Integer.Parse(input(0))
        Dim cols = Integer.Parse(input(1))

        
        Dim arr(rows - 1, cols - 1) As Integer

        arr(0, 0) = 2
        Console.WriteLine(arr(0, 0))
    End Sub
End Module