WeixiangYan/CodeTransOcean huggingface dataset:
Task: Compare length of two strings







Python: A = 'I am string'
B = 'I am string too'

if len(A) > len(B):
    print('"' + A + '"', 'has length', len(A), 'and is the longest of the two strings')
    print('"' + B + '"', 'has length', len(B), 'and is the shortest of the two strings')
elif len(A) < len(B):
    print('"' + B + '"', 'has length', len(B), 'and is the longest of the two strings')
    print('"' + A + '"', 'has length', len(A), 'and is the shortest of the two strings')
else:
    print('"' + A + '"', 'has length', len(A), 'and it is as long as the second string')
    print('"' + B + '"', 'has length', len(B), 'and it is as long as the second string')
Task: Compare length of two strings




Go: package main

import (
	"fmt"
	"os"
	"sort"
)

func main() {
	
	if len(os.Args) == 1 {
		compareStrings("abcd", "123456789", "abcdef", "1234567")
	} else {
		
		strings := os.Args[1:]
		compareStrings(strings...)
	}
}


func compareStrings(strings ...string) {
	
	
	sort.SliceStable(strings, func(i, j int) bool {
		return len(strings[i]) > len(strings[j])
	})

	for _, s := range strings {
		fmt.Printf("%d: %s\n", len(s), s)
	}
}
Task: Compare length of two strings



C#: using System;
using System.Collections.Generic;

namespace example
{
    class Program
    {
        static void Main(string[] args)
        {
            var strings = new string[] { "abcd", "123456789", "abcdef", "1234567" };
            compareAndReportStringsLength(strings);
        }

        private static void compareAndReportStringsLength(string[] strings)
        {
            if (strings.Length > 0)
            {
                char Q = '"';
                string hasLength = " has length ";
                string predicateMax = " and is the longest string";
                string predicateMin = " and is the shortest string";
                string predicateAve = " and is neither the longest nor the shortest string";
                string predicate;

                (int, int)[] li = new (int, int)[strings.Length];
                for (int i = 0; i < strings.Length; i++)
                    li[i] = (strings[i].Length, i);
                Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1);
                int maxLength = li[0].Item1;
                int minLength = li[strings.Length - 1].Item1;

                for (int i = 0; i < strings.Length; i++)
                {
                    int length = li[i].Item1;
                    string str = strings[li[i].Item2];
                    if (length == maxLength)
                        predicate = predicateMax;
                    else if (length == minLength)
                        predicate = predicateMin;
                    else
                        predicate = predicateAve;
                    Console.WriteLine(Q + str + Q + hasLength + length + predicate);
                }
            }
        }

    }
}








Fortran: program demo_sort_indexed
implicit none

   call print_sorted_by_length( [character(len=20) :: "shorter","longer"] )
   call print_sorted_by_length( [character(len=20) :: "abcd","123456789","abcdef","1234567"] )
   call print_sorted_by_length( [character(len=20) :: 'the','quick','brown','fox','jumps','over','the','lazy','dog'])

contains

subroutine print_sorted_by_length(list)
character(len=*) :: list(:)
integer :: i

   list(sort_int(len_trim(list)))=list 
   write(*,'(i9,1x,a)')(len_trim(list(i)), list(i),i=size(list),1,-1)
   write(*,*)

end subroutine print_sorted_by_length

function sort_int(input) result(counts) 
integer :: input(:), counts(size(input)), i
   counts=[(count(input(i) > input)+count(input(i) == input(:i)),i=1, size(input) )]
end function sort_int

end program demo_sort_indexed
Task: Compare length of two strings


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

using namespace std;

bool cmp(const string& a, const string& b)
{
    return b.length() < a.length(); 
}

void compareAndReportStringsLength(list<string> listOfStrings)
{
    if (!listOfStrings.empty())
    {
        char Q = '"';
        string has_length(" has length ");
        string predicate_max(" and is the longest string");
        string predicate_min(" and is the shortest string");
        string predicate_ave(" and is neither the longest nor the shortest string");

        list<string> ls(listOfStrings); 
        ls.sort(cmp);
        int max = ls.front().length();
        int min = ls.back().length();

        for (list<string>::iterator s = ls.begin(); s != ls.end(); s++)
        {
            int length = s->length();
            string* predicate;
            if (length == max)
                predicate = &predicate_max;
            else if (length == min)
                predicate = &predicate_min;
            else
                predicate = &predicate_ave;

            cout << Q << *s << Q << has_length << length << *predicate << endl;
        }
    }
}

int main(int argc, char* argv[])
{
    list<string> listOfStrings{ "abcd", "123456789", "abcdef", "1234567" };
    compareAndReportStringsLength(listOfStrings);

    return EXIT_SUCCESS;
}









Fortran: program demo_sort_indexed
implicit none

   call print_sorted_by_length( [character(len=20) :: "shorter","longer"] )
   call print_sorted_by_length( [character(len=20) :: "abcd","123456789","abcdef","1234567"] )
   call print_sorted_by_length( [character(len=20) :: 'the','quick','brown','fox','jumps','over','the','lazy','dog'])

contains

subroutine print_sorted_by_length(list)
character(len=*) :: list(:)
integer :: i

   list(sort_int(len_trim(list)))=list 
   write(*,'(i9,1x,a)')(len_trim(list(i)), list(i),i=size(list),1,-1)
   write(*,*)

end subroutine print_sorted_by_length

function sort_int(input) result(counts) 
integer :: input(:), counts(size(input)), i
   counts=[(count(input(i) > input)+count(input(i) == input(:i)),i=1, size(input) )]
end function sort_int

end program demo_sort_indexed
Task: Compare length of two strings

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

int cmp(const int* a, const int* b)
{
    return *b - *a; 
}

void compareAndReportStringsLength(const char* strings[], const int n)
{
    if (n > 0)
    {
        char* has_length = "has length";
        char* predicate_max = "and is the longest string";
        char* predicate_min = "and is the shortest string";
        char* predicate_ave = "and is neither the longest nor the shortest string";

        int* si = malloc(2 * n * sizeof(int));
        if (si != NULL)
        {
            for (int i = 0; i < n; i++)
            {
                si[2 * i] = strlen(strings[i]);
                si[2 * i + 1] = i;
            }
            qsort(si, n, 2 * sizeof(int), cmp);

            int max = si[0];
            int min = si[2 * (n - 1)];

            for (int i = 0; i < n; i++)
            {
                int length = si[2 * i];
                char* string = strings[si[2 * i + 1]];
                char* predicate;
                if (length == max)
                    predicate = predicate_max;
                else if (length == min)
                    predicate = predicate_min;
                else
                    predicate = predicate_ave;
                printf("\"%s\" %s %d %s\n",
                    string, has_length, length, predicate);
            }

            free(si);
        }
        else
        {
            fputs("unable allocate memory buffer", stderr);
        }
    }
}

int main(int argc, char* argv[])
{
    char* list[] = { "abcd", "123456789", "abcdef", "1234567" };

    compareAndReportStringsLength(list, 4);

    return EXIT_SUCCESS;
}










Fortran: program demo_sort_indexed
implicit none

   call print_sorted_by_length( [character(len=20) :: "shorter","longer"] )
   call print_sorted_by_length( [character(len=20) :: "abcd","123456789","abcdef","1234567"] )
   call print_sorted_by_length( [character(len=20) :: 'the','quick','brown','fox','jumps','over','the','lazy','dog'])

contains

subroutine print_sorted_by_length(list)
character(len=*) :: list(:)
integer :: i

   list(sort_int(len_trim(list)))=list 
   write(*,'(i9,1x,a)')(len_trim(list(i)), list(i),i=size(list),1,-1)
   write(*,*)

end subroutine print_sorted_by_length

function sort_int(input) result(counts) 
integer :: input(:), counts(size(input)), i
   counts=[(count(input(i) > input)+count(input(i) == input(:i)),i=1, size(input) )]
end function sort_int

end program demo_sort_indexed
Task: Compare length of two strings





Java: package stringlensort;

import java.io.PrintStream;
import java.util.Arrays;
import java.util.Comparator;

public class ReportStringLengths {

    public static void main(String[] args) {
        String[] list = {"abcd", "123456789", "abcdef", "1234567"};
        String[] strings = args.length > 0 ? args : list;

        compareAndReportStringsLength(strings);
    }

        
    public static void compareAndReportStringsLength(String[] strings) {
        compareAndReportStringsLength(strings, System.out);
    }

    
    public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {
        if (strings.length > 0) {
            strings = strings.clone();
            final String QUOTE = "\"";
            Arrays.sort(strings, Comparator.comparing(String::length));
            int min = strings[0].length();
            int max = strings[strings.length - 1].length();
            for (int i = strings.length - 1; i >= 0; i--) {
                int length = strings[i].length();
                String predicate;
                if (length == max) {
                    predicate = "is the longest string";
                } else if (length == min) {
                    predicate = "is the shortest string";
                } else {
                    predicate = "is neither the longest nor the shortest string";
                }
                
                stream.println(QUOTE + strings[i] + QUOTE + " has length " + length
                        + " and " + predicate);
            }
        }
    }
}






Fortran: program demo_sort_indexed
implicit none

   call print_sorted_by_length( [character(len=20) :: "shorter","longer"] )
   call print_sorted_by_length( [character(len=20) :: "abcd","123456789","abcdef","1234567"] )
   call print_sorted_by_length( [character(len=20) :: 'the','quick','brown','fox','jumps','over','the','lazy','dog'])

contains

subroutine print_sorted_by_length(list)
character(len=*) :: list(:)
integer :: i

   list(sort_int(len_trim(list)))=list 
   write(*,'(i9,1x,a)')(len_trim(list(i)), list(i),i=size(list),1,-1)
   write(*,*)

end subroutine print_sorted_by_length

function sort_int(input) result(counts) 
integer :: input(:), counts(size(input)), i
   counts=[(count(input(i) > input)+count(input(i) == input(:i)),i=1, size(input) )]
end function sort_int

end program demo_sort_indexed
Task: Compare length of two strings







Python: A = 'I am string'
B = 'I am string too'

if len(A) > len(B):
    print('"' + A + '"', 'has length', len(A), 'and is the longest of the two strings')
    print('"' + B + '"', 'has length', len(B), 'and is the shortest of the two strings')
elif len(A) < len(B):
    print('"' + B + '"', 'has length', len(B), 'and is the longest of the two strings')
    print('"' + A + '"', 'has length', len(A), 'and is the shortest of the two strings')
else:
    print('"' + A + '"', 'has length', len(A), 'and it is as long as the second string')
    print('"' + B + '"', 'has length', len(B), 'and it is as long as the second string')




Fortran: program demo_sort_indexed
implicit none

   call print_sorted_by_length( [character(len=20) :: "shorter","longer"] )
   call print_sorted_by_length( [character(len=20) :: "abcd","123456789","abcdef","1234567"] )
   call print_sorted_by_length( [character(len=20) :: 'the','quick','brown','fox','jumps','over','the','lazy','dog'])

contains

subroutine print_sorted_by_length(list)
character(len=*) :: list(:)
integer :: i

   list(sort_int(len_trim(list)))=list 
   write(*,'(i9,1x,a)')(len_trim(list(i)), list(i),i=size(list),1,-1)
   write(*,*)

end subroutine print_sorted_by_length

function sort_int(input) result(counts) 
integer :: input(:), counts(size(input)), i
   counts=[(count(input(i) > input)+count(input(i) == input(:i)),i=1, size(input) )]
end function sort_int

end program demo_sort_indexed
Task: Compare length of two strings






PHP: <?php


function retrieveStrings()
{
    if (isset($_POST['input'])) {
        $strings = explode("\n", $_POST['input']);
    } else {
        $strings = ['abcd', '123456789', 'abcdef', '1234567'];
    }
    return $strings;
}


function setInput()
{
    echo join("\n", retrieveStrings());
}


function setOutput()
{
    $strings = retrieveStrings();


    $strings = array_map('trim', $strings);
    $strings = array_filter($strings);

    if (!empty($strings)) {
        usort($strings, function ($a, $b) {
            return strlen($b) - strlen($a);
        });
        $max_len = strlen($strings[0]);
        $min_len = strlen($strings[count($strings) - 1]);
        foreach ($strings as $s) {
            $length = strlen($s);
            if ($length == $max_len) {
                $predicate = "is the longest string";
            } elseif ($length == $min_len) {
                $predicate = "is the shortest string";
            } else {
                $predicate = "is neither the longest nor the shortest string";
            }
            echo "$s has length $length and $predicate\n";
        }
    }
}

?>


<!DOCTYPE html>
<html lang="en">

<head>
    <style>
        div {
            margin-top: 4ch;
            margin-bottom: 4ch;
        }

        label {
            display: block;
            margin-bottom: 1ch;
        }

        textarea {
            display: block;
        }

        input {
            display: block;
            margin-top: 4ch;
            margin-bottom: 4ch;
        }
    </style>
</head>


<body>
    <main>
        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method="post" accept-charset="utf-8">
            <div>
                <label for="input">Input:
                </label>
                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>
                </label>
            </div>
            <input type="submit" value="press to compare strings">
            </input>
            <div>
                <label for="Output">Output:
                </label>
                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>
            </div>
        </form>
    </main>
</body>

</html>





Fortran: program demo_sort_indexed
implicit none

   call print_sorted_by_length( [character(len=20) :: "shorter","longer"] )
   call print_sorted_by_length( [character(len=20) :: "abcd","123456789","abcdef","1234567"] )
   call print_sorted_by_length( [character(len=20) :: 'the','quick','brown','fox','jumps','over','the','lazy','dog'])

contains

subroutine print_sorted_by_length(list)
character(len=*) :: list(:)
integer :: i

   list(sort_int(len_trim(list)))=list 
   write(*,'(i9,1x,a)')(len_trim(list(i)), list(i),i=size(list),1,-1)
   write(*,*)

end subroutine print_sorted_by_length

function sort_int(input) result(counts) 
integer :: input(:), counts(size(input)), i
   counts=[(count(input(i) > input)+count(input(i) == input(:i)),i=1, size(input) )]
end function sort_int

end program demo_sort_indexed
Task: Compare length of two strings






PHP: <?php


function retrieveStrings()
{
    if (isset($_POST['input'])) {
        $strings = explode("\n", $_POST['input']);
    } else {
        $strings = ['abcd', '123456789', 'abcdef', '1234567'];
    }
    return $strings;
}


function setInput()
{
    echo join("\n", retrieveStrings());
}


function setOutput()
{
    $strings = retrieveStrings();


    $strings = array_map('trim', $strings);
    $strings = array_filter($strings);

    if (!empty($strings)) {
        usort($strings, function ($a, $b) {
            return strlen($b) - strlen($a);
        });
        $max_len = strlen($strings[0]);
        $min_len = strlen($strings[count($strings) - 1]);
        foreach ($strings as $s) {
            $length = strlen($s);
            if ($length == $max_len) {
                $predicate = "is the longest string";
            } elseif ($length == $min_len) {
                $predicate = "is the shortest string";
            } else {
                $predicate = "is neither the longest nor the shortest string";
            }
            echo "$s has length $length and $predicate\n";
        }
    }
}

?>


<!DOCTYPE html>
<html lang="en">

<head>
    <style>
        div {
            margin-top: 4ch;
            margin-bottom: 4ch;
        }

        label {
            display: block;
            margin-bottom: 1ch;
        }

        textarea {
            display: block;
        }

        input {
            display: block;
            margin-top: 4ch;
            margin-bottom: 4ch;
        }
    </style>
</head>


<body>
    <main>
        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method="post" accept-charset="utf-8">
            <div>
                <label for="input">Input:
                </label>
                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>
                </label>
            </div>
            <input type="submit" value="press to compare strings">
            </input>
            <div>
                <label for="Output">Output:
                </label>
                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>
            </div>
        </form>
    </main>
</body>

</html>
Task: Compare length of two strings






PHP: <?php


function retrieveStrings()
{
    if (isset($_POST['input'])) {
        $strings = explode("\n", $_POST['input']);
    } else {
        $strings = ['abcd', '123456789', 'abcdef', '1234567'];
    }
    return $strings;
}


function setInput()
{
    echo join("\n", retrieveStrings());
}


function setOutput()
{
    $strings = retrieveStrings();


    $strings = array_map('trim', $strings);
    $strings = array_filter($strings);

    if (!empty($strings)) {
        usort($strings, function ($a, $b) {
            return strlen($b) - strlen($a);
        });
        $max_len = strlen($strings[0]);
        $min_len = strlen($strings[count($strings) - 1]);
        foreach ($strings as $s) {
            $length = strlen($s);
            if ($length == $max_len) {
                $predicate = "is the longest string";
            } elseif ($length == $min_len) {
                $predicate = "is the shortest string";
            } else {
                $predicate = "is neither the longest nor the shortest string";
            }
            echo "$s has length $length and $predicate\n";
        }
    }
}

?>


<!DOCTYPE html>
<html lang="en">

<head>
    <style>
        div {
            margin-top: 4ch;
            margin-bottom: 4ch;
        }

        label {
            display: block;
            margin-bottom: 1ch;
        }

        textarea {
            display: block;
        }

        input {
            display: block;
            margin-top: 4ch;
            margin-bottom: 4ch;
        }
    </style>
</head>


<body>
    <main>
        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method="post" accept-charset="utf-8">
            <div>
                <label for="input">Input:
                </label>
                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>
                </label>
            </div>
            <input type="submit" value="press to compare strings">
            </input>
            <div>
                <label for="Output">Output:
                </label>
                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>
            </div>
        </form>
    </main>
</body>

</html>






Ada: with ada.command_line, ada.containers.indefinite_vectors, ada.text_io;
procedure compare_lengths is
   package string_vector is new ada.containers.indefinite_vectors
     (index_type => Positive, element_type => String);

   function "<" (left, right : String) return Boolean is
   begin
      return left'length > right'length;
   end "<";

   package string_vector_sorting is new string_vector.generic_sorting;
   list : string_vector.Vector;
begin
   for i in 1 .. ada.command_line.argument_count loop
      list.append (ada.command_line.argument (i));
   end loop;
   string_vector_sorting.sort (list);
   for elem of list loop
      ada.text_io.put_line (elem'length'image & ": " & elem);
   end loop;
end compare_lengths;
Task: Zig-zag matrix



C#: public static int[,] ZigZag(int n)
{
    int[,] result = new int[n, n];
    int i = 0, j = 0;
    int d = -1; 
    int start = 0, end = n * n - 1;
    do
    {
        result[i, j] = start++;
        result[n - i - 1, n - j - 1] = end--;

        i += d; j -= d;
        if (i < 0)
        {
            i++; d = -d; 
        }
        else if (j < 0)
        {
            j++; d = -d; 
        }
    } while (start < end);
    if (start == end)
        result[i, j] = start;
    return result;
}









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

procedure Test_Zig_Zag is

   type Matrix is array (Positive range <>, Positive range <>) of Natural;
   function Zig_Zag (Size : Positive) return Matrix is
      Data : Matrix (1..Size, 1..Size);
      I, J : Integer := 1;
   begin
      Data (1, 1) := 0;
      for Element in 1..Size**2 - 1 loop
         if (I + J) mod 2 = 0 then
            
            if J < Size then
               J := J + 1;
            else
               I := I + 2;
            end if;
            if I > 1 then
               I := I - 1;
            end if;
         else
            
            if I < Size then
               I := I + 1;
            else
               J := J + 2;
            end if;
            if J > 1 then
               J := J - 1;
            end if;
         end if;
         Data (I, J) := Element;
      end loop;
      return Data;
   end Zig_Zag;
   
   procedure Put (Data : Matrix) is
   begin
      for I in Data'Range (1) loop
         for J in Data'Range (2) loop
            Put (Integer'Image (Data (I, J)));
         end loop;
         New_Line;
      end loop;
   end Put;

begin
   Put (Zig_Zag (5));
end Test_Zig_Zag;
Task: Zig-zag matrix

C: #include <stdio.h>
#include <stdlib.h>
 
int main(int c, char **v)
{
	int i, j, m, n, *s;
 
	
	if (c < 2 || ((m = atoi(v[1]))) <= 0) m = 5;
 
	
	s = malloc(sizeof(int) * m * m);
 
	for (i = n = 0; i < m * 2; i++)
		for (j = (i < m) ? 0 : i-m+1; j <= i && j < m; j++)
			s[(i&1)? j*(m-1)+i : (i-j)*m+j ] = n++;
 
	for (i = 0; i < m * m; putchar((++i % m) ? ' ':'\n'))
		printf("%3d", s[i]);

	
	return 0;
}











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

procedure Test_Zig_Zag is

   type Matrix is array (Positive range <>, Positive range <>) of Natural;
   function Zig_Zag (Size : Positive) return Matrix is
      Data : Matrix (1..Size, 1..Size);
      I, J : Integer := 1;
   begin
      Data (1, 1) := 0;
      for Element in 1..Size**2 - 1 loop
         if (I + J) mod 2 = 0 then
            
            if J < Size then
               J := J + 1;
            else
               I := I + 2;
            end if;
            if I > 1 then
               I := I - 1;
            end if;
         else
            
            if I < Size then
               I := I + 1;
            else
               J := J + 2;
            end if;
            if J > 1 then
               J := J - 1;
            end if;
         end if;
         Data (I, J) := Element;
      end loop;
      return Data;
   end Zig_Zag;
   
   procedure Put (Data : Matrix) is
   begin
      for I in Data'Range (1) loop
         for J in Data'Range (2) loop
            Put (Integer'Image (Data (I, J)));
         end loop;
         New_Line;
      end loop;
   end Put;

begin
   Put (Zig_Zag (5));
end Test_Zig_Zag;