WeixiangYan/CodeTransOcean huggingface dataset:
Task: Order two numerical lists


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

int main() {
  std::vector<int> a;
  a.push_back(1);
  a.push_back(2);
  a.push_back(1);
  a.push_back(3);
  a.push_back(2);
  std::vector<int> b;
  b.push_back(1);
  b.push_back(2);
  b.push_back(0);
  b.push_back(4);
  b.push_back(4);
  b.push_back(0);
  b.push_back(0);
  b.push_back(0);

  std::cout << std::boolalpha << (a < b) << std::endl; 
  return 0;
}
Task: Order two numerical lists





Java: import java.util.Arrays;
import java.util.List;

public class ListOrder{
	public static boolean ordered(double[] first, double[] second){
		if(first.length == 0) return true;
		if(second.length == 0) return false;
		if(first[0] == second[0])
			return ordered(Arrays.copyOfRange(first, 1, first.length),
					Arrays.copyOfRange(second, 1, second.length));
		return first[0] < second[0];
	}
	
	public static <T extends Comparable<? super T>> boolean ordered(List<T> first, List<T> second){
		int i = 0;
		for(; i < first.size() && i < second.size();i++){
			int cmp = first.get(i).compareTo(second.get(i));
			if(cmp == 0) continue;
			if(cmp < 0) return true;
			return false;
		}
		return i == first.size();
	}
	
	public static boolean ordered2(double[] first, double[] second){
		int i = 0;
		for(; i < first.length && i < second.length;i++){
			if(first[i] == second[i]) continue;
			if(first[i] < second[i]) return true;
			return false;
		}
		return i == first.length;
	}
}
Task: Order two numerical lists







Python: >>> [1,2,1,3,2] < [1,2,0,4,4,0,0,0]
False
Task: Order two numerical lists








VB: Private Function order(list1 As Variant, list2 As Variant) As Boolean
    i = 1
    Do While list1(i) <= list2(i)
        i = i + 1
        If i > UBound(list1) Then
            order = True
            Exit Function
        End If
        If i > UBound(list2) Then
            order = False
            Exit Function
        End If
    Loop
    order = False
End Function
Public Sub main()
    Debug.Print order([{1, 2, 3, 4}], [{1,2,0,1,2}])
    Debug.Print order([{1, 2, 3, 4}], [{1,2,3}])
    Debug.Print order([{1, 2, 3}], [{1,2,3,4}])
End Sub
Task: Order two numerical lists




Go: package main

import "fmt"



func lessRune(a, b []rune) bool {
    return string(a) < string(b) 
}



type numericType int

func lessNT(a, b []numericType) bool {
    l := len(a)
    if len(b) < l {
        l = len(b)
    }
    for i := 0; i < l; i++ {
        if a[i] != b[i] {
            return a[i] < b[i]
        }
    }
    return l < len(b)
}

var testCases = [][][]numericType{
    {{0}, {}},
    {{}, {}},
    {{}, {0}},

    {{-1}, {0}},
    {{0}, {0}},
    {{0}, {-1}},

    {{0}, {0, -1}},
    {{0}, {0, 0}},
    {{0}, {0, 1}},
    {{0, -1}, {0}},
    {{0, 0}, {0}},
    {{0, 0}, {1}},
}

func main() {
    
    for _, tc := range testCases {
        fmt.Printf("order %6s before %6s : %t\n",
            fmt.Sprintf("%v", tc[0]),
            fmt.Sprintf("%v", tc[1]),
            lessNT(tc[0], tc[1]))
    }
    fmt.Println()

    
    
    for _, tc := range testCases {
        a := toByte(tc[0])
        b := toByte(tc[1])
        fmt.Printf("order %6q before %6q : %t\n",
            string(a),
            string(b),
            lessByte(a, b))
    }
}

func toByte(a []numericType) []byte {
    b := make([]byte, len(a))
    for i, n := range a {
        b[i] = 'b' + byte(n)
    }
    return b
}
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.")
                )
            );
        }
    }
}









Ada: with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_All_Chars_Unique is
   procedure All_Chars_Unique (S : in String) is
   begin
      Put_Line ("Input = """ & S & """, length =" & S'Length'Image);
      for I in S'First .. S'Last - 1 loop
         for J in I + 1 .. S'Last loop
            if S(I) = S(J) then
               Put (" First duplicate at positions" & I'Image &
                    " and" & J'Image & ", character = '" & S(I) &
                    "', hex = ");
               Put (Character'Pos (S(I)), Width => 0, Base => 16);
               New_Line;
               return;
            end if;
         end loop;
      end loop;
      Put_Line (" All characters are unique.");
   end All_Chars_Unique;
begin
   All_Chars_Unique ("");
   All_Chars_Unique (".");
   All_Chars_Unique ("abcABC");
   All_Chars_Unique ("XYZ ZYX");
   All_Chars_Unique ("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ");
end Test_All_Chars_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;
}










Ada: with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_All_Chars_Unique is
   procedure All_Chars_Unique (S : in String) is
   begin
      Put_Line ("Input = """ & S & """, length =" & S'Length'Image);
      for I in S'First .. S'Last - 1 loop
         for J in I + 1 .. S'Last loop
            if S(I) = S(J) then
               Put (" First duplicate at positions" & I'Image &
                    " and" & J'Image & ", character = '" & S(I) &
                    "', hex = ");
               Put (Character'Pos (S(I)), Width => 0, Base => 16);
               New_Line;
               return;
            end if;
         end loop;
      end loop;
      Put_Line (" All characters are unique.");
   end All_Chars_Unique;
begin
   All_Chars_Unique ("");
   All_Chars_Unique (".");
   All_Chars_Unique ("abcABC");
   All_Chars_Unique ("XYZ ZYX");
   All_Chars_Unique ("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ");
end Test_All_Chars_Unique;
Task: Determine if a string has all unique characters




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)
    }
}








Ada: with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_All_Chars_Unique is
   procedure All_Chars_Unique (S : in String) is
   begin
      Put_Line ("Input = """ & S & """, length =" & S'Length'Image);
      for I in S'First .. S'Last - 1 loop
         for J in I + 1 .. S'Last loop
            if S(I) = S(J) then
               Put (" First duplicate at positions" & I'Image &
                    " and" & J'Image & ", character = '" & S(I) &
                    "', hex = ");
               Put (Character'Pos (S(I)), Width => 0, Base => 16);
               New_Line;
               return;
            end if;
         end loop;
      end loop;
      Put_Line (" All characters are unique.");
   end All_Chars_Unique;
begin
   All_Chars_Unique ("");
   All_Chars_Unique (".");
   All_Chars_Unique ("abcABC");
   All_Chars_Unique ("XYZ ZYX");
   All_Chars_Unique ("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ");
end Test_All_Chars_Unique;
Task: Determine if a string has all unique characters





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);
    }

}







Ada: with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_All_Chars_Unique is
   procedure All_Chars_Unique (S : in String) is
   begin
      Put_Line ("Input = """ & S & """, length =" & S'Length'Image);
      for I in S'First .. S'Last - 1 loop
         for J in I + 1 .. S'Last loop
            if S(I) = S(J) then
               Put (" First duplicate at positions" & I'Image &
                    " and" & J'Image & ", character = '" & S(I) &
                    "', hex = ");
               Put (Character'Pos (S(I)), Width => 0, Base => 16);
               New_Line;
               return;
            end if;
         end loop;
      end loop;
      Put_Line (" All characters are unique.");
   end All_Chars_Unique;
begin
   All_Chars_Unique ("");
   All_Chars_Unique (".");
   All_Chars_Unique ("abcABC");
   All_Chars_Unique ("XYZ ZYX");
   All_Chars_Unique ("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ");
end Test_All_Chars_Unique;
Task: Determine if a string has all unique characters







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()





Ada: with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_All_Chars_Unique is
   procedure All_Chars_Unique (S : in String) is
   begin
      Put_Line ("Input = """ & S & """, length =" & S'Length'Image);
      for I in S'First .. S'Last - 1 loop
         for J in I + 1 .. S'Last loop
            if S(I) = S(J) then
               Put (" First duplicate at positions" & I'Image &
                    " and" & J'Image & ", character = '" & S(I) &
                    "', hex = ");
               Put (Character'Pos (S(I)), Width => 0, Base => 16);
               New_Line;
               return;
            end if;
         end loop;
      end loop;
      Put_Line (" All characters are unique.");
   end All_Chars_Unique;
begin
   All_Chars_Unique ("");
   All_Chars_Unique (".");
   All_Chars_Unique ("abcABC");
   All_Chars_Unique ("XYZ ZYX");
   All_Chars_Unique ("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ");
end Test_All_Chars_Unique;
Task: Determine if a string has all unique characters








VB: Module Module1

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

End Module




Ada: with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_All_Chars_Unique is
   procedure All_Chars_Unique (S : in String) is
   begin
      Put_Line ("Input = """ & S & """, length =" & S'Length'Image);
      for I in S'First .. S'Last - 1 loop
         for J in I + 1 .. S'Last loop
            if S(I) = S(J) then
               Put (" First duplicate at positions" & I'Image &
                    " and" & J'Image & ", character = '" & S(I) &
                    "', hex = ");
               Put (Character'Pos (S(I)), Width => 0, Base => 16);
               New_Line;
               return;
            end if;
         end loop;
      end loop;
      Put_Line (" All characters are unique.");
   end All_Chars_Unique;
begin
   All_Chars_Unique ("");
   All_Chars_Unique (".");
   All_Chars_Unique ("abcABC");
   All_Chars_Unique ("XYZ ZYX");
   All_Chars_Unique ("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ");
end Test_All_Chars_Unique;
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.")
                )
            );
        }
    }
}
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;
}
Task: Determine if a string has all unique characters





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







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()
Task: Determine if a string has all unique characters








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




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)
    }
}