WeixiangYan/CodeTransOcean huggingface dataset:
Task: Short-circuit evaluation


C++: #include <iostream>

bool a(bool in)
{
    std::cout << "a" << std::endl;
    return in;
}

bool b(bool in)
{
    std::cout << "b" << std::endl;
    return in;
}

void test(bool i, bool j) {
    std::cout << std::boolalpha << i << " and " << j << " = " << (a(i) && b(j)) << std::endl;
    std::cout << std::boolalpha << i << " or " << j << " = " << (a(i) || b(j)) << std::endl;
}

int main()
{
    test(false, false);
    test(false, true);
    test(true, false);
    test(true, true);
    return 0;
}



Go: package main

import "fmt"

func a(v bool) bool {
    fmt.Print("a")
    return v
}

func b(v bool) bool {
    fmt.Print("b")
    return v
}

func test(i, j bool) {
    fmt.Printf("Testing a(%t) && b(%t)\n", i, j)
    fmt.Print("Trace:  ")
    fmt.Println("\nResult:", a(i) && b(j))

    fmt.Printf("Testing a(%t) || b(%t)\n", i, j)
    fmt.Print("Trace:  ")
    fmt.Println("\nResult:", a(i) || b(j))

    fmt.Println("")
}

func main() {
    test(false, false)
    test(false, true)
    test(true, false)
    test(true, true)
}
Task: Find limit of recursion


C++: #include <iostream>
 
void recurse(unsigned int i)
{
  std::cout<<i<<"\n";
  recurse(i+1);
}
 
int main()
{
  recurse(0);
}



Go: package main

import (
	"flag"
	"fmt"
	"runtime/debug"
)

func main() {
	stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default")
	flag.Parse()
	if *stack > 0 {
		debug.SetMaxStack(*stack)
	}
	r(1)
}

func r(l int) {
	if l%1000 == 0 {
		fmt.Println(l)
	}
	r(l + 1)
}
Task: Carmichael 3 strong pseudoprimes


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

int mod(int n, int d) {
    return (d + n % d) % d;
}

bool is_prime(int n) {
    if (n < 2)
        return false;
    if (n % 2 == 0)
        return n == 2;
    if (n % 3 == 0)
        return n == 3;
    for (int p = 5; p * p <= n; p += 4) {
        if (n % p == 0)
            return false;
        p += 2;
        if (n % p == 0)
            return false;
    }
    return true;
}

void print_carmichael_numbers(int prime1) {
    for (int h3 = 1; h3 < prime1; ++h3) {
        for (int d = 1; d < h3 + prime1; ++d) {
            if (mod((h3 + prime1) * (prime1 - 1), d) != 0
                || mod(-prime1 * prime1, h3) != mod(d, h3))
                continue;
            int prime2 = 1 + (prime1 - 1) * (h3 + prime1)/d;
            if (!is_prime(prime2))
                continue;
            int prime3 = 1 + prime1 * prime2/h3;
            if (!is_prime(prime3))
                continue;
            if (mod(prime2 * prime3, prime1 - 1) != 1)
                continue;
            unsigned int c = prime1 * prime2 * prime3;
            std::cout << std::setw(2) << prime1 << " x "
                << std::setw(4) << prime2 << " x "
                << std::setw(5) << prime3 << " = "
                << std::setw(10) << c << '\n';
        }
    }
}

int main() {
    for (int p = 2; p <= 61; ++p) {
        if (is_prime(p))
            print_carmichael_numbers(p);
    }
    return 0;
}



Go: package main

import "fmt"


func mod(n, m int) int {
    return ((n % m) + m) % m
}

func isPrime(n int) bool {
    if n < 2 { return false }
    if n % 2 == 0 { return n == 2 }
    if n % 3 == 0 { return n == 3 }
    d := 5
    for d * d <= n {
        if n % d == 0 { return false }
        d += 2
        if n % d == 0 { return false }
        d += 4
    }
    return true
}

func carmichael(p1 int) {
    for h3 := 2; h3 < p1; h3++ {
        for d := 1; d < h3 + p1; d++ {
            if (h3 + p1) * (p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3 {
                p2 := 1 + (p1 - 1) * (h3 + p1) / d
                if !isPrime(p2) { continue }
                p3 := 1 + p1 * p2 / h3
                if !isPrime(p3) { continue }
                if p2 * p3 % (p1 - 1) != 1 { continue }
                c := p1 * p2 * p3
                fmt.Printf("%2d   %4d   %5d     %d\n", p1, p2, p3, c)
            }
        }
    }
}

func main() {
    fmt.Println("The following are Carmichael munbers for p1 <= 61:\n")
    fmt.Println("p1     p2      p3     product")
    fmt.Println("==     ==      ==     =======")

    for p1 := 2; p1 <= 61; p1++ {
        if isPrime(p1) { carmichael(p1) }
    }
}
Task: Arithmetic numbers


C++: #include <cstdio>

void divisor_count_and_sum(unsigned int n,
			   unsigned int& divisor_count,
			   unsigned int& divisor_sum)
{
  divisor_count = 0;
  divisor_sum = 0;
  for (unsigned int i = 1;; i++)
  {
    unsigned int j = n / i;
    if (j < i)
      break;
    if (i * j != n)
      continue;
    divisor_sum += i;
    divisor_count += 1;
    if (i != j)
    {
      divisor_sum += j;
      divisor_count += 1;
    }
  }
}

int main()
{
  unsigned int arithmetic_count = 0;
  unsigned int composite_count = 0;

  for (unsigned int n = 1; arithmetic_count <= 1000000; n++)
  {
    unsigned int divisor_count;
    unsigned int divisor_sum;
    divisor_count_and_sum(n, divisor_count, divisor_sum);
    unsigned int mean = divisor_sum / divisor_count;
    if (mean * divisor_count != divisor_sum)
      continue;
    arithmetic_count++;
    if (divisor_count > 2)
      composite_count++;
    if (arithmetic_count <= 100)
    {
      
      std::printf("%3u ", n);
      if (arithmetic_count % 10 == 0)
	std::printf("\n");
    }
    if ((arithmetic_count == 1000) || (arithmetic_count == 10000) ||
	(arithmetic_count == 100000) || (arithmetic_count == 1000000))
    {
      std::printf("\n%uth arithmetic number is %u\n", arithmetic_count, n);
      std::printf("Number of composite arithmetic numbers <= %u: %u\n", n, composite_count);
    }
  }
  return 0;
}



Go: package main

import (
    "fmt"
    "math"
    "rcu"
    "sort"
)

func main() {
    arithmetic := []int{1}
    primes := []int{}
    limit := int(1e6)
    for n := 3; len(arithmetic) < limit; n++ {
        divs := rcu.Divisors(n)
        if len(divs) == 2 {
            primes = append(primes, n)
            arithmetic = append(arithmetic, n)
        } else {
            mean := float64(rcu.SumInts(divs)) / float64(len(divs))
            if mean == math.Trunc(mean) {
                arithmetic = append(arithmetic, n)
            }
        }
    }
    fmt.Println("The first 100 arithmetic numbers are:")
    rcu.PrintTable(arithmetic[0:100], 10, 3, false)

    for _, x := range []int{1e3, 1e4, 1e5, 1e6} {
        last := arithmetic[x-1]
        lastc := rcu.Commatize(last)
        fmt.Printf("\nThe %sth arithmetic number is: %s\n", rcu.Commatize(x), lastc)
        pcount := sort.SearchInts(primes, last) + 1
        if !rcu.IsPrime(last) {
            pcount--
        }
        comp := x - pcount - 1 
        compc := rcu.Commatize(comp)
        fmt.Printf("The count of such numbers <= %s which are composite is %s.\n", lastc, compc)
    }
}
Task: Keyboard input_Obtain a Y or N response


C++: #include <conio.h>
#include <iostream>

using namespace std;

int main()
{
	char ch;
	_cputs( "Yes or no?" );
	do
	{
		ch = _getch();
		ch = toupper( ch );
	} while(ch!='Y'&&ch!='N');

	if(ch=='N')
	{
		cout << "You said no" << endl;
	}
	else
	{
		cout << "You said yes" << endl;
	}
	return 0;
}



Go: package main

import (
    "log"

    gc "code.google.com/p/goncurses"
)

func main() {
    s, err := gc.Init()
    if err != nil {
        log.Fatal("init:", err)
    }
    defer gc.End()
    var k gc.Key
    for {
        gc.FlushInput()
        s.MovePrint(20, 0, "Press y/n ")
        s.Refresh()
        switch k = s.GetChar(); k {
        default:
            continue
        case 'y', 'Y', 'n', 'N':
        }
        break
    }
    s.Printf("\nThanks for the %c!\n", k)
    s.Refresh()
    s.GetChar()
}
Task: Perfect numbers


C++: #include <iostream>
using namespace std ;

int divisor_sum( int number ) { 
   int sum = 0 ; 
   for ( int i = 1 ; i < number ; i++ ) 
      if ( number % i == 0 ) 
         sum += i ; 
   return sum; 
}

int main( ) { 
   cout << "Perfect numbers from 1 to 33550337:\n" ;
   for ( int num = 1 ; num < 33550337 ; num++ ) { 
      if (divisor_sum(num) == num) 
         cout << num << '\n' ;
   }   
   return 0 ; 
}



Go: package main

import "fmt"

func computePerfect(n int64) bool {
    var sum int64
    for i := int64(1); i < n; i++ {
        if n%i == 0 {
            sum += i
        }
    }
    return sum == n
}



func isPerfect(n int64) bool {
    switch n {
    case 6, 28, 496, 8128, 33550336, 8589869056,
        137438691328, 2305843008139952128:
        return true
    }
    return false
}


func main() {
    for n := int64(1); ; n++ {
        if isPerfect(n) != computePerfect(n) {
            panic("bug")
        }
        if n%1e3 == 0 {
            fmt.Println("tested", n)
        }
    }
}
Task: Jacobsthal numbers


C++: #include <gmpxx.h>

#include <iomanip>
#include <iostream>

using big_int = mpz_class;

bool is_probably_prime(const big_int& n) {
    return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;
}

big_int jacobsthal_number(unsigned int n) {
    return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;
}

big_int jacobsthal_lucas_number(unsigned int n) {
    return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);
}

big_int jacobsthal_oblong_number(unsigned int n) {
    return jacobsthal_number(n) * jacobsthal_number(n + 1);
}

int main() {
    std::cout << "First 30 Jacobsthal Numbers:\n";
    for (unsigned int n = 0; n < 30; ++n) {
        std::cout << std::setw(9) << jacobsthal_number(n)
                  << ((n + 1) % 5 == 0 ? '\n' : ' ');
    }
    std::cout << "\nFirst 30 Jacobsthal-Lucas Numbers:\n";
    for (unsigned int n = 0; n < 30; ++n) {
        std::cout << std::setw(9) << jacobsthal_lucas_number(n)
                  << ((n + 1) % 5 == 0 ? '\n' : ' ');
    }
    std::cout << "\nFirst 20 Jacobsthal oblong Numbers:\n";
    for (unsigned int n = 0; n < 20; ++n) {
        std::cout << std::setw(11) << jacobsthal_oblong_number(n)
                  << ((n + 1) % 5 == 0 ? '\n' : ' ');
    }
    std::cout << "\nFirst 20 Jacobsthal primes:\n";
    for (unsigned int n = 0, count = 0; count < 20; ++n) {
        auto jn = jacobsthal_number(n);
        if (is_probably_prime(jn)) {
            ++count;
            std::cout << jn << '\n';
        }
    }
}



Go: package main

import (
    "fmt"
    "math/big"
)

func jacobsthal(n uint) *big.Int {
    t := big.NewInt(1)
    t.Lsh(t, n)
    s := big.NewInt(1)
    if n%2 != 0 {
        s.Neg(s)
    }
    t.Sub(t, s)
    return t.Div(t, big.NewInt(3))
}

func jacobsthalLucas(n uint) *big.Int {
    t := big.NewInt(1)
    t.Lsh(t, n)
    a := big.NewInt(1)
    if n%2 != 0 {
        a.Neg(a)
    }
    return t.Add(t, a)
}

func main() {
    jac := make([]*big.Int, 30)
    fmt.Println("First 30 Jacobsthal numbers:")
    for i := uint(0); i < 30; i++ {
        jac[i] = jacobsthal(i)
        fmt.Printf("%9d ", jac[i])
        if (i+1)%5 == 0 {
            fmt.Println()
        }
    }

    fmt.Println("\nFirst 30 Jacobsthal-Lucas numbers:")
    for i := uint(0); i < 30; i++ {
        fmt.Printf("%9d ", jacobsthalLucas(i))
        if (i+1)%5 == 0 {
            fmt.Println()
        }
    }

    fmt.Println("\nFirst 20 Jacobsthal oblong numbers:")
    for i := uint(0); i < 20; i++ {
        t := big.NewInt(0)
        fmt.Printf("%11d ", t.Mul(jac[i], jac[i+1]))
        if (i+1)%5 == 0 {
            fmt.Println()
        }
    }

    fmt.Println("\nFirst 20 Jacobsthal primes:")
    for n, count := uint(0), 0; count < 20; n++ {
        j := jacobsthal(n)
        if j.ProbablyPrime(10) {
            fmt.Println(j)
            count++
        }
    }
}
Task: Sorting algorithms_Bead sort


C++: 



#include <iostream>
#include <vector>

using std::cout;
using std::vector;

void distribute(int dist, vector<int> &List) {
	
    if (dist > List.size() )
        List.resize(dist); 

    for (int i=0; i < dist; i++)
        List[i]++;
}

vector<int> beadSort(int *myints, int n) {
    vector<int> list, list2, fifth (myints, myints + n);

    cout << "#1 Beads falling down: ";
    for (int i=0; i < fifth.size(); i++)
        distribute (fifth[i], list);
    cout << '\n';

    cout << "\nBeads on their sides: ";
    for (int i=0; i < list.size(); i++)
        cout << " " << list[i];
    cout << '\n';

    

    cout << "#2 Beads right side up: ";
    for (int i=0; i < list.size(); i++)
        distribute (list[i], list2);
    cout << '\n';

    return list2;
}

int main() {
    int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1};
	vector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int));
	cout << "Sorted list/array: ";
	for(unsigned int i=0; i<sorted.size(); i++)
		cout << sorted[i] << ' ';
}



Go: package main

import (
    "fmt"
    "sync"
)

var a = []int{170, 45, 75, 90, 802, 24, 2, 66}
var aMax = 1000

const bead = 'o'

func main() {
    fmt.Println("before:", a)
    beadSort()
    fmt.Println("after: ", a)
}

func beadSort() {
    
    all := make([]byte, aMax*len(a))
    
    
    abacus := make([][]byte, aMax)
    for pole, space := 0, all; pole < aMax; pole++ {
        abacus[pole] = space[:len(a)]
        space = space[len(a):]
    }
    
    var wg sync.WaitGroup
    
    
    
    wg.Add(len(a))
    for row, n := range a {
        go func(row, n int) {
            for pole := 0; pole < n; pole++ {
                abacus[pole][row] = bead
            }
            wg.Done()
        }(row, n)
    }
    wg.Wait()
    
    wg.Add(aMax)
    for _, pole := range abacus {
        go func(pole []byte) {
            
            top := 0
            for row, space := range pole {
                if space == bead {
                    
                    
                    
                    
                    
                    pole[row] = 0
                    pole[top] = bead
                    top++
                }
            }
            wg.Done()
        }(pole)
    }
    wg.Wait()
    
    for row := range a {
        x := 0
        for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {
            x++
        }
        a[len(a)-1-row] = x
    }
}
Task: Arbitrary-precision integers (included)


C++: #include <iostream>
#include <boost/multiprecision/gmp.hpp>
#include <string>

namespace mp = boost::multiprecision;

int main(int argc, char const *argv[])
{
    
    
    
    
    uint64_t tmpres = mp::pow(mp::mpz_int(4)
                            , mp::pow(mp::mpz_int(3)
                                    , 2).convert_to<uint64_t>()
                                      ).convert_to<uint64_t>();
    mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres);
    std::string s = res.str();
    std::cout << s.substr(0, 20) 
              << "..."
              << s.substr(s.length() - 20, 20) << std::endl;
    return 0;
}



Go: package main

import (
	"fmt"
	"math/big"
)

func main() {
	x := big.NewInt(2)
	x = x.Exp(big.NewInt(3), x, nil)
	x = x.Exp(big.NewInt(4), x, nil)
	x = x.Exp(big.NewInt(5), x, nil)
	str := x.String()
	fmt.Printf("5^(4^(3^2)) has %d digits: %s ... %s\n",
		len(str),
		str[:20],
		str[len(str)-20:],
	)
}
Task: Draw a sphere


C++: 

#include <QImage>
#include <QPainter>

int main() {
    const QColor black(0, 0, 0);
    const QColor white(255, 255, 255);

    const int size = 300;
    const double diameter = 0.6 * size;

    QImage image(size, size, QImage::Format_RGB32);
    QPainter painter(&image);
    painter.setRenderHint(QPainter::Antialiasing);

    QLinearGradient linearGradient(0, 0, 0, size);
    linearGradient.setColorAt(0, white);
    linearGradient.setColorAt(1, black);

    QBrush brush(linearGradient);
    painter.fillRect(QRect(0, 0, size, size), brush);

    QPointF point1(0.4 * size, 0.4 * size);
    QPointF point2(0.45 * size, 0.4 * size);
    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);
    radialGradient.setColorAt(0, white);
    radialGradient.setColorAt(1, black);

    QBrush brush2(radialGradient);
    painter.setPen(Qt::NoPen);
    painter.setBrush(brush2);
    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));

    image.save("sphere.png");
    return 0;
}



Go: package main

import (
    "fmt"
    "image"
    "image/color"
    "image/png"
    "math"
    "os"
)

type vector [3]float64

func normalize(v *vector) {
    invLen := 1 / math.Sqrt(dot(v, v))
    v[0] *= invLen
    v[1] *= invLen
    v[2] *= invLen
}

func dot(x, y *vector) float64 {
    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
}

func drawSphere(r int, k, amb float64, dir *vector) *image.Gray {
    w, h := r*4, r*3
    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))
    vec := new(vector)
    for x := -r; x < r; x++ {
        for y := -r; y < r; y++ {
            if z := r*r - x*x - y*y; z >= 0 {
                vec[0] = float64(x)
                vec[1] = float64(y)
                vec[2] = math.Sqrt(float64(z))
                normalize(vec)
                s := dot(dir, vec)
                if s < 0 {
                    s = 0
                }
                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)
                if lum < 0 {
                    lum = 0
                } else if lum > 255 {
                    lum = 255
                }
                img.SetGray(x, y, color.Gray{uint8(lum)})
            }
        }
    }
    return img
}

func main() {
    dir := &vector{-30, -30, 50}
    normalize(dir)
    img := drawSphere(200, 1.5, .2, dir)
    f, err := os.Create("sphere.png")
    if err != nil {
        fmt.Println(err)
        return
    }
    if err = png.Encode(f, img); err != nil {
        fmt.Println(err)
    }
    if err = f.Close(); err != nil {
        fmt.Println(err)
    }
}
Task: Least common multiple


C++: #include <boost/math/common_factor.hpp>
#include <iostream>

int main( ) {
   std::cout << "The least common multiple of 12 and 18 is " << 
      boost::math::lcm( 12 , 18 ) << " ,\n"
      << "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ;
   return 0 ;
}



Go: package main

import (
    "fmt"
    "math/big"
)

var m, n, z big.Int

func init() {
    m.SetString("2562047788015215500854906332309589561", 10)
    n.SetString("6795454494268282920431565661684282819", 10)
}

func main() {
    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))
}
Task: Loops_Break


C++: #include <iostream>
#include <ctime>
#include <cstdlib>

int main(){
	srand(time(NULL)); 
	while(true){
		const int a = rand() % 20; 
		std::cout << a << std::endl;
		if(a == 10)
			break;
		const int b = rand() % 20;
		std::cout << b << std::endl;
	}
	return 0;
}



Go: package main

import "fmt"
import "math/rand"
import "time"

func main() {
    rand.Seed(time.Now().UnixNano())
    for {
        a := rand.Intn(20)
        fmt.Println(a)
        if a == 10 {
            break
        }
        b := rand.Intn(20)
        fmt.Println(b)
    }
}
Task: Hello world_Line printer


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

int main(){
  std::ofstream lprFile;
  lprFile.open( "/dev/lp0" );
  lprFile << "Hello World!\n";
  lprFile.close();
  return 0;
}



Go: package main

import (
	"fmt"
	"os"
)

func main() {
	lp0, err := os.Create("/dev/lp0")

	if err != nil {
		panic(err)
	}

	defer lp0.Close()

	fmt.Fprintln(lp0, "Hello World!")
}
Task: Water collected between towers


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

enum { EMPTY, WALL, WATER };

auto fill(const std::vector<int> b) {
  auto water = 0;
  const auto rows = *std::max_element(std::begin(b), std::end(b));
  const auto cols = std::size(b);
  std::vector<std::vector<int>> g(rows);
  for (auto& r : g) {
    for (auto i = 0; i < cols; ++i) {
      r.push_back(EMPTY);
    }
  }
  for (auto c = 0; c < cols; ++c) {
    for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) {
      g[r][c] = WALL;
    }
  }
  for (auto c = 0; c < cols - 1; ++c) {
    auto start_row = rows - b[c];
    while (start_row < rows) {
      if (g[start_row][c] == EMPTY) break;
      auto c2 = c + 1;
      bool hitWall = false;
      while (c2 < cols) {
        if (g[start_row][c2] == WALL) {
          hitWall = true;
          break;
        }
        ++c2;
      }
      if (hitWall) {
        for (auto i = c + 1; i < c2; ++i) {
          g[start_row][i] = WATER;
          ++water;
        }
      }
      ++start_row;
    }
  }
  return water;
}

int main() {
  std::vector<std::vector<int>> b = {
    { 1, 5, 3, 7, 2 },
    { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },
    { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },
    { 5, 5, 5, 5 },
    { 5, 6, 7, 8 },
    { 8, 7, 7, 6 },
    { 6, 7, 10, 7, 6 }
  };
  for (const auto v : b) {
    auto water = fill(v);
    std::cout << water << " water drops." << std::endl;
  }
  std::cin.ignore();
  std::cin.get();
  return 0;
}



Go: package main

import "fmt"

func maxl(hm []int ) []int{
	res := make([]int,len(hm))
	max := 1
	for i := 0; i < len(hm);i++{
		if(hm[i] > max){
			max = hm[i]
		}
		res[i] = max;
	}
	return res
}
func maxr(hm []int ) []int{
	res := make([]int,len(hm))
	max := 1
	for i := len(hm) - 1 ; i >= 0;i--{
		if(hm[i] > max){
			max = hm[i]
		}
		res[i] = max;
	}
	return res
}
func min(a,b []int)  []int {
	res := make([]int,len(a))
	for i := 0; i < len(a);i++{
		if a[i] >= b[i]{
			res[i] = b[i]
		}else {
			res[i] = a[i]
		}
	}
	return res
}
func diff(hm, min []int) []int {
	res := make([]int,len(hm))
	for i := 0; i < len(hm);i++{
		if min[i] > hm[i]{
			res[i] = min[i] - hm[i]
		}
	}
	return res
}
func sum(a []int) int {
	res := 0
	for i := 0; i < len(a);i++{
		res += a[i]
	}
	return res
}

func waterCollected(hm []int) int {
	maxr := maxr(hm)
	maxl := maxl(hm)
	min := min(maxr,maxl)
	diff := diff(hm,min)
	sum := sum(diff)
	return sum
}


func main() {
	fmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))
	fmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))
	fmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))
	fmt.Println(waterCollected([]int{5, 5, 5, 5}))
	fmt.Println(waterCollected([]int{5, 6, 7, 8}))
	fmt.Println(waterCollected([]int{8, 7, 7, 6}))
	fmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))
}
Task: Descending primes


C++: #include <iostream>

bool ispr(unsigned int n) {
    if ((n & 1) == 0 || n < 2) return n == 2;
    for (unsigned int j = 3; j * j <= n; j += 2)
      if (n % j == 0) return false; return true; }

int main() {
  unsigned int c = 0, nc, pc = 9, i, a, b, l,
    ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128];
  while (true) {
    nc = 0;
    for (i = 0; i < pc; i++) {
        if (ispr(a = ps[i]))
          printf("%8d%s", a, ++c % 5 == 0 ? "\n" : " ");
        for (b = a * 10, l = a % 10 + b++; b < l; b++)
          nxt[nc++] = b;
      }
      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];
      else break;
    }
    printf("\n%d descending primes found", c);
}



Go: package main

import (
    "fmt"
    "rcu"
    "sort"
    "strconv"
)

func combinations(a []int, k int) [][]int {
    n := len(a)
    c := make([]int, k)
    var combs [][]int
    var combine func(start, end, index int)
    combine = func(start, end, index int) {
        if index == k {
            t := make([]int, len(c))
            copy(t, c)
            combs = append(combs, t)
            return
        }
        for i := start; i <= end && end-i+1 >= k-index; i++ {
            c[index] = a[i]
            combine(i+1, end, index+1)
        }
    }
    combine(0, n-1, 0)
    return combs
}

func powerset(a []int) (res [][]int) {
    if len(a) == 0 {
        return
    }
    for i := 1; i <= len(a); i++ {
        res = append(res, combinations(a, i)...)
    }
    return
}

func main() {
    ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})
    var descPrimes []int
    for i := 1; i < len(ps); i++ {
        s := ""
        for _, e := range ps[i] {
            s += string(e + '0')
        }
        p, _ := strconv.Atoi(s)
        if rcu.IsPrime(p) {
            descPrimes = append(descPrimes, p)
        }
    }
    sort.Ints(descPrimes)
    fmt.Println("There are", len(descPrimes), "descending primes, namely:")
    for i := 0; i < len(descPrimes); i++ {
        fmt.Printf("%8d ", descPrimes[i])
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
    fmt.Println()
}