WeixiangYan/CodeTransOcean huggingface dataset:
Task: Strong and weak primes



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

public static class StrongAndWeakPrimes
{
    public static void Main() {
        var primes = PrimeGenerator(10_000_100).ToList();
        var strongPrimes = from i in Range(1, primes.Count - 2) where primes[i] > (primes[i-1] + primes[i+1]) / 2 select primes[i];
        var weakPrimes = from i in Range(1, primes.Count - 2) where primes[i] < (primes[i-1] + primes[i+1]) / 2.0 select primes[i];
        WriteLine($"First 36 strong primes: {string.Join(", ", strongPrimes.Take(36))}");
        WriteLine($"There are {strongPrimes.TakeWhile(p => p < 1_000_000).Count():N0} strong primes below {1_000_000:N0}");
        WriteLine($"There are {strongPrimes.TakeWhile(p => p < 10_000_000).Count():N0} strong primes below {10_000_000:N0}");
        WriteLine($"First 37 weak primes: {string.Join(", ", weakPrimes.Take(37))}");
        WriteLine($"There are {weakPrimes.TakeWhile(p => p < 1_000_000).Count():N0} weak primes below {1_000_000:N0}");
        WriteLine($"There are {weakPrimes.TakeWhile(p => p < 10_000_000).Count():N0} weak primes below {1_000_000:N0}");
    }
   
}


Go: package main

import "fmt"

func sieve(limit int) []bool {
    limit++
    
    
    c := make([]bool, limit)
    c[0] = true
    c[1] = true

    p := 3 
    for {
        p2 := p * p
        if p2 >= limit {
            break
        }
        for i := p2; i < limit; i += 2 * p {
            c[i] = true
        }
        for {
            p += 2
            if !c[p] {
                break
            }
        }
    }
    return c
}

func commatize(n int) string {
    s := fmt.Sprintf("%d", n)
    le := len(s)
    for i := le - 3; i >= 1; i -= 3 {
        s = s[0:i] + "," + s[i:]
    }
    return s
}

func main() {
    
    const limit = 1e7 + 19
    sieved := sieve(limit)
    
    var primes = []int{2}
    for i := 3; i <= limit; i += 2 {
        if !sieved[i] {
            primes = append(primes, i)
        }
    }
    
    var strong []int
    var weak = []int{3}                  
    for i := 2; i < len(primes)-1; i++ { 
        if primes[i] > (primes[i-1]+primes[i+1])/2 {
            strong = append(strong, primes[i])
        } else if primes[i] < (primes[i-1]+primes[i+1])/2 {
            weak = append(weak, primes[i])
        }
    }

    fmt.Println("The first 36 strong primes are:")
    fmt.Println(strong[:36])
    count := 0
    for _, p := range strong {
        if p >= 1e6 {
            break
        }
        count++
    }
    fmt.Println("\nThe number of strong primes below 1,000,000 is", commatize(count))
    fmt.Println("\nThe number of strong primes below 10,000,000 is", commatize(len(strong)))

    fmt.Println("\nThe first 37 weak primes are:")
    fmt.Println(weak[:37])
    count = 0
    for _, p := range weak {
        if p >= 1e6 {
            break
        }
        count++
    }
    fmt.Println("\nThe number of weak primes below 1,000,000 is", commatize(count))
    fmt.Println("\nThe number of weak primes below 10,000,000 is", commatize(len(weak)))
}
Task: Abbreviations, automatic

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

void process(int lineNum, char buffer[]) {
    char days[7][64];
    int i = 0, d = 0, j = 0;

    while (buffer[i] != 0) {
        if (buffer[i] == ' ') {
            days[d][j] = '\0';
            ++d;
            j = 0;
        } else if (buffer[i] == '\n' || buffer[i] == '\r') {
            days[d][j] = '\0';
            ++d;
            break;
        } else {
            days[d][j] = buffer[i];
            ++j;
        }

        if (d >= 7) {
            printf("There aren't 7 days in line %d\n", lineNum);
            return;
        }
        ++i;
    }
    if (buffer[i] == '\0') {
        days[d][j] = '\0';
        ++d;
    }

    if (d < 7) {
        printf("There aren't 7 days in line %d\n", lineNum);
        return;
    } else {
        int len = 0;

        for (len = 1; len < 64; ++len) {
            int d1;
            for (d1 = 0; d1 < 7; ++d1) {
                int d2;
                for (d2 = d1 + 1; d2 < 7; ++d2) {
                    int unique = 0;
                    for (i = 0; i < len; ++i) {
                        if (days[d1][i] != days[d2][i]) {
                            unique = 1;
                            break;
                        }
                    }
                    if (!unique) {
                        goto next_length;
                    }
                }
            }

            
            printf("%2d ", len);
            for (i = 0; i < 7; ++i) {
                printf(" %s", days[i]);
            }
            printf("\n");
            return;

            
        next_length: {}
        }
    }

    printf("Failed to find uniqueness within the bounds.");
}

int main() {
    char buffer[1024];
    int lineNum = 1, len;
    FILE *fp;

    fp = fopen("days_of_week.txt", "r");
    while (1) {
        memset(buffer, 0, sizeof(buffer));

        fgets(buffer, sizeof(buffer), fp);
        len = strlen(buffer);

        if (len == 0 || buffer[len - 1] == '\0') {
            break;
        }

        process(lineNum++, buffer);
    }
    fclose(fp);

    return 0;
}







Python: def shortest_abbreviation_length(line, list_size):
    words = line.split()
    word_count = len(words)
    
    if word_count != list_size:
        raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')

    
    abbreviation_length = 1
    abbreviations = set()
    while(True):
        abbreviations = {word[:abbreviation_length] for word in words}
        if len(abbreviations) == list_size:
            return abbreviation_length
        abbreviation_length += 1
        abbreviations.clear()

def automatic_abbreviations(filename, words_per_line):
    with open(filename) as file:
        for line in file:
            line = line.rstrip()
            if len(line) > 0:
                length = shortest_abbreviation_length(line, words_per_line)
                print(f'{length:2} {line}')
            else:
                print()

automatic_abbreviations('daysOfWeek.txt', 7)
Task: Abbreviations, automatic


C++: #include <iomanip>
#include <iostream>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>

std::vector<std::string> split(const std::string& str, char delimiter) {
    std::vector<std::string> tokens;
    std::string token;
    std::istringstream tokenStream(str);
    while (std::getline(tokenStream, token, delimiter)) {
        tokens.push_back(token);
    }
    return tokens;
}

int main() {
    using namespace std;
    string line;
    int i = 0;

    ifstream in("days_of_week.txt");
    if (in.is_open()) {
        while (getline(in, line)) {
            i++;
            if (line.empty()) {
                continue;
            }

            auto days = split(line, ' ');
            if (days.size() != 7) {
                throw std::runtime_error("There aren't 7 days in line " + i);
            }

            map<string, int> temp;
            for (auto& day : days) {
                if (temp.find(day) != temp.end()) {
                    cerr << " ∞  " << line << '\n';
                    continue;
                }
                temp[day] = 1;
            }

            int len = 1;
            while (true) {
                temp.clear();
                for (auto& day : days) {
                    string key = day.substr(0, len);
                    if (temp.find(key) != temp.end()) {
                        break;
                    }
                    temp[key] = 1;
                }
                if (temp.size() == 7) {
                    cout << setw(2) << len << "  " << line << '\n';
                    break;
                }
                len++;
            }
        }
    }

    return 0;
}






Python: def shortest_abbreviation_length(line, list_size):
    words = line.split()
    word_count = len(words)
    
    if word_count != list_size:
        raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')

    
    abbreviation_length = 1
    abbreviations = set()
    while(True):
        abbreviations = {word[:abbreviation_length] for word in words}
        if len(abbreviations) == list_size:
            return abbreviation_length
        abbreviation_length += 1
        abbreviations.clear()

def automatic_abbreviations(filename, words_per_line):
    with open(filename) as file:
        for line in file:
            line = line.rstrip()
            if len(line) > 0:
                length = shortest_abbreviation_length(line, words_per_line)
                print(f'{length:2} {line}')
            else:
                print()

automatic_abbreviations('daysOfWeek.txt', 7)
Task: Abbreviations, automatic



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

namespace Abbreviations {
    class Program {
        static void Main(string[] args) {
            string[] lines = System.IO.File.ReadAllLines("days_of_week.txt");
            int i = 0;

            foreach (string line in lines) {
                i++;
                if (line.Length > 0) {
                    var days = line.Split();
                    if (days.Length != 7) {
                        throw new Exception("There aren't 7 days in line " + i);
                    }

                    Dictionary<string, int> temp = new Dictionary<string, int>();
                    foreach (string day in days) {
                        if (temp.ContainsKey(day)) {
                            Console.WriteLine(" ∞  {0}", line);
                            continue;
                        }
                        temp.Add(day, 1);
                    }

                    int len = 1;
                    while (true) {
                        temp.Clear();
                        foreach(string day in days) {
                            string key;
                            if (len < day.Length) {
                                key = day.Substring(0, len);
                            } else {
                                key = day;
                            }
                            if (temp.ContainsKey(key)) {
                                break;
                            }
                            temp.Add(key, 1);
                        }
                        if (temp.Count == 7) {
                            Console.WriteLine("{0,2:D}  {1}", len, line);
                            break;
                        }
                        len++;
                    }
                }
            }
        }
    }
}





Python: def shortest_abbreviation_length(line, list_size):
    words = line.split()
    word_count = len(words)
    
    if word_count != list_size:
        raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')

    
    abbreviation_length = 1
    abbreviations = set()
    while(True):
        abbreviations = {word[:abbreviation_length] for word in words}
        if len(abbreviations) == list_size:
            return abbreviation_length
        abbreviation_length += 1
        abbreviations.clear()

def automatic_abbreviations(filename, words_per_line):
    with open(filename) as file:
        for line in file:
            line = line.rstrip()
            if len(line) > 0:
                length = shortest_abbreviation_length(line, words_per_line)
                print(f'{length:2} {line}')
            else:
                print()

automatic_abbreviations('daysOfWeek.txt', 7)
Task: Abbreviations, automatic



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

namespace Abbreviations {
    class Program {
        static void Main(string[] args) {
            string[] lines = System.IO.File.ReadAllLines("days_of_week.txt");
            int i = 0;

            foreach (string line in lines) {
                i++;
                if (line.Length > 0) {
                    var days = line.Split();
                    if (days.Length != 7) {
                        throw new Exception("There aren't 7 days in line " + i);
                    }

                    Dictionary<string, int> temp = new Dictionary<string, int>();
                    foreach (string day in days) {
                        if (temp.ContainsKey(day)) {
                            Console.WriteLine(" ∞  {0}", line);
                            continue;
                        }
                        temp.Add(day, 1);
                    }

                    int len = 1;
                    while (true) {
                        temp.Clear();
                        foreach(string day in days) {
                            string key;
                            if (len < day.Length) {
                                key = day.Substring(0, len);
                            } else {
                                key = day;
                            }
                            if (temp.ContainsKey(key)) {
                                break;
                            }
                            temp.Add(key, 1);
                        }
                        if (temp.Count == 7) {
                            Console.WriteLine("{0,2:D}  {1}", len, line);
                            break;
                        }
                        len++;
                    }
                }
            }
        }
    }
}






VB: Function MinimalLenght(strLine As String) As Integer
Dim myVar As Variant, I As Integer, Flag As Boolean, myColl As Collection, Count As Integer
   myVar = Split(strLine, " ")
   Count = 0
   Do
      Set myColl = New Collection
      Count = Count + 1
      On Error Resume Next
      Do
         myColl.Add Left$(myVar(I), Count), Left$(myVar(I), Count)
         I = I + 1
      Loop While Err.Number = 0 And I <= UBound(myVar)
      Flag = Err.Number = 0
      On Error GoTo 0
      I = 0
      Set myColl = Nothing
   Loop While Not Flag
   MinimalLenght = Count
End Function
Task: Abbreviations, automatic





Java: import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Abbreviations {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("days_of_week.txt");
        List<String> readAllLines = Files.readAllLines(path);
        for (int i = 0; i < readAllLines.size(); i++) {
            String line = readAllLines.get(i);
            if (line.length() == 0) continue;

            String[] days = line.split(" ");
            if (days.length != 7) throw new RuntimeException("There aren't 7 days on line " + (i + 1));

            Map<String, Integer> temp = new HashMap<>();
            for (String day : days) {
                Integer count = temp.getOrDefault(day, 0);
                temp.put(day, count + 1);
            }
            if (temp.size() < 7) {
                System.out.print(" ∞  ");
                System.out.println(line);
                continue;
            }

            int len = 1;
            while (true) {
                temp.clear();
                for (String day : days) {
                    String sd;
                    if (len >= day.length()) {
                        sd = day;
                    } else {
                        sd = day.substring(0, len);
                    }
                    Integer count = temp.getOrDefault(sd, 0);
                    temp.put(sd, count + 1);
                }
                if (temp.size() == 7) {
                    System.out.printf("%2d  %s\n", len, line);
                    break;
                }
                len++;
            }
        }
    }
}



Python: def shortest_abbreviation_length(line, list_size):
    words = line.split()
    word_count = len(words)
    
    if word_count != list_size:
        raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')

    
    abbreviation_length = 1
    abbreviations = set()
    while(True):
        abbreviations = {word[:abbreviation_length] for word in words}
        if len(abbreviations) == list_size:
            return abbreviation_length
        abbreviation_length += 1
        abbreviations.clear()

def automatic_abbreviations(filename, words_per_line):
    with open(filename) as file:
        for line in file:
            line = line.rstrip()
            if len(line) > 0:
                length = shortest_abbreviation_length(line, words_per_line)
                print(f'{length:2} {line}')
            else:
                print()

automatic_abbreviations('daysOfWeek.txt', 7)
Task: Abbreviations, automatic





Java: import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Abbreviations {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("days_of_week.txt");
        List<String> readAllLines = Files.readAllLines(path);
        for (int i = 0; i < readAllLines.size(); i++) {
            String line = readAllLines.get(i);
            if (line.length() == 0) continue;

            String[] days = line.split(" ");
            if (days.length != 7) throw new RuntimeException("There aren't 7 days on line " + (i + 1));

            Map<String, Integer> temp = new HashMap<>();
            for (String day : days) {
                Integer count = temp.getOrDefault(day, 0);
                temp.put(day, count + 1);
            }
            if (temp.size() < 7) {
                System.out.print(" ∞  ");
                System.out.println(line);
                continue;
            }

            int len = 1;
            while (true) {
                temp.clear();
                for (String day : days) {
                    String sd;
                    if (len >= day.length()) {
                        sd = day;
                    } else {
                        sd = day.substring(0, len);
                    }
                    Integer count = temp.getOrDefault(sd, 0);
                    temp.put(sd, count + 1);
                }
                if (temp.size() == 7) {
                    System.out.printf("%2d  %s\n", len, line);
                    break;
                }
                len++;
            }
        }
    }
}




VB: Function MinimalLenght(strLine As String) As Integer
Dim myVar As Variant, I As Integer, Flag As Boolean, myColl As Collection, Count As Integer
   myVar = Split(strLine, " ")
   Count = 0
   Do
      Set myColl = New Collection
      Count = Count + 1
      On Error Resume Next
      Do
         myColl.Add Left$(myVar(I), Count), Left$(myVar(I), Count)
         I = I + 1
      Loop While Err.Number = 0 And I <= UBound(myVar)
      Flag = Err.Number = 0
      On Error GoTo 0
      I = 0
      Set myColl = Nothing
   Loop While Not Flag
   MinimalLenght = Count
End Function
Task: Abbreviations, automatic




Go: package main

import(
    "bufio"
    "fmt"
    "os"
    "strings"
)

func distinctStrings(strs []string) []string {
    len := len(strs)
    set := make(map[string]bool, len)
    distinct := make([]string, 0, len)
    for _, str := range strs {
        if !set[str] {
            distinct = append(distinct, str)
            set[str] = true
        }
    }
    return distinct
}

func takeRunes(s string, n int) string {
    i := 0
    for j := range s {
        if i == n {
            return s[:j]
        }
        i++
    }
    return s
}

func main() {
    file, err := os.Open("days_of_week.txt")
    if err != nil {
        fmt.Println("Unable to open file.")
        return
    }
    defer file.Close()
    reader := bufio.NewReader(file)
    lineCount := 0
    for {
        line, err := reader.ReadString('\n')
        if err != nil { 
            return
        }
        line = strings.TrimSpace(line)
        lineCount++
        if line == "" {
            fmt.Println()
            continue
        }
        days := strings.Fields(line)
        daysLen := len(days)
        if (len(days) != 7) {
            fmt.Println("There aren't 7 days in line", lineCount)
            return
        }
        if len(distinctStrings(days)) != 7 { 
            fmt.Println(" ∞ ", line)
            continue
        }
        for abbrevLen := 1; ; abbrevLen++ {
            abbrevs := make([]string, daysLen)
            for i := 0; i < daysLen; i++ {
                abbrevs[i] = takeRunes(days[i], abbrevLen)
            }
            if len(distinctStrings(abbrevs)) == 7 {
                fmt.Printf("%2d  %s\n", abbrevLen, line)
                break
            }
        }
    }
}




Python: def shortest_abbreviation_length(line, list_size):
    words = line.split()
    word_count = len(words)
    
    if word_count != list_size:
        raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')

    
    abbreviation_length = 1
    abbreviations = set()
    while(True):
        abbreviations = {word[:abbreviation_length] for word in words}
        if len(abbreviations) == list_size:
            return abbreviation_length
        abbreviation_length += 1
        abbreviations.clear()

def automatic_abbreviations(filename, words_per_line):
    with open(filename) as file:
        for line in file:
            line = line.rstrip()
            if len(line) > 0:
                length = shortest_abbreviation_length(line, words_per_line)
                print(f'{length:2} {line}')
            else:
                print()

automatic_abbreviations('daysOfWeek.txt', 7)
Task: Abbreviations, automatic




Go: package main

import(
    "bufio"
    "fmt"
    "os"
    "strings"
)

func distinctStrings(strs []string) []string {
    len := len(strs)
    set := make(map[string]bool, len)
    distinct := make([]string, 0, len)
    for _, str := range strs {
        if !set[str] {
            distinct = append(distinct, str)
            set[str] = true
        }
    }
    return distinct
}

func takeRunes(s string, n int) string {
    i := 0
    for j := range s {
        if i == n {
            return s[:j]
        }
        i++
    }
    return s
}

func main() {
    file, err := os.Open("days_of_week.txt")
    if err != nil {
        fmt.Println("Unable to open file.")
        return
    }
    defer file.Close()
    reader := bufio.NewReader(file)
    lineCount := 0
    for {
        line, err := reader.ReadString('\n')
        if err != nil { 
            return
        }
        line = strings.TrimSpace(line)
        lineCount++
        if line == "" {
            fmt.Println()
            continue
        }
        days := strings.Fields(line)
        daysLen := len(days)
        if (len(days) != 7) {
            fmt.Println("There aren't 7 days in line", lineCount)
            return
        }
        if len(distinctStrings(days)) != 7 { 
            fmt.Println(" ∞ ", line)
            continue
        }
        for abbrevLen := 1; ; abbrevLen++ {
            abbrevs := make([]string, daysLen)
            for i := 0; i < daysLen; i++ {
                abbrevs[i] = takeRunes(days[i], abbrevLen)
            }
            if len(distinctStrings(abbrevs)) == 7 {
                fmt.Printf("%2d  %s\n", abbrevLen, line)
                break
            }
        }
    }
}





VB: Function MinimalLenght(strLine As String) As Integer
Dim myVar As Variant, I As Integer, Flag As Boolean, myColl As Collection, Count As Integer
   myVar = Split(strLine, " ")
   Count = 0
   Do
      Set myColl = New Collection
      Count = Count + 1
      On Error Resume Next
      Do
         myColl.Add Left$(myVar(I), Count), Left$(myVar(I), Count)
         I = I + 1
      Loop While Err.Number = 0 And I <= UBound(myVar)
      Flag = Err.Number = 0
      On Error GoTo 0
      I = 0
      Set myColl = Nothing
   Loop While Not Flag
   MinimalLenght = Count
End Function