WeixiangYan/CodeTransOcean huggingface dataset:
Task: Unix_ls

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>

int cmpstr(const void *a, const void *b)
{
    return strcmp(*(const char**)a, *(const char**)b);
}

int main(void)
{
    DIR *basedir;
    char path[PATH_MAX];
    struct dirent *entry;
    char **dirnames;
    int diralloc = 128;
    int dirsize  = 0;
    
    if (!(dirnames = malloc(diralloc * sizeof(char*)))) {
        perror("malloc error:");
        return 1;
    }

    if (!getcwd(path, PATH_MAX)) {
        perror("getcwd error:");
        return 1;
    }

    if (!(basedir = opendir(path))) {
        perror("opendir error:");
        return 1;
    }

    while ((entry = readdir(basedir))) {
        if (dirsize >= diralloc) {
            diralloc *= 2;
            if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) {
                perror("realloc error:");
                return 1;
            }
        }
        dirnames[dirsize++] = strdup(entry->d_name);
    }

    qsort(dirnames, dirsize, sizeof(char*), cmpstr);

    int i;
    for (i = 0; i < dirsize; ++i) {
        if (dirnames[i][0] != '.') {
            printf("%s\n", dirnames[i]);
        }
    }

    for (i = 0; i < dirsize; ++i)
        free(dirnames[i]);
    free(dirnames);
    closedir(basedir);
    return 0;
}










Fortran:       PROGRAM LS		
      USE DFLIB			
      TYPE(FILE$INFO) INFO	
      NAMELIST /HIC/INFO	
      INTEGER MARK,L		

      MARK = FILE$FIRST		
Call for the next file.
   10 L = GETFILEINFOQQ("*",INFO,MARK)	
      IF (MARK.EQ.FILE$ERROR) THEN	
        WRITE (6,*) "Error
        WRITE (6,HIC)			
        STOP "That wasn't nice."	
      ELSE IF (IAND(INFO.PERMIT,FILE$DIR) .EQ. 0) THEN	
        IF (L.GT.0) WRITE (6,*) INFO.NAME(1:L)	
      END IF				
      IF (MARK.NE.FILE$LAST) GO TO 10	
      END
Task: Unix_ls





Java: package rosetta;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class UnixLS {

	public static void main(String[] args) throws IOException {
		Files.list(Path.of("")).sorted().forEach(System.out::println);
	}
}






Fortran:       PROGRAM LS		
      USE DFLIB			
      TYPE(FILE$INFO) INFO	
      NAMELIST /HIC/INFO	
      INTEGER MARK,L		

      MARK = FILE$FIRST		
Call for the next file.
   10 L = GETFILEINFOQQ("*",INFO,MARK)	
      IF (MARK.EQ.FILE$ERROR) THEN	
        WRITE (6,*) "Error
        WRITE (6,HIC)			
        STOP "That wasn't nice."	
      ELSE IF (IAND(INFO.PERMIT,FILE$DIR) .EQ. 0) THEN	
        IF (L.GT.0) WRITE (6,*) INFO.NAME(1:L)	
      END IF				
      IF (MARK.NE.FILE$LAST) GO TO 10	
      END
Task: Unix_ls







Python: >>> import os
>>> print('\n'.join(sorted(os.listdir('.'))))
DLLs
Doc
LICENSE.txt
Lib
NEWS.txt
README.txt
Scripts
Tools
include
libs
python.exe
pythonw.exe
tcl
>>>




Fortran:       PROGRAM LS		
      USE DFLIB			
      TYPE(FILE$INFO) INFO	
      NAMELIST /HIC/INFO	
      INTEGER MARK,L		

      MARK = FILE$FIRST		
Call for the next file.
   10 L = GETFILEINFOQQ("*",INFO,MARK)	
      IF (MARK.EQ.FILE$ERROR) THEN	
        WRITE (6,*) "Error
        WRITE (6,HIC)			
        STOP "That wasn't nice."	
      ELSE IF (IAND(INFO.PERMIT,FILE$DIR) .EQ. 0) THEN	
        IF (L.GT.0) WRITE (6,*) INFO.NAME(1:L)	
      END IF				
      IF (MARK.NE.FILE$LAST) GO TO 10	
      END
Task: Unix_ls






PHP: <?php
foreach(scandir('.') as $fileName){
    echo $fileName."\n";
}





Fortran:       PROGRAM LS		
      USE DFLIB			
      TYPE(FILE$INFO) INFO	
      NAMELIST /HIC/INFO	
      INTEGER MARK,L		

      MARK = FILE$FIRST		
Call for the next file.
   10 L = GETFILEINFOQQ("*",INFO,MARK)	
      IF (MARK.EQ.FILE$ERROR) THEN	
        WRITE (6,*) "Error
        WRITE (6,HIC)			
        STOP "That wasn't nice."	
      ELSE IF (IAND(INFO.PERMIT,FILE$DIR) .EQ. 0) THEN	
        IF (L.GT.0) WRITE (6,*) INFO.NAME(1:L)	
      END IF				
      IF (MARK.NE.FILE$LAST) GO TO 10	
      END
Task: Unix_ls






PHP: <?php
foreach(scandir('.') as $fileName){
    echo $fileName."\n";
}
Task: Unix_ls






PHP: <?php
foreach(scandir('.') as $fileName){
    echo $fileName."\n";
}






Ada: with Ada.Text_IO, Ada.Directories, Ada.Containers.Indefinite_Vectors; 

procedure Directory_List is
   
   use Ada.Directories, Ada.Text_IO;
   Search: Search_Type; Found: Directory_Entry_Type;
   package SV is new Ada.Containers.Indefinite_Vectors(Natural, String);
   Result: SV.Vector;
   package Sorting is new SV.Generic_Sorting; use Sorting;
   function SName return String is (Simple_Name(Found));
   
begin
   
   Start_Search(Search, Directory => ".", Pattern =>"");
   while More_Entries(Search) loop
      Get_Next_Entry(Search, Found);
      declare
         Name: String := Simple_Name(Found);
      begin
         if Name(Name'First) /= '.' then
            Result.Append(Name);
         end if; 
      end;
   end loop; 
   
   Sort(Result); 

   
   for I in Result.First_Index .. Result.Last_Index loop 
      Put_Line(Result.Element(I));
   end loop;   
end Directory_List;
Task: Law of cosines - triples

C: 

#include <stdio.h>
#include <math.h>

#define MAX_SIDE_LENGTH 13


int main(void)
{
    static char description[3][80] = {
        "gamma =  90 degrees,  a*a + b*b       == c*c",
        "gamma =  60 degrees,  a*a + b*b - a*b == c*c",
        "gamma = 120 degrees,  a*a + b*b + a*b == c*c"
    };
    static int coeff[3] = { 0, 1, -1 };

    for (int k = 0; k < 3; k++)
    {
        int counter = 0;
        for (int a = 1; a <= MAX_SIDE_LENGTH; a++)
            for (int b = 1; b <= a; b++)
                for (int c = 1; c <= MAX_SIDE_LENGTH; c++)
                    if (a * a + b * b - coeff[k] * a * b == c * c)
                    {
                        counter++;
#ifdef DISPLAY_TRIANGLES
                        printf("  %d  %d  %d\n", a, b, c);
#endif
                    }
        printf("%s,  number of triangles = %d\n", description[k], counter);
    }

    return 0;
}











Ada: with Ada.Text_IO;
with Ada.Containers.Ordered_Maps;

procedure Law_Of_Cosines is

   type Angle_Kind is (Angle_60, Angle_90, Angle_120);

   function Is_Triangle (A, B, C : in Positive;
                         Angle   : in Angle_Kind) return Boolean
   is
      A2 : constant Positive := A**2;
      B2 : constant Positive := B**2;
      C2 : constant Positive := C**2;
      AB : constant Positive := A * B;
   begin
      case Angle is
         when Angle_60  =>  return A2 + B2 - AB = C2;
         when Angle_90  =>  return A2 + B2 = C2;
         when Angle_120 =>  return A2 + B2 + AB = C2;
      end case;
   end Is_Triangle;

   procedure Count_Triangles is
      use Ada.Text_IO;
      Count : Natural;
   begin
      for Angle in Angle_Kind loop
         Count := 0;
         Put_Line (Angle'Image & " triangles");
         for A in 1 ..13 loop
            for B in 1 .. A loop
               for C in 1 .. 13 loop
                  if Is_Triangle (A, B, C, Angle) then
                     Put_Line (A'Image & B'Image & C'Image);
                     Count := Count + 1;
                  end if;
               end loop;
            end loop;
         end loop;
         Put_Line ("There are " & Count'Image & " " & Angle'Image &" triangles");
      end loop;
   end Count_Triangles;

   procedure Extra_Credit (Limit : in Natural) is
      use Ada.Text_IO;

      package Square_Maps is new Ada.Containers.Ordered_Maps (Natural, Boolean);
      Squares : Square_Maps.Map;

      Count : Natural :=  0;
   begin
      for C in 1 .. Limit loop
         Squares.Insert (C**2, True);
      end loop;

      for A in 1 .. Limit loop
         for B in 1 .. A loop
            if Squares.Contains (A**2 + B**2 - A * B) then
               Count := Count + 1;
            end if;
         end loop;
      end loop;
      Put_Line ("There are " & Natural'(Count - Limit)'Image &
                  " " & Angle_60'Image &" triangles between 1 and " & Limit'Image & ".");
   end Extra_Credit;

begin
   Count_Triangles;
   Extra_Credit (Limit => 10_000);
end Law_Of_Cosines;
Task: Law of cosines - triples







Python: N = 13

def method1(N=N):
    squares = [x**2 for x in range(0, N+1)]
    sqrset = set(squares)
    tri90, tri60, tri120 = (set() for _ in range(3))
    for a in range(1, N+1):
        a2 = squares[a]
        for b in range(1, a + 1):
            b2 = squares[b]
            c2 = a2 + b2
            if c2 in sqrset:
                tri90.add(tuple(sorted((a, b, int(c2**0.5)))))
            ab = a * b
            c2 -= ab
            if c2 in sqrset:
                tri60.add(tuple(sorted((a, b, int(c2**0.5)))))
            c2 += 2 * ab
            if c2 in sqrset:
                tri120.add(tuple(sorted((a, b, int(c2**0.5)))))
    return  sorted(tri90), sorted(tri60), sorted(tri120)

if __name__ == '__main__':
    print(f'Integer triangular triples for sides 1..{N}:')
    for angle, triples in zip([90, 60, 120], method1(N)):
        print(f'  {angle:3}° has {len(triples)} solutions:\n    {triples}')
    _, t60, _ = method1(10_000)
    notsame = sum(1 for a, b, c in t60 if a != b or b != c)
    print('Extra credit:', notsame)





Ada: with Ada.Text_IO;
with Ada.Containers.Ordered_Maps;

procedure Law_Of_Cosines is

   type Angle_Kind is (Angle_60, Angle_90, Angle_120);

   function Is_Triangle (A, B, C : in Positive;
                         Angle   : in Angle_Kind) return Boolean
   is
      A2 : constant Positive := A**2;
      B2 : constant Positive := B**2;
      C2 : constant Positive := C**2;
      AB : constant Positive := A * B;
   begin
      case Angle is
         when Angle_60  =>  return A2 + B2 - AB = C2;
         when Angle_90  =>  return A2 + B2 = C2;
         when Angle_120 =>  return A2 + B2 + AB = C2;
      end case;
   end Is_Triangle;

   procedure Count_Triangles is
      use Ada.Text_IO;
      Count : Natural;
   begin
      for Angle in Angle_Kind loop
         Count := 0;
         Put_Line (Angle'Image & " triangles");
         for A in 1 ..13 loop
            for B in 1 .. A loop
               for C in 1 .. 13 loop
                  if Is_Triangle (A, B, C, Angle) then
                     Put_Line (A'Image & B'Image & C'Image);
                     Count := Count + 1;
                  end if;
               end loop;
            end loop;
         end loop;
         Put_Line ("There are " & Count'Image & " " & Angle'Image &" triangles");
      end loop;
   end Count_Triangles;

   procedure Extra_Credit (Limit : in Natural) is
      use Ada.Text_IO;

      package Square_Maps is new Ada.Containers.Ordered_Maps (Natural, Boolean);
      Squares : Square_Maps.Map;

      Count : Natural :=  0;
   begin
      for C in 1 .. Limit loop
         Squares.Insert (C**2, True);
      end loop;

      for A in 1 .. Limit loop
         for B in 1 .. A loop
            if Squares.Contains (A**2 + B**2 - A * B) then
               Count := Count + 1;
            end if;
         end loop;
      end loop;
      Put_Line ("There are " & Natural'(Count - Limit)'Image &
                  " " & Angle_60'Image &" triangles between 1 and " & Limit'Image & ".");
   end Extra_Credit;

begin
   Count_Triangles;
   Extra_Credit (Limit => 10_000);
end Law_Of_Cosines;
Task: Law of cosines - triples

C: 

#include <stdio.h>
#include <math.h>

#define MAX_SIDE_LENGTH 13


int main(void)
{
    static char description[3][80] = {
        "gamma =  90 degrees,  a*a + b*b       == c*c",
        "gamma =  60 degrees,  a*a + b*b - a*b == c*c",
        "gamma = 120 degrees,  a*a + b*b + a*b == c*c"
    };
    static int coeff[3] = { 0, 1, -1 };

    for (int k = 0; k < 3; k++)
    {
        int counter = 0;
        for (int a = 1; a <= MAX_SIDE_LENGTH; a++)
            for (int b = 1; b <= a; b++)
                for (int c = 1; c <= MAX_SIDE_LENGTH; c++)
                    if (a * a + b * b - coeff[k] * a * b == c * c)
                    {
                        counter++;
#ifdef DISPLAY_TRIANGLES
                        printf("  %d  %d  %d\n", a, b, c);
#endif
                    }
        printf("%s,  number of triangles = %d\n", description[k], counter);
    }

    return 0;
}
Task: Law of cosines - triples



C#: using System;
using System.Collections.Generic;
using static System.Linq.Enumerable;

public static class LawOfCosinesTriples
{
    public static void Main2() {
        PrintTriples(60, 13);
        PrintTriples(90, 13);
        PrintTriples(120, 13);
        PrintTriples(60, 10_000, true, false);
    }

    private static void PrintTriples(int degrees, int maxSideLength, bool notAllTheSameLength = false, bool print = true) {
        string s = $"{degrees} degree triangles in range 1..{maxSideLength}";
        if (notAllTheSameLength) s += " where not all sides are the same";
        Console.WriteLine(s);
        int count = 0;
        var triples = FindTriples(degrees, maxSideLength);
        if (notAllTheSameLength) triples = triples.Where(NotAllTheSameLength);
        foreach (var triple in triples) {
            count++;
            if (print) Console.WriteLine(triple);
        }
        Console.WriteLine($"{count} solutions");
    }

    private static IEnumerable<(int a, int b, int c)> FindTriples(int degrees, int maxSideLength) {
        double radians = degrees * Math.PI / 180;
        int coefficient = (int)Math.Round(Math.Cos(radians) * -2, MidpointRounding.AwayFromZero);
        int maxSideLengthSquared = maxSideLength * maxSideLength;
        return
            from a in Range(1, maxSideLength)
            from b in Range(1, a)
            let cc = a * a + b * b + a * b * coefficient
            where cc <= maxSideLengthSquared
            let c = (int)Math.Sqrt(cc)
            where c * c == cc
            select (a, b, c);
    }

    private static bool NotAllTheSameLength((int a, int b, int c) triple) => triple.a != triple.b || triple.a != triple.c;
}
Task: Law of cosines - triples


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

using triple = std::tuple<int, int, int>;

void print_triple(std::ostream& out, const triple& t) {
    out << '(' << std::get<0>(t) << ',' << std::get<1>(t) << ',' << std::get<2>(t) << ')';
}

void print_vector(std::ostream& out, const std::vector<triple>& vec) {
    if (vec.empty())
        return;
    auto i = vec.begin();
    print_triple(out, *i++);
    for (; i != vec.end(); ++i) {
        out << ' ';
        print_triple(out, *i);
    }
    out << "\n\n";
}

int isqrt(int n) {
    return static_cast<int>(std::sqrt(n));
}

int main() {
    const int min = 1, max = 13;
    std::vector<triple> solutions90, solutions60, solutions120;

    for (int a = min; a <= max; ++a) {
        int a2 = a * a;
        for (int b = a; b <= max; ++b) {
            int b2 = b * b, ab = a * b;
            int c2 = a2 + b2;
            int c = isqrt(c2);
            if (c <= max && c * c == c2)
                solutions90.emplace_back(a, b, c);
            else {
                c2 = a2 + b2 - ab;
                c = isqrt(c2);
                if (c <= max && c * c == c2)
                    solutions60.emplace_back(a, b, c);
                else {
                    c2 = a2 + b2 + ab;
                    c = isqrt(c2);
                    if (c <= max && c * c == c2)
                        solutions120.emplace_back(a, b, c);
                }
            }
        }
    }

    std::cout << "There are " << solutions60.size() << " solutions for gamma = 60 degrees:\n";
    print_vector(std::cout, solutions60);

    std::cout << "There are " << solutions90.size() << " solutions for gamma = 90 degrees:\n";
    print_vector(std::cout, solutions90);

    std::cout << "There are " << solutions120.size() << " solutions for gamma = 120 degrees:\n";
    print_vector(std::cout, solutions120);
    
    const int max2 = 10000;
    int count = 0;
    for (int a = min; a <= max2; ++a) {
        for (int b = a + 1; b <= max2; ++b) {
            int c2 = a * a + b * b - a * b;
            int c = isqrt(c2);
            if (c <= max2 && c * c == c2)
                ++count;
        }
    }
    std::cout << "There are " << count << " solutions for gamma = 60 degrees in the range "
        << min << " to " << max2 << " where the sides are not all of the same length.\n";
    return 0;
}
Task: Law of cosines - triples





Java: public class LawOfCosines {

    public static void main(String[] args) {
        generateTriples(13);
        generateTriples60(10000);
    }
    
    private static void generateTriples(int max) {
        for ( int coeff : new int[] {0, -1, 1} ) {
            int count = 0;
            System.out.printf("Max side length %d, formula:  a*a + b*b %s= c*c%n", max, coeff == 0 ? "" : (coeff<0 ? "-"  : "+") + " a*b ");
            for ( int a = 1 ; a <= max ; a++ ) {
                for ( int b = 1 ; b <= a ; b++ ) {
                    int val = a*a + b*b + coeff*a*b;
                    int c = (int) (Math.sqrt(val) + .5d);
                    if ( c > max ) {
                        break;
                    }
                    if ( c*c == val ) {
                        System.out.printf("  (%d, %d, %d)%n", a, b ,c);
                        count++;
                    }
                }
            }
            System.out.printf("%d triangles%n", count);
        }        
    }

    private static void generateTriples60(int max) {
        int count = 0;
        System.out.printf("%nExtra Credit.%nMax side length %d, sides different length, formula:  a*a + b*b - a*b = c*c%n", max);
        for ( int a = 1 ; a <= max ; a++ ) {
            for ( int b = 1 ; b < a ; b++ ) {
                int val = a*a + b*b - a*b;
                int c = (int) (Math.sqrt(val) + .5d);
                if ( c*c == val ) {
                    count++;
                }
            }
        }
        System.out.printf("%d triangles%n", count);
    }

}
Task: Law of cosines - triples







Python: N = 13

def method1(N=N):
    squares = [x**2 for x in range(0, N+1)]
    sqrset = set(squares)
    tri90, tri60, tri120 = (set() for _ in range(3))
    for a in range(1, N+1):
        a2 = squares[a]
        for b in range(1, a + 1):
            b2 = squares[b]
            c2 = a2 + b2
            if c2 in sqrset:
                tri90.add(tuple(sorted((a, b, int(c2**0.5)))))
            ab = a * b
            c2 -= ab
            if c2 in sqrset:
                tri60.add(tuple(sorted((a, b, int(c2**0.5)))))
            c2 += 2 * ab
            if c2 in sqrset:
                tri120.add(tuple(sorted((a, b, int(c2**0.5)))))
    return  sorted(tri90), sorted(tri60), sorted(tri120)

if __name__ == '__main__':
    print(f'Integer triangular triples for sides 1..{N}:')
    for angle, triples in zip([90, 60, 120], method1(N)):
        print(f'  {angle:3}° has {len(triples)} solutions:\n    {triples}')
    _, t60, _ = method1(10_000)
    notsame = sum(1 for a, b, c in t60 if a != b or b != c)
    print('Extra credit:', notsame)
Task: Law of cosines - triples




Go: package main

import "fmt"

type triple struct{ a, b, c int }

var squares13 = make(map[int]int, 13)
var squares10000 = make(map[int]int, 10000)

func init() {
    for i := 1; i <= 13; i++ {
        squares13[i*i] = i
    }
    for i := 1; i <= 10000; i++ {
        squares10000[i*i] = i
    }
}

func solve(angle, maxLen int, allowSame bool) []triple {
    var solutions []triple
    for a := 1; a <= maxLen; a++ {
        for b := a; b <= maxLen; b++ {
            lhs := a*a + b*b
            if angle != 90 {
                switch angle {
                case 60:
                    lhs -= a * b
                case 120:
                    lhs += a * b
                default:
                    panic("Angle must be 60, 90 or 120 degrees")
                }
            }
            switch maxLen {
            case 13:
                if c, ok := squares13[lhs]; ok {
                    if !allowSame && a == b && b == c {
                        continue
                    }
                    solutions = append(solutions, triple{a, b, c})
                }
            case 10000:
                if c, ok := squares10000[lhs]; ok {
                    if !allowSame && a == b && b == c {
                        continue
                    }
                    solutions = append(solutions, triple{a, b, c})
                }
            default:
                panic("Maximum length must be either 13 or 10000")
            }
        }
    }
    return solutions
}

func main() {
    fmt.Print("For sides in the range [1, 13] ")
    fmt.Println("where they can all be of the same length:-\n")
    angles := []int{90, 60, 120}
    var solutions []triple
    for _, angle := range angles {
        solutions = solve(angle, 13, true)
        fmt.Printf("  For an angle of %d degrees", angle)
        fmt.Println(" there are", len(solutions), "solutions, namely:")
        fmt.Printf("  %v\n", solutions)
        fmt.Println()
    }
    fmt.Print("For sides in the range [1, 10000] ")
    fmt.Println("where they cannot ALL be of the same length:-\n")
    solutions = solve(60, 10000, false)
    fmt.Print("  For an angle of 60 degrees")
    fmt.Println(" there are", len(solutions), "solutions.")
}
Task: Top rank per group

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

typedef struct {
    const char *name, *id, *dept;
    int sal;
} person;

person ppl[] = {
    {"Tyler Bennett",   "E10297", "D101", 32000},
    {"John Rappl",      "E21437", "D050", 47000},
    {"George Woltman",  "E00127", "D101", 53500},
    {"Adam Smith",      "E63535", "D202", 18000},
    {"Claire Buckman",  "E39876", "D202", 27800},
    {"David McClellan", "E04242", "D101", 41500},
    {"Rich Holcomb",    "E01234", "D202", 49500},
    {"Nathan Adams",    "E41298", "D050", 21900},
    {"Richard Potter",  "E43128", "D101", 15900},
    {"David Motsinger", "E27002", "D202", 19250},
    {"Tim Sampair",     "E03033", "D101", 27000},
    {"Kim Arlich",      "E10001", "D190", 57000},
    {"Timothy Grove",   "E16398", "D190", 29900},
};

int pcmp(const void *a, const void *b)
{
    const person *aa = a, *bb = b;
    int x = strcmp(aa->dept, bb->dept);
    if (x) return x;
    return aa->sal > bb->sal ? -1 : aa->sal < bb->sal;
}

#define N sizeof(ppl)/sizeof(person)
void top(int n)
{
    int i, rank;
    qsort(ppl, N, sizeof(person), pcmp);

    for (i = rank = 0; i < N; i++) {
        if (i && strcmp(ppl[i].dept, ppl[i - 1].dept)) {
            rank = 0;
            printf("\n");
        }

        if (rank++ < n)
            printf("%s %d: %s\n", ppl[i].dept, ppl[i].sal, ppl[i].name);
    }
}

int main()
{
    top(2);
    return 0;
}