WeixiangYan/CodeTransOcean huggingface dataset:
Task: Longest common substring



C#: using System;

namespace LongestCommonSubstring
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(lcs("thisisatest", "testing123testing"));
            Console.ReadKey(true);
        }

        public static string lcs(string a, string b)
        {
            var lengths = new int[a.Length, b.Length];
            int greatestLength = 0;
            string output = "";
            for (int i = 0; i < a.Length; i++)
            {
                for (int j = 0; j < b.Length; j++)
                {
                    if (a[i] == b[j])
                    {
                        lengths[i, j] = i == 0 || j == 0 ? 1 : lengths[i - 1, j - 1] + 1;
                        if (lengths[i, j] > greatestLength)
                        {
                            greatestLength = lengths[i, j];
                            output = a.Substring(i - greatestLength + 1, greatestLength);
                        }
                    }
                    else
                    {
                        lengths[i, j] = 0;
                    }
                }
            }
            return output;
        }
    }
}








Fortran: program main
implicit none
   call  compare('testing123testingthing', 'thisis',                 'thi')
   call  compare('testing',                'sting',                  'sting')
   call  compare('thisisatest_stinger',    'testing123testingthing', 'sting')
   call  compare('thisisatest_stinger',    'thisis',                 'thisis')
   call  compare('thisisatest',            'testing123testing',      'test')
   call  compare('thisisatest',            'thisisatest',            'thisisatest')
contains
subroutine compare(a,b,answer)
character(len=*),intent(in) :: a, b, answer
character(len=:),allocatable :: a2, match
character(len=*),parameter :: g='(*(g0))'
integer :: i
   a2=a 
   match=''
   do i=1,len(a2)-1
      call compare_sub(a2,b,match)
      if(len(a2).lt.len(match))exit
      a2=a2(:len(a2)-1)
   enddo
   write(*,g) merge('(PASSED)','(FAILED)',answer.eq.match), &
   & ' longest match found: "',match,'"; expected "',answer,'"', &
   & ' comparing "',a,'" and "',b,'"'
end subroutine
subroutine compare_sub(a,b,match)
character(len=*),intent(in) :: a, b
character(len=:),allocatable :: match
integer :: left, foundat, len_a
   len_a=len(a)
   do left=1,len_a
      foundat=index(b,a(left:))
      if(foundat.ne.0.and.len(match).lt.len_a-left+1)then
         if(len(a(left:)).gt.len(match))then
            match=a(left:)
            exit
         endif
      endif
   enddo
end subroutine compare_sub
end program main
Task: Longest common substring


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

auto collectSubStrings( const std::string& s, int maxSubLength )
{
    int l = s.length();
    auto res = std::set<std::string>();
    for ( int start = 0; start < l; start++ )
    {
        int m = std::min( maxSubLength, l - start + 1 );
        for ( int length = 1; length < m; length++ )
        {
            res.insert( s.substr( start, length ) );
        }
    }
    return res;
}

std::string lcs( const std::string& s0, const std::string& s1 )
{
    
    auto maxSubLength = std::min( s0.length(), s1.length() );
    auto set0 = collectSubStrings( s0, maxSubLength );
    auto set1 = collectSubStrings( s1, maxSubLength );

    
    auto common = std::vector<std::string>();
    std::set_intersection( set0.begin(), set0.end(), set1.begin(), set1.end(),
        std::back_inserter( common ) );

    
    std::nth_element( common.begin(), common.begin(), common.end(),
        []( const std::string& s1, const std::string& s2 ) {
            return s1.length() > s2.length();
        } );
    return *common.begin();
}

int main( int argc, char* argv[] )
{
    auto s1 = std::string( "thisisatest" );
    auto s2 = std::string( "testing123testing" );
    std::cout << "The longest common substring of " << s1 << " and " << s2
              << " is:\n";
    std::cout << "\"" << lcs( s1, s2 ) << "\" !\n";
    return 0;
}









Fortran: program main
implicit none
   call  compare('testing123testingthing', 'thisis',                 'thi')
   call  compare('testing',                'sting',                  'sting')
   call  compare('thisisatest_stinger',    'testing123testingthing', 'sting')
   call  compare('thisisatest_stinger',    'thisis',                 'thisis')
   call  compare('thisisatest',            'testing123testing',      'test')
   call  compare('thisisatest',            'thisisatest',            'thisisatest')
contains
subroutine compare(a,b,answer)
character(len=*),intent(in) :: a, b, answer
character(len=:),allocatable :: a2, match
character(len=*),parameter :: g='(*(g0))'
integer :: i
   a2=a 
   match=''
   do i=1,len(a2)-1
      call compare_sub(a2,b,match)
      if(len(a2).lt.len(match))exit
      a2=a2(:len(a2)-1)
   enddo
   write(*,g) merge('(PASSED)','(FAILED)',answer.eq.match), &
   & ' longest match found: "',match,'"; expected "',answer,'"', &
   & ' comparing "',a,'" and "',b,'"'
end subroutine
subroutine compare_sub(a,b,match)
character(len=*),intent(in) :: a, b
character(len=:),allocatable :: match
integer :: left, foundat, len_a
   len_a=len(a)
   do left=1,len_a
      foundat=index(b,a(left:))
      if(foundat.ne.0.and.len(match).lt.len_a-left+1)then
         if(len(a(left:)).gt.len(match))then
            match=a(left:)
            exit
         endif
      endif
   enddo
end subroutine compare_sub
end program main
Task: Longest common substring

C: #include <stdio.h>

void lcs(const char * const sa, const char * const sb, char ** const beg, char ** const end) {
    size_t apos, bpos;
    ptrdiff_t len;

    *beg = 0;
    *end = 0;
    len = 0;

    for (apos = 0; sa[apos] != 0; ++apos) {
        for (bpos = 0; sb[bpos] != 0; ++bpos) {
            if (sa[apos] == sb[bpos]) {
                len = 1;
                while (sa[apos + len] != 0 && sb[bpos + len] != 0 && sa[apos + len] == sb[bpos + len]) {
                    len++;
                }
            }

            if (len > *end - *beg) {
                *beg = sa + apos;
                *end = *beg + len;
                len = 0;
            }
        }
    }
}

int main() {
    char *s1 = "thisisatest";
    char *s2 = "testing123testing";
    char *beg, *end, *it;

    lcs(s1, s2, &beg, &end);

    for (it = beg; it != end; it++) {
        putchar(*it);
    }
    printf("\n");

    return 0;
}










Fortran: program main
implicit none
   call  compare('testing123testingthing', 'thisis',                 'thi')
   call  compare('testing',                'sting',                  'sting')
   call  compare('thisisatest_stinger',    'testing123testingthing', 'sting')
   call  compare('thisisatest_stinger',    'thisis',                 'thisis')
   call  compare('thisisatest',            'testing123testing',      'test')
   call  compare('thisisatest',            'thisisatest',            'thisisatest')
contains
subroutine compare(a,b,answer)
character(len=*),intent(in) :: a, b, answer
character(len=:),allocatable :: a2, match
character(len=*),parameter :: g='(*(g0))'
integer :: i
   a2=a 
   match=''
   do i=1,len(a2)-1
      call compare_sub(a2,b,match)
      if(len(a2).lt.len(match))exit
      a2=a2(:len(a2)-1)
   enddo
   write(*,g) merge('(PASSED)','(FAILED)',answer.eq.match), &
   & ' longest match found: "',match,'"; expected "',answer,'"', &
   & ' comparing "',a,'" and "',b,'"'
end subroutine
subroutine compare_sub(a,b,match)
character(len=*),intent(in) :: a, b
character(len=:),allocatable :: match
integer :: left, foundat, len_a
   len_a=len(a)
   do left=1,len_a
      foundat=index(b,a(left:))
      if(foundat.ne.0.and.len(match).lt.len_a-left+1)then
         if(len(a(left:)).gt.len(match))then
            match=a(left:)
            exit
         endif
      endif
   enddo
end subroutine compare_sub
end program main
Task: Longest common substring




Go: package main

import "fmt"

func lcs(a, b string) (output string) {
    lengths := make([]int, len(a)*len(b))
    greatestLength := 0
    for i, x := range a {
        for j, y := range b {
            if x == y {
                if i == 0 || j == 0 {
                    lengths[i*len(b)+j] = 1
                } else {
                    lengths[i*len(b)+j] = lengths[(i-1)*len(b)+j-1] + 1
                }
                if lengths[i*len(b)+j] > greatestLength {
                    greatestLength = lengths[i*len(b)+j]
                    output = a[i-greatestLength+1 : i+1]
                }
            }
        }
    }
    return
}

func main() {
    fmt.Println(lcs("thisisatest", "testing123testing"))
}







Fortran: program main
implicit none
   call  compare('testing123testingthing', 'thisis',                 'thi')
   call  compare('testing',                'sting',                  'sting')
   call  compare('thisisatest_stinger',    'testing123testingthing', 'sting')
   call  compare('thisisatest_stinger',    'thisis',                 'thisis')
   call  compare('thisisatest',            'testing123testing',      'test')
   call  compare('thisisatest',            'thisisatest',            'thisisatest')
contains
subroutine compare(a,b,answer)
character(len=*),intent(in) :: a, b, answer
character(len=:),allocatable :: a2, match
character(len=*),parameter :: g='(*(g0))'
integer :: i
   a2=a 
   match=''
   do i=1,len(a2)-1
      call compare_sub(a2,b,match)
      if(len(a2).lt.len(match))exit
      a2=a2(:len(a2)-1)
   enddo
   write(*,g) merge('(PASSED)','(FAILED)',answer.eq.match), &
   & ' longest match found: "',match,'"; expected "',answer,'"', &
   & ' comparing "',a,'" and "',b,'"'
end subroutine
subroutine compare_sub(a,b,match)
character(len=*),intent(in) :: a, b
character(len=:),allocatable :: match
integer :: left, foundat, len_a
   len_a=len(a)
   do left=1,len_a
      foundat=index(b,a(left:))
      if(foundat.ne.0.and.len(match).lt.len_a-left+1)then
         if(len(a(left:)).gt.len(match))then
            match=a(left:)
            exit
         endif
      endif
   enddo
end subroutine compare_sub
end program main
Task: Longest common substring





Java: public class LongestCommonSubstring {

    public static void main(String[] args) {
        System.out.println(lcs("testing123testing", "thisisatest"));
        System.out.println(lcs("test", "thisisatest"));
        System.out.println(lcs("testing", "sting"));
        System.out.println(lcs("testing", "thisisasting"));
    }

    static String lcs(String a, String b) {
        if (a.length() > b.length())
            return lcs(b, a);

        String res = "";
        for (int ai = 0; ai < a.length(); ai++) {
            for (int len = a.length() - ai; len > 0; len--) {

                for (int bi = 0; bi <= b.length() - len; bi++) {

                    if (a.regionMatches(ai, b, bi, len) && len > res.length()) {
                        res = a.substring(ai, ai + len);
                    }
                }
            }
        }
        return res;
    }
}






Fortran: program main
implicit none
   call  compare('testing123testingthing', 'thisis',                 'thi')
   call  compare('testing',                'sting',                  'sting')
   call  compare('thisisatest_stinger',    'testing123testingthing', 'sting')
   call  compare('thisisatest_stinger',    'thisis',                 'thisis')
   call  compare('thisisatest',            'testing123testing',      'test')
   call  compare('thisisatest',            'thisisatest',            'thisisatest')
contains
subroutine compare(a,b,answer)
character(len=*),intent(in) :: a, b, answer
character(len=:),allocatable :: a2, match
character(len=*),parameter :: g='(*(g0))'
integer :: i
   a2=a 
   match=''
   do i=1,len(a2)-1
      call compare_sub(a2,b,match)
      if(len(a2).lt.len(match))exit
      a2=a2(:len(a2)-1)
   enddo
   write(*,g) merge('(PASSED)','(FAILED)',answer.eq.match), &
   & ' longest match found: "',match,'"; expected "',answer,'"', &
   & ' comparing "',a,'" and "',b,'"'
end subroutine
subroutine compare_sub(a,b,match)
character(len=*),intent(in) :: a, b
character(len=:),allocatable :: match
integer :: left, foundat, len_a
   len_a=len(a)
   do left=1,len_a
      foundat=index(b,a(left:))
      if(foundat.ne.0.and.len(match).lt.len_a-left+1)then
         if(len(a(left:)).gt.len(match))then
            match=a(left:)
            exit
         endif
      endif
   enddo
end subroutine compare_sub
end program main
Task: Longest common substring







Python: s1 = "thisisatest"
s2 = "testing123testing"
len1, len2 = len(s1), len(s2)
ir, jr = 0, -1
for i1 in range(len1):
    i2 = s2.find(s1[i1])
    while i2 >= 0:
        j1, j2 = i1, i2
        while j1 < len1 and j2 < len2 and s2[j2] == s1[j1]:
            if j1-i1 >= jr-ir:
                ir, jr = i1, j1
            j1 += 1; j2 += 1
        i2 = s2.find(s1[i1], i2+1)
print (s1[ir:jr+1])




Fortran: program main
implicit none
   call  compare('testing123testingthing', 'thisis',                 'thi')
   call  compare('testing',                'sting',                  'sting')
   call  compare('thisisatest_stinger',    'testing123testingthing', 'sting')
   call  compare('thisisatest_stinger',    'thisis',                 'thisis')
   call  compare('thisisatest',            'testing123testing',      'test')
   call  compare('thisisatest',            'thisisatest',            'thisisatest')
contains
subroutine compare(a,b,answer)
character(len=*),intent(in) :: a, b, answer
character(len=:),allocatable :: a2, match
character(len=*),parameter :: g='(*(g0))'
integer :: i
   a2=a 
   match=''
   do i=1,len(a2)-1
      call compare_sub(a2,b,match)
      if(len(a2).lt.len(match))exit
      a2=a2(:len(a2)-1)
   enddo
   write(*,g) merge('(PASSED)','(FAILED)',answer.eq.match), &
   & ' longest match found: "',match,'"; expected "',answer,'"', &
   & ' comparing "',a,'" and "',b,'"'
end subroutine
subroutine compare_sub(a,b,match)
character(len=*),intent(in) :: a, b
character(len=:),allocatable :: match
integer :: left, foundat, len_a
   len_a=len(a)
   do left=1,len_a
      foundat=index(b,a(left:))
      if(foundat.ne.0.and.len(match).lt.len_a-left+1)then
         if(len(a(left:)).gt.len(match))then
            match=a(left:)
            exit
         endif
      endif
   enddo
end subroutine compare_sub
end program main
Task: Password generator



C#: using System;
using System.Linq;

class Program
{
    const string Lower = "abcdefghijklmnopqrstuvwxyz";
    const string Upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const string Digits = "0123456789";
    const string Symbols = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~";
    static readonly string[] Full = {Lower, Upper, Digits, Symbols, Lower + Upper + Digits + Symbols};

    const string Similar = "Il1O05S2Z";
    static readonly string[] Excluded = Full.Select(x => new string(x.Except(Similar).ToArray())).ToArray();

    static Random _rng = new Random();
    static string[] _symbolSet = Full;

    static void Main(string[] args)
    {
        int length = 12, count = 1;
        try
        {
            foreach (var x in args.Select(arg => arg.Split(':')))
            {
                switch (x[0])
                {
                    case "-l": length = int.Parse(x[1]); break;
                    case "-c": count = int.Parse(x[1]); break;
                    case "-s": _rng = new Random(x[1].GetHashCode()); break;
                    case "-x": _symbolSet = bool.Parse(x[1]) ? Excluded : Full; break;
                    default: throw new FormatException("Could not parse arguments");
                }
            }
        }
        catch { ShowUsage(); return; }
        try
        {
            for (int i = 0; i < count; i++)
                Console.WriteLine(GeneratePass(length));
        }
        catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); }
    }

    static void ShowUsage()
    {
        Console.WriteLine("Usage: PASSGEN [-l:length] [-c:count] [-s:seed] [-x:(true|false)]");
        Console.WriteLine("\t-l: the length of the generated passwords");
        Console.WriteLine("\t-c: the number of passwords to generate");
        Console.WriteLine("\t-s: seed for the random number generator");
        Console.WriteLine("\t-x: exclude similar characters: " + Similar);
        Console.WriteLine("Example: PASSGEN -l:10 -c:5 -s:\"Sample Seed\" -x:true");
    }

    static string GeneratePass(int length)
    {
        var minLength = _symbolSet.Length - 1;
        if(length < minLength)
            throw new Exception("password length must be " + minLength + " or greater");

        int[] usesRemaining = Enumerable.Repeat(1, _symbolSet.Length).ToArray();
        usesRemaining[minLength] = length - minLength;
        var password = new char[length];
        for (int ii = 0; ii < length; ii++)
        {
            int set = _rng.Next(0, _symbolSet.Length);
            if (usesRemaining[set] > 0)
            {
                usesRemaining[set]--;
                password[ii] = _symbolSet[set][_rng.Next(0, _symbolSet[set].Length)];
            }
            else ii--;
        }
        return new string(password);
    }
}
Task: Password generator


C++: #include <iostream>
#include <string>
#include <algorithm>
#include <ctime>

const std::string CHR[] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", 
                            "0123456789", "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" };
const std::string UNS = "O0l1I5S2Z";

std::string createPW( int len, bool safe ) {
    std::string pw;
    char t;
    for( int x = 0; x < len; x += 4 ) {
        for( int y = x; y < x + 4 && y < len; y++ ) {
            do {
                t = CHR[y % 4].at( rand() % CHR[y % 4].size() );
            } while( safe && UNS.find( t ) != UNS.npos );
            pw.append( 1, t );
        }
    }
    std::random_shuffle( pw.begin(), pw.end() );
    return pw;
}
void generate( int len, int count, bool safe ) {
    for( int c = 0; c < count; c++ ) {
        std::cout << createPW( len, safe ) << "\n";
    }
    std::cout << "\n\n";
}
int main( int argc, char* argv[] ){
    if( argv[1][1] == '?' || argc < 5 ) {
        std::cout << "Syntax: PWGEN length count safe seed /?\n"
                     "length:\tthe length of the password(min 4)\n"
                     "count:\thow many passwords should be generated\n"
                     "safe:\t1 will exclude visually similar characters, 0 won't\n"
                     "seed:\tnumber to seed the random generator or 0\n"
                     "/?\tthis text\n\n";
    } else {
        int l = atoi( argv[1] ),
            c = atoi( argv[2] ),
            e = atoi( argv[3] ), 
            s = atoi( argv[4] );
        if( l < 4 ) {
            std::cout << "Passwords must be at least 4 characters long.\n\n";
        } else {
            if (s == 0) {
               std::srand( time( NULL ) );
            } else {
               std::srand( unsigned( s ) );
            }
            generate( l, c, e != 0 );
        }
    }
    return 0;   
}
Task: Password generator





Java: import java.util.*;

public class PasswordGenerator {
    final static Random rand = new Random();

    public static void main(String[] args) {
        int num, len;

        try {
            if (args.length != 2)
                throw new IllegalArgumentException();

            len = Integer.parseInt(args[0]);
            if (len < 4 || len > 16)
                throw new IllegalArgumentException();

            num = Integer.parseInt(args[1]);
            if (num < 1 || num > 10)
                throw new IllegalArgumentException();

            for (String pw : generatePasswords(num, len))
                System.out.println(pw);

        } catch (IllegalArgumentException e) {
            String s = "Provide the length of the passwords (min 4, max 16) you "
                    + "want to generate,\nand how many (min 1, max 10)";
            System.out.println(s);
        }
    }

    private static List<String> generatePasswords(int num, int len) {
        final String s = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~";

        List<String> result = new ArrayList<>();

        for (int i = 0; i < num; i++) {
            StringBuilder sb = new StringBuilder();
            sb.append(s.charAt(rand.nextInt(s.length())));
            sb.append((char) (rand.nextInt(10) + '0'));
            sb.append((char) (rand.nextInt(26) + 'a'));
            sb.append((char) (rand.nextInt(26) + 'A'));

            for (int j = 4; j < len; j++) {
                int r = rand.nextInt(93) + '!';
                if (r == 92 || r == 96) {
                    j--;
                } else {
                    sb.append((char) r);
                }
            }
            result.add(shuffle(sb));
        }
        return result;
    }

    public static String shuffle(StringBuilder sb) {
        int len = sb.length();
        for (int i = len - 1; i > 0; i--) {
            int r = rand.nextInt(i);
            char tmp = sb.charAt(i);
            sb.setCharAt(i, sb.charAt(r));
            sb.setCharAt(r, tmp);
        }
        return sb.toString();
    }
}
Task: Password generator







Python: import random

lowercase = 'abcdefghijklmnopqrstuvwxyz' 
uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 
digits = '0123456789'                    
punctuation = '!"

allowed = lowercase + uppercase + digits + punctuation

visually_similar = 'Il1O05S2Z'


def new_password(length:int, readable=True) -> str:
    if length < 4:
        print("password length={} is too short,".format(length),
            "minimum length=4")
        return ''
    choice = random.SystemRandom().choice
    while True:
        password_chars = [
            choice(lowercase),
            choice(uppercase),
            choice(digits),
            choice(punctuation)
            ] + random.sample(allowed, length-4)
        if (not readable or 
                all(c not in visually_similar for c in password_chars)):
            random.SystemRandom().shuffle(password_chars)
            return ''.join(password_chars)


def password_generator(length, qty=1, readable=True):
    for i in range(qty):
        print(new_password(length, readable))