Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Please provide an equivalent version of this Scala code in C#.
fun indexOf(n: Int, s: IntArray): Int { for (i_j in s.withIndex()) { if (n == i_j.value) { return i_j.index } } return -1 } fun getDigits(n: Int, le: Int, digits: IntArray): Boolean { var mn = n var mle = le while (mn > 0) { val r = mn % 10 if (r == 0 || indexOf(r, digits) >= 0) { return false } mle-- digits[mle] = r mn /= 10 } return true } val pows = intArrayOf(1, 10, 100, 1_000, 10_000) fun removeDigit(digits: IntArray, le: Int, idx: Int): Int { var sum = 0 var pow = pows[le - 2] for (i in 0 until le) { if (i == idx) { continue } sum += digits[i] * pow pow /= 10 } return sum } fun main() { val lims = listOf( Pair(12, 97), Pair(123, 986), Pair(1234, 9875), Pair(12345, 98764) ) val count = IntArray(5) var omitted = arrayOf<Array<Int>>() for (i in 0 until 5) { var array = arrayOf<Int>() for (j in 0 until 10) { array += 0 } omitted += array } for (i_lim in lims.withIndex()) { val i = i_lim.index val lim = i_lim.value val nDigits = IntArray(i + 2) val dDigits = IntArray(i + 2) val blank = IntArray(i + 2) { 0 } for (n in lim.first..lim.second) { blank.copyInto(nDigits) val nOk = getDigits(n, i + 2, nDigits) if (!nOk) { continue } for (d in n + 1..lim.second + 1) { blank.copyInto(dDigits) val dOk = getDigits(d, i + 2, dDigits) if (!dOk) { continue } for (nix_digit in nDigits.withIndex()) { val dix = indexOf(nix_digit.value, dDigits) if (dix >= 0) { val rn = removeDigit(nDigits, i + 2, nix_digit.index) val rd = removeDigit(dDigits, i + 2, dix) if (n.toDouble() / d.toDouble() == rn.toDouble() / rd.toDouble()) { count[i]++ omitted[i][nix_digit.value]++ if (count[i] <= 12) { println("$n/$d = $rn/$rd by omitting ${nix_digit.value}'s") } } } } } } println() } for (i in 2..5) { println("There are ${count[i - 2]} $i-digit fractions of which:") for (j in 1..9) { if (omitted[i - 2][j] == 0) { continue } println("%6d have %d's omitted".format(omitted[i - 2][j], j)) } println() } }
using System; namespace FractionReduction { class Program { static int IndexOf(int n, int[] s) { for (int i = 0; i < s.Length; i++) { if (s[i] == n) { return i; } } return -1; } static bool GetDigits(int n, int le, int[] digits) { while (n > 0) { var r = n % 10; if (r == 0 || IndexOf(r, digits) >= 0) { return false; } le--; digits[le] = r; n /= 10; } return true; } static int RemoveDigit(int[] digits, int le, int idx) { int[] pows = { 1, 10, 100, 1000, 10000 }; var sum = 0; var pow = pows[le - 2]; for (int i = 0; i < le; i++) { if (i == idx) continue; sum += digits[i] * pow; pow /= 10; } return sum; } static void Main() { var lims = new int[,] { { 12, 97 }, { 123, 986 }, { 1234, 9875 }, { 12345, 98764 } }; var count = new int[5]; var omitted = new int[5, 10]; var upperBound = lims.GetLength(0); for (int i = 0; i < upperBound; i++) { var nDigits = new int[i + 2]; var dDigits = new int[i + 2]; var blank = new int[i + 2]; for (int n = lims[i, 0]; n <= lims[i, 1]; n++) { blank.CopyTo(nDigits, 0); var nOk = GetDigits(n, i + 2, nDigits); if (!nOk) { continue; } for (int d = n + 1; d <= lims[i, 1] + 1; d++) { blank.CopyTo(dDigits, 0); var dOk = GetDigits(d, i + 2, dDigits); if (!dOk) { continue; } for (int nix = 0; nix < nDigits.Length; nix++) { var digit = nDigits[nix]; var dix = IndexOf(digit, dDigits); if (dix >= 0) { var rn = RemoveDigit(nDigits, i + 2, nix); var rd = RemoveDigit(dDigits, i + 2, dix); if ((double)n / d == (double)rn / rd) { count[i]++; omitted[i, digit]++; if (count[i] <= 12) { Console.WriteLine("{0}/{1} = {2}/{3} by omitting {4}'s", n, d, rn, rd, digit); } } } } } } Console.WriteLine(); } for (int i = 2; i <= 5; i++) { Console.WriteLine("There are {0} {1}-digit fractions of which:", count[i - 2], i); for (int j = 1; j <= 9; j++) { if (omitted[i - 2, j] == 0) { continue; } Console.WriteLine("{0,6} have {1}'s omitted", omitted[i - 2, j], j); } Console.WriteLine(); } } } }
Transform the following Scala implementation into C++, maintaining the same output and logic.
fun indexOf(n: Int, s: IntArray): Int { for (i_j in s.withIndex()) { if (n == i_j.value) { return i_j.index } } return -1 } fun getDigits(n: Int, le: Int, digits: IntArray): Boolean { var mn = n var mle = le while (mn > 0) { val r = mn % 10 if (r == 0 || indexOf(r, digits) >= 0) { return false } mle-- digits[mle] = r mn /= 10 } return true } val pows = intArrayOf(1, 10, 100, 1_000, 10_000) fun removeDigit(digits: IntArray, le: Int, idx: Int): Int { var sum = 0 var pow = pows[le - 2] for (i in 0 until le) { if (i == idx) { continue } sum += digits[i] * pow pow /= 10 } return sum } fun main() { val lims = listOf( Pair(12, 97), Pair(123, 986), Pair(1234, 9875), Pair(12345, 98764) ) val count = IntArray(5) var omitted = arrayOf<Array<Int>>() for (i in 0 until 5) { var array = arrayOf<Int>() for (j in 0 until 10) { array += 0 } omitted += array } for (i_lim in lims.withIndex()) { val i = i_lim.index val lim = i_lim.value val nDigits = IntArray(i + 2) val dDigits = IntArray(i + 2) val blank = IntArray(i + 2) { 0 } for (n in lim.first..lim.second) { blank.copyInto(nDigits) val nOk = getDigits(n, i + 2, nDigits) if (!nOk) { continue } for (d in n + 1..lim.second + 1) { blank.copyInto(dDigits) val dOk = getDigits(d, i + 2, dDigits) if (!dOk) { continue } for (nix_digit in nDigits.withIndex()) { val dix = indexOf(nix_digit.value, dDigits) if (dix >= 0) { val rn = removeDigit(nDigits, i + 2, nix_digit.index) val rd = removeDigit(dDigits, i + 2, dix) if (n.toDouble() / d.toDouble() == rn.toDouble() / rd.toDouble()) { count[i]++ omitted[i][nix_digit.value]++ if (count[i] <= 12) { println("$n/$d = $rn/$rd by omitting ${nix_digit.value}'s") } } } } } } println() } for (i in 2..5) { println("There are ${count[i - 2]} $i-digit fractions of which:") for (j in 1..9) { if (omitted[i - 2][j] == 0) { continue } println("%6d have %d's omitted".format(omitted[i - 2][j], j)) } println() } }
#include <array> #include <iomanip> #include <iostream> #include <vector> int indexOf(const std::vector<int> &haystack, int needle) { auto it = haystack.cbegin(); auto end = haystack.cend(); int idx = 0; for (; it != end; it = std::next(it)) { if (*it == needle) { return idx; } idx++; } return -1; } bool getDigits(int n, int le, std::vector<int> &digits) { while (n > 0) { auto r = n % 10; if (r == 0 || indexOf(digits, r) >= 0) { return false; } le--; digits[le] = r; n /= 10; } return true; } int removeDigit(const std::vector<int> &digits, int le, int idx) { static std::array<int, 5> pows = { 1, 10, 100, 1000, 10000 }; int sum = 0; auto pow = pows[le - 2]; for (int i = 0; i < le; i++) { if (i == idx) continue; sum += digits[i] * pow; pow /= 10; } return sum; } int main() { std::vector<std::pair<int, int>> lims = { {12, 97}, {123, 986}, {1234, 9875}, {12345, 98764} }; std::array<int, 5> count; std::array<std::array<int, 10>, 5> omitted; std::fill(count.begin(), count.end(), 0); std::for_each(omitted.begin(), omitted.end(), [](auto &a) { std::fill(a.begin(), a.end(), 0); } ); for (size_t i = 0; i < lims.size(); i++) { std::vector<int> nDigits(i + 2); std::vector<int> dDigits(i + 2); for (int n = lims[i].first; n <= lims[i].second; n++) { std::fill(nDigits.begin(), nDigits.end(), 0); bool nOk = getDigits(n, i + 2, nDigits); if (!nOk) { continue; } for (int d = n + 1; d <= lims[i].second + 1; d++) { std::fill(dDigits.begin(), dDigits.end(), 0); bool dOk = getDigits(d, i + 2, dDigits); if (!dOk) { continue; } for (size_t nix = 0; nix < nDigits.size(); nix++) { auto digit = nDigits[nix]; auto dix = indexOf(dDigits, digit); if (dix >= 0) { auto rn = removeDigit(nDigits, i + 2, nix); auto rd = removeDigit(dDigits, i + 2, dix); if ((double)n / d == (double)rn / rd) { count[i]++; omitted[i][digit]++; if (count[i] <= 12) { std::cout << n << '/' << d << " = " << rn << '/' << rd << " by omitting " << digit << "'s\n"; } } } } } } std::cout << '\n'; } for (int i = 2; i <= 5; i++) { std::cout << "There are " << count[i - 2] << ' ' << i << "-digit fractions of which:\n"; for (int j = 1; j <= 9; j++) { if (omitted[i - 2][j] == 0) { continue; } std::cout << std::setw(6) << omitted[i - 2][j] << " have " << j << "'s omitted\n"; } std::cout << '\n'; } return 0; }
Translate the given Scala code snippet into Java without altering its behavior.
fun indexOf(n: Int, s: IntArray): Int { for (i_j in s.withIndex()) { if (n == i_j.value) { return i_j.index } } return -1 } fun getDigits(n: Int, le: Int, digits: IntArray): Boolean { var mn = n var mle = le while (mn > 0) { val r = mn % 10 if (r == 0 || indexOf(r, digits) >= 0) { return false } mle-- digits[mle] = r mn /= 10 } return true } val pows = intArrayOf(1, 10, 100, 1_000, 10_000) fun removeDigit(digits: IntArray, le: Int, idx: Int): Int { var sum = 0 var pow = pows[le - 2] for (i in 0 until le) { if (i == idx) { continue } sum += digits[i] * pow pow /= 10 } return sum } fun main() { val lims = listOf( Pair(12, 97), Pair(123, 986), Pair(1234, 9875), Pair(12345, 98764) ) val count = IntArray(5) var omitted = arrayOf<Array<Int>>() for (i in 0 until 5) { var array = arrayOf<Int>() for (j in 0 until 10) { array += 0 } omitted += array } for (i_lim in lims.withIndex()) { val i = i_lim.index val lim = i_lim.value val nDigits = IntArray(i + 2) val dDigits = IntArray(i + 2) val blank = IntArray(i + 2) { 0 } for (n in lim.first..lim.second) { blank.copyInto(nDigits) val nOk = getDigits(n, i + 2, nDigits) if (!nOk) { continue } for (d in n + 1..lim.second + 1) { blank.copyInto(dDigits) val dOk = getDigits(d, i + 2, dDigits) if (!dOk) { continue } for (nix_digit in nDigits.withIndex()) { val dix = indexOf(nix_digit.value, dDigits) if (dix >= 0) { val rn = removeDigit(nDigits, i + 2, nix_digit.index) val rd = removeDigit(dDigits, i + 2, dix) if (n.toDouble() / d.toDouble() == rn.toDouble() / rd.toDouble()) { count[i]++ omitted[i][nix_digit.value]++ if (count[i] <= 12) { println("$n/$d = $rn/$rd by omitting ${nix_digit.value}'s") } } } } } } println() } for (i in 2..5) { println("There are ${count[i - 2]} $i-digit fractions of which:") for (j in 1..9) { if (omitted[i - 2][j] == 0) { continue } println("%6d have %d's omitted".format(omitted[i - 2][j], j)) } println() } }
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class FractionReduction { public static void main(String[] args) { for ( int size = 2 ; size <= 5 ; size++ ) { reduce(size); } } private static void reduce(int numDigits) { System.out.printf("Fractions with digits of length %d where cancellation is valid. Examples:%n", numDigits); int min = (int) Math.pow(10, numDigits-1); int max = (int) Math.pow(10, numDigits) - 1; List<Integer> values = new ArrayList<>(); for ( int number = min ; number <= max ; number++ ) { if ( isValid(number) ) { values.add(number); } } Map<Integer,Integer> cancelCount = new HashMap<>(); int size = values.size(); int solutions = 0; for ( int nIndex = 0 ; nIndex < size - 1 ; nIndex++ ) { int numerator = values.get(nIndex); for ( int dIndex = nIndex + 1 ; dIndex < size ; dIndex++ ) { int denominator = values.get(dIndex); for ( int commonDigit : digitsInCommon(numerator, denominator) ) { int numRemoved = removeDigit(numerator, commonDigit); int denRemoved = removeDigit(denominator, commonDigit); if ( numerator * denRemoved == denominator * numRemoved ) { solutions++; cancelCount.merge(commonDigit, 1, (v1, v2) -> v1 + v2); if ( solutions <= 12 ) { System.out.printf(" When %d is removed, %d/%d = %d/%d%n", commonDigit, numerator, denominator, numRemoved, denRemoved); } } } } } System.out.printf("Number of fractions where cancellation is valid = %d.%n", solutions); List<Integer> sorted = new ArrayList<>(cancelCount.keySet()); Collections.sort(sorted); for ( int removed : sorted ) { System.out.printf(" The digit %d was removed %d times.%n", removed, cancelCount.get(removed)); } System.out.println(); } private static int[] powers = new int[] {1, 10, 100, 1000, 10000, 100000}; private static int removeDigit(int n, int removed) { int m = 0; int pow = 0; while ( n > 0 ) { int r = n % 10; if ( r != removed ) { m = m + r*powers[pow]; pow++; } n /= 10; } return m; } private static List<Integer> digitsInCommon(int n1, int n2) { int[] count = new int[10]; List<Integer> common = new ArrayList<>(); while ( n1 > 0 ) { int r = n1 % 10; count[r] += 1; n1 /= 10; } while ( n2 > 0 ) { int r = n2 % 10; if ( count[r] > 0 ) { common.add(r); } n2 /= 10; } return common; } private static boolean isValid(int num) { int[] count = new int[10]; while ( num > 0 ) { int r = num % 10; if ( r == 0 || count[r] == 1 ) { return false; } count[r] = 1; num /= 10; } return true; } }
Keep all operations the same but rewrite the snippet in Python.
fun indexOf(n: Int, s: IntArray): Int { for (i_j in s.withIndex()) { if (n == i_j.value) { return i_j.index } } return -1 } fun getDigits(n: Int, le: Int, digits: IntArray): Boolean { var mn = n var mle = le while (mn > 0) { val r = mn % 10 if (r == 0 || indexOf(r, digits) >= 0) { return false } mle-- digits[mle] = r mn /= 10 } return true } val pows = intArrayOf(1, 10, 100, 1_000, 10_000) fun removeDigit(digits: IntArray, le: Int, idx: Int): Int { var sum = 0 var pow = pows[le - 2] for (i in 0 until le) { if (i == idx) { continue } sum += digits[i] * pow pow /= 10 } return sum } fun main() { val lims = listOf( Pair(12, 97), Pair(123, 986), Pair(1234, 9875), Pair(12345, 98764) ) val count = IntArray(5) var omitted = arrayOf<Array<Int>>() for (i in 0 until 5) { var array = arrayOf<Int>() for (j in 0 until 10) { array += 0 } omitted += array } for (i_lim in lims.withIndex()) { val i = i_lim.index val lim = i_lim.value val nDigits = IntArray(i + 2) val dDigits = IntArray(i + 2) val blank = IntArray(i + 2) { 0 } for (n in lim.first..lim.second) { blank.copyInto(nDigits) val nOk = getDigits(n, i + 2, nDigits) if (!nOk) { continue } for (d in n + 1..lim.second + 1) { blank.copyInto(dDigits) val dOk = getDigits(d, i + 2, dDigits) if (!dOk) { continue } for (nix_digit in nDigits.withIndex()) { val dix = indexOf(nix_digit.value, dDigits) if (dix >= 0) { val rn = removeDigit(nDigits, i + 2, nix_digit.index) val rd = removeDigit(dDigits, i + 2, dix) if (n.toDouble() / d.toDouble() == rn.toDouble() / rd.toDouble()) { count[i]++ omitted[i][nix_digit.value]++ if (count[i] <= 12) { println("$n/$d = $rn/$rd by omitting ${nix_digit.value}'s") } } } } } } println() } for (i in 2..5) { println("There are ${count[i - 2]} $i-digit fractions of which:") for (j in 1..9) { if (omitted[i - 2][j] == 0) { continue } println("%6d have %d's omitted".format(omitted[i - 2][j], j)) } println() } }
def indexOf(haystack, needle): idx = 0 for straw in haystack: if straw == needle: return idx else: idx += 1 return -1 def getDigits(n, le, digits): while n > 0: r = n % 10 if r == 0 or indexOf(digits, r) >= 0: return False le -= 1 digits[le] = r n = int(n / 10) return True def removeDigit(digits, le, idx): pows = [1, 10, 100, 1000, 10000] sum = 0 pow = pows[le - 2] i = 0 while i < le: if i == idx: i += 1 continue sum = sum + digits[i] * pow pow = int(pow / 10) i += 1 return sum def main(): lims = [ [ 12, 97 ], [ 123, 986 ], [ 1234, 9875 ], [ 12345, 98764 ] ] count = [0 for i in range(5)] omitted = [[0 for i in range(10)] for j in range(5)] i = 0 while i < len(lims): n = lims[i][0] while n < lims[i][1]: nDigits = [0 for k in range(i + 2)] nOk = getDigits(n, i + 2, nDigits) if not nOk: n += 1 continue d = n + 1 while d <= lims[i][1] + 1: dDigits = [0 for k in range(i + 2)] dOk = getDigits(d, i + 2, dDigits) if not dOk: d += 1 continue nix = 0 while nix < len(nDigits): digit = nDigits[nix] dix = indexOf(dDigits, digit) if dix >= 0: rn = removeDigit(nDigits, i + 2, nix) rd = removeDigit(dDigits, i + 2, dix) if (1.0 * n / d) == (1.0 * rn / rd): count[i] += 1 omitted[i][digit] += 1 if count[i] <= 12: print "%d/%d = %d/%d by omitting %d's" % (n, d, rn, rd, digit) nix += 1 d += 1 n += 1 print i += 1 i = 2 while i <= 5: print "There are %d %d-digit fractions of which:" % (count[i - 2], i) j = 1 while j <= 9: if omitted[i - 2][j] == 0: j += 1 continue print "%6s have %d's omitted" % (omitted[i - 2][j], j) j += 1 print i += 1 return None main()
Produce a functionally identical VB code for the snippet given in Scala.
fun indexOf(n: Int, s: IntArray): Int { for (i_j in s.withIndex()) { if (n == i_j.value) { return i_j.index } } return -1 } fun getDigits(n: Int, le: Int, digits: IntArray): Boolean { var mn = n var mle = le while (mn > 0) { val r = mn % 10 if (r == 0 || indexOf(r, digits) >= 0) { return false } mle-- digits[mle] = r mn /= 10 } return true } val pows = intArrayOf(1, 10, 100, 1_000, 10_000) fun removeDigit(digits: IntArray, le: Int, idx: Int): Int { var sum = 0 var pow = pows[le - 2] for (i in 0 until le) { if (i == idx) { continue } sum += digits[i] * pow pow /= 10 } return sum } fun main() { val lims = listOf( Pair(12, 97), Pair(123, 986), Pair(1234, 9875), Pair(12345, 98764) ) val count = IntArray(5) var omitted = arrayOf<Array<Int>>() for (i in 0 until 5) { var array = arrayOf<Int>() for (j in 0 until 10) { array += 0 } omitted += array } for (i_lim in lims.withIndex()) { val i = i_lim.index val lim = i_lim.value val nDigits = IntArray(i + 2) val dDigits = IntArray(i + 2) val blank = IntArray(i + 2) { 0 } for (n in lim.first..lim.second) { blank.copyInto(nDigits) val nOk = getDigits(n, i + 2, nDigits) if (!nOk) { continue } for (d in n + 1..lim.second + 1) { blank.copyInto(dDigits) val dOk = getDigits(d, i + 2, dDigits) if (!dOk) { continue } for (nix_digit in nDigits.withIndex()) { val dix = indexOf(nix_digit.value, dDigits) if (dix >= 0) { val rn = removeDigit(nDigits, i + 2, nix_digit.index) val rd = removeDigit(dDigits, i + 2, dix) if (n.toDouble() / d.toDouble() == rn.toDouble() / rd.toDouble()) { count[i]++ omitted[i][nix_digit.value]++ if (count[i] <= 12) { println("$n/$d = $rn/$rd by omitting ${nix_digit.value}'s") } } } } } } println() } for (i in 2..5) { println("There are ${count[i - 2]} $i-digit fractions of which:") for (j in 1..9) { if (omitted[i - 2][j] == 0) { continue } println("%6d have %d's omitted".format(omitted[i - 2][j], j)) } println() } }
Module Module1 Function IndexOf(n As Integer, s As Integer()) As Integer For ii = 1 To s.Length Dim i = ii - 1 If s(i) = n Then Return i End If Next Return -1 End Function Function GetDigits(n As Integer, le As Integer, digits As Integer()) As Boolean While n > 0 Dim r = n Mod 10 If r = 0 OrElse IndexOf(r, digits) >= 0 Then Return False End If le -= 1 digits(le) = r n \= 10 End While Return True End Function Function RemoveDigit(digits As Integer(), le As Integer, idx As Integer) As Integer Dim pows = {1, 10, 100, 1000, 10000} Dim sum = 0 Dim pow = pows(le - 2) For ii = 1 To le Dim i = ii - 1 If i = idx Then Continue For End If sum += digits(i) * pow pow \= 10 Next Return sum End Function Sub Main() Dim lims = {{12, 97}, {123, 986}, {1234, 9875}, {12345, 98764}} Dim count(5) As Integer Dim omitted(5, 10) As Integer Dim upperBound = lims.GetLength(0) For ii = 1 To upperBound Dim i = ii - 1 Dim nDigits(i + 2 - 1) As Integer Dim dDigits(i + 2 - 1) As Integer Dim blank(i + 2 - 1) As Integer For n = lims(i, 0) To lims(i, 1) blank.CopyTo(nDigits, 0) Dim nOk = GetDigits(n, i + 2, nDigits) If Not nOk Then Continue For End If For d = n + 1 To lims(i, 1) + 1 blank.CopyTo(dDigits, 0) Dim dOk = GetDigits(d, i + 2, dDigits) If Not dOk Then Continue For End If For nixt = 1 To nDigits.Length Dim nix = nixt - 1 Dim digit = nDigits(nix) Dim dix = IndexOf(digit, dDigits) If dix >= 0 Then Dim rn = RemoveDigit(nDigits, i + 2, nix) Dim rd = RemoveDigit(dDigits, i + 2, dix) If (n / d) = (rn / rd) Then count(i) += 1 omitted(i, digit) += 1 If count(i) <= 12 Then Console.WriteLine("{0}/{1} = {2}/{3} by omitting {4} End If End If End If Next Next Next Console.WriteLine() Next For i = 2 To 5 Console.WriteLine("There are {0} {1}-digit fractions of which:", count(i - 2), i) For j = 1 To 9 If omitted(i - 2, j) = 0 Then Continue For End If Console.WriteLine("{0,6} have {1} Next Console.WriteLine() Next End Sub End Module
Can you help me rewrite this code in Go instead of Scala, keeping it the same logically?
fun indexOf(n: Int, s: IntArray): Int { for (i_j in s.withIndex()) { if (n == i_j.value) { return i_j.index } } return -1 } fun getDigits(n: Int, le: Int, digits: IntArray): Boolean { var mn = n var mle = le while (mn > 0) { val r = mn % 10 if (r == 0 || indexOf(r, digits) >= 0) { return false } mle-- digits[mle] = r mn /= 10 } return true } val pows = intArrayOf(1, 10, 100, 1_000, 10_000) fun removeDigit(digits: IntArray, le: Int, idx: Int): Int { var sum = 0 var pow = pows[le - 2] for (i in 0 until le) { if (i == idx) { continue } sum += digits[i] * pow pow /= 10 } return sum } fun main() { val lims = listOf( Pair(12, 97), Pair(123, 986), Pair(1234, 9875), Pair(12345, 98764) ) val count = IntArray(5) var omitted = arrayOf<Array<Int>>() for (i in 0 until 5) { var array = arrayOf<Int>() for (j in 0 until 10) { array += 0 } omitted += array } for (i_lim in lims.withIndex()) { val i = i_lim.index val lim = i_lim.value val nDigits = IntArray(i + 2) val dDigits = IntArray(i + 2) val blank = IntArray(i + 2) { 0 } for (n in lim.first..lim.second) { blank.copyInto(nDigits) val nOk = getDigits(n, i + 2, nDigits) if (!nOk) { continue } for (d in n + 1..lim.second + 1) { blank.copyInto(dDigits) val dOk = getDigits(d, i + 2, dDigits) if (!dOk) { continue } for (nix_digit in nDigits.withIndex()) { val dix = indexOf(nix_digit.value, dDigits) if (dix >= 0) { val rn = removeDigit(nDigits, i + 2, nix_digit.index) val rd = removeDigit(dDigits, i + 2, dix) if (n.toDouble() / d.toDouble() == rn.toDouble() / rd.toDouble()) { count[i]++ omitted[i][nix_digit.value]++ if (count[i] <= 12) { println("$n/$d = $rn/$rd by omitting ${nix_digit.value}'s") } } } } } } println() } for (i in 2..5) { println("There are ${count[i - 2]} $i-digit fractions of which:") for (j in 1..9) { if (omitted[i - 2][j] == 0) { continue } println("%6d have %d's omitted".format(omitted[i - 2][j], j)) } println() } }
package main import ( "fmt" "time" ) func indexOf(n int, s []int) int { for i, j := range s { if n == j { return i } } return -1 } func getDigits(n, le int, digits []int) bool { for n > 0 { r := n % 10 if r == 0 || indexOf(r, digits) >= 0 { return false } le-- digits[le] = r n /= 10 } return true } var pows = [5]int{1, 10, 100, 1000, 10000} func removeDigit(digits []int, le, idx int) int { sum := 0 pow := pows[le-2] for i := 0; i < le; i++ { if i == idx { continue } sum += digits[i] * pow pow /= 10 } return sum } func main() { start := time.Now() lims := [5][2]int{ {12, 97}, {123, 986}, {1234, 9875}, {12345, 98764}, {123456, 987653}, } var count [5]int var omitted [5][10]int for i, lim := range lims { nDigits := make([]int, i+2) dDigits := make([]int, i+2) blank := make([]int, i+2) for n := lim[0]; n <= lim[1]; n++ { copy(nDigits, blank) nOk := getDigits(n, i+2, nDigits) if !nOk { continue } for d := n + 1; d <= lim[1]+1; d++ { copy(dDigits, blank) dOk := getDigits(d, i+2, dDigits) if !dOk { continue } for nix, digit := range nDigits { if dix := indexOf(digit, dDigits); dix >= 0 { rn := removeDigit(nDigits, i+2, nix) rd := removeDigit(dDigits, i+2, dix) if float64(n)/float64(d) == float64(rn)/float64(rd) { count[i]++ omitted[i][digit]++ if count[i] <= 12 { fmt.Printf("%d/%d = %d/%d by omitting %d's\n", n, d, rn, rd, digit) } } } } } } fmt.Println() } for i := 2; i <= 6; i++ { fmt.Printf("There are %d %d-digit fractions of which:\n", count[i-2], i) for j := 1; j <= 9; j++ { if omitted[i-2][j] == 0 { continue } fmt.Printf("%6d have %d's omitted\n", omitted[i-2][j], j) } fmt.Println() } fmt.Printf("Took %s\n", time.Since(start)) }
Convert this Ada block to C#, preserving its control flow and logic.
with Knights_Tour, Ada.Text_IO, Ada.Command_Line; procedure Holy_Knight is Size: Positive := Positive'Value(Ada.Command_Line.Argument(1)); package KT is new Knights_Tour(Size => Size); Board: KT.Tour := (others => (others => Natural'Last)); Start_X, Start_Y: KT.Index:= 1; S: String(KT.Index); I: Positive := KT.Index'First; begin while not Ada.Text_IO.End_Of_File and I <= Size loop S := Ada.Text_IO.Get_Line; for J in KT.Index loop if S(J) = ' ' or S(J) = '-' then Board(I,J) := Natural'Last; elsif S(J) = '1' then Start_X := I; Start_Y := J; Board(I,J) := 1; else Board(I,J) := 0; end if; end loop; I := I + 1; end loop; Ada.Text_IO.Put_Line("Start Configuration (Length:" & Natural'Image(KT.Count_Moves(Board)) & "):"); KT.Tour_IO(Board, Width => 1); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line("Tour:"); KT.Tour_IO(KT.Warnsdorff_Get_Tour(Start_X, Start_Y, Board)); end Holy_Knight;
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Write a version of this Ada function in C# with identical behavior.
with Knights_Tour, Ada.Text_IO, Ada.Command_Line; procedure Holy_Knight is Size: Positive := Positive'Value(Ada.Command_Line.Argument(1)); package KT is new Knights_Tour(Size => Size); Board: KT.Tour := (others => (others => Natural'Last)); Start_X, Start_Y: KT.Index:= 1; S: String(KT.Index); I: Positive := KT.Index'First; begin while not Ada.Text_IO.End_Of_File and I <= Size loop S := Ada.Text_IO.Get_Line; for J in KT.Index loop if S(J) = ' ' or S(J) = '-' then Board(I,J) := Natural'Last; elsif S(J) = '1' then Start_X := I; Start_Y := J; Board(I,J) := 1; else Board(I,J) := 0; end if; end loop; I := I + 1; end loop; Ada.Text_IO.Put_Line("Start Configuration (Length:" & Natural'Image(KT.Count_Moves(Board)) & "):"); KT.Tour_IO(Board, Width => 1); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line("Tour:"); KT.Tour_IO(KT.Warnsdorff_Get_Tour(Start_X, Start_Y, Board)); end Holy_Knight;
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Convert this Ada snippet to C++ and keep its semantics consistent.
with Knights_Tour, Ada.Text_IO, Ada.Command_Line; procedure Holy_Knight is Size: Positive := Positive'Value(Ada.Command_Line.Argument(1)); package KT is new Knights_Tour(Size => Size); Board: KT.Tour := (others => (others => Natural'Last)); Start_X, Start_Y: KT.Index:= 1; S: String(KT.Index); I: Positive := KT.Index'First; begin while not Ada.Text_IO.End_Of_File and I <= Size loop S := Ada.Text_IO.Get_Line; for J in KT.Index loop if S(J) = ' ' or S(J) = '-' then Board(I,J) := Natural'Last; elsif S(J) = '1' then Start_X := I; Start_Y := J; Board(I,J) := 1; else Board(I,J) := 0; end if; end loop; I := I + 1; end loop; Ada.Text_IO.Put_Line("Start Configuration (Length:" & Natural'Image(KT.Count_Moves(Board)) & "):"); KT.Tour_IO(Board, Width => 1); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line("Tour:"); KT.Tour_IO(KT.Warnsdorff_Get_Tour(Start_X, Start_Y, Board)); end Holy_Knight;
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Can you help me rewrite this code in C++ instead of Ada, keeping it the same logically?
with Knights_Tour, Ada.Text_IO, Ada.Command_Line; procedure Holy_Knight is Size: Positive := Positive'Value(Ada.Command_Line.Argument(1)); package KT is new Knights_Tour(Size => Size); Board: KT.Tour := (others => (others => Natural'Last)); Start_X, Start_Y: KT.Index:= 1; S: String(KT.Index); I: Positive := KT.Index'First; begin while not Ada.Text_IO.End_Of_File and I <= Size loop S := Ada.Text_IO.Get_Line; for J in KT.Index loop if S(J) = ' ' or S(J) = '-' then Board(I,J) := Natural'Last; elsif S(J) = '1' then Start_X := I; Start_Y := J; Board(I,J) := 1; else Board(I,J) := 0; end if; end loop; I := I + 1; end loop; Ada.Text_IO.Put_Line("Start Configuration (Length:" & Natural'Image(KT.Count_Moves(Board)) & "):"); KT.Tour_IO(Board, Width => 1); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line("Tour:"); KT.Tour_IO(KT.Warnsdorff_Get_Tour(Start_X, Start_Y, Board)); end Holy_Knight;
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Generate a Go translation of this Ada snippet without changing its computational steps.
with Knights_Tour, Ada.Text_IO, Ada.Command_Line; procedure Holy_Knight is Size: Positive := Positive'Value(Ada.Command_Line.Argument(1)); package KT is new Knights_Tour(Size => Size); Board: KT.Tour := (others => (others => Natural'Last)); Start_X, Start_Y: KT.Index:= 1; S: String(KT.Index); I: Positive := KT.Index'First; begin while not Ada.Text_IO.End_Of_File and I <= Size loop S := Ada.Text_IO.Get_Line; for J in KT.Index loop if S(J) = ' ' or S(J) = '-' then Board(I,J) := Natural'Last; elsif S(J) = '1' then Start_X := I; Start_Y := J; Board(I,J) := 1; else Board(I,J) := 0; end if; end loop; I := I + 1; end loop; Ada.Text_IO.Put_Line("Start Configuration (Length:" & Natural'Image(KT.Count_Moves(Board)) & "):"); KT.Tour_IO(Board, Width => 1); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line("Tour:"); KT.Tour_IO(KT.Warnsdorff_Get_Tour(Start_X, Start_Y, Board)); end Holy_Knight;
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
Write the same code in Go as shown below in Ada.
with Knights_Tour, Ada.Text_IO, Ada.Command_Line; procedure Holy_Knight is Size: Positive := Positive'Value(Ada.Command_Line.Argument(1)); package KT is new Knights_Tour(Size => Size); Board: KT.Tour := (others => (others => Natural'Last)); Start_X, Start_Y: KT.Index:= 1; S: String(KT.Index); I: Positive := KT.Index'First; begin while not Ada.Text_IO.End_Of_File and I <= Size loop S := Ada.Text_IO.Get_Line; for J in KT.Index loop if S(J) = ' ' or S(J) = '-' then Board(I,J) := Natural'Last; elsif S(J) = '1' then Start_X := I; Start_Y := J; Board(I,J) := 1; else Board(I,J) := 0; end if; end loop; I := I + 1; end loop; Ada.Text_IO.Put_Line("Start Configuration (Length:" & Natural'Image(KT.Count_Moves(Board)) & "):"); KT.Tour_IO(Board, Width => 1); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line("Tour:"); KT.Tour_IO(KT.Warnsdorff_Get_Tour(Start_X, Start_Y, Board)); end Holy_Knight;
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
Convert the following code from Ada to Java, ensuring the logic remains intact.
with Knights_Tour, Ada.Text_IO, Ada.Command_Line; procedure Holy_Knight is Size: Positive := Positive'Value(Ada.Command_Line.Argument(1)); package KT is new Knights_Tour(Size => Size); Board: KT.Tour := (others => (others => Natural'Last)); Start_X, Start_Y: KT.Index:= 1; S: String(KT.Index); I: Positive := KT.Index'First; begin while not Ada.Text_IO.End_Of_File and I <= Size loop S := Ada.Text_IO.Get_Line; for J in KT.Index loop if S(J) = ' ' or S(J) = '-' then Board(I,J) := Natural'Last; elsif S(J) = '1' then Start_X := I; Start_Y := J; Board(I,J) := 1; else Board(I,J) := 0; end if; end loop; I := I + 1; end loop; Ada.Text_IO.Put_Line("Start Configuration (Length:" & Natural'Image(KT.Count_Moves(Board)) & "):"); KT.Tour_IO(Board, Width => 1); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line("Tour:"); KT.Tour_IO(KT.Warnsdorff_Get_Tour(Start_X, Start_Y, Board)); end Holy_Knight;
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; 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 = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } 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, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (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) - 1; 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 void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
Convert this Ada block to Java, preserving its control flow and logic.
with Knights_Tour, Ada.Text_IO, Ada.Command_Line; procedure Holy_Knight is Size: Positive := Positive'Value(Ada.Command_Line.Argument(1)); package KT is new Knights_Tour(Size => Size); Board: KT.Tour := (others => (others => Natural'Last)); Start_X, Start_Y: KT.Index:= 1; S: String(KT.Index); I: Positive := KT.Index'First; begin while not Ada.Text_IO.End_Of_File and I <= Size loop S := Ada.Text_IO.Get_Line; for J in KT.Index loop if S(J) = ' ' or S(J) = '-' then Board(I,J) := Natural'Last; elsif S(J) = '1' then Start_X := I; Start_Y := J; Board(I,J) := 1; else Board(I,J) := 0; end if; end loop; I := I + 1; end loop; Ada.Text_IO.Put_Line("Start Configuration (Length:" & Natural'Image(KT.Count_Moves(Board)) & "):"); KT.Tour_IO(Board, Width => 1); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line("Tour:"); KT.Tour_IO(KT.Warnsdorff_Get_Tour(Start_X, Start_Y, Board)); end Holy_Knight;
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; 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 = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } 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, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (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) - 1; 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 void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
Transform the following Ada implementation into Python, maintaining the same output and logic.
with Knights_Tour, Ada.Text_IO, Ada.Command_Line; procedure Holy_Knight is Size: Positive := Positive'Value(Ada.Command_Line.Argument(1)); package KT is new Knights_Tour(Size => Size); Board: KT.Tour := (others => (others => Natural'Last)); Start_X, Start_Y: KT.Index:= 1; S: String(KT.Index); I: Positive := KT.Index'First; begin while not Ada.Text_IO.End_Of_File and I <= Size loop S := Ada.Text_IO.Get_Line; for J in KT.Index loop if S(J) = ' ' or S(J) = '-' then Board(I,J) := Natural'Last; elsif S(J) = '1' then Start_X := I; Start_Y := J; Board(I,J) := 1; else Board(I,J) := 0; end if; end loop; I := I + 1; end loop; Ada.Text_IO.Put_Line("Start Configuration (Length:" & Natural'Image(KT.Count_Moves(Board)) & "):"); KT.Tour_IO(Board, Width => 1); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line("Tour:"); KT.Tour_IO(KT.Warnsdorff_Get_Tour(Start_X, Start_Y, Board)); end Holy_Knight;
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Keep all operations the same but rewrite the snippet in Python.
with Knights_Tour, Ada.Text_IO, Ada.Command_Line; procedure Holy_Knight is Size: Positive := Positive'Value(Ada.Command_Line.Argument(1)); package KT is new Knights_Tour(Size => Size); Board: KT.Tour := (others => (others => Natural'Last)); Start_X, Start_Y: KT.Index:= 1; S: String(KT.Index); I: Positive := KT.Index'First; begin while not Ada.Text_IO.End_Of_File and I <= Size loop S := Ada.Text_IO.Get_Line; for J in KT.Index loop if S(J) = ' ' or S(J) = '-' then Board(I,J) := Natural'Last; elsif S(J) = '1' then Start_X := I; Start_Y := J; Board(I,J) := 1; else Board(I,J) := 0; end if; end loop; I := I + 1; end loop; Ada.Text_IO.Put_Line("Start Configuration (Length:" & Natural'Image(KT.Count_Moves(Board)) & "):"); KT.Tour_IO(Board, Width => 1); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line("Tour:"); KT.Tour_IO(KT.Warnsdorff_Get_Tour(Start_X, Start_Y, Board)); end Holy_Knight;
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Ensure the translated C# code behaves exactly like the original D snippet.
import std.stdio, std.conv, std.string, std.range, std.algorithm, std.typecons, std.typetuple; struct HolyKnightPuzzle { private alias InputCellBaseType = char; private enum InputCell : InputCellBaseType { available = '#', unavailable = '.', start='1' } private alias Cell = uint; private enum : Cell { unknownCell = 0, unavailableCell = Cell.max, startCell=1 } static struct P { int x, y; } alias shifts = TypeTuple!(P(-2, -1), P(2, -1), P(-2, 1), P(2, 1), P(-1, -2), P(1, -2), P(-1, 2), P(1, 2)); immutable size_t gridWidth, gridHeight; private immutable Cell nAvailableCells; private const InputCell[] flatPuzzle; private Cell[] grid; @disable this(); this(in string[] rawPuzzle) pure @safe in { assert(!rawPuzzle.empty); assert(!rawPuzzle[0].empty); assert(rawPuzzle.all!(row => row.length == rawPuzzle[0].length)); assert(rawPuzzle.join.count(InputCell.start) == 1); } body { immutable puzzle = rawPuzzle.map!representation.array.to!(InputCell[][]); gridWidth = puzzle[0].length; gridHeight = puzzle.length; flatPuzzle = puzzle.join; nAvailableCells = flatPuzzle.representation.count!(ic => ic != InputCell.unavailable); grid = flatPuzzle .map!(ic => ic.predSwitch(InputCell.available, unknownCell, InputCell.unavailable, unavailableCell, InputCell.start, startCell)) .array; } Nullable!(string[][]) solve(size_t width)() pure @safe out(result) { if (!result.isNull) assert(!grid.canFind(unknownCell)); } body { assert(width == gridWidth); foreach (immutable r; 0 .. gridHeight) foreach (immutable c; 0 .. width) if (grid[r * width + c] == startCell && search!width(r, c, startCell + 1)) { auto result = zip(flatPuzzle, grid) .map!(pc => (pc[0] == InputCell.available) ? pc[1].text : InputCellBaseType(pc[0]).text) .array .chunks(width) .array; return typeof(return)(result); } return typeof(return)(); } private bool search(size_t width)(in size_t r, in size_t c, in Cell cell) pure nothrow @safe @nogc { if (cell > nAvailableCells) return true; foreach (immutable sh; shifts) { immutable r2 = r + sh.x, c2 = c + sh.y, pos = r2 * width + c2; if (c2 < width && r2 < gridHeight && grid[pos] == unknownCell) { grid[pos] = cell; if (search!width(r2, c2, cell + 1)) return true; grid[pos] = unknownCell; } } return false; } } void main() @safe { enum puzzle1 = ".###.... .#.##... .####### ###..#.# #.#..### 1######. ..##.#.. ...###..".split.HolyKnightPuzzle; enum puzzle2 = ".....1.#..... .....#.#..... ....#####.... .....###..... ..#..#.#..#.. #####...##### ..##.....##.. #####...##### ..#..#.#..#.. .....###..... ....#####.... .....#.#..... .....#.#.....".split.HolyKnightPuzzle; foreach ( puzzle; TypeTuple!(puzzle1, puzzle2)) { enum width = puzzle.gridWidth; immutable solution = puzzle.solve!width; if (solution.isNull) writeln("No solution found for puzzle.\n"); else writefln("One solution:\n%(%-(%2s %)\n%)\n", solution); } }
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Please provide an equivalent version of this D code in C#.
import std.stdio, std.conv, std.string, std.range, std.algorithm, std.typecons, std.typetuple; struct HolyKnightPuzzle { private alias InputCellBaseType = char; private enum InputCell : InputCellBaseType { available = '#', unavailable = '.', start='1' } private alias Cell = uint; private enum : Cell { unknownCell = 0, unavailableCell = Cell.max, startCell=1 } static struct P { int x, y; } alias shifts = TypeTuple!(P(-2, -1), P(2, -1), P(-2, 1), P(2, 1), P(-1, -2), P(1, -2), P(-1, 2), P(1, 2)); immutable size_t gridWidth, gridHeight; private immutable Cell nAvailableCells; private const InputCell[] flatPuzzle; private Cell[] grid; @disable this(); this(in string[] rawPuzzle) pure @safe in { assert(!rawPuzzle.empty); assert(!rawPuzzle[0].empty); assert(rawPuzzle.all!(row => row.length == rawPuzzle[0].length)); assert(rawPuzzle.join.count(InputCell.start) == 1); } body { immutable puzzle = rawPuzzle.map!representation.array.to!(InputCell[][]); gridWidth = puzzle[0].length; gridHeight = puzzle.length; flatPuzzle = puzzle.join; nAvailableCells = flatPuzzle.representation.count!(ic => ic != InputCell.unavailable); grid = flatPuzzle .map!(ic => ic.predSwitch(InputCell.available, unknownCell, InputCell.unavailable, unavailableCell, InputCell.start, startCell)) .array; } Nullable!(string[][]) solve(size_t width)() pure @safe out(result) { if (!result.isNull) assert(!grid.canFind(unknownCell)); } body { assert(width == gridWidth); foreach (immutable r; 0 .. gridHeight) foreach (immutable c; 0 .. width) if (grid[r * width + c] == startCell && search!width(r, c, startCell + 1)) { auto result = zip(flatPuzzle, grid) .map!(pc => (pc[0] == InputCell.available) ? pc[1].text : InputCellBaseType(pc[0]).text) .array .chunks(width) .array; return typeof(return)(result); } return typeof(return)(); } private bool search(size_t width)(in size_t r, in size_t c, in Cell cell) pure nothrow @safe @nogc { if (cell > nAvailableCells) return true; foreach (immutable sh; shifts) { immutable r2 = r + sh.x, c2 = c + sh.y, pos = r2 * width + c2; if (c2 < width && r2 < gridHeight && grid[pos] == unknownCell) { grid[pos] = cell; if (search!width(r2, c2, cell + 1)) return true; grid[pos] = unknownCell; } } return false; } } void main() @safe { enum puzzle1 = ".###.... .#.##... .####### ###..#.# #.#..### 1######. ..##.#.. ...###..".split.HolyKnightPuzzle; enum puzzle2 = ".....1.#..... .....#.#..... ....#####.... .....###..... ..#..#.#..#.. #####...##### ..##.....##.. #####...##### ..#..#.#..#.. .....###..... ....#####.... .....#.#..... .....#.#.....".split.HolyKnightPuzzle; foreach ( puzzle; TypeTuple!(puzzle1, puzzle2)) { enum width = puzzle.gridWidth; immutable solution = puzzle.solve!width; if (solution.isNull) writeln("No solution found for puzzle.\n"); else writefln("One solution:\n%(%-(%2s %)\n%)\n", solution); } }
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Generate a C++ translation of this D snippet without changing its computational steps.
import std.stdio, std.conv, std.string, std.range, std.algorithm, std.typecons, std.typetuple; struct HolyKnightPuzzle { private alias InputCellBaseType = char; private enum InputCell : InputCellBaseType { available = '#', unavailable = '.', start='1' } private alias Cell = uint; private enum : Cell { unknownCell = 0, unavailableCell = Cell.max, startCell=1 } static struct P { int x, y; } alias shifts = TypeTuple!(P(-2, -1), P(2, -1), P(-2, 1), P(2, 1), P(-1, -2), P(1, -2), P(-1, 2), P(1, 2)); immutable size_t gridWidth, gridHeight; private immutable Cell nAvailableCells; private const InputCell[] flatPuzzle; private Cell[] grid; @disable this(); this(in string[] rawPuzzle) pure @safe in { assert(!rawPuzzle.empty); assert(!rawPuzzle[0].empty); assert(rawPuzzle.all!(row => row.length == rawPuzzle[0].length)); assert(rawPuzzle.join.count(InputCell.start) == 1); } body { immutable puzzle = rawPuzzle.map!representation.array.to!(InputCell[][]); gridWidth = puzzle[0].length; gridHeight = puzzle.length; flatPuzzle = puzzle.join; nAvailableCells = flatPuzzle.representation.count!(ic => ic != InputCell.unavailable); grid = flatPuzzle .map!(ic => ic.predSwitch(InputCell.available, unknownCell, InputCell.unavailable, unavailableCell, InputCell.start, startCell)) .array; } Nullable!(string[][]) solve(size_t width)() pure @safe out(result) { if (!result.isNull) assert(!grid.canFind(unknownCell)); } body { assert(width == gridWidth); foreach (immutable r; 0 .. gridHeight) foreach (immutable c; 0 .. width) if (grid[r * width + c] == startCell && search!width(r, c, startCell + 1)) { auto result = zip(flatPuzzle, grid) .map!(pc => (pc[0] == InputCell.available) ? pc[1].text : InputCellBaseType(pc[0]).text) .array .chunks(width) .array; return typeof(return)(result); } return typeof(return)(); } private bool search(size_t width)(in size_t r, in size_t c, in Cell cell) pure nothrow @safe @nogc { if (cell > nAvailableCells) return true; foreach (immutable sh; shifts) { immutable r2 = r + sh.x, c2 = c + sh.y, pos = r2 * width + c2; if (c2 < width && r2 < gridHeight && grid[pos] == unknownCell) { grid[pos] = cell; if (search!width(r2, c2, cell + 1)) return true; grid[pos] = unknownCell; } } return false; } } void main() @safe { enum puzzle1 = ".###.... .#.##... .####### ###..#.# #.#..### 1######. ..##.#.. ...###..".split.HolyKnightPuzzle; enum puzzle2 = ".....1.#..... .....#.#..... ....#####.... .....###..... ..#..#.#..#.. #####...##### ..##.....##.. #####...##### ..#..#.#..#.. .....###..... ....#####.... .....#.#..... .....#.#.....".split.HolyKnightPuzzle; foreach ( puzzle; TypeTuple!(puzzle1, puzzle2)) { enum width = puzzle.gridWidth; immutable solution = puzzle.solve!width; if (solution.isNull) writeln("No solution found for puzzle.\n"); else writefln("One solution:\n%(%-(%2s %)\n%)\n", solution); } }
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Write the same algorithm in C++ as shown in this D implementation.
import std.stdio, std.conv, std.string, std.range, std.algorithm, std.typecons, std.typetuple; struct HolyKnightPuzzle { private alias InputCellBaseType = char; private enum InputCell : InputCellBaseType { available = '#', unavailable = '.', start='1' } private alias Cell = uint; private enum : Cell { unknownCell = 0, unavailableCell = Cell.max, startCell=1 } static struct P { int x, y; } alias shifts = TypeTuple!(P(-2, -1), P(2, -1), P(-2, 1), P(2, 1), P(-1, -2), P(1, -2), P(-1, 2), P(1, 2)); immutable size_t gridWidth, gridHeight; private immutable Cell nAvailableCells; private const InputCell[] flatPuzzle; private Cell[] grid; @disable this(); this(in string[] rawPuzzle) pure @safe in { assert(!rawPuzzle.empty); assert(!rawPuzzle[0].empty); assert(rawPuzzle.all!(row => row.length == rawPuzzle[0].length)); assert(rawPuzzle.join.count(InputCell.start) == 1); } body { immutable puzzle = rawPuzzle.map!representation.array.to!(InputCell[][]); gridWidth = puzzle[0].length; gridHeight = puzzle.length; flatPuzzle = puzzle.join; nAvailableCells = flatPuzzle.representation.count!(ic => ic != InputCell.unavailable); grid = flatPuzzle .map!(ic => ic.predSwitch(InputCell.available, unknownCell, InputCell.unavailable, unavailableCell, InputCell.start, startCell)) .array; } Nullable!(string[][]) solve(size_t width)() pure @safe out(result) { if (!result.isNull) assert(!grid.canFind(unknownCell)); } body { assert(width == gridWidth); foreach (immutable r; 0 .. gridHeight) foreach (immutable c; 0 .. width) if (grid[r * width + c] == startCell && search!width(r, c, startCell + 1)) { auto result = zip(flatPuzzle, grid) .map!(pc => (pc[0] == InputCell.available) ? pc[1].text : InputCellBaseType(pc[0]).text) .array .chunks(width) .array; return typeof(return)(result); } return typeof(return)(); } private bool search(size_t width)(in size_t r, in size_t c, in Cell cell) pure nothrow @safe @nogc { if (cell > nAvailableCells) return true; foreach (immutable sh; shifts) { immutable r2 = r + sh.x, c2 = c + sh.y, pos = r2 * width + c2; if (c2 < width && r2 < gridHeight && grid[pos] == unknownCell) { grid[pos] = cell; if (search!width(r2, c2, cell + 1)) return true; grid[pos] = unknownCell; } } return false; } } void main() @safe { enum puzzle1 = ".###.... .#.##... .####### ###..#.# #.#..### 1######. ..##.#.. ...###..".split.HolyKnightPuzzle; enum puzzle2 = ".....1.#..... .....#.#..... ....#####.... .....###..... ..#..#.#..#.. #####...##### ..##.....##.. #####...##### ..#..#.#..#.. .....###..... ....#####.... .....#.#..... .....#.#.....".split.HolyKnightPuzzle; foreach ( puzzle; TypeTuple!(puzzle1, puzzle2)) { enum width = puzzle.gridWidth; immutable solution = puzzle.solve!width; if (solution.isNull) writeln("No solution found for puzzle.\n"); else writefln("One solution:\n%(%-(%2s %)\n%)\n", solution); } }
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Convert this D block to Java, preserving its control flow and logic.
import std.stdio, std.conv, std.string, std.range, std.algorithm, std.typecons, std.typetuple; struct HolyKnightPuzzle { private alias InputCellBaseType = char; private enum InputCell : InputCellBaseType { available = '#', unavailable = '.', start='1' } private alias Cell = uint; private enum : Cell { unknownCell = 0, unavailableCell = Cell.max, startCell=1 } static struct P { int x, y; } alias shifts = TypeTuple!(P(-2, -1), P(2, -1), P(-2, 1), P(2, 1), P(-1, -2), P(1, -2), P(-1, 2), P(1, 2)); immutable size_t gridWidth, gridHeight; private immutable Cell nAvailableCells; private const InputCell[] flatPuzzle; private Cell[] grid; @disable this(); this(in string[] rawPuzzle) pure @safe in { assert(!rawPuzzle.empty); assert(!rawPuzzle[0].empty); assert(rawPuzzle.all!(row => row.length == rawPuzzle[0].length)); assert(rawPuzzle.join.count(InputCell.start) == 1); } body { immutable puzzle = rawPuzzle.map!representation.array.to!(InputCell[][]); gridWidth = puzzle[0].length; gridHeight = puzzle.length; flatPuzzle = puzzle.join; nAvailableCells = flatPuzzle.representation.count!(ic => ic != InputCell.unavailable); grid = flatPuzzle .map!(ic => ic.predSwitch(InputCell.available, unknownCell, InputCell.unavailable, unavailableCell, InputCell.start, startCell)) .array; } Nullable!(string[][]) solve(size_t width)() pure @safe out(result) { if (!result.isNull) assert(!grid.canFind(unknownCell)); } body { assert(width == gridWidth); foreach (immutable r; 0 .. gridHeight) foreach (immutable c; 0 .. width) if (grid[r * width + c] == startCell && search!width(r, c, startCell + 1)) { auto result = zip(flatPuzzle, grid) .map!(pc => (pc[0] == InputCell.available) ? pc[1].text : InputCellBaseType(pc[0]).text) .array .chunks(width) .array; return typeof(return)(result); } return typeof(return)(); } private bool search(size_t width)(in size_t r, in size_t c, in Cell cell) pure nothrow @safe @nogc { if (cell > nAvailableCells) return true; foreach (immutable sh; shifts) { immutable r2 = r + sh.x, c2 = c + sh.y, pos = r2 * width + c2; if (c2 < width && r2 < gridHeight && grid[pos] == unknownCell) { grid[pos] = cell; if (search!width(r2, c2, cell + 1)) return true; grid[pos] = unknownCell; } } return false; } } void main() @safe { enum puzzle1 = ".###.... .#.##... .####### ###..#.# #.#..### 1######. ..##.#.. ...###..".split.HolyKnightPuzzle; enum puzzle2 = ".....1.#..... .....#.#..... ....#####.... .....###..... ..#..#.#..#.. #####...##### ..##.....##.. #####...##### ..#..#.#..#.. .....###..... ....#####.... .....#.#..... .....#.#.....".split.HolyKnightPuzzle; foreach ( puzzle; TypeTuple!(puzzle1, puzzle2)) { enum width = puzzle.gridWidth; immutable solution = puzzle.solve!width; if (solution.isNull) writeln("No solution found for puzzle.\n"); else writefln("One solution:\n%(%-(%2s %)\n%)\n", solution); } }
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; 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 = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } 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, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (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) - 1; 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 void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
Preserve the algorithm and functionality while converting the code from D to Java.
import std.stdio, std.conv, std.string, std.range, std.algorithm, std.typecons, std.typetuple; struct HolyKnightPuzzle { private alias InputCellBaseType = char; private enum InputCell : InputCellBaseType { available = '#', unavailable = '.', start='1' } private alias Cell = uint; private enum : Cell { unknownCell = 0, unavailableCell = Cell.max, startCell=1 } static struct P { int x, y; } alias shifts = TypeTuple!(P(-2, -1), P(2, -1), P(-2, 1), P(2, 1), P(-1, -2), P(1, -2), P(-1, 2), P(1, 2)); immutable size_t gridWidth, gridHeight; private immutable Cell nAvailableCells; private const InputCell[] flatPuzzle; private Cell[] grid; @disable this(); this(in string[] rawPuzzle) pure @safe in { assert(!rawPuzzle.empty); assert(!rawPuzzle[0].empty); assert(rawPuzzle.all!(row => row.length == rawPuzzle[0].length)); assert(rawPuzzle.join.count(InputCell.start) == 1); } body { immutable puzzle = rawPuzzle.map!representation.array.to!(InputCell[][]); gridWidth = puzzle[0].length; gridHeight = puzzle.length; flatPuzzle = puzzle.join; nAvailableCells = flatPuzzle.representation.count!(ic => ic != InputCell.unavailable); grid = flatPuzzle .map!(ic => ic.predSwitch(InputCell.available, unknownCell, InputCell.unavailable, unavailableCell, InputCell.start, startCell)) .array; } Nullable!(string[][]) solve(size_t width)() pure @safe out(result) { if (!result.isNull) assert(!grid.canFind(unknownCell)); } body { assert(width == gridWidth); foreach (immutable r; 0 .. gridHeight) foreach (immutable c; 0 .. width) if (grid[r * width + c] == startCell && search!width(r, c, startCell + 1)) { auto result = zip(flatPuzzle, grid) .map!(pc => (pc[0] == InputCell.available) ? pc[1].text : InputCellBaseType(pc[0]).text) .array .chunks(width) .array; return typeof(return)(result); } return typeof(return)(); } private bool search(size_t width)(in size_t r, in size_t c, in Cell cell) pure nothrow @safe @nogc { if (cell > nAvailableCells) return true; foreach (immutable sh; shifts) { immutable r2 = r + sh.x, c2 = c + sh.y, pos = r2 * width + c2; if (c2 < width && r2 < gridHeight && grid[pos] == unknownCell) { grid[pos] = cell; if (search!width(r2, c2, cell + 1)) return true; grid[pos] = unknownCell; } } return false; } } void main() @safe { enum puzzle1 = ".###.... .#.##... .####### ###..#.# #.#..### 1######. ..##.#.. ...###..".split.HolyKnightPuzzle; enum puzzle2 = ".....1.#..... .....#.#..... ....#####.... .....###..... ..#..#.#..#.. #####...##### ..##.....##.. #####...##### ..#..#.#..#.. .....###..... ....#####.... .....#.#..... .....#.#.....".split.HolyKnightPuzzle; foreach ( puzzle; TypeTuple!(puzzle1, puzzle2)) { enum width = puzzle.gridWidth; immutable solution = puzzle.solve!width; if (solution.isNull) writeln("No solution found for puzzle.\n"); else writefln("One solution:\n%(%-(%2s %)\n%)\n", solution); } }
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; 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 = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } 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, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (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) - 1; 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 void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
Convert this D snippet to Python and keep its semantics consistent.
import std.stdio, std.conv, std.string, std.range, std.algorithm, std.typecons, std.typetuple; struct HolyKnightPuzzle { private alias InputCellBaseType = char; private enum InputCell : InputCellBaseType { available = '#', unavailable = '.', start='1' } private alias Cell = uint; private enum : Cell { unknownCell = 0, unavailableCell = Cell.max, startCell=1 } static struct P { int x, y; } alias shifts = TypeTuple!(P(-2, -1), P(2, -1), P(-2, 1), P(2, 1), P(-1, -2), P(1, -2), P(-1, 2), P(1, 2)); immutable size_t gridWidth, gridHeight; private immutable Cell nAvailableCells; private const InputCell[] flatPuzzle; private Cell[] grid; @disable this(); this(in string[] rawPuzzle) pure @safe in { assert(!rawPuzzle.empty); assert(!rawPuzzle[0].empty); assert(rawPuzzle.all!(row => row.length == rawPuzzle[0].length)); assert(rawPuzzle.join.count(InputCell.start) == 1); } body { immutable puzzle = rawPuzzle.map!representation.array.to!(InputCell[][]); gridWidth = puzzle[0].length; gridHeight = puzzle.length; flatPuzzle = puzzle.join; nAvailableCells = flatPuzzle.representation.count!(ic => ic != InputCell.unavailable); grid = flatPuzzle .map!(ic => ic.predSwitch(InputCell.available, unknownCell, InputCell.unavailable, unavailableCell, InputCell.start, startCell)) .array; } Nullable!(string[][]) solve(size_t width)() pure @safe out(result) { if (!result.isNull) assert(!grid.canFind(unknownCell)); } body { assert(width == gridWidth); foreach (immutable r; 0 .. gridHeight) foreach (immutable c; 0 .. width) if (grid[r * width + c] == startCell && search!width(r, c, startCell + 1)) { auto result = zip(flatPuzzle, grid) .map!(pc => (pc[0] == InputCell.available) ? pc[1].text : InputCellBaseType(pc[0]).text) .array .chunks(width) .array; return typeof(return)(result); } return typeof(return)(); } private bool search(size_t width)(in size_t r, in size_t c, in Cell cell) pure nothrow @safe @nogc { if (cell > nAvailableCells) return true; foreach (immutable sh; shifts) { immutable r2 = r + sh.x, c2 = c + sh.y, pos = r2 * width + c2; if (c2 < width && r2 < gridHeight && grid[pos] == unknownCell) { grid[pos] = cell; if (search!width(r2, c2, cell + 1)) return true; grid[pos] = unknownCell; } } return false; } } void main() @safe { enum puzzle1 = ".###.... .#.##... .####### ###..#.# #.#..### 1######. ..##.#.. ...###..".split.HolyKnightPuzzle; enum puzzle2 = ".....1.#..... .....#.#..... ....#####.... .....###..... ..#..#.#..#.. #####...##### ..##.....##.. #####...##### ..#..#.#..#.. .....###..... ....#####.... .....#.#..... .....#.#.....".split.HolyKnightPuzzle; foreach ( puzzle; TypeTuple!(puzzle1, puzzle2)) { enum width = puzzle.gridWidth; immutable solution = puzzle.solve!width; if (solution.isNull) writeln("No solution found for puzzle.\n"); else writefln("One solution:\n%(%-(%2s %)\n%)\n", solution); } }
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Can you help me rewrite this code in Python instead of D, keeping it the same logically?
import std.stdio, std.conv, std.string, std.range, std.algorithm, std.typecons, std.typetuple; struct HolyKnightPuzzle { private alias InputCellBaseType = char; private enum InputCell : InputCellBaseType { available = '#', unavailable = '.', start='1' } private alias Cell = uint; private enum : Cell { unknownCell = 0, unavailableCell = Cell.max, startCell=1 } static struct P { int x, y; } alias shifts = TypeTuple!(P(-2, -1), P(2, -1), P(-2, 1), P(2, 1), P(-1, -2), P(1, -2), P(-1, 2), P(1, 2)); immutable size_t gridWidth, gridHeight; private immutable Cell nAvailableCells; private const InputCell[] flatPuzzle; private Cell[] grid; @disable this(); this(in string[] rawPuzzle) pure @safe in { assert(!rawPuzzle.empty); assert(!rawPuzzle[0].empty); assert(rawPuzzle.all!(row => row.length == rawPuzzle[0].length)); assert(rawPuzzle.join.count(InputCell.start) == 1); } body { immutable puzzle = rawPuzzle.map!representation.array.to!(InputCell[][]); gridWidth = puzzle[0].length; gridHeight = puzzle.length; flatPuzzle = puzzle.join; nAvailableCells = flatPuzzle.representation.count!(ic => ic != InputCell.unavailable); grid = flatPuzzle .map!(ic => ic.predSwitch(InputCell.available, unknownCell, InputCell.unavailable, unavailableCell, InputCell.start, startCell)) .array; } Nullable!(string[][]) solve(size_t width)() pure @safe out(result) { if (!result.isNull) assert(!grid.canFind(unknownCell)); } body { assert(width == gridWidth); foreach (immutable r; 0 .. gridHeight) foreach (immutable c; 0 .. width) if (grid[r * width + c] == startCell && search!width(r, c, startCell + 1)) { auto result = zip(flatPuzzle, grid) .map!(pc => (pc[0] == InputCell.available) ? pc[1].text : InputCellBaseType(pc[0]).text) .array .chunks(width) .array; return typeof(return)(result); } return typeof(return)(); } private bool search(size_t width)(in size_t r, in size_t c, in Cell cell) pure nothrow @safe @nogc { if (cell > nAvailableCells) return true; foreach (immutable sh; shifts) { immutable r2 = r + sh.x, c2 = c + sh.y, pos = r2 * width + c2; if (c2 < width && r2 < gridHeight && grid[pos] == unknownCell) { grid[pos] = cell; if (search!width(r2, c2, cell + 1)) return true; grid[pos] = unknownCell; } } return false; } } void main() @safe { enum puzzle1 = ".###.... .#.##... .####### ###..#.# #.#..### 1######. ..##.#.. ...###..".split.HolyKnightPuzzle; enum puzzle2 = ".....1.#..... .....#.#..... ....#####.... .....###..... ..#..#.#..#.. #####...##### ..##.....##.. #####...##### ..#..#.#..#.. .....###..... ....#####.... .....#.#..... .....#.#.....".split.HolyKnightPuzzle; foreach ( puzzle; TypeTuple!(puzzle1, puzzle2)) { enum width = puzzle.gridWidth; immutable solution = puzzle.solve!width; if (solution.isNull) writeln("No solution found for puzzle.\n"); else writefln("One solution:\n%(%-(%2s %)\n%)\n", solution); } }
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Can you help me rewrite this code in Go instead of D, keeping it the same logically?
import std.stdio, std.conv, std.string, std.range, std.algorithm, std.typecons, std.typetuple; struct HolyKnightPuzzle { private alias InputCellBaseType = char; private enum InputCell : InputCellBaseType { available = '#', unavailable = '.', start='1' } private alias Cell = uint; private enum : Cell { unknownCell = 0, unavailableCell = Cell.max, startCell=1 } static struct P { int x, y; } alias shifts = TypeTuple!(P(-2, -1), P(2, -1), P(-2, 1), P(2, 1), P(-1, -2), P(1, -2), P(-1, 2), P(1, 2)); immutable size_t gridWidth, gridHeight; private immutable Cell nAvailableCells; private const InputCell[] flatPuzzle; private Cell[] grid; @disable this(); this(in string[] rawPuzzle) pure @safe in { assert(!rawPuzzle.empty); assert(!rawPuzzle[0].empty); assert(rawPuzzle.all!(row => row.length == rawPuzzle[0].length)); assert(rawPuzzle.join.count(InputCell.start) == 1); } body { immutable puzzle = rawPuzzle.map!representation.array.to!(InputCell[][]); gridWidth = puzzle[0].length; gridHeight = puzzle.length; flatPuzzle = puzzle.join; nAvailableCells = flatPuzzle.representation.count!(ic => ic != InputCell.unavailable); grid = flatPuzzle .map!(ic => ic.predSwitch(InputCell.available, unknownCell, InputCell.unavailable, unavailableCell, InputCell.start, startCell)) .array; } Nullable!(string[][]) solve(size_t width)() pure @safe out(result) { if (!result.isNull) assert(!grid.canFind(unknownCell)); } body { assert(width == gridWidth); foreach (immutable r; 0 .. gridHeight) foreach (immutable c; 0 .. width) if (grid[r * width + c] == startCell && search!width(r, c, startCell + 1)) { auto result = zip(flatPuzzle, grid) .map!(pc => (pc[0] == InputCell.available) ? pc[1].text : InputCellBaseType(pc[0]).text) .array .chunks(width) .array; return typeof(return)(result); } return typeof(return)(); } private bool search(size_t width)(in size_t r, in size_t c, in Cell cell) pure nothrow @safe @nogc { if (cell > nAvailableCells) return true; foreach (immutable sh; shifts) { immutable r2 = r + sh.x, c2 = c + sh.y, pos = r2 * width + c2; if (c2 < width && r2 < gridHeight && grid[pos] == unknownCell) { grid[pos] = cell; if (search!width(r2, c2, cell + 1)) return true; grid[pos] = unknownCell; } } return false; } } void main() @safe { enum puzzle1 = ".###.... .#.##... .####### ###..#.# #.#..### 1######. ..##.#.. ...###..".split.HolyKnightPuzzle; enum puzzle2 = ".....1.#..... .....#.#..... ....#####.... .....###..... ..#..#.#..#.. #####...##### ..##.....##.. #####...##### ..#..#.#..#.. .....###..... ....#####.... .....#.#..... .....#.#.....".split.HolyKnightPuzzle; foreach ( puzzle; TypeTuple!(puzzle1, puzzle2)) { enum width = puzzle.gridWidth; immutable solution = puzzle.solve!width; if (solution.isNull) writeln("No solution found for puzzle.\n"); else writefln("One solution:\n%(%-(%2s %)\n%)\n", solution); } }
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
Port the provided D code into Go while preserving the original functionality.
import std.stdio, std.conv, std.string, std.range, std.algorithm, std.typecons, std.typetuple; struct HolyKnightPuzzle { private alias InputCellBaseType = char; private enum InputCell : InputCellBaseType { available = '#', unavailable = '.', start='1' } private alias Cell = uint; private enum : Cell { unknownCell = 0, unavailableCell = Cell.max, startCell=1 } static struct P { int x, y; } alias shifts = TypeTuple!(P(-2, -1), P(2, -1), P(-2, 1), P(2, 1), P(-1, -2), P(1, -2), P(-1, 2), P(1, 2)); immutable size_t gridWidth, gridHeight; private immutable Cell nAvailableCells; private const InputCell[] flatPuzzle; private Cell[] grid; @disable this(); this(in string[] rawPuzzle) pure @safe in { assert(!rawPuzzle.empty); assert(!rawPuzzle[0].empty); assert(rawPuzzle.all!(row => row.length == rawPuzzle[0].length)); assert(rawPuzzle.join.count(InputCell.start) == 1); } body { immutable puzzle = rawPuzzle.map!representation.array.to!(InputCell[][]); gridWidth = puzzle[0].length; gridHeight = puzzle.length; flatPuzzle = puzzle.join; nAvailableCells = flatPuzzle.representation.count!(ic => ic != InputCell.unavailable); grid = flatPuzzle .map!(ic => ic.predSwitch(InputCell.available, unknownCell, InputCell.unavailable, unavailableCell, InputCell.start, startCell)) .array; } Nullable!(string[][]) solve(size_t width)() pure @safe out(result) { if (!result.isNull) assert(!grid.canFind(unknownCell)); } body { assert(width == gridWidth); foreach (immutable r; 0 .. gridHeight) foreach (immutable c; 0 .. width) if (grid[r * width + c] == startCell && search!width(r, c, startCell + 1)) { auto result = zip(flatPuzzle, grid) .map!(pc => (pc[0] == InputCell.available) ? pc[1].text : InputCellBaseType(pc[0]).text) .array .chunks(width) .array; return typeof(return)(result); } return typeof(return)(); } private bool search(size_t width)(in size_t r, in size_t c, in Cell cell) pure nothrow @safe @nogc { if (cell > nAvailableCells) return true; foreach (immutable sh; shifts) { immutable r2 = r + sh.x, c2 = c + sh.y, pos = r2 * width + c2; if (c2 < width && r2 < gridHeight && grid[pos] == unknownCell) { grid[pos] = cell; if (search!width(r2, c2, cell + 1)) return true; grid[pos] = unknownCell; } } return false; } } void main() @safe { enum puzzle1 = ".###.... .#.##... .####### ###..#.# #.#..### 1######. ..##.#.. ...###..".split.HolyKnightPuzzle; enum puzzle2 = ".....1.#..... .....#.#..... ....#####.... .....###..... ..#..#.#..#.. #####...##### ..##.....##.. #####...##### ..#..#.#..#.. .....###..... ....#####.... .....#.#..... .....#.#.....".split.HolyKnightPuzzle; foreach ( puzzle; TypeTuple!(puzzle1, puzzle2)) { enum width = puzzle.gridWidth; immutable solution = puzzle.solve!width; if (solution.isNull) writeln("No solution found for puzzle.\n"); else writefln("One solution:\n%(%-(%2s %)\n%)\n", solution); } }
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
Produce a functionally identical C# code for the snippet given in Elixir.
adjacent = [{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}] """ . . 0 0 0 . . 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0 0 0 0 . . 0 0 . 0 . . . 0 0 0 """ |> HLPsolver.solve(adjacent) """ _ _ _ _ _ 1 _ 0 _ _ _ _ _ 0 _ 0 _ _ _ _ 0 0 0 0 0 _ _ _ _ _ 0 0 0 _ _ 0 _ _ 0 _ 0 _ _ 0 0 0 0 0 0 _ _ _ 0 0 0 0 0 _ _ 0 0 _ _ _ _ _ 0 0 0 0 0 0 0 _ _ _ 0 0 0 0 0 _ _ 0 _ _ 0 _ 0 _ _ 0 _ _ _ _ _ 0 0 0 _ _ _ _ 0 0 0 0 0 _ _ _ _ _ 0 _ 0 _ _ _ _ _ 0 _ 0 """ |> HLPsolver.solve(adjacent)
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Translate the given Elixir code snippet into C# without altering its behavior.
adjacent = [{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}] """ . . 0 0 0 . . 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0 0 0 0 . . 0 0 . 0 . . . 0 0 0 """ |> HLPsolver.solve(adjacent) """ _ _ _ _ _ 1 _ 0 _ _ _ _ _ 0 _ 0 _ _ _ _ 0 0 0 0 0 _ _ _ _ _ 0 0 0 _ _ 0 _ _ 0 _ 0 _ _ 0 0 0 0 0 0 _ _ _ 0 0 0 0 0 _ _ 0 0 _ _ _ _ _ 0 0 0 0 0 0 0 _ _ _ 0 0 0 0 0 _ _ 0 _ _ 0 _ 0 _ _ 0 _ _ _ _ _ 0 0 0 _ _ _ _ 0 0 0 0 0 _ _ _ _ _ 0 _ 0 _ _ _ _ _ 0 _ 0 """ |> HLPsolver.solve(adjacent)
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Preserve the algorithm and functionality while converting the code from Elixir to C++.
adjacent = [{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}] """ . . 0 0 0 . . 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0 0 0 0 . . 0 0 . 0 . . . 0 0 0 """ |> HLPsolver.solve(adjacent) """ _ _ _ _ _ 1 _ 0 _ _ _ _ _ 0 _ 0 _ _ _ _ 0 0 0 0 0 _ _ _ _ _ 0 0 0 _ _ 0 _ _ 0 _ 0 _ _ 0 0 0 0 0 0 _ _ _ 0 0 0 0 0 _ _ 0 0 _ _ _ _ _ 0 0 0 0 0 0 0 _ _ _ 0 0 0 0 0 _ _ 0 _ _ 0 _ 0 _ _ 0 _ _ _ _ _ 0 0 0 _ _ _ _ 0 0 0 0 0 _ _ _ _ _ 0 _ 0 _ _ _ _ _ 0 _ 0 """ |> HLPsolver.solve(adjacent)
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Please provide an equivalent version of this Elixir code in C++.
adjacent = [{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}] """ . . 0 0 0 . . 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0 0 0 0 . . 0 0 . 0 . . . 0 0 0 """ |> HLPsolver.solve(adjacent) """ _ _ _ _ _ 1 _ 0 _ _ _ _ _ 0 _ 0 _ _ _ _ 0 0 0 0 0 _ _ _ _ _ 0 0 0 _ _ 0 _ _ 0 _ 0 _ _ 0 0 0 0 0 0 _ _ _ 0 0 0 0 0 _ _ 0 0 _ _ _ _ _ 0 0 0 0 0 0 0 _ _ _ 0 0 0 0 0 _ _ 0 _ _ 0 _ 0 _ _ 0 _ _ _ _ _ 0 0 0 _ _ _ _ 0 0 0 0 0 _ _ _ _ _ 0 _ 0 _ _ _ _ _ 0 _ 0 """ |> HLPsolver.solve(adjacent)
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Generate an equivalent Java version of this Elixir code.
adjacent = [{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}] """ . . 0 0 0 . . 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0 0 0 0 . . 0 0 . 0 . . . 0 0 0 """ |> HLPsolver.solve(adjacent) """ _ _ _ _ _ 1 _ 0 _ _ _ _ _ 0 _ 0 _ _ _ _ 0 0 0 0 0 _ _ _ _ _ 0 0 0 _ _ 0 _ _ 0 _ 0 _ _ 0 0 0 0 0 0 _ _ _ 0 0 0 0 0 _ _ 0 0 _ _ _ _ _ 0 0 0 0 0 0 0 _ _ _ 0 0 0 0 0 _ _ 0 _ _ 0 _ 0 _ _ 0 _ _ _ _ _ 0 0 0 _ _ _ _ 0 0 0 0 0 _ _ _ _ _ 0 _ 0 _ _ _ _ _ 0 _ 0 """ |> HLPsolver.solve(adjacent)
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; 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 = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } 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, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (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) - 1; 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 void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
Preserve the algorithm and functionality while converting the code from Elixir to Java.
adjacent = [{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}] """ . . 0 0 0 . . 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0 0 0 0 . . 0 0 . 0 . . . 0 0 0 """ |> HLPsolver.solve(adjacent) """ _ _ _ _ _ 1 _ 0 _ _ _ _ _ 0 _ 0 _ _ _ _ 0 0 0 0 0 _ _ _ _ _ 0 0 0 _ _ 0 _ _ 0 _ 0 _ _ 0 0 0 0 0 0 _ _ _ 0 0 0 0 0 _ _ 0 0 _ _ _ _ _ 0 0 0 0 0 0 0 _ _ _ 0 0 0 0 0 _ _ 0 _ _ 0 _ 0 _ _ 0 _ _ _ _ _ 0 0 0 _ _ _ _ 0 0 0 0 0 _ _ _ _ _ 0 _ 0 _ _ _ _ _ 0 _ 0 """ |> HLPsolver.solve(adjacent)
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; 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 = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } 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, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (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) - 1; 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 void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
Produce a language-to-language conversion: from Elixir to Python, same semantics.
adjacent = [{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}] """ . . 0 0 0 . . 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0 0 0 0 . . 0 0 . 0 . . . 0 0 0 """ |> HLPsolver.solve(adjacent) """ _ _ _ _ _ 1 _ 0 _ _ _ _ _ 0 _ 0 _ _ _ _ 0 0 0 0 0 _ _ _ _ _ 0 0 0 _ _ 0 _ _ 0 _ 0 _ _ 0 0 0 0 0 0 _ _ _ 0 0 0 0 0 _ _ 0 0 _ _ _ _ _ 0 0 0 0 0 0 0 _ _ _ 0 0 0 0 0 _ _ 0 _ _ 0 _ 0 _ _ 0 _ _ _ _ _ 0 0 0 _ _ _ _ 0 0 0 0 0 _ _ _ _ _ 0 _ 0 _ _ _ _ _ 0 _ 0 """ |> HLPsolver.solve(adjacent)
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Produce a language-to-language conversion: from Elixir to Python, same semantics.
adjacent = [{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}] """ . . 0 0 0 . . 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0 0 0 0 . . 0 0 . 0 . . . 0 0 0 """ |> HLPsolver.solve(adjacent) """ _ _ _ _ _ 1 _ 0 _ _ _ _ _ 0 _ 0 _ _ _ _ 0 0 0 0 0 _ _ _ _ _ 0 0 0 _ _ 0 _ _ 0 _ 0 _ _ 0 0 0 0 0 0 _ _ _ 0 0 0 0 0 _ _ 0 0 _ _ _ _ _ 0 0 0 0 0 0 0 _ _ _ 0 0 0 0 0 _ _ 0 _ _ 0 _ 0 _ _ 0 _ _ _ _ _ 0 0 0 _ _ _ _ 0 0 0 0 0 _ _ _ _ _ 0 _ 0 _ _ _ _ _ 0 _ 0 """ |> HLPsolver.solve(adjacent)
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Produce a language-to-language conversion: from Elixir to Go, same semantics.
adjacent = [{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}] """ . . 0 0 0 . . 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0 0 0 0 . . 0 0 . 0 . . . 0 0 0 """ |> HLPsolver.solve(adjacent) """ _ _ _ _ _ 1 _ 0 _ _ _ _ _ 0 _ 0 _ _ _ _ 0 0 0 0 0 _ _ _ _ _ 0 0 0 _ _ 0 _ _ 0 _ 0 _ _ 0 0 0 0 0 0 _ _ _ 0 0 0 0 0 _ _ 0 0 _ _ _ _ _ 0 0 0 0 0 0 0 _ _ _ 0 0 0 0 0 _ _ 0 _ _ 0 _ 0 _ _ 0 _ _ _ _ _ 0 0 0 _ _ _ _ 0 0 0 0 0 _ _ _ _ _ 0 _ 0 _ _ _ _ _ 0 _ 0 """ |> HLPsolver.solve(adjacent)
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
Convert this Elixir snippet to Go and keep its semantics consistent.
adjacent = [{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}] """ . . 0 0 0 . . 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0 0 0 0 . . 0 0 . 0 . . . 0 0 0 """ |> HLPsolver.solve(adjacent) """ _ _ _ _ _ 1 _ 0 _ _ _ _ _ 0 _ 0 _ _ _ _ 0 0 0 0 0 _ _ _ _ _ 0 0 0 _ _ 0 _ _ 0 _ 0 _ _ 0 0 0 0 0 0 _ _ _ 0 0 0 0 0 _ _ 0 0 _ _ _ _ _ 0 0 0 0 0 0 0 _ _ _ 0 0 0 0 0 _ _ 0 _ _ 0 _ 0 _ _ 0 _ _ _ _ _ 0 0 0 _ _ _ _ 0 0 0 0 0 _ _ _ _ _ 0 _ 0 _ _ _ _ _ 0 _ 0 """ |> HLPsolver.solve(adjacent)
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
Write the same algorithm in C# as shown in this Haskell implementation.
import Data.Array (Array, (//), (!), assocs, elems, bounds, listArray) import Data.Foldable (forM_) import Data.List (intercalate, transpose) import Data.Maybe type Position = (Int, Int) type KnightBoard = Array Position (Maybe Int) toSlot :: Char -> Maybe Int toSlot '0' = Just 0 toSlot '1' = Just 1 toSlot _ = Nothing toString :: Maybe Int -> String toString Nothing = replicate 3 ' ' toString (Just n) = replicate (3 - length nn) ' ' ++ nn where nn = show n chunksOf :: Int -> [a] -> [[a]] chunksOf _ [] = [] chunksOf n xs = let (chunk, rest) = splitAt n xs in chunk : chunksOf n rest showBoard :: KnightBoard -> String showBoard board = intercalate "\n" . map concat . transpose . chunksOf (height + 1) . map toString $ elems board where (_, (_, height)) = bounds board toBoard :: [String] -> KnightBoard toBoard strs = board where height = length strs width = minimum (length <$> strs) board = listArray ((0, 0), (width - 1, height - 1)) . map toSlot . concat . transpose $ take width <$> strs add :: Num a => (a, a) -> (a, a) -> (a, a) add (a, b) (x, y) = (a + x, b + y) within :: Ord a => ((a, a), (a, a)) -> (a, a) -> Bool within ((a, b), (c, d)) (x, y) = a <= x && x <= c && b <= y && y <= d validMoves :: KnightBoard -> Position -> [Position] validMoves board position = filter isValid plausible where bound = bounds board plausible = add position <$> [(1, 2), (2, 1), (2, -1), (-1, 2), (-2, 1), (1, -2), (-1, -2), (-2, -1)] isValid pos = within bound pos && maybe False (== 0) (board ! pos) isSolved :: KnightBoard -> Bool isSolved = all (maybe True (0 /=)) solveKnightTour :: KnightBoard -> Maybe KnightBoard solveKnightTour board = solve board 1 initPosition where initPosition = fst $ head $ filter ((== Just 1) . snd) $ assocs board solve boardA depth position = let boardB = boardA // [(position, Just depth)] in if isSolved boardB then Just boardB else listToMaybe $ mapMaybe (solve boardB $ depth + 1) $ validMoves boardB position tourExA :: [String] tourExA = [ " 000 " , " 0 00 " , " 0000000" , "000 0 0" , "0 0 000" , "1000000 " , " 00 0 " , " 000 " ] tourExB :: [String] tourExB = [ " , " , " , " , " , "00000 , " , "00000 , " , " , " , " , " ] main :: IO () main = forM_ [tourExA, tourExB] (\board -> case solveKnightTour $ toBoard board of Nothing -> putStrLn "No solution.\n" Just solution -> putStrLn $ showBoard solution ++ "\n")
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Convert the following code from Haskell to C#, ensuring the logic remains intact.
import Data.Array (Array, (//), (!), assocs, elems, bounds, listArray) import Data.Foldable (forM_) import Data.List (intercalate, transpose) import Data.Maybe type Position = (Int, Int) type KnightBoard = Array Position (Maybe Int) toSlot :: Char -> Maybe Int toSlot '0' = Just 0 toSlot '1' = Just 1 toSlot _ = Nothing toString :: Maybe Int -> String toString Nothing = replicate 3 ' ' toString (Just n) = replicate (3 - length nn) ' ' ++ nn where nn = show n chunksOf :: Int -> [a] -> [[a]] chunksOf _ [] = [] chunksOf n xs = let (chunk, rest) = splitAt n xs in chunk : chunksOf n rest showBoard :: KnightBoard -> String showBoard board = intercalate "\n" . map concat . transpose . chunksOf (height + 1) . map toString $ elems board where (_, (_, height)) = bounds board toBoard :: [String] -> KnightBoard toBoard strs = board where height = length strs width = minimum (length <$> strs) board = listArray ((0, 0), (width - 1, height - 1)) . map toSlot . concat . transpose $ take width <$> strs add :: Num a => (a, a) -> (a, a) -> (a, a) add (a, b) (x, y) = (a + x, b + y) within :: Ord a => ((a, a), (a, a)) -> (a, a) -> Bool within ((a, b), (c, d)) (x, y) = a <= x && x <= c && b <= y && y <= d validMoves :: KnightBoard -> Position -> [Position] validMoves board position = filter isValid plausible where bound = bounds board plausible = add position <$> [(1, 2), (2, 1), (2, -1), (-1, 2), (-2, 1), (1, -2), (-1, -2), (-2, -1)] isValid pos = within bound pos && maybe False (== 0) (board ! pos) isSolved :: KnightBoard -> Bool isSolved = all (maybe True (0 /=)) solveKnightTour :: KnightBoard -> Maybe KnightBoard solveKnightTour board = solve board 1 initPosition where initPosition = fst $ head $ filter ((== Just 1) . snd) $ assocs board solve boardA depth position = let boardB = boardA // [(position, Just depth)] in if isSolved boardB then Just boardB else listToMaybe $ mapMaybe (solve boardB $ depth + 1) $ validMoves boardB position tourExA :: [String] tourExA = [ " 000 " , " 0 00 " , " 0000000" , "000 0 0" , "0 0 000" , "1000000 " , " 00 0 " , " 000 " ] tourExB :: [String] tourExB = [ " , " , " , " , " , "00000 , " , "00000 , " , " , " , " , " ] main :: IO () main = forM_ [tourExA, tourExB] (\board -> case solveKnightTour $ toBoard board of Nothing -> putStrLn "No solution.\n" Just solution -> putStrLn $ showBoard solution ++ "\n")
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Rewrite the snippet below in C++ so it works the same as the original Haskell code.
import Data.Array (Array, (//), (!), assocs, elems, bounds, listArray) import Data.Foldable (forM_) import Data.List (intercalate, transpose) import Data.Maybe type Position = (Int, Int) type KnightBoard = Array Position (Maybe Int) toSlot :: Char -> Maybe Int toSlot '0' = Just 0 toSlot '1' = Just 1 toSlot _ = Nothing toString :: Maybe Int -> String toString Nothing = replicate 3 ' ' toString (Just n) = replicate (3 - length nn) ' ' ++ nn where nn = show n chunksOf :: Int -> [a] -> [[a]] chunksOf _ [] = [] chunksOf n xs = let (chunk, rest) = splitAt n xs in chunk : chunksOf n rest showBoard :: KnightBoard -> String showBoard board = intercalate "\n" . map concat . transpose . chunksOf (height + 1) . map toString $ elems board where (_, (_, height)) = bounds board toBoard :: [String] -> KnightBoard toBoard strs = board where height = length strs width = minimum (length <$> strs) board = listArray ((0, 0), (width - 1, height - 1)) . map toSlot . concat . transpose $ take width <$> strs add :: Num a => (a, a) -> (a, a) -> (a, a) add (a, b) (x, y) = (a + x, b + y) within :: Ord a => ((a, a), (a, a)) -> (a, a) -> Bool within ((a, b), (c, d)) (x, y) = a <= x && x <= c && b <= y && y <= d validMoves :: KnightBoard -> Position -> [Position] validMoves board position = filter isValid plausible where bound = bounds board plausible = add position <$> [(1, 2), (2, 1), (2, -1), (-1, 2), (-2, 1), (1, -2), (-1, -2), (-2, -1)] isValid pos = within bound pos && maybe False (== 0) (board ! pos) isSolved :: KnightBoard -> Bool isSolved = all (maybe True (0 /=)) solveKnightTour :: KnightBoard -> Maybe KnightBoard solveKnightTour board = solve board 1 initPosition where initPosition = fst $ head $ filter ((== Just 1) . snd) $ assocs board solve boardA depth position = let boardB = boardA // [(position, Just depth)] in if isSolved boardB then Just boardB else listToMaybe $ mapMaybe (solve boardB $ depth + 1) $ validMoves boardB position tourExA :: [String] tourExA = [ " 000 " , " 0 00 " , " 0000000" , "000 0 0" , "0 0 000" , "1000000 " , " 00 0 " , " 000 " ] tourExB :: [String] tourExB = [ " , " , " , " , " , "00000 , " , "00000 , " , " , " , " , " ] main :: IO () main = forM_ [tourExA, tourExB] (\board -> case solveKnightTour $ toBoard board of Nothing -> putStrLn "No solution.\n" Just solution -> putStrLn $ showBoard solution ++ "\n")
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Keep all operations the same but rewrite the snippet in C++.
import Data.Array (Array, (//), (!), assocs, elems, bounds, listArray) import Data.Foldable (forM_) import Data.List (intercalate, transpose) import Data.Maybe type Position = (Int, Int) type KnightBoard = Array Position (Maybe Int) toSlot :: Char -> Maybe Int toSlot '0' = Just 0 toSlot '1' = Just 1 toSlot _ = Nothing toString :: Maybe Int -> String toString Nothing = replicate 3 ' ' toString (Just n) = replicate (3 - length nn) ' ' ++ nn where nn = show n chunksOf :: Int -> [a] -> [[a]] chunksOf _ [] = [] chunksOf n xs = let (chunk, rest) = splitAt n xs in chunk : chunksOf n rest showBoard :: KnightBoard -> String showBoard board = intercalate "\n" . map concat . transpose . chunksOf (height + 1) . map toString $ elems board where (_, (_, height)) = bounds board toBoard :: [String] -> KnightBoard toBoard strs = board where height = length strs width = minimum (length <$> strs) board = listArray ((0, 0), (width - 1, height - 1)) . map toSlot . concat . transpose $ take width <$> strs add :: Num a => (a, a) -> (a, a) -> (a, a) add (a, b) (x, y) = (a + x, b + y) within :: Ord a => ((a, a), (a, a)) -> (a, a) -> Bool within ((a, b), (c, d)) (x, y) = a <= x && x <= c && b <= y && y <= d validMoves :: KnightBoard -> Position -> [Position] validMoves board position = filter isValid plausible where bound = bounds board plausible = add position <$> [(1, 2), (2, 1), (2, -1), (-1, 2), (-2, 1), (1, -2), (-1, -2), (-2, -1)] isValid pos = within bound pos && maybe False (== 0) (board ! pos) isSolved :: KnightBoard -> Bool isSolved = all (maybe True (0 /=)) solveKnightTour :: KnightBoard -> Maybe KnightBoard solveKnightTour board = solve board 1 initPosition where initPosition = fst $ head $ filter ((== Just 1) . snd) $ assocs board solve boardA depth position = let boardB = boardA // [(position, Just depth)] in if isSolved boardB then Just boardB else listToMaybe $ mapMaybe (solve boardB $ depth + 1) $ validMoves boardB position tourExA :: [String] tourExA = [ " 000 " , " 0 00 " , " 0000000" , "000 0 0" , "0 0 000" , "1000000 " , " 00 0 " , " 000 " ] tourExB :: [String] tourExB = [ " , " , " , " , " , "00000 , " , "00000 , " , " , " , " , " ] main :: IO () main = forM_ [tourExA, tourExB] (\board -> case solveKnightTour $ toBoard board of Nothing -> putStrLn "No solution.\n" Just solution -> putStrLn $ showBoard solution ++ "\n")
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Generate an equivalent Java version of this Haskell code.
import Data.Array (Array, (//), (!), assocs, elems, bounds, listArray) import Data.Foldable (forM_) import Data.List (intercalate, transpose) import Data.Maybe type Position = (Int, Int) type KnightBoard = Array Position (Maybe Int) toSlot :: Char -> Maybe Int toSlot '0' = Just 0 toSlot '1' = Just 1 toSlot _ = Nothing toString :: Maybe Int -> String toString Nothing = replicate 3 ' ' toString (Just n) = replicate (3 - length nn) ' ' ++ nn where nn = show n chunksOf :: Int -> [a] -> [[a]] chunksOf _ [] = [] chunksOf n xs = let (chunk, rest) = splitAt n xs in chunk : chunksOf n rest showBoard :: KnightBoard -> String showBoard board = intercalate "\n" . map concat . transpose . chunksOf (height + 1) . map toString $ elems board where (_, (_, height)) = bounds board toBoard :: [String] -> KnightBoard toBoard strs = board where height = length strs width = minimum (length <$> strs) board = listArray ((0, 0), (width - 1, height - 1)) . map toSlot . concat . transpose $ take width <$> strs add :: Num a => (a, a) -> (a, a) -> (a, a) add (a, b) (x, y) = (a + x, b + y) within :: Ord a => ((a, a), (a, a)) -> (a, a) -> Bool within ((a, b), (c, d)) (x, y) = a <= x && x <= c && b <= y && y <= d validMoves :: KnightBoard -> Position -> [Position] validMoves board position = filter isValid plausible where bound = bounds board plausible = add position <$> [(1, 2), (2, 1), (2, -1), (-1, 2), (-2, 1), (1, -2), (-1, -2), (-2, -1)] isValid pos = within bound pos && maybe False (== 0) (board ! pos) isSolved :: KnightBoard -> Bool isSolved = all (maybe True (0 /=)) solveKnightTour :: KnightBoard -> Maybe KnightBoard solveKnightTour board = solve board 1 initPosition where initPosition = fst $ head $ filter ((== Just 1) . snd) $ assocs board solve boardA depth position = let boardB = boardA // [(position, Just depth)] in if isSolved boardB then Just boardB else listToMaybe $ mapMaybe (solve boardB $ depth + 1) $ validMoves boardB position tourExA :: [String] tourExA = [ " 000 " , " 0 00 " , " 0000000" , "000 0 0" , "0 0 000" , "1000000 " , " 00 0 " , " 000 " ] tourExB :: [String] tourExB = [ " , " , " , " , " , "00000 , " , "00000 , " , " , " , " , " ] main :: IO () main = forM_ [tourExA, tourExB] (\board -> case solveKnightTour $ toBoard board of Nothing -> putStrLn "No solution.\n" Just solution -> putStrLn $ showBoard solution ++ "\n")
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; 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 = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } 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, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (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) - 1; 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 void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
Produce a language-to-language conversion: from Haskell to Java, same semantics.
import Data.Array (Array, (//), (!), assocs, elems, bounds, listArray) import Data.Foldable (forM_) import Data.List (intercalate, transpose) import Data.Maybe type Position = (Int, Int) type KnightBoard = Array Position (Maybe Int) toSlot :: Char -> Maybe Int toSlot '0' = Just 0 toSlot '1' = Just 1 toSlot _ = Nothing toString :: Maybe Int -> String toString Nothing = replicate 3 ' ' toString (Just n) = replicate (3 - length nn) ' ' ++ nn where nn = show n chunksOf :: Int -> [a] -> [[a]] chunksOf _ [] = [] chunksOf n xs = let (chunk, rest) = splitAt n xs in chunk : chunksOf n rest showBoard :: KnightBoard -> String showBoard board = intercalate "\n" . map concat . transpose . chunksOf (height + 1) . map toString $ elems board where (_, (_, height)) = bounds board toBoard :: [String] -> KnightBoard toBoard strs = board where height = length strs width = minimum (length <$> strs) board = listArray ((0, 0), (width - 1, height - 1)) . map toSlot . concat . transpose $ take width <$> strs add :: Num a => (a, a) -> (a, a) -> (a, a) add (a, b) (x, y) = (a + x, b + y) within :: Ord a => ((a, a), (a, a)) -> (a, a) -> Bool within ((a, b), (c, d)) (x, y) = a <= x && x <= c && b <= y && y <= d validMoves :: KnightBoard -> Position -> [Position] validMoves board position = filter isValid plausible where bound = bounds board plausible = add position <$> [(1, 2), (2, 1), (2, -1), (-1, 2), (-2, 1), (1, -2), (-1, -2), (-2, -1)] isValid pos = within bound pos && maybe False (== 0) (board ! pos) isSolved :: KnightBoard -> Bool isSolved = all (maybe True (0 /=)) solveKnightTour :: KnightBoard -> Maybe KnightBoard solveKnightTour board = solve board 1 initPosition where initPosition = fst $ head $ filter ((== Just 1) . snd) $ assocs board solve boardA depth position = let boardB = boardA // [(position, Just depth)] in if isSolved boardB then Just boardB else listToMaybe $ mapMaybe (solve boardB $ depth + 1) $ validMoves boardB position tourExA :: [String] tourExA = [ " 000 " , " 0 00 " , " 0000000" , "000 0 0" , "0 0 000" , "1000000 " , " 00 0 " , " 000 " ] tourExB :: [String] tourExB = [ " , " , " , " , " , "00000 , " , "00000 , " , " , " , " , " ] main :: IO () main = forM_ [tourExA, tourExB] (\board -> case solveKnightTour $ toBoard board of Nothing -> putStrLn "No solution.\n" Just solution -> putStrLn $ showBoard solution ++ "\n")
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; 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 = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } 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, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (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) - 1; 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 void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
Translate this program into Python but keep the logic exactly as in Haskell.
import Data.Array (Array, (//), (!), assocs, elems, bounds, listArray) import Data.Foldable (forM_) import Data.List (intercalate, transpose) import Data.Maybe type Position = (Int, Int) type KnightBoard = Array Position (Maybe Int) toSlot :: Char -> Maybe Int toSlot '0' = Just 0 toSlot '1' = Just 1 toSlot _ = Nothing toString :: Maybe Int -> String toString Nothing = replicate 3 ' ' toString (Just n) = replicate (3 - length nn) ' ' ++ nn where nn = show n chunksOf :: Int -> [a] -> [[a]] chunksOf _ [] = [] chunksOf n xs = let (chunk, rest) = splitAt n xs in chunk : chunksOf n rest showBoard :: KnightBoard -> String showBoard board = intercalate "\n" . map concat . transpose . chunksOf (height + 1) . map toString $ elems board where (_, (_, height)) = bounds board toBoard :: [String] -> KnightBoard toBoard strs = board where height = length strs width = minimum (length <$> strs) board = listArray ((0, 0), (width - 1, height - 1)) . map toSlot . concat . transpose $ take width <$> strs add :: Num a => (a, a) -> (a, a) -> (a, a) add (a, b) (x, y) = (a + x, b + y) within :: Ord a => ((a, a), (a, a)) -> (a, a) -> Bool within ((a, b), (c, d)) (x, y) = a <= x && x <= c && b <= y && y <= d validMoves :: KnightBoard -> Position -> [Position] validMoves board position = filter isValid plausible where bound = bounds board plausible = add position <$> [(1, 2), (2, 1), (2, -1), (-1, 2), (-2, 1), (1, -2), (-1, -2), (-2, -1)] isValid pos = within bound pos && maybe False (== 0) (board ! pos) isSolved :: KnightBoard -> Bool isSolved = all (maybe True (0 /=)) solveKnightTour :: KnightBoard -> Maybe KnightBoard solveKnightTour board = solve board 1 initPosition where initPosition = fst $ head $ filter ((== Just 1) . snd) $ assocs board solve boardA depth position = let boardB = boardA // [(position, Just depth)] in if isSolved boardB then Just boardB else listToMaybe $ mapMaybe (solve boardB $ depth + 1) $ validMoves boardB position tourExA :: [String] tourExA = [ " 000 " , " 0 00 " , " 0000000" , "000 0 0" , "0 0 000" , "1000000 " , " 00 0 " , " 000 " ] tourExB :: [String] tourExB = [ " , " , " , " , " , "00000 , " , "00000 , " , " , " , " , " ] main :: IO () main = forM_ [tourExA, tourExB] (\board -> case solveKnightTour $ toBoard board of Nothing -> putStrLn "No solution.\n" Just solution -> putStrLn $ showBoard solution ++ "\n")
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Write the same code in Python as shown below in Haskell.
import Data.Array (Array, (//), (!), assocs, elems, bounds, listArray) import Data.Foldable (forM_) import Data.List (intercalate, transpose) import Data.Maybe type Position = (Int, Int) type KnightBoard = Array Position (Maybe Int) toSlot :: Char -> Maybe Int toSlot '0' = Just 0 toSlot '1' = Just 1 toSlot _ = Nothing toString :: Maybe Int -> String toString Nothing = replicate 3 ' ' toString (Just n) = replicate (3 - length nn) ' ' ++ nn where nn = show n chunksOf :: Int -> [a] -> [[a]] chunksOf _ [] = [] chunksOf n xs = let (chunk, rest) = splitAt n xs in chunk : chunksOf n rest showBoard :: KnightBoard -> String showBoard board = intercalate "\n" . map concat . transpose . chunksOf (height + 1) . map toString $ elems board where (_, (_, height)) = bounds board toBoard :: [String] -> KnightBoard toBoard strs = board where height = length strs width = minimum (length <$> strs) board = listArray ((0, 0), (width - 1, height - 1)) . map toSlot . concat . transpose $ take width <$> strs add :: Num a => (a, a) -> (a, a) -> (a, a) add (a, b) (x, y) = (a + x, b + y) within :: Ord a => ((a, a), (a, a)) -> (a, a) -> Bool within ((a, b), (c, d)) (x, y) = a <= x && x <= c && b <= y && y <= d validMoves :: KnightBoard -> Position -> [Position] validMoves board position = filter isValid plausible where bound = bounds board plausible = add position <$> [(1, 2), (2, 1), (2, -1), (-1, 2), (-2, 1), (1, -2), (-1, -2), (-2, -1)] isValid pos = within bound pos && maybe False (== 0) (board ! pos) isSolved :: KnightBoard -> Bool isSolved = all (maybe True (0 /=)) solveKnightTour :: KnightBoard -> Maybe KnightBoard solveKnightTour board = solve board 1 initPosition where initPosition = fst $ head $ filter ((== Just 1) . snd) $ assocs board solve boardA depth position = let boardB = boardA // [(position, Just depth)] in if isSolved boardB then Just boardB else listToMaybe $ mapMaybe (solve boardB $ depth + 1) $ validMoves boardB position tourExA :: [String] tourExA = [ " 000 " , " 0 00 " , " 0000000" , "000 0 0" , "0 0 000" , "1000000 " , " 00 0 " , " 000 " ] tourExB :: [String] tourExB = [ " , " , " , " , " , "00000 , " , "00000 , " , " , " , " , " ] main :: IO () main = forM_ [tourExA, tourExB] (\board -> case solveKnightTour $ toBoard board of Nothing -> putStrLn "No solution.\n" Just solution -> putStrLn $ showBoard solution ++ "\n")
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Translate this program into Go but keep the logic exactly as in Haskell.
import Data.Array (Array, (//), (!), assocs, elems, bounds, listArray) import Data.Foldable (forM_) import Data.List (intercalate, transpose) import Data.Maybe type Position = (Int, Int) type KnightBoard = Array Position (Maybe Int) toSlot :: Char -> Maybe Int toSlot '0' = Just 0 toSlot '1' = Just 1 toSlot _ = Nothing toString :: Maybe Int -> String toString Nothing = replicate 3 ' ' toString (Just n) = replicate (3 - length nn) ' ' ++ nn where nn = show n chunksOf :: Int -> [a] -> [[a]] chunksOf _ [] = [] chunksOf n xs = let (chunk, rest) = splitAt n xs in chunk : chunksOf n rest showBoard :: KnightBoard -> String showBoard board = intercalate "\n" . map concat . transpose . chunksOf (height + 1) . map toString $ elems board where (_, (_, height)) = bounds board toBoard :: [String] -> KnightBoard toBoard strs = board where height = length strs width = minimum (length <$> strs) board = listArray ((0, 0), (width - 1, height - 1)) . map toSlot . concat . transpose $ take width <$> strs add :: Num a => (a, a) -> (a, a) -> (a, a) add (a, b) (x, y) = (a + x, b + y) within :: Ord a => ((a, a), (a, a)) -> (a, a) -> Bool within ((a, b), (c, d)) (x, y) = a <= x && x <= c && b <= y && y <= d validMoves :: KnightBoard -> Position -> [Position] validMoves board position = filter isValid plausible where bound = bounds board plausible = add position <$> [(1, 2), (2, 1), (2, -1), (-1, 2), (-2, 1), (1, -2), (-1, -2), (-2, -1)] isValid pos = within bound pos && maybe False (== 0) (board ! pos) isSolved :: KnightBoard -> Bool isSolved = all (maybe True (0 /=)) solveKnightTour :: KnightBoard -> Maybe KnightBoard solveKnightTour board = solve board 1 initPosition where initPosition = fst $ head $ filter ((== Just 1) . snd) $ assocs board solve boardA depth position = let boardB = boardA // [(position, Just depth)] in if isSolved boardB then Just boardB else listToMaybe $ mapMaybe (solve boardB $ depth + 1) $ validMoves boardB position tourExA :: [String] tourExA = [ " 000 " , " 0 00 " , " 0000000" , "000 0 0" , "0 0 000" , "1000000 " , " 00 0 " , " 000 " ] tourExB :: [String] tourExB = [ " , " , " , " , " , "00000 , " , "00000 , " , " , " , " , " ] main :: IO () main = forM_ [tourExA, tourExB] (\board -> case solveKnightTour $ toBoard board of Nothing -> putStrLn "No solution.\n" Just solution -> putStrLn $ showBoard solution ++ "\n")
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
Write the same algorithm in Go as shown in this Haskell implementation.
import Data.Array (Array, (//), (!), assocs, elems, bounds, listArray) import Data.Foldable (forM_) import Data.List (intercalate, transpose) import Data.Maybe type Position = (Int, Int) type KnightBoard = Array Position (Maybe Int) toSlot :: Char -> Maybe Int toSlot '0' = Just 0 toSlot '1' = Just 1 toSlot _ = Nothing toString :: Maybe Int -> String toString Nothing = replicate 3 ' ' toString (Just n) = replicate (3 - length nn) ' ' ++ nn where nn = show n chunksOf :: Int -> [a] -> [[a]] chunksOf _ [] = [] chunksOf n xs = let (chunk, rest) = splitAt n xs in chunk : chunksOf n rest showBoard :: KnightBoard -> String showBoard board = intercalate "\n" . map concat . transpose . chunksOf (height + 1) . map toString $ elems board where (_, (_, height)) = bounds board toBoard :: [String] -> KnightBoard toBoard strs = board where height = length strs width = minimum (length <$> strs) board = listArray ((0, 0), (width - 1, height - 1)) . map toSlot . concat . transpose $ take width <$> strs add :: Num a => (a, a) -> (a, a) -> (a, a) add (a, b) (x, y) = (a + x, b + y) within :: Ord a => ((a, a), (a, a)) -> (a, a) -> Bool within ((a, b), (c, d)) (x, y) = a <= x && x <= c && b <= y && y <= d validMoves :: KnightBoard -> Position -> [Position] validMoves board position = filter isValid plausible where bound = bounds board plausible = add position <$> [(1, 2), (2, 1), (2, -1), (-1, 2), (-2, 1), (1, -2), (-1, -2), (-2, -1)] isValid pos = within bound pos && maybe False (== 0) (board ! pos) isSolved :: KnightBoard -> Bool isSolved = all (maybe True (0 /=)) solveKnightTour :: KnightBoard -> Maybe KnightBoard solveKnightTour board = solve board 1 initPosition where initPosition = fst $ head $ filter ((== Just 1) . snd) $ assocs board solve boardA depth position = let boardB = boardA // [(position, Just depth)] in if isSolved boardB then Just boardB else listToMaybe $ mapMaybe (solve boardB $ depth + 1) $ validMoves boardB position tourExA :: [String] tourExA = [ " 000 " , " 0 00 " , " 0000000" , "000 0 0" , "0 0 000" , "1000000 " , " 00 0 " , " 000 " ] tourExB :: [String] tourExB = [ " , " , " , " , " , "00000 , " , "00000 , " , " , " , " , " ] main :: IO () main = forM_ [tourExA, tourExB] (\board -> case solveKnightTour $ toBoard board of Nothing -> putStrLn "No solution.\n" Just solution -> putStrLn $ showBoard solution ++ "\n")
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
Translate this program into C# but keep the logic exactly as in J.
9!:21]2^34 unpack=:verb define mask=. +./' '~:y board=. (255 0 1{a.) {~ {.@:>:@:"."0 mask#"1 y ) ex1=:unpack ];._2]0 :0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 ) solve=:verb define board=.,:y for_move.1+i.+/({.a.)=,y do. board=. ;move <@knight"2 board end. ) kmoves=: ,/(2 1,:1 2)*"1/_1^#:i.4 knight=:dyad define pos=. ($y)#:(,y)i.x{a. moves=. <"1(#~ 0&<: */"1@:* ($y)&>"1)pos+"1 kmoves moves=. (#~ (0{a.)={&y) moves moves y adverb def (':';'y x} m')"0 (x+1){a. )
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Convert the following code from J to C#, ensuring the logic remains intact.
9!:21]2^34 unpack=:verb define mask=. +./' '~:y board=. (255 0 1{a.) {~ {.@:>:@:"."0 mask#"1 y ) ex1=:unpack ];._2]0 :0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 ) solve=:verb define board=.,:y for_move.1+i.+/({.a.)=,y do. board=. ;move <@knight"2 board end. ) kmoves=: ,/(2 1,:1 2)*"1/_1^#:i.4 knight=:dyad define pos=. ($y)#:(,y)i.x{a. moves=. <"1(#~ 0&<: */"1@:* ($y)&>"1)pos+"1 kmoves moves=. (#~ (0{a.)={&y) moves moves y adverb def (':';'y x} m')"0 (x+1){a. )
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Convert this J snippet to C++ and keep its semantics consistent.
9!:21]2^34 unpack=:verb define mask=. +./' '~:y board=. (255 0 1{a.) {~ {.@:>:@:"."0 mask#"1 y ) ex1=:unpack ];._2]0 :0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 ) solve=:verb define board=.,:y for_move.1+i.+/({.a.)=,y do. board=. ;move <@knight"2 board end. ) kmoves=: ,/(2 1,:1 2)*"1/_1^#:i.4 knight=:dyad define pos=. ($y)#:(,y)i.x{a. moves=. <"1(#~ 0&<: */"1@:* ($y)&>"1)pos+"1 kmoves moves=. (#~ (0{a.)={&y) moves moves y adverb def (':';'y x} m')"0 (x+1){a. )
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Convert the following code from J to C++, ensuring the logic remains intact.
9!:21]2^34 unpack=:verb define mask=. +./' '~:y board=. (255 0 1{a.) {~ {.@:>:@:"."0 mask#"1 y ) ex1=:unpack ];._2]0 :0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 ) solve=:verb define board=.,:y for_move.1+i.+/({.a.)=,y do. board=. ;move <@knight"2 board end. ) kmoves=: ,/(2 1,:1 2)*"1/_1^#:i.4 knight=:dyad define pos=. ($y)#:(,y)i.x{a. moves=. <"1(#~ 0&<: */"1@:* ($y)&>"1)pos+"1 kmoves moves=. (#~ (0{a.)={&y) moves moves y adverb def (':';'y x} m')"0 (x+1){a. )
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Translate this program into Java but keep the logic exactly as in J.
9!:21]2^34 unpack=:verb define mask=. +./' '~:y board=. (255 0 1{a.) {~ {.@:>:@:"."0 mask#"1 y ) ex1=:unpack ];._2]0 :0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 ) solve=:verb define board=.,:y for_move.1+i.+/({.a.)=,y do. board=. ;move <@knight"2 board end. ) kmoves=: ,/(2 1,:1 2)*"1/_1^#:i.4 knight=:dyad define pos=. ($y)#:(,y)i.x{a. moves=. <"1(#~ 0&<: */"1@:* ($y)&>"1)pos+"1 kmoves moves=. (#~ (0{a.)={&y) moves moves y adverb def (':';'y x} m')"0 (x+1){a. )
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; 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 = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } 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, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (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) - 1; 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 void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
Rewrite this program in Java while keeping its functionality equivalent to the J version.
9!:21]2^34 unpack=:verb define mask=. +./' '~:y board=. (255 0 1{a.) {~ {.@:>:@:"."0 mask#"1 y ) ex1=:unpack ];._2]0 :0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 ) solve=:verb define board=.,:y for_move.1+i.+/({.a.)=,y do. board=. ;move <@knight"2 board end. ) kmoves=: ,/(2 1,:1 2)*"1/_1^#:i.4 knight=:dyad define pos=. ($y)#:(,y)i.x{a. moves=. <"1(#~ 0&<: */"1@:* ($y)&>"1)pos+"1 kmoves moves=. (#~ (0{a.)={&y) moves moves y adverb def (':';'y x} m')"0 (x+1){a. )
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; 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 = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } 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, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (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) - 1; 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 void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
Generate a Python translation of this J snippet without changing its computational steps.
9!:21]2^34 unpack=:verb define mask=. +./' '~:y board=. (255 0 1{a.) {~ {.@:>:@:"."0 mask#"1 y ) ex1=:unpack ];._2]0 :0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 ) solve=:verb define board=.,:y for_move.1+i.+/({.a.)=,y do. board=. ;move <@knight"2 board end. ) kmoves=: ,/(2 1,:1 2)*"1/_1^#:i.4 knight=:dyad define pos=. ($y)#:(,y)i.x{a. moves=. <"1(#~ 0&<: */"1@:* ($y)&>"1)pos+"1 kmoves moves=. (#~ (0{a.)={&y) moves moves y adverb def (':';'y x} m')"0 (x+1){a. )
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Translate this program into Python but keep the logic exactly as in J.
9!:21]2^34 unpack=:verb define mask=. +./' '~:y board=. (255 0 1{a.) {~ {.@:>:@:"."0 mask#"1 y ) ex1=:unpack ];._2]0 :0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 ) solve=:verb define board=.,:y for_move.1+i.+/({.a.)=,y do. board=. ;move <@knight"2 board end. ) kmoves=: ,/(2 1,:1 2)*"1/_1^#:i.4 knight=:dyad define pos=. ($y)#:(,y)i.x{a. moves=. <"1(#~ 0&<: */"1@:* ($y)&>"1)pos+"1 kmoves moves=. (#~ (0{a.)={&y) moves moves y adverb def (':';'y x} m')"0 (x+1){a. )
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Preserve the algorithm and functionality while converting the code from J to Go.
9!:21]2^34 unpack=:verb define mask=. +./' '~:y board=. (255 0 1{a.) {~ {.@:>:@:"."0 mask#"1 y ) ex1=:unpack ];._2]0 :0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 ) solve=:verb define board=.,:y for_move.1+i.+/({.a.)=,y do. board=. ;move <@knight"2 board end. ) kmoves=: ,/(2 1,:1 2)*"1/_1^#:i.4 knight=:dyad define pos=. ($y)#:(,y)i.x{a. moves=. <"1(#~ 0&<: */"1@:* ($y)&>"1)pos+"1 kmoves moves=. (#~ (0{a.)={&y) moves moves y adverb def (':';'y x} m')"0 (x+1){a. )
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
Rewrite the snippet below in Go so it works the same as the original J code.
9!:21]2^34 unpack=:verb define mask=. +./' '~:y board=. (255 0 1{a.) {~ {.@:>:@:"."0 mask#"1 y ) ex1=:unpack ];._2]0 :0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 ) solve=:verb define board=.,:y for_move.1+i.+/({.a.)=,y do. board=. ;move <@knight"2 board end. ) kmoves=: ,/(2 1,:1 2)*"1/_1^#:i.4 knight=:dyad define pos=. ($y)#:(,y)i.x{a. moves=. <"1(#~ 0&<: */"1@:* ($y)&>"1)pos+"1 kmoves moves=. (#~ (0{a.)={&y) moves moves y adverb def (':';'y x} m')"0 (x+1){a. )
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
Maintain the same structure and functionality when rewriting this code in C#.
using .Hidato const holyknight = """ . 0 0 0 . . . . . 0 . 0 0 . . . . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0 0 0 0 . . . 0 0 . 0 . . . . . 0 0 0 . . """ const knightmoves = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]] board, maxmoves, fixed, starts = hidatoconfigure(holyknight) printboard(board, " 0", " ") hidatosolve(board, maxmoves, knightmoves, fixed, starts[1][1], starts[1][2], 1) printboard(board)
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Write the same algorithm in C# as shown in this Julia implementation.
using .Hidato const holyknight = """ . 0 0 0 . . . . . 0 . 0 0 . . . . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0 0 0 0 . . . 0 0 . 0 . . . . . 0 0 0 . . """ const knightmoves = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]] board, maxmoves, fixed, starts = hidatoconfigure(holyknight) printboard(board, " 0", " ") hidatosolve(board, maxmoves, knightmoves, fixed, starts[1][1], starts[1][2], 1) printboard(board)
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Produce a functionally identical C++ code for the snippet given in Julia.
using .Hidato const holyknight = """ . 0 0 0 . . . . . 0 . 0 0 . . . . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0 0 0 0 . . . 0 0 . 0 . . . . . 0 0 0 . . """ const knightmoves = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]] board, maxmoves, fixed, starts = hidatoconfigure(holyknight) printboard(board, " 0", " ") hidatosolve(board, maxmoves, knightmoves, fixed, starts[1][1], starts[1][2], 1) printboard(board)
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Change the following Julia code into C++ without altering its purpose.
using .Hidato const holyknight = """ . 0 0 0 . . . . . 0 . 0 0 . . . . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0 0 0 0 . . . 0 0 . 0 . . . . . 0 0 0 . . """ const knightmoves = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]] board, maxmoves, fixed, starts = hidatoconfigure(holyknight) printboard(board, " 0", " ") hidatosolve(board, maxmoves, knightmoves, fixed, starts[1][1], starts[1][2], 1) printboard(board)
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Convert this Julia snippet to Java and keep its semantics consistent.
using .Hidato const holyknight = """ . 0 0 0 . . . . . 0 . 0 0 . . . . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0 0 0 0 . . . 0 0 . 0 . . . . . 0 0 0 . . """ const knightmoves = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]] board, maxmoves, fixed, starts = hidatoconfigure(holyknight) printboard(board, " 0", " ") hidatosolve(board, maxmoves, knightmoves, fixed, starts[1][1], starts[1][2], 1) printboard(board)
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; 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 = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } 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, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (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) - 1; 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 void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
Write the same algorithm in Java as shown in this Julia implementation.
using .Hidato const holyknight = """ . 0 0 0 . . . . . 0 . 0 0 . . . . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0 0 0 0 . . . 0 0 . 0 . . . . . 0 0 0 . . """ const knightmoves = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]] board, maxmoves, fixed, starts = hidatoconfigure(holyknight) printboard(board, " 0", " ") hidatosolve(board, maxmoves, knightmoves, fixed, starts[1][1], starts[1][2], 1) printboard(board)
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; 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 = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } 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, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (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) - 1; 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 void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
Change the programming language of this snippet from Julia to Python without modifying what it does.
using .Hidato const holyknight = """ . 0 0 0 . . . . . 0 . 0 0 . . . . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0 0 0 0 . . . 0 0 . 0 . . . . . 0 0 0 . . """ const knightmoves = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]] board, maxmoves, fixed, starts = hidatoconfigure(holyknight) printboard(board, " 0", " ") hidatosolve(board, maxmoves, knightmoves, fixed, starts[1][1], starts[1][2], 1) printboard(board)
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Maintain the same structure and functionality when rewriting this code in Go.
using .Hidato const holyknight = """ . 0 0 0 . . . . . 0 . 0 0 . . . . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0 0 0 0 . . . 0 0 . 0 . . . . . 0 0 0 . . """ const knightmoves = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]] board, maxmoves, fixed, starts = hidatoconfigure(holyknight) printboard(board, " 0", " ") hidatosolve(board, maxmoves, knightmoves, fixed, starts[1][1], starts[1][2], 1) printboard(board)
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
Translate this program into Go but keep the logic exactly as in Julia.
using .Hidato const holyknight = """ . 0 0 0 . . . . . 0 . 0 0 . . . . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0 0 0 0 . . . 0 0 . 0 . . . . . 0 0 0 . . """ const knightmoves = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]] board, maxmoves, fixed, starts = hidatoconfigure(holyknight) printboard(board, " 0", " ") hidatosolve(board, maxmoves, knightmoves, fixed, starts[1][1], starts[1][2], 1) printboard(board)
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
Write the same algorithm in C# as shown in this Lua implementation.
local p1, p1W = ".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8 local p2, p2W = ".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13 local puzzle, movesCnt, wid = {}, 0, 0 local moves = { { -1, -2 }, { 1, -2 }, { -1, 2 }, { 1, 2 }, { -2, -1 }, { -2, 1 }, { 2, -1 }, { 2, 1 } } function isValid( x, y ) return( x > 0 and x <= wid and y > 0 and y <= wid and puzzle[x + y * wid - wid] == 0 ) end function solve( x, y, s ) if s > movesCnt then return true end local test, a, b for i = 1, #moves do test = false a = x + moves[i][1]; b = y + moves[i][2] if isValid( a, b ) then puzzle[a + b * wid - wid] = s if solve( a, b, s + 1 ) then return true end puzzle[a + b * wid - wid] = 0 end end return false end function printSolution() local lp for j = 1, wid do for i = 1, wid do lp = puzzle[i + j * wid - wid] if lp == -1 then io.write( " " ) else io.write( string.format( " %.2d", lp ) ) end end print() end print( "\n" ) end local sx, sy function fill( pz, w ) puzzle = {}; wid = w; movesCnt = #pz local lp for i = 1, #pz do lp = pz:sub( i, i ) if lp == "x" then table.insert( puzzle, 0 ) elseif lp == "." then table.insert( puzzle, -1 ); movesCnt = movesCnt - 1 else table.insert( puzzle, 1 ) sx = 1 + ( i - 1 ) % wid; sy = math.floor( ( i + wid - 1 ) / wid ) end end end print( "\n\n" ); fill( p1, p1W ); if solve( sx, sy, 2 ) then printSolution() end print( "\n\n" ); fill( p2, p2W ); if solve( sx, sy, 2 ) then printSolution() end
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Convert this Lua snippet to C# and keep its semantics consistent.
local p1, p1W = ".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8 local p2, p2W = ".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13 local puzzle, movesCnt, wid = {}, 0, 0 local moves = { { -1, -2 }, { 1, -2 }, { -1, 2 }, { 1, 2 }, { -2, -1 }, { -2, 1 }, { 2, -1 }, { 2, 1 } } function isValid( x, y ) return( x > 0 and x <= wid and y > 0 and y <= wid and puzzle[x + y * wid - wid] == 0 ) end function solve( x, y, s ) if s > movesCnt then return true end local test, a, b for i = 1, #moves do test = false a = x + moves[i][1]; b = y + moves[i][2] if isValid( a, b ) then puzzle[a + b * wid - wid] = s if solve( a, b, s + 1 ) then return true end puzzle[a + b * wid - wid] = 0 end end return false end function printSolution() local lp for j = 1, wid do for i = 1, wid do lp = puzzle[i + j * wid - wid] if lp == -1 then io.write( " " ) else io.write( string.format( " %.2d", lp ) ) end end print() end print( "\n" ) end local sx, sy function fill( pz, w ) puzzle = {}; wid = w; movesCnt = #pz local lp for i = 1, #pz do lp = pz:sub( i, i ) if lp == "x" then table.insert( puzzle, 0 ) elseif lp == "." then table.insert( puzzle, -1 ); movesCnt = movesCnt - 1 else table.insert( puzzle, 1 ) sx = 1 + ( i - 1 ) % wid; sy = math.floor( ( i + wid - 1 ) / wid ) end end end print( "\n\n" ); fill( p1, p1W ); if solve( sx, sy, 2 ) then printSolution() end print( "\n\n" ); fill( p2, p2W ); if solve( sx, sy, 2 ) then printSolution() end
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Produce a language-to-language conversion: from Lua to C++, same semantics.
local p1, p1W = ".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8 local p2, p2W = ".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13 local puzzle, movesCnt, wid = {}, 0, 0 local moves = { { -1, -2 }, { 1, -2 }, { -1, 2 }, { 1, 2 }, { -2, -1 }, { -2, 1 }, { 2, -1 }, { 2, 1 } } function isValid( x, y ) return( x > 0 and x <= wid and y > 0 and y <= wid and puzzle[x + y * wid - wid] == 0 ) end function solve( x, y, s ) if s > movesCnt then return true end local test, a, b for i = 1, #moves do test = false a = x + moves[i][1]; b = y + moves[i][2] if isValid( a, b ) then puzzle[a + b * wid - wid] = s if solve( a, b, s + 1 ) then return true end puzzle[a + b * wid - wid] = 0 end end return false end function printSolution() local lp for j = 1, wid do for i = 1, wid do lp = puzzle[i + j * wid - wid] if lp == -1 then io.write( " " ) else io.write( string.format( " %.2d", lp ) ) end end print() end print( "\n" ) end local sx, sy function fill( pz, w ) puzzle = {}; wid = w; movesCnt = #pz local lp for i = 1, #pz do lp = pz:sub( i, i ) if lp == "x" then table.insert( puzzle, 0 ) elseif lp == "." then table.insert( puzzle, -1 ); movesCnt = movesCnt - 1 else table.insert( puzzle, 1 ) sx = 1 + ( i - 1 ) % wid; sy = math.floor( ( i + wid - 1 ) / wid ) end end end print( "\n\n" ); fill( p1, p1W ); if solve( sx, sy, 2 ) then printSolution() end print( "\n\n" ); fill( p2, p2W ); if solve( sx, sy, 2 ) then printSolution() end
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Generate a C++ translation of this Lua snippet without changing its computational steps.
local p1, p1W = ".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8 local p2, p2W = ".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13 local puzzle, movesCnt, wid = {}, 0, 0 local moves = { { -1, -2 }, { 1, -2 }, { -1, 2 }, { 1, 2 }, { -2, -1 }, { -2, 1 }, { 2, -1 }, { 2, 1 } } function isValid( x, y ) return( x > 0 and x <= wid and y > 0 and y <= wid and puzzle[x + y * wid - wid] == 0 ) end function solve( x, y, s ) if s > movesCnt then return true end local test, a, b for i = 1, #moves do test = false a = x + moves[i][1]; b = y + moves[i][2] if isValid( a, b ) then puzzle[a + b * wid - wid] = s if solve( a, b, s + 1 ) then return true end puzzle[a + b * wid - wid] = 0 end end return false end function printSolution() local lp for j = 1, wid do for i = 1, wid do lp = puzzle[i + j * wid - wid] if lp == -1 then io.write( " " ) else io.write( string.format( " %.2d", lp ) ) end end print() end print( "\n" ) end local sx, sy function fill( pz, w ) puzzle = {}; wid = w; movesCnt = #pz local lp for i = 1, #pz do lp = pz:sub( i, i ) if lp == "x" then table.insert( puzzle, 0 ) elseif lp == "." then table.insert( puzzle, -1 ); movesCnt = movesCnt - 1 else table.insert( puzzle, 1 ) sx = 1 + ( i - 1 ) % wid; sy = math.floor( ( i + wid - 1 ) / wid ) end end end print( "\n\n" ); fill( p1, p1W ); if solve( sx, sy, 2 ) then printSolution() end print( "\n\n" ); fill( p2, p2W ); if solve( sx, sy, 2 ) then printSolution() end
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Write the same algorithm in Java as shown in this Lua implementation.
local p1, p1W = ".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8 local p2, p2W = ".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13 local puzzle, movesCnt, wid = {}, 0, 0 local moves = { { -1, -2 }, { 1, -2 }, { -1, 2 }, { 1, 2 }, { -2, -1 }, { -2, 1 }, { 2, -1 }, { 2, 1 } } function isValid( x, y ) return( x > 0 and x <= wid and y > 0 and y <= wid and puzzle[x + y * wid - wid] == 0 ) end function solve( x, y, s ) if s > movesCnt then return true end local test, a, b for i = 1, #moves do test = false a = x + moves[i][1]; b = y + moves[i][2] if isValid( a, b ) then puzzle[a + b * wid - wid] = s if solve( a, b, s + 1 ) then return true end puzzle[a + b * wid - wid] = 0 end end return false end function printSolution() local lp for j = 1, wid do for i = 1, wid do lp = puzzle[i + j * wid - wid] if lp == -1 then io.write( " " ) else io.write( string.format( " %.2d", lp ) ) end end print() end print( "\n" ) end local sx, sy function fill( pz, w ) puzzle = {}; wid = w; movesCnt = #pz local lp for i = 1, #pz do lp = pz:sub( i, i ) if lp == "x" then table.insert( puzzle, 0 ) elseif lp == "." then table.insert( puzzle, -1 ); movesCnt = movesCnt - 1 else table.insert( puzzle, 1 ) sx = 1 + ( i - 1 ) % wid; sy = math.floor( ( i + wid - 1 ) / wid ) end end end print( "\n\n" ); fill( p1, p1W ); if solve( sx, sy, 2 ) then printSolution() end print( "\n\n" ); fill( p2, p2W ); if solve( sx, sy, 2 ) then printSolution() end
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; 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 = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } 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, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (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) - 1; 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 void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
Generate a Java translation of this Lua snippet without changing its computational steps.
local p1, p1W = ".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8 local p2, p2W = ".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13 local puzzle, movesCnt, wid = {}, 0, 0 local moves = { { -1, -2 }, { 1, -2 }, { -1, 2 }, { 1, 2 }, { -2, -1 }, { -2, 1 }, { 2, -1 }, { 2, 1 } } function isValid( x, y ) return( x > 0 and x <= wid and y > 0 and y <= wid and puzzle[x + y * wid - wid] == 0 ) end function solve( x, y, s ) if s > movesCnt then return true end local test, a, b for i = 1, #moves do test = false a = x + moves[i][1]; b = y + moves[i][2] if isValid( a, b ) then puzzle[a + b * wid - wid] = s if solve( a, b, s + 1 ) then return true end puzzle[a + b * wid - wid] = 0 end end return false end function printSolution() local lp for j = 1, wid do for i = 1, wid do lp = puzzle[i + j * wid - wid] if lp == -1 then io.write( " " ) else io.write( string.format( " %.2d", lp ) ) end end print() end print( "\n" ) end local sx, sy function fill( pz, w ) puzzle = {}; wid = w; movesCnt = #pz local lp for i = 1, #pz do lp = pz:sub( i, i ) if lp == "x" then table.insert( puzzle, 0 ) elseif lp == "." then table.insert( puzzle, -1 ); movesCnt = movesCnt - 1 else table.insert( puzzle, 1 ) sx = 1 + ( i - 1 ) % wid; sy = math.floor( ( i + wid - 1 ) / wid ) end end end print( "\n\n" ); fill( p1, p1W ); if solve( sx, sy, 2 ) then printSolution() end print( "\n\n" ); fill( p2, p2W ); if solve( sx, sy, 2 ) then printSolution() end
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; 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 = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } 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, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (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) - 1; 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 void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
Please provide an equivalent version of this Lua code in Python.
local p1, p1W = ".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8 local p2, p2W = ".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13 local puzzle, movesCnt, wid = {}, 0, 0 local moves = { { -1, -2 }, { 1, -2 }, { -1, 2 }, { 1, 2 }, { -2, -1 }, { -2, 1 }, { 2, -1 }, { 2, 1 } } function isValid( x, y ) return( x > 0 and x <= wid and y > 0 and y <= wid and puzzle[x + y * wid - wid] == 0 ) end function solve( x, y, s ) if s > movesCnt then return true end local test, a, b for i = 1, #moves do test = false a = x + moves[i][1]; b = y + moves[i][2] if isValid( a, b ) then puzzle[a + b * wid - wid] = s if solve( a, b, s + 1 ) then return true end puzzle[a + b * wid - wid] = 0 end end return false end function printSolution() local lp for j = 1, wid do for i = 1, wid do lp = puzzle[i + j * wid - wid] if lp == -1 then io.write( " " ) else io.write( string.format( " %.2d", lp ) ) end end print() end print( "\n" ) end local sx, sy function fill( pz, w ) puzzle = {}; wid = w; movesCnt = #pz local lp for i = 1, #pz do lp = pz:sub( i, i ) if lp == "x" then table.insert( puzzle, 0 ) elseif lp == "." then table.insert( puzzle, -1 ); movesCnt = movesCnt - 1 else table.insert( puzzle, 1 ) sx = 1 + ( i - 1 ) % wid; sy = math.floor( ( i + wid - 1 ) / wid ) end end end print( "\n\n" ); fill( p1, p1W ); if solve( sx, sy, 2 ) then printSolution() end print( "\n\n" ); fill( p2, p2W ); if solve( sx, sy, 2 ) then printSolution() end
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Please provide an equivalent version of this Lua code in Python.
local p1, p1W = ".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8 local p2, p2W = ".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13 local puzzle, movesCnt, wid = {}, 0, 0 local moves = { { -1, -2 }, { 1, -2 }, { -1, 2 }, { 1, 2 }, { -2, -1 }, { -2, 1 }, { 2, -1 }, { 2, 1 } } function isValid( x, y ) return( x > 0 and x <= wid and y > 0 and y <= wid and puzzle[x + y * wid - wid] == 0 ) end function solve( x, y, s ) if s > movesCnt then return true end local test, a, b for i = 1, #moves do test = false a = x + moves[i][1]; b = y + moves[i][2] if isValid( a, b ) then puzzle[a + b * wid - wid] = s if solve( a, b, s + 1 ) then return true end puzzle[a + b * wid - wid] = 0 end end return false end function printSolution() local lp for j = 1, wid do for i = 1, wid do lp = puzzle[i + j * wid - wid] if lp == -1 then io.write( " " ) else io.write( string.format( " %.2d", lp ) ) end end print() end print( "\n" ) end local sx, sy function fill( pz, w ) puzzle = {}; wid = w; movesCnt = #pz local lp for i = 1, #pz do lp = pz:sub( i, i ) if lp == "x" then table.insert( puzzle, 0 ) elseif lp == "." then table.insert( puzzle, -1 ); movesCnt = movesCnt - 1 else table.insert( puzzle, 1 ) sx = 1 + ( i - 1 ) % wid; sy = math.floor( ( i + wid - 1 ) / wid ) end end end print( "\n\n" ); fill( p1, p1W ); if solve( sx, sy, 2 ) then printSolution() end print( "\n\n" ); fill( p2, p2W ); if solve( sx, sy, 2 ) then printSolution() end
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Write a version of this Lua function in Go with identical behavior.
local p1, p1W = ".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8 local p2, p2W = ".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13 local puzzle, movesCnt, wid = {}, 0, 0 local moves = { { -1, -2 }, { 1, -2 }, { -1, 2 }, { 1, 2 }, { -2, -1 }, { -2, 1 }, { 2, -1 }, { 2, 1 } } function isValid( x, y ) return( x > 0 and x <= wid and y > 0 and y <= wid and puzzle[x + y * wid - wid] == 0 ) end function solve( x, y, s ) if s > movesCnt then return true end local test, a, b for i = 1, #moves do test = false a = x + moves[i][1]; b = y + moves[i][2] if isValid( a, b ) then puzzle[a + b * wid - wid] = s if solve( a, b, s + 1 ) then return true end puzzle[a + b * wid - wid] = 0 end end return false end function printSolution() local lp for j = 1, wid do for i = 1, wid do lp = puzzle[i + j * wid - wid] if lp == -1 then io.write( " " ) else io.write( string.format( " %.2d", lp ) ) end end print() end print( "\n" ) end local sx, sy function fill( pz, w ) puzzle = {}; wid = w; movesCnt = #pz local lp for i = 1, #pz do lp = pz:sub( i, i ) if lp == "x" then table.insert( puzzle, 0 ) elseif lp == "." then table.insert( puzzle, -1 ); movesCnt = movesCnt - 1 else table.insert( puzzle, 1 ) sx = 1 + ( i - 1 ) % wid; sy = math.floor( ( i + wid - 1 ) / wid ) end end end print( "\n\n" ); fill( p1, p1W ); if solve( sx, sy, 2 ) then printSolution() end print( "\n\n" ); fill( p2, p2W ); if solve( sx, sy, 2 ) then printSolution() end
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
Change the following Lua code into Go without altering its purpose.
local p1, p1W = ".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8 local p2, p2W = ".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13 local puzzle, movesCnt, wid = {}, 0, 0 local moves = { { -1, -2 }, { 1, -2 }, { -1, 2 }, { 1, 2 }, { -2, -1 }, { -2, 1 }, { 2, -1 }, { 2, 1 } } function isValid( x, y ) return( x > 0 and x <= wid and y > 0 and y <= wid and puzzle[x + y * wid - wid] == 0 ) end function solve( x, y, s ) if s > movesCnt then return true end local test, a, b for i = 1, #moves do test = false a = x + moves[i][1]; b = y + moves[i][2] if isValid( a, b ) then puzzle[a + b * wid - wid] = s if solve( a, b, s + 1 ) then return true end puzzle[a + b * wid - wid] = 0 end end return false end function printSolution() local lp for j = 1, wid do for i = 1, wid do lp = puzzle[i + j * wid - wid] if lp == -1 then io.write( " " ) else io.write( string.format( " %.2d", lp ) ) end end print() end print( "\n" ) end local sx, sy function fill( pz, w ) puzzle = {}; wid = w; movesCnt = #pz local lp for i = 1, #pz do lp = pz:sub( i, i ) if lp == "x" then table.insert( puzzle, 0 ) elseif lp == "." then table.insert( puzzle, -1 ); movesCnt = movesCnt - 1 else table.insert( puzzle, 1 ) sx = 1 + ( i - 1 ) % wid; sy = math.floor( ( i + wid - 1 ) / wid ) end end end print( "\n\n" ); fill( p1, p1W ); if solve( sx, sy, 2 ) then printSolution() end print( "\n\n" ); fill( p2, p2W ); if solve( sx, sy, 2 ) then printSolution() end
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
Translate the given Mathematica code snippet into C# without altering its behavior.
puzzle = " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0"; puzzle = StringSplit[puzzle, "\n"]; puzzle = StringTake[#, {1, -1, 2}] & /@ puzzle; pos0 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "0"][[All, 1]], {i, Length@puzzle}]; pos1 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "1"][[All, 1]], {i, Length@puzzle}]; allpoints = Join[pos1, pos0]; validmoves = Select[Subsets[allpoints, {2}], Differences /* Norm /* EqualTo[Sqrt[5]]]; g = Graph[UndirectedEdge @@@ validmoves]; e = VertexList[g]; order = FindShortestTour[g][[2]] Graphics[{Red, Disk[#, 0.2] & /@ e, Black, BlockMap[Arrow, e[[order]], 2, 1]}]
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Transform the following Mathematica implementation into C#, maintaining the same output and logic.
puzzle = " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0"; puzzle = StringSplit[puzzle, "\n"]; puzzle = StringTake[#, {1, -1, 2}] & /@ puzzle; pos0 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "0"][[All, 1]], {i, Length@puzzle}]; pos1 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "1"][[All, 1]], {i, Length@puzzle}]; allpoints = Join[pos1, pos0]; validmoves = Select[Subsets[allpoints, {2}], Differences /* Norm /* EqualTo[Sqrt[5]]]; g = Graph[UndirectedEdge @@@ validmoves]; e = VertexList[g]; order = FindShortestTour[g][[2]] Graphics[{Red, Disk[#, 0.2] & /@ e, Black, BlockMap[Arrow, e[[order]], 2, 1]}]
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Port the provided Mathematica code into C++ while preserving the original functionality.
puzzle = " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0"; puzzle = StringSplit[puzzle, "\n"]; puzzle = StringTake[#, {1, -1, 2}] & /@ puzzle; pos0 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "0"][[All, 1]], {i, Length@puzzle}]; pos1 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "1"][[All, 1]], {i, Length@puzzle}]; allpoints = Join[pos1, pos0]; validmoves = Select[Subsets[allpoints, {2}], Differences /* Norm /* EqualTo[Sqrt[5]]]; g = Graph[UndirectedEdge @@@ validmoves]; e = VertexList[g]; order = FindShortestTour[g][[2]] Graphics[{Red, Disk[#, 0.2] & /@ e, Black, BlockMap[Arrow, e[[order]], 2, 1]}]
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Change the following Mathematica code into C++ without altering its purpose.
puzzle = " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0"; puzzle = StringSplit[puzzle, "\n"]; puzzle = StringTake[#, {1, -1, 2}] & /@ puzzle; pos0 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "0"][[All, 1]], {i, Length@puzzle}]; pos1 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "1"][[All, 1]], {i, Length@puzzle}]; allpoints = Join[pos1, pos0]; validmoves = Select[Subsets[allpoints, {2}], Differences /* Norm /* EqualTo[Sqrt[5]]]; g = Graph[UndirectedEdge @@@ validmoves]; e = VertexList[g]; order = FindShortestTour[g][[2]] Graphics[{Red, Disk[#, 0.2] & /@ e, Black, BlockMap[Arrow, e[[order]], 2, 1]}]
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Convert this Mathematica snippet to Java and keep its semantics consistent.
puzzle = " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0"; puzzle = StringSplit[puzzle, "\n"]; puzzle = StringTake[#, {1, -1, 2}] & /@ puzzle; pos0 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "0"][[All, 1]], {i, Length@puzzle}]; pos1 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "1"][[All, 1]], {i, Length@puzzle}]; allpoints = Join[pos1, pos0]; validmoves = Select[Subsets[allpoints, {2}], Differences /* Norm /* EqualTo[Sqrt[5]]]; g = Graph[UndirectedEdge @@@ validmoves]; e = VertexList[g]; order = FindShortestTour[g][[2]] Graphics[{Red, Disk[#, 0.2] & /@ e, Black, BlockMap[Arrow, e[[order]], 2, 1]}]
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; 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 = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } 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, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (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) - 1; 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 void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
Convert the following code from Mathematica to Java, ensuring the logic remains intact.
puzzle = " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0"; puzzle = StringSplit[puzzle, "\n"]; puzzle = StringTake[#, {1, -1, 2}] & /@ puzzle; pos0 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "0"][[All, 1]], {i, Length@puzzle}]; pos1 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "1"][[All, 1]], {i, Length@puzzle}]; allpoints = Join[pos1, pos0]; validmoves = Select[Subsets[allpoints, {2}], Differences /* Norm /* EqualTo[Sqrt[5]]]; g = Graph[UndirectedEdge @@@ validmoves]; e = VertexList[g]; order = FindShortestTour[g][[2]] Graphics[{Red, Disk[#, 0.2] & /@ e, Black, BlockMap[Arrow, e[[order]], 2, 1]}]
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; 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 = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } 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, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (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) - 1; 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 void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
Rewrite the snippet below in Python so it works the same as the original Mathematica code.
puzzle = " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0"; puzzle = StringSplit[puzzle, "\n"]; puzzle = StringTake[#, {1, -1, 2}] & /@ puzzle; pos0 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "0"][[All, 1]], {i, Length@puzzle}]; pos1 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "1"][[All, 1]], {i, Length@puzzle}]; allpoints = Join[pos1, pos0]; validmoves = Select[Subsets[allpoints, {2}], Differences /* Norm /* EqualTo[Sqrt[5]]]; g = Graph[UndirectedEdge @@@ validmoves]; e = VertexList[g]; order = FindShortestTour[g][[2]] Graphics[{Red, Disk[#, 0.2] & /@ e, Black, BlockMap[Arrow, e[[order]], 2, 1]}]
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Convert the following code from Mathematica to Python, ensuring the logic remains intact.
puzzle = " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0"; puzzle = StringSplit[puzzle, "\n"]; puzzle = StringTake[#, {1, -1, 2}] & /@ puzzle; pos0 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "0"][[All, 1]], {i, Length@puzzle}]; pos1 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "1"][[All, 1]], {i, Length@puzzle}]; allpoints = Join[pos1, pos0]; validmoves = Select[Subsets[allpoints, {2}], Differences /* Norm /* EqualTo[Sqrt[5]]]; g = Graph[UndirectedEdge @@@ validmoves]; e = VertexList[g]; order = FindShortestTour[g][[2]] Graphics[{Red, Disk[#, 0.2] & /@ e, Black, BlockMap[Arrow, e[[order]], 2, 1]}]
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Port the following code from Mathematica to Go with equivalent syntax and logic.
puzzle = " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0"; puzzle = StringSplit[puzzle, "\n"]; puzzle = StringTake[#, {1, -1, 2}] & /@ puzzle; pos0 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "0"][[All, 1]], {i, Length@puzzle}]; pos1 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "1"][[All, 1]], {i, Length@puzzle}]; allpoints = Join[pos1, pos0]; validmoves = Select[Subsets[allpoints, {2}], Differences /* Norm /* EqualTo[Sqrt[5]]]; g = Graph[UndirectedEdge @@@ validmoves]; e = VertexList[g]; order = FindShortestTour[g][[2]] Graphics[{Red, Disk[#, 0.2] & /@ e, Black, BlockMap[Arrow, e[[order]], 2, 1]}]
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
Convert this Mathematica snippet to Go and keep its semantics consistent.
puzzle = " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0"; puzzle = StringSplit[puzzle, "\n"]; puzzle = StringTake[#, {1, -1, 2}] & /@ puzzle; pos0 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "0"][[All, 1]], {i, Length@puzzle}]; pos1 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "1"][[All, 1]], {i, Length@puzzle}]; allpoints = Join[pos1, pos0]; validmoves = Select[Subsets[allpoints, {2}], Differences /* Norm /* EqualTo[Sqrt[5]]]; g = Graph[UndirectedEdge @@@ validmoves]; e = VertexList[g]; order = FindShortestTour[g][[2]] Graphics[{Red, Disk[#, 0.2] & /@ e, Black, BlockMap[Arrow, e[[order]], 2, 1]}]
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
Produce a language-to-language conversion: from Nim to C#, same semantics.
import sequtils, strformat const Moves = [[-1, -2], [1, -2], [-2, -1], [2, -1], [-2, 1], [2, 1], [-1, 2], [1, 2]] proc solve(pz: var seq[seq[int]]; sx, sy, idx, count: Natural): bool = if idx > count: return true var x, y: int for move in Moves: x = sx + move[0] y = sy + move[1] if x in 0..pz.high and y in 0..pz.high and pz[x][y] == 0: pz[x][y] = idx if pz.solve(x, y, idx + 1, count): return true pz[x][y] = 0 proc findSolution(board: openArray[string]) = let sz = board.len var pz = newSeqWith(sz, repeat(-1, sz)) var count = 0 var x, y: int for i in 0..<sz: for j in 0..<sz: case board[i][j] of 'x': pz[i][j] = 0 inc count of 's': pz[i][j] = 1 inc count (x, y) = (i, j) else: discard if pz.solve(x, y, 2, count): for i in 0..<sz: for j in 0..<sz: if pz[i][j] != -1: stdout.write &"{pz[i][j]:02} " else: stdout.write "-- " stdout.write '\n' when isMainModule: const Board1 = [" xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "sxxxxxx ", " xx x ", " xxx "] Board2 = [".....s.x.....", ".....x.x.....", "....xxxxx....", ".....xxx.....", "..x..x.x..x..", "xxxxx...xxxxx", "..xx.....xx..", "xxxxx...xxxxx", "..x..x.x..x..", ".....xxx.....", "....xxxxx....", ".....x.x.....", ".....x.x....."] Board1.findSolution() echo() Board2.findSolution()
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Produce a functionally identical C# code for the snippet given in Nim.
import sequtils, strformat const Moves = [[-1, -2], [1, -2], [-2, -1], [2, -1], [-2, 1], [2, 1], [-1, 2], [1, 2]] proc solve(pz: var seq[seq[int]]; sx, sy, idx, count: Natural): bool = if idx > count: return true var x, y: int for move in Moves: x = sx + move[0] y = sy + move[1] if x in 0..pz.high and y in 0..pz.high and pz[x][y] == 0: pz[x][y] = idx if pz.solve(x, y, idx + 1, count): return true pz[x][y] = 0 proc findSolution(board: openArray[string]) = let sz = board.len var pz = newSeqWith(sz, repeat(-1, sz)) var count = 0 var x, y: int for i in 0..<sz: for j in 0..<sz: case board[i][j] of 'x': pz[i][j] = 0 inc count of 's': pz[i][j] = 1 inc count (x, y) = (i, j) else: discard if pz.solve(x, y, 2, count): for i in 0..<sz: for j in 0..<sz: if pz[i][j] != -1: stdout.write &"{pz[i][j]:02} " else: stdout.write "-- " stdout.write '\n' when isMainModule: const Board1 = [" xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "sxxxxxx ", " xx x ", " xxx "] Board2 = [".....s.x.....", ".....x.x.....", "....xxxxx....", ".....xxx.....", "..x..x.x..x..", "xxxxx...xxxxx", "..xx.....xx..", "xxxxx...xxxxx", "..x..x.x..x..", ".....xxx.....", "....xxxxx....", ".....x.x.....", ".....x.x....."] Board1.findSolution() echo() Board2.findSolution()
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Convert the following code from Nim to C++, ensuring the logic remains intact.
import sequtils, strformat const Moves = [[-1, -2], [1, -2], [-2, -1], [2, -1], [-2, 1], [2, 1], [-1, 2], [1, 2]] proc solve(pz: var seq[seq[int]]; sx, sy, idx, count: Natural): bool = if idx > count: return true var x, y: int for move in Moves: x = sx + move[0] y = sy + move[1] if x in 0..pz.high and y in 0..pz.high and pz[x][y] == 0: pz[x][y] = idx if pz.solve(x, y, idx + 1, count): return true pz[x][y] = 0 proc findSolution(board: openArray[string]) = let sz = board.len var pz = newSeqWith(sz, repeat(-1, sz)) var count = 0 var x, y: int for i in 0..<sz: for j in 0..<sz: case board[i][j] of 'x': pz[i][j] = 0 inc count of 's': pz[i][j] = 1 inc count (x, y) = (i, j) else: discard if pz.solve(x, y, 2, count): for i in 0..<sz: for j in 0..<sz: if pz[i][j] != -1: stdout.write &"{pz[i][j]:02} " else: stdout.write "-- " stdout.write '\n' when isMainModule: const Board1 = [" xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "sxxxxxx ", " xx x ", " xxx "] Board2 = [".....s.x.....", ".....x.x.....", "....xxxxx....", ".....xxx.....", "..x..x.x..x..", "xxxxx...xxxxx", "..xx.....xx..", "xxxxx...xxxxx", "..x..x.x..x..", ".....xxx.....", "....xxxxx....", ".....x.x.....", ".....x.x....."] Board1.findSolution() echo() Board2.findSolution()
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Produce a functionally identical C++ code for the snippet given in Nim.
import sequtils, strformat const Moves = [[-1, -2], [1, -2], [-2, -1], [2, -1], [-2, 1], [2, 1], [-1, 2], [1, 2]] proc solve(pz: var seq[seq[int]]; sx, sy, idx, count: Natural): bool = if idx > count: return true var x, y: int for move in Moves: x = sx + move[0] y = sy + move[1] if x in 0..pz.high and y in 0..pz.high and pz[x][y] == 0: pz[x][y] = idx if pz.solve(x, y, idx + 1, count): return true pz[x][y] = 0 proc findSolution(board: openArray[string]) = let sz = board.len var pz = newSeqWith(sz, repeat(-1, sz)) var count = 0 var x, y: int for i in 0..<sz: for j in 0..<sz: case board[i][j] of 'x': pz[i][j] = 0 inc count of 's': pz[i][j] = 1 inc count (x, y) = (i, j) else: discard if pz.solve(x, y, 2, count): for i in 0..<sz: for j in 0..<sz: if pz[i][j] != -1: stdout.write &"{pz[i][j]:02} " else: stdout.write "-- " stdout.write '\n' when isMainModule: const Board1 = [" xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "sxxxxxx ", " xx x ", " xxx "] Board2 = [".....s.x.....", ".....x.x.....", "....xxxxx....", ".....xxx.....", "..x..x.x..x..", "xxxxx...xxxxx", "..xx.....xx..", "xxxxx...xxxxx", "..x..x.x..x..", ".....xxx.....", "....xxxxx....", ".....x.x.....", ".....x.x....."] Board1.findSolution() echo() Board2.findSolution()
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Preserve the algorithm and functionality while converting the code from Nim to Java.
import sequtils, strformat const Moves = [[-1, -2], [1, -2], [-2, -1], [2, -1], [-2, 1], [2, 1], [-1, 2], [1, 2]] proc solve(pz: var seq[seq[int]]; sx, sy, idx, count: Natural): bool = if idx > count: return true var x, y: int for move in Moves: x = sx + move[0] y = sy + move[1] if x in 0..pz.high and y in 0..pz.high and pz[x][y] == 0: pz[x][y] = idx if pz.solve(x, y, idx + 1, count): return true pz[x][y] = 0 proc findSolution(board: openArray[string]) = let sz = board.len var pz = newSeqWith(sz, repeat(-1, sz)) var count = 0 var x, y: int for i in 0..<sz: for j in 0..<sz: case board[i][j] of 'x': pz[i][j] = 0 inc count of 's': pz[i][j] = 1 inc count (x, y) = (i, j) else: discard if pz.solve(x, y, 2, count): for i in 0..<sz: for j in 0..<sz: if pz[i][j] != -1: stdout.write &"{pz[i][j]:02} " else: stdout.write "-- " stdout.write '\n' when isMainModule: const Board1 = [" xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "sxxxxxx ", " xx x ", " xxx "] Board2 = [".....s.x.....", ".....x.x.....", "....xxxxx....", ".....xxx.....", "..x..x.x..x..", "xxxxx...xxxxx", "..xx.....xx..", "xxxxx...xxxxx", "..x..x.x..x..", ".....xxx.....", "....xxxxx....", ".....x.x.....", ".....x.x....."] Board1.findSolution() echo() Board2.findSolution()
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; 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 = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } 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, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (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) - 1; 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 void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
Write a version of this Nim function in Java with identical behavior.
import sequtils, strformat const Moves = [[-1, -2], [1, -2], [-2, -1], [2, -1], [-2, 1], [2, 1], [-1, 2], [1, 2]] proc solve(pz: var seq[seq[int]]; sx, sy, idx, count: Natural): bool = if idx > count: return true var x, y: int for move in Moves: x = sx + move[0] y = sy + move[1] if x in 0..pz.high and y in 0..pz.high and pz[x][y] == 0: pz[x][y] = idx if pz.solve(x, y, idx + 1, count): return true pz[x][y] = 0 proc findSolution(board: openArray[string]) = let sz = board.len var pz = newSeqWith(sz, repeat(-1, sz)) var count = 0 var x, y: int for i in 0..<sz: for j in 0..<sz: case board[i][j] of 'x': pz[i][j] = 0 inc count of 's': pz[i][j] = 1 inc count (x, y) = (i, j) else: discard if pz.solve(x, y, 2, count): for i in 0..<sz: for j in 0..<sz: if pz[i][j] != -1: stdout.write &"{pz[i][j]:02} " else: stdout.write "-- " stdout.write '\n' when isMainModule: const Board1 = [" xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "sxxxxxx ", " xx x ", " xxx "] Board2 = [".....s.x.....", ".....x.x.....", "....xxxxx....", ".....xxx.....", "..x..x.x..x..", "xxxxx...xxxxx", "..xx.....xx..", "xxxxx...xxxxx", "..x..x.x..x..", ".....xxx.....", "....xxxxx....", ".....x.x.....", ".....x.x....."] Board1.findSolution() echo() Board2.findSolution()
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; 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 = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } 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, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (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) - 1; 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 void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
Convert the following code from Nim to Python, ensuring the logic remains intact.
import sequtils, strformat const Moves = [[-1, -2], [1, -2], [-2, -1], [2, -1], [-2, 1], [2, 1], [-1, 2], [1, 2]] proc solve(pz: var seq[seq[int]]; sx, sy, idx, count: Natural): bool = if idx > count: return true var x, y: int for move in Moves: x = sx + move[0] y = sy + move[1] if x in 0..pz.high and y in 0..pz.high and pz[x][y] == 0: pz[x][y] = idx if pz.solve(x, y, idx + 1, count): return true pz[x][y] = 0 proc findSolution(board: openArray[string]) = let sz = board.len var pz = newSeqWith(sz, repeat(-1, sz)) var count = 0 var x, y: int for i in 0..<sz: for j in 0..<sz: case board[i][j] of 'x': pz[i][j] = 0 inc count of 's': pz[i][j] = 1 inc count (x, y) = (i, j) else: discard if pz.solve(x, y, 2, count): for i in 0..<sz: for j in 0..<sz: if pz[i][j] != -1: stdout.write &"{pz[i][j]:02} " else: stdout.write "-- " stdout.write '\n' when isMainModule: const Board1 = [" xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "sxxxxxx ", " xx x ", " xxx "] Board2 = [".....s.x.....", ".....x.x.....", "....xxxxx....", ".....xxx.....", "..x..x.x..x..", "xxxxx...xxxxx", "..xx.....xx..", "xxxxx...xxxxx", "..x..x.x..x..", ".....xxx.....", "....xxxxx....", ".....x.x.....", ".....x.x....."] Board1.findSolution() echo() Board2.findSolution()
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Port the provided Nim code into Python while preserving the original functionality.
import sequtils, strformat const Moves = [[-1, -2], [1, -2], [-2, -1], [2, -1], [-2, 1], [2, 1], [-1, 2], [1, 2]] proc solve(pz: var seq[seq[int]]; sx, sy, idx, count: Natural): bool = if idx > count: return true var x, y: int for move in Moves: x = sx + move[0] y = sy + move[1] if x in 0..pz.high and y in 0..pz.high and pz[x][y] == 0: pz[x][y] = idx if pz.solve(x, y, idx + 1, count): return true pz[x][y] = 0 proc findSolution(board: openArray[string]) = let sz = board.len var pz = newSeqWith(sz, repeat(-1, sz)) var count = 0 var x, y: int for i in 0..<sz: for j in 0..<sz: case board[i][j] of 'x': pz[i][j] = 0 inc count of 's': pz[i][j] = 1 inc count (x, y) = (i, j) else: discard if pz.solve(x, y, 2, count): for i in 0..<sz: for j in 0..<sz: if pz[i][j] != -1: stdout.write &"{pz[i][j]:02} " else: stdout.write "-- " stdout.write '\n' when isMainModule: const Board1 = [" xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "sxxxxxx ", " xx x ", " xxx "] Board2 = [".....s.x.....", ".....x.x.....", "....xxxxx....", ".....xxx.....", "..x..x.x..x..", "xxxxx...xxxxx", "..xx.....xx..", "xxxxx...xxxxx", "..x..x.x..x..", ".....xxx.....", "....xxxxx....", ".....x.x.....", ".....x.x....."] Board1.findSolution() echo() Board2.findSolution()
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Keep all operations the same but rewrite the snippet in Go.
import sequtils, strformat const Moves = [[-1, -2], [1, -2], [-2, -1], [2, -1], [-2, 1], [2, 1], [-1, 2], [1, 2]] proc solve(pz: var seq[seq[int]]; sx, sy, idx, count: Natural): bool = if idx > count: return true var x, y: int for move in Moves: x = sx + move[0] y = sy + move[1] if x in 0..pz.high and y in 0..pz.high and pz[x][y] == 0: pz[x][y] = idx if pz.solve(x, y, idx + 1, count): return true pz[x][y] = 0 proc findSolution(board: openArray[string]) = let sz = board.len var pz = newSeqWith(sz, repeat(-1, sz)) var count = 0 var x, y: int for i in 0..<sz: for j in 0..<sz: case board[i][j] of 'x': pz[i][j] = 0 inc count of 's': pz[i][j] = 1 inc count (x, y) = (i, j) else: discard if pz.solve(x, y, 2, count): for i in 0..<sz: for j in 0..<sz: if pz[i][j] != -1: stdout.write &"{pz[i][j]:02} " else: stdout.write "-- " stdout.write '\n' when isMainModule: const Board1 = [" xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "sxxxxxx ", " xx x ", " xxx "] Board2 = [".....s.x.....", ".....x.x.....", "....xxxxx....", ".....xxx.....", "..x..x.x..x..", "xxxxx...xxxxx", "..xx.....xx..", "xxxxx...xxxxx", "..x..x.x..x..", ".....xxx.....", "....xxxxx....", ".....x.x.....", ".....x.x....."] Board1.findSolution() echo() Board2.findSolution()
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
Change the following Nim code into Go without altering its purpose.
import sequtils, strformat const Moves = [[-1, -2], [1, -2], [-2, -1], [2, -1], [-2, 1], [2, 1], [-1, 2], [1, 2]] proc solve(pz: var seq[seq[int]]; sx, sy, idx, count: Natural): bool = if idx > count: return true var x, y: int for move in Moves: x = sx + move[0] y = sy + move[1] if x in 0..pz.high and y in 0..pz.high and pz[x][y] == 0: pz[x][y] = idx if pz.solve(x, y, idx + 1, count): return true pz[x][y] = 0 proc findSolution(board: openArray[string]) = let sz = board.len var pz = newSeqWith(sz, repeat(-1, sz)) var count = 0 var x, y: int for i in 0..<sz: for j in 0..<sz: case board[i][j] of 'x': pz[i][j] = 0 inc count of 's': pz[i][j] = 1 inc count (x, y) = (i, j) else: discard if pz.solve(x, y, 2, count): for i in 0..<sz: for j in 0..<sz: if pz[i][j] != -1: stdout.write &"{pz[i][j]:02} " else: stdout.write "-- " stdout.write '\n' when isMainModule: const Board1 = [" xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "sxxxxxx ", " xx x ", " xxx "] Board2 = [".....s.x.....", ".....x.x.....", "....xxxxx....", ".....xxx.....", "..x..x.x..x..", "xxxxx...xxxxx", "..xx.....xx..", "xxxxx...xxxxx", "..x..x.x..x..", ".....xxx.....", "....xxxxx....", ".....x.x.....", ".....x.x....."] Board1.findSolution() echo() Board2.findSolution()
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
Convert this Perl snippet to Java and keep its semantics consistent.
package KT_Locations; use strict; use overload '""' => "as_string"; use English; use Class::Tiny qw(N locations); use List::Util qw(all); sub BUILD { my $self = shift; $self->{N} //= 8; $self->{N} >= 3 or die "N must be at least 3"; all {ref($ARG) eq 'ARRAY' && scalar(@{$ARG}) == 2} @{$self->{locations}} or die "At least one element of 'locations' is invalid"; return; } sub as_string { my $self = shift; my %idxs; my $idx = 1; foreach my $loc (@{$self->locations}) { $idxs{join(q{K},@{$loc})} = $idx++; } my $str; { my $w = int(log(scalar(@{$self->locations}))/log(10.)) + 2; my $fmt = "%${w}d"; my $N = $self->N; my $non_tour = q{ } x ($w-1) . q{-}; for (my $r=0; $r<$N; $r++) { for (my $f=0; $f<$N; $f++) { my $k = join(q{K}, $r, $f); $str .= exists($idxs{$k}) ? sprintf($fmt, $idxs{$k}) : $non_tour; } $str .= "\n"; } } return $str; } sub as_idx_hash { my $self = shift; my $N = $self->N; my $result; foreach my $pair (@{$self->locations}) { my ($r, $f) = @{$pair}; $result->{$r * $N + $f}++; } return $result; } package KnightsTour; use strict; use Class::Tiny qw( N start_location locations_to_visit str legal_move_idxs ); use English; use Parallel::ForkManager; use Time::HiRes qw( gettimeofday tv_interval ); sub BUILD { my $self = shift; if ($self->{str}) { my ($n, $sl, $ltv) = _parse_input_string($self->{str}); $self->{N} = $n; $self->{start_location} = $sl; $self->{locations_to_visit} = $ltv; } $self->{N} //= 8; $self->{N} >= 3 or die "N must be at least 3"; exists($self->{start_location}) or die "Must supply start_location"; die "start_location is invalid" if ref($self->{start_location}) ne 'ARRAY' || scalar(@{$self->{start_location}}) != 2; exists($self->{locations_to_visit}) or die "Must supply locations_to_visit"; ref($self->{locations_to_visit}) eq 'KT_Locations' or die "locations_to_visit must be a KT_Locations instance"; $self->{N} == $self->{locations_to_visit}->N or die "locations_to_visit has mismatched board size"; $self->precompute_legal_moves(); return; } sub _parse_input_string { my @rows = split(/[\r\n]+/s, shift); my $N = scalar(@rows); my ($start_location, @to_visit); for (my $r=0; $r<$N; $r++) { my $row_r = $rows[$r]; for (my $f=0; $f<$N; $f++) { my $c = substr($row_r, $f, 1); if ($c eq '1') { $start_location = [$r, $f]; } elsif ($c eq '0') { push @to_visit, [$r, $f]; } } } $start_location or die "No starting location provided"; return ($N, $start_location, KT_Locations->new(N => $N, locations => \@to_visit)); } sub precompute_legal_moves { my $self = shift; my $N = $self->{N}; my $ktl_ixs = $self->{locations_to_visit}->as_idx_hash(); for (my $r=0; $r<$N; $r++) { for (my $f=0; $f<$N; $f++) { my $k = $r * $N + $f; $self->{legal_move_idxs}->{$k} = _precompute_legal_move_idxs($r, $f, $N, $ktl_ixs); } } return; } sub _precompute_legal_move_idxs { my ($r, $f, $N, $ktl_ixs) = @ARG; my $r_plus_1 = $r + 1; my $r_plus_2 = $r + 2; my $r_minus_1 = $r - 1; my $r_minus_2 = $r - 2; my $f_plus_1 = $f + 1; my $f_plus_2 = $f + 2; my $f_minus_1 = $f - 1; my $f_minus_2 = $f - 2; my @result = grep { exists($ktl_ixs->{$ARG}) } map { $ARG->[0] * $N + $ARG->[1] } grep {$ARG->[0] >= 0 && $ARG->[0] < $N && $ARG->[1] >= 0 && $ARG->[1] < $N} ([$r_plus_2, $f_minus_1], [$r_plus_2, $f_plus_1], [$r_minus_2, $f_minus_1], [$r_minus_2, $f_plus_1], [$r_plus_1, $f_plus_2], [$r_plus_1, $f_minus_2], [$r_minus_1, $f_plus_2], [$r_minus_1, $f_minus_2]); return \@result; } sub find_tour { my $self = shift; my $num_to_visit = scalar(@{$self->locations_to_visit->locations}); my $N = $self->N; my $start_loc_idx = $self->start_location->[0] * $N + $self->start_location->[1]; my $visited; for (my $i=0; $i<$N*$N; $i++) { vec($visited, $i, 1) = 0; } vec($visited, $start_loc_idx, 1) = 1; my @next_loc_idxs = @{$self->legal_move_idxs->{$start_loc_idx}}; my $pm = new Parallel::ForkManager(scalar(@next_loc_idxs)); foreach my $next_loc_idx (@next_loc_idxs) { $pm->start and next; my $t0 = [gettimeofday]; vec($visited, $next_loc_idx, 1) = 1; my $tour = _find_tour_helper($N, $num_to_visit - 1, $next_loc_idx, $visited, $self->legal_move_idxs); my $elapsed = tv_interval($t0); my ($r, $f) = _idx_to_rank_and_file($next_loc_idx, $N); if (defined $tour) { my @tour_locs = map { [_idx_to_rank_and_file($ARG, $N)] } ($start_loc_idx, $next_loc_idx, split(/\s+/s, $tour)); my $kt_locs = KT_Locations->new(N => $N, locations => \@tour_locs); print "Found a tour after first move ($r, $f) ", "in $elapsed seconds:\n", $kt_locs, "\n"; } else { print "No tour found after first move ($r, $f). ", "Took $elapsed seconds.\n"; } $pm->finish; } $pm->wait_all_children; return; } sub _idx_to_rank_and_file { my ($idx, $N) = @ARG; my $f = $idx % $N; my $r = ($idx - $f) / $N; return ($r, $f); } sub _find_tour_helper { my ($N, $num_to_visit, $current_loc_idx, $visited, $legal_move_idxs) = @ARG; local *inner_helper = sub { my ($num_to_visit, $current_loc_idx, $visited) = @ARG; if ($num_to_visit == 0) { return q{ }; } my @next_loc_idxs = @{$legal_move_idxs->{$current_loc_idx}}; my $num_to_visit2 = $num_to_visit - 1; foreach my $loc_idx2 (@next_loc_idxs) { next if vec($visited, $loc_idx2, 1); my $visited2 = $visited; vec($visited2, $loc_idx2, 1) = 1; my $recursion = inner_helper($num_to_visit2, $loc_idx2, $visited2); return $loc_idx2 . q{ } . $recursion if defined $recursion; } return; }; return inner_helper($num_to_visit, $current_loc_idx, $visited); } package main; use strict; solve_size_8_problem(); solve_size_13_problem(); exit 0; sub solve_size_8_problem { my $problem = <<"END_SIZE_8_PROBLEM"; --000--- --0-00-- -0000000 000--0-0 0-0--000 1000000- --00-0-- ---000-- END_SIZE_8_PROBLEM my $kt = KnightsTour->new(str => $problem); print "Finding a tour for an 8x8 problem...\n"; $kt->find_tour(); return; } sub solve_size_13_problem { my $problem = <<"END_SIZE_13_PROBLEM"; -----1-0----- -----0-0----- ----00000---- -----000----- --0--0-0--0-- 00000---00000 --00-----00-- 00000---00000 --0--0-0--0-- -----000----- ----00000---- -----0-0----- -----0-0----- END_SIZE_13_PROBLEM my $kt = KnightsTour->new(str => $problem); print "Finding a tour for a 13x13 problem...\n"; $kt->find_tour(); return; }
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; 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 = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } 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, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (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) - 1; 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 void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
Maintain the same structure and functionality when rewriting this code in Java.
package KT_Locations; use strict; use overload '""' => "as_string"; use English; use Class::Tiny qw(N locations); use List::Util qw(all); sub BUILD { my $self = shift; $self->{N} //= 8; $self->{N} >= 3 or die "N must be at least 3"; all {ref($ARG) eq 'ARRAY' && scalar(@{$ARG}) == 2} @{$self->{locations}} or die "At least one element of 'locations' is invalid"; return; } sub as_string { my $self = shift; my %idxs; my $idx = 1; foreach my $loc (@{$self->locations}) { $idxs{join(q{K},@{$loc})} = $idx++; } my $str; { my $w = int(log(scalar(@{$self->locations}))/log(10.)) + 2; my $fmt = "%${w}d"; my $N = $self->N; my $non_tour = q{ } x ($w-1) . q{-}; for (my $r=0; $r<$N; $r++) { for (my $f=0; $f<$N; $f++) { my $k = join(q{K}, $r, $f); $str .= exists($idxs{$k}) ? sprintf($fmt, $idxs{$k}) : $non_tour; } $str .= "\n"; } } return $str; } sub as_idx_hash { my $self = shift; my $N = $self->N; my $result; foreach my $pair (@{$self->locations}) { my ($r, $f) = @{$pair}; $result->{$r * $N + $f}++; } return $result; } package KnightsTour; use strict; use Class::Tiny qw( N start_location locations_to_visit str legal_move_idxs ); use English; use Parallel::ForkManager; use Time::HiRes qw( gettimeofday tv_interval ); sub BUILD { my $self = shift; if ($self->{str}) { my ($n, $sl, $ltv) = _parse_input_string($self->{str}); $self->{N} = $n; $self->{start_location} = $sl; $self->{locations_to_visit} = $ltv; } $self->{N} //= 8; $self->{N} >= 3 or die "N must be at least 3"; exists($self->{start_location}) or die "Must supply start_location"; die "start_location is invalid" if ref($self->{start_location}) ne 'ARRAY' || scalar(@{$self->{start_location}}) != 2; exists($self->{locations_to_visit}) or die "Must supply locations_to_visit"; ref($self->{locations_to_visit}) eq 'KT_Locations' or die "locations_to_visit must be a KT_Locations instance"; $self->{N} == $self->{locations_to_visit}->N or die "locations_to_visit has mismatched board size"; $self->precompute_legal_moves(); return; } sub _parse_input_string { my @rows = split(/[\r\n]+/s, shift); my $N = scalar(@rows); my ($start_location, @to_visit); for (my $r=0; $r<$N; $r++) { my $row_r = $rows[$r]; for (my $f=0; $f<$N; $f++) { my $c = substr($row_r, $f, 1); if ($c eq '1') { $start_location = [$r, $f]; } elsif ($c eq '0') { push @to_visit, [$r, $f]; } } } $start_location or die "No starting location provided"; return ($N, $start_location, KT_Locations->new(N => $N, locations => \@to_visit)); } sub precompute_legal_moves { my $self = shift; my $N = $self->{N}; my $ktl_ixs = $self->{locations_to_visit}->as_idx_hash(); for (my $r=0; $r<$N; $r++) { for (my $f=0; $f<$N; $f++) { my $k = $r * $N + $f; $self->{legal_move_idxs}->{$k} = _precompute_legal_move_idxs($r, $f, $N, $ktl_ixs); } } return; } sub _precompute_legal_move_idxs { my ($r, $f, $N, $ktl_ixs) = @ARG; my $r_plus_1 = $r + 1; my $r_plus_2 = $r + 2; my $r_minus_1 = $r - 1; my $r_minus_2 = $r - 2; my $f_plus_1 = $f + 1; my $f_plus_2 = $f + 2; my $f_minus_1 = $f - 1; my $f_minus_2 = $f - 2; my @result = grep { exists($ktl_ixs->{$ARG}) } map { $ARG->[0] * $N + $ARG->[1] } grep {$ARG->[0] >= 0 && $ARG->[0] < $N && $ARG->[1] >= 0 && $ARG->[1] < $N} ([$r_plus_2, $f_minus_1], [$r_plus_2, $f_plus_1], [$r_minus_2, $f_minus_1], [$r_minus_2, $f_plus_1], [$r_plus_1, $f_plus_2], [$r_plus_1, $f_minus_2], [$r_minus_1, $f_plus_2], [$r_minus_1, $f_minus_2]); return \@result; } sub find_tour { my $self = shift; my $num_to_visit = scalar(@{$self->locations_to_visit->locations}); my $N = $self->N; my $start_loc_idx = $self->start_location->[0] * $N + $self->start_location->[1]; my $visited; for (my $i=0; $i<$N*$N; $i++) { vec($visited, $i, 1) = 0; } vec($visited, $start_loc_idx, 1) = 1; my @next_loc_idxs = @{$self->legal_move_idxs->{$start_loc_idx}}; my $pm = new Parallel::ForkManager(scalar(@next_loc_idxs)); foreach my $next_loc_idx (@next_loc_idxs) { $pm->start and next; my $t0 = [gettimeofday]; vec($visited, $next_loc_idx, 1) = 1; my $tour = _find_tour_helper($N, $num_to_visit - 1, $next_loc_idx, $visited, $self->legal_move_idxs); my $elapsed = tv_interval($t0); my ($r, $f) = _idx_to_rank_and_file($next_loc_idx, $N); if (defined $tour) { my @tour_locs = map { [_idx_to_rank_and_file($ARG, $N)] } ($start_loc_idx, $next_loc_idx, split(/\s+/s, $tour)); my $kt_locs = KT_Locations->new(N => $N, locations => \@tour_locs); print "Found a tour after first move ($r, $f) ", "in $elapsed seconds:\n", $kt_locs, "\n"; } else { print "No tour found after first move ($r, $f). ", "Took $elapsed seconds.\n"; } $pm->finish; } $pm->wait_all_children; return; } sub _idx_to_rank_and_file { my ($idx, $N) = @ARG; my $f = $idx % $N; my $r = ($idx - $f) / $N; return ($r, $f); } sub _find_tour_helper { my ($N, $num_to_visit, $current_loc_idx, $visited, $legal_move_idxs) = @ARG; local *inner_helper = sub { my ($num_to_visit, $current_loc_idx, $visited) = @ARG; if ($num_to_visit == 0) { return q{ }; } my @next_loc_idxs = @{$legal_move_idxs->{$current_loc_idx}}; my $num_to_visit2 = $num_to_visit - 1; foreach my $loc_idx2 (@next_loc_idxs) { next if vec($visited, $loc_idx2, 1); my $visited2 = $visited; vec($visited2, $loc_idx2, 1) = 1; my $recursion = inner_helper($num_to_visit2, $loc_idx2, $visited2); return $loc_idx2 . q{ } . $recursion if defined $recursion; } return; }; return inner_helper($num_to_visit, $current_loc_idx, $visited); } package main; use strict; solve_size_8_problem(); solve_size_13_problem(); exit 0; sub solve_size_8_problem { my $problem = <<"END_SIZE_8_PROBLEM"; --000--- --0-00-- -0000000 000--0-0 0-0--000 1000000- --00-0-- ---000-- END_SIZE_8_PROBLEM my $kt = KnightsTour->new(str => $problem); print "Finding a tour for an 8x8 problem...\n"; $kt->find_tour(); return; } sub solve_size_13_problem { my $problem = <<"END_SIZE_13_PROBLEM"; -----1-0----- -----0-0----- ----00000---- -----000----- --0--0-0--0-- 00000---00000 --00-----00-- 00000---00000 --0--0-0--0-- -----000----- ----00000---- -----0-0----- -----0-0----- END_SIZE_13_PROBLEM my $kt = KnightsTour->new(str => $problem); print "Finding a tour for a 13x13 problem...\n"; $kt->find_tour(); return; }
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; 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 = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } 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, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (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) - 1; 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 void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
Generate an equivalent Python version of this Perl code.
package KT_Locations; use strict; use overload '""' => "as_string"; use English; use Class::Tiny qw(N locations); use List::Util qw(all); sub BUILD { my $self = shift; $self->{N} //= 8; $self->{N} >= 3 or die "N must be at least 3"; all {ref($ARG) eq 'ARRAY' && scalar(@{$ARG}) == 2} @{$self->{locations}} or die "At least one element of 'locations' is invalid"; return; } sub as_string { my $self = shift; my %idxs; my $idx = 1; foreach my $loc (@{$self->locations}) { $idxs{join(q{K},@{$loc})} = $idx++; } my $str; { my $w = int(log(scalar(@{$self->locations}))/log(10.)) + 2; my $fmt = "%${w}d"; my $N = $self->N; my $non_tour = q{ } x ($w-1) . q{-}; for (my $r=0; $r<$N; $r++) { for (my $f=0; $f<$N; $f++) { my $k = join(q{K}, $r, $f); $str .= exists($idxs{$k}) ? sprintf($fmt, $idxs{$k}) : $non_tour; } $str .= "\n"; } } return $str; } sub as_idx_hash { my $self = shift; my $N = $self->N; my $result; foreach my $pair (@{$self->locations}) { my ($r, $f) = @{$pair}; $result->{$r * $N + $f}++; } return $result; } package KnightsTour; use strict; use Class::Tiny qw( N start_location locations_to_visit str legal_move_idxs ); use English; use Parallel::ForkManager; use Time::HiRes qw( gettimeofday tv_interval ); sub BUILD { my $self = shift; if ($self->{str}) { my ($n, $sl, $ltv) = _parse_input_string($self->{str}); $self->{N} = $n; $self->{start_location} = $sl; $self->{locations_to_visit} = $ltv; } $self->{N} //= 8; $self->{N} >= 3 or die "N must be at least 3"; exists($self->{start_location}) or die "Must supply start_location"; die "start_location is invalid" if ref($self->{start_location}) ne 'ARRAY' || scalar(@{$self->{start_location}}) != 2; exists($self->{locations_to_visit}) or die "Must supply locations_to_visit"; ref($self->{locations_to_visit}) eq 'KT_Locations' or die "locations_to_visit must be a KT_Locations instance"; $self->{N} == $self->{locations_to_visit}->N or die "locations_to_visit has mismatched board size"; $self->precompute_legal_moves(); return; } sub _parse_input_string { my @rows = split(/[\r\n]+/s, shift); my $N = scalar(@rows); my ($start_location, @to_visit); for (my $r=0; $r<$N; $r++) { my $row_r = $rows[$r]; for (my $f=0; $f<$N; $f++) { my $c = substr($row_r, $f, 1); if ($c eq '1') { $start_location = [$r, $f]; } elsif ($c eq '0') { push @to_visit, [$r, $f]; } } } $start_location or die "No starting location provided"; return ($N, $start_location, KT_Locations->new(N => $N, locations => \@to_visit)); } sub precompute_legal_moves { my $self = shift; my $N = $self->{N}; my $ktl_ixs = $self->{locations_to_visit}->as_idx_hash(); for (my $r=0; $r<$N; $r++) { for (my $f=0; $f<$N; $f++) { my $k = $r * $N + $f; $self->{legal_move_idxs}->{$k} = _precompute_legal_move_idxs($r, $f, $N, $ktl_ixs); } } return; } sub _precompute_legal_move_idxs { my ($r, $f, $N, $ktl_ixs) = @ARG; my $r_plus_1 = $r + 1; my $r_plus_2 = $r + 2; my $r_minus_1 = $r - 1; my $r_minus_2 = $r - 2; my $f_plus_1 = $f + 1; my $f_plus_2 = $f + 2; my $f_minus_1 = $f - 1; my $f_minus_2 = $f - 2; my @result = grep { exists($ktl_ixs->{$ARG}) } map { $ARG->[0] * $N + $ARG->[1] } grep {$ARG->[0] >= 0 && $ARG->[0] < $N && $ARG->[1] >= 0 && $ARG->[1] < $N} ([$r_plus_2, $f_minus_1], [$r_plus_2, $f_plus_1], [$r_minus_2, $f_minus_1], [$r_minus_2, $f_plus_1], [$r_plus_1, $f_plus_2], [$r_plus_1, $f_minus_2], [$r_minus_1, $f_plus_2], [$r_minus_1, $f_minus_2]); return \@result; } sub find_tour { my $self = shift; my $num_to_visit = scalar(@{$self->locations_to_visit->locations}); my $N = $self->N; my $start_loc_idx = $self->start_location->[0] * $N + $self->start_location->[1]; my $visited; for (my $i=0; $i<$N*$N; $i++) { vec($visited, $i, 1) = 0; } vec($visited, $start_loc_idx, 1) = 1; my @next_loc_idxs = @{$self->legal_move_idxs->{$start_loc_idx}}; my $pm = new Parallel::ForkManager(scalar(@next_loc_idxs)); foreach my $next_loc_idx (@next_loc_idxs) { $pm->start and next; my $t0 = [gettimeofday]; vec($visited, $next_loc_idx, 1) = 1; my $tour = _find_tour_helper($N, $num_to_visit - 1, $next_loc_idx, $visited, $self->legal_move_idxs); my $elapsed = tv_interval($t0); my ($r, $f) = _idx_to_rank_and_file($next_loc_idx, $N); if (defined $tour) { my @tour_locs = map { [_idx_to_rank_and_file($ARG, $N)] } ($start_loc_idx, $next_loc_idx, split(/\s+/s, $tour)); my $kt_locs = KT_Locations->new(N => $N, locations => \@tour_locs); print "Found a tour after first move ($r, $f) ", "in $elapsed seconds:\n", $kt_locs, "\n"; } else { print "No tour found after first move ($r, $f). ", "Took $elapsed seconds.\n"; } $pm->finish; } $pm->wait_all_children; return; } sub _idx_to_rank_and_file { my ($idx, $N) = @ARG; my $f = $idx % $N; my $r = ($idx - $f) / $N; return ($r, $f); } sub _find_tour_helper { my ($N, $num_to_visit, $current_loc_idx, $visited, $legal_move_idxs) = @ARG; local *inner_helper = sub { my ($num_to_visit, $current_loc_idx, $visited) = @ARG; if ($num_to_visit == 0) { return q{ }; } my @next_loc_idxs = @{$legal_move_idxs->{$current_loc_idx}}; my $num_to_visit2 = $num_to_visit - 1; foreach my $loc_idx2 (@next_loc_idxs) { next if vec($visited, $loc_idx2, 1); my $visited2 = $visited; vec($visited2, $loc_idx2, 1) = 1; my $recursion = inner_helper($num_to_visit2, $loc_idx2, $visited2); return $loc_idx2 . q{ } . $recursion if defined $recursion; } return; }; return inner_helper($num_to_visit, $current_loc_idx, $visited); } package main; use strict; solve_size_8_problem(); solve_size_13_problem(); exit 0; sub solve_size_8_problem { my $problem = <<"END_SIZE_8_PROBLEM"; --000--- --0-00-- -0000000 000--0-0 0-0--000 1000000- --00-0-- ---000-- END_SIZE_8_PROBLEM my $kt = KnightsTour->new(str => $problem); print "Finding a tour for an 8x8 problem...\n"; $kt->find_tour(); return; } sub solve_size_13_problem { my $problem = <<"END_SIZE_13_PROBLEM"; -----1-0----- -----0-0----- ----00000---- -----000----- --0--0-0--0-- 00000---00000 --00-----00-- 00000---00000 --0--0-0--0-- -----000----- ----00000---- -----0-0----- -----0-0----- END_SIZE_13_PROBLEM my $kt = KnightsTour->new(str => $problem); print "Finding a tour for a 13x13 problem...\n"; $kt->find_tour(); return; }
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Convert this Perl snippet to Python and keep its semantics consistent.
package KT_Locations; use strict; use overload '""' => "as_string"; use English; use Class::Tiny qw(N locations); use List::Util qw(all); sub BUILD { my $self = shift; $self->{N} //= 8; $self->{N} >= 3 or die "N must be at least 3"; all {ref($ARG) eq 'ARRAY' && scalar(@{$ARG}) == 2} @{$self->{locations}} or die "At least one element of 'locations' is invalid"; return; } sub as_string { my $self = shift; my %idxs; my $idx = 1; foreach my $loc (@{$self->locations}) { $idxs{join(q{K},@{$loc})} = $idx++; } my $str; { my $w = int(log(scalar(@{$self->locations}))/log(10.)) + 2; my $fmt = "%${w}d"; my $N = $self->N; my $non_tour = q{ } x ($w-1) . q{-}; for (my $r=0; $r<$N; $r++) { for (my $f=0; $f<$N; $f++) { my $k = join(q{K}, $r, $f); $str .= exists($idxs{$k}) ? sprintf($fmt, $idxs{$k}) : $non_tour; } $str .= "\n"; } } return $str; } sub as_idx_hash { my $self = shift; my $N = $self->N; my $result; foreach my $pair (@{$self->locations}) { my ($r, $f) = @{$pair}; $result->{$r * $N + $f}++; } return $result; } package KnightsTour; use strict; use Class::Tiny qw( N start_location locations_to_visit str legal_move_idxs ); use English; use Parallel::ForkManager; use Time::HiRes qw( gettimeofday tv_interval ); sub BUILD { my $self = shift; if ($self->{str}) { my ($n, $sl, $ltv) = _parse_input_string($self->{str}); $self->{N} = $n; $self->{start_location} = $sl; $self->{locations_to_visit} = $ltv; } $self->{N} //= 8; $self->{N} >= 3 or die "N must be at least 3"; exists($self->{start_location}) or die "Must supply start_location"; die "start_location is invalid" if ref($self->{start_location}) ne 'ARRAY' || scalar(@{$self->{start_location}}) != 2; exists($self->{locations_to_visit}) or die "Must supply locations_to_visit"; ref($self->{locations_to_visit}) eq 'KT_Locations' or die "locations_to_visit must be a KT_Locations instance"; $self->{N} == $self->{locations_to_visit}->N or die "locations_to_visit has mismatched board size"; $self->precompute_legal_moves(); return; } sub _parse_input_string { my @rows = split(/[\r\n]+/s, shift); my $N = scalar(@rows); my ($start_location, @to_visit); for (my $r=0; $r<$N; $r++) { my $row_r = $rows[$r]; for (my $f=0; $f<$N; $f++) { my $c = substr($row_r, $f, 1); if ($c eq '1') { $start_location = [$r, $f]; } elsif ($c eq '0') { push @to_visit, [$r, $f]; } } } $start_location or die "No starting location provided"; return ($N, $start_location, KT_Locations->new(N => $N, locations => \@to_visit)); } sub precompute_legal_moves { my $self = shift; my $N = $self->{N}; my $ktl_ixs = $self->{locations_to_visit}->as_idx_hash(); for (my $r=0; $r<$N; $r++) { for (my $f=0; $f<$N; $f++) { my $k = $r * $N + $f; $self->{legal_move_idxs}->{$k} = _precompute_legal_move_idxs($r, $f, $N, $ktl_ixs); } } return; } sub _precompute_legal_move_idxs { my ($r, $f, $N, $ktl_ixs) = @ARG; my $r_plus_1 = $r + 1; my $r_plus_2 = $r + 2; my $r_minus_1 = $r - 1; my $r_minus_2 = $r - 2; my $f_plus_1 = $f + 1; my $f_plus_2 = $f + 2; my $f_minus_1 = $f - 1; my $f_minus_2 = $f - 2; my @result = grep { exists($ktl_ixs->{$ARG}) } map { $ARG->[0] * $N + $ARG->[1] } grep {$ARG->[0] >= 0 && $ARG->[0] < $N && $ARG->[1] >= 0 && $ARG->[1] < $N} ([$r_plus_2, $f_minus_1], [$r_plus_2, $f_plus_1], [$r_minus_2, $f_minus_1], [$r_minus_2, $f_plus_1], [$r_plus_1, $f_plus_2], [$r_plus_1, $f_minus_2], [$r_minus_1, $f_plus_2], [$r_minus_1, $f_minus_2]); return \@result; } sub find_tour { my $self = shift; my $num_to_visit = scalar(@{$self->locations_to_visit->locations}); my $N = $self->N; my $start_loc_idx = $self->start_location->[0] * $N + $self->start_location->[1]; my $visited; for (my $i=0; $i<$N*$N; $i++) { vec($visited, $i, 1) = 0; } vec($visited, $start_loc_idx, 1) = 1; my @next_loc_idxs = @{$self->legal_move_idxs->{$start_loc_idx}}; my $pm = new Parallel::ForkManager(scalar(@next_loc_idxs)); foreach my $next_loc_idx (@next_loc_idxs) { $pm->start and next; my $t0 = [gettimeofday]; vec($visited, $next_loc_idx, 1) = 1; my $tour = _find_tour_helper($N, $num_to_visit - 1, $next_loc_idx, $visited, $self->legal_move_idxs); my $elapsed = tv_interval($t0); my ($r, $f) = _idx_to_rank_and_file($next_loc_idx, $N); if (defined $tour) { my @tour_locs = map { [_idx_to_rank_and_file($ARG, $N)] } ($start_loc_idx, $next_loc_idx, split(/\s+/s, $tour)); my $kt_locs = KT_Locations->new(N => $N, locations => \@tour_locs); print "Found a tour after first move ($r, $f) ", "in $elapsed seconds:\n", $kt_locs, "\n"; } else { print "No tour found after first move ($r, $f). ", "Took $elapsed seconds.\n"; } $pm->finish; } $pm->wait_all_children; return; } sub _idx_to_rank_and_file { my ($idx, $N) = @ARG; my $f = $idx % $N; my $r = ($idx - $f) / $N; return ($r, $f); } sub _find_tour_helper { my ($N, $num_to_visit, $current_loc_idx, $visited, $legal_move_idxs) = @ARG; local *inner_helper = sub { my ($num_to_visit, $current_loc_idx, $visited) = @ARG; if ($num_to_visit == 0) { return q{ }; } my @next_loc_idxs = @{$legal_move_idxs->{$current_loc_idx}}; my $num_to_visit2 = $num_to_visit - 1; foreach my $loc_idx2 (@next_loc_idxs) { next if vec($visited, $loc_idx2, 1); my $visited2 = $visited; vec($visited2, $loc_idx2, 1) = 1; my $recursion = inner_helper($num_to_visit2, $loc_idx2, $visited2); return $loc_idx2 . q{ } . $recursion if defined $recursion; } return; }; return inner_helper($num_to_visit, $current_loc_idx, $visited); } package main; use strict; solve_size_8_problem(); solve_size_13_problem(); exit 0; sub solve_size_8_problem { my $problem = <<"END_SIZE_8_PROBLEM"; --000--- --0-00-- -0000000 000--0-0 0-0--000 1000000- --00-0-- ---000-- END_SIZE_8_PROBLEM my $kt = KnightsTour->new(str => $problem); print "Finding a tour for an 8x8 problem...\n"; $kt->find_tour(); return; } sub solve_size_13_problem { my $problem = <<"END_SIZE_13_PROBLEM"; -----1-0----- -----0-0----- ----00000---- -----000----- --0--0-0--0-- 00000---00000 --00-----00-- 00000---00000 --0--0-0--0-- -----000----- ----00000---- -----0-0----- -----0-0----- END_SIZE_13_PROBLEM my $kt = KnightsTour->new(str => $problem); print "Finding a tour for a 13x13 problem...\n"; $kt->find_tour(); return; }
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Write a version of this Perl function in Go with identical behavior.
package KT_Locations; use strict; use overload '""' => "as_string"; use English; use Class::Tiny qw(N locations); use List::Util qw(all); sub BUILD { my $self = shift; $self->{N} //= 8; $self->{N} >= 3 or die "N must be at least 3"; all {ref($ARG) eq 'ARRAY' && scalar(@{$ARG}) == 2} @{$self->{locations}} or die "At least one element of 'locations' is invalid"; return; } sub as_string { my $self = shift; my %idxs; my $idx = 1; foreach my $loc (@{$self->locations}) { $idxs{join(q{K},@{$loc})} = $idx++; } my $str; { my $w = int(log(scalar(@{$self->locations}))/log(10.)) + 2; my $fmt = "%${w}d"; my $N = $self->N; my $non_tour = q{ } x ($w-1) . q{-}; for (my $r=0; $r<$N; $r++) { for (my $f=0; $f<$N; $f++) { my $k = join(q{K}, $r, $f); $str .= exists($idxs{$k}) ? sprintf($fmt, $idxs{$k}) : $non_tour; } $str .= "\n"; } } return $str; } sub as_idx_hash { my $self = shift; my $N = $self->N; my $result; foreach my $pair (@{$self->locations}) { my ($r, $f) = @{$pair}; $result->{$r * $N + $f}++; } return $result; } package KnightsTour; use strict; use Class::Tiny qw( N start_location locations_to_visit str legal_move_idxs ); use English; use Parallel::ForkManager; use Time::HiRes qw( gettimeofday tv_interval ); sub BUILD { my $self = shift; if ($self->{str}) { my ($n, $sl, $ltv) = _parse_input_string($self->{str}); $self->{N} = $n; $self->{start_location} = $sl; $self->{locations_to_visit} = $ltv; } $self->{N} //= 8; $self->{N} >= 3 or die "N must be at least 3"; exists($self->{start_location}) or die "Must supply start_location"; die "start_location is invalid" if ref($self->{start_location}) ne 'ARRAY' || scalar(@{$self->{start_location}}) != 2; exists($self->{locations_to_visit}) or die "Must supply locations_to_visit"; ref($self->{locations_to_visit}) eq 'KT_Locations' or die "locations_to_visit must be a KT_Locations instance"; $self->{N} == $self->{locations_to_visit}->N or die "locations_to_visit has mismatched board size"; $self->precompute_legal_moves(); return; } sub _parse_input_string { my @rows = split(/[\r\n]+/s, shift); my $N = scalar(@rows); my ($start_location, @to_visit); for (my $r=0; $r<$N; $r++) { my $row_r = $rows[$r]; for (my $f=0; $f<$N; $f++) { my $c = substr($row_r, $f, 1); if ($c eq '1') { $start_location = [$r, $f]; } elsif ($c eq '0') { push @to_visit, [$r, $f]; } } } $start_location or die "No starting location provided"; return ($N, $start_location, KT_Locations->new(N => $N, locations => \@to_visit)); } sub precompute_legal_moves { my $self = shift; my $N = $self->{N}; my $ktl_ixs = $self->{locations_to_visit}->as_idx_hash(); for (my $r=0; $r<$N; $r++) { for (my $f=0; $f<$N; $f++) { my $k = $r * $N + $f; $self->{legal_move_idxs}->{$k} = _precompute_legal_move_idxs($r, $f, $N, $ktl_ixs); } } return; } sub _precompute_legal_move_idxs { my ($r, $f, $N, $ktl_ixs) = @ARG; my $r_plus_1 = $r + 1; my $r_plus_2 = $r + 2; my $r_minus_1 = $r - 1; my $r_minus_2 = $r - 2; my $f_plus_1 = $f + 1; my $f_plus_2 = $f + 2; my $f_minus_1 = $f - 1; my $f_minus_2 = $f - 2; my @result = grep { exists($ktl_ixs->{$ARG}) } map { $ARG->[0] * $N + $ARG->[1] } grep {$ARG->[0] >= 0 && $ARG->[0] < $N && $ARG->[1] >= 0 && $ARG->[1] < $N} ([$r_plus_2, $f_minus_1], [$r_plus_2, $f_plus_1], [$r_minus_2, $f_minus_1], [$r_minus_2, $f_plus_1], [$r_plus_1, $f_plus_2], [$r_plus_1, $f_minus_2], [$r_minus_1, $f_plus_2], [$r_minus_1, $f_minus_2]); return \@result; } sub find_tour { my $self = shift; my $num_to_visit = scalar(@{$self->locations_to_visit->locations}); my $N = $self->N; my $start_loc_idx = $self->start_location->[0] * $N + $self->start_location->[1]; my $visited; for (my $i=0; $i<$N*$N; $i++) { vec($visited, $i, 1) = 0; } vec($visited, $start_loc_idx, 1) = 1; my @next_loc_idxs = @{$self->legal_move_idxs->{$start_loc_idx}}; my $pm = new Parallel::ForkManager(scalar(@next_loc_idxs)); foreach my $next_loc_idx (@next_loc_idxs) { $pm->start and next; my $t0 = [gettimeofday]; vec($visited, $next_loc_idx, 1) = 1; my $tour = _find_tour_helper($N, $num_to_visit - 1, $next_loc_idx, $visited, $self->legal_move_idxs); my $elapsed = tv_interval($t0); my ($r, $f) = _idx_to_rank_and_file($next_loc_idx, $N); if (defined $tour) { my @tour_locs = map { [_idx_to_rank_and_file($ARG, $N)] } ($start_loc_idx, $next_loc_idx, split(/\s+/s, $tour)); my $kt_locs = KT_Locations->new(N => $N, locations => \@tour_locs); print "Found a tour after first move ($r, $f) ", "in $elapsed seconds:\n", $kt_locs, "\n"; } else { print "No tour found after first move ($r, $f). ", "Took $elapsed seconds.\n"; } $pm->finish; } $pm->wait_all_children; return; } sub _idx_to_rank_and_file { my ($idx, $N) = @ARG; my $f = $idx % $N; my $r = ($idx - $f) / $N; return ($r, $f); } sub _find_tour_helper { my ($N, $num_to_visit, $current_loc_idx, $visited, $legal_move_idxs) = @ARG; local *inner_helper = sub { my ($num_to_visit, $current_loc_idx, $visited) = @ARG; if ($num_to_visit == 0) { return q{ }; } my @next_loc_idxs = @{$legal_move_idxs->{$current_loc_idx}}; my $num_to_visit2 = $num_to_visit - 1; foreach my $loc_idx2 (@next_loc_idxs) { next if vec($visited, $loc_idx2, 1); my $visited2 = $visited; vec($visited2, $loc_idx2, 1) = 1; my $recursion = inner_helper($num_to_visit2, $loc_idx2, $visited2); return $loc_idx2 . q{ } . $recursion if defined $recursion; } return; }; return inner_helper($num_to_visit, $current_loc_idx, $visited); } package main; use strict; solve_size_8_problem(); solve_size_13_problem(); exit 0; sub solve_size_8_problem { my $problem = <<"END_SIZE_8_PROBLEM"; --000--- --0-00-- -0000000 000--0-0 0-0--000 1000000- --00-0-- ---000-- END_SIZE_8_PROBLEM my $kt = KnightsTour->new(str => $problem); print "Finding a tour for an 8x8 problem...\n"; $kt->find_tour(); return; } sub solve_size_13_problem { my $problem = <<"END_SIZE_13_PROBLEM"; -----1-0----- -----0-0----- ----00000---- -----000----- --0--0-0--0-- 00000---00000 --00-----00-- 00000---00000 --0--0-0--0-- -----000----- ----00000---- -----0-0----- -----0-0----- END_SIZE_13_PROBLEM my $kt = KnightsTour->new(str => $problem); print "Finding a tour for a 13x13 problem...\n"; $kt->find_tour(); return; }
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }