WeixiangYan/CodeTransOcean huggingface dataset:
Task: Alternade words


C++: #include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <set>
#include <string>

int main(int argc, char** argv) {
    const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
    std::ifstream in(filename);
    if (!in) {
        std::cerr << "Cannot open file '" << filename << "'.\n";
        return EXIT_FAILURE;
    }
    std::string line;
    std::set<std::string> dictionary;
    while (getline(in, line))
        dictionary.insert(line);
    std::cout << std::left;
    for (const std::string& word : dictionary) {
        size_t len = word.size();
        if (len < 6)
            continue;
        std::string word1, word2;
        for (size_t i = 0; i < len; i += 2) {
            word1 += word[i];
            if (i + 1 < len)
                word2 += word[i + 1];
        }
        if (dictionary.find(word1) != dictionary.end()
            && dictionary.find(word2) != dictionary.end()) {
            std::cout << std::setw(10) << word
                    << std::setw(6) << word1 << word2 << '\n';
        }
    }
    return EXIT_SUCCESS;
}




Java: import java.io.*;
import java.util.*;

public class AlternadeWords {
    public static void main(String[] args) {
        try {
            Set<String> dictionary = new TreeSet<>();
            try (BufferedReader reader = new BufferedReader(new FileReader("unixdict.txt"))) {
                String line;
                while ((line = reader.readLine()) != null)
                    dictionary.add(line);
            }
            StringBuilder word1 = new StringBuilder();
            StringBuilder word2 = new StringBuilder();
            for (String word : dictionary) {
                int length = word.length();
                if (length < 6)
                    continue;
                word1.setLength(0);
                word2.setLength(0);
                for (int i = 0; i < length; i += 2) {
                    word1.append(word.charAt(i));
                    if (i + 1 < length)
                        word2.append(word.charAt(i + 1));
                }
                String w1 = word1.toString();
                String w2 = word2.toString();
                if (dictionary.contains(w1) && dictionary.contains(w2))
                    System.out.printf("%-10s%-6s%s\n", word, w1, w2);
            }
        } catch (Exception e)  {
            e.printStackTrace();
        }
    }
}
Task: Alternade words


C++: #include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <set>
#include <string>

int main(int argc, char** argv) {
    const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
    std::ifstream in(filename);
    if (!in) {
        std::cerr << "Cannot open file '" << filename << "'.\n";
        return EXIT_FAILURE;
    }
    std::string line;
    std::set<std::string> dictionary;
    while (getline(in, line))
        dictionary.insert(line);
    std::cout << std::left;
    for (const std::string& word : dictionary) {
        size_t len = word.size();
        if (len < 6)
            continue;
        std::string word1, word2;
        for (size_t i = 0; i < len; i += 2) {
            word1 += word[i];
            if (i + 1 < len)
                word2 += word[i + 1];
        }
        if (dictionary.find(word1) != dictionary.end()
            && dictionary.find(word2) != dictionary.end()) {
            std::cout << std::setw(10) << word
                    << std::setw(6) << word1 << word2 << '\n';
        }
    }
    return EXIT_SUCCESS;
}






Python: WORDFILE = 'unixdict.txt'
MINLEN = 6

class Trie(object):
    
    class Node(object):
        
        def __init__(self, char='\0', parent=None):
            self.children = {}
            self.char = char
            self.final = False
            self.parent = parent
            
        def descend(self, char, extend=False):
            
            if not char in self.children:
                if not extend: return None
                self.children[char] = Trie.Node(char,self)
            return self.children[char]
        
    def __init__(self):
        self.root = Trie.Node()
    
    def insert(self, word):
        
        node = self.root
        for char in word: node = node.descend(char, extend=True)
        node.final = True
        return node
    
    def __contains__(self, word):
        
        node = self.root
        for char in word:
            node = node.descend(char)
            if not node: return False
        return node.final 
    
    def words(self):
        
        nodes = [self.root]
        while nodes:
            node = nodes.pop()
            nodes += node.children.values()
            if node.final:
                word = []
                while node:
                    if node.char != '\0': word.append(node.char)
                    node = node.parent
                yield "".join(reversed(word))
    
    def __iter__(self):
        return self.words()
                

words = Trie()
with open(WORDFILE, "rt") as f:
    for word in f.readlines():
        words.insert(word.strip())

for word in words:
    if len(word) < MINLEN: continue
    even = word[::2]
    odd = word[1::2]
    if even in words and odd in words:
        print(word, even, odd)
Task: Alternade words




Go: package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "log"
    "unicode/utf8"
)

func main() {
    b, err := ioutil.ReadFile("unixdict.txt")
    if err != nil {
        log.Fatal("Error reading file")
    }
    bwords := bytes.Fields(b)
    dict := make(map[string]bool, len(bwords))
    words := make([]string, len(bwords))
    for i, bword := range bwords {
        word := string(bword)
        dict[word] = true
        words[i] = word
    }
    fmt.Println("'unixdict.txt' contains the following alternades of length 6 or more:\n")
    count := 0
    for _, word := range words {
        if utf8.RuneCountInString(word) < 6 {
            continue
        }
        var w1 = ""
        var w2 = ""
        for i, c := range word {
            if i%2 == 0 {
                w1 += string(c)
            } else {
                w2 += string(c)
            }
        }
        _, ok1 := dict[w1]
        _, ok2 := dict[w2]
        if ok1 && ok2 {
            count++
            fmt.Printf("%2d: %-8s -> %-4s %-4s\n", count, word, w1, w2)
        }
    }
}


Java: import java.io.*;
import java.util.*;

public class AlternadeWords {
    public static void main(String[] args) {
        try {
            Set<String> dictionary = new TreeSet<>();
            try (BufferedReader reader = new BufferedReader(new FileReader("unixdict.txt"))) {
                String line;
                while ((line = reader.readLine()) != null)
                    dictionary.add(line);
            }
            StringBuilder word1 = new StringBuilder();
            StringBuilder word2 = new StringBuilder();
            for (String word : dictionary) {
                int length = word.length();
                if (length < 6)
                    continue;
                word1.setLength(0);
                word2.setLength(0);
                for (int i = 0; i < length; i += 2) {
                    word1.append(word.charAt(i));
                    if (i + 1 < length)
                        word2.append(word.charAt(i + 1));
                }
                String w1 = word1.toString();
                String w2 = word2.toString();
                if (dictionary.contains(w1) && dictionary.contains(w2))
                    System.out.printf("%-10s%-6s%s\n", word, w1, w2);
            }
        } catch (Exception e)  {
            e.printStackTrace();
        }
    }
}
Task: Alternade words





Java: import java.io.*;
import java.util.*;

public class AlternadeWords {
    public static void main(String[] args) {
        try {
            Set<String> dictionary = new TreeSet<>();
            try (BufferedReader reader = new BufferedReader(new FileReader("unixdict.txt"))) {
                String line;
                while ((line = reader.readLine()) != null)
                    dictionary.add(line);
            }
            StringBuilder word1 = new StringBuilder();
            StringBuilder word2 = new StringBuilder();
            for (String word : dictionary) {
                int length = word.length();
                if (length < 6)
                    continue;
                word1.setLength(0);
                word2.setLength(0);
                for (int i = 0; i < length; i += 2) {
                    word1.append(word.charAt(i));
                    if (i + 1 < length)
                        word2.append(word.charAt(i + 1));
                }
                String w1 = word1.toString();
                String w2 = word2.toString();
                if (dictionary.contains(w1) && dictionary.contains(w2))
                    System.out.printf("%-10s%-6s%s\n", word, w1, w2);
            }
        } catch (Exception e)  {
            e.printStackTrace();
        }
    }
}



Python: WORDFILE = 'unixdict.txt'
MINLEN = 6

class Trie(object):
    
    class Node(object):
        
        def __init__(self, char='\0', parent=None):
            self.children = {}
            self.char = char
            self.final = False
            self.parent = parent
            
        def descend(self, char, extend=False):
            
            if not char in self.children:
                if not extend: return None
                self.children[char] = Trie.Node(char,self)
            return self.children[char]
        
    def __init__(self):
        self.root = Trie.Node()
    
    def insert(self, word):
        
        node = self.root
        for char in word: node = node.descend(char, extend=True)
        node.final = True
        return node
    
    def __contains__(self, word):
        
        node = self.root
        for char in word:
            node = node.descend(char)
            if not node: return False
        return node.final 
    
    def words(self):
        
        nodes = [self.root]
        while nodes:
            node = nodes.pop()
            nodes += node.children.values()
            if node.final:
                word = []
                while node:
                    if node.char != '\0': word.append(node.char)
                    node = node.parent
                yield "".join(reversed(word))
    
    def __iter__(self):
        return self.words()
                

words = Trie()
with open(WORDFILE, "rt") as f:
    for word in f.readlines():
        words.insert(word.strip())

for word in words:
    if len(word) < MINLEN: continue
    even = word[::2]
    odd = word[1::2]
    if even in words and odd in words:
        print(word, even, odd)
Task: Alternade words




Go: package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "log"
    "unicode/utf8"
)

func main() {
    b, err := ioutil.ReadFile("unixdict.txt")
    if err != nil {
        log.Fatal("Error reading file")
    }
    bwords := bytes.Fields(b)
    dict := make(map[string]bool, len(bwords))
    words := make([]string, len(bwords))
    for i, bword := range bwords {
        word := string(bword)
        dict[word] = true
        words[i] = word
    }
    fmt.Println("'unixdict.txt' contains the following alternades of length 6 or more:\n")
    count := 0
    for _, word := range words {
        if utf8.RuneCountInString(word) < 6 {
            continue
        }
        var w1 = ""
        var w2 = ""
        for i, c := range word {
            if i%2 == 0 {
                w1 += string(c)
            } else {
                w2 += string(c)
            }
        }
        _, ok1 := dict[w1]
        _, ok2 := dict[w2]
        if ok1 && ok2 {
            count++
            fmt.Printf("%2d: %-8s -> %-4s %-4s\n", count, word, w1, w2)
        }
    }
}




Python: WORDFILE = 'unixdict.txt'
MINLEN = 6

class Trie(object):
    
    class Node(object):
        
        def __init__(self, char='\0', parent=None):
            self.children = {}
            self.char = char
            self.final = False
            self.parent = parent
            
        def descend(self, char, extend=False):
            
            if not char in self.children:
                if not extend: return None
                self.children[char] = Trie.Node(char,self)
            return self.children[char]
        
    def __init__(self):
        self.root = Trie.Node()
    
    def insert(self, word):
        
        node = self.root
        for char in word: node = node.descend(char, extend=True)
        node.final = True
        return node
    
    def __contains__(self, word):
        
        node = self.root
        for char in word:
            node = node.descend(char)
            if not node: return False
        return node.final 
    
    def words(self):
        
        nodes = [self.root]
        while nodes:
            node = nodes.pop()
            nodes += node.children.values()
            if node.final:
                word = []
                while node:
                    if node.char != '\0': word.append(node.char)
                    node = node.parent
                yield "".join(reversed(word))
    
    def __iter__(self):
        return self.words()
                

words = Trie()
with open(WORDFILE, "rt") as f:
    for word in f.readlines():
        words.insert(word.strip())

for word in words:
    if len(word) < MINLEN: continue
    even = word[::2]
    odd = word[1::2]
    if even in words and odd in words:
        print(word, even, odd)
Task: Readline interface

C: #include <readline/readline.h>
#include <readline/history.h>
#include <string.h>

int main()
{
	char *s;
	using_history();
	while (1) {
		s = readline("This be a prompt> ");

		if (!s || !strcmp(s, "quit")) {
			puts("bye.");
			return 0;
		}

		if (!strcmp(s, "help"))
			puts("commands: ls, cat, quit");
		else if (!strcmp(s, "ls") || !strcmp(s, "cat")) {
			printf("command `%s' not implemented yet.\n", s);
			add_history(s);
		} else
			puts("Yes...?");
	}
}



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

std::vector<std::string> hist;

std::ostream& operator<<(std::ostream& os, const std::string& str) {
    return os << str.c_str();
}

void appendHistory(const std::string& name) {
    hist.push_back(name);
}

void hello() {
    std::cout << "Hello World!\n";
    appendHistory(__func__);
}

void history() {
    if (hist.size() == 0) {
        std::cout << "No history\n";
    } else {
        for (auto& str : hist) {
            std::cout << " - " << str << '\n';
        }
    }
    appendHistory(__func__);
}

void help() {
    std::cout << "Available commands:\n";
    std::cout << "  hello\n";
    std::cout << "  hist\n";
    std::cout << "  exit\n";
    std::cout << "  help\n";
    appendHistory(__func__);
}

int main() {
    bool done = false;
    std::string cmd;

    do {
        std::cout << "Enter a command, type help for a listing.\n";
        std::cin >> cmd;
        for (size_t i = 0; i < cmd.size(); ++i) {
            cmd[i] = toupper(cmd[i]);
        }

        if (strcmp(cmd.c_str(), "HELLO") == 0) {
            hello();
        } else if (strcmp(cmd.c_str(), "HIST") == 0) {
            history();
        } else if (strcmp(cmd.c_str(), "EXIT") == 0) {
            done = true;
        } else {
            help();
        }
    } while (!done);

    return 0;
}
Task: Readline interface

C: #include <readline/readline.h>
#include <readline/history.h>
#include <string.h>

int main()
{
	char *s;
	using_history();
	while (1) {
		s = readline("This be a prompt> ");

		if (!s || !strcmp(s, "quit")) {
			puts("bye.");
			return 0;
		}

		if (!strcmp(s, "help"))
			puts("commands: ls, cat, quit");
		else if (!strcmp(s, "ls") || !strcmp(s, "cat")) {
			printf("command `%s' not implemented yet.\n", s);
			add_history(s);
		} else
			puts("Yes...?");
	}
}




Go: package main

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

type vf = func()

var history []string

func hello() {
    fmt.Println("Hello World!")
    history = append(history, "hello")
}

func hist() {
    if len(history) == 0 {
        fmt.Println("No history")
    } else {
        for _, cmd := range history {
            fmt.Println("  -", cmd)
        }
    }
    history = append(history, "hist")
}

func help() {
    fmt.Println("Available commands:")
    fmt.Println("  hello")
    fmt.Println("  hist")
    fmt.Println("  exit")
    fmt.Println("  help")
    history = append(history, "help")
}

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    vfs := map[string]vf{"help": help, "hist": hist, "hello": hello}
    fmt.Println("Enter a command, type help for a listing.")
    for {
        fmt.Print(">")
        scanner.Scan()
        if scerr := scanner.Err(); scerr != nil {
            log.Fatal(scerr)
        }
        line := strings.TrimSpace(scanner.Text())
        if line == "exit" {
            return
        }
        cmd, ok := vfs[line]
        if !ok {
            fmt.Println("Unknown command, try again")
        } else {
            cmd()
        }
    }
}
Task: Readline interface

C: #include <readline/readline.h>
#include <readline/history.h>
#include <string.h>

int main()
{
	char *s;
	using_history();
	while (1) {
		s = readline("This be a prompt> ");

		if (!s || !strcmp(s, "quit")) {
			puts("bye.");
			return 0;
		}

		if (!strcmp(s, "help"))
			puts("commands: ls, cat, quit");
		else if (!strcmp(s, "ls") || !strcmp(s, "cat")) {
			printf("command `%s' not implemented yet.\n", s);
			add_history(s);
		} else
			puts("Yes...?");
	}
}





Java: import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

public class ReadlineInterface {
    private static LinkedList<String> histArr = new LinkedList<>();

    private static void hist() {
        if (histArr.isEmpty()) {
            System.out.println("No history");
        } else {
            histArr.forEach(cmd -> System.out.printf(" - %s\n", cmd));
        }

        class Crutch {}
        histArr.add(Crutch.class.getEnclosingMethod().getName());
    }

    private static void hello() {
        System.out.println("Hello World!");

        class Crutch {}
        histArr.add(Crutch.class.getEnclosingMethod().getName());
    }

    private static void help() {
        System.out.println("Available commands:");
        System.out.println("  hello");
        System.out.println("  hist");
        System.out.println("  exit");
        System.out.println("  help");

        class Crutch {}
        histArr.add(Crutch.class.getEnclosingMethod().getName());
    }

    public static void main(String[] args) throws IOException {
        Map<String, Runnable> cmdMap = new HashMap<>();
        cmdMap.put("help", ReadlineInterface::help);
        cmdMap.put("hist", ReadlineInterface::hist);
        cmdMap.put("hello", ReadlineInterface::hello);

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Enter a command, type help for a listing.");
        while (true) {
            System.out.print(">");
            String line = in.readLine();
            if ("exit".equals(line)) {
                break;
            }

            cmdMap.getOrDefault(line, ReadlineInterface::help).run();
        }
    }
}
Task: Readline interface

C: #include <readline/readline.h>
#include <readline/history.h>
#include <string.h>

int main()
{
	char *s;
	using_history();
	while (1) {
		s = readline("This be a prompt> ");

		if (!s || !strcmp(s, "quit")) {
			puts("bye.");
			return 0;
		}

		if (!strcmp(s, "help"))
			puts("commands: ls, cat, quit");
		else if (!strcmp(s, "ls") || !strcmp(s, "cat")) {
			printf("command `%s' not implemented yet.\n", s);
			add_history(s);
		} else
			puts("Yes...?");
	}
}







Python: 






import readline

while True:
    try:
        print(input('> '))
    except:
        break
Task: Readline interface


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

std::vector<std::string> hist;

std::ostream& operator<<(std::ostream& os, const std::string& str) {
    return os << str.c_str();
}

void appendHistory(const std::string& name) {
    hist.push_back(name);
}

void hello() {
    std::cout << "Hello World!\n";
    appendHistory(__func__);
}

void history() {
    if (hist.size() == 0) {
        std::cout << "No history\n";
    } else {
        for (auto& str : hist) {
            std::cout << " - " << str << '\n';
        }
    }
    appendHistory(__func__);
}

void help() {
    std::cout << "Available commands:\n";
    std::cout << "  hello\n";
    std::cout << "  hist\n";
    std::cout << "  exit\n";
    std::cout << "  help\n";
    appendHistory(__func__);
}

int main() {
    bool done = false;
    std::string cmd;

    do {
        std::cout << "Enter a command, type help for a listing.\n";
        std::cin >> cmd;
        for (size_t i = 0; i < cmd.size(); ++i) {
            cmd[i] = toupper(cmd[i]);
        }

        if (strcmp(cmd.c_str(), "HELLO") == 0) {
            hello();
        } else if (strcmp(cmd.c_str(), "HIST") == 0) {
            history();
        } else if (strcmp(cmd.c_str(), "EXIT") == 0) {
            done = true;
        } else {
            help();
        }
    } while (!done);

    return 0;
}




Java: import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

public class ReadlineInterface {
    private static LinkedList<String> histArr = new LinkedList<>();

    private static void hist() {
        if (histArr.isEmpty()) {
            System.out.println("No history");
        } else {
            histArr.forEach(cmd -> System.out.printf(" - %s\n", cmd));
        }

        class Crutch {}
        histArr.add(Crutch.class.getEnclosingMethod().getName());
    }

    private static void hello() {
        System.out.println("Hello World!");

        class Crutch {}
        histArr.add(Crutch.class.getEnclosingMethod().getName());
    }

    private static void help() {
        System.out.println("Available commands:");
        System.out.println("  hello");
        System.out.println("  hist");
        System.out.println("  exit");
        System.out.println("  help");

        class Crutch {}
        histArr.add(Crutch.class.getEnclosingMethod().getName());
    }

    public static void main(String[] args) throws IOException {
        Map<String, Runnable> cmdMap = new HashMap<>();
        cmdMap.put("help", ReadlineInterface::help);
        cmdMap.put("hist", ReadlineInterface::hist);
        cmdMap.put("hello", ReadlineInterface::hello);

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Enter a command, type help for a listing.");
        while (true) {
            System.out.print(">");
            String line = in.readLine();
            if ("exit".equals(line)) {
                break;
            }

            cmdMap.getOrDefault(line, ReadlineInterface::help).run();
        }
    }
}