WeixiangYan/CodeTransOcean huggingface dataset:
Task: Sort disjoint sublist





Java: import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Disjoint {
    public static <T extends Comparable<? super T>> void sortDisjoint(
            List<T> array, int[] idxs) {
        Arrays.sort(idxs);
        List<T> disjoint = new ArrayList<T>();
        for (int idx : idxs) {
            disjoint.add(array.get(idx));
        }
        Collections.sort(disjoint);
        int i = 0;
        for (int idx : idxs) {
            array.set(idx, disjoint.get(i++));
        }
    }

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(7, 6, 5, 4, 3, 2, 1, 0);
        int[] indices = {6, 1, 7};
        System.out.println(list);
        sortDisjoint(list, indices);
        System.out.println(list);
    }
}







Ada: with Ada.Text_IO, GNAT.Bubble_Sort;
use  Ada.Text_IO;

procedure DisjointSort is

   package Int_Io is new Integer_IO (Integer);

   subtype Index_Range is Natural range 1 .. 8;
   Input_Array : array (Index_Range) of Integer := (7, 6, 5, 4, 3, 2, 1, 0);

   subtype Subindex_Range is Natural range 1 .. 3;
   type Sub_Arrays is array (Subindex_Range) of Integer;

   Sub_Index : Sub_Arrays := (7, 2, 8);
   Sub_Array : Sub_Arrays;

   

   procedure Sort (Work_Array : in out Sub_Arrays) is
      procedure Exchange (Op1, Op2 : Natural) is
         Temp : Integer;
      begin
         Temp             := Work_Array (Op1);
         Work_Array (Op1) := Work_Array (Op2);
         Work_Array (Op2) := Temp;
      end Exchange;

      function Lt (Op1, Op2 : Natural) return Boolean is
      begin
         return (Work_Array (Op1) < Work_Array (Op2));
      end Lt;
   begin
      GNAT.Bubble_Sort.Sort
        (N    => Subindex_Range'Last,
         Xchg => Exchange'Unrestricted_Access,
         Lt   => Lt'Unrestricted_Access);
   end Sort;

begin
   
   Sort (Sub_Index);
   
   for I in Subindex_Range loop
      Sub_Array (I) := Input_Array (Sub_Index (I));
   end loop;
   Sort (Sub_Array);
   
   for I in Subindex_Range loop
      Input_Array (Sub_Index (I))  := Sub_Array (I);
   end loop;

   for I in Index_Range loop
      Int_Io.Put (Input_Array (I), Width => 2);
   end loop;
   New_Line;

end DisjointSort;
Task: Sort disjoint sublist







Python: >>> def sort_disjoint_sublist(data, indices):
	indices = sorted(indices)
	values  = sorted(data[i] for i in indices)
	for index, value in zip(indices, values):
		data[index] = value

		
>>> d = [7, 6, 5, 4, 3, 2, 1, 0]
>>> i = set([6, 1, 7])
>>> sort_disjoint_sublist(d, i)
>>> d
[7, 0, 5, 4, 3, 2, 1, 6]
>>> 
>>> def sort_disjoint_sublist(data, indices):
	for index, value in zip(sorted(indices), sorted(data[i] for i in indices)): data[index] = value

	
>>>





Ada: with Ada.Text_IO, GNAT.Bubble_Sort;
use  Ada.Text_IO;

procedure DisjointSort is

   package Int_Io is new Integer_IO (Integer);

   subtype Index_Range is Natural range 1 .. 8;
   Input_Array : array (Index_Range) of Integer := (7, 6, 5, 4, 3, 2, 1, 0);

   subtype Subindex_Range is Natural range 1 .. 3;
   type Sub_Arrays is array (Subindex_Range) of Integer;

   Sub_Index : Sub_Arrays := (7, 2, 8);
   Sub_Array : Sub_Arrays;

   

   procedure Sort (Work_Array : in out Sub_Arrays) is
      procedure Exchange (Op1, Op2 : Natural) is
         Temp : Integer;
      begin
         Temp             := Work_Array (Op1);
         Work_Array (Op1) := Work_Array (Op2);
         Work_Array (Op2) := Temp;
      end Exchange;

      function Lt (Op1, Op2 : Natural) return Boolean is
      begin
         return (Work_Array (Op1) < Work_Array (Op2));
      end Lt;
   begin
      GNAT.Bubble_Sort.Sort
        (N    => Subindex_Range'Last,
         Xchg => Exchange'Unrestricted_Access,
         Lt   => Lt'Unrestricted_Access);
   end Sort;

begin
   
   Sort (Sub_Index);
   
   for I in Subindex_Range loop
      Sub_Array (I) := Input_Array (Sub_Index (I));
   end loop;
   Sort (Sub_Array);
   
   for I in Subindex_Range loop
      Input_Array (Sub_Index (I))  := Sub_Array (I);
   end loop;

   for I in Index_Range loop
      Int_Io.Put (Input_Array (I), Width => 2);
   end loop;
   New_Line;

end DisjointSort;
Task: Sort disjoint sublist

C: #include <stdio.h>


void bubble_sort(int *idx, int n_idx, int *buf)
{
        int i, j, tmp;
#define for_ij for (i = 0; i < n_idx; i++) for (j = i + 1; j < n_idx; j++)
#define sort(a, b) if (a < b) { tmp = a; a = b; b = tmp;}
        for_ij { sort(idx[j], idx[i]);          }
        for_ij { sort(buf[idx[j]], buf[idx[i]]);}
#undef for_ij
#undef sort
}

int main()
{
        int values[] = {7, 6, 5, 4, 3, 2, 1, 0};
        int idx[] = {6, 1, 7};
        int i;

        printf("before sort:\n");
        for (i = 0; i < 8; i++)
                printf("%d ", values[i]);

        printf("\n\nafter sort:\n");
        bubble_sort(idx, 3, values);

        for (i = 0; i < 8; i++)
                printf("%d ", values[i]);
        printf("\n");

        return 0;
}
Task: Sort disjoint sublist



C#: using System;
using System.Linq;
using System.Collections.Generic;
     
public class Test
{
    public static void Main()
    {
        var list = new List<int>{ 7, 6, 5, 4, 3, 2, 1, 0 };
        list.SortSublist(6, 1, 7);
        Console.WriteLine(string.Join(", ", list));
    }
}
     
public static class Extensions
{
    public static void SortSublist<T>(this List<T> list, params int[] indices)
        where T : IComparable<T>
    {
        var sublist = indices.OrderBy(i => i)
            .Zip(indices.Select(i => list[i]).OrderBy(v => v),
                (Index, Value) => new { Index, Value });
     
        foreach (var entry in sublist) {
            list[entry.Index] = entry.Value;
        }
    }
     
}
Task: Sort disjoint sublist


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

template <typename ValueIterator, typename IndicesIterator>
void sortDisjoint(ValueIterator valsBegin, IndicesIterator indicesBegin,
		  IndicesIterator indicesEnd) {
    std::vector<int> temp;

    for (IndicesIterator i = indicesBegin; i != indicesEnd; ++i)
        temp.push_back(valsBegin[*i]); 

    std::sort(indicesBegin, indicesEnd); 
    std::sort(temp.begin(), temp.end()); 

    std::vector<int>::const_iterator j = temp.begin();
    for (IndicesIterator i = indicesBegin; i != indicesEnd; ++i, ++j)
        valsBegin[*i] = *j; 
}
		  

int main()
{
    int values[] = { 7, 6, 5, 4, 3, 2, 1, 0 };
    int indices[] = { 6, 1, 7 };

    sortDisjoint(values, indices, indices+3);

    std::copy(values, values + 8, std::ostream_iterator<int>(std::cout, " "));
    std::cout << "\n";

    return 0;
}
Task: Sort disjoint sublist





Java: import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Disjoint {
    public static <T extends Comparable<? super T>> void sortDisjoint(
            List<T> array, int[] idxs) {
        Arrays.sort(idxs);
        List<T> disjoint = new ArrayList<T>();
        for (int idx : idxs) {
            disjoint.add(array.get(idx));
        }
        Collections.sort(disjoint);
        int i = 0;
        for (int idx : idxs) {
            array.set(idx, disjoint.get(i++));
        }
    }

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(7, 6, 5, 4, 3, 2, 1, 0);
        int[] indices = {6, 1, 7};
        System.out.println(list);
        sortDisjoint(list, indices);
        System.out.println(list);
    }
}
Task: Sort disjoint sublist







Python: >>> def sort_disjoint_sublist(data, indices):
	indices = sorted(indices)
	values  = sorted(data[i] for i in indices)
	for index, value in zip(indices, values):
		data[index] = value

		
>>> d = [7, 6, 5, 4, 3, 2, 1, 0]
>>> i = set([6, 1, 7])
>>> sort_disjoint_sublist(d, i)
>>> d
[7, 0, 5, 4, 3, 2, 1, 6]
>>> 
>>> def sort_disjoint_sublist(data, indices):
	for index, value in zip(sorted(indices), sorted(data[i] for i in indices)): data[index] = value

	
>>>
Task: Sort disjoint sublist




Go: package main

import (
    "fmt"
    "sort"
)

func main() {
    
    values := []int{7, 6, 5, 4, 3, 2, 1, 0}
    indices := map[int]int{6: 0, 1: 0, 7: 0}

    orderedValues := make([]int, len(indices))
    orderedIndices := make([]int, len(indices))
    i := 0
    for j := range indices {
        
        if j < 0 || j >= len(values) {
            fmt.Println("Invalid index: ", j)
            return
        }
        
        orderedValues[i] = values[j]
        orderedIndices[i] = j
        i++
    }
    
    sort.Ints(orderedValues)
    sort.Ints(orderedIndices)

    fmt.Println("initial:", values)
    
    for i, v := range orderedValues {
        values[orderedIndices[i]] = v
    }
    fmt.Println("sorted: ", values)
}
Task: Sort disjoint sublist



C#: using System;
using System.Linq;
using System.Collections.Generic;
     
public class Test
{
    public static void Main()
    {
        var list = new List<int>{ 7, 6, 5, 4, 3, 2, 1, 0 };
        list.SortSublist(6, 1, 7);
        Console.WriteLine(string.Join(", ", list));
    }
}
     
public static class Extensions
{
    public static void SortSublist<T>(this List<T> list, params int[] indices)
        where T : IComparable<T>
    {
        var sublist = indices.OrderBy(i => i)
            .Zip(indices.Select(i => list[i]).OrderBy(v => v),
                (Index, Value) => new { Index, Value });
     
        foreach (var entry in sublist) {
            list[entry.Index] = entry.Value;
        }
    }
     
}








Fortran: program Example
  implicit none

  integer :: array(8) = (/ 7, 6, 5, 4, 3, 2, 1, 0 /)
  integer :: indices(3) = (/ 7, 2, 8 /)



  call Isort(indices)




  call Isort(array(indices))

  write(*,*) array

contains

subroutine Isort(a)
  integer, intent(in out) :: a(:)
  integer :: temp
  integer :: i, j
   
  do i = 2, size(a)
     j = i - 1
     temp = a(i)
     do while (j>=1 .and. a(j)>temp)
        a(j+1) = a(j)
        j = j - 1
     end do
     a(j+1) = temp
  end do
  
end subroutine Isort
end program Example
Task: Sort disjoint sublist


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

template <typename ValueIterator, typename IndicesIterator>
void sortDisjoint(ValueIterator valsBegin, IndicesIterator indicesBegin,
		  IndicesIterator indicesEnd) {
    std::vector<int> temp;

    for (IndicesIterator i = indicesBegin; i != indicesEnd; ++i)
        temp.push_back(valsBegin[*i]); 

    std::sort(indicesBegin, indicesEnd); 
    std::sort(temp.begin(), temp.end()); 

    std::vector<int>::const_iterator j = temp.begin();
    for (IndicesIterator i = indicesBegin; i != indicesEnd; ++i, ++j)
        valsBegin[*i] = *j; 
}
		  

int main()
{
    int values[] = { 7, 6, 5, 4, 3, 2, 1, 0 };
    int indices[] = { 6, 1, 7 };

    sortDisjoint(values, indices, indices+3);

    std::copy(values, values + 8, std::ostream_iterator<int>(std::cout, " "));
    std::cout << "\n";

    return 0;
}









Fortran: program Example
  implicit none

  integer :: array(8) = (/ 7, 6, 5, 4, 3, 2, 1, 0 /)
  integer :: indices(3) = (/ 7, 2, 8 /)



  call Isort(indices)




  call Isort(array(indices))

  write(*,*) array

contains

subroutine Isort(a)
  integer, intent(in out) :: a(:)
  integer :: temp
  integer :: i, j
   
  do i = 2, size(a)
     j = i - 1
     temp = a(i)
     do while (j>=1 .and. a(j)>temp)
        a(j+1) = a(j)
        j = j - 1
     end do
     a(j+1) = temp
  end do
  
end subroutine Isort
end program Example
Task: Sort disjoint sublist

C: #include <stdio.h>


void bubble_sort(int *idx, int n_idx, int *buf)
{
        int i, j, tmp;
#define for_ij for (i = 0; i < n_idx; i++) for (j = i + 1; j < n_idx; j++)
#define sort(a, b) if (a < b) { tmp = a; a = b; b = tmp;}
        for_ij { sort(idx[j], idx[i]);          }
        for_ij { sort(buf[idx[j]], buf[idx[i]]);}
#undef for_ij
#undef sort
}

int main()
{
        int values[] = {7, 6, 5, 4, 3, 2, 1, 0};
        int idx[] = {6, 1, 7};
        int i;

        printf("before sort:\n");
        for (i = 0; i < 8; i++)
                printf("%d ", values[i]);

        printf("\n\nafter sort:\n");
        bubble_sort(idx, 3, values);

        for (i = 0; i < 8; i++)
                printf("%d ", values[i]);
        printf("\n");

        return 0;
}










Fortran: program Example
  implicit none

  integer :: array(8) = (/ 7, 6, 5, 4, 3, 2, 1, 0 /)
  integer :: indices(3) = (/ 7, 2, 8 /)



  call Isort(indices)




  call Isort(array(indices))

  write(*,*) array

contains

subroutine Isort(a)
  integer, intent(in out) :: a(:)
  integer :: temp
  integer :: i, j
   
  do i = 2, size(a)
     j = i - 1
     temp = a(i)
     do while (j>=1 .and. a(j)>temp)
        a(j+1) = a(j)
        j = j - 1
     end do
     a(j+1) = temp
  end do
  
end subroutine Isort
end program Example
Task: Sort disjoint sublist





Java: import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Disjoint {
    public static <T extends Comparable<? super T>> void sortDisjoint(
            List<T> array, int[] idxs) {
        Arrays.sort(idxs);
        List<T> disjoint = new ArrayList<T>();
        for (int idx : idxs) {
            disjoint.add(array.get(idx));
        }
        Collections.sort(disjoint);
        int i = 0;
        for (int idx : idxs) {
            array.set(idx, disjoint.get(i++));
        }
    }

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(7, 6, 5, 4, 3, 2, 1, 0);
        int[] indices = {6, 1, 7};
        System.out.println(list);
        sortDisjoint(list, indices);
        System.out.println(list);
    }
}






Fortran: program Example
  implicit none

  integer :: array(8) = (/ 7, 6, 5, 4, 3, 2, 1, 0 /)
  integer :: indices(3) = (/ 7, 2, 8 /)



  call Isort(indices)




  call Isort(array(indices))

  write(*,*) array

contains

subroutine Isort(a)
  integer, intent(in out) :: a(:)
  integer :: temp
  integer :: i, j
   
  do i = 2, size(a)
     j = i - 1
     temp = a(i)
     do while (j>=1 .and. a(j)>temp)
        a(j+1) = a(j)
        j = j - 1
     end do
     a(j+1) = temp
  end do
  
end subroutine Isort
end program Example
Task: Sort disjoint sublist







Python: >>> def sort_disjoint_sublist(data, indices):
	indices = sorted(indices)
	values  = sorted(data[i] for i in indices)
	for index, value in zip(indices, values):
		data[index] = value

		
>>> d = [7, 6, 5, 4, 3, 2, 1, 0]
>>> i = set([6, 1, 7])
>>> sort_disjoint_sublist(d, i)
>>> d
[7, 0, 5, 4, 3, 2, 1, 6]
>>> 
>>> def sort_disjoint_sublist(data, indices):
	for index, value in zip(sorted(indices), sorted(data[i] for i in indices)): data[index] = value

	
>>>




Fortran: program Example
  implicit none

  integer :: array(8) = (/ 7, 6, 5, 4, 3, 2, 1, 0 /)
  integer :: indices(3) = (/ 7, 2, 8 /)



  call Isort(indices)




  call Isort(array(indices))

  write(*,*) array

contains

subroutine Isort(a)
  integer, intent(in out) :: a(:)
  integer :: temp
  integer :: i, j
   
  do i = 2, size(a)
     j = i - 1
     temp = a(i)
     do while (j>=1 .and. a(j)>temp)
        a(j+1) = a(j)
        j = j - 1
     end do
     a(j+1) = temp
  end do
  
end subroutine Isort
end program Example
Task: Kronecker product







Python: 


a1 = [[1, 2], [3, 4]]
b1 = [[0, 5], [6, 7]]


a2 = [[0, 1, 0], [1, 1, 1], [0, 1, 0]]
b2 = [[1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1]]

def kronecker(matrix1, matrix2):
    final_list = []
    sub_list = []

    count = len(matrix2)

    for elem1 in matrix1:
        counter = 0
        check = 0
        while check < count:
            for num1 in elem1:
                for num2 in matrix2[counter]:
                    sub_list.append(num1 * num2)
            counter += 1
            final_list.append(sub_list)
            sub_list = []
            check +=1
            
    return final_list


result1 = kronecker(a1, b1)
for elem in result1:
    print(elem)

print("")


result2 = kronecker(a2, b2)
for elem in result2:
    print(elem)





Ada: with Ada.Text_IO;
with Ada.Integer_Text_IO;

procedure Kronecker_Product is
   type Matrix is array (Positive range <>, Positive range <>) of Integer;

   function "*"(Left, Right : in Matrix) return Matrix is
      result : Matrix
        (1 .. Left'Length(1) * Right'Length(1),
         1 .. Left'Length(2) * Right'Length(2));
      LI : Natural := 0;
      LJ : Natural := 0;
   begin
      for I in 0 .. result'Length(1) - 1 loop
         for J in 0 .. result'Length(2) - 1 loop
            result (I + 1, J + 1) :=
              Left(Left'First(1) + (LI), Left'First(2) + (LJ))
              * Right
                (Right'First(1) + (I mod Right'Length(1)),
                 Right'First(2) + (J mod Right'Length(2)));
            if (J+1) mod Right'Length(2) = 0 then
               LJ := LJ + 1;
            end if;
         end loop;
         if (I+1) mod Right'Length(1) = 0 then
            LI := LI + 1;
         end if;
         LJ := 0;
      end loop;
      return result;
   end "*";

   Left1   : constant Matrix := ((1, 2), (3, 4));
   Right1  : constant Matrix := ((0, 5), (6, 7));
   result1 : constant Matrix := Left1 * Right1;
   Left2   : constant Matrix := ((0, 1, 0), (1, 1, 1), (0, 1, 0));
   Right2  : constant Matrix := ((1, 1, 1, 1), (1, 0, 0, 1), (1, 1, 1, 1));
   result2 : constant Matrix := Left2 * Right2;
begin
   for I in result1'Range(1) loop
      for J in result1'Range(2) loop
         Ada.Integer_Text_IO.Put(Ada.Text_IO.Standard_Output, result1(I, J));
      end loop;
      Ada.Text_IO.New_Line;
   end loop;

   Ada.Text_IO.New_Line;

   for I in result2'Range(1) loop
      for J in result2'Range(2) loop
         Ada.Integer_Text_IO.Put(Ada.Text_IO.Standard_Output, result2(I, J));
      end loop;
      Ada.Text_IO.New_Line;
   end loop;
end Kronecker_Product;
Task: Kronecker product

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

int main(){
	
	char input[100],output[100];
	int i,j,k,l,rowA,colA,rowB,colB,rowC,colC,startRow,startCol;
	double **matrixA,**matrixB,**matrixC;
	
	printf("Enter full path of input file : ");
	fscanf(stdin,"%s",input);
	
	printf("Enter full path of output file : ");
	fscanf(stdin,"%s",output);
	
	FILE* inputFile = fopen(input,"r");
	
	fscanf(inputFile,"%d%d",&rowA,&colA);
	
	matrixA = (double**)malloc(rowA * sizeof(double*));
	
	for(i=0;i<rowA;i++){
		matrixA[i] = (double*)malloc(colA*sizeof(double));
		for(j=0;j<colA;j++){
			fscanf(inputFile,"%lf",&matrixA[i][j]);
		}
	}
	
	fscanf(inputFile,"%d%d",&rowB,&colB);
	
	matrixB = (double**)malloc(rowB * sizeof(double*));
	
	for(i=0;i<rowB;i++){
		matrixB[i] = (double*)malloc(colB*sizeof(double));
		for(j=0;j<colB;j++){
			fscanf(inputFile,"%lf",&matrixB[i][j]);
		}
	}
	
	fclose(inputFile);
	
	rowC = rowA*rowB;
	colC = colA*colB;
	
	matrixC = (double**)malloc(rowC*sizeof(double*));
	
	for(i=0;i<rowA*rowB;i++){
		matrixC[i] = (double*)malloc(colA*colB*sizeof(double));
	}
	
	for(i=0;i<rowA;i++){
		for(j=0;j<colA;j++){
			startRow = i*rowB;
			startCol = j*colB;
			for(k=0;k<rowB;k++){
				for(l=0;l<colB;l++){
					matrixC[startRow+k][startCol+l] = matrixA[i][j]*matrixB[k][l];
				}
			}
		}
	}

	FILE* outputFile = fopen(output,"w");
	
	for(i=0;i<rowC;i++){
		for(j=0;j<colC;j++){
			fprintf(outputFile,"%lf\t",matrixC[i][j]);
		}
		fprintf(outputFile,"\n");
	}
	
	fclose(outputFile);
	
	printf("\n\n\nKronecker product of the two matrices written to %s.",output);
}
Task: Kronecker product



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

public static class KroneckerProduct
{
    public static void Main() {
        int[,] left = { {1, 2}, {3, 4} };
        int[,] right = { {0, 5}, {6, 7} };
        Print(Multiply(left, right));

        left = new [,] { {0, 1, 0}, {1, 1, 1}, {0, 1, 0} };
        right = new [,] { {1, 1, 1, 1}, {1, 0, 0, 1}, {1, 1, 1, 1} };
        Print(Multiply(left, right));
    }

    static int[,] Multiply(int[,] left, int[,] right) {
        (int lRows, int lColumns) = (left.GetLength(0), left.GetLength(1));
        (int rRows, int rColumns) = (right.GetLength(0), right.GetLength(1));
        int[,] result = new int[lRows * rRows, lColumns * rColumns];

        foreach (var (r, c) in from r in Range(0, lRows) from c in Range(0, lColumns) select (r, c)) {
            Copy(r * rRows, c * rColumns, left[r, c]);
        }
        return result;
        
        void Copy(int startRow, int startColumn, int multiplier) {
            foreach (var (r, c) in from r in Range(0, rRows) from c in Range(0, rColumns) select (r, c)) {
                result[startRow + r, startColumn + c] = right[r, c] * multiplier;
            }
        }
    }

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

    private static int LengthOf(int i) {
        if (i < 0) return LengthOf(-i) + 1;
        int length = 0;
        while (i > 0) {
            length++;
            i /= 10;
        }
        return length;
    }

}
Task: Kronecker product





Java: package kronecker;


public class Product {
  
  public static int[][] product(final int[][] a, final int[][] b) {
    
    
    final int[][] c = new int[a.length*b.length][];
    
    
    for (int ix = 0; ix < c.length; ix++) {
      final int num_cols = a[0].length*b[0].length;
      c[ix] = new int[num_cols];
    }
    
    
    for (int ia = 0; ia < a.length; ia++) {
      for (int ja = 0; ja < a[ia].length; ja++) {
        
        for (int ib = 0; ib < b.length; ib++) {
          for (int jb = 0; jb < b[ib].length; jb++) {
             c[b.length*ia+ib][b[ib].length*ja+jb] = a[ia][ja] * b[ib][jb];
          }
        }
      }
    }

    
    return c;
  }

  
  public static void print_matrix(final int[][] m) {
    
    
    
    
    final String[][] sts = new String[m.length][];
    int max_length = 0;  
    for (int im = 0; im < m.length; im++) {
      sts[im] = new String[m[im].length];
      for (int jm = 0; jm < m[im].length; jm++) {
        final String st = String.valueOf(m[im][jm]);
        if (st.length() > max_length) {
          max_length = st.length();
        }
        sts[im][jm] = st;
      }
    }

    
    
    
    final String format = String.format("%%%ds", max_length);
    for (int im = 0; im < m.length; im++) {
      System.out.print("|");
      
      for (int jm = 0; jm < m[im].length - 1; jm++) {
        System.out.format(format, m[im][jm]);
        System.out.print(" ");
      }
      System.out.format(format, m[im][m[im].length - 1]);
      System.out.println("|");
    }
  }

  
  private static void test(final int[][] a, final int[][] b) {
    
    System.out.println("Testing Kronecker product");
    System.out.println("Size of matrix a: " + a.length + " by " + a[0].length);
    System.out.println("Matrix a:");
    print_matrix(a);
    System.out.println("Size of matrix b: " + b.length + " by " + b[0].length);
    System.out.println("Matrix b:");
    print_matrix(b);
    System.out.println("Calculating matrix c as Kronecker product");
    final int[][] c = product(a, b);
    System.out.println("Size of matrix c: " + c.length + " by " + c[0].length);
    System.out.println("Matrix c:");
    print_matrix(c);
  }

  
  private static void test1() {
    
    final int[][] a = new int[2][];  
    a[0] = new int[]{1, 2};
    a[1] = new int[]{3, 4};
    final int[][] b = new int[2][];  
    b[0] = new int[]{0, 5};
    b[1] = new int[]{6, 7};
    
    test(a, b);
  }

  
  private static void test2() {
    
    final int[][] a = new int[3][];  
    a[0] = new int[]{0, 1, 0};
    a[1] = new int[]{1, 1, 1};
    a[2] = new int[]{0, 1, 0};
    final int[][] b = new int[3][];  
    b[0] = new int[]{1, 1, 1, 1};
    b[1] = new int[]{1, 0, 0, 1};
    b[2] = new int[]{1, 1, 1, 1};
    
    test(a, b);
  }

  
  public static void main(final String[] args) {
    
    test1();
    test2();
  }

}