WeixiangYan/CodeTransOcean huggingface dataset:
Task: Middle three digits




Go: package m3

import (
    "errors"
    "strconv"
)

var (
    ErrorLT3  = errors.New("N of at least three digits required.")
    ErrorEven = errors.New("N with odd number of digits required.")
)

func Digits(i int) (string, error) {
    if i < 0 {
        i = -i
    }
    if i < 100 {
        return "", ErrorLT3
    }
    s := strconv.Itoa(i)
    if len(s)%2 == 0 {
        return "", ErrorEven
    }
    m := len(s) / 2
    return s[m-1 : m+2], nil
}






COBOL: identification division.
program-id. middle3.
environment division.
data division.
working-storage section.
01  num                 pic 9(9). 
    88 num-too-small    values are -99 thru 99.
01  num-disp            pic ---------9.

01  div                 pic 9(9).
01  mod                 pic 9(9).
01  mod-disp            pic 9(3).

01  digit-counter       pic 999.
01  digit-div           pic 9(9).
    88  no-more-digits  value 0.
01  digit-mod           pic 9(9).
    88  is-even         value 0.

01  multiplier          pic 9(9).

01  value-items.
    05  filler  pic s9(9) value 123.
    05  filler  pic s9(9) value 12345.
    05  filler  pic s9(9) value 1234567.
    05  filler  pic s9(9) value 987654321.
    05  filler  pic s9(9) value 10001.
    05  filler  pic s9(9) value -10001.
    05  filler  pic s9(9) value -123.
    05  filler  pic s9(9) value -100.
    05  filler  pic s9(9) value 100.
    05  filler  pic s9(9) value -12345.
    05  filler  pic s9(9) value 1.
    05  filler  pic s9(9) value 2.
    05  filler  pic s9(9) value -1.
    05  filler  pic s9(9) value -10.
    05  filler  pic s9(9) value 2002.
    05  filler  pic s9(9) value -2002.
    05  filler  pic s9(9) value 0.
    
01  value-array redefines value-items.
    05  items   pic s9(9)  occurs 17 times indexed by item.

01  result  pic x(20).

procedure division.
10-main.
    perform with test after varying item from 1 by 1 until items(item) = 0
        move items(item) to num
        move items(item) to num-disp
        perform 20-check
        display num-disp " --> " result
    end-perform.
    stop run.
    
20-check.
    if num-too-small
        move "Number too small" to result
        exit paragraph
    end-if.

    perform 30-count-digits.
    divide digit-counter by 2 giving digit-div remainder digit-mod.
    if is-even
        move "Even number of digits" to result
        exit paragraph
    end-if.
    
    
    
    
        
    if digit-counter > 3
        compute multiplier rounded = 10 ** (((digit-counter - 5) / 2) + 1) 
        divide num by multiplier giving num
        divide num by 1000 giving div remainder mod
        move mod to mod-disp
    else
        move num to mod-disp
    end-if.
    move mod-disp to result.
    exit paragraph.
    
30-count-digits.
    move zeroes to digit-counter.
    move num to digit-div.
    perform with test before until no-more-digits
        divide digit-div by 10 giving digit-div remainder digit-mod
        add 1 to digit-counter
    end-perform.
    exit paragraph.
Task: Middle three digits






PHP: 


function middlethree($integer)
{
	$int 	= (int)str_replace('-','',$integer);
	$length = strlen($int);

	if(is_int($int))
	{
		if($length >= 3)
		{
			if($length % 2 == 1)
			{
				$middle = floor($length / 2) - 1;
				return substr($int,$middle, 3);
			}
			else
			{
				return 'The value must contain an odd amount of digits...';	
			}
		}
		else
		{
			return 'The value must contain at least three digits...';	
		}
	}
	else
	{
		return 'The value does not appear to be an integer...';
	}
}

$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);

foreach($numbers as $nums)
{
	echo $nums.' : '.middlethree($nums). '<br>';
}
Task: Middle three digits






PHP: 


function middlethree($integer)
{
	$int 	= (int)str_replace('-','',$integer);
	$length = strlen($int);

	if(is_int($int))
	{
		if($length >= 3)
		{
			if($length % 2 == 1)
			{
				$middle = floor($length / 2) - 1;
				return substr($int,$middle, 3);
			}
			else
			{
				return 'The value must contain an odd amount of digits...';	
			}
		}
		else
		{
			return 'The value must contain at least three digits...';	
		}
	}
	else
	{
		return 'The value does not appear to be an integer...';
	}
}

$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);

foreach($numbers as $nums)
{
	echo $nums.' : '.middlethree($nums). '<br>';
}






Ada: with Ada.Text_IO;

procedure Middle_Three_Digits is

   Impossible: exception;

   function Middle_String(I: Integer; Middle_Size: Positive) return String is
      S: constant String := Integer'Image(I);
      First: Natural := S'First;
      Full_Size, Border: Natural;
   begin
      while S(First) not in '0' .. '9' loop 
         First := First + 1;
      end loop;
      Full_Size := S'Last-First+1;
      if (Full_Size < Middle_Size) or (Full_Size mod 2 = 0) then
         raise Impossible;
      else
         Border := (Full_Size - Middle_Size)/2;
         return S(First+Border .. First+Border+Middle_Size-1);
      end if;
   end Middle_String;

   Inputs: array(Positive range <>) of Integer :=
     (123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345,
      1, 2, -1, -10, 2002, -2002, 0);
   Error_Message: constant String := "number of digits must be >= 3 and odd";

   package IIO is new Ada.Text_IO.Integer_IO(Integer);

begin
   for I in Inputs'Range loop
      IIO.Put(Inputs(I), Width => 9);
      Ada.Text_IO.Put(": ");
      begin
         Ada.Text_IO.Put(Middle_String(Inputs(I), 3));
      exception
         when Impossible => Ada.Text_IO.Put("****" & Error_Message & "****");
      end;
      Ada.Text_IO.New_Line;
   end loop;

end Middle_Three_Digits;
Task: Range expansion



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

class Program
{
    static void Main(string[] args)
    {
        var rangeString = "-6,-3--1,3-5,7-11,14,15,17-20";
        var matches = Regex.Matches(rangeString, @"(?<f>-?\d+)-(?
-?\d+)|(-?\d+)");
        var values = new List<string>();

        foreach (var m in matches.OfType<Match>())
        {
            if (m.Groups[1].Success)
            {
                values.Add(m.Value);
                continue;
            }

            var start = Convert.ToInt32(m.Groups["f"].Value);
            var end = Convert.ToInt32(m.Groups["s"].Value) + 1;

            values.AddRange(Enumerable.Range(start, end - start).Select(v => v.ToString()));
        }

        Console.WriteLine(string.Join(", ", values));
    }
}









Ada: with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Range_Expansion is
   type Sequence is array (Positive range <>) of Integer;
   function Expand (Text : String) return Sequence is
      To    : Integer := Text'First;
      Count : Natural := 0;
      Low   : Integer;
      function Get return Integer is
         From : Integer := To;
      begin
         if Text (To) = '-' then
            To := To + 1;
         end if;
         while To <= Text'Last loop
            case Text (To) is
               when ',' | '-' => exit;
               when others => To := To + 1;
            end case;
         end loop;
         return Integer'Value (Text (From..To - 1));
      end Get;
   begin
      while To <= Text'Last loop 
         Low := Get;
         if To > Text'Last or else Text (To) = ',' then
            Count := Count + 1;
         else
            To := To + 1;
            Count := Count + Get - Low + 1;
         end if;
         To := To + 1;
      end loop;
      return Result : Sequence (1..Count) do
         Count := 0;
         To := Text'First;
         while To <= Text'Last loop 
            Low := Get;
            if To > Text'Last or else Text (To) = ',' then
               Count := Count + 1;
               Result (Count) := Low;
            else
               To := To + 1;
               for Item in Low..Get loop
                  Count := Count + 1;
                  Result (Count) := Item;
               end loop;
            end if;
            To := To + 1;
         end loop;
      end return;
   end Expand;
   procedure Put (S : Sequence) is
      First : Boolean := True;
   begin
      for I in S'Range loop
         if First then
            First := False;
         else
            Put (',');
         end if;
         Put (Integer'Image (S (I)));
      end loop;
   end Put;
begin
   Put (Expand ("-6,-3
end Test_Range_Expansion;
Task: Range expansion

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



int get_list(const char *, char **);
int get_rnge(const char *, char **);


void add_number(int x);
int add_range(int x, int y);

#define skip_space while(isspace(*s)) s++
#define get_number(x, s, e) (x = strtol(s, e, 10), *e != s)
int get_list(const char *s, char **e)
{
	int x;
	while (1) {
		skip_space;
		if (!get_rnge(s, e) && !get_number(x, s, e)) break;
		s = *e;

		skip_space;
		if ((*s) == '\0') { putchar('\n'); return 1; }
		if ((*s) == ',')  { s++; continue; }
		break;
	}
	*(const char **)e = s;
	printf("\nSyntax error at %s\n", s);
	return 0;
}

int get_rnge(const char *s, char **e)
{
	int x, y;
	char *ee;
	if (!get_number(x, s, &ee)) return 0;
	s = ee;

	skip_space;
	if (*s != '-') {
		*(const char **)e = s;
		return 0;
	}
	s++;
	if(!get_number(y, s, e)) return 0;
	return add_range(x, y);
}

void add_number(int x)
{
	printf("%d ", x);
}

int add_range(int x, int y)
{
	if (y <= x) return 0;
	while (x <= y) printf("%d ", x++);
	return 1;
}

int main()
{
	char *end;

	
	if (get_list("-6,-3--1,3-5,7-11,14,15,17-20", &end)) puts("Ok");

	
	get_list("-6 -3--1,3-5,7-11,14,15,17-20", &end);

	return 0;
}











Ada: with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Range_Expansion is
   type Sequence is array (Positive range <>) of Integer;
   function Expand (Text : String) return Sequence is
      To    : Integer := Text'First;
      Count : Natural := 0;
      Low   : Integer;
      function Get return Integer is
         From : Integer := To;
      begin
         if Text (To) = '-' then
            To := To + 1;
         end if;
         while To <= Text'Last loop
            case Text (To) is
               when ',' | '-' => exit;
               when others => To := To + 1;
            end case;
         end loop;
         return Integer'Value (Text (From..To - 1));
      end Get;
   begin
      while To <= Text'Last loop 
         Low := Get;
         if To > Text'Last or else Text (To) = ',' then
            Count := Count + 1;
         else
            To := To + 1;
            Count := Count + Get - Low + 1;
         end if;
         To := To + 1;
      end loop;
      return Result : Sequence (1..Count) do
         Count := 0;
         To := Text'First;
         while To <= Text'Last loop 
            Low := Get;
            if To > Text'Last or else Text (To) = ',' then
               Count := Count + 1;
               Result (Count) := Low;
            else
               To := To + 1;
               for Item in Low..Get loop
                  Count := Count + 1;
                  Result (Count) := Item;
               end loop;
            end if;
            To := To + 1;
         end loop;
      end return;
   end Expand;
   procedure Put (S : Sequence) is
      First : Boolean := True;
   begin
      for I in S'Range loop
         if First then
            First := False;
         else
            Put (',');
         end if;
         Put (Integer'Image (S (I)));
      end loop;
   end Put;
begin
   Put (Expand ("-6,-3
end Test_Range_Expansion;
Task: Range expansion







Python: def rangeexpand(txt):
    lst = []
    for r in txt.split(','):
        if '-' in r[1:]:
            r0, r1 = r[1:].split('-', 1)
            lst += range(int(r[0] + r0), int(r1) + 1)
        else:
            lst.append(int(r))
    return lst

print(rangeexpand('-6,-3--1,3-5,7-11,14,15,17-20'))





Ada: with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Range_Expansion is
   type Sequence is array (Positive range <>) of Integer;
   function Expand (Text : String) return Sequence is
      To    : Integer := Text'First;
      Count : Natural := 0;
      Low   : Integer;
      function Get return Integer is
         From : Integer := To;
      begin
         if Text (To) = '-' then
            To := To + 1;
         end if;
         while To <= Text'Last loop
            case Text (To) is
               when ',' | '-' => exit;
               when others => To := To + 1;
            end case;
         end loop;
         return Integer'Value (Text (From..To - 1));
      end Get;
   begin
      while To <= Text'Last loop 
         Low := Get;
         if To > Text'Last or else Text (To) = ',' then
            Count := Count + 1;
         else
            To := To + 1;
            Count := Count + Get - Low + 1;
         end if;
         To := To + 1;
      end loop;
      return Result : Sequence (1..Count) do
         Count := 0;
         To := Text'First;
         while To <= Text'Last loop 
            Low := Get;
            if To > Text'Last or else Text (To) = ',' then
               Count := Count + 1;
               Result (Count) := Low;
            else
               To := To + 1;
               for Item in Low..Get loop
                  Count := Count + 1;
                  Result (Count) := Item;
               end loop;
            end if;
            To := To + 1;
         end loop;
      end return;
   end Expand;
   procedure Put (S : Sequence) is
      First : Boolean := True;
   begin
      for I in S'Range loop
         if First then
            First := False;
         else
            Put (',');
         end if;
         Put (Integer'Image (S (I)));
      end loop;
   end Put;
begin
   Put (Expand ("-6,-3
end Test_Range_Expansion;
Task: Range expansion

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



int get_list(const char *, char **);
int get_rnge(const char *, char **);


void add_number(int x);
int add_range(int x, int y);

#define skip_space while(isspace(*s)) s++
#define get_number(x, s, e) (x = strtol(s, e, 10), *e != s)
int get_list(const char *s, char **e)
{
	int x;
	while (1) {
		skip_space;
		if (!get_rnge(s, e) && !get_number(x, s, e)) break;
		s = *e;

		skip_space;
		if ((*s) == '\0') { putchar('\n'); return 1; }
		if ((*s) == ',')  { s++; continue; }
		break;
	}
	*(const char **)e = s;
	printf("\nSyntax error at %s\n", s);
	return 0;
}

int get_rnge(const char *s, char **e)
{
	int x, y;
	char *ee;
	if (!get_number(x, s, &ee)) return 0;
	s = ee;

	skip_space;
	if (*s != '-') {
		*(const char **)e = s;
		return 0;
	}
	s++;
	if(!get_number(y, s, e)) return 0;
	return add_range(x, y);
}

void add_number(int x)
{
	printf("%d ", x);
}

int add_range(int x, int y)
{
	if (y <= x) return 0;
	while (x <= y) printf("%d ", x++);
	return 1;
}

int main()
{
	char *end;

	
	if (get_list("-6,-3--1,3-5,7-11,14,15,17-20", &end)) puts("Ok");

	
	get_list("-6 -3--1,3-5,7-11,14,15,17-20", &end);

	return 0;
}
Task: Range expansion



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

class Program
{
    static void Main(string[] args)
    {
        var rangeString = "-6,-3--1,3-5,7-11,14,15,17-20";
        var matches = Regex.Matches(rangeString, @"(?<f>-?\d+)-(?
-?\d+)|(-?\d+)");
        var values = new List<string>();

        foreach (var m in matches.OfType<Match>())
        {
            if (m.Groups[1].Success)
            {
                values.Add(m.Value);
                continue;
            }

            var start = Convert.ToInt32(m.Groups["f"].Value);
            var end = Convert.ToInt32(m.Groups["s"].Value) + 1;

            values.AddRange(Enumerable.Range(start, end - start).Select(v => v.ToString()));
        }

        Console.WriteLine(string.Join(", ", values));
    }
}
Task: Range expansion


C++: #include <iostream>
#include <sstream>
#include <iterator>
#include <climits>
#include <deque>








template<typename OutIter>
 bool parse_number_list_with_ranges(std::istream& is, OutIter out)
{
  int number;
  
  while (is >> number)
  {
    *out++ = number;

    char c;
    if (is >> c)
      switch(c)
      {
      case ',':
        continue;
      case '-':
        {
          int number2;
          if (is >> number2)
          {
            if (number2 < number)
              return false;
            while (number < number2)
              *out++ = ++number;
            char c2;
            if (is >> c2)
              if (c2 == ',')
                continue;
              else
                return false;
            else
              return is.eof();
          }
          else
            return false;
        }
      default:
        return is.eof();
      }
    else
      return is.eof();
  }
  
  
  return false;
}

int main()
{
  std::istringstream example("-6,-3--1,3-5,7-11,14,15,17-20");
  std::deque<int> v;
  bool success = parse_number_list_with_ranges(example, std::back_inserter(v));
  if (success)
  {
    std::copy(v.begin(), v.end()-1,
              std::ostream_iterator<int>(std::cout, ","));
    std::cout << v.back() << "\n";
  }
  else
    std::cout << "an error occured.";
}
Task: Range expansion





Java: import java.util.*;

class RangeExpander implements Iterator<Integer>, Iterable<Integer> {

    private static final Pattern TOKEN_PATTERN = Pattern.compile("([+-]?\\d+)-([+-]?\\d+)");

    private final Iterator<String> tokensIterator;

    private boolean inRange;
    private int upperRangeEndpoint;
    private int nextRangeValue;

    public RangeExpander(String range) {
        String[] tokens = range.split("\\s*,\\s*");
        this.tokensIterator = Arrays.asList(tokens).iterator();
    }

    @Override
    public boolean hasNext() {
        return hasNextRangeValue() || this.tokensIterator.hasNext();
    }

    private boolean hasNextRangeValue() {
        return this.inRange && this.nextRangeValue <= this.upperRangeEndpoint;
    }

    @Override
    public Integer next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }

        if (hasNextRangeValue()) {
            return this.nextRangeValue++;
        }

        String token = this.tokensIterator.next();

        Matcher matcher = TOKEN_PATTERN.matcher(token);
        if (matcher.find()) {
            this.inRange = true;
            this.upperRangeEndpoint = Integer.valueOf(matcher.group(2));
            this.nextRangeValue = Integer.valueOf(matcher.group(1));
            return this.nextRangeValue++;
        }

        this.inRange = false;
        return Integer.valueOf(token);
    }

    @Override
    public Iterator<Integer> iterator() {
        return this;
    }

}

class RangeExpanderTest {
    public static void main(String[] args) {
        RangeExpander re = new RangeExpander("-6,-3--1,3-5,7-11,14,15,17-20");
        for (int i : re) {
            System.out.print(i + " ");
        }
    }
}
Task: Range expansion







Python: def rangeexpand(txt):
    lst = []
    for r in txt.split(','):
        if '-' in r[1:]:
            r0, r1 = r[1:].split('-', 1)
            lst += range(int(r[0] + r0), int(r1) + 1)
        else:
            lst.append(int(r))
    return lst

print(rangeexpand('-6,-3--1,3-5,7-11,14,15,17-20'))
Task: Range expansion




Go: package main

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

const input = "-6,-3--1,3-5,7-11,14,15,17-20"

func main() {
    fmt.Println("range:", input)
    var r []int
    var last int
    for _, part := range strings.Split(input, ",") {
        if i := strings.Index(part[1:], "-"); i == -1 {
            n, err := strconv.Atoi(part)
            if err != nil {
                fmt.Println(err)
                return
            }
            if len(r) > 0 {
                if last == n {
                    fmt.Println("duplicate value:", n)
                    return
                } else if last > n {
                    fmt.Println("values not ordered:", last, ">", n)
                    return
                }
            }
            r = append(r, n)
            last = n
        } else {
            n1, err := strconv.Atoi(part[:i+1])
            if err != nil {
                fmt.Println(err)
                return
            }
            n2, err := strconv.Atoi(part[i+2:])
            if err != nil {
                fmt.Println(err)
                return
            }
            if n2 < n1+2 {
                fmt.Println("invalid range:", part)
                return
            }
            if len(r) > 0 {
                if last == n1 {
                    fmt.Println("duplicate value:", n1)
                    return
                } else if last > n1 {
                    fmt.Println("values not ordered:", last, ">", n1)
                    return
                }
            }
            for i = n1; i <= n2; i++ {
                r = append(r, i)
            }
            last = n2
        }
    }
    fmt.Println("expanded:", r)
}
Task: Range expansion







Python: def rangeexpand(txt):
    lst = []
    for r in txt.split(','):
        if '-' in r[1:]:
            r0, r1 = r[1:].split('-', 1)
            lst += range(int(r[0] + r0), int(r1) + 1)
        else:
            lst.append(int(r))
    return lst

print(rangeexpand('-6,-3--1,3-5,7-11,14,15,17-20'))



COBOL:        >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. expand-range.

DATA DIVISION.
WORKING-STORAGE SECTION.
01  comma-pos                           PIC 99 COMP VALUE 1.
01  dash-pos                            PIC 99 COMP.
01  end-num                             PIC S9(3).
01  Max-Part-Len                        CONSTANT 10.
01  num                                 PIC S9(3).
01  edited-num                          PIC -(3)9.
01  part                                PIC X(10).

01  part-flag                           PIC X.
    88 last-part                        VALUE "Y".

01  range-str                           PIC X(80).
01  Range-Str-Len                       CONSTANT 80.
01  start-pos                           PIC 99 COMP.
01  start-num                           PIC S9(3).

PROCEDURE DIVISION.
    ACCEPT range-str

    PERFORM WITH TEST AFTER UNTIL last-part
        UNSTRING range-str DELIMITED BY "," INTO part WITH POINTER comma-pos
        PERFORM check-if-last

        PERFORM find-range-dash
            
        IF dash-pos > Max-Part-Len
            PERFORM display-num
        ELSE
            PERFORM display-range
        END-IF
    END-PERFORM

    DISPLAY SPACES
    
    GOBACK
    .
check-if-last SECTION.
    IF comma-pos > Range-Str-Len
        SET last-part TO TRUE
    END-IF
    .
find-range-dash SECTION.
    IF part (1:1) <> "-"
        MOVE 1 TO start-pos
    ELSE
        MOVE 2 TO start-pos
    END-IF

    MOVE 1 TO dash-pos
    INSPECT part (start-pos:) TALLYING dash-pos FOR CHARACTERS BEFORE "-"
    COMPUTE dash-pos = dash-pos + start-pos - 1
    .
display-num SECTION.
    MOVE part TO edited-num
    CALL "display-edited-num" USING CONTENT part-flag, edited-num
    .
display-range SECTION.
    MOVE part (1:dash-pos - 1) TO start-num
    MOVE part (dash-pos + 1:) TO end-num

    PERFORM VARYING num FROM start-num BY 1 UNTIL num = end-num
        MOVE num TO edited-num
        CALL "display-edited-num" USING CONTENT "N", edited-num
    END-PERFORM

    MOVE end-num TO edited-num
    CALL "display-edited-num" USING CONTENT part-flag, edited-num
    .
END PROGRAM expand-range.


IDENTIFICATION DIVISION.
PROGRAM-ID. display-edited-num.

DATA DIVISION.
LINKAGE SECTION.
01  hide-comma-flag                     PIC X.
    88  hide-comma                      VALUE "Y".
01  edited-num                          PIC -(3)9.

PROCEDURE DIVISION USING hide-comma-flag, edited-num.
    DISPLAY FUNCTION TRIM(edited-num) NO ADVANCING
    IF NOT hide-comma
        DISPLAY ", " NO ADVANCING
    END-IF
    .
END PROGRAM display-edited-num.
Task: Range expansion






PHP: function rangex($str) {
    $lst = array();
    foreach (explode(',', $str) as $e) {
        if (strpos($e, '-', 1) !== FALSE) {
            list($a, $b) = explode('-', substr($e, 1), 2);
            $lst = array_merge($lst, range($e[0] . $a, $b));
        } else {
            $lst[] = (int) $e;
        }
    }
    return $lst;
}