WeixiangYan/CodeTransOcean huggingface dataset:
Task: Palindrome dates





Java: import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class PalindromeDates {

    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2020, 2, 3);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        DateTimeFormatter formatterDash = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        System.out.printf("First 15 palindrome dates after 2020-02-02 are:%n");
        for ( int count = 0 ; count < 15 ; date = date.plusDays(1) ) {
            String dateFormatted = date.format(formatter);
            if ( dateFormatted.compareTo(new StringBuilder(dateFormatted).reverse().toString()) == 0 ) {
                count++;
                System.out.printf("date = %s%n", date.format(formatterDash));
            }
        }
    }

}







Ada: with Ada.Text_IO;
with Ada.Calendar.Formatting;
with Ada.Calendar.Arithmetic;

procedure Palindrome_Dates is
   Desired_Count : constant := 15;
   Start_Date    : constant String := "2020-01-01 00:00:00";

   use Ada.Calendar;

   function Is_Palindrome_Date (Date : Time) return Boolean is
      Image : String renames Formatting.Image (Date);
   begin
      return
        Image (1) = Image (10) and
        Image (2) = Image (9)  and
        Image (3) = Image (7)  and
        Image (4) = Image (6);
   end Is_Palindrome_Date;

   Date  : Ada.Calendar.Time := Formatting.Value (Start_Date);
   Count : Natural := 0;

   use type Ada.Calendar.Arithmetic.Day_Count;
begin
   loop
      if Is_Palindrome_Date (Date) then
         Ada.Text_IO.Put_Line (Formatting.Image (Date) (1 .. 10));
         Count := Count + 1;
      end if;
      exit when Count = Desired_Count;
      Date := Date + 1;
   end loop;
end Palindrome_Dates;
Task: Palindrome dates







Python: 

from datetime import datetime
from itertools import chain



def palinDay(y):
    
    s = str(y)
    r = s[::-1]
    iso = '-'.join([s, r[0:2], r[2:]])
    try:
        datetime.strptime(iso, '%Y-%m-%d')
        return [iso]
    except ValueError:
        return []




def main():
    
    palinDates = list(chain.from_iterable(
        map(palinDay, range(2021, 10000))
    ))
    for x in [
            'Count of palindromic dates [2021..9999]:',
            len(palinDates),
            '\nFirst 15:',
            '\n'.join(palinDates[0:15]),
            '\nLast 15:',
            '\n'.join(palinDates[-15:])
    ]:
        print(x)



if __name__ == '__main__':
    main()





Ada: with Ada.Text_IO;
with Ada.Calendar.Formatting;
with Ada.Calendar.Arithmetic;

procedure Palindrome_Dates is
   Desired_Count : constant := 15;
   Start_Date    : constant String := "2020-01-01 00:00:00";

   use Ada.Calendar;

   function Is_Palindrome_Date (Date : Time) return Boolean is
      Image : String renames Formatting.Image (Date);
   begin
      return
        Image (1) = Image (10) and
        Image (2) = Image (9)  and
        Image (3) = Image (7)  and
        Image (4) = Image (6);
   end Is_Palindrome_Date;

   Date  : Ada.Calendar.Time := Formatting.Value (Start_Date);
   Count : Natural := 0;

   use type Ada.Calendar.Arithmetic.Day_Count;
begin
   loop
      if Is_Palindrome_Date (Date) then
         Ada.Text_IO.Put_Line (Formatting.Image (Date) (1 .. 10));
         Count := Count + 1;
      end if;
      exit when Count = Desired_Count;
      Date := Date + 1;
   end loop;
end Palindrome_Dates;
Task: Palindrome dates








VB: dateTest = ""
mes = 0 : dia = 0 : anno = 0 : Pal = 0
total = 0
print "Siguientes 15 fechas palindrómicas al 2020-02-02:"
for anno = 2021 to 9999
	dateTest = ltrim(string(anno))
	for mes = 1 to 12
		if mes < 10 then dateTest = dateTest + "0"
		dateTest = dateTest + ltrim(string(mes))
		for dia = 1 to 31
			if mes = 2 and dia > 28 then exit for
			if (mes = 4 or mes = 6 or mes = 9 or mes = 11) and dia > 30 then exit for
			if dia < 10 then dateTest = dateTest + "0"
			dateTest = dateTest + ltrim(string(dia))
			for Pal = 1 to 4
				if mid(dateTest, Pal, 1) <> mid(dateTest, 9 - Pal, 1) then exit for
			next Pal
			if Pal = 5 then
				total += 1
				if total <= 15 then print left(dateTest,4);"-";mid(dateTest,5,2);"-";right(dateTest,2)
			end if
			if total > 15 then exit for : exit for : exit for
			dateTest = left(dateTest, 6)
		next dia
		dateTest = left(dateTest, 4)
	next mes
	dateTest = ""
next anno
end




Ada: with Ada.Text_IO;
with Ada.Calendar.Formatting;
with Ada.Calendar.Arithmetic;

procedure Palindrome_Dates is
   Desired_Count : constant := 15;
   Start_Date    : constant String := "2020-01-01 00:00:00";

   use Ada.Calendar;

   function Is_Palindrome_Date (Date : Time) return Boolean is
      Image : String renames Formatting.Image (Date);
   begin
      return
        Image (1) = Image (10) and
        Image (2) = Image (9)  and
        Image (3) = Image (7)  and
        Image (4) = Image (6);
   end Is_Palindrome_Date;

   Date  : Ada.Calendar.Time := Formatting.Value (Start_Date);
   Count : Natural := 0;

   use type Ada.Calendar.Arithmetic.Day_Count;
begin
   loop
      if Is_Palindrome_Date (Date) then
         Ada.Text_IO.Put_Line (Formatting.Image (Date) (1 .. 10));
         Count := Count + 1;
      end if;
      exit when Count = Desired_Count;
      Date := Date + 1;
   end loop;
end Palindrome_Dates;
Task: Palindrome dates

C: #include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <time.h>

bool is_palindrome(const char* str) {
    size_t n = strlen(str);
    for (size_t i = 0; i + 1 < n; ++i, --n) {
        if (str[i] != str[n - 1])
            return false;
    }
    return true;
}

int main() {
    time_t timestamp = time(0);
    const int seconds_per_day = 24*60*60;
    int count = 15;
    char str[32];
    printf("Next %d palindrome dates:\n", count);
    for (; count > 0; timestamp += seconds_per_day) {
        struct tm* ptr = gmtime(&timestamp);
        strftime(str, sizeof(str), "%Y%m%d", ptr);
        if (is_palindrome(str)) {
            strftime(str, sizeof(str), "%F", ptr);
            printf("%s\n", str);
            --count;
        }
    }
    return 0;
}
Task: Palindrome dates



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

public class Program
{
    static void Main()
    {
        foreach (var date in PalindromicDates(2021).Take(15)) WriteLine(date.ToString("yyyy-MM-dd"));
    }

    public static IEnumerable<DateTime> PalindromicDates(int startYear) {
        for (int y = startYear; ; y++) {
            int m = Reverse(y % 100);
            int d = Reverse(y / 100);
            if (IsValidDate(y, m, d, out var date)) yield return date;
        }

        int Reverse(int x) => x % 10 * 10 + x / 10;
        bool IsValidDate(int y, int m, int d, out DateTime date) => DateTime.TryParse($"{y}-{m}-{d}", out date);
    }
}
Task: Palindrome dates


C++: #include <iostream>
#include <string>
#include <boost/date_time/gregorian/gregorian.hpp>

bool is_palindrome(const std::string& str) {
    for (size_t i = 0, j = str.size(); i + 1 < j; ++i, --j) {
        if (str[i] != str[j - 1])
            return false;
    }
    return true;
}

int main() {
    using boost::gregorian::date;
    using boost::gregorian::day_clock;
    using boost::gregorian::date_duration;
    
    date today(day_clock::local_day());
    date_duration day(1);
    int count = 15;
    std::cout << "Next " << count << " palindrome dates:\n";
    for (; count > 0; today += day) {
        if (is_palindrome(to_iso_string(today))) {
            std::cout << to_iso_extended_string(today) << '\n';
            --count;
        }
    }
    return 0;
}
Task: Palindrome dates





Java: import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class PalindromeDates {

    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2020, 2, 3);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        DateTimeFormatter formatterDash = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        System.out.printf("First 15 palindrome dates after 2020-02-02 are:%n");
        for ( int count = 0 ; count < 15 ; date = date.plusDays(1) ) {
            String dateFormatted = date.format(formatter);
            if ( dateFormatted.compareTo(new StringBuilder(dateFormatted).reverse().toString()) == 0 ) {
                count++;
                System.out.printf("date = %s%n", date.format(formatterDash));
            }
        }
    }

}
Task: Palindrome dates







Python: 

from datetime import datetime
from itertools import chain



def palinDay(y):
    
    s = str(y)
    r = s[::-1]
    iso = '-'.join([s, r[0:2], r[2:]])
    try:
        datetime.strptime(iso, '%Y-%m-%d')
        return [iso]
    except ValueError:
        return []




def main():
    
    palinDates = list(chain.from_iterable(
        map(palinDay, range(2021, 10000))
    ))
    for x in [
            'Count of palindromic dates [2021..9999]:',
            len(palinDates),
            '\nFirst 15:',
            '\n'.join(palinDates[0:15]),
            '\nLast 15:',
            '\n'.join(palinDates[-15:])
    ]:
        print(x)



if __name__ == '__main__':
    main()
Task: Palindrome dates








VB: dateTest = ""
mes = 0 : dia = 0 : anno = 0 : Pal = 0
total = 0
print "Siguientes 15 fechas palindrómicas al 2020-02-02:"
for anno = 2021 to 9999
	dateTest = ltrim(string(anno))
	for mes = 1 to 12
		if mes < 10 then dateTest = dateTest + "0"
		dateTest = dateTest + ltrim(string(mes))
		for dia = 1 to 31
			if mes = 2 and dia > 28 then exit for
			if (mes = 4 or mes = 6 or mes = 9 or mes = 11) and dia > 30 then exit for
			if dia < 10 then dateTest = dateTest + "0"
			dateTest = dateTest + ltrim(string(dia))
			for Pal = 1 to 4
				if mid(dateTest, Pal, 1) <> mid(dateTest, 9 - Pal, 1) then exit for
			next Pal
			if Pal = 5 then
				total += 1
				if total <= 15 then print left(dateTest,4);"-";mid(dateTest,5,2);"-";right(dateTest,2)
			end if
			if total > 15 then exit for : exit for : exit for
			dateTest = left(dateTest, 6)
		next dia
		dateTest = left(dateTest, 4)
	next mes
	dateTest = ""
next anno
end
Task: Palindrome dates




Go: package main

import (
    "fmt"
    "time"
)

func reverse(s string) string {
    chars := []rune(s)
    for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {
        chars[i], chars[j] = chars[j], chars[i]
    }
    return string(chars)
}

func main() {
    const (
        layout  = "20060102"
        layout2 = "2006-01-02"
    )
    fmt.Println("The next 15 palindromic dates in yyyymmdd format after 20200202 are:")
    date := time.Date(2020, 2, 2, 0, 0, 0, 0, time.UTC)
    count := 0
    for count < 15 {
        date = date.AddDate(0, 0, 1)
        s := date.Format(layout)
        r := reverse(s)
        if r == s {
            fmt.Println(date.Format(layout2))
            count++
        }
    }
}
Task: Palindrome dates








VB: Sub MainPalindromeDates()
Const FirstDate As String = "2020-02-02"
Const NumberOfDates As Integer = 15
Dim D As String, temp As String, Cpt As Integer
    temp = Format(DateAdd("d", 1, CDate(FirstDate)), "yyyy-mm-dd")
    Do
        D = Replace(temp, "-", "")
        If IsDatePalindrome(D) Then
            Debug.Print Left(D, 4) & "-" & Mid(D, 5, 2) & "-" & Right(D, 2)
            Cpt = Cpt + 1
        End If
        temp = Format(DateAdd("d", 1, CDate(temp)), "yyyy-mm-dd")
    Loop While Cpt < NumberOfDates
End Sub
Function IsDatePalindrome(strDate As String) As Boolean
    IsDatePalindrome = StrReverse(Left(strDate, 4)) = Right(strDate, 4)
End Function
Task: Multi-dimensional array



C#: var array = new int[,] { 
    { 1, 2, 3 },
    { 4, 5, 6}
}

array[0, 0] = 999;


var array = new int[5, 4, 3, 2];









Ada: type Grade is range 0..100;
subtype Lower_Case is Character range 'a'..'z';
subtype Natural is Integer range 0..Integer'Last;
subtype Positive is Integer range 1..Integer'Last;
type Deflection is range -180..180;
Task: Multi-dimensional array

C: 
int a[10];



float b[3][2];



char c[4][5][6];



double d[6][7][8][9];



int e[][3];



float f[5][4][];


int *g;


float **h;


double **i[];



char **j[][5];











Ada: type Grade is range 0..100;
subtype Lower_Case is Character range 'a'..'z';
subtype Natural is Integer range 0..Integer'Last;
subtype Positive is Integer range 1..Integer'Last;
type Deflection is range -180..180;
Task: Multi-dimensional array


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


template<typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T>& c) {
    auto it = c.cbegin();
    auto end = c.cend();

    out << '[';
    if (it != end) {
        out << *it;
        it = std::next(it);
    }
    while (it != end) {
        out << ", " << *it;
        it = std::next(it);
    }
    return out << ']';
}

void fourDim() {
    using namespace std;

    
    vector<vector<vector<vector<int>>>> arr;
    int cnt = 0;

    arr.push_back(vector<vector<vector<int>>>{});
    arr[0].push_back(vector<vector<int>>{});
    arr[0][0].push_back(vector<int>{});
    arr[0][0][0].push_back(cnt++);
    arr[0][0][0].push_back(cnt++);
    arr[0][0][0].push_back(cnt++);
    arr[0][0][0].push_back(cnt++);
    arr[0].push_back(vector<vector<int>>{});
    arr[0][1].push_back(vector<int>{});
    arr[0][1][0].push_back(cnt++);
    arr[0][1][0].push_back(cnt++);
    arr[0][1][0].push_back(cnt++);
    arr[0][1][0].push_back(cnt++);
    arr[0][1].push_back(vector<int>{});
    arr[0][1][1].push_back(cnt++);
    arr[0][1][1].push_back(cnt++);
    arr[0][1][1].push_back(cnt++);
    arr[0][1][1].push_back(cnt++);

    arr.push_back(vector<vector<vector<int>>>{});
    arr[1].push_back(vector<vector<int>>{});
    arr[1][0].push_back(vector<int>{});
    arr[1][0][0].push_back(cnt++);
    arr[1][0][0].push_back(cnt++);
    arr[1][0][0].push_back(cnt++);
    arr[1][0][0].push_back(cnt++);

    cout << arr << '\n';
}

int main() {
    

    fourDim();

    return 0;
}










Ada: type Grade is range 0..100;
subtype Lower_Case is Character range 'a'..'z';
subtype Natural is Integer range 0..Integer'Last;
subtype Positive is Integer range 1..Integer'Last;
type Deflection is range -180..180;
Task: Multi-dimensional array




Go: package main

import "fmt"

type md struct {
    dim []int
    ele []float64
}

func newMD(dim ...int) *md {
    n := 1
    for _, d := range dim {
        n *= d
    }
    return &md{append([]int{}, dim...), make([]float64, n)}
}

func (m *md) index(i ...int) (x int) {
    for d, dx := range m.dim {
        x = x*dx + i[d]
    }
    return
}

func (m *md) at(i ...int) float64 {
    return m.ele[m.index(i...)]
}

func (m *md) set(x float64, i ...int) {
    m.ele[m.index(i...)] = x
}

func (m *md) show(i ...int) {
    fmt.Printf("m%d = %g\n", i, m.at(i...))
}

func main() {
    m := newMD(5, 4, 3, 2)
    m.show(4, 3, 2, 1)
    m.set(87, 4, 3, 2, 1)
    m.show(4, 3, 2, 1)

    for i := 0; i < m.dim[0]; i++ {
        for j := 0; j < m.dim[1]; j++ {
            for k := 0; k < m.dim[2]; k++ {
                for l := 0; l < m.dim[3]; l++ {
                    x := m.index(i, j, k, l)
                    m.set(float64(x)+.1, i, j, k, l)
                }
            }
        }
    }
    fmt.Println(m.ele[:10])
    fmt.Println(m.ele[len(m.ele)-10:])
    m.show(4, 3, 2, 1)
}








Ada: type Grade is range 0..100;
subtype Lower_Case is Character range 'a'..'z';
subtype Natural is Integer range 0..Integer'Last;
subtype Positive is Integer range 1..Integer'Last;
type Deflection is range -180..180;
Task: Multi-dimensional array





Java: public class MultiDimensionalArray {
    public static void main(String[] args) {
        
        int m = 1;
        int[][][][] a4 = new int[5][4][3][2];
        for (int i = 0; i < a4.length; ++i) {
            for (int j = 0; j < a4[0].length; ++j) {
                for (int k = 0; k < a4[0][0].length; ++k) {
                    for (int l = 0; l < a4[0][0][0].length; ++l) {
                        a4[i][j][k][l] = m++;
                    }
                }
            }
        }

        System.out.println("First element = " + a4[0][0][0][0]);  
        a4[0][0][0][0] = 121;                                     
        System.out.println();

        for (int i = 0; i < a4.length; ++i) {
            for (int j = 0; j < a4[0].length; ++j) {
                for (int k = 0; k < a4[0][0].length; ++k) {
                    for (int l = 0; l < a4[0][0][0].length; ++l) {
                        System.out.printf("%4d", a4[i][j][k][l]);
                    }
                }
            }
        }
    }
}







Ada: type Grade is range 0..100;
subtype Lower_Case is Character range 'a'..'z';
subtype Natural is Integer range 0..Integer'Last;
subtype Positive is Integer range 1..Integer'Last;
type Deflection is range -180..180;
Task: Multi-dimensional array







Python: >>> from pprint import pprint as pp   
>>> from itertools import product
>>> 
>>> def dict_as_mdarray(dimensions=(2, 3), init=0.0):
...     return {indices: init for indices in product(*(range(i) for i in dimensions))}
... 
>>> 
>>> mdarray = dict_as_mdarray((2, 3, 4, 5))
>>> pp(mdarray)
{(0, 0, 0, 0): 0.0,
 (0, 0, 0, 1): 0.0,
 (0, 0, 0, 2): 0.0,
 (0, 0, 0, 3): 0.0,
 (0, 0, 0, 4): 0.0,
 (0, 0, 1, 0): 0.0,
...
 (1, 2, 3, 0): 0.0,
 (1, 2, 3, 1): 0.0,
 (1, 2, 3, 2): 0.0,
 (1, 2, 3, 3): 0.0,
 (1, 2, 3, 4): 0.0}
>>> mdarray[(0, 1, 2, 3)]
0.0
>>> mdarray[(0, 1, 2, 3)] = 6.78
>>> mdarray[(0, 1, 2, 3)]
6.78
>>> mdarray[(0, 1, 2, 3)] = 5.4321
>>> mdarray[(0, 1, 2, 3)]
5.4321
>>> pp(mdarray)
{(0, 0, 0, 0): 0.0,
 (0, 0, 0, 1): 0.0,
 (0, 0, 0, 2): 0.0,
...
 (0, 1, 2, 2): 0.0,
 (0, 1, 2, 3): 5.4321,
 (0, 1, 2, 4): 0.0,
...
 (1, 2, 3, 3): 0.0,
 (1, 2, 3, 4): 0.0}
>>>





Ada: type Grade is range 0..100;
subtype Lower_Case is Character range 'a'..'z';
subtype Natural is Integer range 0..Integer'Last;
subtype Positive is Integer range 1..Integer'Last;
type Deflection is range -180..180;
Task: Multi-dimensional array

C: 
int a[10];



float b[3][2];



char c[4][5][6];



double d[6][7][8][9];



int e[][3];



float f[5][4][];


int *g;


float **h;


double **i[];



char **j[][5];
Task: Multi-dimensional array



C#: var array = new int[,] { 
    { 1, 2, 3 },
    { 4, 5, 6}
}

array[0, 0] = 999;


var array = new int[5, 4, 3, 2];
Task: Multi-dimensional array


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


template<typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T>& c) {
    auto it = c.cbegin();
    auto end = c.cend();

    out << '[';
    if (it != end) {
        out << *it;
        it = std::next(it);
    }
    while (it != end) {
        out << ", " << *it;
        it = std::next(it);
    }
    return out << ']';
}

void fourDim() {
    using namespace std;

    
    vector<vector<vector<vector<int>>>> arr;
    int cnt = 0;

    arr.push_back(vector<vector<vector<int>>>{});
    arr[0].push_back(vector<vector<int>>{});
    arr[0][0].push_back(vector<int>{});
    arr[0][0][0].push_back(cnt++);
    arr[0][0][0].push_back(cnt++);
    arr[0][0][0].push_back(cnt++);
    arr[0][0][0].push_back(cnt++);
    arr[0].push_back(vector<vector<int>>{});
    arr[0][1].push_back(vector<int>{});
    arr[0][1][0].push_back(cnt++);
    arr[0][1][0].push_back(cnt++);
    arr[0][1][0].push_back(cnt++);
    arr[0][1][0].push_back(cnt++);
    arr[0][1].push_back(vector<int>{});
    arr[0][1][1].push_back(cnt++);
    arr[0][1][1].push_back(cnt++);
    arr[0][1][1].push_back(cnt++);
    arr[0][1][1].push_back(cnt++);

    arr.push_back(vector<vector<vector<int>>>{});
    arr[1].push_back(vector<vector<int>>{});
    arr[1][0].push_back(vector<int>{});
    arr[1][0][0].push_back(cnt++);
    arr[1][0][0].push_back(cnt++);
    arr[1][0][0].push_back(cnt++);
    arr[1][0][0].push_back(cnt++);

    cout << arr << '\n';
}

int main() {
    

    fourDim();

    return 0;
}
Task: Multi-dimensional array





Java: public class MultiDimensionalArray {
    public static void main(String[] args) {
        
        int m = 1;
        int[][][][] a4 = new int[5][4][3][2];
        for (int i = 0; i < a4.length; ++i) {
            for (int j = 0; j < a4[0].length; ++j) {
                for (int k = 0; k < a4[0][0].length; ++k) {
                    for (int l = 0; l < a4[0][0][0].length; ++l) {
                        a4[i][j][k][l] = m++;
                    }
                }
            }
        }

        System.out.println("First element = " + a4[0][0][0][0]);  
        a4[0][0][0][0] = 121;                                     
        System.out.println();

        for (int i = 0; i < a4.length; ++i) {
            for (int j = 0; j < a4[0].length; ++j) {
                for (int k = 0; k < a4[0][0].length; ++k) {
                    for (int l = 0; l < a4[0][0][0].length; ++l) {
                        System.out.printf("%4d", a4[i][j][k][l]);
                    }
                }
            }
        }
    }
}
Task: Multi-dimensional array







Python: >>> from pprint import pprint as pp   
>>> from itertools import product
>>> 
>>> def dict_as_mdarray(dimensions=(2, 3), init=0.0):
...     return {indices: init for indices in product(*(range(i) for i in dimensions))}
... 
>>> 
>>> mdarray = dict_as_mdarray((2, 3, 4, 5))
>>> pp(mdarray)
{(0, 0, 0, 0): 0.0,
 (0, 0, 0, 1): 0.0,
 (0, 0, 0, 2): 0.0,
 (0, 0, 0, 3): 0.0,
 (0, 0, 0, 4): 0.0,
 (0, 0, 1, 0): 0.0,
...
 (1, 2, 3, 0): 0.0,
 (1, 2, 3, 1): 0.0,
 (1, 2, 3, 2): 0.0,
 (1, 2, 3, 3): 0.0,
 (1, 2, 3, 4): 0.0}
>>> mdarray[(0, 1, 2, 3)]
0.0
>>> mdarray[(0, 1, 2, 3)] = 6.78
>>> mdarray[(0, 1, 2, 3)]
6.78
>>> mdarray[(0, 1, 2, 3)] = 5.4321
>>> mdarray[(0, 1, 2, 3)]
5.4321
>>> pp(mdarray)
{(0, 0, 0, 0): 0.0,
 (0, 0, 0, 1): 0.0,
 (0, 0, 0, 2): 0.0,
...
 (0, 1, 2, 2): 0.0,
 (0, 1, 2, 3): 5.4321,
 (0, 1, 2, 4): 0.0,
...
 (1, 2, 3, 3): 0.0,
 (1, 2, 3, 4): 0.0}
>>>
Task: Multi-dimensional array




Go: package main

import "fmt"

type md struct {
    dim []int
    ele []float64
}

func newMD(dim ...int) *md {
    n := 1
    for _, d := range dim {
        n *= d
    }
    return &md{append([]int{}, dim...), make([]float64, n)}
}

func (m *md) index(i ...int) (x int) {
    for d, dx := range m.dim {
        x = x*dx + i[d]
    }
    return
}

func (m *md) at(i ...int) float64 {
    return m.ele[m.index(i...)]
}

func (m *md) set(x float64, i ...int) {
    m.ele[m.index(i...)] = x
}

func (m *md) show(i ...int) {
    fmt.Printf("m%d = %g\n", i, m.at(i...))
}

func main() {
    m := newMD(5, 4, 3, 2)
    m.show(4, 3, 2, 1)
    m.set(87, 4, 3, 2, 1)
    m.show(4, 3, 2, 1)

    for i := 0; i < m.dim[0]; i++ {
        for j := 0; j < m.dim[1]; j++ {
            for k := 0; k < m.dim[2]; k++ {
                for l := 0; l < m.dim[3]; l++ {
                    x := m.index(i, j, k, l)
                    m.set(float64(x)+.1, i, j, k, l)
                }
            }
        }
    }
    fmt.Println(m.ele[:10])
    fmt.Println(m.ele[len(m.ele)-10:])
    m.show(4, 3, 2, 1)
}
Task: Multi-dimensional array



C#: var array = new int[,] { 
    { 1, 2, 3 },
    { 4, 5, 6}
}

array[0, 0] = 999;


var array = new int[5, 4, 3, 2];








Fortran:       DIMENSION A(5,4,3,2)                 
      X = 3*A(2,I,1,K)                     
      A(1,2,3,4) = X + 1