WeixiangYan/CodeTransOcean huggingface dataset:
Task: Primality by Wilson's theorem



C#: using System;
using System.Linq;
using System.Collections;
using static System.Console;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;

class Program {

  
    const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st;
    static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method", 
       fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:";
    static List<int> lst = new List<int>();

  
    static void Dump(int s, int t, string f) {
        foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); }

  
    static string Ord(int x, string fmt = "{0:n0}") {
      var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0;
      return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); }

  
    static void ShowOne(string title, ref double et) {
        WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} ");
        WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} ");
        WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); }

  
    static BI factorial(int n) { BI res = 1; if (n < 2) return res;
        while (n > 0) res *= n--; return res; }

    static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; }

    static BI[] facts;

    static void initFacts(int n) {
        facts = new BI[n]; facts[0] = facts[1] = 1;
        for (int i = 1, j = 2; j < n; i = j++)
            facts[j] = facts[i] * j; }

    static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; }
  

    static void Main(string[] args) { st = DateTime.Now;
        BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n);
        ShowOne(ms1, ref et1);
        st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1);
        for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) {
                lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; }
        ShowOne(ms2, ref et2);
        WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2);

      
        WriteLine("\n" + ms1 + " stand-alone computation:");
        WriteLine("factorial computed for each item");
        st = DateTime.Now;
        for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x);
        WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);

        WriteLine("factorials precomputed up to highest item");
        st = DateTime.Now; initFacts(lst[max - 1]);
        for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x);
        WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
    }
}





Python: from math import factorial

def is_wprime(n):
    return n == 2 or (
        n > 1
        and n % 2 != 0
        and (factorial(n - 1) + 1) % n == 0
    )

if __name__ == '__main__':
    c = int(input('Enter upper limit: '))
    print(f'Primes under {c}:')
    print([n for n in range(c) if is_wprime(n)])
Task: Primality by Wilson's theorem




Go: package main

import (
    "fmt"
    "math/big"
)

var (
    zero = big.NewInt(0)
    one  = big.NewInt(1)
    prev = big.NewInt(factorial(20))
)


func factorial(n int64) int64 {
    res := int64(1)
    for k := n; k > 1; k-- {
        res *= k
    }
    return res
}



func wilson(n int64, memo bool) bool {
    if n <= 1 || (n%2 == 0 && n != 2) {
        return false
    }
    if n <= 21 {
        return (factorial(n-1)+1)%n == 0
    }
    b := big.NewInt(n)
    r := big.NewInt(0)
    z := big.NewInt(0)
    if !memo {
        z.MulRange(2, n-1) 
    } else {
        prev.Mul(prev, r.MulRange(n-2, n-1)) 
        z.Set(prev)
    }
    z.Add(z, one)
    return r.Rem(z, b).Cmp(zero) == 0    
}

func main() {
    numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}
    fmt.Println("  n  prime")
    fmt.Println("---  -----")
    for _, n := range numbers {
        fmt.Printf("%3d  %t\n", n, wilson(n, false))
    }

    
    fmt.Println("\nThe first 120 prime numbers are:")
    for i, count := int64(2), 0; count < 1015; i += 2 {
        if wilson(i, true) {
            count++
            if count <= 120 {
                fmt.Printf("%3d ", i)
                if count%20 == 0 {
                    fmt.Println()
                }
            } else if count >= 1000 {
                if count == 1000 {
                    fmt.Println("\nThe 1,000th to 1,015th prime numbers are:") 
                }
                fmt.Printf("%4d ", i)
            }            
        }
        if i == 2 {
            i--
        }
    }
    fmt.Println()    
}


Java: import java.math.BigInteger;

public class PrimaltyByWilsonsTheorem {

    public static void main(String[] args) {
        System.out.printf("Primes less than 100 testing by Wilson's Theorem%n");
        for ( int i = 0 ; i <= 100 ; i++ ) {
            if ( isPrime(i) ) {
                System.out.printf("%d ", i);
            }
        }
    }
    
    
    private static boolean isPrime(long p) {
        if ( p <= 1) {
            return false;
        }
        return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0;
    }
    
    private static BigInteger fact(long n) {
        BigInteger fact = BigInteger.ONE;
        for ( int i = 2 ; i <= n ; i++ ) {
            fact = fact.multiply(BigInteger.valueOf(i));
        }
        return fact;
    }

}
Task: Primality by Wilson's theorem




Go: package main

import (
    "fmt"
    "math/big"
)

var (
    zero = big.NewInt(0)
    one  = big.NewInt(1)
    prev = big.NewInt(factorial(20))
)


func factorial(n int64) int64 {
    res := int64(1)
    for k := n; k > 1; k-- {
        res *= k
    }
    return res
}



func wilson(n int64, memo bool) bool {
    if n <= 1 || (n%2 == 0 && n != 2) {
        return false
    }
    if n <= 21 {
        return (factorial(n-1)+1)%n == 0
    }
    b := big.NewInt(n)
    r := big.NewInt(0)
    z := big.NewInt(0)
    if !memo {
        z.MulRange(2, n-1) 
    } else {
        prev.Mul(prev, r.MulRange(n-2, n-1)) 
        z.Set(prev)
    }
    z.Add(z, one)
    return r.Rem(z, b).Cmp(zero) == 0    
}

func main() {
    numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}
    fmt.Println("  n  prime")
    fmt.Println("---  -----")
    for _, n := range numbers {
        fmt.Printf("%3d  %t\n", n, wilson(n, false))
    }

    
    fmt.Println("\nThe first 120 prime numbers are:")
    for i, count := int64(2), 0; count < 1015; i += 2 {
        if wilson(i, true) {
            count++
            if count <= 120 {
                fmt.Printf("%3d ", i)
                if count%20 == 0 {
                    fmt.Println()
                }
            } else if count >= 1000 {
                if count == 1000 {
                    fmt.Println("\nThe 1,000th to 1,015th prime numbers are:") 
                }
                fmt.Printf("%4d ", i)
            }            
        }
        if i == 2 {
            i--
        }
    }
    fmt.Println()    
}




Python: from math import factorial

def is_wprime(n):
    return n == 2 or (
        n > 1
        and n % 2 != 0
        and (factorial(n - 1) + 1) % n == 0
    )

if __name__ == '__main__':
    c = int(input('Enter upper limit: '))
    print(f'Primes under {c}:')
    print([n for n in range(c) if is_wprime(n)])
Task: Primality by Wilson's theorem

C: #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

uint64_t factorial(uint64_t n) {
    uint64_t product = 1;

    if (n < 2) {
        return 1;
    }

    for (; n > 0; n--) {
        uint64_t prev = product;
        product *= n;
        if (product < prev) {
            fprintf(stderr, "Overflowed\n");
            return product;
        }
    }

    return product;
}


bool isPrime(uint64_t n) {
    uint64_t large = factorial(n - 1) + 1;
    return (large % n) == 0;
}

int main() {
    uint64_t n;

    
    for (n = 2; n < 22; n++) {
        printf("Is %llu prime: %d\n", n, isPrime(n));
    }

    return 0;
}







Python: from math import factorial

def is_wprime(n):
    return n == 2 or (
        n > 1
        and n % 2 != 0
        and (factorial(n - 1) + 1) % n == 0
    )

if __name__ == '__main__':
    c = int(input('Enter upper limit: '))
    print(f'Primes under {c}:')
    print([n for n in range(c) if is_wprime(n)])
Task: Primality by Wilson's theorem





Java: import java.math.BigInteger;

public class PrimaltyByWilsonsTheorem {

    public static void main(String[] args) {
        System.out.printf("Primes less than 100 testing by Wilson's Theorem%n");
        for ( int i = 0 ; i <= 100 ; i++ ) {
            if ( isPrime(i) ) {
                System.out.printf("%d ", i);
            }
        }
    }
    
    
    private static boolean isPrime(long p) {
        if ( p <= 1) {
            return false;
        }
        return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0;
    }
    
    private static BigInteger fact(long n) {
        BigInteger fact = BigInteger.ONE;
        for ( int i = 2 ; i <= n ; i++ ) {
            fact = fact.multiply(BigInteger.valueOf(i));
        }
        return fact;
    }

}



Python: from math import factorial

def is_wprime(n):
    return n == 2 or (
        n > 1
        and n % 2 != 0
        and (factorial(n - 1) + 1) % n == 0
    )

if __name__ == '__main__':
    c = int(input('Enter upper limit: '))
    print(f'Primes under {c}:')
    print([n for n in range(c) if is_wprime(n)])
Task: Pick random element

C: #include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int main(){
   char array[] = { 'a', 'b', 'c','d','e','f','g','h','i','j' };
   int i;
   time_t t;
   srand((unsigned)time(&t));
   
   for(i=0;i<30;i++){
		printf("%c\n", array[rand()%10]);
   }
   
   return 0;
}


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

int main( ) {
   std::vector<int> numbers { 11 , 88 , -5 , 13 , 4 , 121 , 77 , 2 } ;
   std::random_device seed ;
   
   std::mt19937 engine( seed( ) ) ;
   
   std::uniform_int_distribution<int> choose( 0 , numbers.size( ) - 1 ) ;
   std::cout << "random element picked : " << numbers[ choose( engine ) ] 
      << " !\n" ;
   return 0 ;
}
Task: Pick random element

C: #include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int main(){
   char array[] = { 'a', 'b', 'c','d','e','f','g','h','i','j' };
   int i;
   time_t t;
   srand((unsigned)time(&t));
   
   for(i=0;i<30;i++){
		printf("%c\n", array[rand()%10]);
   }
   
   return 0;
}




Go: package main

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

var list = []string{"bleen", "fuligin", "garrow", "grue", "hooloovoo"}

func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Println(list[rand.Intn(len(list))])
}
Task: Pick random element

C: #include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int main(){
   char array[] = { 'a', 'b', 'c','d','e','f','g','h','i','j' };
   int i;
   time_t t;
   srand((unsigned)time(&t));
   
   for(i=0;i<30;i++){
		printf("%c\n", array[rand()%10]);
   }
   
   return 0;
}





Java: import java.util.Random;
...
int[] array = {1,2,3};
return array[new Random().nextInt(array.length)];
Task: Pick random element

C: #include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int main(){
   char array[] = { 'a', 'b', 'c','d','e','f','g','h','i','j' };
   int i;
   time_t t;
   srand((unsigned)time(&t));
   
   for(i=0;i<30;i++){
		printf("%c\n", array[rand()%10]);
   }
   
   return 0;
}








VB: Option Explicit

Sub Main_Pick_Random_Element()
    Debug.Print Pick_Random_Element(Array(1, 2, 3, 4, 5, #11/24/2017#, "azerty"))
End Sub

Function Pick_Random_Element(myArray)
    Randomize Timer
    Pick_Random_Element = myArray(Int((Rnd * (UBound(myArray) - LBound(myArray) + 1) + LBound(myArray))))
End Function
Task: Pick random element


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

int main( ) {
   std::vector<int> numbers { 11 , 88 , -5 , 13 , 4 , 121 , 77 , 2 } ;
   std::random_device seed ;
   
   std::mt19937 engine( seed( ) ) ;
   
   std::uniform_int_distribution<int> choose( 0 , numbers.size( ) - 1 ) ;
   std::cout << "random element picked : " << numbers[ choose( engine ) ] 
      << " !\n" ;
   return 0 ;
}




Java: import java.util.Random;
...
int[] array = {1,2,3};
return array[new Random().nextInt(array.length)];
Task: Pick random element


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

int main( ) {
   std::vector<int> numbers { 11 , 88 , -5 , 13 , 4 , 121 , 77 , 2 } ;
   std::random_device seed ;
   
   std::mt19937 engine( seed( ) ) ;
   
   std::uniform_int_distribution<int> choose( 0 , numbers.size( ) - 1 ) ;
   std::cout << "random element picked : " << numbers[ choose( engine ) ] 
      << " !\n" ;
   return 0 ;
}






Python: >>> import random
>>> random.choice(['foo', 'bar', 'baz'])
'baz'
Task: Pick random element



C#: using System;
using System.Collections.Generic;

class RandomElementPicker {
  static void Main() {
    var list = new List<int>(new[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
    var rng = new Random();
    var randomElement = list[rng.Next(list.Count)];
    Console.WriteLine("I picked element {0}", randomElement);
  }
}


Go: package main

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

var list = []string{"bleen", "fuligin", "garrow", "grue", "hooloovoo"}

func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Println(list[rand.Intn(len(list))])
}
Task: Pick random element



C#: using System;
using System.Collections.Generic;

class RandomElementPicker {
  static void Main() {
    var list = new List<int>(new[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
    var rng = new Random();
    var randomElement = list[rng.Next(list.Count)];
    Console.WriteLine("I picked element {0}", randomElement);
  }
}





Python: >>> import random
>>> random.choice(['foo', 'bar', 'baz'])
'baz'
Task: Pick random element



C#: using System;
using System.Collections.Generic;

class RandomElementPicker {
  static void Main() {
    var list = new List<int>(new[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
    var rng = new Random();
    var randomElement = list[rng.Next(list.Count)];
    Console.WriteLine("I picked element {0}", randomElement);
  }
}






VB: Option Explicit

Sub Main_Pick_Random_Element()
    Debug.Print Pick_Random_Element(Array(1, 2, 3, 4, 5, #11/24/2017#, "azerty"))
End Sub

Function Pick_Random_Element(myArray)
    Randomize Timer
    Pick_Random_Element = myArray(Int((Rnd * (UBound(myArray) - LBound(myArray) + 1) + LBound(myArray))))
End Function
Task: Pick random element





Java: import java.util.Random;
...
int[] array = {1,2,3};
return array[new Random().nextInt(array.length)]; 



Python: >>> import random
>>> random.choice(['foo', 'bar', 'baz'])
'baz'
Task: Pick random element





Java: import java.util.Random;
...
int[] array = {1,2,3};
return array[new Random().nextInt(array.length)]; 




VB: Option Explicit

Sub Main_Pick_Random_Element()
    Debug.Print Pick_Random_Element(Array(1, 2, 3, 4, 5, #11/24/2017#, "azerty"))
End Sub

Function Pick_Random_Element(myArray)
    Randomize Timer
    Pick_Random_Element = myArray(Int((Rnd * (UBound(myArray) - LBound(myArray) + 1) + LBound(myArray))))
End Function
Task: Pick random element




Go: package main

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

var list = []string{"bleen", "fuligin", "garrow", "grue", "hooloovoo"}

func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Println(list[rand.Intn(len(list))])
}




Python: >>> import random
>>> random.choice(['foo', 'bar', 'baz'])
'baz'
Task: Pick random element




Go: package main

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

var list = []string{"bleen", "fuligin", "garrow", "grue", "hooloovoo"}

func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Println(list[rand.Intn(len(list))])
}





VB: Option Explicit

Sub Main_Pick_Random_Element()
    Debug.Print Pick_Random_Element(Array(1, 2, 3, 4, 5, #11/24/2017#, "azerty"))
End Sub

Function Pick_Random_Element(myArray)
    Randomize Timer
    Pick_Random_Element = myArray(Int((Rnd * (UBound(myArray) - LBound(myArray) + 1) + LBound(myArray))))
End Function
Task: Pick random element







Python: >>> import random
>>> random.choice(['foo', 'bar', 'baz'])
'baz'


VB: Option Explicit

Sub Main_Pick_Random_Element()
    Debug.Print Pick_Random_Element(Array(1, 2, 3, 4, 5, #11/24/2017#, "azerty"))
End Sub

Function Pick_Random_Element(myArray)
    Randomize Timer
    Pick_Random_Element = myArray(Int((Rnd * (UBound(myArray) - LBound(myArray) + 1) + LBound(myArray))))
End Function
Task: Pick random element

C: #include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int main(){
   char array[] = { 'a', 'b', 'c','d','e','f','g','h','i','j' };
   int i;
   time_t t;
   srand((unsigned)time(&t));
   
   for(i=0;i<30;i++){
		printf("%c\n", array[rand()%10]);
   }
   
   return 0;
}



C#: using System;
using System.Collections.Generic;

class RandomElementPicker {
  static void Main() {
    var list = new List<int>(new[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
    var rng = new Random();
    var randomElement = list[rng.Next(list.Count)];
    Console.WriteLine("I picked element {0}", randomElement);
  }
}
Task: Pick random element


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

int main( ) {
   std::vector<int> numbers { 11 , 88 , -5 , 13 , 4 , 121 , 77 , 2 } ;
   std::random_device seed ;
   
   std::mt19937 engine( seed( ) ) ;
   
   std::uniform_int_distribution<int> choose( 0 , numbers.size( ) - 1 ) ;
   std::cout << "random element picked : " << numbers[ choose( engine ) ] 
      << " !\n" ;
   return 0 ;
}







VB: Option Explicit

Sub Main_Pick_Random_Element()
    Debug.Print Pick_Random_Element(Array(1, 2, 3, 4, 5, #11/24/2017#, "azerty"))
End Sub

Function Pick_Random_Element(myArray)
    Randomize Timer
    Pick_Random_Element = myArray(Int((Rnd * (UBound(myArray) - LBound(myArray) + 1) + LBound(myArray))))
End Function
Task: Pick random element



C#: using System;
using System.Collections.Generic;

class RandomElementPicker {
  static void Main() {
    var list = new List<int>(new[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
    var rng = new Random();
    var randomElement = list[rng.Next(list.Count)];
    Console.WriteLine("I picked element {0}", randomElement);
  }
}



Java: import java.util.Random;
...
int[] array = {1,2,3};
return array[new Random().nextInt(array.length)];
Task: Pick random element

C: #include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int main(){
   char array[] = { 'a', 'b', 'c','d','e','f','g','h','i','j' };
   int i;
   time_t t;
   srand((unsigned)time(&t));
   
   for(i=0;i<30;i++){
		printf("%c\n", array[rand()%10]);
   }
   
   return 0;
}







Python: >>> import random
>>> random.choice(['foo', 'bar', 'baz'])
'baz'
Task: Pick random element


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

int main( ) {
   std::vector<int> numbers { 11 , 88 , -5 , 13 , 4 , 121 , 77 , 2 } ;
   std::random_device seed ;
   
   std::mt19937 engine( seed( ) ) ;
   
   std::uniform_int_distribution<int> choose( 0 , numbers.size( ) - 1 ) ;
   std::cout << "random element picked : " << numbers[ choose( engine ) ] 
      << " !\n" ;
   return 0 ;
}


C#: using System;
using System.Collections.Generic;

class RandomElementPicker {
  static void Main() {
    var list = new List<int>(new[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
    var rng = new Random();
    var randomElement = list[rng.Next(list.Count)];
    Console.WriteLine("I picked element {0}", randomElement);
  }
}
Task: Pick random element


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

int main( ) {
   std::vector<int> numbers { 11 , 88 , -5 , 13 , 4 , 121 , 77 , 2 } ;
   std::random_device seed ;
   
   std::mt19937 engine( seed( ) ) ;
   
   std::uniform_int_distribution<int> choose( 0 , numbers.size( ) - 1 ) ;
   std::cout << "random element picked : " << numbers[ choose( engine ) ] 
      << " !\n" ;
   return 0 ;
}



Go: package main

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

var list = []string{"bleen", "fuligin", "garrow", "grue", "hooloovoo"}

func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Println(list[rand.Intn(len(list))])
}
Task: Pick random element




Go: package main

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

var list = []string{"bleen", "fuligin", "garrow", "grue", "hooloovoo"}

func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Println(list[rand.Intn(len(list))])
}


Java: import java.util.Random;
...
int[] array = {1,2,3};
return array[new Random().nextInt(array.length)];
Task: Pick random element

C: #include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int main(){
   char array[] = { 'a', 'b', 'c','d','e','f','g','h','i','j' };
   int i;
   time_t t;
   srand((unsigned)time(&t));
   
   for(i=0;i<30;i++){
		printf("%c\n", array[rand()%10]);
   }
   
   return 0;
}






PHP: $arr = array('foo', 'bar', 'baz');
$x = $arr[array_rand($arr)];
Task: Pick random element



C#: using System;
using System.Collections.Generic;

class RandomElementPicker {
  static void Main() {
    var list = new List<int>(new[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
    var rng = new Random();
    var randomElement = list[rng.Next(list.Count)];
    Console.WriteLine("I picked element {0}", randomElement);
  }
}




PHP: $arr = array('foo', 'bar', 'baz');
$x = $arr[array_rand($arr)];
Task: Pick random element


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

int main( ) {
   std::vector<int> numbers { 11 , 88 , -5 , 13 , 4 , 121 , 77 , 2 } ;
   std::random_device seed ;
   
   std::mt19937 engine( seed( ) ) ;
   
   std::uniform_int_distribution<int> choose( 0 , numbers.size( ) - 1 ) ;
   std::cout << "random element picked : " << numbers[ choose( engine ) ] 
      << " !\n" ;
   return 0 ;
}





PHP: $arr = array('foo', 'bar', 'baz');
$x = $arr[array_rand($arr)];
Task: Pick random element




Go: package main

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

var list = []string{"bleen", "fuligin", "garrow", "grue", "hooloovoo"}

func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Println(list[rand.Intn(len(list))])
}



PHP: $arr = array('foo', 'bar', 'baz');
$x = $arr[array_rand($arr)];
Task: Pick random element





Java: import java.util.Random;
...
int[] array = {1,2,3};
return array[new Random().nextInt(array.length)]; 


PHP: $arr = array('foo', 'bar', 'baz');
$x = $arr[array_rand($arr)];
Task: Pick random element






PHP: $arr = array('foo', 'bar', 'baz');
$x = $arr[array_rand($arr)];


Python: >>> import random
>>> random.choice(['foo', 'bar', 'baz'])
'baz'
Task: Pick random element






PHP: $arr = array('foo', 'bar', 'baz');
$x = $arr[array_rand($arr)];



VB: Option Explicit

Sub Main_Pick_Random_Element()
    Debug.Print Pick_Random_Element(Array(1, 2, 3, 4, 5, #11/24/2017#, "azerty"))
End Sub

Function Pick_Random_Element(myArray)
    Randomize Timer
    Pick_Random_Element = myArray(Int((Rnd * (UBound(myArray) - LBound(myArray) + 1) + LBound(myArray))))
End Function
Task: URL encoding

C: #include <stdio.h>
#include <ctype.h>
 
char rfc3986[256] = {0};
char html5[256] = {0};


void encode(const char *s, char *enc, char *tb)
{
	for (; *s; s++) {
		if (tb[*s]) sprintf(enc, "%c", tb[*s]);
		else        sprintf(enc, "%%%02X", *s);
		while (*++enc);
	}
}
 
int main()
{
	const char url[] = "http:
	char enc[(strlen(url) * 3) + 1];
 
	int i;
	for (i = 0; i < 256; i++) {
		rfc3986[i] = isalnum(i)||i == '~'||i == '-'||i == '.'||i == '_'
			? i : 0;
		html5[i] = isalnum(i)||i == '*'||i == '-'||i == '.'||i == '_'
			? i : (i == ' ') ? '+' : 0;
	}
 
	encode(url, enc, rfc3986);
	puts(enc);
 
	return 0;
}


C++: #include <QByteArray>
#include <iostream>

int main( ) {
   QByteArray text ( "http:
   QByteArray encoded( text.toPercentEncoding( ) ) ;
   std::cout << encoded.data( ) << '\n' ;
   return 0 ;
}