WeixiangYan/CodeTransOcean huggingface dataset:
Task: Pascal matrix generation



C#: using System;

public static class PascalMatrixGeneration
{
    public static void Main() {
        Print(GenerateUpper(5));
        Console.WriteLine();
        Print(GenerateLower(5));
        Console.WriteLine();
        Print(GenerateSymmetric(5));
    }

    static int[,] GenerateUpper(int size) {
        int[,] m = new int[size, size];
        for (int c = 0; c < size; c++) m[0, c] = 1;
        for (int r = 1; r < size; r++) {
            for (int c = r; c < size; c++) {
                m[r, c] = m[r-1, c-1] + m[r, c-1];
            }
        }
        return m;
    }

    static int[,] GenerateLower(int size) {
        int[,] m = new int[size, size];
        for (int r = 0; r < size; r++) m[r, 0] = 1;
        for (int c = 1; c < size; c++) {
            for (int r = c; r < size; r++) {
                m[r, c] = m[r-1, c-1] + m[r-1, c];
            }
        }
        return m;
    }

    static int[,] GenerateSymmetric(int size) {
        int[,] m = new int[size, size];
        for (int i = 0; i < size; i++) m[0, i] = m[i, 0] = 1;
        for (int r = 1; r < size; r++) {
            for (int c = 1; c < size; c++) {
                m[r, c] = m[r-1, c] + m[r, c-1];
            }
        }
        return m;
    }

    static void Print(int[,] matrix) {
        string[,] m = ToString(matrix);
        int width = m.Cast<string>().Select(s => s.Length).Max();
        int rows = matrix.GetLength(0), columns = matrix.GetLength(1);
        for (int row = 0; row < rows; row++) {
            Console.WriteLine("|" + string.Join(" ", Range(0, columns).Select(column => m[row, column].PadLeft(width, ' '))) + "|");
        }
    }

    static string[,] ToString(int[,] matrix) {
        int rows = matrix.GetLength(0), columns = matrix.GetLength(1);
        string[,] m = new string[rows, columns];
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < columns; c++) {
                m[r, c] = matrix[r, c].ToString();
            }
        }
        return m;
    }
    
}
Task: Mad Libs



C#: using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace MadLibs_RosettaCode
{
	class Program
	{
		static void Main(string[] args)
		{
			string madLibs = 
@"Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story, 
ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
Given this example, it should then ask for a name, 
a he or she and a noun (<name> gets replaced both times with the same value).";

			StringBuilder sb = new StringBuilder();
			Regex pattern = new Regex(@"\<(.*?)\>");
			string storyLine;
			string replacement;

			Console.WriteLine(madLibs + Environment.NewLine + Environment.NewLine);
			Console.WriteLine("Enter a story: ");

			
			do
			{
				storyLine = Console.ReadLine();
				sb.Append(storyLine + Environment.NewLine);
			} while (!string.IsNullOrEmpty(storyLine) && !string.IsNullOrWhiteSpace(storyLine));

			
			Match nameMatch = pattern.Matches(sb.ToString()).OfType<Match>().Where(x => x.Value.Equals("<name>")).Select(x => x.Value).Distinct() as Match;
			if(nameMatch != null)
			{
				do
				{
					Console.WriteLine("Enter value for: " + nameMatch.Value);
					replacement = Console.ReadLine();
				} while (string.IsNullOrEmpty(replacement) || string.IsNullOrWhiteSpace(replacement));
				sb.Replace(nameMatch.Value, replacement);
			}

			foreach (Match match in pattern.Matches(sb.ToString()))
			{
				replacement = string.Empty;
				
				do
				{
					Console.WriteLine("Enter value for: " + match.Value);
					replacement = Console.ReadLine();
				} while (string.IsNullOrEmpty(replacement) || string.IsNullOrWhiteSpace(replacement));

				int location = sb.ToString().IndexOf(match.Value);
				sb.Remove(location, match.Value.Length).Insert(location, replacement);
			}

			Console.WriteLine(Environment.NewLine + Environment.NewLine + "--[ Here's your story! ]--");
			Console.WriteLine(sb.ToString());
		}
	}
}
Task: Shortest common supersequence



C#: public class ShortestCommonSupersequence
{
    Dictionary<(string, string), string> cache = new();

    public string scs(string x, string y)
    {
        if (x.Length == 0) return y;
        if (y.Length == 0) return x;

        if (cache.TryGetValue((x, y), out var result)) return result;

        if (x[0] == y[0])
        {
            return cache[(x, y)] = x[0] + scs(x.Substring(1), y.Substring(1));
        }

        var xr = scs(x.Substring(1), y);
        var yr = scs(x, y.Substring(1));
        if (yr.Length <= xr.Length)
        {
            return cache[(x, y)] = y[0] + yr;
        }
        else
        {
            return cache[(x, y)] = x[0] + xr;
        }
    }

    public static void Main(string[] args)
    {
        var scs = new ShortestCommonSupersequence();
        Console.WriteLine(scs.scs("abcbdab", "bdcaba"));
    }
}
Task: Magic 8-ball



C#: using System;

namespace newProg
{

    class Program
    {
        static void Main(string[] args)
        {
            string[] answers =
            {
                "It is certain.",
                "It is decidedly so.",
                "Without a doubt.",
                "Yes – definitely.",
                "You may rely on it.",
                "As I see it, yes.",
                "Most likely.",
                "Outlook good.",
                "Yes.",
                "Signs point to yes.",
                "Reply hazy, try again.",
                "Ask again later",
                "Better not tell you now.",
                "Cannot predict now.",
                "Concentrate and ask again.",
                "Don't count on it.",
                "My reply is no.",
                "My sources say no.",
                "Outlook not so good.",
                "Very doubtful."
            };

            while (true)
            {
                Random rnd = new Random();
                int result = rnd.Next(0, 19);

                Console.WriteLine("Magic 8 Ball! Ask question and hit a key for the answer!");

                string inp = Console.ReadLine();
                
                Console.WriteLine(answers[result]);

            }
        }
    }
}
Task: Validate International Securities Identification Number



C#: using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace ValidateIsin
{
    public static class IsinValidator
    {
        public static bool IsValidIsin(string isin) => 
            IsinRegex.IsMatch(isin) && LuhnTest(Digitize(isin));

        private static readonly Regex IsinRegex = 
            new Regex("^[A-Z]{2}[A-Z0-9]{9}\\d$", RegexOptions.Compiled);

        private static string Digitize(string isin) =>
            string.Join("", isin.Select(c => $"{DigitValue(c)}"));

        private static bool LuhnTest(string number) => 
            number.Reverse().Select(DigitValue).Select(Summand).Sum() % 10 == 0;

        private static int Summand(int digit, int i) =>
            digit + (i % 2) * (digit - digit / 5 * 9);

        private static int DigitValue(char c) =>
            c >= '0' && c <= '9' 
                ? c - '0' 
                : c - 'A' + 10;
   }
	
   public class Program
   {
        public static void Main() 
        {
            string[] isins = 
            {
                "US0378331005",
                "US0373831005",
                "U50378331005",
                "US03378331005",
                "AU0000XVGZA3",
                "AU0000VXGZA3",
                "FR0000988040"
            };

            foreach (string isin in isins) {
                string validOrNot = IsinValidator.IsValidIsin(isin) ? "valid" : "not valid";
                Console.WriteLine($"{isin} is {validOrNot}");
            }
        }
    }
}
Task: Orbital elements



C#: using System;

namespace OrbitalElements {
    class Vector {
        public Vector(double x, double y, double z) {
            X = x;
            Y = y;
            Z = z;
        }

        public double X { get; set; }
        public double Y { get; set; }
        public double Z { get; set; }

        public double Abs() {
            return Math.Sqrt(X * X + Y * Y + Z * Z);
        }

        public static Vector operator +(Vector lhs, Vector rhs) {
            return new Vector(lhs.X + rhs.X, lhs.Y + rhs.Y, lhs.Z + rhs.Z);
        }

        public static Vector operator *(Vector self, double m) {
            return new Vector(self.X * m, self.Y * m, self.Z * m);
        }

        public static Vector operator /(Vector self, double m) {
            return new Vector(self.X / m, self.Y / m, self.Z / m);
        }

        public override string ToString() {
            return string.Format("({0}, {1}, {2})", X, Y, Z);
        }
    }

    class Program {
        static Tuple<Vector, Vector> OrbitalStateVectors(
            double semiMajorAxis,
            double eccentricity,
            double inclination,
            double longitudeOfAscendingNode,
            double argumentOfPeriapsis,
            double trueAnomaly
        ) {
            Vector mulAdd(Vector v1, double x1, Vector v2, double x2) {
                return v1 * x1 + v2 * x2;
            }

            Tuple<Vector, Vector> rotate(Vector iv, Vector jv, double alpha) {
                return new Tuple<Vector, Vector>(
                    mulAdd(iv, +Math.Cos(alpha), jv, Math.Sin(alpha)),
                    mulAdd(iv, -Math.Sin(alpha), jv, Math.Cos(alpha))
                );
            }

            var i = new Vector(1, 0, 0);
            var j = new Vector(0, 1, 0);
            var k = new Vector(0, 0, 1);

            var p = rotate(i, j, longitudeOfAscendingNode);
            i = p.Item1; j = p.Item2;
            p = rotate(j, k, inclination);
            j = p.Item1;
            p = rotate(i, j, argumentOfPeriapsis);
            i = p.Item1; j = p.Item2;

            var l = semiMajorAxis * ((eccentricity == 1.0) ? 2.0 : (1.0 - eccentricity * eccentricity));
            var c = Math.Cos(trueAnomaly);
            var s = Math.Sin(trueAnomaly);
            var r = l / (1.0 + eccentricity * c);
            var rprime = s * r * r / l;
            var position = mulAdd(i, c, j, s) * r;
            var speed = mulAdd(i, rprime * c - r * s, j, rprime * s + r * c);
            speed /= speed.Abs();
            speed *= Math.Sqrt(2.0 / r - 1.0 / semiMajorAxis);

            return new Tuple<Vector, Vector>(position, speed);
        }

        static void Main(string[] args) {
            var res = OrbitalStateVectors(1.0, 0.1, 0.0, 355.0 / (113.0 * 6.0), 0.0, 0.0);
            Console.WriteLine("Position : {0}", res.Item1);
            Console.WriteLine("Speed    : {0}", res.Item2);
        }
    }
}
Task: Input_Output for pairs of numbers



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

public class Program
{
    static void Main(string[] args)
    {
	int count = Convert.ToInt32(Console.ReadLine());
	for (int line = 0; line < count; line++) {
            Console.WriteLine(Console.ReadLine().Split(' ').Sum(i => Convert.ToInt32(i)));
	}
    }
}
Task: Text between



C#: using System;

namespace TextBetween {
    class Program {
        static string TextBetween(string source, string beg, string end) {
            int startIndex;

            if (beg == "start") {
                startIndex = 0;
            }
            else {
                startIndex = source.IndexOf(beg);
                if (startIndex < 0) {
                    return "";
                }
                startIndex += beg.Length;
            }

            int endIndex = source.IndexOf(end, startIndex);
            if (endIndex < 0 || end == "end") {
                return source.Substring(startIndex);
            }
            return source.Substring(startIndex, endIndex - startIndex);
        }

        static void Print(string s, string b, string e) {
            Console.WriteLine("text: '{0}'", s);
            Console.WriteLine("start: '{0}'", b);
            Console.WriteLine("end: '{0}'", e);
            Console.WriteLine("result: '{0}'", TextBetween(s, b, e));
            Console.WriteLine();
        }

        static void Main(string[] args) {
            Print("Hello Rosetta Code world", "Hello ", " world");
            Print("Hello Rosetta Code world", "start", " world");
            Print("Hello Rosetta Code world", "Hello ", "end");
            Print("</div><div style=\"chinese\">你好嗎</div>", "<div style=\"chinese\">", "</div>");
            Print("<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">", "<text>", "<table>");
            Print("<table style=\"myTable\"><tr><td>hello world</td></tr></table>", "<table>", "</table>");
            Print("The quick brown fox jumps over the lazy other fox", "quick ", " fox");
            Print("One fish two fish red fish blue fish", "fish ", " red");
            Print("FooBarBazFooBuxQuux", "Foo", "Foo");
        }
    }
}
Task: Flow-control structures



C#: int GetNumber() {
    return 5;
}
Task: Exceptions



C#: public class MyException : Exception
{
  
};
Task: Enforced immutability



C#: readonly DateTime now = DateTime.Now;
Task: Largest number divisible by its digits



C#: using System;

class Program {
    static int gcd(int a, int b) { return b > 0 ? gcd(b, a % b) : a; }

    
    static int lcmd(long x, int b) {
      int r = (int)(x % b), a; x /= b; while (x > 0) {
        r = (r * (a = (int)(x % b))) / gcd(r, a); x /= b; } return r; }

    static void Main(string[] args) {
        var sw = System.Diagnostics.Stopwatch.StartNew();
        long mx = 987654321; 
             mx = 98764321; 
             mx /= 10;     
        long skip = lcmd(mx, 10), i; bool nDup;
        for (i = mx - mx % skip; ; i -= skip) {
            var s = i.ToString().ToCharArray(); Array.Sort(s);
            if (s[0] == '0') continue; 
            nDup = true; 
            for (int j = 0, k = 1; k < s.Length; j = k++)
                if (s[j] == s[k] || s[k] == '5') { nDup = false; break; }
            if (nDup) break; } sw.Stop(); 
        Console.Write("base 10 = {0} in {1} μs\n", i,
          1000 * sw.Elapsed.TotalMilliseconds);
        sw.Restart();
        mx = 0xfedcba987654321;    
        skip = lcmd(mx >> 4, 16); 
        for (i = mx - mx % skip; ; i -= skip) {
            var s = i.ToString("x").ToCharArray(); Array.Sort(s);
            if (s[0] == '0') continue; 
            nDup = true; 
            for (int j = 0, k = 1; k < s.Length; j = k++)
                if (s[j] == s[k]) { nDup = false; break; }
            if (nDup) break; } sw.Stop(); 
        Console.Write("base 16 = {0} in {1} ms", i.ToString("x"),
          sw.Elapsed.TotalMilliseconds); } }
Task: Bitmap_Bézier curves_Cubic







Python: def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):
    pts = []
    for i in range(n+1):
        t = i / n
        a = (1. - t)**3
        b = 3. * t * (1. - t)**2
        c = 3.0 * t**2 * (1.0 - t)
        d = t**3
        
        x = int(a * x0 + b * x1 + c * x2 + d * x3)
        y = int(a * y0 + b * y1 + c * y2 + d * y3)
        pts.append( (x, y) )
    for i in range(n):
        self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1])
Bitmap.cubicbezier = cubicbezier

bitmap = Bitmap(17,17)
bitmap.cubicbezier(16,1, 1,4, 3,16, 15,11)
bitmap.chardisplay()
Task: Range consolidation

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

typedef struct range_tag {
    double low;
    double high;
} range_t;

void normalize_range(range_t* range) {
    if (range->high < range->low) {
        double tmp = range->low;
        range->low = range->high;
        range->high = tmp;
    }
}

int range_compare(const void* p1, const void* p2) {
    const range_t* r1 = p1;
    const range_t* r2 = p2;
    if (r1->low < r2->low)
        return -1;
    if (r1->low > r2->low)
        return 1;
    if (r1->high < r2->high)
        return -1;
    if (r1->high > r2->high)
        return 1;
    return 0;
}

void normalize_ranges(range_t* ranges, size_t count) {
    for (size_t i = 0; i < count; ++i)
        normalize_range(&ranges[i]);
    qsort(ranges, count, sizeof(range_t), range_compare);
}



size_t consolidate_ranges(range_t* ranges, size_t count) {
    normalize_ranges(ranges, count);
    size_t out_index = 0;
    for (size_t i = 0; i < count; ) {
        size_t j = i;
        while (++j < count && ranges[j].low <= ranges[i].high) {
            if (ranges[i].high < ranges[j].high)
                ranges[i].high = ranges[j].high;
        }
        ranges[out_index++] = ranges[i];
        i = j;
    }
    return out_index;
}

void print_range(const range_t* range) {
    printf("[%g, %g]", range->low, range->high);
}

void print_ranges(const range_t* ranges, size_t count) {
    if (count == 0)
        return;
    print_range(&ranges[0]);
    for (size_t i = 1; i < count; ++i) {
        printf(", ");
        print_range(&ranges[i]);
    }
}

void test_consolidate_ranges(range_t* ranges, size_t count) {
    print_ranges(ranges, count);
    printf(" -> ");
    count = consolidate_ranges(ranges, count);
    print_ranges(ranges, count);
    printf("\n");
}

#define LENGTHOF(a) sizeof(a)/sizeof(a[0])

int main() {
    range_t test1[] = { {1.1, 2.2} };
    range_t test2[] = { {6.1, 7.2}, {7.2, 8.3} };
    range_t test3[] = { {4, 3}, {2, 1} };
    range_t test4[] = { {4, 3}, {2, 1}, {-1, -2}, {3.9, 10} };
    range_t test5[] = { {1, 3}, {-6, -1}, {-4, -5}, {8, 2}, {-6, -6} };
    test_consolidate_ranges(test1, LENGTHOF(test1));
    test_consolidate_ranges(test2, LENGTHOF(test2));
    test_consolidate_ranges(test3, LENGTHOF(test3));
    test_consolidate_ranges(test4, LENGTHOF(test4));
    test_consolidate_ranges(test5, LENGTHOF(test5));
    return 0;
}
Task: Mad Libs

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

#define err(...) fprintf(stderr, ## __VA_ARGS__), exit(1)


typedef struct {
    char *data;
    size_t alloc;
    size_t length;
} dstr;

inline int dstr_space(dstr *s, size_t grow_amount)
{
    return s->length + grow_amount < s->alloc;
}

int dstr_grow(dstr *s)
{
    s->alloc *= 2;
    char *attempt = realloc(s->data, s->alloc);

    if (!attempt) return 0;
    else s->data = attempt;

    return 1;
}

dstr* dstr_init(const size_t to_allocate)
{
    dstr *s = malloc(sizeof(dstr));
    if (!s) goto failure;

    s->length = 0;
    s->alloc  = to_allocate;
    s->data   = malloc(s->alloc);

    if (!s->data) goto failure;

    return s;

failure:
    if (s->data) free(s->data);
    if (s) free(s);
    return NULL;
}

void dstr_delete(dstr *s)
{
    if (s->data) free(s->data);
    if (s) free(s);
}

dstr* readinput(FILE *fd)
{
    static const size_t buffer_size = 4096;
    char buffer[buffer_size];

    dstr *s = dstr_init(buffer_size);
    if (!s) goto failure;

    while (fgets(buffer, buffer_size, fd)) {
        while (!dstr_space(s, buffer_size))
            if (!dstr_grow(s)) goto failure;

        strncpy(s->data + s->length, buffer, buffer_size);
        s->length += strlen(buffer);
    }

    return s;

failure:
    dstr_delete(s);
    return NULL;
}

void dstr_replace_all(dstr *story, const char *replace, const char *insert)
{
    const size_t replace_l = strlen(replace);
    const size_t insert_l  = strlen(insert);
    char *start = story->data;

    while ((start = strstr(start, replace))) {
        if (!dstr_space(story, insert_l - replace_l))
            if (!dstr_grow(story)) err("Failed to allocate memory");

        if (insert_l != replace_l) {
            memmove(start + insert_l, start + replace_l, story->length -
                    (start + replace_l - story->data));

            
            story->length += insert_l - replace_l;
            story->data[story->length] = 0;
        }

        memmove(start, insert, insert_l);
    }
}

void madlibs(dstr *story)
{
    static const size_t buffer_size = 128;
    char insert[buffer_size];
    char replace[buffer_size];

    char *start,
         *end = story->data;

    while (start = strchr(end, '<')) {
        if (!(end = strchr(start, '>'))) err("Malformed brackets in input");

        
        strncpy(replace, start, end - start + 1);
        replace[end - start + 1] = '\0';

        printf("Enter value for field %s: ", replace);

        fgets(insert, buffer_size, stdin);
        const size_t il = strlen(insert) - 1;
        if (insert[il] == '\n')
            insert[il] = '\0';

        dstr_replace_all(story, replace, insert);
    }
    printf("\n");
}

int main(int argc, char *argv[])
{
    if (argc < 2) return 0;

    FILE *fd = fopen(argv[1], "r");
    if (!fd) err("Could not open file: '%s\n", argv[1]);

    dstr *story = readinput(fd); fclose(fd);
    if (!story) err("Failed to allocate memory");

    madlibs(story);
    printf("%s\n", story->data);
    dstr_delete(story);
    return 0;
}
Task: Mian-Chowla sequence

C: #include <stdio.h>
#include <stdbool.h>
#include <time.h>
 
#define n 100
#define nn ((n * (n + 1)) >> 1)

bool Contains(int lst[], int item, int size) {
	for (int i = size - 1; i >= 0; i--)
 		if (item == lst[i]) return true;
	return false;
}
 
int * MianChowla()
{
	static int mc[n]; mc[0] = 1;
	int sums[nn];	sums[0] = 2;
	int sum, le, ss = 1;
	for (int i = 1; i < n; i++) {
		le = ss;
		for (int j = mc[i - 1] + 1; ; j++) {
			mc[i] = j;
			for (int k = 0; k <= i; k++) {
				sum = mc[k] + j;
				if (Contains(sums, sum, ss)) {
					ss = le; goto nxtJ;
				}
				sums[ss++] = sum;
			}
			break;
		nxtJ:;
		}
	}
	return mc;
}
 
int main() {
	clock_t st = clock(); int * mc; mc = MianChowla();
        double et = ((double)(clock() - st)) / CLOCKS_PER_SEC;
	printf("The first 30 terms of the Mian-Chowla sequence are:\n");
	for (int i = 0; i < 30; i++) printf("%d ", mc[i]);
	printf("\n\nTerms 91 to 100 of the Mian-Chowla sequence are:\n");
	for (int i = 90; i < 100; i++) printf("%d ", mc[i]); 
	printf("\n\nComputation time was %f seconds.", et);
}
Task: Water collected between towers

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

int getWater(int* arr,int start,int end,int cutoff){
	int i, sum = 0;
	
	for(i=start;i<=end;i++)
		sum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);
	
	return sum;
}

int netWater(int* arr,int size){
	int i, j, ref1, ref2, marker, markerSet = 0,sum = 0;
	
	if(size<3)
		return 0;

	for(i=0;i<size-1;i++){
		start:if(i!=size-2 && arr[i]>arr[i+1]){
				ref1 = i;
				
				for(j=ref1+1;j<size;j++){
					if(arr[j]>=arr[ref1]){
						ref2 = j;
						
						sum += getWater(arr,ref1+1,ref2-1,ref1);

						i = ref2;
						
						goto start;
					}
					
					else if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){
						marker = j+1;
						markerSet = 1;
					}
				}
				
				if(markerSet==1){
					sum += getWater(arr,ref1+1,marker-1,marker);

					i = marker;
					
					markerSet = 0;
					
					goto start;
				}
			}
		}
	
	return sum;
}

int main(int argC,char* argV[])
{
	int *arr,i;
	
	if(argC==1)
		printf("Usage : %s <followed by space separated series of integers>");
	else{
		arr = (int*)malloc((argC-1)*sizeof(int));
		
		for(i=1;i<argC;i++)
			arr[i-1] = atoi(argV[i]);

		printf("Water collected : %d",netWater(arr,argC-1));
	}
	
	return 0;
}