WeixiangYan/CodeTransOcean huggingface dataset:
Task: Four sides of square

C: #include <stdio.h>

void hollowMatrix(unsigned int n) {
    int i, j;
    for (i = 0; i < n; ++i) {
        for (j = 0; j < n; ++j) {
            if (i == 0 || i == n - 1 || j == 0 || j == n - 1) {
                printf("%d ", 1);
            } else {
                printf("%d ", 0);
            }
        }
        printf("\n");
    }
}

int main() {
    hollowMatrix(10);
    printf("\n");
    hollowMatrix(11);
    return 0;
}











Ada: with Ada.Text_Io;
with Ada.Command_Line;

procedure Four_Sides is

   type Matrix_Type is array (Natural range <>, Natural range <>) of Character;

   function Hollow (Length : Natural) return Matrix_Type is
   begin
      return M : Matrix_Type (1 .. Length, 1 .. Length) do
         for Row in M'Range(1) loop
            for Col in M'Range (2) loop
               M (Row, Col) := (if Row in M'First (1) | M'Last (1) or
                                  Col in M'First (2) | M'Last (2)
                                then '1' else '0');
            end loop;
         end loop;
      end return;
   end Hollow;

   procedure Put (M : Matrix_Type) is
   begin
      for Row in M'Range (1) loop
         for Col in M'Range (2) loop
            Ada.Text_Io.Put (" ");
            Ada.Text_Io.Put (M(Row,Col));
         end loop;
         Ada.Text_Io.New_Line;
      end loop;
   end Put;

begin
   Put (Hollow (Length => Natural'Value (Ada.Command_Line.Argument (1))));
exception
   when others =>
      Ada.Text_Io.Put_Line ("Usage: ./four_sides <length>");
end Four_Sides;
Task: Numeric separator syntax

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

int main()
{
  unsigned long long int trillion = 1000000000000;

  setlocale(LC_NUMERIC,"");

  printf("Locale : %s, One Trillion : %'llu\n", setlocale(LC_CTYPE,NULL),trillion);

  return 0;
}











Ada: with Ada.Text_IO;       use Ada.Text_IO;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;

procedure Main is
   type u64 is mod 2**64;
   pi       : constant Float := 
     3.14159_26535_89793_23846_26433_83279_50288_41971_69399_37511;
   Trillion : u64            := 1_000_000_000_000;
begin
   Put ("pi : ");
   Put (Item => pi, Exp => 0, Aft => 7);
   New_Line;
   Put_Line ("Trillion : " & Trillion'Image);
end Main;
Task: Distinct power numbers

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

int compare(const void *a, const void *b) {
    int ia = *(int*)a;
    int ib = *(int*)b;
    return (ia>ib) - (ia<ib);
}

int main() {
    int pows[16];
    int a, b, i=0;
    
    for (a=2; a<=5; a++)
        for (b=2; b<=5; b++)
            pows[i++] = pow(a, b);
    
    qsort(pows, 16, sizeof(int), compare);
    
    for (i=0; i<16; i++)
        if (i==0 || pows[i] != pows[i-1]) 
            printf("%d ", pows[i]);
    
    printf("\n");
    return 0;
}











Ada: with Ada.Text_Io;
with Ada.Containers.Doubly_Linked_Lists;

procedure Power_Numbers is

   package Number_Lists   is new Ada.Containers.Doubly_Linked_Lists (Integer);
   package Number_Sorting is new Number_Lists.Generic_Sorting;
   use Number_Lists, Ada.Text_Io;

   List : Number_Lists.List;
begin
   for A in 2 .. 5 loop
      for B in 2 .. 5 loop
         declare
            R : constant Integer := A**B;
         begin
            if not List.Contains (R) then
               List.Append (R);
            end if;
         end;
      end loop;
   end loop;

   Number_Sorting.Sort (List);

   for E of List loop
      Put (Integer'Image (E));
      Put (" ");
   end loop;
   New_Line;

end Power_Numbers;
Task: Unique characters

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

char *uniques(char *str[], char *buf) {
    static unsigned counts[256];
    unsigned i;
    char *s, *o = buf;
    memset(counts, 0, 256 * sizeof(unsigned));
    
    for (; *str; str++)
        for (s = *str; *s; s++)
            counts[(unsigned) *s]++;
    
    for (i=0; i<256; i++)
        if (counts[i] == 1)
            *o++ = (char) i;
    
    *o = '\0';
    return buf;
}

int main() {
    char buf[256];
    char *strings[] = {
        "133252abcdeeffd",
        "a6789798st",
        "yxcdfgxcyz",
        NULL
    };
    
    printf("%s\n", uniques(strings, buf));
    return 0;
}











Ada: with Ada.Text_Io;

procedure Unique_Characters is

   List : array (Character) of Natural := (others => 0);

   procedure Count (Item : String) is
   begin
      for C of Item loop
         List (C) := List (C) + 1;
      end loop;
   end Count;

   procedure Put_Only_Once is
      use Ada.Text_Io;
   begin
      for C in List'Range loop
         if List (C) = 1 then
            Put (C);
            Put (' ');
         end if;
      end loop;
      New_Line;
   end Put_Only_Once;

begin
   Count ("133252abcdeeffd");
   Count ("a6789798st");
   Count ("yxcdfgxcyz");
   Put_Only_Once;
end Unique_Characters;
Task: Day of the week of Christmas and New Year

C: #define _XOPEN_SOURCE
#include <stdio.h>
#include <time.h>

int main() {
    struct tm t[2];
    strptime("2021-12-25", "%F", &t[0]);
    strptime("2022-01-01", "%F", &t[1]);
    for (int i=0; i<2; i++) {
        char buf[32];
        strftime(buf, 32, "%F is a %A", &t[i]);
        puts(buf);
    }
    return 0;
}











Ada: with Ada.Text_Io;
with Ada.Calendar.Formatting;

procedure Weekdays is
   use Ada.Text_Io;
   use Ada.Calendar.Formatting;

   subtype Time is Ada.Calendar.Time;

   procedure Info (Date : Time) is
   begin
      Put (Image (Date));
      Put (" is a ");
      Put (Day_Name'Image (Day_Of_Week (Date)));
      Put (".");
      New_Line;
   end Info;

   Christmas_Day : constant Time := Time_Of (Year => 2021, Month => 12, Day => 25);
   New_Years_Day : constant Time := Time_Of (Year => 2022, Month => 01, Day => 01);

begin
   Info (Christmas_Day);
   Info (New_Years_Day);
end Weekdays;
Task: Code Golf_ Code Golf







Python: print(end="Code Golf")
Task: Play recorded sounds







Python: import time
from pygame import mixer

mixer.init(frequency=16000) 
s1 = mixer.Sound('test.wav')
s2 = mixer.Sound('test2.wav')


s1.play(-1)         
time.sleep(0.5)


s2.play()          
time.sleep(2)
s2.play(2)         
time.sleep(10)


s1.set_volume(0.1)
time.sleep(5)


s1.set_volume(1)
time.sleep(5)

s1.stop()
s2.stop()
mixer.quit()
Task: Audio alarm







Python: import time
import os

seconds = input("Enter a number of seconds: ")
sound = input("Enter an mp3 filename: ")

time.sleep(float(seconds))
os.startfile(sound + ".mp3")
Task: Double Twin Primes







Python: 

def isPrime(n):
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False        
    return True
    
if __name__ == "__main__":
    num = 3
    while num <= 1000:
        if isPrime(num):
            if isPrime(num+2):
                if isPrime(num+6):
                    if isPrime(num+8):
                        print(num, num+2, num+6, num+8, sep="\t")
        num += 2
Task: Distance and Bearing







Python: 

from math import radians, degrees, sin, cos, asin, atan2, sqrt
from pandas import read_csv


EARTH_RADIUS_KM = 6372.8
TASK_CONVERT_NM =  0.0094174
AIRPORT_DATA_FILE = 'airports.dat.txt'

QUERY_LATITUDE, QUERY_LONGITUDE = 51.514669, 2.198581


def haversine(lat1, lon1, lat2, lon2):
    
    rlat1, rlon1, rlat2, rlon2 = [radians(x) for x in [lat1, lon1, lat2, lon2]]
    dlat = rlat2 - rlat1
    dlon = rlon2 - rlon1
    arc = sin(dlat / 2) ** 2 + cos(rlat1) * cos(rlat2) * sin(dlon / 2) ** 2
    clen = 2.0 * degrees(asin(sqrt(arc)))
    theta = atan2(sin(dlon) * cos(rlat2),
                  cos(rlat1) * sin(rlat2) - sin(rlat1) * cos(rlat2) * cos(dlon))
    theta = (degrees(theta) + 360) % 360
    return EARTH_RADIUS_KM * clen * TASK_CONVERT_NM, theta


def find_nearest_airports(latitude, longitude, wanted=20, csv=AIRPORT_DATA_FILE):
    
    airports = read_csv(csv, header=None, usecols=[1, 3, 5, 6, 7], names=[
                        'Name', 'Country', 'ICAO', 'Latitude', 'Longitude'])
    airports['Distance'] = 0.0
    airports['Bearing'] = 0
    for (idx, row) in enumerate(airports.itertuples()):
        distance, bearing = haversine(
            latitude, longitude, row.Latitude, row.Longitude)
        airports.at[idx, 'Distance'] = round(distance, ndigits=1)
        airports.at[idx, 'Bearing'] = int(round(bearing))

    airports.sort_values(by=['Distance'], ignore_index=True, inplace=True)
    return airports.loc[0:wanted-1, ['Name', 'Country', 'ICAO', 'Distance', 'Bearing']]


print(find_nearest_airports(QUERY_LATITUDE, QUERY_LONGITUDE))
Task: McNuggets problem

C: #include <stdio.h>

int
main() {
    int max = 0, i = 0, sixes, nines, twenties;

loopstart: while (i < 100) {
        for (sixes = 0; sixes*6 < i; sixes++) {
            if (sixes*6 == i) {
                i++;
                goto loopstart;
            }

            for (nines = 0; nines*9 < i; nines++) {
                if (sixes*6 + nines*9 == i) {
                    i++;
                    goto loopstart;
                }

                for (twenties = 0; twenties*20 < i; twenties++) {
                    if (sixes*6 + nines*9 + twenties*20 == i) {
                        i++;
                        goto loopstart;
                    }
                }
            }
        }
        max = i;
        i++;
    }

    printf("Maximum non-McNuggets number is %d\n", max);

    return 0;
}
Task: Retrieve and search chat history

C: #include<curl/curl.h>
#include<string.h>
#include<stdio.h>

#define MAX_LEN 1000

void searchChatLogs(char* searchString){
	char* baseURL = "http:
	time_t t;
	struct tm* currentDate;
	char dateString[30],dateStringFile[30],lineData[MAX_LEN],targetURL[100];
	int i,flag;
	FILE *fp;
	
	CURL *curl;
	CURLcode res;
	
	time(&t);
	currentDate = localtime(&t);
	
	strftime(dateString, 30, "%Y-%m-%d", currentDate);
	printf("Today is : %s",dateString);
	
	if((curl = curl_easy_init())!=NULL){
		for(i=0;i<=10;i++){
			
		flag = 0;
		sprintf(targetURL,"%s%s.tcl",baseURL,dateString);
		
		strcpy(dateStringFile,dateString);
		
		printf("\nRetrieving chat logs from %s\n",targetURL);
		
		if((fp = fopen("nul","w"))==0){
			printf("Cant's read from %s",targetURL);
		}
		else{
			curl_easy_setopt(curl, CURLOPT_URL, targetURL);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
		
		res = curl_easy_perform(curl);
		
		if(res == CURLE_OK){
			while(fgets(lineData,MAX_LEN,fp)!=NULL){
				if(strstr(lineData,searchString)!=NULL){
					flag = 1;
					fputs(lineData,stdout);
				}
			}
			
			if(flag==0)
				printf("\nNo matching lines found.");
		}
		fflush(fp);
		fclose(fp);
		}
		
		currentDate->tm_mday--;
		mktime(currentDate);
		strftime(dateString, 30, "%Y-%m-%d", currentDate);	
			
	}
	curl_easy_cleanup(curl);
	
	}
}

int main(int argC,char* argV[])
{
	if(argC!=2)
		printf("Usage : %s <followed by search string, enclosed by \" if it contains spaces>",argV[0]);
	else
		searchChatLogs(argV[1]);
	return 0;
}
Task: Numbers with same digit set in base 10 and base 16




Go: package main

import (
    "fmt"
    "rcu"
    "strconv"
)

func equalSets(s1, s2 map[rune]bool) bool {
    if len(s1) != len(s2) {
        return false
    }
    for k, _ := range s1 {
        _, ok := s2[k]
        if !ok {
            return false
        }
    }
    return true
}

func main() {
    const limit = 100_000
    count := 0
    fmt.Println("Numbers under 100,000 which use the same digits in decimal or hex:")
    for n := 0; n < limit; n++ {
        h := strconv.FormatInt(int64(n), 16)
        hs := make(map[rune]bool)
        for _, c := range h {
            hs[c] = true
        }
        ns := make(map[rune]bool)
        for _, c := range strconv.Itoa(n) {
            ns[c] = true
        }
        if equalSets(hs, ns) {
            count++
            fmt.Printf("%6s ", rcu.Commatize(n))
            if count%10 == 0 {
                fmt.Println()
            }
        }
    }
    fmt.Printf("\n\n%d such numbers found.\n", count)
}
Task: Four sides of square




Go: package main

import "fmt"

func hollowMatrix(n uint) {
    for i := uint(0); i < n; i++ {
        for j := uint(0); j < n; j++ {
            if i == 0 || i == n-1 || j == 0 || j == n-1 {
                fmt.Printf("%d ", 1)
            } else {
                fmt.Printf("%d ", 0)
            }
        }
        fmt.Println()
    }
}

func main() {
    hollowMatrix(8)
    fmt.Println()
    hollowMatrix(9)
}
Task: Longest common suffix




Go: package main

import (
    "fmt"
    "strings"
)

func lcs(a []string) string {
    le := len(a)
    if le == 0 {
        return ""
    }
    if le == 1 {
        return a[0]
    }
    le0 := len(a[0])
    minLen := le0
    for i := 1; i < le; i++ {
        if len(a[i]) < minLen {
            minLen = len(a[i])
        }
    }
    if minLen == 0 {
        return ""
    }
    res := ""
    a1 := a[1:]
    for i := 1; i <= minLen; i++ {
        suffix := a[0][le0-i:]
        for _, e := range a1 {
            if !strings.HasSuffix(e, suffix) {
                return res
            }
        }
        res = suffix
    }
    return res
}

func main() {
    tests := [][]string{
        {"baabababc", "baabc", "bbbabc"},
        {"baabababc", "baabc", "bbbazc"},
        {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"},
        {"longest", "common", "suffix"},
        {"suffix"},
        {""},
    }
    for _, test := range tests {
        fmt.Printf("%v -> \"%s\"\n", test, lcs(test))
    }
}
Task: Numeric separator syntax




Go: package main

import "fmt"

func main() {
    integers := []int{1_2_3, 0b1_0_1_0_1, 0xa_bc_d, 0o4_37, 0_43_7, 0x_beef}
    for _, integer := range integers {
        fmt.Printf("%d  ", integer)
    }
    floats := []float64{1_2_3_4.2_5, 6.0_22e4, 0x_1.5p-2}
    for _, float := range floats {
        fmt.Printf("%g  ", float)
    }
    fmt.Println()
    
    
}
Task: Distinct power numbers




Go: package main

import (
    "fmt"
    "rcu"
    "sort"
)

func main() {
    var pows []int
    for a := 2; a <= 5; a++ {
        pow := a
        for b := 2; b <= 5; b++ {
            pow *= a
            pows = append(pows, pow)
        }
    }
    set := make(map[int]bool)
    for _, e := range pows {
        set[e] = true
    }
    pows = pows[:0]
    for k := range set {
        pows = append(pows, k)
    }
    sort.Ints(pows)
    fmt.Println("Ordered distinct values of a ^ b for a in [2..5] and b in [2..5]:")
    for i, pow := range pows {
        fmt.Printf("%5s ", rcu.Commatize(pow))
        if (i+1)%5 == 0 {
            fmt.Println()
        }
    }
    fmt.Println("\nFound", len(pows), "such numbers.")
}
Task: Unique characters




Go: package main

import (
    "fmt"
    "sort"
)

func main() {
    strings := []string{"133252abcdeeffd", "a6789798st", "yxcdfgxcyz"}
    m := make(map[rune]int)
    for _, s := range strings {
        for _, c := range s {
            m[c]++
        }
    }
    var chars []rune
    for k, v := range m {
        if v == 1 {
            chars = append(chars, k)
        }
    }
    sort.Slice(chars, func(i, j int) bool { return chars[i] < chars[j] })
    fmt.Println(string(chars))
}
Task: Abelian sandpile model_Identity




Go: package main

import (
    "fmt"
    "strconv"
    "strings"
)

type sandpile struct{ a [9]int }

var neighbors = [][]int{
    {1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7},
}


func newSandpile(a [9]int) *sandpile { return &sandpile{a} }

func (s *sandpile) plus(other *sandpile) *sandpile {
    b := [9]int{}
    for i := 0; i < 9; i++ {
        b[i] = s.a[i] + other.a[i]
    }
    return &sandpile{b}
}

func (s *sandpile) isStable() bool {
    for _, e := range s.a {
        if e > 3 {
            return false
        }
    }
    return true
}


func (s *sandpile) topple() {
    for i := 0; i < 9; i++ {
        if s.a[i] > 3 {
            s.a[i] -= 4
            for _, j := range neighbors[i] {
                s.a[j]++
            }
            return
        }
    }
}

func (s *sandpile) String() string {
    var sb strings.Builder
    for i := 0; i < 3; i++ {
        for j := 0; j < 3; j++ {
            sb.WriteString(strconv.Itoa(s.a[3*i+j]) + " ")
        }
        sb.WriteString("\n")
    }
    return sb.String()
}

func main() {
    fmt.Println("Avalanche of topplings:\n")
    s4 := newSandpile([9]int{4, 3, 3, 3, 1, 2, 0, 2, 3})
    fmt.Println(s4)
    for !s4.isStable() {
        s4.topple()
        fmt.Println(s4)
    }

    fmt.Println("Commutative additions:\n")
    s1 := newSandpile([9]int{1, 2, 0, 2, 1, 1, 0, 1, 3})
    s2 := newSandpile([9]int{2, 1, 3, 1, 0, 1, 0, 1, 0})
    s3_a := s1.plus(s2)
    for !s3_a.isStable() {
        s3_a.topple()
    }
    s3_b := s2.plus(s1)
    for !s3_b.isStable() {
        s3_b.topple()
    }
    fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s\n", s1, s2, s3_a)
    fmt.Printf("and\n\n%s\nplus\n\n%s\nalso equals\n\n%s\n", s2, s1, s3_b)

    fmt.Println("Addition of identity sandpile:\n")
    s3 := newSandpile([9]int{3, 3, 3, 3, 3, 3, 3, 3, 3})
    s3_id := newSandpile([9]int{2, 1, 2, 1, 0, 1, 2, 1, 2})
    s4 = s3.plus(s3_id)
    for !s4.isStable() {
        s4.topple()
    }
    fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s\n", s3, s3_id, s4)

    fmt.Println("Addition of identities:\n")
    s5 := s3_id.plus(s3_id)
    for !s5.isStable() {
        s5.topple()
    }
    fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s", s3_id, s3_id, s5)
}
Task: Base 16 numbers needing a to f




Go: package main

import (
    "fmt"
    "strconv"
    "strings"
)

func main() {
    const nondecimal = "abcdef"
    c := 0
    for i := int64(0); i <= 500; i++ {
        hex := strconv.FormatInt(i, 16)
        if strings.ContainsAny(nondecimal, hex) {
            fmt.Printf("%3d ", i)
            c++
            if c%15 == 0 {
                fmt.Println()
            }
        }
    }
    fmt.Printf("\n\n%d such numbers found.\n", c)
}
Task: Address of a variable




Go: package main

import (
	"fmt"
	"unsafe"
)

func main() {
	myVar := 3.14
	myPointer := &myVar
	fmt.Println("Address:", myPointer, &myVar)
	fmt.Printf("Address: %p %p\n", myPointer, &myVar)

	var addr64 int64
	var addr32 int32
	ptr := unsafe.Pointer(myPointer)
	if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) {
		addr64 = int64(uintptr(ptr))
		fmt.Printf("Pointer stored in   int64: %#016x\n", addr64)
	}
	if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) {
		
		addr32 = int32(uintptr(ptr))
		fmt.Printf("Pointer stored in   int32: %#08x\n", addr32)
	}
	addr := uintptr(ptr)
	fmt.Printf("Pointer stored in uintptr: %#08x\n", addr)

	fmt.Println("value as float:", myVar)
	i := (*int32)(unsafe.Pointer(&myVar))
	fmt.Printf("value as int32: %#08x\n", *i)
}
Task: Fixed length records




Go: package main

import (
    "fmt"
    "log"
    "os"
    "os/exec"
)

func reverseBytes(bytes []byte) {
    for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 {
        bytes[i], bytes[j] = bytes[j], bytes[i]
    }
}

func check(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    in, err := os.Open("infile.dat")
    check(err)
    defer in.Close()

    out, err := os.Create("outfile.dat")
    check(err)

    record := make([]byte, 80)
    empty := make([]byte, 80)
    for {
        n, err := in.Read(record)
        if err != nil {
            if n == 0 {
                break 
            } else {
                out.Close()
                log.Fatal(err)
            }
        }
        reverseBytes(record)
        out.Write(record)
        copy(record, empty)
    }
    out.Close()

    
    
    cmd := exec.Command("dd", "if=outfile.dat", "cbs=80", "conv=unblock")
    bytes, err := cmd.Output()
    check(err)
    fmt.Println(string(bytes))
}
Task: Find words whose first and last three letters are equal




Go: package main

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

func main() {
    wordList := "unixdict.txt"
    b, err := ioutil.ReadFile(wordList)
    if err != nil {
        log.Fatal("Error reading file")
    }
    bwords := bytes.Fields(b)
    count := 0
    for _, bword := range bwords {
        s := string(bword)
        if utf8.RuneCountInString(s) > 5 && (s[0:3] == s[len(s)-3:]) {
            count++
            fmt.Printf("%d: %s\n", count, s)
        }
    }
}
Task: Find words which contain the most consonants




Go: package main

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

func contains(list []int, value int) bool {
    for _, v := range list {
        if v == value {
            return true
        }
    }
    return false
}

func main() {
    wordList := "unixdict.txt"
    b, err := ioutil.ReadFile(wordList)
    if err != nil {
        log.Fatal("Error reading file")
    }
    bwords := bytes.Fields(b)
    var words []string
    for _, bword := range bwords {
        s := string(bword)
        if utf8.RuneCountInString(s) > 10 {
            words = append(words, s)
        }
    }
    vowelIndices := []int{0, 4, 8, 14, 20}
    wordGroups := make([][]string, 12)
    for _, word := range words {
        letters := make([]int, 26)
        for _, c := range word {
            index := c - 97
            if index >= 0 && index < 26 {
                letters[index]++
            }
        }
        eligible := true
        uc := 0 
        for i := 0; i < 26; i++ {
            if !contains(vowelIndices, i) {
                if letters[i] > 1 {
                    eligible = false
                    break
                } else if letters[i] == 1 {
                    uc++
                }
            }
        }
        if eligible {
            wordGroups[uc] = append(wordGroups[uc], word)
        }
    }

    for i := 11; i >= 0; i-- {
        count := len(wordGroups[i])
        if count > 0 {
            s := "s"
            if count == 1 {
                s = ""
            }
            fmt.Printf("%d word%s found with %d unique consonants:\n", count, s, i)
            for j := 0; j < count; j++ {
                fmt.Printf("%-15s", wordGroups[i][j])
                if j > 0 && (j+1)%5 == 0 {
                    fmt.Println()
                }
            }
            fmt.Println()
            if count%5 != 0 {
                fmt.Println()
            }
        }
    }
}
Task: Find words which contains all the vowels




Go: package main

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

func main() {
    wordList := "unixdict.txt"
    b, err := ioutil.ReadFile(wordList)
    if err != nil {
        log.Fatal("Error reading file")
    }
    bwords := bytes.Fields(b)
    var words []string
    for _, bword := range bwords {
        s := string(bword)
        if utf8.RuneCountInString(s) > 10 {
            words = append(words, s)
        }
    }
    count := 0
    fmt.Println("Words which contain all 5 vowels once in", wordList, "\b:\n")
    for _, word := range words {
        ca, ce, ci, co, cu := 0, 0, 0, 0, 0
        for _, r := range word {
            switch r {
            case 'a':
                ca++
            case 'e':
                ce++
            case 'i':
                ci++
            case 'o':
                co++
            case 'u':
                cu++
            }
        }
        if ca == 1 && ce == 1 && ci == 1 && co == 1 && cu == 1 {
            count++
            fmt.Printf("%2d: %s\n", count, word)
        }
    }
}
Task: Odd words




Go: package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "log"
    "sort"
    "strings"
)

func main() {
    wordList := "unixdict.txt"
    b, err := ioutil.ReadFile(wordList)
    if err != nil {
        log.Fatal("Error reading file")
    }
    bwords := bytes.Fields(b)
    words := make([]string, len(bwords))
    for i, bword := range bwords {
        words[i] = string(bword)
    }
    count := 0
    fmt.Println("The odd words with length > 4 in", wordList, "are:")
    for _, word := range words {
        rword := []rune(word) 
        if len(rword) > 8 {
            var sb strings.Builder
            for i := 0; i < len(rword); i += 2 {
                sb.WriteRune(rword[i])
            }
            s := sb.String()
            idx := sort.SearchStrings(words, s)      
            if idx < len(words) && words[idx] == s { 
                count = count + 1
                fmt.Printf("%2d: %-12s -> %s\n", count, word, s)
            }
        }
    }
}