WeixiangYan/CodeTransOcean huggingface dataset:
Task: Loops_Foreach


C++: for (container_type::iterator i = container.begin(); i != container.end(); ++i)
{
  std::cout << *i << "\n";
}


C#: string[] things = {"Apple", "Banana", "Coconut"};

foreach (string thing in things)
{
    Console.WriteLine(thing);
}
Task: Loops_Foreach


C++: for (container_type::iterator i = container.begin(); i != container.end(); ++i)
{
  std::cout << *i << "\n";
}



Go: func printAll(values []int) {
   for i, x := range values {
      fmt.Printf("Item %d = %d\n", i, x)
   }
}
Task: Loops_Foreach


C++: for (container_type::iterator i = container.begin(); i != container.end(); ++i)
{
  std::cout << *i << "\n";
}




Java: module LoopForEach
    {
    @Inject Console console;
    void run()
        {
        val vals = [10, 20, 30, 40];
        console.print("Array of values:");
        Loop: for (val val : vals)
            {
            console.print($"  value #{Loop.count + 1}: {val}");
            }

        Map<String, Int> pairs = ["x"=42, "y"=69];
        console.print("\nKeys and values:");
        for ((String key, Int val) : pairs)
            {
            console.print($"  {key}={val}");
            }
        console.print("\nJust the keys:");
        Loop: for (String key : pairs)
            {
            console.print($"  key #{Loop.count + 1}: {key}");
            }

        console.print("\nValues from a range:");
        for (Int n : 1..5)
            {
            console.print($"  {n}");
            }
        }
    }
Task: Loops_Foreach


C++: for (container_type::iterator i = container.begin(); i != container.end(); ++i)
{
  std::cout << *i << "\n";
}







VB: Public Sub LoopsForeach()
    Dim FruitArray() As Variant
    Dim Fruit As Variant
    FruitArray = [{"Apple","Banana","Strawberry"}]
    Dim FruitBasket As Collection
    Set FruitBasket = New Collection
    For Each Fruit In FruitArray
        FruitBasket.Add Fruit
    Next Fruit
    For Each Fruit In FruitBasket
        Debug.Print Fruit
    Next Fruit
End Sub
Task: Loops_Foreach



C#: string[] things = {"Apple", "Banana", "Coconut"};

foreach (string thing in things)
{
    Console.WriteLine(thing);
}


Go: func printAll(values []int) {
   for i, x := range values {
      fmt.Printf("Item %d = %d\n", i, x)
   }
}
Task: Loops_Foreach



C#: string[] things = {"Apple", "Banana", "Coconut"};

foreach (string thing in things)
{
    Console.WriteLine(thing);
}



Java: module LoopForEach
    {
    @Inject Console console;
    void run()
        {
        val vals = [10, 20, 30, 40];
        console.print("Array of values:");
        Loop: for (val val : vals)
            {
            console.print($"  value #{Loop.count + 1}: {val}");
            }

        Map<String, Int> pairs = ["x"=42, "y"=69];
        console.print("\nKeys and values:");
        for ((String key, Int val) : pairs)
            {
            console.print($"  {key}={val}");
            }
        console.print("\nJust the keys:");
        Loop: for (String key : pairs)
            {
            console.print($"  key #{Loop.count + 1}: {key}");
            }

        console.print("\nValues from a range:");
        for (Int n : 1..5)
            {
            console.print($"  {n}");
            }
        }
    }
Task: Loops_Foreach



C#: string[] things = {"Apple", "Banana", "Coconut"};

foreach (string thing in things)
{
    Console.WriteLine(thing);
}





Python: for i in collection:
   print i
Task: Loops_Foreach



C#: string[] things = {"Apple", "Banana", "Coconut"};

foreach (string thing in things)
{
    Console.WriteLine(thing);
}






VB: Public Sub LoopsForeach()
    Dim FruitArray() As Variant
    Dim Fruit As Variant
    FruitArray = [{"Apple","Banana","Strawberry"}]
    Dim FruitBasket As Collection
    Set FruitBasket = New Collection
    For Each Fruit In FruitArray
        FruitBasket.Add Fruit
    Next Fruit
    For Each Fruit In FruitBasket
        Debug.Print Fruit
    Next Fruit
End Sub
Task: Loops_Foreach




Go: func printAll(values []int) {
   for i, x := range values {
      fmt.Printf("Item %d = %d\n", i, x)
   }
}


Java: module LoopForEach
    {
    @Inject Console console;
    void run()
        {
        val vals = [10, 20, 30, 40];
        console.print("Array of values:");
        Loop: for (val val : vals)
            {
            console.print($"  value #{Loop.count + 1}: {val}");
            }

        Map<String, Int> pairs = ["x"=42, "y"=69];
        console.print("\nKeys and values:");
        for ((String key, Int val) : pairs)
            {
            console.print($"  {key}={val}");
            }
        console.print("\nJust the keys:");
        Loop: for (String key : pairs)
            {
            console.print($"  key #{Loop.count + 1}: {key}");
            }

        console.print("\nValues from a range:");
        for (Int n : 1..5)
            {
            console.print($"  {n}");
            }
        }
    }
Task: Loops_Foreach





Java: module LoopForEach
    {
    @Inject Console console;
    void run()
        {
        val vals = [10, 20, 30, 40];
        console.print("Array of values:");
        Loop: for (val val : vals)
            {
            console.print($"  value #{Loop.count + 1}: {val}");
            }

        Map<String, Int> pairs = ["x"=42, "y"=69];
        console.print("\nKeys and values:");
        for ((String key, Int val) : pairs)
            {
            console.print($"  {key}={val}");
            }
        console.print("\nJust the keys:");
        Loop: for (String key : pairs)
            {
            console.print($"  key #{Loop.count + 1}: {key}");
            }

        console.print("\nValues from a range:");
        for (Int n : 1..5)
            {
            console.print($"  {n}");
            }
        }
    }




VB: Public Sub LoopsForeach()
    Dim FruitArray() As Variant
    Dim Fruit As Variant
    FruitArray = [{"Apple","Banana","Strawberry"}]
    Dim FruitBasket As Collection
    Set FruitBasket = New Collection
    For Each Fruit In FruitArray
        FruitBasket.Add Fruit
    Next Fruit
    For Each Fruit In FruitBasket
        Debug.Print Fruit
    Next Fruit
End Sub
Task: Loops_Foreach




Go: func printAll(values []int) {
   for i, x := range values {
      fmt.Printf("Item %d = %d\n", i, x)
   }
}




Python: for i in collection:
   print i
Task: Loops_Foreach




Go: func printAll(values []int) {
   for i, x := range values {
      fmt.Printf("Item %d = %d\n", i, x)
   }
}





VB: Public Sub LoopsForeach()
    Dim FruitArray() As Variant
    Dim Fruit As Variant
    FruitArray = [{"Apple","Banana","Strawberry"}]
    Dim FruitBasket As Collection
    Set FruitBasket = New Collection
    For Each Fruit In FruitArray
        FruitBasket.Add Fruit
    Next Fruit
    For Each Fruit In FruitBasket
        Debug.Print Fruit
    Next Fruit
End Sub
Task: Loops_Foreach


C++: for (container_type::iterator i = container.begin(); i != container.end(); ++i)
{
  std::cout << *i << "\n";
}






Python: for i in collection:
   print i
Task: Loops_Foreach





Java: module LoopForEach
    {
    @Inject Console console;
    void run()
        {
        val vals = [10, 20, 30, 40];
        console.print("Array of values:");
        Loop: for (val val : vals)
            {
            console.print($"  value #{Loop.count + 1}: {val}");
            }

        Map<String, Int> pairs = ["x"=42, "y"=69];
        console.print("\nKeys and values:");
        for ((String key, Int val) : pairs)
            {
            console.print($"  {key}={val}");
            }
        console.print("\nJust the keys:");
        Loop: for (String key : pairs)
            {
            console.print($"  key #{Loop.count + 1}: {key}");
            }

        console.print("\nValues from a range:");
        for (Int n : 1..5)
            {
            console.print($"  {n}");
            }
        }
    }



Python: for i in collection:
   print i
Task: Loops_Foreach







Python: for i in collection:
   print i


VB: Public Sub LoopsForeach()
    Dim FruitArray() As Variant
    Dim Fruit As Variant
    FruitArray = [{"Apple","Banana","Strawberry"}]
    Dim FruitBasket As Collection
    Set FruitBasket = New Collection
    For Each Fruit In FruitArray
        FruitBasket.Add Fruit
    Next Fruit
    For Each Fruit In FruitBasket
        Debug.Print Fruit
    Next Fruit
End Sub
Task: Loops_Foreach

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

const char *list[] = {"Red","Green","Blue","Black","White"};
#define LIST_SIZE (sizeof(list)/sizeof(list[0]))

int ix;
for(ix=0; ix<LIST_SIZE; ix++) {
   printf("%s\n", list[ix]);
}






PHP: foreach ($collect as $i) {
   echo "$i\n";
}

foreach ($collect as $key => $i) {
   echo "\$collect[$key] = $i\n";
}
Task: Loops_Foreach



C#: string[] things = {"Apple", "Banana", "Coconut"};

foreach (string thing in things)
{
    Console.WriteLine(thing);
}




PHP: foreach ($collect as $i) {
   echo "$i\n";
}

foreach ($collect as $key => $i) {
   echo "\$collect[$key] = $i\n";
}
Task: Loops_Foreach


C++: for (container_type::iterator i = container.begin(); i != container.end(); ++i)
{
  std::cout << *i << "\n";
}





PHP: foreach ($collect as $i) {
   echo "$i\n";
}

foreach ($collect as $key => $i) {
   echo "\$collect[$key] = $i\n";
}
Task: Loops_Foreach




Go: func printAll(values []int) {
   for i, x := range values {
      fmt.Printf("Item %d = %d\n", i, x)
   }
}



PHP: foreach ($collect as $i) {
   echo "$i\n";
}

foreach ($collect as $key => $i) {
   echo "\$collect[$key] = $i\n";
}
Task: Loops_Foreach





Java: module LoopForEach
    {
    @Inject Console console;
    void run()
        {
        val vals = [10, 20, 30, 40];
        console.print("Array of values:");
        Loop: for (val val : vals)
            {
            console.print($"  value #{Loop.count + 1}: {val}");
            }

        Map<String, Int> pairs = ["x"=42, "y"=69];
        console.print("\nKeys and values:");
        for ((String key, Int val) : pairs)
            {
            console.print($"  {key}={val}");
            }
        console.print("\nJust the keys:");
        Loop: for (String key : pairs)
            {
            console.print($"  key #{Loop.count + 1}: {key}");
            }

        console.print("\nValues from a range:");
        for (Int n : 1..5)
            {
            console.print($"  {n}");
            }
        }
    }


PHP: foreach ($collect as $i) {
   echo "$i\n";
}

foreach ($collect as $key => $i) {
   echo "\$collect[$key] = $i\n";
}
Task: Loops_Foreach






PHP: foreach ($collect as $i) {
   echo "$i\n";
}

foreach ($collect as $key => $i) {
   echo "\$collect[$key] = $i\n";
}


Python: for i in collection:
   print i
Task: Loops_Foreach






PHP: foreach ($collect as $i) {
   echo "$i\n";
}

foreach ($collect as $key => $i) {
   echo "\$collect[$key] = $i\n";
}



VB: Public Sub LoopsForeach()
    Dim FruitArray() As Variant
    Dim Fruit As Variant
    FruitArray = [{"Apple","Banana","Strawberry"}]
    Dim FruitBasket As Collection
    Set FruitBasket = New Collection
    For Each Fruit In FruitArray
        FruitBasket.Add Fruit
    Next Fruit
    For Each Fruit In FruitBasket
        Debug.Print Fruit
    Next Fruit
End Sub
Task: Determine if a string has all unique characters


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

void string_has_repeated_character(const std::string& str) {
    size_t len = str.length();
    std::cout << "input: \"" << str << "\", length: " << len << '\n';
    for (size_t i = 0; i < len; ++i) {
        for (size_t j = i + 1; j < len; ++j) {
            if (str[i] == str[j]) {
                std::cout << "String contains a repeated character.\n";
                std::cout << "Character '" << str[i]
                    << "' (hex " << std::hex << static_cast<unsigned int>(str[i])
                    << ") occurs at positions " << std::dec << i + 1
                    << " and " << j + 1 << ".\n\n";
                return;
            }
        }
    }
    std::cout << "String contains no repeated characters.\n\n";
}

int main() {
    string_has_repeated_character("");
    string_has_repeated_character(".");
    string_has_repeated_character("abcABC");
    string_has_repeated_character("XYZ ZYX");
    string_has_repeated_character("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ");
    return 0;
}


C#: using System;
using System.Linq;

public class Program
{
    static void Main
    {
        string[] input = {"", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"};
        foreach (string s in input) {
            Console.WriteLine($"\"{s}\" (Length {s.Length}) " +
                string.Join(", ",
                    s.Select((c, i) => (c, i))
                    .GroupBy(t => t.c).Where(g => g.Count() > 1)
                    .Select(g => $"'{g.Key}' (0X{(int)g.Key:X})[{string.Join(", ", g.Select(t => t.i))}]")
                    .DefaultIfEmpty("All characters are unique.")
                )
            );
        }
    }
}
Task: Determine if a string has all unique characters


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

void string_has_repeated_character(const std::string& str) {
    size_t len = str.length();
    std::cout << "input: \"" << str << "\", length: " << len << '\n';
    for (size_t i = 0; i < len; ++i) {
        for (size_t j = i + 1; j < len; ++j) {
            if (str[i] == str[j]) {
                std::cout << "String contains a repeated character.\n";
                std::cout << "Character '" << str[i]
                    << "' (hex " << std::hex << static_cast<unsigned int>(str[i])
                    << ") occurs at positions " << std::dec << i + 1
                    << " and " << j + 1 << ".\n\n";
                return;
            }
        }
    }
    std::cout << "String contains no repeated characters.\n\n";
}

int main() {
    string_has_repeated_character("");
    string_has_repeated_character(".");
    string_has_repeated_character("abcABC");
    string_has_repeated_character("XYZ ZYX");
    string_has_repeated_character("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ");
    return 0;
}



Go: package main

import "fmt"

func analyze(s string) {
    chars := []rune(s)
    le := len(chars)
    fmt.Printf("Analyzing %q which has a length of %d:\n", s, le)
    if le > 1 {
        for i := 0; i < le-1; i++ {
            for j := i + 1; j < le; j++ {
                if chars[j] == chars[i] {
                    fmt.Println("  Not all characters in the string are unique.")
                    fmt.Printf("  %q (%#[1]x) is duplicated at positions %d and %d.\n\n", chars[i], i+1, j+1)
                    return
                }
            }
        }
    }
    fmt.Println("  All characters in the string are unique.\n")
}

func main() {
    strings := []string{
        "",
        ".",
        "abcABC",
        "XYZ ZYX",
        "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
        "01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X",
        "hétérogénéité",
        "🎆🎃🎇🎈",
        "😍😀🙌💃😍🙌",
        "🐠🐟🐡🦈🐬🐳🐋🐡",
    }
    for _, s := range strings {
        analyze(s)
    }
}
Task: Determine if a string has all unique characters


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

void string_has_repeated_character(const std::string& str) {
    size_t len = str.length();
    std::cout << "input: \"" << str << "\", length: " << len << '\n';
    for (size_t i = 0; i < len; ++i) {
        for (size_t j = i + 1; j < len; ++j) {
            if (str[i] == str[j]) {
                std::cout << "String contains a repeated character.\n";
                std::cout << "Character '" << str[i]
                    << "' (hex " << std::hex << static_cast<unsigned int>(str[i])
                    << ") occurs at positions " << std::dec << i + 1
                    << " and " << j + 1 << ".\n\n";
                return;
            }
        }
    }
    std::cout << "String contains no repeated characters.\n\n";
}

int main() {
    string_has_repeated_character("");
    string_has_repeated_character(".");
    string_has_repeated_character("abcABC");
    string_has_repeated_character("XYZ ZYX");
    string_has_repeated_character("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ");
    return 0;
}




Java: import java.util.HashMap;
import java.util.Map;



public class StringUniqueCharacters {

    public static void main(String[] args) {
        System.out.printf("%-40s  %2s  %10s  %8s  %s  %s%n", "String", "Length", "All Unique", "1st Diff", "Hex", "Positions");
        System.out.printf("%-40s  %2s  %10s  %8s  %s  %s%n", "------------------------", "------", "----------", "--------", "---", "---------");
        for ( String s : new String[] {"", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"} ) {
            processString(s);
        }
    }
    
    
    
    private static void processString(String input) {
        Map<Character,Integer> charMap = new HashMap<>(); 
        char dup = 0;
        int index = 0;
        int pos1 = -1;
        int pos2 = -1;
        for ( char key : input.toCharArray() ) {
            index++;
            if ( charMap.containsKey(key) ) {
                dup = key;
                pos1 = charMap.get(key);
                pos2 = index;
                break;
            }
            charMap.put(key, index);
        }
        String unique = dup == 0 ? "yes" : "no";
        String diff = dup == 0 ? "" : "'" + dup + "'";
        String hex = dup == 0 ? "" : Integer.toHexString(dup).toUpperCase();
        String position = dup == 0 ? "" : pos1 + " " + pos2;
        System.out.printf("%-40s  %-6d  %-10s  %-8s  %-3s  %-5s%n", input, input.length(), unique, diff, hex, position);
    }

}
Task: Determine if a string has all unique characters


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

void string_has_repeated_character(const std::string& str) {
    size_t len = str.length();
    std::cout << "input: \"" << str << "\", length: " << len << '\n';
    for (size_t i = 0; i < len; ++i) {
        for (size_t j = i + 1; j < len; ++j) {
            if (str[i] == str[j]) {
                std::cout << "String contains a repeated character.\n";
                std::cout << "Character '" << str[i]
                    << "' (hex " << std::hex << static_cast<unsigned int>(str[i])
                    << ") occurs at positions " << std::dec << i + 1
                    << " and " << j + 1 << ".\n\n";
                return;
            }
        }
    }
    std::cout << "String contains no repeated characters.\n\n";
}

int main() {
    string_has_repeated_character("");
    string_has_repeated_character(".");
    string_has_repeated_character("abcABC");
    string_has_repeated_character("XYZ ZYX");
    string_has_repeated_character("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ");
    return 0;
}







VB: Module Module1

    Sub Main()
        Dim input() = {"", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"}
        For Each s In input
            Console.WriteLine($"
        Next
    End Sub

End Module
Task: Determine if a string has all unique characters



C#: using System;
using System.Linq;

public class Program
{
    static void Main
    {
        string[] input = {"", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"};
        foreach (string s in input) {
            Console.WriteLine($"\"{s}\" (Length {s.Length}) " +
                string.Join(", ",
                    s.Select((c, i) => (c, i))
                    .GroupBy(t => t.c).Where(g => g.Count() > 1)
                    .Select(g => $"'{g.Key}' (0X{(int)g.Key:X})[{string.Join(", ", g.Select(t => t.i))}]")
                    .DefaultIfEmpty("All characters are unique.")
                )
            );
        }
    }
}



Java: import java.util.HashMap;
import java.util.Map;



public class StringUniqueCharacters {

    public static void main(String[] args) {
        System.out.printf("%-40s  %2s  %10s  %8s  %s  %s%n", "String", "Length", "All Unique", "1st Diff", "Hex", "Positions");
        System.out.printf("%-40s  %2s  %10s  %8s  %s  %s%n", "------------------------", "------", "----------", "--------", "---", "---------");
        for ( String s : new String[] {"", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"} ) {
            processString(s);
        }
    }
    
    
    
    private static void processString(String input) {
        Map<Character,Integer> charMap = new HashMap<>(); 
        char dup = 0;
        int index = 0;
        int pos1 = -1;
        int pos2 = -1;
        for ( char key : input.toCharArray() ) {
            index++;
            if ( charMap.containsKey(key) ) {
                dup = key;
                pos1 = charMap.get(key);
                pos2 = index;
                break;
            }
            charMap.put(key, index);
        }
        String unique = dup == 0 ? "yes" : "no";
        String diff = dup == 0 ? "" : "'" + dup + "'";
        String hex = dup == 0 ? "" : Integer.toHexString(dup).toUpperCase();
        String position = dup == 0 ? "" : pos1 + " " + pos2;
        System.out.printf("%-40s  %-6d  %-10s  %-8s  %-3s  %-5s%n", input, input.length(), unique, diff, hex, position);
    }

}
Task: Determine if a string has all unique characters



C#: using System;
using System.Linq;

public class Program
{
    static void Main
    {
        string[] input = {"", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"};
        foreach (string s in input) {
            Console.WriteLine($"\"{s}\" (Length {s.Length}) " +
                string.Join(", ",
                    s.Select((c, i) => (c, i))
                    .GroupBy(t => t.c).Where(g => g.Count() > 1)
                    .Select(g => $"'{g.Key}' (0X{(int)g.Key:X})[{string.Join(", ", g.Select(t => t.i))}]")
                    .DefaultIfEmpty("All characters are unique.")
                )
            );
        }
    }
}





Python: 

from itertools import groupby



def duplicatedCharIndices(s):
    
    def go(xs):
        if 1 < len(xs):
            duplicates = list(filter(lambda kv: 1 < len(kv[1]), [
                (k, list(v)) for k, v in groupby(
                    sorted(xs, key=swap),
                    key=snd
                )
            ]))
            return Just(second(fmap(fst))(
                sorted(
                    duplicates,
                    key=lambda kv: kv[1][0]
                )[0]
            )) if duplicates else Nothing()
        else:
            return Nothing()
    return go(list(enumerate(s)))




def main():
    

    def showSample(s):
        return repr(s) + ' (' + str(len(s)) + ')'

    def showDuplicate(cix):
        c, ix = cix
        return repr(c) + (
            ' (' + hex(ord(c)) + ') at ' + repr(ix)
        )

    print(
        fTable('First duplicated character, if any:')(
            showSample
        )(maybe('None')(showDuplicate))(duplicatedCharIndices)([
            '', '.', 'abcABC', 'XYZ ZYX',
            '1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'
        ])
    )






def fTable(s):
    
    def go(xShow, fxShow, f, xs):
        ys = [xShow(x) for x in xs]
        w = max(map(len, ys))
        return s + '\n' + '\n'.join(map(
            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
            xs, ys
        ))
    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
        xShow, fxShow, f, xs
    )





def Just(x):
    
    return {'type': 'Maybe', 'Nothing': False, 'Just': x}



def Nothing():
    
    return {'type': 'Maybe', 'Nothing': True}



def fmap(f):
    
    return lambda xs: [f(x) for x in xs]



def fst(tpl):
    
    return tpl[0]



def head(xs):
    
    return xs[0] if isinstance(xs, list) else next(xs)



def maybe(v):
    
    return lambda f: lambda m: v if (
        None is m or m.get('Nothing')
    ) else f(m.get('Just'))



def second(f):
    
    return lambda xy: (xy[0], f(xy[1]))



def snd(tpl):
    
    return tpl[1]



def swap(tpl):
    
    return (tpl[1], tpl[0])



if __name__ == '__main__':
    main()