WeixiangYan/CodeTransOcean huggingface dataset:
Task: Variable-length quantity



C#: namespace Vlq
{
  using System;
  using System.Collections.Generic;
  using System.Linq;

  public static class VarLenQuantity
  {
    public static ulong ToVlq(ulong integer)
    {
      var array = new byte[8];
      var buffer = ToVlqCollection(integer)
        .SkipWhile(b => b == 0)
        .Reverse()
        .ToArray();
      Array.Copy(buffer, array, buffer.Length);
      return BitConverter.ToUInt64(array, 0);
    }

    public static ulong FromVlq(ulong integer)
    {
      var collection = BitConverter.GetBytes(integer).Reverse();
      return FromVlqCollection(collection);
    }

    public static IEnumerable<byte> ToVlqCollection(ulong integer)
    {
      if (integer > Math.Pow(2, 56))
        throw new OverflowException("Integer exceeds max value.");

      var index = 7;
      var significantBitReached = false;
      var mask = 0x7fUL << (index * 7);
      while (index >= 0)
      {
        var buffer = (mask & integer);
        if (buffer > 0 || significantBitReached)
        {
          significantBitReached = true;
          buffer >>= index * 7;
          if (index > 0)
            buffer |= 0x80;
          yield return (byte)buffer;
        }
        mask >>= 7;
        index--;
      }
    }


    public static ulong FromVlqCollection(IEnumerable<byte> vlq)
    {
      ulong integer = 0;
      var significantBitReached = false;

      using (var enumerator = vlq.GetEnumerator())
      {
        int index = 0;
        while (enumerator.MoveNext())
        {
          var buffer = enumerator.Current;
          if (buffer > 0 || significantBitReached)
          {
            significantBitReached = true;
            integer <<= 7;
            integer |= (buffer & 0x7fUL);
          }

          if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))
            break;
        }
      }
      return integer;
    }

    public static void Main()
    {
      var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };

      foreach (var original in integers)
      {
        Console.WriteLine("Original: 0x{0:X}", original);

        
        var seq = ToVlqCollection(original);
        Console.WriteLine("Sequence: 0x{0}", seq.Select(b => b.ToString("X2")).Aggregate(string.Concat));

        var decoded = FromVlqCollection(seq);
        Console.WriteLine("Decoded: 0x{0:X}", decoded);

        
        var encoded = ToVlq(original);
        Console.WriteLine("Encoded: 0x{0:X}", encoded);

        decoded = FromVlq(encoded);
        Console.WriteLine("Decoded: 0x{0:X}", decoded);

        Console.WriteLine();
      }
      Console.WriteLine("Press any key to continue...");
      Console.ReadKey();
    }
  }
}


Go: package main

import (
    "fmt"
    "encoding/binary"
)

func main() {
    buf := make([]byte, binary.MaxVarintLen64)
    for _, x := range []int64{0x200000, 0x1fffff} {
        v := buf[:binary.PutVarint(buf, x)]
        fmt.Printf("%d encodes into %d bytes: %x\n", x, len(v), v)
        x, _ = binary.Varint(v)
        fmt.Println(x, "decoded")
    }
}
Task: String case



C#: using System;

namespace StringCase
{
  class Program
  {
    public static void Main()
    {
      String input = scope .("alphaBETA");
      input.ToUpper();
      Console.WriteLine(input);
      input.ToLower();
      Console.WriteLine(input);
    }
  }
}


Go: package main

import (
    "fmt"
    "strings"
    "unicode"
    "unicode/utf8"
)

func main() {
    show("alphaBETA")
    show("alpha BETA")
    
    show("Ǆǈǌ")
    
    show("o'hare O'HARE o’hare don't")
}

func show(s string) {
    fmt.Println("\nstring:         ",
        s, " len:", utf8.RuneCountInString(s), "runes") 
    fmt.Println("All upper case: ", strings.ToUpper(s)) 
    fmt.Println("All lower case: ", strings.ToLower(s)) 
    fmt.Println("All title case: ", strings.ToTitle(s)) 
    fmt.Println("Title words:    ", strings.Title(s))   
    fmt.Println("Swapping case:  ",                     
        strings.Map(unicode.SimpleFold, s))
}
Task: MD5



C#: using System.Text;
using System.Security.Cryptography;

byte[] data = Encoding.ASCII.GetBytes("The quick brown fox jumped over the lazy dog's back");
byte[] hash = MD5.Create().ComputeHash(data);
Console.WriteLine(BitConverter.ToString(hash).Replace("-", "").ToLower());


Go: package main

import (
    "crypto/md5"
    "fmt"
)

func main() {
    for _, p := range [][2]string{
        
        {"d41d8cd98f00b204e9800998ecf8427e", ""},
        {"0cc175b9c0f1b6a831c399e269772661", "a"},
        {"900150983cd24fb0d6963f7d28e17f72", "abc"},
        {"f96b697d7cb7938d525a2f31aaf161d0", "message digest"},
        {"c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz"},
        {"d174ab98d277d9f5a5611c2c9f419d9f",
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"},
        {"57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890" +
            "123456789012345678901234567890123456789012345678901234567890"},
        
        {"e38ca1d920c4b8b8d3946b2c72f01680",
            "The quick brown fox jumped over the lazy dog's back"},
    } {
        validate(p[0], p[1])
    }
}

var h = md5.New()

func validate(check, s string) {
    h.Reset()
    h.Write([]byte(s))
    sum := fmt.Sprintf("%x", h.Sum(nil))
    if sum != check {
        fmt.Println("MD5 fail")
        fmt.Println("  for string,", s)
        fmt.Println("  expected:  ", check)
        fmt.Println("  got:       ", sum)
    }
}
Task: Date manipulation



C#: class Program
{
    static void Main(string[] args)
    {
        CultureInfo ci=CultureInfo.CreateSpecificCulture("en-US");
        string dateString = "March 7 2009 7:30pm EST";
        string format = "MMMM d yyyy h:mmtt z";
        DateTime myDateTime = DateTime.ParseExact(dateString.Replace("EST","+6"),format,ci) ;
        DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;
        Console.WriteLine(newDateTime.ToString(format).Replace("-5","EST")); 

        Console.ReadLine();
    }
}


Go: package main

import (
    "fmt"
    "time"
)

const taskDate = "March 7 2009 7:30pm EST"
const taskFormat = "January 2 2006 3:04pm MST"

func main() {
    if etz, err := time.LoadLocation("US/Eastern"); err == nil {
        time.Local = etz
    }
    fmt.Println("Input:             ", taskDate)
    t, err := time.Parse(taskFormat, taskDate)
    if err != nil {
        fmt.Println(err)
        return
    }
    t = t.Add(12 * time.Hour)
    fmt.Println("+12 hrs:           ", t)
    if _, offset := t.Zone(); offset == 0 {
        fmt.Println("No time zone info.")
        return
    }
    atz, err := time.LoadLocation("US/Arizona")
    if err == nil {
        fmt.Println("+12 hrs in Arizona:", t.In(atz))
    }
}
Task: Sorting algorithms_Sleep sort



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

class Program
{
    static void ThreadStart(object item)
    {
        Thread.Sleep(1000 * (int)item);
        Console.WriteLine(item);
    }

    static void SleepSort(IEnumerable<int> items)
    {
        foreach (var item in items)
        {
            new Thread(ThreadStart).Start(item);
        }
    }

    static void Main(string[] arguments)
    {
        SleepSort(arguments.Select(int.Parse));
    }
}


Go: package main

import (
	"fmt"
	"log"
	"os"
	"strconv"
	"time"
)

func main() {
	out := make(chan uint64)
	for _, a := range os.Args[1:] {
		i, err := strconv.ParseUint(a, 10, 64)
		if err != nil {
			log.Fatal(err)
		}
		go func(n uint64) {
			time.Sleep(time.Duration(n) * time.Millisecond)
			out <- n
		}(i)
	}
	for _ = range os.Args[1:] {
		fmt.Println(<-out)
	}
}
Task: Loops_Nested



C#: using System;

class Program {
    static void Main(string[] args) {
        int[,] a = new int[10, 10];
        Random r = new Random();

        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                a[i, j] = r.Next(0, 21) + 1;
            }
        }
        
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                Console.Write(" {0}", a[i, j]);
                if (a[i, j] == 20) {
                    goto Done;
                }
            }
            Console.WriteLine();
        }
    Done:
        Console.WriteLine();
    }
}


Go: package main

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

func main() {
    rand.Seed(time.Now().UnixNano())

    values := make([][]int, 10)
    for i := range values {
        values[i] = make([]int, 10)
        for j := range values[i] {
            values[i][j] = rand.Intn(20) + 1
        }
    }

outerLoop:
    for i, row := range values {
        fmt.Printf("%3d)", i)
        for _, value := range row {
            fmt.Printf(" %3d", value)
            if value == 20 {
                break outerLoop
            }
        }
        fmt.Printf("\n")
    }
    fmt.Printf("\n")
}
Task: Remove duplicate elements



C#: int[] nums = { 1, 1, 2, 3, 4, 4 };
List<int> unique = new List<int>();
foreach (int n in nums)
    if (!unique.Contains(n))
        unique.Add(n);


Go: package main

import "fmt"

func uniq(list []int) []int {
	unique_set := make(map[int]bool, len(list))
	for _, x := range list {
		unique_set[x] = true
	}
	result := make([]int, 0, len(unique_set))
	for x := range unique_set {
		result = append(result, x)
	}
	return result
}

func main() {
	fmt.Println(uniq([]int{1, 2, 3, 2, 3, 4})) 
}
Task: Look-and-say sequence



C#: using System;
using System.Text;
using System.Linq;

class Program
{
    static string lookandsay(string number)
    {
        StringBuilder result = new StringBuilder();

        char repeat = number[0];
        number = number.Substring(1, number.Length-1)+" ";
        int times = 1;
      
        foreach (char actual in number)
        {
            if (actual != repeat)
            {
                result.Append(Convert.ToString(times)+repeat);
                times = 1;
                repeat = actual;
            }
            else
            {
                times += 1;
            }
        }
        return result.ToString();
    }

    static void Main(string[] args)
    {
        string num = "1"; 

        foreach (int i in Enumerable.Range(1, 10)) {
             Console.WriteLine(num);
             num = lookandsay(num);             
        }
    }
}


Go: package main

import (
    "fmt"
    "strconv"
)

func lss(s string) (r string) {
    c := s[0]
    nc := 1
    for i := 1; i < len(s); i++ {
        d := s[i]
        if d == c {
            nc++
            continue
        }
        r += strconv.Itoa(nc) + string(c)
        c = d
        nc = 1
    }
    return r + strconv.Itoa(nc) + string(c)
}

func main() {
    s := "1"
    fmt.Println(s)
    for i := 0; i < 8; i++ {
        s = lss(s)
        fmt.Println(s)
    }
}
Task: Stack



C#: 
System.Collections.Stack stack = new System.Collections.Stack();
stack.Push( obj );
bool isEmpty = stack.Count == 0;
object top = stack.Peek(); 
top = stack.Pop();


System.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();
stack.Push(new Foo());
bool isEmpty = stack.Count == 0;
Foo top = stack.Peek(); 
top = stack.Pop();


Go: var intStack []int
Task: Totient function



C#: using static System.Console;
using static System.Linq.Enumerable;

public class Program
{
    static void Main()
    {
        for (int i = 1; i <= 25; i++) {
            int t = Totient(i);
            WriteLine(i + "\t" + t + (t == i - 1 ? "\tprime" : ""));
        }
        WriteLine();
        for (int i = 100; i <= 100_000; i *= 10) {
            WriteLine($"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}");
        }
    }

    static int Totient(int n) {
        if (n < 3) return 1;
        if (n == 3) return 2;

        int totient = n;

        if ((n & 1) == 0) {
            totient >>= 1;
            while (((n >>= 1) & 1) == 0) ;
        }

        for (int i = 3; i * i <= n; i += 2) {
            if (n % i == 0) {
                totient -= totient / i;
                while ((n /= i) % i == 0) ;
            }
        }
        if (n > 1) totient -= totient / n;
        return totient;
    }
}


Go: package main

import "fmt"

func gcd(n, k int) int {
    if n < k || k < 1 {
        panic("Need n >= k and k >= 1")
    }

    s := 1
    for n&1 == 0 && k&1 == 0 {
        n >>= 1
        k >>= 1
        s <<= 1
    }

    t := n
    if n&1 != 0 {
        t = -k
    }
    for t != 0 {
        for t&1 == 0 {
            t >>= 1
        }
        if t > 0 {
            n = t
        } else {
            k = -t
        }
        t = n - k
    }
    return n * s
}

func totient(n int) int {
    tot := 0
    for k := 1; k <= n; k++ {
        if gcd(n, k) == 1 {
            tot++
        }
    }
    return tot
}

func main() {
    fmt.Println(" n  phi   prime")
    fmt.Println("---------------")
    count := 0
    for n := 1; n <= 25; n++ {
        tot := totient(n)
        isPrime := n-1 == tot
        if isPrime {
            count++
        }
        fmt.Printf("%2d   %2d   %t\n", n, tot, isPrime)
    }
    fmt.Println("\nNumber of primes up to 25     =", count)
    for n := 26; n <= 100000; n++ {
        tot := totient(n)
        if tot == n-1 {
            count++
        }
        if n == 100 || n == 1000 || n%10000 == 0 {
            fmt.Printf("\nNumber of primes up to %-6d = %d\n", n, count)
        }
    }
}
Task: Conditional structures



C#: if (condition)
{
   
}

if (condition)
{
  
}
else if (condition2)
{
  
}
else
{
  
}


Go: if booleanExpression {
    statements
}
Task: Sort using a custom comparator



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

namespace RosettaCode {
    class SortCustomComparator {
        
        public void CustomSort() {
            String[] items = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" };
            List<String> list = new List<string>(items);

            DisplayList("Unsorted", list);
            
            list.Sort(CustomCompare);
            DisplayList("Descending Length", list);

            list.Sort();
            DisplayList("Ascending order", list);
        }

        
        public int CustomCompare(String x, String y) {
            int result = -x.Length.CompareTo(y.Length);
            if (result == 0) {
                result = x.ToLower().CompareTo(y.ToLower());
            }

            return result;
        }

        
        public void DisplayList(String header, List<String> theList) {
            Console.WriteLine(header);
            Console.WriteLine("".PadLeft(header.Length, '*'));
            foreach (String str in theList) {
                Console.WriteLine(str);
            }
            Console.WriteLine();
        }
    }
}


Go: package main

import (
    "fmt"
    "sort"
    "strings"
)

type sortable []string

func (s sortable) Len() int      { return len(s) }
func (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s sortable) Less(i, j int) bool {
    a, b := s[i], s[j]
    if len(a) != len(b) {
        return len(a) > len(b)
    }
    return strings.ToLower(a) < strings.ToLower(b)
}

func main() {
    var s sortable = strings.Fields("To tell your name the livelong day To an admiring bog")
    fmt.Println(s, "(original)")

    sort.Sort(s)
    fmt.Println(s, "(sorted)")
}
Task: Animation



C#: using System;
using System.Drawing;
using System.Windows.Forms;

namespace BasicAnimation
{
  class BasicAnimationForm : Form
  {
    bool isReverseDirection;
    Label textLabel;
    Timer timer;

    internal BasicAnimationForm()
    {
      this.Size = new Size(150, 75);
      this.Text = "Basic Animation";

      textLabel = new Label();
      textLabel.Text = "Hello World! ";
      textLabel.Location = new Point(3,3);
      textLabel.AutoSize = true;
      textLabel.Click += new EventHandler(textLabel_OnClick);
      this.Controls.Add(textLabel);

      timer = new Timer();
      timer.Interval = 500;
      timer.Tick += new EventHandler(timer_OnTick);
      timer.Enabled = true;

      isReverseDirection = false;
    }

    private void timer_OnTick(object sender, EventArgs e)
    {
      string oldText = textLabel.Text, newText;
      if(isReverseDirection)
        newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);
      else
        newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);
      textLabel.Text = newText;
    }

    private void textLabel_OnClick(object sender, EventArgs e)
    {
      isReverseDirection = !isReverseDirection;
    }
  }

   class Program
   {
      static void Main()
      {
	Application.Run(new BasicAnimationForm());
      }
   }
}


Go: package main

import (
    "log"
    "time"

    "github.com/gdamore/tcell"
)

const (
    msg             = "Hello World! "
    x0, y0          = 8, 3
    shiftsPerSecond = 4
    clicksToExit    = 5
)

func main() {
    s, err := tcell.NewScreen()
    if err != nil {
        log.Fatal(err)
    }
    if err = s.Init(); err != nil {
        log.Fatal(err)
    }
    s.Clear()
    s.EnableMouse()
    tick := time.Tick(time.Second / shiftsPerSecond)
    click := make(chan bool)
    go func() {
        for {
            em, ok := s.PollEvent().(*tcell.EventMouse)
            if !ok || em.Buttons()&0xFF == tcell.ButtonNone {
                continue
            }
            mx, my := em.Position()
            if my == y0 && mx >= x0 && mx < x0+len(msg) {
                click <- true
            }
        }
    }()
    for inc, shift, clicks := 1, 0, 0; ; {
        select {
        case <-tick:
            shift = (shift + inc) % len(msg)
            for i, r := range msg {
                s.SetContent(x0+((shift+i)%len(msg)), y0, r, nil, 0)
            }
            s.Show()
        case <-click:
            clicks++
            if clicks == clicksToExit {
                s.Fini()
                return
            }
            inc = len(msg) - inc
        }
    }
}
Task: Sorting algorithms_Radix sort



C#: using System;

namespace RadixSort
{
    class Program
    {
        static void Sort(int[] old)
        {
            int i, j;
            int[] tmp = new int[old.Length];
            for (int shift = 31; shift > -1; --shift)
            {
                j = 0;
                for (i = 0; i < old.Length; ++i)
                {
                    bool move = (old[i] << shift) >= 0;
                    if (shift == 0 ? !move : move)  
                        old[i-j] = old[i];
                    else                            
                        tmp[j++] = old[i];
                }
                Array.Copy(tmp, 0, old, old.Length-j, j);
            }
        }
        static void Main(string[] args)
        {
            int[] old = new int[] { 2, 5, 1, -3, 4 };
            Console.WriteLine(string.Join(", ", old));
            Sort(old);
            Console.WriteLine(string.Join(", ", old));
            Console.Read();
        }
    }
}


Go: package main

import (
    "bytes"
    "encoding/binary"
    "fmt"
)


type word int32
const wordLen = 4
const highBit = -1 << 31

var data = []word{170, 45, 75, -90, -802, 24, 2, 66}

func main() {
    buf := bytes.NewBuffer(nil)
    ds := make([][]byte, len(data))
    for i, x := range data {
        binary.Write(buf, binary.LittleEndian, x^highBit)
        b := make([]byte, wordLen)
        buf.Read(b)
        ds[i] = b
    }
    bins := make([][][]byte, 256)
    for i := 0; i < wordLen; i++ {
        for _, b := range ds {
            bins[b[i]] = append(bins[b[i]], b)
        }
        j := 0
        for k, bs := range bins {
            copy(ds[j:], bs)
            j += len(bs)
            bins[k] = bs[:0]
        }
    }
    fmt.Println("original:", data)
    var w word
    for i, b := range ds {
        buf.Write(b)
        binary.Read(buf, binary.LittleEndian, &w)
        data[i] = w^highBit
    }
    fmt.Println("sorted:  ", data)
}
Task: List comprehensions



C#: using System.Linq;

static class Program
{
  static void Main()
  {
    var ts =
      from a in Enumerable.Range(1, 20)
      from b in Enumerable.Range(a, 21 - a)
      from c in Enumerable.Range(b, 21 - b)
      where a * a + b * b == c * c
      select new { a, b, c };

      foreach (var t in ts)
        System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
  }
}


Go: package main

import "fmt"

type (
    seq  []int
    sofs []seq
)

func newSeq(start, end int) seq {
    if end < start {
        end = start
    }
    s := make(seq, end-start+1)
    for i := 0; i < len(s); i++ {
        s[i] = start + i
    }
    return s
}

func newSofs() sofs {
    return sofs{seq{}}
}

func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs {
    var s2 sofs
    for _, t := range expr(s, in) {
        if pred(t) {
            s2 = append(s2, t)
        }
    }
    return s2
}

func (s sofs) build(t seq) sofs {
    var u sofs
    for _, ss := range s {
        for _, tt := range t {
            uu := make(seq, len(ss))
            copy(uu, ss)
            uu = append(uu, tt)
            u = append(u, uu)
        }
    }
    return u
}

func main() {
    pt := newSofs()
    in := newSeq(1, 20)
    expr := func(s sofs, t seq) sofs {
        return s.build(t).build(t).build(t)
    }
    pred := func(t seq) bool {
        if len(t) != 3 {
            return false
        }
        return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2]
    }
    pt = pt.listComp(in, expr, pred)
    fmt.Println(pt)
}
Task: Sorting algorithms_Selection sort



C#: class SelectionSort<T> where T : IComparable {
    public T[] Sort(T[] list) {
        int k;
        T temp;

        for (int i = 0; i < list.Length; i++) {
            k = i;
            for (int j=i + 1; j < list.Length; j++) {
                if (list[j].CompareTo(list[k]) < 0) {
                    k = j;
                }
            }
            temp = list[i];
            list[i] = list[k];
            list[k] = temp;
        }

        return list;
    }
}


Go: package main

import "fmt"

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

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

func selectionSort(a []int) {
    last := len(a) - 1
    for i := 0; i < last; i++ {
        aMin := a[i]
        iMin := i
        for j := i + 1; j < len(a); j++ {
            if a[j] < aMin {
                aMin = a[j]
                iMin = j
            }
        }
        a[i], a[iMin] = aMin, a[i]
    }
}
Task: Apply a callback to an array



C#: int[] intArray = { 1, 2, 3, 4, 5 };

int[] squares1 = intArray.Select(x => x * x).ToArray();


int[] squares2 = (from x in intArray
                  select x * x).ToArray();


foreach (var i in intArray)
    Console.WriteLine(i * i);


Go: package main

import "fmt"

func main() {
    for _, i := range []int{1, 2, 3, 4, 5} {
        fmt.Println(i * i)
    }
}
Task: Singleton



C#: public sealed class Singleton1 
{
    private static Singleton1 instance;
    private static readonly object lockObj = new object();
    
    public static Singleton1 Instance {
        get {
            lock(lockObj) {
                if (instance == null) {
                    instance = new Singleton1();
                }
            }
            return instance;
        }
    }
}


Go: package main

import (
    "log"
    "math/rand"
    "sync"
    "time"
)

var (
    instance string
    once     sync.Once 
)

func claim(color string, w *sync.WaitGroup) {
    time.Sleep(time.Duration(rand.Intn(1e8))) 
    log.Println("trying to claim", color)
    once.Do(func() { instance = color })
    log.Printf("tried %s. instance: %s", color, instance)
    w.Done()
}

func main() {
    rand.Seed(time.Now().Unix())
    var w sync.WaitGroup
    w.Add(2)
    go claim("red", &w) 
    go claim("blue", &w)
    w.Wait()
    log.Println("after trying both, instance =", instance)
}