Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Produce a functionally identical Go code for the snippet given in Perl.
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) }
Write the same code in C# as shown below in Racket.
#lang racket (require "hidato-family-solver.rkt") (define knights-neighbour-offsets '((+1 +2) (-1 +2) (+1 -2) (-1 -2) (+2 +1) (-2 +1) (+2 -1) (-2 -1))) (define solve-a-knights-tour (solve-hidato-family knights-neighbour-offsets)) (displayln (puzzle->string (solve-a-knights-tour #(#(_ 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 _ _))))) (newline) (displayln (puzzle->string (solve-a-knights-tour #(#(- - - - - 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 - - - - -)))))
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 Racket.
#lang racket (require "hidato-family-solver.rkt") (define knights-neighbour-offsets '((+1 +2) (-1 +2) (+1 -2) (-1 -2) (+2 +1) (-2 +1) (+2 -1) (-2 -1))) (define solve-a-knights-tour (solve-hidato-family knights-neighbour-offsets)) (displayln (puzzle->string (solve-a-knights-tour #(#(_ 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 _ _))))) (newline) (displayln (puzzle->string (solve-a-knights-tour #(#(- - - - - 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 - - - - -)))))
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 Racket code snippet into C++ without altering its behavior.
#lang racket (require "hidato-family-solver.rkt") (define knights-neighbour-offsets '((+1 +2) (-1 +2) (+1 -2) (-1 -2) (+2 +1) (-2 +1) (+2 -1) (-2 -1))) (define solve-a-knights-tour (solve-hidato-family knights-neighbour-offsets)) (displayln (puzzle->string (solve-a-knights-tour #(#(_ 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 _ _))))) (newline) (displayln (puzzle->string (solve-a-knights-tour #(#(- - - - - 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 - - - - -)))))
#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" ); }
Port the provided Racket code into C++ while preserving the original functionality.
#lang racket (require "hidato-family-solver.rkt") (define knights-neighbour-offsets '((+1 +2) (-1 +2) (+1 -2) (-1 -2) (+2 +1) (-2 +1) (+2 -1) (-2 -1))) (define solve-a-knights-tour (solve-hidato-family knights-neighbour-offsets)) (displayln (puzzle->string (solve-a-knights-tour #(#(_ 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 _ _))))) (newline) (displayln (puzzle->string (solve-a-knights-tour #(#(- - - - - 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 - - - - -)))))
#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 Racket snippet to Java and keep its semantics consistent.
#lang racket (require "hidato-family-solver.rkt") (define knights-neighbour-offsets '((+1 +2) (-1 +2) (+1 -2) (-1 -2) (+2 +1) (-2 +1) (+2 -1) (-2 -1))) (define solve-a-knights-tour (solve-hidato-family knights-neighbour-offsets)) (displayln (puzzle->string (solve-a-knights-tour #(#(_ 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 _ _))))) (newline) (displayln (puzzle->string (solve-a-knights-tour #(#(- - - - - 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 - - - - -)))))
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(); } } }
Keep all operations the same but rewrite the snippet in Java.
#lang racket (require "hidato-family-solver.rkt") (define knights-neighbour-offsets '((+1 +2) (-1 +2) (+1 -2) (-1 -2) (+2 +1) (-2 +1) (+2 -1) (-2 -1))) (define solve-a-knights-tour (solve-hidato-family knights-neighbour-offsets)) (displayln (puzzle->string (solve-a-knights-tour #(#(_ 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 _ _))))) (newline) (displayln (puzzle->string (solve-a-knights-tour #(#(- - - - - 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 - - - - -)))))
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(); } } }
Keep all operations the same but rewrite the snippet in Python.
#lang racket (require "hidato-family-solver.rkt") (define knights-neighbour-offsets '((+1 +2) (-1 +2) (+1 -2) (-1 -2) (+2 +1) (-2 +1) (+2 -1) (-2 -1))) (define solve-a-knights-tour (solve-hidato-family knights-neighbour-offsets)) (displayln (puzzle->string (solve-a-knights-tour #(#(_ 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 _ _))))) (newline) (displayln (puzzle->string (solve-a-knights-tour #(#(- - - - - 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 - - - - -)))))
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)
Generate an equivalent Python version of this Racket code.
#lang racket (require "hidato-family-solver.rkt") (define knights-neighbour-offsets '((+1 +2) (-1 +2) (+1 -2) (-1 -2) (+2 +1) (-2 +1) (+2 -1) (-2 -1))) (define solve-a-knights-tour (solve-hidato-family knights-neighbour-offsets)) (displayln (puzzle->string (solve-a-knights-tour #(#(_ 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 _ _))))) (newline) (displayln (puzzle->string (solve-a-knights-tour #(#(- - - - - 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 - - - - -)))))
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 Go code behaves exactly like the original Racket snippet.
#lang racket (require "hidato-family-solver.rkt") (define knights-neighbour-offsets '((+1 +2) (-1 +2) (+1 -2) (-1 -2) (+2 +1) (-2 +1) (+2 -1) (-2 -1))) (define solve-a-knights-tour (solve-hidato-family knights-neighbour-offsets)) (displayln (puzzle->string (solve-a-knights-tour #(#(_ 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 _ _))))) (newline) (displayln (puzzle->string (solve-a-knights-tour #(#(- - - - - 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 - - - - -)))))
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 following code from Racket to Go with equivalent syntax and logic.
#lang racket (require "hidato-family-solver.rkt") (define knights-neighbour-offsets '((+1 +2) (-1 +2) (+1 -2) (-1 -2) (+2 +1) (-2 +1) (+2 -1) (-2 -1))) (define solve-a-knights-tour (solve-hidato-family knights-neighbour-offsets)) (displayln (puzzle->string (solve-a-knights-tour #(#(_ 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 _ _))))) (newline) (displayln (puzzle->string (solve-a-knights-tour #(#(- - - - - 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 - - - - -)))))
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 REXX implementation.
blank=pos('//', space(arg(1), 0))\==0 parse arg ops '/' cent parse var ops N sRank sFile . if N=='' | N=="," then N=8 if sRank=='' | sRank=="," then sRank=N if sFile=='' | sFile=="," then sFile=1 NN=N**2; NxN='a ' N"x"N ' chessboard' @.=; do r=1 for N; do f=1 for N; @.r.f=.; end cent=space( translate( cent, , ',') ) cents=0 do while cent\='' parse var cent cr cf x '/' cent if x='' then x=1 if cr='' then iterate do cf=cf for x @.cr.cf= '¢' end end do r=1 for N; do f=1 for N; cents=cents + (@.r.f=='¢'); end if cents\==0 then say cents 'pennies placed on chessboard.' target=NN - cents Kr = '2 1 -1 -2 -2 -1 1 2' Kf = '1 2 2 1 -1 -2 -2 -1' kr.M=words(Kr) parse var Kr Kr.1 Kr.2 Kr.3 Kr.4 Kr.5 Kr.6 Kr.7 Kr.8 parse var Kf Kf.1 Kf.2 Kf.3 Kf.4 Kf.5 Kf.6 Kf.7 Kf.8 beg= '-1-' if @.sRank.sFile ==. then @.sRank.sFile=beg if @.sRank.sFile\==beg then do sRank=1 for N do sFile=1 for N if @.sRank.sFile\==. then iterate @.sRank.sFile=beg leave sRank end end @hkt= "holy knight's tour" if \move(2,sRank,sFile) & \(N==1) then say 'No' @hkt "solution for" NxN'.' else say 'A solution for the' @hkt "on" NxN':' !=left('', 9 * (n<18) ); say _=substr( copies("┼───", N), 2); say ! translate('┌'_"┐", '┬', "┼") do r=N for N by -1; if r\==N then say ! '├'_"┤"; L=@. do f=1 for N; ?=@.r.f; if ?==target then ?='end'; L=L'│'center(?,3) end if blank then L=translate(L,,'¢') say ! translate(L'│', , .) end say ! translate('└'_"┘", '┴', "┼") exit move: procedure expose @. Kr. Kf. target; parse arg #,rank,file do t=1 for Kr.M; nr=rank+Kr.t; nf=file+Kf.t if @.nr.nf==. then do; @.nr.nf=# if #==target then return 1 if move(#+1,nr,nf) then return 1 @.nr.nf=. end end return 0
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 REXX implementation.
blank=pos('//', space(arg(1), 0))\==0 parse arg ops '/' cent parse var ops N sRank sFile . if N=='' | N=="," then N=8 if sRank=='' | sRank=="," then sRank=N if sFile=='' | sFile=="," then sFile=1 NN=N**2; NxN='a ' N"x"N ' chessboard' @.=; do r=1 for N; do f=1 for N; @.r.f=.; end cent=space( translate( cent, , ',') ) cents=0 do while cent\='' parse var cent cr cf x '/' cent if x='' then x=1 if cr='' then iterate do cf=cf for x @.cr.cf= '¢' end end do r=1 for N; do f=1 for N; cents=cents + (@.r.f=='¢'); end if cents\==0 then say cents 'pennies placed on chessboard.' target=NN - cents Kr = '2 1 -1 -2 -2 -1 1 2' Kf = '1 2 2 1 -1 -2 -2 -1' kr.M=words(Kr) parse var Kr Kr.1 Kr.2 Kr.3 Kr.4 Kr.5 Kr.6 Kr.7 Kr.8 parse var Kf Kf.1 Kf.2 Kf.3 Kf.4 Kf.5 Kf.6 Kf.7 Kf.8 beg= '-1-' if @.sRank.sFile ==. then @.sRank.sFile=beg if @.sRank.sFile\==beg then do sRank=1 for N do sFile=1 for N if @.sRank.sFile\==. then iterate @.sRank.sFile=beg leave sRank end end @hkt= "holy knight's tour" if \move(2,sRank,sFile) & \(N==1) then say 'No' @hkt "solution for" NxN'.' else say 'A solution for the' @hkt "on" NxN':' !=left('', 9 * (n<18) ); say _=substr( copies("┼───", N), 2); say ! translate('┌'_"┐", '┬', "┼") do r=N for N by -1; if r\==N then say ! '├'_"┤"; L=@. do f=1 for N; ?=@.r.f; if ?==target then ?='end'; L=L'│'center(?,3) end if blank then L=translate(L,,'¢') say ! translate(L'│', , .) end say ! translate('└'_"┘", '┴', "┼") exit move: procedure expose @. Kr. Kf. target; parse arg #,rank,file do t=1 for Kr.M; nr=rank+Kr.t; nf=file+Kf.t if @.nr.nf==. then do; @.nr.nf=# if #==target then return 1 if move(#+1,nr,nf) then return 1 @.nr.nf=. end end return 0
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 REXX snippet without changing its computational steps.
blank=pos('//', space(arg(1), 0))\==0 parse arg ops '/' cent parse var ops N sRank sFile . if N=='' | N=="," then N=8 if sRank=='' | sRank=="," then sRank=N if sFile=='' | sFile=="," then sFile=1 NN=N**2; NxN='a ' N"x"N ' chessboard' @.=; do r=1 for N; do f=1 for N; @.r.f=.; end cent=space( translate( cent, , ',') ) cents=0 do while cent\='' parse var cent cr cf x '/' cent if x='' then x=1 if cr='' then iterate do cf=cf for x @.cr.cf= '¢' end end do r=1 for N; do f=1 for N; cents=cents + (@.r.f=='¢'); end if cents\==0 then say cents 'pennies placed on chessboard.' target=NN - cents Kr = '2 1 -1 -2 -2 -1 1 2' Kf = '1 2 2 1 -1 -2 -2 -1' kr.M=words(Kr) parse var Kr Kr.1 Kr.2 Kr.3 Kr.4 Kr.5 Kr.6 Kr.7 Kr.8 parse var Kf Kf.1 Kf.2 Kf.3 Kf.4 Kf.5 Kf.6 Kf.7 Kf.8 beg= '-1-' if @.sRank.sFile ==. then @.sRank.sFile=beg if @.sRank.sFile\==beg then do sRank=1 for N do sFile=1 for N if @.sRank.sFile\==. then iterate @.sRank.sFile=beg leave sRank end end @hkt= "holy knight's tour" if \move(2,sRank,sFile) & \(N==1) then say 'No' @hkt "solution for" NxN'.' else say 'A solution for the' @hkt "on" NxN':' !=left('', 9 * (n<18) ); say _=substr( copies("┼───", N), 2); say ! translate('┌'_"┐", '┬', "┼") do r=N for N by -1; if r\==N then say ! '├'_"┤"; L=@. do f=1 for N; ?=@.r.f; if ?==target then ?='end'; L=L'│'center(?,3) end if blank then L=translate(L,,'¢') say ! translate(L'│', , .) end say ! translate('└'_"┘", '┴', "┼") exit move: procedure expose @. Kr. Kf. target; parse arg #,rank,file do t=1 for Kr.M; nr=rank+Kr.t; nf=file+Kf.t if @.nr.nf==. then do; @.nr.nf=# if #==target then return 1 if move(#+1,nr,nf) then return 1 @.nr.nf=. end end return 0
#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 REXX code into C++ without altering its purpose.
blank=pos('//', space(arg(1), 0))\==0 parse arg ops '/' cent parse var ops N sRank sFile . if N=='' | N=="," then N=8 if sRank=='' | sRank=="," then sRank=N if sFile=='' | sFile=="," then sFile=1 NN=N**2; NxN='a ' N"x"N ' chessboard' @.=; do r=1 for N; do f=1 for N; @.r.f=.; end cent=space( translate( cent, , ',') ) cents=0 do while cent\='' parse var cent cr cf x '/' cent if x='' then x=1 if cr='' then iterate do cf=cf for x @.cr.cf= '¢' end end do r=1 for N; do f=1 for N; cents=cents + (@.r.f=='¢'); end if cents\==0 then say cents 'pennies placed on chessboard.' target=NN - cents Kr = '2 1 -1 -2 -2 -1 1 2' Kf = '1 2 2 1 -1 -2 -2 -1' kr.M=words(Kr) parse var Kr Kr.1 Kr.2 Kr.3 Kr.4 Kr.5 Kr.6 Kr.7 Kr.8 parse var Kf Kf.1 Kf.2 Kf.3 Kf.4 Kf.5 Kf.6 Kf.7 Kf.8 beg= '-1-' if @.sRank.sFile ==. then @.sRank.sFile=beg if @.sRank.sFile\==beg then do sRank=1 for N do sFile=1 for N if @.sRank.sFile\==. then iterate @.sRank.sFile=beg leave sRank end end @hkt= "holy knight's tour" if \move(2,sRank,sFile) & \(N==1) then say 'No' @hkt "solution for" NxN'.' else say 'A solution for the' @hkt "on" NxN':' !=left('', 9 * (n<18) ); say _=substr( copies("┼───", N), 2); say ! translate('┌'_"┐", '┬', "┼") do r=N for N by -1; if r\==N then say ! '├'_"┤"; L=@. do f=1 for N; ?=@.r.f; if ?==target then ?='end'; L=L'│'center(?,3) end if blank then L=translate(L,,'¢') say ! translate(L'│', , .) end say ! translate('└'_"┘", '┴', "┼") exit move: procedure expose @. Kr. Kf. target; parse arg #,rank,file do t=1 for Kr.M; nr=rank+Kr.t; nf=file+Kf.t if @.nr.nf==. then do; @.nr.nf=# if #==target then return 1 if move(#+1,nr,nf) then return 1 @.nr.nf=. end end return 0
#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" ); }
Rewrite this program in Java while keeping its functionality equivalent to the REXX version.
blank=pos('//', space(arg(1), 0))\==0 parse arg ops '/' cent parse var ops N sRank sFile . if N=='' | N=="," then N=8 if sRank=='' | sRank=="," then sRank=N if sFile=='' | sFile=="," then sFile=1 NN=N**2; NxN='a ' N"x"N ' chessboard' @.=; do r=1 for N; do f=1 for N; @.r.f=.; end cent=space( translate( cent, , ',') ) cents=0 do while cent\='' parse var cent cr cf x '/' cent if x='' then x=1 if cr='' then iterate do cf=cf for x @.cr.cf= '¢' end end do r=1 for N; do f=1 for N; cents=cents + (@.r.f=='¢'); end if cents\==0 then say cents 'pennies placed on chessboard.' target=NN - cents Kr = '2 1 -1 -2 -2 -1 1 2' Kf = '1 2 2 1 -1 -2 -2 -1' kr.M=words(Kr) parse var Kr Kr.1 Kr.2 Kr.3 Kr.4 Kr.5 Kr.6 Kr.7 Kr.8 parse var Kf Kf.1 Kf.2 Kf.3 Kf.4 Kf.5 Kf.6 Kf.7 Kf.8 beg= '-1-' if @.sRank.sFile ==. then @.sRank.sFile=beg if @.sRank.sFile\==beg then do sRank=1 for N do sFile=1 for N if @.sRank.sFile\==. then iterate @.sRank.sFile=beg leave sRank end end @hkt= "holy knight's tour" if \move(2,sRank,sFile) & \(N==1) then say 'No' @hkt "solution for" NxN'.' else say 'A solution for the' @hkt "on" NxN':' !=left('', 9 * (n<18) ); say _=substr( copies("┼───", N), 2); say ! translate('┌'_"┐", '┬', "┼") do r=N for N by -1; if r\==N then say ! '├'_"┤"; L=@. do f=1 for N; ?=@.r.f; if ?==target then ?='end'; L=L'│'center(?,3) end if blank then L=translate(L,,'¢') say ! translate(L'│', , .) end say ! translate('└'_"┘", '┴', "┼") exit move: procedure expose @. Kr. Kf. target; parse arg #,rank,file do t=1 for Kr.M; nr=rank+Kr.t; nf=file+Kf.t if @.nr.nf==. then do; @.nr.nf=# if #==target then return 1 if move(#+1,nr,nf) then return 1 @.nr.nf=. end end return 0
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 REXX block to Java, preserving its control flow and logic.
blank=pos('//', space(arg(1), 0))\==0 parse arg ops '/' cent parse var ops N sRank sFile . if N=='' | N=="," then N=8 if sRank=='' | sRank=="," then sRank=N if sFile=='' | sFile=="," then sFile=1 NN=N**2; NxN='a ' N"x"N ' chessboard' @.=; do r=1 for N; do f=1 for N; @.r.f=.; end cent=space( translate( cent, , ',') ) cents=0 do while cent\='' parse var cent cr cf x '/' cent if x='' then x=1 if cr='' then iterate do cf=cf for x @.cr.cf= '¢' end end do r=1 for N; do f=1 for N; cents=cents + (@.r.f=='¢'); end if cents\==0 then say cents 'pennies placed on chessboard.' target=NN - cents Kr = '2 1 -1 -2 -2 -1 1 2' Kf = '1 2 2 1 -1 -2 -2 -1' kr.M=words(Kr) parse var Kr Kr.1 Kr.2 Kr.3 Kr.4 Kr.5 Kr.6 Kr.7 Kr.8 parse var Kf Kf.1 Kf.2 Kf.3 Kf.4 Kf.5 Kf.6 Kf.7 Kf.8 beg= '-1-' if @.sRank.sFile ==. then @.sRank.sFile=beg if @.sRank.sFile\==beg then do sRank=1 for N do sFile=1 for N if @.sRank.sFile\==. then iterate @.sRank.sFile=beg leave sRank end end @hkt= "holy knight's tour" if \move(2,sRank,sFile) & \(N==1) then say 'No' @hkt "solution for" NxN'.' else say 'A solution for the' @hkt "on" NxN':' !=left('', 9 * (n<18) ); say _=substr( copies("┼───", N), 2); say ! translate('┌'_"┐", '┬', "┼") do r=N for N by -1; if r\==N then say ! '├'_"┤"; L=@. do f=1 for N; ?=@.r.f; if ?==target then ?='end'; L=L'│'center(?,3) end if blank then L=translate(L,,'¢') say ! translate(L'│', , .) end say ! translate('└'_"┘", '┴', "┼") exit move: procedure expose @. Kr. Kf. target; parse arg #,rank,file do t=1 for Kr.M; nr=rank+Kr.t; nf=file+Kf.t if @.nr.nf==. then do; @.nr.nf=# if #==target then return 1 if move(#+1,nr,nf) then return 1 @.nr.nf=. end end return 0
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 following REXX code into Python without altering its purpose.
blank=pos('//', space(arg(1), 0))\==0 parse arg ops '/' cent parse var ops N sRank sFile . if N=='' | N=="," then N=8 if sRank=='' | sRank=="," then sRank=N if sFile=='' | sFile=="," then sFile=1 NN=N**2; NxN='a ' N"x"N ' chessboard' @.=; do r=1 for N; do f=1 for N; @.r.f=.; end cent=space( translate( cent, , ',') ) cents=0 do while cent\='' parse var cent cr cf x '/' cent if x='' then x=1 if cr='' then iterate do cf=cf for x @.cr.cf= '¢' end end do r=1 for N; do f=1 for N; cents=cents + (@.r.f=='¢'); end if cents\==0 then say cents 'pennies placed on chessboard.' target=NN - cents Kr = '2 1 -1 -2 -2 -1 1 2' Kf = '1 2 2 1 -1 -2 -2 -1' kr.M=words(Kr) parse var Kr Kr.1 Kr.2 Kr.3 Kr.4 Kr.5 Kr.6 Kr.7 Kr.8 parse var Kf Kf.1 Kf.2 Kf.3 Kf.4 Kf.5 Kf.6 Kf.7 Kf.8 beg= '-1-' if @.sRank.sFile ==. then @.sRank.sFile=beg if @.sRank.sFile\==beg then do sRank=1 for N do sFile=1 for N if @.sRank.sFile\==. then iterate @.sRank.sFile=beg leave sRank end end @hkt= "holy knight's tour" if \move(2,sRank,sFile) & \(N==1) then say 'No' @hkt "solution for" NxN'.' else say 'A solution for the' @hkt "on" NxN':' !=left('', 9 * (n<18) ); say _=substr( copies("┼───", N), 2); say ! translate('┌'_"┐", '┬', "┼") do r=N for N by -1; if r\==N then say ! '├'_"┤"; L=@. do f=1 for N; ?=@.r.f; if ?==target then ?='end'; L=L'│'center(?,3) end if blank then L=translate(L,,'¢') say ! translate(L'│', , .) end say ! translate('└'_"┘", '┴', "┼") exit move: procedure expose @. Kr. Kf. target; parse arg #,rank,file do t=1 for Kr.M; nr=rank+Kr.t; nf=file+Kf.t if @.nr.nf==. then do; @.nr.nf=# if #==target then return 1 if move(#+1,nr,nf) then return 1 @.nr.nf=. end end return 0
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 the given REXX code snippet into Python without altering its behavior.
blank=pos('//', space(arg(1), 0))\==0 parse arg ops '/' cent parse var ops N sRank sFile . if N=='' | N=="," then N=8 if sRank=='' | sRank=="," then sRank=N if sFile=='' | sFile=="," then sFile=1 NN=N**2; NxN='a ' N"x"N ' chessboard' @.=; do r=1 for N; do f=1 for N; @.r.f=.; end cent=space( translate( cent, , ',') ) cents=0 do while cent\='' parse var cent cr cf x '/' cent if x='' then x=1 if cr='' then iterate do cf=cf for x @.cr.cf= '¢' end end do r=1 for N; do f=1 for N; cents=cents + (@.r.f=='¢'); end if cents\==0 then say cents 'pennies placed on chessboard.' target=NN - cents Kr = '2 1 -1 -2 -2 -1 1 2' Kf = '1 2 2 1 -1 -2 -2 -1' kr.M=words(Kr) parse var Kr Kr.1 Kr.2 Kr.3 Kr.4 Kr.5 Kr.6 Kr.7 Kr.8 parse var Kf Kf.1 Kf.2 Kf.3 Kf.4 Kf.5 Kf.6 Kf.7 Kf.8 beg= '-1-' if @.sRank.sFile ==. then @.sRank.sFile=beg if @.sRank.sFile\==beg then do sRank=1 for N do sFile=1 for N if @.sRank.sFile\==. then iterate @.sRank.sFile=beg leave sRank end end @hkt= "holy knight's tour" if \move(2,sRank,sFile) & \(N==1) then say 'No' @hkt "solution for" NxN'.' else say 'A solution for the' @hkt "on" NxN':' !=left('', 9 * (n<18) ); say _=substr( copies("┼───", N), 2); say ! translate('┌'_"┐", '┬', "┼") do r=N for N by -1; if r\==N then say ! '├'_"┤"; L=@. do f=1 for N; ?=@.r.f; if ?==target then ?='end'; L=L'│'center(?,3) end if blank then L=translate(L,,'¢') say ! translate(L'│', , .) end say ! translate('└'_"┘", '┴', "┼") exit move: procedure expose @. Kr. Kf. target; parse arg #,rank,file do t=1 for Kr.M; nr=rank+Kr.t; nf=file+Kf.t if @.nr.nf==. then do; @.nr.nf=# if #==target then return 1 if move(#+1,nr,nf) then return 1 @.nr.nf=. end end return 0
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 REXX to Go.
blank=pos('//', space(arg(1), 0))\==0 parse arg ops '/' cent parse var ops N sRank sFile . if N=='' | N=="," then N=8 if sRank=='' | sRank=="," then sRank=N if sFile=='' | sFile=="," then sFile=1 NN=N**2; NxN='a ' N"x"N ' chessboard' @.=; do r=1 for N; do f=1 for N; @.r.f=.; end cent=space( translate( cent, , ',') ) cents=0 do while cent\='' parse var cent cr cf x '/' cent if x='' then x=1 if cr='' then iterate do cf=cf for x @.cr.cf= '¢' end end do r=1 for N; do f=1 for N; cents=cents + (@.r.f=='¢'); end if cents\==0 then say cents 'pennies placed on chessboard.' target=NN - cents Kr = '2 1 -1 -2 -2 -1 1 2' Kf = '1 2 2 1 -1 -2 -2 -1' kr.M=words(Kr) parse var Kr Kr.1 Kr.2 Kr.3 Kr.4 Kr.5 Kr.6 Kr.7 Kr.8 parse var Kf Kf.1 Kf.2 Kf.3 Kf.4 Kf.5 Kf.6 Kf.7 Kf.8 beg= '-1-' if @.sRank.sFile ==. then @.sRank.sFile=beg if @.sRank.sFile\==beg then do sRank=1 for N do sFile=1 for N if @.sRank.sFile\==. then iterate @.sRank.sFile=beg leave sRank end end @hkt= "holy knight's tour" if \move(2,sRank,sFile) & \(N==1) then say 'No' @hkt "solution for" NxN'.' else say 'A solution for the' @hkt "on" NxN':' !=left('', 9 * (n<18) ); say _=substr( copies("┼───", N), 2); say ! translate('┌'_"┐", '┬', "┼") do r=N for N by -1; if r\==N then say ! '├'_"┤"; L=@. do f=1 for N; ?=@.r.f; if ?==target then ?='end'; L=L'│'center(?,3) end if blank then L=translate(L,,'¢') say ! translate(L'│', , .) end say ! translate('└'_"┘", '┴', "┼") exit move: procedure expose @. Kr. Kf. target; parse arg #,rank,file do t=1 for Kr.M; nr=rank+Kr.t; nf=file+Kf.t if @.nr.nf==. then do; @.nr.nf=# if #==target then return 1 if move(#+1,nr,nf) then return 1 @.nr.nf=. end end return 0
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 a version of this REXX function in Go with identical behavior.
blank=pos('//', space(arg(1), 0))\==0 parse arg ops '/' cent parse var ops N sRank sFile . if N=='' | N=="," then N=8 if sRank=='' | sRank=="," then sRank=N if sFile=='' | sFile=="," then sFile=1 NN=N**2; NxN='a ' N"x"N ' chessboard' @.=; do r=1 for N; do f=1 for N; @.r.f=.; end cent=space( translate( cent, , ',') ) cents=0 do while cent\='' parse var cent cr cf x '/' cent if x='' then x=1 if cr='' then iterate do cf=cf for x @.cr.cf= '¢' end end do r=1 for N; do f=1 for N; cents=cents + (@.r.f=='¢'); end if cents\==0 then say cents 'pennies placed on chessboard.' target=NN - cents Kr = '2 1 -1 -2 -2 -1 1 2' Kf = '1 2 2 1 -1 -2 -2 -1' kr.M=words(Kr) parse var Kr Kr.1 Kr.2 Kr.3 Kr.4 Kr.5 Kr.6 Kr.7 Kr.8 parse var Kf Kf.1 Kf.2 Kf.3 Kf.4 Kf.5 Kf.6 Kf.7 Kf.8 beg= '-1-' if @.sRank.sFile ==. then @.sRank.sFile=beg if @.sRank.sFile\==beg then do sRank=1 for N do sFile=1 for N if @.sRank.sFile\==. then iterate @.sRank.sFile=beg leave sRank end end @hkt= "holy knight's tour" if \move(2,sRank,sFile) & \(N==1) then say 'No' @hkt "solution for" NxN'.' else say 'A solution for the' @hkt "on" NxN':' !=left('', 9 * (n<18) ); say _=substr( copies("┼───", N), 2); say ! translate('┌'_"┐", '┬', "┼") do r=N for N by -1; if r\==N then say ! '├'_"┤"; L=@. do f=1 for N; ?=@.r.f; if ?==target then ?='end'; L=L'│'center(?,3) end if blank then L=translate(L,,'¢') say ! translate(L'│', , .) end say ! translate('└'_"┘", '┴', "┼") exit move: procedure expose @. Kr. Kf. target; parse arg #,rank,file do t=1 for Kr.M; nr=rank+Kr.t; nf=file+Kf.t if @.nr.nf==. then do; @.nr.nf=# if #==target then return 1 if move(#+1,nr,nf) then return 1 @.nr.nf=. end end return 0
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 C# as shown below in Ruby.
require 'HLPsolver' ADJACENT = [[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2]] boardy = <<EOS . . 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 EOS t0 = Time.now HLPsolver.new(boardy).solve puts "
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 Ruby code in C#.
require 'HLPsolver' ADJACENT = [[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2]] boardy = <<EOS . . 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 EOS t0 = Time.now HLPsolver.new(boardy).solve puts "
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(); } }
Change the following Ruby code into C++ without altering its purpose.
require 'HLPsolver' ADJACENT = [[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2]] boardy = <<EOS . . 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 EOS t0 = Time.now HLPsolver.new(boardy).solve puts "
#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 Ruby snippet to C++ and keep its semantics consistent.
require 'HLPsolver' ADJACENT = [[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2]] boardy = <<EOS . . 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 EOS t0 = Time.now HLPsolver.new(boardy).solve puts "
#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 Ruby implementation.
require 'HLPsolver' ADJACENT = [[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2]] boardy = <<EOS . . 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 EOS t0 = Time.now HLPsolver.new(boardy).solve puts "
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(); } } }
Can you help me rewrite this code in Java instead of Ruby, keeping it the same logically?
require 'HLPsolver' ADJACENT = [[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2]] boardy = <<EOS . . 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 EOS t0 = Time.now HLPsolver.new(boardy).solve puts "
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 Ruby.
require 'HLPsolver' ADJACENT = [[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2]] boardy = <<EOS . . 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 EOS t0 = Time.now HLPsolver.new(boardy).solve puts "
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 Ruby function in Python with identical behavior.
require 'HLPsolver' ADJACENT = [[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2]] boardy = <<EOS . . 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 EOS t0 = Time.now HLPsolver.new(boardy).solve puts "
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 Ruby code in Go.
require 'HLPsolver' ADJACENT = [[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2]] boardy = <<EOS . . 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 EOS t0 = Time.now HLPsolver.new(boardy).solve puts "
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 Ruby code into Go without altering its purpose.
require 'HLPsolver' ADJACENT = [[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2]] boardy = <<EOS . . 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 EOS t0 = Time.now HLPsolver.new(boardy).solve puts "
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#.
val moves = arrayOf( intArrayOf(-1, -2), intArrayOf( 1, -2), intArrayOf(-1, 2), intArrayOf(1, 2), intArrayOf(-2, -1), intArrayOf(-2, 1), intArrayOf( 2, -1), intArrayOf(2, 1) ) val board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " val 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....." fun solve(pz: Array<IntArray>, sz: Int, sx: Int, sy: Int, idx: Int, cnt: Int): Boolean { if (idx > cnt) return true for (i in 0 until moves.size) { val x = sx + moves[i][0] val y = sy + moves[i][1] if ((x in 0 until sz) && (y in 0 until 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 } fun findSolution(b: String, sz: Int) { val pz = Array(sz) { IntArray(sz) { -1 } } var x = 0 var y = 0 var idx = 0 var cnt = 0 for (j in 0 until sz) { for (i in 0 until sz) { if (b[idx] == 'x') { pz[i][j] = 0 cnt++ } else if (b[idx] == 's') { pz[i][j] = 1 cnt++ x = i y = j } idx++ } } if (solve(pz, sz, x, y, 2, cnt)) { for (j in 0 until sz) { for (i in 0 until sz) { if (pz[i][j] != -1) print("%02d ".format(pz[i][j])) else print("-- ") } println() } } else println("Cannot solve this puzzle!") } fun main(args: Array<String>) { findSolution(board1, 8) println() findSolution(board2, 13) }
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 Scala code into C# while preserving the original functionality.
val moves = arrayOf( intArrayOf(-1, -2), intArrayOf( 1, -2), intArrayOf(-1, 2), intArrayOf(1, 2), intArrayOf(-2, -1), intArrayOf(-2, 1), intArrayOf( 2, -1), intArrayOf(2, 1) ) val board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " val 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....." fun solve(pz: Array<IntArray>, sz: Int, sx: Int, sy: Int, idx: Int, cnt: Int): Boolean { if (idx > cnt) return true for (i in 0 until moves.size) { val x = sx + moves[i][0] val y = sy + moves[i][1] if ((x in 0 until sz) && (y in 0 until 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 } fun findSolution(b: String, sz: Int) { val pz = Array(sz) { IntArray(sz) { -1 } } var x = 0 var y = 0 var idx = 0 var cnt = 0 for (j in 0 until sz) { for (i in 0 until sz) { if (b[idx] == 'x') { pz[i][j] = 0 cnt++ } else if (b[idx] == 's') { pz[i][j] = 1 cnt++ x = i y = j } idx++ } } if (solve(pz, sz, x, y, 2, cnt)) { for (j in 0 until sz) { for (i in 0 until sz) { if (pz[i][j] != -1) print("%02d ".format(pz[i][j])) else print("-- ") } println() } } else println("Cannot solve this puzzle!") } fun main(args: Array<String>) { findSolution(board1, 8) println() findSolution(board2, 13) }
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 Scala to C++, ensuring the logic remains intact.
val moves = arrayOf( intArrayOf(-1, -2), intArrayOf( 1, -2), intArrayOf(-1, 2), intArrayOf(1, 2), intArrayOf(-2, -1), intArrayOf(-2, 1), intArrayOf( 2, -1), intArrayOf(2, 1) ) val board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " val 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....." fun solve(pz: Array<IntArray>, sz: Int, sx: Int, sy: Int, idx: Int, cnt: Int): Boolean { if (idx > cnt) return true for (i in 0 until moves.size) { val x = sx + moves[i][0] val y = sy + moves[i][1] if ((x in 0 until sz) && (y in 0 until 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 } fun findSolution(b: String, sz: Int) { val pz = Array(sz) { IntArray(sz) { -1 } } var x = 0 var y = 0 var idx = 0 var cnt = 0 for (j in 0 until sz) { for (i in 0 until sz) { if (b[idx] == 'x') { pz[i][j] = 0 cnt++ } else if (b[idx] == 's') { pz[i][j] = 1 cnt++ x = i y = j } idx++ } } if (solve(pz, sz, x, y, 2, cnt)) { for (j in 0 until sz) { for (i in 0 until sz) { if (pz[i][j] != -1) print("%02d ".format(pz[i][j])) else print("-- ") } println() } } else println("Cannot solve this puzzle!") } fun main(args: Array<String>) { findSolution(board1, 8) println() findSolution(board2, 13) }
#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 C++ version of this Scala code.
val moves = arrayOf( intArrayOf(-1, -2), intArrayOf( 1, -2), intArrayOf(-1, 2), intArrayOf(1, 2), intArrayOf(-2, -1), intArrayOf(-2, 1), intArrayOf( 2, -1), intArrayOf(2, 1) ) val board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " val 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....." fun solve(pz: Array<IntArray>, sz: Int, sx: Int, sy: Int, idx: Int, cnt: Int): Boolean { if (idx > cnt) return true for (i in 0 until moves.size) { val x = sx + moves[i][0] val y = sy + moves[i][1] if ((x in 0 until sz) && (y in 0 until 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 } fun findSolution(b: String, sz: Int) { val pz = Array(sz) { IntArray(sz) { -1 } } var x = 0 var y = 0 var idx = 0 var cnt = 0 for (j in 0 until sz) { for (i in 0 until sz) { if (b[idx] == 'x') { pz[i][j] = 0 cnt++ } else if (b[idx] == 's') { pz[i][j] = 1 cnt++ x = i y = j } idx++ } } if (solve(pz, sz, x, y, 2, cnt)) { for (j in 0 until sz) { for (i in 0 until sz) { if (pz[i][j] != -1) print("%02d ".format(pz[i][j])) else print("-- ") } println() } } else println("Cannot solve this puzzle!") } fun main(args: Array<String>) { findSolution(board1, 8) println() findSolution(board2, 13) }
#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 the given Scala code snippet into Java without altering its behavior.
val moves = arrayOf( intArrayOf(-1, -2), intArrayOf( 1, -2), intArrayOf(-1, 2), intArrayOf(1, 2), intArrayOf(-2, -1), intArrayOf(-2, 1), intArrayOf( 2, -1), intArrayOf(2, 1) ) val board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " val 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....." fun solve(pz: Array<IntArray>, sz: Int, sx: Int, sy: Int, idx: Int, cnt: Int): Boolean { if (idx > cnt) return true for (i in 0 until moves.size) { val x = sx + moves[i][0] val y = sy + moves[i][1] if ((x in 0 until sz) && (y in 0 until 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 } fun findSolution(b: String, sz: Int) { val pz = Array(sz) { IntArray(sz) { -1 } } var x = 0 var y = 0 var idx = 0 var cnt = 0 for (j in 0 until sz) { for (i in 0 until sz) { if (b[idx] == 'x') { pz[i][j] = 0 cnt++ } else if (b[idx] == 's') { pz[i][j] = 1 cnt++ x = i y = j } idx++ } } if (solve(pz, sz, x, y, 2, cnt)) { for (j in 0 until sz) { for (i in 0 until sz) { if (pz[i][j] != -1) print("%02d ".format(pz[i][j])) else print("-- ") } println() } } else println("Cannot solve this puzzle!") } fun main(args: Array<String>) { findSolution(board1, 8) println() findSolution(board2, 13) }
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 functionally identical Java code for the snippet given in Scala.
val moves = arrayOf( intArrayOf(-1, -2), intArrayOf( 1, -2), intArrayOf(-1, 2), intArrayOf(1, 2), intArrayOf(-2, -1), intArrayOf(-2, 1), intArrayOf( 2, -1), intArrayOf(2, 1) ) val board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " val 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....." fun solve(pz: Array<IntArray>, sz: Int, sx: Int, sy: Int, idx: Int, cnt: Int): Boolean { if (idx > cnt) return true for (i in 0 until moves.size) { val x = sx + moves[i][0] val y = sy + moves[i][1] if ((x in 0 until sz) && (y in 0 until 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 } fun findSolution(b: String, sz: Int) { val pz = Array(sz) { IntArray(sz) { -1 } } var x = 0 var y = 0 var idx = 0 var cnt = 0 for (j in 0 until sz) { for (i in 0 until sz) { if (b[idx] == 'x') { pz[i][j] = 0 cnt++ } else if (b[idx] == 's') { pz[i][j] = 1 cnt++ x = i y = j } idx++ } } if (solve(pz, sz, x, y, 2, cnt)) { for (j in 0 until sz) { for (i in 0 until sz) { if (pz[i][j] != -1) print("%02d ".format(pz[i][j])) else print("-- ") } println() } } else println("Cannot solve this puzzle!") } fun main(args: Array<String>) { findSolution(board1, 8) println() findSolution(board2, 13) }
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 Scala function in Python with identical behavior.
val moves = arrayOf( intArrayOf(-1, -2), intArrayOf( 1, -2), intArrayOf(-1, 2), intArrayOf(1, 2), intArrayOf(-2, -1), intArrayOf(-2, 1), intArrayOf( 2, -1), intArrayOf(2, 1) ) val board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " val 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....." fun solve(pz: Array<IntArray>, sz: Int, sx: Int, sy: Int, idx: Int, cnt: Int): Boolean { if (idx > cnt) return true for (i in 0 until moves.size) { val x = sx + moves[i][0] val y = sy + moves[i][1] if ((x in 0 until sz) && (y in 0 until 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 } fun findSolution(b: String, sz: Int) { val pz = Array(sz) { IntArray(sz) { -1 } } var x = 0 var y = 0 var idx = 0 var cnt = 0 for (j in 0 until sz) { for (i in 0 until sz) { if (b[idx] == 'x') { pz[i][j] = 0 cnt++ } else if (b[idx] == 's') { pz[i][j] = 1 cnt++ x = i y = j } idx++ } } if (solve(pz, sz, x, y, 2, cnt)) { for (j in 0 until sz) { for (i in 0 until sz) { if (pz[i][j] != -1) print("%02d ".format(pz[i][j])) else print("-- ") } println() } } else println("Cannot solve this puzzle!") } fun main(args: Array<String>) { findSolution(board1, 8) println() findSolution(board2, 13) }
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 Scala code into Python while preserving the original functionality.
val moves = arrayOf( intArrayOf(-1, -2), intArrayOf( 1, -2), intArrayOf(-1, 2), intArrayOf(1, 2), intArrayOf(-2, -1), intArrayOf(-2, 1), intArrayOf( 2, -1), intArrayOf(2, 1) ) val board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " val 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....." fun solve(pz: Array<IntArray>, sz: Int, sx: Int, sy: Int, idx: Int, cnt: Int): Boolean { if (idx > cnt) return true for (i in 0 until moves.size) { val x = sx + moves[i][0] val y = sy + moves[i][1] if ((x in 0 until sz) && (y in 0 until 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 } fun findSolution(b: String, sz: Int) { val pz = Array(sz) { IntArray(sz) { -1 } } var x = 0 var y = 0 var idx = 0 var cnt = 0 for (j in 0 until sz) { for (i in 0 until sz) { if (b[idx] == 'x') { pz[i][j] = 0 cnt++ } else if (b[idx] == 's') { pz[i][j] = 1 cnt++ x = i y = j } idx++ } } if (solve(pz, sz, x, y, 2, cnt)) { for (j in 0 until sz) { for (i in 0 until sz) { if (pz[i][j] != -1) print("%02d ".format(pz[i][j])) else print("-- ") } println() } } else println("Cannot solve this puzzle!") } fun main(args: Array<String>) { findSolution(board1, 8) println() findSolution(board2, 13) }
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.
val moves = arrayOf( intArrayOf(-1, -2), intArrayOf( 1, -2), intArrayOf(-1, 2), intArrayOf(1, 2), intArrayOf(-2, -1), intArrayOf(-2, 1), intArrayOf( 2, -1), intArrayOf(2, 1) ) val board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " val 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....." fun solve(pz: Array<IntArray>, sz: Int, sx: Int, sy: Int, idx: Int, cnt: Int): Boolean { if (idx > cnt) return true for (i in 0 until moves.size) { val x = sx + moves[i][0] val y = sy + moves[i][1] if ((x in 0 until sz) && (y in 0 until 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 } fun findSolution(b: String, sz: Int) { val pz = Array(sz) { IntArray(sz) { -1 } } var x = 0 var y = 0 var idx = 0 var cnt = 0 for (j in 0 until sz) { for (i in 0 until sz) { if (b[idx] == 'x') { pz[i][j] = 0 cnt++ } else if (b[idx] == 's') { pz[i][j] = 1 cnt++ x = i y = j } idx++ } } if (solve(pz, sz, x, y, 2, cnt)) { for (j in 0 until sz) { for (i in 0 until sz) { if (pz[i][j] != -1) print("%02d ".format(pz[i][j])) else print("-- ") } println() } } else println("Cannot solve this puzzle!") } fun main(args: Array<String>) { findSolution(board1, 8) println() findSolution(board2, 13) }
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 Scala to Go, same semantics.
val moves = arrayOf( intArrayOf(-1, -2), intArrayOf( 1, -2), intArrayOf(-1, 2), intArrayOf(1, 2), intArrayOf(-2, -1), intArrayOf(-2, 1), intArrayOf( 2, -1), intArrayOf(2, 1) ) val board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " val 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....." fun solve(pz: Array<IntArray>, sz: Int, sx: Int, sy: Int, idx: Int, cnt: Int): Boolean { if (idx > cnt) return true for (i in 0 until moves.size) { val x = sx + moves[i][0] val y = sy + moves[i][1] if ((x in 0 until sz) && (y in 0 until 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 } fun findSolution(b: String, sz: Int) { val pz = Array(sz) { IntArray(sz) { -1 } } var x = 0 var y = 0 var idx = 0 var cnt = 0 for (j in 0 until sz) { for (i in 0 until sz) { if (b[idx] == 'x') { pz[i][j] = 0 cnt++ } else if (b[idx] == 's') { pz[i][j] = 1 cnt++ x = i y = j } idx++ } } if (solve(pz, sz, x, y, 2, cnt)) { for (j in 0 until sz) { for (i in 0 until sz) { if (pz[i][j] != -1) print("%02d ".format(pz[i][j])) else print("-- ") } println() } } else println("Cannot solve this puzzle!") } fun main(args: Array<String>) { findSolution(board1, 8) println() findSolution(board2, 13) }
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 C# as shown below in Tcl.
package require Tcl 8.6 oo::class create HKTSolver { variable grid start limit constructor {puzzle} { set grid $puzzle for {set y 0} {$y < [llength $grid]} {incr y} { for {set x 0} {$x < [llength [lindex $grid $y]]} {incr x} { if {[set cell [lindex $grid $y $x]] == 1} { set start [list $y $x] } incr limit [expr {$cell>=0}] } } if {![info exist start]} { return -code error "no starting position found" } } method moves {} { return { -1 -2 1 -2 -2 -1 2 -1 -2 1 2 1 -1 2 1 2 } } method Moves {g r c} { set valid {} foreach {dr dc} [my moves] { set R [expr {$r + $dr}] set C [expr {$c + $dc}] if {[lindex $g $R $C] == 0} { lappend valid $R $C } } return $valid } method Solve {g r c v} { lset g $r $c [incr v] if {$v >= $limit} {return $g} foreach {r c} [my Moves $g $r $c] { return [my Solve $g $r $c $v] } return -code continue } method solve {} { while {[incr i]==1} { set grid [my Solve $grid {*}$start 0] return } return -code error "solution not possible" } method solution {} {return $grid} } proc parsePuzzle {str} { foreach line [split $str "\n"] { if {[string trim $line] eq ""} continue lappend rows [lmap {- c} [regexp -all -inline {(.)\s?} $line] { string map {" " -1} $c }] } set len [tcl::mathfunc::max {*}[lmap r $rows {llength $r}]] for {set i 0} {$i < [llength $rows]} {incr i} { while {[llength [lindex $rows $i]] < $len} { lset rows $i end+1 -1 } } return $rows } proc showPuzzle {grid name} { foreach row $grid {foreach cell $row {incr c [expr {$cell>=0}]}} set len [string length $c] set u [string repeat "_" $len] puts "$name with $c cells" foreach row $grid { puts [format " %s" [join [lmap c $row { format "%*s" $len [if {$c==-1} list elseif {$c==0} {set u} {set c}] }]]] } } set puzzle [parsePuzzle { 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 }] showPuzzle $puzzle "Input" HKTSolver create hkt $puzzle hkt solve showPuzzle [hkt solution] "Output"
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 Tcl to C#.
package require Tcl 8.6 oo::class create HKTSolver { variable grid start limit constructor {puzzle} { set grid $puzzle for {set y 0} {$y < [llength $grid]} {incr y} { for {set x 0} {$x < [llength [lindex $grid $y]]} {incr x} { if {[set cell [lindex $grid $y $x]] == 1} { set start [list $y $x] } incr limit [expr {$cell>=0}] } } if {![info exist start]} { return -code error "no starting position found" } } method moves {} { return { -1 -2 1 -2 -2 -1 2 -1 -2 1 2 1 -1 2 1 2 } } method Moves {g r c} { set valid {} foreach {dr dc} [my moves] { set R [expr {$r + $dr}] set C [expr {$c + $dc}] if {[lindex $g $R $C] == 0} { lappend valid $R $C } } return $valid } method Solve {g r c v} { lset g $r $c [incr v] if {$v >= $limit} {return $g} foreach {r c} [my Moves $g $r $c] { return [my Solve $g $r $c $v] } return -code continue } method solve {} { while {[incr i]==1} { set grid [my Solve $grid {*}$start 0] return } return -code error "solution not possible" } method solution {} {return $grid} } proc parsePuzzle {str} { foreach line [split $str "\n"] { if {[string trim $line] eq ""} continue lappend rows [lmap {- c} [regexp -all -inline {(.)\s?} $line] { string map {" " -1} $c }] } set len [tcl::mathfunc::max {*}[lmap r $rows {llength $r}]] for {set i 0} {$i < [llength $rows]} {incr i} { while {[llength [lindex $rows $i]] < $len} { lset rows $i end+1 -1 } } return $rows } proc showPuzzle {grid name} { foreach row $grid {foreach cell $row {incr c [expr {$cell>=0}]}} set len [string length $c] set u [string repeat "_" $len] puts "$name with $c cells" foreach row $grid { puts [format " %s" [join [lmap c $row { format "%*s" $len [if {$c==-1} list elseif {$c==0} {set u} {set c}] }]]] } } set puzzle [parsePuzzle { 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 }] showPuzzle $puzzle "Input" HKTSolver create hkt $puzzle hkt solve showPuzzle [hkt solution] "Output"
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 this program in C++ while keeping its functionality equivalent to the Tcl version.
package require Tcl 8.6 oo::class create HKTSolver { variable grid start limit constructor {puzzle} { set grid $puzzle for {set y 0} {$y < [llength $grid]} {incr y} { for {set x 0} {$x < [llength [lindex $grid $y]]} {incr x} { if {[set cell [lindex $grid $y $x]] == 1} { set start [list $y $x] } incr limit [expr {$cell>=0}] } } if {![info exist start]} { return -code error "no starting position found" } } method moves {} { return { -1 -2 1 -2 -2 -1 2 -1 -2 1 2 1 -1 2 1 2 } } method Moves {g r c} { set valid {} foreach {dr dc} [my moves] { set R [expr {$r + $dr}] set C [expr {$c + $dc}] if {[lindex $g $R $C] == 0} { lappend valid $R $C } } return $valid } method Solve {g r c v} { lset g $r $c [incr v] if {$v >= $limit} {return $g} foreach {r c} [my Moves $g $r $c] { return [my Solve $g $r $c $v] } return -code continue } method solve {} { while {[incr i]==1} { set grid [my Solve $grid {*}$start 0] return } return -code error "solution not possible" } method solution {} {return $grid} } proc parsePuzzle {str} { foreach line [split $str "\n"] { if {[string trim $line] eq ""} continue lappend rows [lmap {- c} [regexp -all -inline {(.)\s?} $line] { string map {" " -1} $c }] } set len [tcl::mathfunc::max {*}[lmap r $rows {llength $r}]] for {set i 0} {$i < [llength $rows]} {incr i} { while {[llength [lindex $rows $i]] < $len} { lset rows $i end+1 -1 } } return $rows } proc showPuzzle {grid name} { foreach row $grid {foreach cell $row {incr c [expr {$cell>=0}]}} set len [string length $c] set u [string repeat "_" $len] puts "$name with $c cells" foreach row $grid { puts [format " %s" [join [lmap c $row { format "%*s" $len [if {$c==-1} list elseif {$c==0} {set u} {set c}] }]]] } } set puzzle [parsePuzzle { 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 }] showPuzzle $puzzle "Input" HKTSolver create hkt $puzzle hkt solve showPuzzle [hkt solution] "Output"
#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 C++ version of this Tcl code.
package require Tcl 8.6 oo::class create HKTSolver { variable grid start limit constructor {puzzle} { set grid $puzzle for {set y 0} {$y < [llength $grid]} {incr y} { for {set x 0} {$x < [llength [lindex $grid $y]]} {incr x} { if {[set cell [lindex $grid $y $x]] == 1} { set start [list $y $x] } incr limit [expr {$cell>=0}] } } if {![info exist start]} { return -code error "no starting position found" } } method moves {} { return { -1 -2 1 -2 -2 -1 2 -1 -2 1 2 1 -1 2 1 2 } } method Moves {g r c} { set valid {} foreach {dr dc} [my moves] { set R [expr {$r + $dr}] set C [expr {$c + $dc}] if {[lindex $g $R $C] == 0} { lappend valid $R $C } } return $valid } method Solve {g r c v} { lset g $r $c [incr v] if {$v >= $limit} {return $g} foreach {r c} [my Moves $g $r $c] { return [my Solve $g $r $c $v] } return -code continue } method solve {} { while {[incr i]==1} { set grid [my Solve $grid {*}$start 0] return } return -code error "solution not possible" } method solution {} {return $grid} } proc parsePuzzle {str} { foreach line [split $str "\n"] { if {[string trim $line] eq ""} continue lappend rows [lmap {- c} [regexp -all -inline {(.)\s?} $line] { string map {" " -1} $c }] } set len [tcl::mathfunc::max {*}[lmap r $rows {llength $r}]] for {set i 0} {$i < [llength $rows]} {incr i} { while {[llength [lindex $rows $i]] < $len} { lset rows $i end+1 -1 } } return $rows } proc showPuzzle {grid name} { foreach row $grid {foreach cell $row {incr c [expr {$cell>=0}]}} set len [string length $c] set u [string repeat "_" $len] puts "$name with $c cells" foreach row $grid { puts [format " %s" [join [lmap c $row { format "%*s" $len [if {$c==-1} list elseif {$c==0} {set u} {set c}] }]]] } } set puzzle [parsePuzzle { 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 }] showPuzzle $puzzle "Input" HKTSolver create hkt $puzzle hkt solve showPuzzle [hkt solution] "Output"
#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 Java code for the snippet given in Tcl.
package require Tcl 8.6 oo::class create HKTSolver { variable grid start limit constructor {puzzle} { set grid $puzzle for {set y 0} {$y < [llength $grid]} {incr y} { for {set x 0} {$x < [llength [lindex $grid $y]]} {incr x} { if {[set cell [lindex $grid $y $x]] == 1} { set start [list $y $x] } incr limit [expr {$cell>=0}] } } if {![info exist start]} { return -code error "no starting position found" } } method moves {} { return { -1 -2 1 -2 -2 -1 2 -1 -2 1 2 1 -1 2 1 2 } } method Moves {g r c} { set valid {} foreach {dr dc} [my moves] { set R [expr {$r + $dr}] set C [expr {$c + $dc}] if {[lindex $g $R $C] == 0} { lappend valid $R $C } } return $valid } method Solve {g r c v} { lset g $r $c [incr v] if {$v >= $limit} {return $g} foreach {r c} [my Moves $g $r $c] { return [my Solve $g $r $c $v] } return -code continue } method solve {} { while {[incr i]==1} { set grid [my Solve $grid {*}$start 0] return } return -code error "solution not possible" } method solution {} {return $grid} } proc parsePuzzle {str} { foreach line [split $str "\n"] { if {[string trim $line] eq ""} continue lappend rows [lmap {- c} [regexp -all -inline {(.)\s?} $line] { string map {" " -1} $c }] } set len [tcl::mathfunc::max {*}[lmap r $rows {llength $r}]] for {set i 0} {$i < [llength $rows]} {incr i} { while {[llength [lindex $rows $i]] < $len} { lset rows $i end+1 -1 } } return $rows } proc showPuzzle {grid name} { foreach row $grid {foreach cell $row {incr c [expr {$cell>=0}]}} set len [string length $c] set u [string repeat "_" $len] puts "$name with $c cells" foreach row $grid { puts [format " %s" [join [lmap c $row { format "%*s" $len [if {$c==-1} list elseif {$c==0} {set u} {set c}] }]]] } } set puzzle [parsePuzzle { 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 }] showPuzzle $puzzle "Input" HKTSolver create hkt $puzzle hkt solve showPuzzle [hkt solution] "Output"
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 functionally identical Java code for the snippet given in Tcl.
package require Tcl 8.6 oo::class create HKTSolver { variable grid start limit constructor {puzzle} { set grid $puzzle for {set y 0} {$y < [llength $grid]} {incr y} { for {set x 0} {$x < [llength [lindex $grid $y]]} {incr x} { if {[set cell [lindex $grid $y $x]] == 1} { set start [list $y $x] } incr limit [expr {$cell>=0}] } } if {![info exist start]} { return -code error "no starting position found" } } method moves {} { return { -1 -2 1 -2 -2 -1 2 -1 -2 1 2 1 -1 2 1 2 } } method Moves {g r c} { set valid {} foreach {dr dc} [my moves] { set R [expr {$r + $dr}] set C [expr {$c + $dc}] if {[lindex $g $R $C] == 0} { lappend valid $R $C } } return $valid } method Solve {g r c v} { lset g $r $c [incr v] if {$v >= $limit} {return $g} foreach {r c} [my Moves $g $r $c] { return [my Solve $g $r $c $v] } return -code continue } method solve {} { while {[incr i]==1} { set grid [my Solve $grid {*}$start 0] return } return -code error "solution not possible" } method solution {} {return $grid} } proc parsePuzzle {str} { foreach line [split $str "\n"] { if {[string trim $line] eq ""} continue lappend rows [lmap {- c} [regexp -all -inline {(.)\s?} $line] { string map {" " -1} $c }] } set len [tcl::mathfunc::max {*}[lmap r $rows {llength $r}]] for {set i 0} {$i < [llength $rows]} {incr i} { while {[llength [lindex $rows $i]] < $len} { lset rows $i end+1 -1 } } return $rows } proc showPuzzle {grid name} { foreach row $grid {foreach cell $row {incr c [expr {$cell>=0}]}} set len [string length $c] set u [string repeat "_" $len] puts "$name with $c cells" foreach row $grid { puts [format " %s" [join [lmap c $row { format "%*s" $len [if {$c==-1} list elseif {$c==0} {set u} {set c}] }]]] } } set puzzle [parsePuzzle { 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 }] showPuzzle $puzzle "Input" HKTSolver create hkt $puzzle hkt solve showPuzzle [hkt solution] "Output"
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 Tcl snippet to Python and keep its semantics consistent.
package require Tcl 8.6 oo::class create HKTSolver { variable grid start limit constructor {puzzle} { set grid $puzzle for {set y 0} {$y < [llength $grid]} {incr y} { for {set x 0} {$x < [llength [lindex $grid $y]]} {incr x} { if {[set cell [lindex $grid $y $x]] == 1} { set start [list $y $x] } incr limit [expr {$cell>=0}] } } if {![info exist start]} { return -code error "no starting position found" } } method moves {} { return { -1 -2 1 -2 -2 -1 2 -1 -2 1 2 1 -1 2 1 2 } } method Moves {g r c} { set valid {} foreach {dr dc} [my moves] { set R [expr {$r + $dr}] set C [expr {$c + $dc}] if {[lindex $g $R $C] == 0} { lappend valid $R $C } } return $valid } method Solve {g r c v} { lset g $r $c [incr v] if {$v >= $limit} {return $g} foreach {r c} [my Moves $g $r $c] { return [my Solve $g $r $c $v] } return -code continue } method solve {} { while {[incr i]==1} { set grid [my Solve $grid {*}$start 0] return } return -code error "solution not possible" } method solution {} {return $grid} } proc parsePuzzle {str} { foreach line [split $str "\n"] { if {[string trim $line] eq ""} continue lappend rows [lmap {- c} [regexp -all -inline {(.)\s?} $line] { string map {" " -1} $c }] } set len [tcl::mathfunc::max {*}[lmap r $rows {llength $r}]] for {set i 0} {$i < [llength $rows]} {incr i} { while {[llength [lindex $rows $i]] < $len} { lset rows $i end+1 -1 } } return $rows } proc showPuzzle {grid name} { foreach row $grid {foreach cell $row {incr c [expr {$cell>=0}]}} set len [string length $c] set u [string repeat "_" $len] puts "$name with $c cells" foreach row $grid { puts [format " %s" [join [lmap c $row { format "%*s" $len [if {$c==-1} list elseif {$c==0} {set u} {set c}] }]]] } } set puzzle [parsePuzzle { 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 }] showPuzzle $puzzle "Input" HKTSolver create hkt $puzzle hkt solve showPuzzle [hkt solution] "Output"
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 the given Tcl code snippet into Python without altering its behavior.
package require Tcl 8.6 oo::class create HKTSolver { variable grid start limit constructor {puzzle} { set grid $puzzle for {set y 0} {$y < [llength $grid]} {incr y} { for {set x 0} {$x < [llength [lindex $grid $y]]} {incr x} { if {[set cell [lindex $grid $y $x]] == 1} { set start [list $y $x] } incr limit [expr {$cell>=0}] } } if {![info exist start]} { return -code error "no starting position found" } } method moves {} { return { -1 -2 1 -2 -2 -1 2 -1 -2 1 2 1 -1 2 1 2 } } method Moves {g r c} { set valid {} foreach {dr dc} [my moves] { set R [expr {$r + $dr}] set C [expr {$c + $dc}] if {[lindex $g $R $C] == 0} { lappend valid $R $C } } return $valid } method Solve {g r c v} { lset g $r $c [incr v] if {$v >= $limit} {return $g} foreach {r c} [my Moves $g $r $c] { return [my Solve $g $r $c $v] } return -code continue } method solve {} { while {[incr i]==1} { set grid [my Solve $grid {*}$start 0] return } return -code error "solution not possible" } method solution {} {return $grid} } proc parsePuzzle {str} { foreach line [split $str "\n"] { if {[string trim $line] eq ""} continue lappend rows [lmap {- c} [regexp -all -inline {(.)\s?} $line] { string map {" " -1} $c }] } set len [tcl::mathfunc::max {*}[lmap r $rows {llength $r}]] for {set i 0} {$i < [llength $rows]} {incr i} { while {[llength [lindex $rows $i]] < $len} { lset rows $i end+1 -1 } } return $rows } proc showPuzzle {grid name} { foreach row $grid {foreach cell $row {incr c [expr {$cell>=0}]}} set len [string length $c] set u [string repeat "_" $len] puts "$name with $c cells" foreach row $grid { puts [format " %s" [join [lmap c $row { format "%*s" $len [if {$c==-1} list elseif {$c==0} {set u} {set c}] }]]] } } set puzzle [parsePuzzle { 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 }] showPuzzle $puzzle "Input" HKTSolver create hkt $puzzle hkt solve showPuzzle [hkt solution] "Output"
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 Tcl, keeping it the same logically?
package require Tcl 8.6 oo::class create HKTSolver { variable grid start limit constructor {puzzle} { set grid $puzzle for {set y 0} {$y < [llength $grid]} {incr y} { for {set x 0} {$x < [llength [lindex $grid $y]]} {incr x} { if {[set cell [lindex $grid $y $x]] == 1} { set start [list $y $x] } incr limit [expr {$cell>=0}] } } if {![info exist start]} { return -code error "no starting position found" } } method moves {} { return { -1 -2 1 -2 -2 -1 2 -1 -2 1 2 1 -1 2 1 2 } } method Moves {g r c} { set valid {} foreach {dr dc} [my moves] { set R [expr {$r + $dr}] set C [expr {$c + $dc}] if {[lindex $g $R $C] == 0} { lappend valid $R $C } } return $valid } method Solve {g r c v} { lset g $r $c [incr v] if {$v >= $limit} {return $g} foreach {r c} [my Moves $g $r $c] { return [my Solve $g $r $c $v] } return -code continue } method solve {} { while {[incr i]==1} { set grid [my Solve $grid {*}$start 0] return } return -code error "solution not possible" } method solution {} {return $grid} } proc parsePuzzle {str} { foreach line [split $str "\n"] { if {[string trim $line] eq ""} continue lappend rows [lmap {- c} [regexp -all -inline {(.)\s?} $line] { string map {" " -1} $c }] } set len [tcl::mathfunc::max {*}[lmap r $rows {llength $r}]] for {set i 0} {$i < [llength $rows]} {incr i} { while {[llength [lindex $rows $i]] < $len} { lset rows $i end+1 -1 } } return $rows } proc showPuzzle {grid name} { foreach row $grid {foreach cell $row {incr c [expr {$cell>=0}]}} set len [string length $c] set u [string repeat "_" $len] puts "$name with $c cells" foreach row $grid { puts [format " %s" [join [lmap c $row { format "%*s" $len [if {$c==-1} list elseif {$c==0} {set u} {set c}] }]]] } } set puzzle [parsePuzzle { 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 }] showPuzzle $puzzle "Input" HKTSolver create hkt $puzzle hkt solve showPuzzle [hkt solution] "Output"
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 Tcl implementation.
package require Tcl 8.6 oo::class create HKTSolver { variable grid start limit constructor {puzzle} { set grid $puzzle for {set y 0} {$y < [llength $grid]} {incr y} { for {set x 0} {$x < [llength [lindex $grid $y]]} {incr x} { if {[set cell [lindex $grid $y $x]] == 1} { set start [list $y $x] } incr limit [expr {$cell>=0}] } } if {![info exist start]} { return -code error "no starting position found" } } method moves {} { return { -1 -2 1 -2 -2 -1 2 -1 -2 1 2 1 -1 2 1 2 } } method Moves {g r c} { set valid {} foreach {dr dc} [my moves] { set R [expr {$r + $dr}] set C [expr {$c + $dc}] if {[lindex $g $R $C] == 0} { lappend valid $R $C } } return $valid } method Solve {g r c v} { lset g $r $c [incr v] if {$v >= $limit} {return $g} foreach {r c} [my Moves $g $r $c] { return [my Solve $g $r $c $v] } return -code continue } method solve {} { while {[incr i]==1} { set grid [my Solve $grid {*}$start 0] return } return -code error "solution not possible" } method solution {} {return $grid} } proc parsePuzzle {str} { foreach line [split $str "\n"] { if {[string trim $line] eq ""} continue lappend rows [lmap {- c} [regexp -all -inline {(.)\s?} $line] { string map {" " -1} $c }] } set len [tcl::mathfunc::max {*}[lmap r $rows {llength $r}]] for {set i 0} {$i < [llength $rows]} {incr i} { while {[llength [lindex $rows $i]] < $len} { lset rows $i end+1 -1 } } return $rows } proc showPuzzle {grid name} { foreach row $grid {foreach cell $row {incr c [expr {$cell>=0}]}} set len [string length $c] set u [string repeat "_" $len] puts "$name with $c cells" foreach row $grid { puts [format " %s" [join [lmap c $row { format "%*s" $len [if {$c==-1} list elseif {$c==0} {set u} {set c}] }]]] } } set puzzle [parsePuzzle { 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 }] showPuzzle $puzzle "Input" HKTSolver create hkt $puzzle hkt solve showPuzzle [hkt solution] "Output"
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) }
Transform the following Ada implementation into C#, maintaining the same output and logic.
generic type Number is private; Zero : Number; One : Number; Two : Number; with function Image (X : Number) return String is <>; with function "+" (X, Y : Number) return Number is <>; with function "/" (X, Y : Number) return Number is <>; with function "mod" (X, Y : Number) return Number is <>; with function ">=" (X, Y : Number) return Boolean is <>; package Prime_Numbers is type Number_List is array (Positive range <>) of Number; procedure Put (List : Number_List); task type Calculate_Factors is entry Start (The_Number : in Number); entry Get_Size (Size : out Natural); entry Get_Result (List : out Number_List); end Calculate_Factors; end Prime_Numbers;
using System; using System.Collections.Generic; using System.Linq; class Program { public static List<int> PrimeFactors(int number) { var primes = new List<int>(); for (int div = 2; div <= number; div++) { while (number % div == 0) { primes.Add(div); number = number / div; } } return primes; } static void Main(string[] args) { int[] n = { 12757923, 12878611, 12757923, 15808973, 15780709, 197622519 }; var factors = n.AsParallel().Select(PrimeFactors).ToList(); var smallestFactors = factors.Select(thisNumbersFactors => thisNumbersFactors.Min()).ToList(); int biggestFactor = smallestFactors.Max(); int whatIndexIsThat = smallestFactors.IndexOf(biggestFactor); Console.WriteLine("{0} has the largest minimum prime factor: {1}", n[whatIndexIsThat], biggestFactor); Console.WriteLine(string.Join(" ", factors[whatIndexIsThat])); } }
Port the following code from Ada to C with equivalent syntax and logic.
generic type Number is private; Zero : Number; One : Number; Two : Number; with function Image (X : Number) return String is <>; with function "+" (X, Y : Number) return Number is <>; with function "/" (X, Y : Number) return Number is <>; with function "mod" (X, Y : Number) return Number is <>; with function ">=" (X, Y : Number) return Boolean is <>; package Prime_Numbers is type Number_List is array (Positive range <>) of Number; procedure Put (List : Number_List); task type Calculate_Factors is entry Start (The_Number : in Number); entry Get_Size (Size : out Natural); entry Get_Result (List : out Number_List); end Calculate_Factors; end Prime_Numbers;
#include <stdio.h> #include <omp.h> int main() { int data[] = {12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519}; int largest, largest_factor = 0; omp_set_num_threads(4); #pragma omp parallel for shared(largest_factor, largest) for (int i = 0; i < 7; i++) { int p, n = data[i]; for (p = 3; p * p <= n && n % p; p += 2); if (p * p > n) p = n; if (p > largest_factor) { largest_factor = p; largest = n; printf("thread %d: found larger: %d of %d\n", omp_get_thread_num(), p, n); } else { printf("thread %d: not larger: %d of %d\n", omp_get_thread_num(), p, n); } } printf("Largest factor: %d of %d\n", largest_factor, largest); return 0; }
Rewrite this program in C++ while keeping its functionality equivalent to the Ada version.
generic type Number is private; Zero : Number; One : Number; Two : Number; with function Image (X : Number) return String is <>; with function "+" (X, Y : Number) return Number is <>; with function "/" (X, Y : Number) return Number is <>; with function "mod" (X, Y : Number) return Number is <>; with function ">=" (X, Y : Number) return Boolean is <>; package Prime_Numbers is type Number_List is array (Positive range <>) of Number; procedure Put (List : Number_List); task type Calculate_Factors is entry Start (The_Number : in Number); entry Get_Size (Size : out Natural); entry Get_Result (List : out Number_List); end Calculate_Factors; end Prime_Numbers;
#include <iostream> #include <iterator> #include <vector> #include <ppl.h> #include <concurrent_vector.h> struct Factors { int number; std::vector<int> primes; }; const int data[] = { 12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519 }; int main() { Concurrency::concurrent_vector<Factors> results; Concurrency::parallel_for_each(std::begin(data), std::end(data), [&](int n) { Factors factors; factors.number = n; for (int f = 2; n > 1; ++f) { while (n % f == 0) { factors.primes.push_back(f); n /= f; } } results.push_back(factors); }); auto max = std::max_element(results.begin(), results.end(), [](const Factors &a, const Factors &b) { return a.primes.front() < b.primes.front(); }); std::for_each(results.begin(), results.end(), [&](const Factors &f) { if (f.primes.front() == max->primes.front()) { std::cout << f.number << " = [ "; std::copy(f.primes.begin(), f.primes.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "]\n"; } }); return 0; }
Rewrite this program in Go while keeping its functionality equivalent to the Ada version.
generic type Number is private; Zero : Number; One : Number; Two : Number; with function Image (X : Number) return String is <>; with function "+" (X, Y : Number) return Number is <>; with function "/" (X, Y : Number) return Number is <>; with function "mod" (X, Y : Number) return Number is <>; with function ">=" (X, Y : Number) return Boolean is <>; package Prime_Numbers is type Number_List is array (Positive range <>) of Number; procedure Put (List : Number_List); task type Calculate_Factors is entry Start (The_Number : in Number); entry Get_Size (Size : out Natural); entry Get_Result (List : out Number_List); end Calculate_Factors; end Prime_Numbers;
package main import ( "fmt" "math/big" ) var numbers = []*big.Int{ big.NewInt(12757923), big.NewInt(12878611), big.NewInt(12878893), big.NewInt(12757923), big.NewInt(15808973), big.NewInt(15780709), } func main() { rs := lmf(numbers) fmt.Println("largest minimal factor:", rs[0].decomp[0]) for _, r := range rs { fmt.Println(r.number, "->", r.decomp) } } type result struct { number *big.Int decomp []*big.Int } func lmf([]*big.Int) []result { rCh := make(chan result) for _, n := range numbers { go decomp(n, rCh) } rs := []result{<-rCh} for i := 1; i < len(numbers); i++ { switch r := <-rCh; r.decomp[0].Cmp(rs[0].decomp[0]) { case 1: rs = rs[:1] rs[0] = r case 0: rs = append(rs, r) } } return rs } func decomp(n *big.Int, rCh chan result) { rCh <- result{n, Primes(new(big.Int).Set(n))} } var ( ZERO = big.NewInt(0) ONE = big.NewInt(1) ) func Primes(n *big.Int) []*big.Int { res := []*big.Int{} mod, div := new(big.Int), new(big.Int) for i := big.NewInt(2); i.Cmp(n) != 1; { div.DivMod(n, i, mod) for mod.Cmp(ZERO) == 0 { res = append(res, new(big.Int).Set(i)) n.Set(div) div.DivMod(n, i, mod) } i.Add(i, ONE) } return res }
Write the same code in Java as shown below in Ada.
generic type Number is private; Zero : Number; One : Number; Two : Number; with function Image (X : Number) return String is <>; with function "+" (X, Y : Number) return Number is <>; with function "/" (X, Y : Number) return Number is <>; with function "mod" (X, Y : Number) return Number is <>; with function ">=" (X, Y : Number) return Boolean is <>; package Prime_Numbers is type Number_List is array (Positive range <>) of Number; procedure Put (List : Number_List); task type Calculate_Factors is entry Start (The_Number : in Number); entry Get_Size (Size : out Natural); entry Get_Result (List : out Number_List); end Calculate_Factors; end Prime_Numbers;
import static java.lang.System.out; import static java.util.Arrays.stream; import static java.util.Comparator.comparing; public interface ParallelCalculations { public static final long[] NUMBERS = { 12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519 }; public static void main(String... arguments) { stream(NUMBERS) .unordered() .parallel() .mapToObj(ParallelCalculations::minimalPrimeFactor) .max(comparing(a -> a[0])) .ifPresent(res -> out.printf( "%d has the largest minimum prime factor: %d%n", res[1], res[0] )); } public static long[] minimalPrimeFactor(long n) { for (long i = 2; n >= i * i; i++) { if (n % i == 0) { return new long[]{i, n}; } } return new long[]{n, n}; } }
Write a version of this Ada function in Python with identical behavior.
generic type Number is private; Zero : Number; One : Number; Two : Number; with function Image (X : Number) return String is <>; with function "+" (X, Y : Number) return Number is <>; with function "/" (X, Y : Number) return Number is <>; with function "mod" (X, Y : Number) return Number is <>; with function ">=" (X, Y : Number) return Boolean is <>; package Prime_Numbers is type Number_List is array (Positive range <>) of Number; procedure Put (List : Number_List); task type Calculate_Factors is entry Start (The_Number : in Number); entry Get_Size (Size : out Natural); entry Get_Result (List : out Number_List); end Calculate_Factors; end Prime_Numbers;
from concurrent import futures from math import floor, sqrt NUMBERS = [ 112272537195293, 112582718962171, 112272537095293, 115280098190773, 115797840077099, 1099726829285419] def lowest_factor(n, _start=3): if n % 2 == 0: return 2 search_max = int(floor(sqrt(n))) + 1 for i in range(_start, search_max, 2): if n % i == 0: return i return n def prime_factors(n, lowest): pf = [] while n > 1: pf.append(lowest) n //= lowest lowest = lowest_factor(n, max(lowest, 3)) return pf def prime_factors_of_number_with_lowest_prime_factor(NUMBERS): with futures.ProcessPoolExecutor() as executor: low_factor, number = max( (l, f) for l, f in zip(executor.map(lowest_factor, NUMBERS), NUMBERS) ) all_factors = prime_factors(number, low_factor) return number, all_factors def main(): print('For these numbers:') print('\n '.join(str(p) for p in NUMBERS)) number, all_factors = prime_factors_of_number_with_lowest_prime_factor(NUMBERS) print(' The one with the largest minimum prime factor is {}:'.format(number)) print(' All its prime factors in order are: {}'.format(all_factors)) if __name__ == '__main__': main()
Translate the given Clojure code snippet into C without altering its behavior.
(use '[clojure.contrib.lazy-seqs :only [primes]]) (defn lpf [n] [n (or (last (for [p (take-while #(<= (* % %) n) primes) :when (zero? (rem n p))] p)) 1)]) (->> (range 2 100000) (pmap lpf) (apply max-key second) println time)
#include <stdio.h> #include <omp.h> int main() { int data[] = {12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519}; int largest, largest_factor = 0; omp_set_num_threads(4); #pragma omp parallel for shared(largest_factor, largest) for (int i = 0; i < 7; i++) { int p, n = data[i]; for (p = 3; p * p <= n && n % p; p += 2); if (p * p > n) p = n; if (p > largest_factor) { largest_factor = p; largest = n; printf("thread %d: found larger: %d of %d\n", omp_get_thread_num(), p, n); } else { printf("thread %d: not larger: %d of %d\n", omp_get_thread_num(), p, n); } } printf("Largest factor: %d of %d\n", largest_factor, largest); return 0; }
Convert the following code from Clojure to C#, ensuring the logic remains intact.
(use '[clojure.contrib.lazy-seqs :only [primes]]) (defn lpf [n] [n (or (last (for [p (take-while #(<= (* % %) n) primes) :when (zero? (rem n p))] p)) 1)]) (->> (range 2 100000) (pmap lpf) (apply max-key second) println time)
using System; using System.Collections.Generic; using System.Linq; class Program { public static List<int> PrimeFactors(int number) { var primes = new List<int>(); for (int div = 2; div <= number; div++) { while (number % div == 0) { primes.Add(div); number = number / div; } } return primes; } static void Main(string[] args) { int[] n = { 12757923, 12878611, 12757923, 15808973, 15780709, 197622519 }; var factors = n.AsParallel().Select(PrimeFactors).ToList(); var smallestFactors = factors.Select(thisNumbersFactors => thisNumbersFactors.Min()).ToList(); int biggestFactor = smallestFactors.Max(); int whatIndexIsThat = smallestFactors.IndexOf(biggestFactor); Console.WriteLine("{0} has the largest minimum prime factor: {1}", n[whatIndexIsThat], biggestFactor); Console.WriteLine(string.Join(" ", factors[whatIndexIsThat])); } }
Convert this Clojure snippet to C++ and keep its semantics consistent.
(use '[clojure.contrib.lazy-seqs :only [primes]]) (defn lpf [n] [n (or (last (for [p (take-while #(<= (* % %) n) primes) :when (zero? (rem n p))] p)) 1)]) (->> (range 2 100000) (pmap lpf) (apply max-key second) println time)
#include <iostream> #include <iterator> #include <vector> #include <ppl.h> #include <concurrent_vector.h> struct Factors { int number; std::vector<int> primes; }; const int data[] = { 12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519 }; int main() { Concurrency::concurrent_vector<Factors> results; Concurrency::parallel_for_each(std::begin(data), std::end(data), [&](int n) { Factors factors; factors.number = n; for (int f = 2; n > 1; ++f) { while (n % f == 0) { factors.primes.push_back(f); n /= f; } } results.push_back(factors); }); auto max = std::max_element(results.begin(), results.end(), [](const Factors &a, const Factors &b) { return a.primes.front() < b.primes.front(); }); std::for_each(results.begin(), results.end(), [&](const Factors &f) { if (f.primes.front() == max->primes.front()) { std::cout << f.number << " = [ "; std::copy(f.primes.begin(), f.primes.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "]\n"; } }); return 0; }
Rewrite the snippet below in Java so it works the same as the original Clojure code.
(use '[clojure.contrib.lazy-seqs :only [primes]]) (defn lpf [n] [n (or (last (for [p (take-while #(<= (* % %) n) primes) :when (zero? (rem n p))] p)) 1)]) (->> (range 2 100000) (pmap lpf) (apply max-key second) println time)
import static java.lang.System.out; import static java.util.Arrays.stream; import static java.util.Comparator.comparing; public interface ParallelCalculations { public static final long[] NUMBERS = { 12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519 }; public static void main(String... arguments) { stream(NUMBERS) .unordered() .parallel() .mapToObj(ParallelCalculations::minimalPrimeFactor) .max(comparing(a -> a[0])) .ifPresent(res -> out.printf( "%d has the largest minimum prime factor: %d%n", res[1], res[0] )); } public static long[] minimalPrimeFactor(long n) { for (long i = 2; n >= i * i; i++) { if (n % i == 0) { return new long[]{i, n}; } } return new long[]{n, n}; } }
Produce a language-to-language conversion: from Clojure to Python, same semantics.
(use '[clojure.contrib.lazy-seqs :only [primes]]) (defn lpf [n] [n (or (last (for [p (take-while #(<= (* % %) n) primes) :when (zero? (rem n p))] p)) 1)]) (->> (range 2 100000) (pmap lpf) (apply max-key second) println time)
from concurrent import futures from math import floor, sqrt NUMBERS = [ 112272537195293, 112582718962171, 112272537095293, 115280098190773, 115797840077099, 1099726829285419] def lowest_factor(n, _start=3): if n % 2 == 0: return 2 search_max = int(floor(sqrt(n))) + 1 for i in range(_start, search_max, 2): if n % i == 0: return i return n def prime_factors(n, lowest): pf = [] while n > 1: pf.append(lowest) n //= lowest lowest = lowest_factor(n, max(lowest, 3)) return pf def prime_factors_of_number_with_lowest_prime_factor(NUMBERS): with futures.ProcessPoolExecutor() as executor: low_factor, number = max( (l, f) for l, f in zip(executor.map(lowest_factor, NUMBERS), NUMBERS) ) all_factors = prime_factors(number, low_factor) return number, all_factors def main(): print('For these numbers:') print('\n '.join(str(p) for p in NUMBERS)) number, all_factors = prime_factors_of_number_with_lowest_prime_factor(NUMBERS) print(' The one with the largest minimum prime factor is {}:'.format(number)) print(' All its prime factors in order are: {}'.format(all_factors)) if __name__ == '__main__': main()
Translate the given Clojure code snippet into Go without altering its behavior.
(use '[clojure.contrib.lazy-seqs :only [primes]]) (defn lpf [n] [n (or (last (for [p (take-while #(<= (* % %) n) primes) :when (zero? (rem n p))] p)) 1)]) (->> (range 2 100000) (pmap lpf) (apply max-key second) println time)
package main import ( "fmt" "math/big" ) var numbers = []*big.Int{ big.NewInt(12757923), big.NewInt(12878611), big.NewInt(12878893), big.NewInt(12757923), big.NewInt(15808973), big.NewInt(15780709), } func main() { rs := lmf(numbers) fmt.Println("largest minimal factor:", rs[0].decomp[0]) for _, r := range rs { fmt.Println(r.number, "->", r.decomp) } } type result struct { number *big.Int decomp []*big.Int } func lmf([]*big.Int) []result { rCh := make(chan result) for _, n := range numbers { go decomp(n, rCh) } rs := []result{<-rCh} for i := 1; i < len(numbers); i++ { switch r := <-rCh; r.decomp[0].Cmp(rs[0].decomp[0]) { case 1: rs = rs[:1] rs[0] = r case 0: rs = append(rs, r) } } return rs } func decomp(n *big.Int, rCh chan result) { rCh <- result{n, Primes(new(big.Int).Set(n))} } var ( ZERO = big.NewInt(0) ONE = big.NewInt(1) ) func Primes(n *big.Int) []*big.Int { res := []*big.Int{} mod, div := new(big.Int), new(big.Int) for i := big.NewInt(2); i.Cmp(n) != 1; { div.DivMod(n, i, mod) for mod.Cmp(ZERO) == 0 { res = append(res, new(big.Int).Set(i)) n.Set(div) div.DivMod(n, i, mod) } i.Add(i, ONE) } return res }
Convert this Common_Lisp snippet to C and keep its semantics consistent.
(ql:quickload '(lparallel)) (setf lparallel:*kernel* (lparallel:make-kernel 4)) (defun factor (n &optional (acc '())) (when (> n 1) (loop with max-d = (isqrt n) for d = 2 then (if (evenp d) (1+ d) (+ d 2)) do (cond ((> d max-d) (return (cons (list n 1) acc))) ((zerop (rem n d)) (return (factor (truncate n d) (if (eq d (caar acc)) (cons (list (caar acc) (1+ (cadar acc))) (cdr acc)) (cons (list d 1) acc))))))))) (defun max-minimum-factor (numbers) (lparallel:pmap-reduce (lambda (n) (cons n (apply #'min (mapcar #'car (factor n))))) (lambda (a b) (if (> (cdr a) (cdr b)) a b)) numbers)) (defun print-max-factor (pair) (format t "~a has the largest minimum factor ~a~%" (car pair) (cdr pair)))
#include <stdio.h> #include <omp.h> int main() { int data[] = {12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519}; int largest, largest_factor = 0; omp_set_num_threads(4); #pragma omp parallel for shared(largest_factor, largest) for (int i = 0; i < 7; i++) { int p, n = data[i]; for (p = 3; p * p <= n && n % p; p += 2); if (p * p > n) p = n; if (p > largest_factor) { largest_factor = p; largest = n; printf("thread %d: found larger: %d of %d\n", omp_get_thread_num(), p, n); } else { printf("thread %d: not larger: %d of %d\n", omp_get_thread_num(), p, n); } } printf("Largest factor: %d of %d\n", largest_factor, largest); return 0; }
Change the programming language of this snippet from Common_Lisp to C# without modifying what it does.
(ql:quickload '(lparallel)) (setf lparallel:*kernel* (lparallel:make-kernel 4)) (defun factor (n &optional (acc '())) (when (> n 1) (loop with max-d = (isqrt n) for d = 2 then (if (evenp d) (1+ d) (+ d 2)) do (cond ((> d max-d) (return (cons (list n 1) acc))) ((zerop (rem n d)) (return (factor (truncate n d) (if (eq d (caar acc)) (cons (list (caar acc) (1+ (cadar acc))) (cdr acc)) (cons (list d 1) acc))))))))) (defun max-minimum-factor (numbers) (lparallel:pmap-reduce (lambda (n) (cons n (apply #'min (mapcar #'car (factor n))))) (lambda (a b) (if (> (cdr a) (cdr b)) a b)) numbers)) (defun print-max-factor (pair) (format t "~a has the largest minimum factor ~a~%" (car pair) (cdr pair)))
using System; using System.Collections.Generic; using System.Linq; class Program { public static List<int> PrimeFactors(int number) { var primes = new List<int>(); for (int div = 2; div <= number; div++) { while (number % div == 0) { primes.Add(div); number = number / div; } } return primes; } static void Main(string[] args) { int[] n = { 12757923, 12878611, 12757923, 15808973, 15780709, 197622519 }; var factors = n.AsParallel().Select(PrimeFactors).ToList(); var smallestFactors = factors.Select(thisNumbersFactors => thisNumbersFactors.Min()).ToList(); int biggestFactor = smallestFactors.Max(); int whatIndexIsThat = smallestFactors.IndexOf(biggestFactor); Console.WriteLine("{0} has the largest minimum prime factor: {1}", n[whatIndexIsThat], biggestFactor); Console.WriteLine(string.Join(" ", factors[whatIndexIsThat])); } }
Can you help me rewrite this code in C++ instead of Common_Lisp, keeping it the same logically?
(ql:quickload '(lparallel)) (setf lparallel:*kernel* (lparallel:make-kernel 4)) (defun factor (n &optional (acc '())) (when (> n 1) (loop with max-d = (isqrt n) for d = 2 then (if (evenp d) (1+ d) (+ d 2)) do (cond ((> d max-d) (return (cons (list n 1) acc))) ((zerop (rem n d)) (return (factor (truncate n d) (if (eq d (caar acc)) (cons (list (caar acc) (1+ (cadar acc))) (cdr acc)) (cons (list d 1) acc))))))))) (defun max-minimum-factor (numbers) (lparallel:pmap-reduce (lambda (n) (cons n (apply #'min (mapcar #'car (factor n))))) (lambda (a b) (if (> (cdr a) (cdr b)) a b)) numbers)) (defun print-max-factor (pair) (format t "~a has the largest minimum factor ~a~%" (car pair) (cdr pair)))
#include <iostream> #include <iterator> #include <vector> #include <ppl.h> #include <concurrent_vector.h> struct Factors { int number; std::vector<int> primes; }; const int data[] = { 12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519 }; int main() { Concurrency::concurrent_vector<Factors> results; Concurrency::parallel_for_each(std::begin(data), std::end(data), [&](int n) { Factors factors; factors.number = n; for (int f = 2; n > 1; ++f) { while (n % f == 0) { factors.primes.push_back(f); n /= f; } } results.push_back(factors); }); auto max = std::max_element(results.begin(), results.end(), [](const Factors &a, const Factors &b) { return a.primes.front() < b.primes.front(); }); std::for_each(results.begin(), results.end(), [&](const Factors &f) { if (f.primes.front() == max->primes.front()) { std::cout << f.number << " = [ "; std::copy(f.primes.begin(), f.primes.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "]\n"; } }); return 0; }
Port the provided Common_Lisp code into Java while preserving the original functionality.
(ql:quickload '(lparallel)) (setf lparallel:*kernel* (lparallel:make-kernel 4)) (defun factor (n &optional (acc '())) (when (> n 1) (loop with max-d = (isqrt n) for d = 2 then (if (evenp d) (1+ d) (+ d 2)) do (cond ((> d max-d) (return (cons (list n 1) acc))) ((zerop (rem n d)) (return (factor (truncate n d) (if (eq d (caar acc)) (cons (list (caar acc) (1+ (cadar acc))) (cdr acc)) (cons (list d 1) acc))))))))) (defun max-minimum-factor (numbers) (lparallel:pmap-reduce (lambda (n) (cons n (apply #'min (mapcar #'car (factor n))))) (lambda (a b) (if (> (cdr a) (cdr b)) a b)) numbers)) (defun print-max-factor (pair) (format t "~a has the largest minimum factor ~a~%" (car pair) (cdr pair)))
import static java.lang.System.out; import static java.util.Arrays.stream; import static java.util.Comparator.comparing; public interface ParallelCalculations { public static final long[] NUMBERS = { 12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519 }; public static void main(String... arguments) { stream(NUMBERS) .unordered() .parallel() .mapToObj(ParallelCalculations::minimalPrimeFactor) .max(comparing(a -> a[0])) .ifPresent(res -> out.printf( "%d has the largest minimum prime factor: %d%n", res[1], res[0] )); } public static long[] minimalPrimeFactor(long n) { for (long i = 2; n >= i * i; i++) { if (n % i == 0) { return new long[]{i, n}; } } return new long[]{n, n}; } }
Transform the following Common_Lisp implementation into Python, maintaining the same output and logic.
(ql:quickload '(lparallel)) (setf lparallel:*kernel* (lparallel:make-kernel 4)) (defun factor (n &optional (acc '())) (when (> n 1) (loop with max-d = (isqrt n) for d = 2 then (if (evenp d) (1+ d) (+ d 2)) do (cond ((> d max-d) (return (cons (list n 1) acc))) ((zerop (rem n d)) (return (factor (truncate n d) (if (eq d (caar acc)) (cons (list (caar acc) (1+ (cadar acc))) (cdr acc)) (cons (list d 1) acc))))))))) (defun max-minimum-factor (numbers) (lparallel:pmap-reduce (lambda (n) (cons n (apply #'min (mapcar #'car (factor n))))) (lambda (a b) (if (> (cdr a) (cdr b)) a b)) numbers)) (defun print-max-factor (pair) (format t "~a has the largest minimum factor ~a~%" (car pair) (cdr pair)))
from concurrent import futures from math import floor, sqrt NUMBERS = [ 112272537195293, 112582718962171, 112272537095293, 115280098190773, 115797840077099, 1099726829285419] def lowest_factor(n, _start=3): if n % 2 == 0: return 2 search_max = int(floor(sqrt(n))) + 1 for i in range(_start, search_max, 2): if n % i == 0: return i return n def prime_factors(n, lowest): pf = [] while n > 1: pf.append(lowest) n //= lowest lowest = lowest_factor(n, max(lowest, 3)) return pf def prime_factors_of_number_with_lowest_prime_factor(NUMBERS): with futures.ProcessPoolExecutor() as executor: low_factor, number = max( (l, f) for l, f in zip(executor.map(lowest_factor, NUMBERS), NUMBERS) ) all_factors = prime_factors(number, low_factor) return number, all_factors def main(): print('For these numbers:') print('\n '.join(str(p) for p in NUMBERS)) number, all_factors = prime_factors_of_number_with_lowest_prime_factor(NUMBERS) print(' The one with the largest minimum prime factor is {}:'.format(number)) print(' All its prime factors in order are: {}'.format(all_factors)) if __name__ == '__main__': main()
Preserve the algorithm and functionality while converting the code from Common_Lisp to Go.
(ql:quickload '(lparallel)) (setf lparallel:*kernel* (lparallel:make-kernel 4)) (defun factor (n &optional (acc '())) (when (> n 1) (loop with max-d = (isqrt n) for d = 2 then (if (evenp d) (1+ d) (+ d 2)) do (cond ((> d max-d) (return (cons (list n 1) acc))) ((zerop (rem n d)) (return (factor (truncate n d) (if (eq d (caar acc)) (cons (list (caar acc) (1+ (cadar acc))) (cdr acc)) (cons (list d 1) acc))))))))) (defun max-minimum-factor (numbers) (lparallel:pmap-reduce (lambda (n) (cons n (apply #'min (mapcar #'car (factor n))))) (lambda (a b) (if (> (cdr a) (cdr b)) a b)) numbers)) (defun print-max-factor (pair) (format t "~a has the largest minimum factor ~a~%" (car pair) (cdr pair)))
package main import ( "fmt" "math/big" ) var numbers = []*big.Int{ big.NewInt(12757923), big.NewInt(12878611), big.NewInt(12878893), big.NewInt(12757923), big.NewInt(15808973), big.NewInt(15780709), } func main() { rs := lmf(numbers) fmt.Println("largest minimal factor:", rs[0].decomp[0]) for _, r := range rs { fmt.Println(r.number, "->", r.decomp) } } type result struct { number *big.Int decomp []*big.Int } func lmf([]*big.Int) []result { rCh := make(chan result) for _, n := range numbers { go decomp(n, rCh) } rs := []result{<-rCh} for i := 1; i < len(numbers); i++ { switch r := <-rCh; r.decomp[0].Cmp(rs[0].decomp[0]) { case 1: rs = rs[:1] rs[0] = r case 0: rs = append(rs, r) } } return rs } func decomp(n *big.Int, rCh chan result) { rCh <- result{n, Primes(new(big.Int).Set(n))} } var ( ZERO = big.NewInt(0) ONE = big.NewInt(1) ) func Primes(n *big.Int) []*big.Int { res := []*big.Int{} mod, div := new(big.Int), new(big.Int) for i := big.NewInt(2); i.Cmp(n) != 1; { div.DivMod(n, i, mod) for mod.Cmp(ZERO) == 0 { res = append(res, new(big.Int).Set(i)) n.Set(div) div.DivMod(n, i, mod) } i.Add(i, ONE) } return res }
Rewrite this program in C while keeping its functionality equivalent to the D version.
ulong[] decompose(ulong n) pure nothrow { typeof(return) result; for (ulong i = 2; n >= i * i; i++) for (; n % i == 0; n /= i) result ~= i; if (n != 1) result ~= n; return result; } void main() { import std.stdio, std.algorithm, std.parallelism, std.typecons; immutable ulong[] data = [ 2UL^^59-1, 2UL^^59-1, 2UL^^59-1, 112_272_537_195_293UL, 115_284_584_522_153, 115_280_098_190_773, 115_797_840_077_099, 112_582_718_962_171, 112_272_537_095_293, 1_099_726_829_285_419]; static genPair(ulong n) pure { return tuple(decompose(n), n); } auto factors = taskPool.amap!genPair(data); auto pairs = factors.map!(p => tuple(p[0].reduce!min, p[1])); writeln("N. with largest min factor: ", pairs.reduce!max[1]); }
#include <stdio.h> #include <omp.h> int main() { int data[] = {12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519}; int largest, largest_factor = 0; omp_set_num_threads(4); #pragma omp parallel for shared(largest_factor, largest) for (int i = 0; i < 7; i++) { int p, n = data[i]; for (p = 3; p * p <= n && n % p; p += 2); if (p * p > n) p = n; if (p > largest_factor) { largest_factor = p; largest = n; printf("thread %d: found larger: %d of %d\n", omp_get_thread_num(), p, n); } else { printf("thread %d: not larger: %d of %d\n", omp_get_thread_num(), p, n); } } printf("Largest factor: %d of %d\n", largest_factor, largest); return 0; }
Maintain the same structure and functionality when rewriting this code in C#.
ulong[] decompose(ulong n) pure nothrow { typeof(return) result; for (ulong i = 2; n >= i * i; i++) for (; n % i == 0; n /= i) result ~= i; if (n != 1) result ~= n; return result; } void main() { import std.stdio, std.algorithm, std.parallelism, std.typecons; immutable ulong[] data = [ 2UL^^59-1, 2UL^^59-1, 2UL^^59-1, 112_272_537_195_293UL, 115_284_584_522_153, 115_280_098_190_773, 115_797_840_077_099, 112_582_718_962_171, 112_272_537_095_293, 1_099_726_829_285_419]; static genPair(ulong n) pure { return tuple(decompose(n), n); } auto factors = taskPool.amap!genPair(data); auto pairs = factors.map!(p => tuple(p[0].reduce!min, p[1])); writeln("N. with largest min factor: ", pairs.reduce!max[1]); }
using System; using System.Collections.Generic; using System.Linq; class Program { public static List<int> PrimeFactors(int number) { var primes = new List<int>(); for (int div = 2; div <= number; div++) { while (number % div == 0) { primes.Add(div); number = number / div; } } return primes; } static void Main(string[] args) { int[] n = { 12757923, 12878611, 12757923, 15808973, 15780709, 197622519 }; var factors = n.AsParallel().Select(PrimeFactors).ToList(); var smallestFactors = factors.Select(thisNumbersFactors => thisNumbersFactors.Min()).ToList(); int biggestFactor = smallestFactors.Max(); int whatIndexIsThat = smallestFactors.IndexOf(biggestFactor); Console.WriteLine("{0} has the largest minimum prime factor: {1}", n[whatIndexIsThat], biggestFactor); Console.WriteLine(string.Join(" ", factors[whatIndexIsThat])); } }
Translate the given D code snippet into C++ without altering its behavior.
ulong[] decompose(ulong n) pure nothrow { typeof(return) result; for (ulong i = 2; n >= i * i; i++) for (; n % i == 0; n /= i) result ~= i; if (n != 1) result ~= n; return result; } void main() { import std.stdio, std.algorithm, std.parallelism, std.typecons; immutable ulong[] data = [ 2UL^^59-1, 2UL^^59-1, 2UL^^59-1, 112_272_537_195_293UL, 115_284_584_522_153, 115_280_098_190_773, 115_797_840_077_099, 112_582_718_962_171, 112_272_537_095_293, 1_099_726_829_285_419]; static genPair(ulong n) pure { return tuple(decompose(n), n); } auto factors = taskPool.amap!genPair(data); auto pairs = factors.map!(p => tuple(p[0].reduce!min, p[1])); writeln("N. with largest min factor: ", pairs.reduce!max[1]); }
#include <iostream> #include <iterator> #include <vector> #include <ppl.h> #include <concurrent_vector.h> struct Factors { int number; std::vector<int> primes; }; const int data[] = { 12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519 }; int main() { Concurrency::concurrent_vector<Factors> results; Concurrency::parallel_for_each(std::begin(data), std::end(data), [&](int n) { Factors factors; factors.number = n; for (int f = 2; n > 1; ++f) { while (n % f == 0) { factors.primes.push_back(f); n /= f; } } results.push_back(factors); }); auto max = std::max_element(results.begin(), results.end(), [](const Factors &a, const Factors &b) { return a.primes.front() < b.primes.front(); }); std::for_each(results.begin(), results.end(), [&](const Factors &f) { if (f.primes.front() == max->primes.front()) { std::cout << f.number << " = [ "; std::copy(f.primes.begin(), f.primes.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "]\n"; } }); return 0; }
Convert this D block to Java, preserving its control flow and logic.
ulong[] decompose(ulong n) pure nothrow { typeof(return) result; for (ulong i = 2; n >= i * i; i++) for (; n % i == 0; n /= i) result ~= i; if (n != 1) result ~= n; return result; } void main() { import std.stdio, std.algorithm, std.parallelism, std.typecons; immutable ulong[] data = [ 2UL^^59-1, 2UL^^59-1, 2UL^^59-1, 112_272_537_195_293UL, 115_284_584_522_153, 115_280_098_190_773, 115_797_840_077_099, 112_582_718_962_171, 112_272_537_095_293, 1_099_726_829_285_419]; static genPair(ulong n) pure { return tuple(decompose(n), n); } auto factors = taskPool.amap!genPair(data); auto pairs = factors.map!(p => tuple(p[0].reduce!min, p[1])); writeln("N. with largest min factor: ", pairs.reduce!max[1]); }
import static java.lang.System.out; import static java.util.Arrays.stream; import static java.util.Comparator.comparing; public interface ParallelCalculations { public static final long[] NUMBERS = { 12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519 }; public static void main(String... arguments) { stream(NUMBERS) .unordered() .parallel() .mapToObj(ParallelCalculations::minimalPrimeFactor) .max(comparing(a -> a[0])) .ifPresent(res -> out.printf( "%d has the largest minimum prime factor: %d%n", res[1], res[0] )); } public static long[] minimalPrimeFactor(long n) { for (long i = 2; n >= i * i; i++) { if (n % i == 0) { return new long[]{i, n}; } } return new long[]{n, n}; } }
Keep all operations the same but rewrite the snippet in Python.
ulong[] decompose(ulong n) pure nothrow { typeof(return) result; for (ulong i = 2; n >= i * i; i++) for (; n % i == 0; n /= i) result ~= i; if (n != 1) result ~= n; return result; } void main() { import std.stdio, std.algorithm, std.parallelism, std.typecons; immutable ulong[] data = [ 2UL^^59-1, 2UL^^59-1, 2UL^^59-1, 112_272_537_195_293UL, 115_284_584_522_153, 115_280_098_190_773, 115_797_840_077_099, 112_582_718_962_171, 112_272_537_095_293, 1_099_726_829_285_419]; static genPair(ulong n) pure { return tuple(decompose(n), n); } auto factors = taskPool.amap!genPair(data); auto pairs = factors.map!(p => tuple(p[0].reduce!min, p[1])); writeln("N. with largest min factor: ", pairs.reduce!max[1]); }
from concurrent import futures from math import floor, sqrt NUMBERS = [ 112272537195293, 112582718962171, 112272537095293, 115280098190773, 115797840077099, 1099726829285419] def lowest_factor(n, _start=3): if n % 2 == 0: return 2 search_max = int(floor(sqrt(n))) + 1 for i in range(_start, search_max, 2): if n % i == 0: return i return n def prime_factors(n, lowest): pf = [] while n > 1: pf.append(lowest) n //= lowest lowest = lowest_factor(n, max(lowest, 3)) return pf def prime_factors_of_number_with_lowest_prime_factor(NUMBERS): with futures.ProcessPoolExecutor() as executor: low_factor, number = max( (l, f) for l, f in zip(executor.map(lowest_factor, NUMBERS), NUMBERS) ) all_factors = prime_factors(number, low_factor) return number, all_factors def main(): print('For these numbers:') print('\n '.join(str(p) for p in NUMBERS)) number, all_factors = prime_factors_of_number_with_lowest_prime_factor(NUMBERS) print(' The one with the largest minimum prime factor is {}:'.format(number)) print(' All its prime factors in order are: {}'.format(all_factors)) if __name__ == '__main__': main()
Change the following D code into Go without altering its purpose.
ulong[] decompose(ulong n) pure nothrow { typeof(return) result; for (ulong i = 2; n >= i * i; i++) for (; n % i == 0; n /= i) result ~= i; if (n != 1) result ~= n; return result; } void main() { import std.stdio, std.algorithm, std.parallelism, std.typecons; immutable ulong[] data = [ 2UL^^59-1, 2UL^^59-1, 2UL^^59-1, 112_272_537_195_293UL, 115_284_584_522_153, 115_280_098_190_773, 115_797_840_077_099, 112_582_718_962_171, 112_272_537_095_293, 1_099_726_829_285_419]; static genPair(ulong n) pure { return tuple(decompose(n), n); } auto factors = taskPool.amap!genPair(data); auto pairs = factors.map!(p => tuple(p[0].reduce!min, p[1])); writeln("N. with largest min factor: ", pairs.reduce!max[1]); }
package main import ( "fmt" "math/big" ) var numbers = []*big.Int{ big.NewInt(12757923), big.NewInt(12878611), big.NewInt(12878893), big.NewInt(12757923), big.NewInt(15808973), big.NewInt(15780709), } func main() { rs := lmf(numbers) fmt.Println("largest minimal factor:", rs[0].decomp[0]) for _, r := range rs { fmt.Println(r.number, "->", r.decomp) } } type result struct { number *big.Int decomp []*big.Int } func lmf([]*big.Int) []result { rCh := make(chan result) for _, n := range numbers { go decomp(n, rCh) } rs := []result{<-rCh} for i := 1; i < len(numbers); i++ { switch r := <-rCh; r.decomp[0].Cmp(rs[0].decomp[0]) { case 1: rs = rs[:1] rs[0] = r case 0: rs = append(rs, r) } } return rs } func decomp(n *big.Int, rCh chan result) { rCh <- result{n, Primes(new(big.Int).Set(n))} } var ( ZERO = big.NewInt(0) ONE = big.NewInt(1) ) func Primes(n *big.Int) []*big.Int { res := []*big.Int{} mod, div := new(big.Int), new(big.Int) for i := big.NewInt(2); i.Cmp(n) != 1; { div.DivMod(n, i, mod) for mod.Cmp(ZERO) == 0 { res = append(res, new(big.Int).Set(i)) n.Set(div) div.DivMod(n, i, mod) } i.Add(i, ONE) } return res }
Convert this Delphi block to C, preserving its control flow and logic.
program Parallel_calculations; uses System.SysUtils, System.Threading, Velthuis.BigIntegers; function IsPrime(n: BigInteger): Boolean; var i: BigInteger; begin if n <= 1 then exit(False); i := 2; while i < BigInteger.Sqrt(n) do begin if n mod i = 0 then exit(False); inc(i); end; Result := True; end; function GetPrimes(n: BigInteger): TArray<BigInteger>; var divisor, next, rest: BigInteger; begin divisor := 2; next := 3; rest := n; while (rest <> 1) do begin while (rest mod divisor = 0) do begin SetLength(Result, Length(Result) + 1); Result[High(Result)] := divisor; rest := rest div divisor; end; divisor := next; next := next + 2; end; end; function Min(l: TArray<BigInteger>): BigInteger; begin if Length(l) = 0 then exit(0); Result := l[0]; for var v in l do if v < result then Result := v; end; const n: array of Uint64 = [12757923, 12878611, 12757923, 15808973, 15780709, 197622519]; var m: BigInteger; len, j, i: Uint64; l: TArray<TArray<BigInteger>>; begin j := 0; m := 0; len := length(n); SetLength(l, len); TParallel.for (0, len - 1, procedure(i: Integer) begin l[i] := getPrimes(n[i]); end); for i := 0 to len - 1 do begin var _min := Min(l[i]); if _min > m then begin m := _min; j := i; end; end; writeln('Number ', n[j].ToString, ' has largest minimal factor:'); for var v in l[j] do write(' ', v.ToString); readln; end.
#include <stdio.h> #include <omp.h> int main() { int data[] = {12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519}; int largest, largest_factor = 0; omp_set_num_threads(4); #pragma omp parallel for shared(largest_factor, largest) for (int i = 0; i < 7; i++) { int p, n = data[i]; for (p = 3; p * p <= n && n % p; p += 2); if (p * p > n) p = n; if (p > largest_factor) { largest_factor = p; largest = n; printf("thread %d: found larger: %d of %d\n", omp_get_thread_num(), p, n); } else { printf("thread %d: not larger: %d of %d\n", omp_get_thread_num(), p, n); } } printf("Largest factor: %d of %d\n", largest_factor, largest); return 0; }
Generate a C# translation of this Delphi snippet without changing its computational steps.
program Parallel_calculations; uses System.SysUtils, System.Threading, Velthuis.BigIntegers; function IsPrime(n: BigInteger): Boolean; var i: BigInteger; begin if n <= 1 then exit(False); i := 2; while i < BigInteger.Sqrt(n) do begin if n mod i = 0 then exit(False); inc(i); end; Result := True; end; function GetPrimes(n: BigInteger): TArray<BigInteger>; var divisor, next, rest: BigInteger; begin divisor := 2; next := 3; rest := n; while (rest <> 1) do begin while (rest mod divisor = 0) do begin SetLength(Result, Length(Result) + 1); Result[High(Result)] := divisor; rest := rest div divisor; end; divisor := next; next := next + 2; end; end; function Min(l: TArray<BigInteger>): BigInteger; begin if Length(l) = 0 then exit(0); Result := l[0]; for var v in l do if v < result then Result := v; end; const n: array of Uint64 = [12757923, 12878611, 12757923, 15808973, 15780709, 197622519]; var m: BigInteger; len, j, i: Uint64; l: TArray<TArray<BigInteger>>; begin j := 0; m := 0; len := length(n); SetLength(l, len); TParallel.for (0, len - 1, procedure(i: Integer) begin l[i] := getPrimes(n[i]); end); for i := 0 to len - 1 do begin var _min := Min(l[i]); if _min > m then begin m := _min; j := i; end; end; writeln('Number ', n[j].ToString, ' has largest minimal factor:'); for var v in l[j] do write(' ', v.ToString); readln; end.
using System; using System.Collections.Generic; using System.Linq; class Program { public static List<int> PrimeFactors(int number) { var primes = new List<int>(); for (int div = 2; div <= number; div++) { while (number % div == 0) { primes.Add(div); number = number / div; } } return primes; } static void Main(string[] args) { int[] n = { 12757923, 12878611, 12757923, 15808973, 15780709, 197622519 }; var factors = n.AsParallel().Select(PrimeFactors).ToList(); var smallestFactors = factors.Select(thisNumbersFactors => thisNumbersFactors.Min()).ToList(); int biggestFactor = smallestFactors.Max(); int whatIndexIsThat = smallestFactors.IndexOf(biggestFactor); Console.WriteLine("{0} has the largest minimum prime factor: {1}", n[whatIndexIsThat], biggestFactor); Console.WriteLine(string.Join(" ", factors[whatIndexIsThat])); } }
Preserve the algorithm and functionality while converting the code from Delphi to C++.
program Parallel_calculations; uses System.SysUtils, System.Threading, Velthuis.BigIntegers; function IsPrime(n: BigInteger): Boolean; var i: BigInteger; begin if n <= 1 then exit(False); i := 2; while i < BigInteger.Sqrt(n) do begin if n mod i = 0 then exit(False); inc(i); end; Result := True; end; function GetPrimes(n: BigInteger): TArray<BigInteger>; var divisor, next, rest: BigInteger; begin divisor := 2; next := 3; rest := n; while (rest <> 1) do begin while (rest mod divisor = 0) do begin SetLength(Result, Length(Result) + 1); Result[High(Result)] := divisor; rest := rest div divisor; end; divisor := next; next := next + 2; end; end; function Min(l: TArray<BigInteger>): BigInteger; begin if Length(l) = 0 then exit(0); Result := l[0]; for var v in l do if v < result then Result := v; end; const n: array of Uint64 = [12757923, 12878611, 12757923, 15808973, 15780709, 197622519]; var m: BigInteger; len, j, i: Uint64; l: TArray<TArray<BigInteger>>; begin j := 0; m := 0; len := length(n); SetLength(l, len); TParallel.for (0, len - 1, procedure(i: Integer) begin l[i] := getPrimes(n[i]); end); for i := 0 to len - 1 do begin var _min := Min(l[i]); if _min > m then begin m := _min; j := i; end; end; writeln('Number ', n[j].ToString, ' has largest minimal factor:'); for var v in l[j] do write(' ', v.ToString); readln; end.
#include <iostream> #include <iterator> #include <vector> #include <ppl.h> #include <concurrent_vector.h> struct Factors { int number; std::vector<int> primes; }; const int data[] = { 12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519 }; int main() { Concurrency::concurrent_vector<Factors> results; Concurrency::parallel_for_each(std::begin(data), std::end(data), [&](int n) { Factors factors; factors.number = n; for (int f = 2; n > 1; ++f) { while (n % f == 0) { factors.primes.push_back(f); n /= f; } } results.push_back(factors); }); auto max = std::max_element(results.begin(), results.end(), [](const Factors &a, const Factors &b) { return a.primes.front() < b.primes.front(); }); std::for_each(results.begin(), results.end(), [&](const Factors &f) { if (f.primes.front() == max->primes.front()) { std::cout << f.number << " = [ "; std::copy(f.primes.begin(), f.primes.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "]\n"; } }); return 0; }
Change the programming language of this snippet from Delphi to Java without modifying what it does.
program Parallel_calculations; uses System.SysUtils, System.Threading, Velthuis.BigIntegers; function IsPrime(n: BigInteger): Boolean; var i: BigInteger; begin if n <= 1 then exit(False); i := 2; while i < BigInteger.Sqrt(n) do begin if n mod i = 0 then exit(False); inc(i); end; Result := True; end; function GetPrimes(n: BigInteger): TArray<BigInteger>; var divisor, next, rest: BigInteger; begin divisor := 2; next := 3; rest := n; while (rest <> 1) do begin while (rest mod divisor = 0) do begin SetLength(Result, Length(Result) + 1); Result[High(Result)] := divisor; rest := rest div divisor; end; divisor := next; next := next + 2; end; end; function Min(l: TArray<BigInteger>): BigInteger; begin if Length(l) = 0 then exit(0); Result := l[0]; for var v in l do if v < result then Result := v; end; const n: array of Uint64 = [12757923, 12878611, 12757923, 15808973, 15780709, 197622519]; var m: BigInteger; len, j, i: Uint64; l: TArray<TArray<BigInteger>>; begin j := 0; m := 0; len := length(n); SetLength(l, len); TParallel.for (0, len - 1, procedure(i: Integer) begin l[i] := getPrimes(n[i]); end); for i := 0 to len - 1 do begin var _min := Min(l[i]); if _min > m then begin m := _min; j := i; end; end; writeln('Number ', n[j].ToString, ' has largest minimal factor:'); for var v in l[j] do write(' ', v.ToString); readln; end.
import static java.lang.System.out; import static java.util.Arrays.stream; import static java.util.Comparator.comparing; public interface ParallelCalculations { public static final long[] NUMBERS = { 12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519 }; public static void main(String... arguments) { stream(NUMBERS) .unordered() .parallel() .mapToObj(ParallelCalculations::minimalPrimeFactor) .max(comparing(a -> a[0])) .ifPresent(res -> out.printf( "%d has the largest minimum prime factor: %d%n", res[1], res[0] )); } public static long[] minimalPrimeFactor(long n) { for (long i = 2; n >= i * i; i++) { if (n % i == 0) { return new long[]{i, n}; } } return new long[]{n, n}; } }
Rewrite the snippet below in Python so it works the same as the original Delphi code.
program Parallel_calculations; uses System.SysUtils, System.Threading, Velthuis.BigIntegers; function IsPrime(n: BigInteger): Boolean; var i: BigInteger; begin if n <= 1 then exit(False); i := 2; while i < BigInteger.Sqrt(n) do begin if n mod i = 0 then exit(False); inc(i); end; Result := True; end; function GetPrimes(n: BigInteger): TArray<BigInteger>; var divisor, next, rest: BigInteger; begin divisor := 2; next := 3; rest := n; while (rest <> 1) do begin while (rest mod divisor = 0) do begin SetLength(Result, Length(Result) + 1); Result[High(Result)] := divisor; rest := rest div divisor; end; divisor := next; next := next + 2; end; end; function Min(l: TArray<BigInteger>): BigInteger; begin if Length(l) = 0 then exit(0); Result := l[0]; for var v in l do if v < result then Result := v; end; const n: array of Uint64 = [12757923, 12878611, 12757923, 15808973, 15780709, 197622519]; var m: BigInteger; len, j, i: Uint64; l: TArray<TArray<BigInteger>>; begin j := 0; m := 0; len := length(n); SetLength(l, len); TParallel.for (0, len - 1, procedure(i: Integer) begin l[i] := getPrimes(n[i]); end); for i := 0 to len - 1 do begin var _min := Min(l[i]); if _min > m then begin m := _min; j := i; end; end; writeln('Number ', n[j].ToString, ' has largest minimal factor:'); for var v in l[j] do write(' ', v.ToString); readln; end.
from concurrent import futures from math import floor, sqrt NUMBERS = [ 112272537195293, 112582718962171, 112272537095293, 115280098190773, 115797840077099, 1099726829285419] def lowest_factor(n, _start=3): if n % 2 == 0: return 2 search_max = int(floor(sqrt(n))) + 1 for i in range(_start, search_max, 2): if n % i == 0: return i return n def prime_factors(n, lowest): pf = [] while n > 1: pf.append(lowest) n //= lowest lowest = lowest_factor(n, max(lowest, 3)) return pf def prime_factors_of_number_with_lowest_prime_factor(NUMBERS): with futures.ProcessPoolExecutor() as executor: low_factor, number = max( (l, f) for l, f in zip(executor.map(lowest_factor, NUMBERS), NUMBERS) ) all_factors = prime_factors(number, low_factor) return number, all_factors def main(): print('For these numbers:') print('\n '.join(str(p) for p in NUMBERS)) number, all_factors = prime_factors_of_number_with_lowest_prime_factor(NUMBERS) print(' The one with the largest minimum prime factor is {}:'.format(number)) print(' All its prime factors in order are: {}'.format(all_factors)) if __name__ == '__main__': main()
Write the same algorithm in Go as shown in this Delphi implementation.
program Parallel_calculations; uses System.SysUtils, System.Threading, Velthuis.BigIntegers; function IsPrime(n: BigInteger): Boolean; var i: BigInteger; begin if n <= 1 then exit(False); i := 2; while i < BigInteger.Sqrt(n) do begin if n mod i = 0 then exit(False); inc(i); end; Result := True; end; function GetPrimes(n: BigInteger): TArray<BigInteger>; var divisor, next, rest: BigInteger; begin divisor := 2; next := 3; rest := n; while (rest <> 1) do begin while (rest mod divisor = 0) do begin SetLength(Result, Length(Result) + 1); Result[High(Result)] := divisor; rest := rest div divisor; end; divisor := next; next := next + 2; end; end; function Min(l: TArray<BigInteger>): BigInteger; begin if Length(l) = 0 then exit(0); Result := l[0]; for var v in l do if v < result then Result := v; end; const n: array of Uint64 = [12757923, 12878611, 12757923, 15808973, 15780709, 197622519]; var m: BigInteger; len, j, i: Uint64; l: TArray<TArray<BigInteger>>; begin j := 0; m := 0; len := length(n); SetLength(l, len); TParallel.for (0, len - 1, procedure(i: Integer) begin l[i] := getPrimes(n[i]); end); for i := 0 to len - 1 do begin var _min := Min(l[i]); if _min > m then begin m := _min; j := i; end; end; writeln('Number ', n[j].ToString, ' has largest minimal factor:'); for var v in l[j] do write(' ', v.ToString); readln; end.
package main import ( "fmt" "math/big" ) var numbers = []*big.Int{ big.NewInt(12757923), big.NewInt(12878611), big.NewInt(12878893), big.NewInt(12757923), big.NewInt(15808973), big.NewInt(15780709), } func main() { rs := lmf(numbers) fmt.Println("largest minimal factor:", rs[0].decomp[0]) for _, r := range rs { fmt.Println(r.number, "->", r.decomp) } } type result struct { number *big.Int decomp []*big.Int } func lmf([]*big.Int) []result { rCh := make(chan result) for _, n := range numbers { go decomp(n, rCh) } rs := []result{<-rCh} for i := 1; i < len(numbers); i++ { switch r := <-rCh; r.decomp[0].Cmp(rs[0].decomp[0]) { case 1: rs = rs[:1] rs[0] = r case 0: rs = append(rs, r) } } return rs } func decomp(n *big.Int, rCh chan result) { rCh <- result{n, Primes(new(big.Int).Set(n))} } var ( ZERO = big.NewInt(0) ONE = big.NewInt(1) ) func Primes(n *big.Int) []*big.Int { res := []*big.Int{} mod, div := new(big.Int), new(big.Int) for i := big.NewInt(2); i.Cmp(n) != 1; { div.DivMod(n, i, mod) for mod.Cmp(ZERO) == 0 { res = append(res, new(big.Int).Set(i)) n.Set(div) div.DivMod(n, i, mod) } i.Add(i, ONE) } return res }
Produce a functionally identical C code for the snippet given in Erlang.
-module( parallel_calculations ). -export( [fun_results/2, task/0] ). fun_results( Fun, Datas ) -> My_pid = erlang:self(), Pids = [fun_spawn( Fun, X, My_pid ) || X <- Datas], [fun_receive(X) || X <- Pids]. task() -> Numbers = [12757923, 12878611, 12757923, 15808973, 15780709, 197622519], Results = fun_results( fun factors/1, Numbers ), Min_results = [lists:min(X) || X <- Results], {_Max_min_factor, Number} = lists:max( lists:zip(Min_results, Numbers) ), {Number, Factors} = lists:keyfind( Number, 1, lists:zip(Numbers, Results) ), io:fwrite( "~p has largest minimal factor among its prime factors ~p~n", [Number, Factors] ). factors(N) -> factors(N,2,[]). factors(1,_,Acc) -> Acc; factors(N,K,Acc) when N rem K == 0 -> factors(N div K,K, [K|Acc]); factors(N,K,Acc) -> factors(N,K+1,Acc). fun_receive( Pid ) -> receive {ok, Result, Pid} -> Result; {Type, Error, Pid} -> erlang:Type( Error ) end. fun_spawn( Fun, Data, My_pid ) -> erlang:spawn( fun() -> Result = try {ok, Fun(Data), erlang:self()} catch Type:Error -> {Type, Error, erlang:self()} end, My_pid ! Result end ).
#include <stdio.h> #include <omp.h> int main() { int data[] = {12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519}; int largest, largest_factor = 0; omp_set_num_threads(4); #pragma omp parallel for shared(largest_factor, largest) for (int i = 0; i < 7; i++) { int p, n = data[i]; for (p = 3; p * p <= n && n % p; p += 2); if (p * p > n) p = n; if (p > largest_factor) { largest_factor = p; largest = n; printf("thread %d: found larger: %d of %d\n", omp_get_thread_num(), p, n); } else { printf("thread %d: not larger: %d of %d\n", omp_get_thread_num(), p, n); } } printf("Largest factor: %d of %d\n", largest_factor, largest); return 0; }
Translate this program into C# but keep the logic exactly as in Erlang.
-module( parallel_calculations ). -export( [fun_results/2, task/0] ). fun_results( Fun, Datas ) -> My_pid = erlang:self(), Pids = [fun_spawn( Fun, X, My_pid ) || X <- Datas], [fun_receive(X) || X <- Pids]. task() -> Numbers = [12757923, 12878611, 12757923, 15808973, 15780709, 197622519], Results = fun_results( fun factors/1, Numbers ), Min_results = [lists:min(X) || X <- Results], {_Max_min_factor, Number} = lists:max( lists:zip(Min_results, Numbers) ), {Number, Factors} = lists:keyfind( Number, 1, lists:zip(Numbers, Results) ), io:fwrite( "~p has largest minimal factor among its prime factors ~p~n", [Number, Factors] ). factors(N) -> factors(N,2,[]). factors(1,_,Acc) -> Acc; factors(N,K,Acc) when N rem K == 0 -> factors(N div K,K, [K|Acc]); factors(N,K,Acc) -> factors(N,K+1,Acc). fun_receive( Pid ) -> receive {ok, Result, Pid} -> Result; {Type, Error, Pid} -> erlang:Type( Error ) end. fun_spawn( Fun, Data, My_pid ) -> erlang:spawn( fun() -> Result = try {ok, Fun(Data), erlang:self()} catch Type:Error -> {Type, Error, erlang:self()} end, My_pid ! Result end ).
using System; using System.Collections.Generic; using System.Linq; class Program { public static List<int> PrimeFactors(int number) { var primes = new List<int>(); for (int div = 2; div <= number; div++) { while (number % div == 0) { primes.Add(div); number = number / div; } } return primes; } static void Main(string[] args) { int[] n = { 12757923, 12878611, 12757923, 15808973, 15780709, 197622519 }; var factors = n.AsParallel().Select(PrimeFactors).ToList(); var smallestFactors = factors.Select(thisNumbersFactors => thisNumbersFactors.Min()).ToList(); int biggestFactor = smallestFactors.Max(); int whatIndexIsThat = smallestFactors.IndexOf(biggestFactor); Console.WriteLine("{0} has the largest minimum prime factor: {1}", n[whatIndexIsThat], biggestFactor); Console.WriteLine(string.Join(" ", factors[whatIndexIsThat])); } }
Port the provided Erlang code into C++ while preserving the original functionality.
-module( parallel_calculations ). -export( [fun_results/2, task/0] ). fun_results( Fun, Datas ) -> My_pid = erlang:self(), Pids = [fun_spawn( Fun, X, My_pid ) || X <- Datas], [fun_receive(X) || X <- Pids]. task() -> Numbers = [12757923, 12878611, 12757923, 15808973, 15780709, 197622519], Results = fun_results( fun factors/1, Numbers ), Min_results = [lists:min(X) || X <- Results], {_Max_min_factor, Number} = lists:max( lists:zip(Min_results, Numbers) ), {Number, Factors} = lists:keyfind( Number, 1, lists:zip(Numbers, Results) ), io:fwrite( "~p has largest minimal factor among its prime factors ~p~n", [Number, Factors] ). factors(N) -> factors(N,2,[]). factors(1,_,Acc) -> Acc; factors(N,K,Acc) when N rem K == 0 -> factors(N div K,K, [K|Acc]); factors(N,K,Acc) -> factors(N,K+1,Acc). fun_receive( Pid ) -> receive {ok, Result, Pid} -> Result; {Type, Error, Pid} -> erlang:Type( Error ) end. fun_spawn( Fun, Data, My_pid ) -> erlang:spawn( fun() -> Result = try {ok, Fun(Data), erlang:self()} catch Type:Error -> {Type, Error, erlang:self()} end, My_pid ! Result end ).
#include <iostream> #include <iterator> #include <vector> #include <ppl.h> #include <concurrent_vector.h> struct Factors { int number; std::vector<int> primes; }; const int data[] = { 12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519 }; int main() { Concurrency::concurrent_vector<Factors> results; Concurrency::parallel_for_each(std::begin(data), std::end(data), [&](int n) { Factors factors; factors.number = n; for (int f = 2; n > 1; ++f) { while (n % f == 0) { factors.primes.push_back(f); n /= f; } } results.push_back(factors); }); auto max = std::max_element(results.begin(), results.end(), [](const Factors &a, const Factors &b) { return a.primes.front() < b.primes.front(); }); std::for_each(results.begin(), results.end(), [&](const Factors &f) { if (f.primes.front() == max->primes.front()) { std::cout << f.number << " = [ "; std::copy(f.primes.begin(), f.primes.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "]\n"; } }); return 0; }
Rewrite the snippet below in Java so it works the same as the original Erlang code.
-module( parallel_calculations ). -export( [fun_results/2, task/0] ). fun_results( Fun, Datas ) -> My_pid = erlang:self(), Pids = [fun_spawn( Fun, X, My_pid ) || X <- Datas], [fun_receive(X) || X <- Pids]. task() -> Numbers = [12757923, 12878611, 12757923, 15808973, 15780709, 197622519], Results = fun_results( fun factors/1, Numbers ), Min_results = [lists:min(X) || X <- Results], {_Max_min_factor, Number} = lists:max( lists:zip(Min_results, Numbers) ), {Number, Factors} = lists:keyfind( Number, 1, lists:zip(Numbers, Results) ), io:fwrite( "~p has largest minimal factor among its prime factors ~p~n", [Number, Factors] ). factors(N) -> factors(N,2,[]). factors(1,_,Acc) -> Acc; factors(N,K,Acc) when N rem K == 0 -> factors(N div K,K, [K|Acc]); factors(N,K,Acc) -> factors(N,K+1,Acc). fun_receive( Pid ) -> receive {ok, Result, Pid} -> Result; {Type, Error, Pid} -> erlang:Type( Error ) end. fun_spawn( Fun, Data, My_pid ) -> erlang:spawn( fun() -> Result = try {ok, Fun(Data), erlang:self()} catch Type:Error -> {Type, Error, erlang:self()} end, My_pid ! Result end ).
import static java.lang.System.out; import static java.util.Arrays.stream; import static java.util.Comparator.comparing; public interface ParallelCalculations { public static final long[] NUMBERS = { 12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519 }; public static void main(String... arguments) { stream(NUMBERS) .unordered() .parallel() .mapToObj(ParallelCalculations::minimalPrimeFactor) .max(comparing(a -> a[0])) .ifPresent(res -> out.printf( "%d has the largest minimum prime factor: %d%n", res[1], res[0] )); } public static long[] minimalPrimeFactor(long n) { for (long i = 2; n >= i * i; i++) { if (n % i == 0) { return new long[]{i, n}; } } return new long[]{n, n}; } }
Write a version of this Erlang function in Python with identical behavior.
-module( parallel_calculations ). -export( [fun_results/2, task/0] ). fun_results( Fun, Datas ) -> My_pid = erlang:self(), Pids = [fun_spawn( Fun, X, My_pid ) || X <- Datas], [fun_receive(X) || X <- Pids]. task() -> Numbers = [12757923, 12878611, 12757923, 15808973, 15780709, 197622519], Results = fun_results( fun factors/1, Numbers ), Min_results = [lists:min(X) || X <- Results], {_Max_min_factor, Number} = lists:max( lists:zip(Min_results, Numbers) ), {Number, Factors} = lists:keyfind( Number, 1, lists:zip(Numbers, Results) ), io:fwrite( "~p has largest minimal factor among its prime factors ~p~n", [Number, Factors] ). factors(N) -> factors(N,2,[]). factors(1,_,Acc) -> Acc; factors(N,K,Acc) when N rem K == 0 -> factors(N div K,K, [K|Acc]); factors(N,K,Acc) -> factors(N,K+1,Acc). fun_receive( Pid ) -> receive {ok, Result, Pid} -> Result; {Type, Error, Pid} -> erlang:Type( Error ) end. fun_spawn( Fun, Data, My_pid ) -> erlang:spawn( fun() -> Result = try {ok, Fun(Data), erlang:self()} catch Type:Error -> {Type, Error, erlang:self()} end, My_pid ! Result end ).
from concurrent import futures from math import floor, sqrt NUMBERS = [ 112272537195293, 112582718962171, 112272537095293, 115280098190773, 115797840077099, 1099726829285419] def lowest_factor(n, _start=3): if n % 2 == 0: return 2 search_max = int(floor(sqrt(n))) + 1 for i in range(_start, search_max, 2): if n % i == 0: return i return n def prime_factors(n, lowest): pf = [] while n > 1: pf.append(lowest) n //= lowest lowest = lowest_factor(n, max(lowest, 3)) return pf def prime_factors_of_number_with_lowest_prime_factor(NUMBERS): with futures.ProcessPoolExecutor() as executor: low_factor, number = max( (l, f) for l, f in zip(executor.map(lowest_factor, NUMBERS), NUMBERS) ) all_factors = prime_factors(number, low_factor) return number, all_factors def main(): print('For these numbers:') print('\n '.join(str(p) for p in NUMBERS)) number, all_factors = prime_factors_of_number_with_lowest_prime_factor(NUMBERS) print(' The one with the largest minimum prime factor is {}:'.format(number)) print(' All its prime factors in order are: {}'.format(all_factors)) if __name__ == '__main__': main()
Generate a Go translation of this Erlang snippet without changing its computational steps.
-module( parallel_calculations ). -export( [fun_results/2, task/0] ). fun_results( Fun, Datas ) -> My_pid = erlang:self(), Pids = [fun_spawn( Fun, X, My_pid ) || X <- Datas], [fun_receive(X) || X <- Pids]. task() -> Numbers = [12757923, 12878611, 12757923, 15808973, 15780709, 197622519], Results = fun_results( fun factors/1, Numbers ), Min_results = [lists:min(X) || X <- Results], {_Max_min_factor, Number} = lists:max( lists:zip(Min_results, Numbers) ), {Number, Factors} = lists:keyfind( Number, 1, lists:zip(Numbers, Results) ), io:fwrite( "~p has largest minimal factor among its prime factors ~p~n", [Number, Factors] ). factors(N) -> factors(N,2,[]). factors(1,_,Acc) -> Acc; factors(N,K,Acc) when N rem K == 0 -> factors(N div K,K, [K|Acc]); factors(N,K,Acc) -> factors(N,K+1,Acc). fun_receive( Pid ) -> receive {ok, Result, Pid} -> Result; {Type, Error, Pid} -> erlang:Type( Error ) end. fun_spawn( Fun, Data, My_pid ) -> erlang:spawn( fun() -> Result = try {ok, Fun(Data), erlang:self()} catch Type:Error -> {Type, Error, erlang:self()} end, My_pid ! Result end ).
package main import ( "fmt" "math/big" ) var numbers = []*big.Int{ big.NewInt(12757923), big.NewInt(12878611), big.NewInt(12878893), big.NewInt(12757923), big.NewInt(15808973), big.NewInt(15780709), } func main() { rs := lmf(numbers) fmt.Println("largest minimal factor:", rs[0].decomp[0]) for _, r := range rs { fmt.Println(r.number, "->", r.decomp) } } type result struct { number *big.Int decomp []*big.Int } func lmf([]*big.Int) []result { rCh := make(chan result) for _, n := range numbers { go decomp(n, rCh) } rs := []result{<-rCh} for i := 1; i < len(numbers); i++ { switch r := <-rCh; r.decomp[0].Cmp(rs[0].decomp[0]) { case 1: rs = rs[:1] rs[0] = r case 0: rs = append(rs, r) } } return rs } func decomp(n *big.Int, rCh chan result) { rCh <- result{n, Primes(new(big.Int).Set(n))} } var ( ZERO = big.NewInt(0) ONE = big.NewInt(1) ) func Primes(n *big.Int) []*big.Int { res := []*big.Int{} mod, div := new(big.Int), new(big.Int) for i := big.NewInt(2); i.Cmp(n) != 1; { div.DivMod(n, i, mod) for mod.Cmp(ZERO) == 0 { res = append(res, new(big.Int).Set(i)) n.Set(div) div.DivMod(n, i, mod) } i.Add(i, ONE) } return res }
Keep all operations the same but rewrite the snippet in C.
open System open PrimeDecomp let data = [112272537195293L; 112582718962171L; 112272537095293L; 115280098190773L; 115797840077099L; 1099726829285419L] let decomp num = decompose num 2L let largestMinPrimeFactor (numbers: int64 list) = let decompDetails = Async.Parallel [ for n in numbers -> async { return n, decomp n } ] |> Async.RunSynchronously |> Array.sortBy (snd >> List.min >> (~-)) decompDetails.[0] let showLargestMinPrimeFactor numbers = let number, primeList = largestMinPrimeFactor numbers printf "Number %d has largest minimal factor:\n " number List.iter (printf "%d ") primeList showLargestMinPrimeFactor data
#include <stdio.h> #include <omp.h> int main() { int data[] = {12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519}; int largest, largest_factor = 0; omp_set_num_threads(4); #pragma omp parallel for shared(largest_factor, largest) for (int i = 0; i < 7; i++) { int p, n = data[i]; for (p = 3; p * p <= n && n % p; p += 2); if (p * p > n) p = n; if (p > largest_factor) { largest_factor = p; largest = n; printf("thread %d: found larger: %d of %d\n", omp_get_thread_num(), p, n); } else { printf("thread %d: not larger: %d of %d\n", omp_get_thread_num(), p, n); } } printf("Largest factor: %d of %d\n", largest_factor, largest); return 0; }
Maintain the same structure and functionality when rewriting this code in C#.
open System open PrimeDecomp let data = [112272537195293L; 112582718962171L; 112272537095293L; 115280098190773L; 115797840077099L; 1099726829285419L] let decomp num = decompose num 2L let largestMinPrimeFactor (numbers: int64 list) = let decompDetails = Async.Parallel [ for n in numbers -> async { return n, decomp n } ] |> Async.RunSynchronously |> Array.sortBy (snd >> List.min >> (~-)) decompDetails.[0] let showLargestMinPrimeFactor numbers = let number, primeList = largestMinPrimeFactor numbers printf "Number %d has largest minimal factor:\n " number List.iter (printf "%d ") primeList showLargestMinPrimeFactor data
using System; using System.Collections.Generic; using System.Linq; class Program { public static List<int> PrimeFactors(int number) { var primes = new List<int>(); for (int div = 2; div <= number; div++) { while (number % div == 0) { primes.Add(div); number = number / div; } } return primes; } static void Main(string[] args) { int[] n = { 12757923, 12878611, 12757923, 15808973, 15780709, 197622519 }; var factors = n.AsParallel().Select(PrimeFactors).ToList(); var smallestFactors = factors.Select(thisNumbersFactors => thisNumbersFactors.Min()).ToList(); int biggestFactor = smallestFactors.Max(); int whatIndexIsThat = smallestFactors.IndexOf(biggestFactor); Console.WriteLine("{0} has the largest minimum prime factor: {1}", n[whatIndexIsThat], biggestFactor); Console.WriteLine(string.Join(" ", factors[whatIndexIsThat])); } }
Change the programming language of this snippet from F# to C++ without modifying what it does.
open System open PrimeDecomp let data = [112272537195293L; 112582718962171L; 112272537095293L; 115280098190773L; 115797840077099L; 1099726829285419L] let decomp num = decompose num 2L let largestMinPrimeFactor (numbers: int64 list) = let decompDetails = Async.Parallel [ for n in numbers -> async { return n, decomp n } ] |> Async.RunSynchronously |> Array.sortBy (snd >> List.min >> (~-)) decompDetails.[0] let showLargestMinPrimeFactor numbers = let number, primeList = largestMinPrimeFactor numbers printf "Number %d has largest minimal factor:\n " number List.iter (printf "%d ") primeList showLargestMinPrimeFactor data
#include <iostream> #include <iterator> #include <vector> #include <ppl.h> #include <concurrent_vector.h> struct Factors { int number; std::vector<int> primes; }; const int data[] = { 12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519 }; int main() { Concurrency::concurrent_vector<Factors> results; Concurrency::parallel_for_each(std::begin(data), std::end(data), [&](int n) { Factors factors; factors.number = n; for (int f = 2; n > 1; ++f) { while (n % f == 0) { factors.primes.push_back(f); n /= f; } } results.push_back(factors); }); auto max = std::max_element(results.begin(), results.end(), [](const Factors &a, const Factors &b) { return a.primes.front() < b.primes.front(); }); std::for_each(results.begin(), results.end(), [&](const Factors &f) { if (f.primes.front() == max->primes.front()) { std::cout << f.number << " = [ "; std::copy(f.primes.begin(), f.primes.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "]\n"; } }); return 0; }
Rewrite this program in Java while keeping its functionality equivalent to the F# version.
open System open PrimeDecomp let data = [112272537195293L; 112582718962171L; 112272537095293L; 115280098190773L; 115797840077099L; 1099726829285419L] let decomp num = decompose num 2L let largestMinPrimeFactor (numbers: int64 list) = let decompDetails = Async.Parallel [ for n in numbers -> async { return n, decomp n } ] |> Async.RunSynchronously |> Array.sortBy (snd >> List.min >> (~-)) decompDetails.[0] let showLargestMinPrimeFactor numbers = let number, primeList = largestMinPrimeFactor numbers printf "Number %d has largest minimal factor:\n " number List.iter (printf "%d ") primeList showLargestMinPrimeFactor data
import static java.lang.System.out; import static java.util.Arrays.stream; import static java.util.Comparator.comparing; public interface ParallelCalculations { public static final long[] NUMBERS = { 12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519 }; public static void main(String... arguments) { stream(NUMBERS) .unordered() .parallel() .mapToObj(ParallelCalculations::minimalPrimeFactor) .max(comparing(a -> a[0])) .ifPresent(res -> out.printf( "%d has the largest minimum prime factor: %d%n", res[1], res[0] )); } public static long[] minimalPrimeFactor(long n) { for (long i = 2; n >= i * i; i++) { if (n % i == 0) { return new long[]{i, n}; } } return new long[]{n, n}; } }
Generate an equivalent Python version of this F# code.
open System open PrimeDecomp let data = [112272537195293L; 112582718962171L; 112272537095293L; 115280098190773L; 115797840077099L; 1099726829285419L] let decomp num = decompose num 2L let largestMinPrimeFactor (numbers: int64 list) = let decompDetails = Async.Parallel [ for n in numbers -> async { return n, decomp n } ] |> Async.RunSynchronously |> Array.sortBy (snd >> List.min >> (~-)) decompDetails.[0] let showLargestMinPrimeFactor numbers = let number, primeList = largestMinPrimeFactor numbers printf "Number %d has largest minimal factor:\n " number List.iter (printf "%d ") primeList showLargestMinPrimeFactor data
from concurrent import futures from math import floor, sqrt NUMBERS = [ 112272537195293, 112582718962171, 112272537095293, 115280098190773, 115797840077099, 1099726829285419] def lowest_factor(n, _start=3): if n % 2 == 0: return 2 search_max = int(floor(sqrt(n))) + 1 for i in range(_start, search_max, 2): if n % i == 0: return i return n def prime_factors(n, lowest): pf = [] while n > 1: pf.append(lowest) n //= lowest lowest = lowest_factor(n, max(lowest, 3)) return pf def prime_factors_of_number_with_lowest_prime_factor(NUMBERS): with futures.ProcessPoolExecutor() as executor: low_factor, number = max( (l, f) for l, f in zip(executor.map(lowest_factor, NUMBERS), NUMBERS) ) all_factors = prime_factors(number, low_factor) return number, all_factors def main(): print('For these numbers:') print('\n '.join(str(p) for p in NUMBERS)) number, all_factors = prime_factors_of_number_with_lowest_prime_factor(NUMBERS) print(' The one with the largest minimum prime factor is {}:'.format(number)) print(' All its prime factors in order are: {}'.format(all_factors)) if __name__ == '__main__': main()
Change the following F# code into Go without altering its purpose.
open System open PrimeDecomp let data = [112272537195293L; 112582718962171L; 112272537095293L; 115280098190773L; 115797840077099L; 1099726829285419L] let decomp num = decompose num 2L let largestMinPrimeFactor (numbers: int64 list) = let decompDetails = Async.Parallel [ for n in numbers -> async { return n, decomp n } ] |> Async.RunSynchronously |> Array.sortBy (snd >> List.min >> (~-)) decompDetails.[0] let showLargestMinPrimeFactor numbers = let number, primeList = largestMinPrimeFactor numbers printf "Number %d has largest minimal factor:\n " number List.iter (printf "%d ") primeList showLargestMinPrimeFactor data
package main import ( "fmt" "math/big" ) var numbers = []*big.Int{ big.NewInt(12757923), big.NewInt(12878611), big.NewInt(12878893), big.NewInt(12757923), big.NewInt(15808973), big.NewInt(15780709), } func main() { rs := lmf(numbers) fmt.Println("largest minimal factor:", rs[0].decomp[0]) for _, r := range rs { fmt.Println(r.number, "->", r.decomp) } } type result struct { number *big.Int decomp []*big.Int } func lmf([]*big.Int) []result { rCh := make(chan result) for _, n := range numbers { go decomp(n, rCh) } rs := []result{<-rCh} for i := 1; i < len(numbers); i++ { switch r := <-rCh; r.decomp[0].Cmp(rs[0].decomp[0]) { case 1: rs = rs[:1] rs[0] = r case 0: rs = append(rs, r) } } return rs } func decomp(n *big.Int, rCh chan result) { rCh <- result{n, Primes(new(big.Int).Set(n))} } var ( ZERO = big.NewInt(0) ONE = big.NewInt(1) ) func Primes(n *big.Int) []*big.Int { res := []*big.Int{} mod, div := new(big.Int), new(big.Int) for i := big.NewInt(2); i.Cmp(n) != 1; { div.DivMod(n, i, mod) for mod.Cmp(ZERO) == 0 { res = append(res, new(big.Int).Set(i)) n.Set(div) div.DivMod(n, i, mod) } i.Add(i, ONE) } return res }
Convert this Factor snippet to C and keep its semantics consistent.
USING: io kernel fry locals sequences arrays math.primes.factors math.parser channels threads prettyprint ; IN: <filename> :: map-parallel ( seq quot -- newseq ) <channel> :> ch seq [ '[ _ quot call ch to ] "factors" spawn ] { } map-as dup length [ ch from ] replicate nip ; { 576460752303423487 576460752303423487 576460752303423487 112272537195293 115284584522153 115280098190773 115797840077099 112582718962171 112272537095293 1099726829285419 } dup [ factors ] map-parallel dup [ infimum ] map dup supremum swap index swap dupd nth -rot swap nth "Number with largest min. factor is " swap number>string append ", with factors: " append write .
#include <stdio.h> #include <omp.h> int main() { int data[] = {12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519}; int largest, largest_factor = 0; omp_set_num_threads(4); #pragma omp parallel for shared(largest_factor, largest) for (int i = 0; i < 7; i++) { int p, n = data[i]; for (p = 3; p * p <= n && n % p; p += 2); if (p * p > n) p = n; if (p > largest_factor) { largest_factor = p; largest = n; printf("thread %d: found larger: %d of %d\n", omp_get_thread_num(), p, n); } else { printf("thread %d: not larger: %d of %d\n", omp_get_thread_num(), p, n); } } printf("Largest factor: %d of %d\n", largest_factor, largest); return 0; }
Can you help me rewrite this code in C# instead of Factor, keeping it the same logically?
USING: io kernel fry locals sequences arrays math.primes.factors math.parser channels threads prettyprint ; IN: <filename> :: map-parallel ( seq quot -- newseq ) <channel> :> ch seq [ '[ _ quot call ch to ] "factors" spawn ] { } map-as dup length [ ch from ] replicate nip ; { 576460752303423487 576460752303423487 576460752303423487 112272537195293 115284584522153 115280098190773 115797840077099 112582718962171 112272537095293 1099726829285419 } dup [ factors ] map-parallel dup [ infimum ] map dup supremum swap index swap dupd nth -rot swap nth "Number with largest min. factor is " swap number>string append ", with factors: " append write .
using System; using System.Collections.Generic; using System.Linq; class Program { public static List<int> PrimeFactors(int number) { var primes = new List<int>(); for (int div = 2; div <= number; div++) { while (number % div == 0) { primes.Add(div); number = number / div; } } return primes; } static void Main(string[] args) { int[] n = { 12757923, 12878611, 12757923, 15808973, 15780709, 197622519 }; var factors = n.AsParallel().Select(PrimeFactors).ToList(); var smallestFactors = factors.Select(thisNumbersFactors => thisNumbersFactors.Min()).ToList(); int biggestFactor = smallestFactors.Max(); int whatIndexIsThat = smallestFactors.IndexOf(biggestFactor); Console.WriteLine("{0} has the largest minimum prime factor: {1}", n[whatIndexIsThat], biggestFactor); Console.WriteLine(string.Join(" ", factors[whatIndexIsThat])); } }
Translate the given Factor code snippet into C++ without altering its behavior.
USING: io kernel fry locals sequences arrays math.primes.factors math.parser channels threads prettyprint ; IN: <filename> :: map-parallel ( seq quot -- newseq ) <channel> :> ch seq [ '[ _ quot call ch to ] "factors" spawn ] { } map-as dup length [ ch from ] replicate nip ; { 576460752303423487 576460752303423487 576460752303423487 112272537195293 115284584522153 115280098190773 115797840077099 112582718962171 112272537095293 1099726829285419 } dup [ factors ] map-parallel dup [ infimum ] map dup supremum swap index swap dupd nth -rot swap nth "Number with largest min. factor is " swap number>string append ", with factors: " append write .
#include <iostream> #include <iterator> #include <vector> #include <ppl.h> #include <concurrent_vector.h> struct Factors { int number; std::vector<int> primes; }; const int data[] = { 12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519 }; int main() { Concurrency::concurrent_vector<Factors> results; Concurrency::parallel_for_each(std::begin(data), std::end(data), [&](int n) { Factors factors; factors.number = n; for (int f = 2; n > 1; ++f) { while (n % f == 0) { factors.primes.push_back(f); n /= f; } } results.push_back(factors); }); auto max = std::max_element(results.begin(), results.end(), [](const Factors &a, const Factors &b) { return a.primes.front() < b.primes.front(); }); std::for_each(results.begin(), results.end(), [&](const Factors &f) { if (f.primes.front() == max->primes.front()) { std::cout << f.number << " = [ "; std::copy(f.primes.begin(), f.primes.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "]\n"; } }); return 0; }
Generate a Java translation of this Factor snippet without changing its computational steps.
USING: io kernel fry locals sequences arrays math.primes.factors math.parser channels threads prettyprint ; IN: <filename> :: map-parallel ( seq quot -- newseq ) <channel> :> ch seq [ '[ _ quot call ch to ] "factors" spawn ] { } map-as dup length [ ch from ] replicate nip ; { 576460752303423487 576460752303423487 576460752303423487 112272537195293 115284584522153 115280098190773 115797840077099 112582718962171 112272537095293 1099726829285419 } dup [ factors ] map-parallel dup [ infimum ] map dup supremum swap index swap dupd nth -rot swap nth "Number with largest min. factor is " swap number>string append ", with factors: " append write .
import static java.lang.System.out; import static java.util.Arrays.stream; import static java.util.Comparator.comparing; public interface ParallelCalculations { public static final long[] NUMBERS = { 12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519 }; public static void main(String... arguments) { stream(NUMBERS) .unordered() .parallel() .mapToObj(ParallelCalculations::minimalPrimeFactor) .max(comparing(a -> a[0])) .ifPresent(res -> out.printf( "%d has the largest minimum prime factor: %d%n", res[1], res[0] )); } public static long[] minimalPrimeFactor(long n) { for (long i = 2; n >= i * i; i++) { if (n % i == 0) { return new long[]{i, n}; } } return new long[]{n, n}; } }
Write a version of this Factor function in Python with identical behavior.
USING: io kernel fry locals sequences arrays math.primes.factors math.parser channels threads prettyprint ; IN: <filename> :: map-parallel ( seq quot -- newseq ) <channel> :> ch seq [ '[ _ quot call ch to ] "factors" spawn ] { } map-as dup length [ ch from ] replicate nip ; { 576460752303423487 576460752303423487 576460752303423487 112272537195293 115284584522153 115280098190773 115797840077099 112582718962171 112272537095293 1099726829285419 } dup [ factors ] map-parallel dup [ infimum ] map dup supremum swap index swap dupd nth -rot swap nth "Number with largest min. factor is " swap number>string append ", with factors: " append write .
from concurrent import futures from math import floor, sqrt NUMBERS = [ 112272537195293, 112582718962171, 112272537095293, 115280098190773, 115797840077099, 1099726829285419] def lowest_factor(n, _start=3): if n % 2 == 0: return 2 search_max = int(floor(sqrt(n))) + 1 for i in range(_start, search_max, 2): if n % i == 0: return i return n def prime_factors(n, lowest): pf = [] while n > 1: pf.append(lowest) n //= lowest lowest = lowest_factor(n, max(lowest, 3)) return pf def prime_factors_of_number_with_lowest_prime_factor(NUMBERS): with futures.ProcessPoolExecutor() as executor: low_factor, number = max( (l, f) for l, f in zip(executor.map(lowest_factor, NUMBERS), NUMBERS) ) all_factors = prime_factors(number, low_factor) return number, all_factors def main(): print('For these numbers:') print('\n '.join(str(p) for p in NUMBERS)) number, all_factors = prime_factors_of_number_with_lowest_prime_factor(NUMBERS) print(' The one with the largest minimum prime factor is {}:'.format(number)) print(' All its prime factors in order are: {}'.format(all_factors)) if __name__ == '__main__': main()
Maintain the same structure and functionality when rewriting this code in Go.
USING: io kernel fry locals sequences arrays math.primes.factors math.parser channels threads prettyprint ; IN: <filename> :: map-parallel ( seq quot -- newseq ) <channel> :> ch seq [ '[ _ quot call ch to ] "factors" spawn ] { } map-as dup length [ ch from ] replicate nip ; { 576460752303423487 576460752303423487 576460752303423487 112272537195293 115284584522153 115280098190773 115797840077099 112582718962171 112272537095293 1099726829285419 } dup [ factors ] map-parallel dup [ infimum ] map dup supremum swap index swap dupd nth -rot swap nth "Number with largest min. factor is " swap number>string append ", with factors: " append write .
package main import ( "fmt" "math/big" ) var numbers = []*big.Int{ big.NewInt(12757923), big.NewInt(12878611), big.NewInt(12878893), big.NewInt(12757923), big.NewInt(15808973), big.NewInt(15780709), } func main() { rs := lmf(numbers) fmt.Println("largest minimal factor:", rs[0].decomp[0]) for _, r := range rs { fmt.Println(r.number, "->", r.decomp) } } type result struct { number *big.Int decomp []*big.Int } func lmf([]*big.Int) []result { rCh := make(chan result) for _, n := range numbers { go decomp(n, rCh) } rs := []result{<-rCh} for i := 1; i < len(numbers); i++ { switch r := <-rCh; r.decomp[0].Cmp(rs[0].decomp[0]) { case 1: rs = rs[:1] rs[0] = r case 0: rs = append(rs, r) } } return rs } func decomp(n *big.Int, rCh chan result) { rCh <- result{n, Primes(new(big.Int).Set(n))} } var ( ZERO = big.NewInt(0) ONE = big.NewInt(1) ) func Primes(n *big.Int) []*big.Int { res := []*big.Int{} mod, div := new(big.Int), new(big.Int) for i := big.NewInt(2); i.Cmp(n) != 1; { div.DivMod(n, i, mod) for mod.Cmp(ZERO) == 0 { res = append(res, new(big.Int).Set(i)) n.Set(div) div.DivMod(n, i, mod) } i.Add(i, ONE) } return res }
Please provide an equivalent version of this Fortran code in C#.
program Primes use ISO_FORTRAN_ENV implicit none integer(int64), dimension(7) :: data = (/2099726827, 15780709, 1122725370, 15808973, 576460741, 12878611, 12757923/) integer(int64), dimension(100) :: outprimes integer(int64) :: largest_factor = 0, largest = 0, minim = 0, val = 0 integer(int16) :: count = 0, OMP_GET_THREAD_NUM call omp_set_num_threads(4); do val = 1, 7 outprimes = 0 call find_factors(data(val), outprimes, count) minim = minval(outprimes(1:count)) if (minim > largest_factor) then largest_factor = minim largest = data(val) end if write(*, fmt = '(A7,i0,A2,i12,100i12)') 'Thread ', OMP_GET_THREAD_NUM(), ': ', data(val), outprimes(1:count) end do write(*, fmt = '(i0,A26,i0)') largest, ' have the Largest factor: ', largest_factor return contains subroutine find_factors(n, d, count) integer(int64), intent(in) :: n integer(int64), dimension(:), intent(out) :: d integer(int16), intent(out) :: count integer(int16) :: i integer(int64) :: div, next, rest i = 1 div = 2; next = 3; rest = n do while (rest /= 1) do while (mod(rest, div) == 0) d(i) = div i = i + 1 rest = rest / div end do div = next next = next + 2 end do count = i - 1 end subroutine find_factors end program Primes
using System; using System.Collections.Generic; using System.Linq; class Program { public static List<int> PrimeFactors(int number) { var primes = new List<int>(); for (int div = 2; div <= number; div++) { while (number % div == 0) { primes.Add(div); number = number / div; } } return primes; } static void Main(string[] args) { int[] n = { 12757923, 12878611, 12757923, 15808973, 15780709, 197622519 }; var factors = n.AsParallel().Select(PrimeFactors).ToList(); var smallestFactors = factors.Select(thisNumbersFactors => thisNumbersFactors.Min()).ToList(); int biggestFactor = smallestFactors.Max(); int whatIndexIsThat = smallestFactors.IndexOf(biggestFactor); Console.WriteLine("{0} has the largest minimum prime factor: {1}", n[whatIndexIsThat], biggestFactor); Console.WriteLine(string.Join(" ", factors[whatIndexIsThat])); } }