WeixiangYan/CodeTransOcean huggingface dataset:
Task: Convert decimal number to rational

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


void rat_approx(double f, int64_t md, int64_t *num, int64_t *denom)
{
	
	int64_t a, h[3] = { 0, 1, 0 }, k[3] = { 1, 0, 0 };
	int64_t x, d, n = 1;
	int i, neg = 0;

	if (md <= 1) { *denom = 1; *num = (int64_t) f; return; }

	if (f < 0) { neg = 1; f = -f; }

	while (f != floor(f)) { n <<= 1; f *= 2; }
	d = f;

	
	for (i = 0; i < 64; i++) {
		a = n ? d / n : 0;
		if (i && !a) break;

		x = d; d = n; n = x % n;

		x = a;
		if (k[1] * a + k[0] >= md) {
			x = (md - k[0]) / k[1];
			if (x * 2 >= a || k[1] >= md)
				i = 65;
			else
				break;
		}

		h[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2];
		k[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2];
	}
	*denom = k[1];
	*num = neg ? -h[1] : h[1];
}

int main()
{
	int i;
	int64_t d, n;
	double f;

	printf("f = %16.14f\n", f = 1.0/7);
	for (i = 1; i <= 20000000; i *= 16) {
		printf("denom <= %d: ", i);
		rat_approx(f, i, &n, &d);
		printf("%lld/%lld\n", n, d);
	}

	printf("\nf = %16.14f\n", f = atan2(1,1) * 4);
	for (i = 1; i <= 20000000; i *= 16) {
		printf("denom <= %d: ", i);
		rat_approx(f, i, &n, &d);
		printf("%lld/%lld\n", n, d);
	}

	return 0;
}











Ada: generic
   type Real is digits <>;
procedure Real_To_Rational(R: Real;
                           Bound: Positive;
                           Nominator: out Integer;
                           Denominator: out Positive);
Task: Convert decimal number to rational




Go: package main

import (
    "fmt"
    "math/big"
)

func main() {
    for _, d := range []string{"0.9054054", "0.518518", "0.75"} {
        if r, ok := new(big.Rat).SetString(d); ok {
            fmt.Println(d, "=", r)
        } else {
            fmt.Println(d, "invalid decimal number")
        }
    }
}








Ada: generic
   type Real is digits <>;
procedure Real_To_Rational(R: Real;
                           Bound: Positive;
                           Nominator: out Integer;
                           Denominator: out Positive);
Task: Convert decimal number to rational





Java: import org.apache.commons.math3.fraction.BigFraction;

public class Test {

    public static void main(String[] args) {
        double[] n = {0.750000000, 0.518518000, 0.905405400, 0.142857143,
            3.141592654, 2.718281828, -0.423310825, 31.415926536};

        for (double d : n)
            System.out.printf("%-12s : %s%n", d, new BigFraction(d, 0.00000002D, 10000));
    }
}







Ada: generic
   type Real is digits <>;
procedure Real_To_Rational(R: Real;
                           Bound: Positive;
                           Nominator: out Integer;
                           Denominator: out Positive);
Task: Convert decimal number to rational







Python: >>> from fractions import Fraction
>>> for d in (0.9054054, 0.518518, 0.75): print(d, Fraction.from_float(d).limit_denominator(100))

0.9054054 67/74
0.518518 14/27
0.75 3/4
>>> for d in '0.9054054 0.518518 0.75'.split(): print(d, Fraction(d))

0.9054054 4527027/5000000
0.518518 259259/500000
0.75 3/4
>>>





Ada: generic
   type Real is digits <>;
procedure Real_To_Rational(R: Real;
                           Bound: Positive;
                           Nominator: out Integer;
                           Denominator: out Positive);
Task: Convert decimal number to rational








VB: Function Real2Rational(r As Double, bound As Long) As String

If r = 0 Then
    Real2Rational = "0/1"
ElseIf r < 0 Then
    Result = Real2Rational(-r, bound)
    Real2Rational = "-" & Result
Else
    best = 1
    bestError = 1E+99
    For i = 1 To bound + 1
        currentError = Abs(i * r - Round(i * r))
        If currentError < bestError Then
            best = i
            bestError = currentError
            If bestError < 1 / bound Then GoTo SkipLoop
        End If
    Next i
SkipLoop:
    Real2Rational = Round(best * r) & "/" & best
End If
End Function

Sub TestReal2Rational()
Debug.Print "0.75" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(0.75, CLng(Order));
Next i
Debug.Print

Debug.Print "0.518518" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(0.518518, CLng(Order));
Next i
Debug.Print

Debug.Print "0.9054054" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(0.9054054, CLng(Order));
Next i
Debug.Print

Debug.Print "0.142857143" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(0.142857143, CLng(Order));
Next i
Debug.Print

Debug.Print "3.141592654" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(3.141592654, CLng(Order));
Next i
Debug.Print

Debug.Print "2.718281828" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(2.718281828, CLng(Order));
Next i
Debug.Print

Debug.Print "-0.423310825" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(-0.423310825, CLng(Order));
Next i
Debug.Print

Debug.Print "31.415926536" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(31.415926536, CLng(Order));
Next i
End Sub




Ada: generic
   type Real is digits <>;
procedure Real_To_Rational(R: Real;
                           Bound: Positive;
                           Nominator: out Integer;
                           Denominator: out Positive);
Task: Convert decimal number to rational

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


void rat_approx(double f, int64_t md, int64_t *num, int64_t *denom)
{
	
	int64_t a, h[3] = { 0, 1, 0 }, k[3] = { 1, 0, 0 };
	int64_t x, d, n = 1;
	int i, neg = 0;

	if (md <= 1) { *denom = 1; *num = (int64_t) f; return; }

	if (f < 0) { neg = 1; f = -f; }

	while (f != floor(f)) { n <<= 1; f *= 2; }
	d = f;

	
	for (i = 0; i < 64; i++) {
		a = n ? d / n : 0;
		if (i && !a) break;

		x = d; d = n; n = x % n;

		x = a;
		if (k[1] * a + k[0] >= md) {
			x = (md - k[0]) / k[1];
			if (x * 2 >= a || k[1] >= md)
				i = 65;
			else
				break;
		}

		h[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2];
		k[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2];
	}
	*denom = k[1];
	*num = neg ? -h[1] : h[1];
}

int main()
{
	int i;
	int64_t d, n;
	double f;

	printf("f = %16.14f\n", f = 1.0/7);
	for (i = 1; i <= 20000000; i *= 16) {
		printf("denom <= %d: ", i);
		rat_approx(f, i, &n, &d);
		printf("%lld/%lld\n", n, d);
	}

	printf("\nf = %16.14f\n", f = atan2(1,1) * 4);
	for (i = 1; i <= 20000000; i *= 16) {
		printf("denom <= %d: ", i);
		rat_approx(f, i, &n, &d);
		printf("%lld/%lld\n", n, d);
	}

	return 0;
}
Task: Convert decimal number to rational



C#: using System;
using System.Text;

namespace RosettaDecimalToFraction
{
    public class Fraction
    {
        public Int64 Numerator;
        public Int64 Denominator;
        public Fraction(double f, Int64 MaximumDenominator = 4096)
        {
            
            
            Int64 a;
            var h = new Int64[3] { 0, 1, 0 };
            var k = new Int64[3] { 1, 0, 0 };
            Int64 x, d, n = 1;
            int i, neg = 0;

            if (MaximumDenominator <= 1)
            {
                Denominator = 1;
                Numerator = (Int64)f;
                return;
            }

            if (f < 0) { neg = 1; f = -f; }

            while (f != Math.Floor(f)) { n <<= 1; f *= 2; }
            d = (Int64)f;

            
            for (i = 0; i < 64; i++)
            {
                a = (n != 0) ? d / n : 0;
                if ((i != 0) && (a == 0)) break;

                x = d; d = n; n = x % n;

                x = a;
                if (k[1] * a + k[0] >= MaximumDenominator)
                {
                    x = (MaximumDenominator - k[0]) / k[1];
                    if (x * 2 >= a || k[1] >= MaximumDenominator)
                        i = 65;
                    else
                        break;
                }

                h[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2];
                k[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2];
            }
            Denominator = k[1];
            Numerator = neg != 0 ? -h[1] : h[1];
        }
        public override string ToString()
        {
            return string.Format("{0} / {1}", Numerator, Denominator);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.OutputEncoding = UTF8Encoding.UTF8;
            foreach (double d in new double[] { 0.9054054, 0.518518, 0.75, 0.4285714, 0.833333,
                0.90909, 3.14159265358979, 2.7182818284590451 })
            {
                var f = new Fraction(d, d >= 2 ? 65536 : 4096);
                Console.WriteLine("{0,20} → {1}", d, f);

            }
        }
    }
}
Task: Convert decimal number to rational





Java: import org.apache.commons.math3.fraction.BigFraction;

public class Test {

    public static void main(String[] args) {
        double[] n = {0.750000000, 0.518518000, 0.905405400, 0.142857143,
            3.141592654, 2.718281828, -0.423310825, 31.415926536};

        for (double d : n)
            System.out.printf("%-12s : %s%n", d, new BigFraction(d, 0.00000002D, 10000));
    }
}
Task: Convert decimal number to rational







Python: >>> from fractions import Fraction
>>> for d in (0.9054054, 0.518518, 0.75): print(d, Fraction.from_float(d).limit_denominator(100))

0.9054054 67/74
0.518518 14/27
0.75 3/4
>>> for d in '0.9054054 0.518518 0.75'.split(): print(d, Fraction(d))

0.9054054 4527027/5000000
0.518518 259259/500000
0.75 3/4
>>>
Task: Convert decimal number to rational








VB: Function Real2Rational(r As Double, bound As Long) As String

If r = 0 Then
    Real2Rational = "0/1"
ElseIf r < 0 Then
    Result = Real2Rational(-r, bound)
    Real2Rational = "-" & Result
Else
    best = 1
    bestError = 1E+99
    For i = 1 To bound + 1
        currentError = Abs(i * r - Round(i * r))
        If currentError < bestError Then
            best = i
            bestError = currentError
            If bestError < 1 / bound Then GoTo SkipLoop
        End If
    Next i
SkipLoop:
    Real2Rational = Round(best * r) & "/" & best
End If
End Function

Sub TestReal2Rational()
Debug.Print "0.75" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(0.75, CLng(Order));
Next i
Debug.Print

Debug.Print "0.518518" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(0.518518, CLng(Order));
Next i
Debug.Print

Debug.Print "0.9054054" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(0.9054054, CLng(Order));
Next i
Debug.Print

Debug.Print "0.142857143" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(0.142857143, CLng(Order));
Next i
Debug.Print

Debug.Print "3.141592654" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(3.141592654, CLng(Order));
Next i
Debug.Print

Debug.Print "2.718281828" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(2.718281828, CLng(Order));
Next i
Debug.Print

Debug.Print "-0.423310825" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(-0.423310825, CLng(Order));
Next i
Debug.Print

Debug.Print "31.415926536" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(31.415926536, CLng(Order));
Next i
End Sub
Task: Convert decimal number to rational




Go: package main

import (
    "fmt"
    "math/big"
)

func main() {
    for _, d := range []string{"0.9054054", "0.518518", "0.75"} {
        if r, ok := new(big.Rat).SetString(d); ok {
            fmt.Println(d, "=", r)
        } else {
            fmt.Println(d, "invalid decimal number")
        }
    }
}
Task: Convert decimal number to rational






PHP: function asRational($val, $tolerance = 1.e-6)
{
    if ($val == (int) $val) {

        return $val;
    }

    $h1=1;
    $h2=0;
    $k1=0;
    $k2=1;
    $b = 1 / $val;

    do {
        $b = 1 / $b;
        $a = floor($b);
        $aux = $h1;
        $h1 = $a * $h1 + $h2;
        $h2 = $aux;
        $aux = $k1;
        $k1 = $a * $k1 + $k2;
        $k2 = $aux;
        $b = $b - $a;
    } while (abs($val-$h1/$k1) > $val * $tolerance);

    return $h1.'/'.$k1;
}
 
echo asRational(1/5)."\n"; // "1/5"
echo asRational(1/4)."\n"; // "1/4"
echo asRational(1/3)."\n"; // "1/3"
echo asRational(5)."\n"; // "5"






Ada: generic
   type Real is digits <>;
procedure Real_To_Rational(R: Real;
                           Bound: Positive;
                           Nominator: out Integer;
                           Denominator: out Positive);
Task: Convert decimal number to rational






PHP: function asRational($val, $tolerance = 1.e-6)
{
    if ($val == (int) $val) {

        return $val;
    }

    $h1=1;
    $h2=0;
    $k1=0;
    $k2=1;
    $b = 1 / $val;

    do {
        $b = 1 / $b;
        $a = floor($b);
        $aux = $h1;
        $h1 = $a * $h1 + $h2;
        $h2 = $aux;
        $aux = $k1;
        $k1 = $a * $k1 + $k2;
        $k2 = $aux;
        $b = $b - $a;
    } while (abs($val-$h1/$k1) > $val * $tolerance);

    return $h1.'/'.$k1;
}
 
echo asRational(1/5)."\n"; // "1/5"
echo asRational(1/4)."\n"; // "1/4"
echo asRational(1/3)."\n"; // "1/3"
echo asRational(5)."\n"; // "5"
Task: Knight's tour



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

namespace prog
{
	class MainClass
	{	
		const int N = 8;
		
		readonly static int[,] moves = { {+1,-2},{+2,-1},{+2,+1},{+1,+2},
			                         {-1,+2},{-2,+1},{-2,-1},{-1,-2} };
		struct ListMoves
		{
			public int x, y;			
			public ListMoves( int _x, int _y ) { x = _x; y = _y; }
		}		
		
		public static void Main (string[] args)
		{
			int[,] board = new int[N,N];
			board.Initialize();
			
			int x = 0,						
			    y = 0;
			
			List<ListMoves> list = new List<ListMoves>(N*N);
			list.Add( new ListMoves(x,y) );
						
			do
			{								
				if ( Move_Possible( board, x, y ) )
				{										
					int move = board[x,y];					
					board[x,y]++;
					x += moves[move,0];
					y += moves[move,1];			
					list.Add( new ListMoves(x,y) );							
				}
				else
				{					
					if ( board[x,y] >= 8 )
					{						
						board[x,y] = 0;																
						list.RemoveAt(list.Count-1);						
						if ( list.Count == 0 )
						{
							Console.WriteLine( "No solution found." );
							return;
						}		
						x = list[list.Count-1].x;
						y = list[list.Count-1].y;						
					}
					board[x,y]++;
				}				
			}
			while( list.Count < N*N );
			
			int last_x = list[0].x,
			    last_y = list[0].y;
			string letters = "ABCDEFGH";
			for( int i=1; i<list.Count; i++ )
			{				
				Console.WriteLine( string.Format("{0,2}:  ", i) + letters[last_x] + (last_y+1) + " - " + letters[list[i].x] + (list[i].y+1) );
				
				last_x = list[i].x;
				last_y = list[i].y;
			}
		}
		
		static bool Move_Possible( int[,] board, int cur_x, int cur_y )
		{			
			if ( board[cur_x,cur_y] >= 8 ) 
				return false;
			
			int new_x = cur_x + moves[board[cur_x,cur_y],0],
			    new_y = cur_y + moves[board[cur_x,cur_y],1];
			
			if ( new_x >= 0 && new_x < N && new_y >= 0 && new_y < N && board[new_x,new_y] == 0 )
				return true;
			
			return false;
		}
	}
}









Ada: generic
   Size: Integer;
package Knights_Tour is
 
   subtype Index is Integer range 1 .. Size;
   type Tour is array  (Index, Index) of Natural;
   Empty: Tour := (others => (others => 0));
   
   function Get_Tour(Start_X, Start_Y: Index; Scene: Tour := Empty) return Tour;
   
   
   
   
   
 
   function Count_Moves(Board: Tour) return Natural;
   
   
   procedure Tour_IO(The_Tour: Tour; Width: Natural := 4);
   
      
end Knights_Tour;
Task: Knight's tour

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

typedef unsigned char cell;
int dx[] = { -2, -2, -1, 1, 2,  2,  1, -1 };
int dy[] = { -1,  1,  2, 2, 1, -1, -2, -2 };

void init_board(int w, int h, cell **a, cell **b)
{
	int i, j, k, x, y, p = w + 4, q = h + 4;
	
	a[0] = (cell*)(a + q);
	b[0] = a[0] + 2;

	for (i = 1; i < q; i++) {
		a[i] = a[i-1] + p;
		b[i] = a[i] + 2;
	}

	memset(a[0], 255, p * q);
	for (i = 0; i < h; i++) {
		for (j = 0; j < w; j++) {
			for (k = 0; k < 8; k++) {
				x = j + dx[k], y = i + dy[k];
				if (b[i+2][j] == 255) b[i+2][j] = 0;
				b[i+2][j] += x >= 0 && x < w && y >= 0 && y < h;
			}
		}
	}
}

#define E "\033["
int walk_board(int w, int h, int x, int y, cell **b)
{
	int i, nx, ny, least;
	int steps = 0;
	printf(E"H"E"J"E"%d;%dH"E"32m[]"E"m", y + 1, 1 + 2 * x);

	while (1) {
		
		b[y][x] = 255;

		
		for (i = 0; i < 8; i++)
			b[ y + dy[i] ][ x + dx[i] ]--;

		
		least = 255;
		for (i = 0; i < 8; i++) {
			if (b[ y + dy[i] ][ x + dx[i] ] < least) {
				nx = x + dx[i];
				ny = y + dy[i];
				least = b[ny][nx];
			}
		}

		if (least > 7) {
			printf(E"%dH", h + 2);
			return steps == w * h - 1;
		}

		if (steps++) printf(E"%d;%dH[]", y + 1, 1 + 2 * x);
		x = nx, y = ny;
		printf(E"%d;%dH"E"31m[]"E"m", y + 1, 1 + 2 * x);
		fflush(stdout);
		usleep(120000);
	}
}

int solve(int w, int h)
{
	int x = 0, y = 0;
	cell **a, **b;
	a = malloc((w + 4) * (h + 4) + sizeof(cell*) * (h + 4));
	b = malloc((h + 4) * sizeof(cell*));

	while (1) {
		init_board(w, h, a, b);
		if (walk_board(w, h, x, y, b + 2)) {
			printf("Success!\n");
			return 1;
		}
		if (++x >= w) x = 0, y++;
		if (y >= h) {
			printf("Failed to find a solution\n");
			return 0;
		}
		printf("Any key to try next start position");
		getchar();
	}
}

int main(int c, char **v)
{
	int w, h;
	if (c < 2 || (w = atoi(v[1])) <= 0) w = 8;
	if (c < 3 || (h = atoi(v[2])) <= 0) h = w;
	solve(w, h);

	return 0;
}











Ada: generic
   Size: Integer;
package Knights_Tour is
 
   subtype Index is Integer range 1 .. Size;
   type Tour is array  (Index, Index) of Natural;
   Empty: Tour := (others => (others => 0));
   
   function Get_Tour(Start_X, Start_Y: Index; Scene: Tour := Empty) return Tour;
   
   
   
   
   
 
   function Count_Moves(Board: Tour) return Natural;
   
   
   procedure Tour_IO(The_Tour: Tour; Width: Natural := 4);
   
      
end Knights_Tour;
Task: Knight's tour




Go: package main

import (
    "fmt"
    "math/rand"
    "time"
)


const startRow = 0
const startCol = 0

func main() {
    rand.Seed(time.Now().Unix())
    for !knightTour() {
    }
}

var moves = []struct{ dr, dc int }{
    {2, 1},
    {2, -1},
    {1, 2},
    {1, -2},
    {-1, 2},
    {-1, -2},
    {-2, 1},
    {-2, -1},
}




func knightTour() bool {
    
    board := make([][]int, 8)
    for i := range board {
        board[i] = make([]int, 8)
    }
    r := startRow
    c := startCol
    board[r][c] = 1 
    for move := 2; move <= 64; move++ {
        minNext := 8
        var mr, mc, nm int
    candidateMoves:
        for _, cm := range moves {
            cr := r + cm.dr
            if cr < 0 || cr >= 8 { 
                continue
            }
            cc := c + cm.dc
            if cc < 0 || cc >= 8 { 
                continue
            }
            if board[cr][cc] > 0 { 
                continue
            }
            
            p := 0 
            for _, m2 := range moves {
                r2 := cr + m2.dr
                if r2 < 0 || r2 >= 8 {
                    continue
                }
                c2 := cc + m2.dc
                if c2 < 0 || c2 >= 8 {
                    continue
                }
                if board[r2][c2] > 0 {
                    continue
                }
                p++
                if p > minNext { 
                    continue candidateMoves
                }
            }
            if p < minNext { 
                minNext = p 
                nm = 1      
                mr = cr     
                mc = cc
                continue
            }
            
            
            nm++                    
            if rand.Intn(nm) == 0 { 
                mr = cr
                mc = cc
            }
        }
        if nm == 0 { 
            return false
        }
        
        r = mr
        c = mc
        board[r][c] = move
    }
    
    for _, r := range board {
        for _, m := range r {
            fmt.Printf("%3d", m)
        }
        fmt.Println()
    }
    return true
}








Ada: generic
   Size: Integer;
package Knights_Tour is
 
   subtype Index is Integer range 1 .. Size;
   type Tour is array  (Index, Index) of Natural;
   Empty: Tour := (others => (others => 0));
   
   function Get_Tour(Start_X, Start_Y: Index; Scene: Tour := Empty) return Tour;
   
   
   
   
   
 
   function Count_Moves(Board: Tour) return Natural;
   
   
   procedure Tour_IO(The_Tour: Tour; Width: Natural := 4);
   
      
end Knights_Tour;
Task: Knight's tour





Java: import java.util.*;

public class KnightsTour {
    private final static int base = 12;
    private final static int[][] moves = {{1,-2},{2,-1},{2,1},{1,2},{-1,2},
        {-2,1},{-2,-1},{-1,-2}};
    private static int[][] grid;
    private static int total;

    public static void main(String[] args) {
        grid = new int[base][base];
        total = (base - 4) * (base - 4);

        for (int r = 0; r < base; r++)
            for (int c = 0; c < base; c++)
                if (r < 2 || r > base - 3 || c < 2 || c > base - 3)
                    grid[r][c] = -1;

        int row = 2 + (int) (Math.random() * (base - 4));
        int col = 2 + (int) (Math.random() * (base - 4));

        grid[row][col] = 1;

        if (solve(row, col, 2))
            printResult();
        else System.out.println("no result");

    }

    private static boolean solve(int r, int c, int count) {
        if (count > total)
            return true;

        List<int[]> nbrs = neighbors(r, c);

        if (nbrs.isEmpty() && count != total)
            return false;

        Collections.sort(nbrs, new Comparator<int[]>() {
            public int compare(int[] a, int[] b) {
                return a[2] - b[2];
            }
        });

        for (int[] nb : nbrs) {
            r = nb[0];
            c = nb[1];
            grid[r][c] = count;
            if (!orphanDetected(count, r, c) && solve(r, c, count + 1))
                return true;
            grid[r][c] = 0;
        }

        return false;
    }

    private static List<int[]> neighbors(int r, int c) {
        List<int[]> nbrs = new ArrayList<>();

        for (int[] m : moves) {
            int x = m[0];
            int y = m[1];
            if (grid[r + y][c + x] == 0) {
                int num = countNeighbors(r + y, c + x);
                nbrs.add(new int[]{r + y, c + x, num});
            }
        }
        return nbrs;
    }

    private static int countNeighbors(int r, int c) {
        int num = 0;
        for (int[] m : moves)
            if (grid[r + m[1]][c + m[0]] == 0)
                num++;
        return num;
    }

    private static boolean orphanDetected(int cnt, int r, int c) {
        if (cnt < total - 1) {
            List<int[]> nbrs = neighbors(r, c);
            for (int[] nb : nbrs)
                if (countNeighbors(nb[0], nb[1]) == 0)
                    return true;
        }
        return false;
    }

    private static void printResult() {
        for (int[] row : grid) {
            for (int i : row) {
                if (i == -1) continue;
                System.out.printf("%2d ", i);
            }
            System.out.println();
        }
    }
}







Ada: generic
   Size: Integer;
package Knights_Tour is
 
   subtype Index is Integer range 1 .. Size;
   type Tour is array  (Index, Index) of Natural;
   Empty: Tour := (others => (others => 0));
   
   function Get_Tour(Start_X, Start_Y: Index; Scene: Tour := Empty) return Tour;
   
   
   
   
   
 
   function Count_Moves(Board: Tour) return Natural;
   
   
   procedure Tour_IO(The_Tour: Tour; Width: Natural := 4);
   
      
end Knights_Tour;