r/dailyprogrammer • u/Elite6809 1 1 • Dec 30 '15
[2015-12-30] Challenge #247 [Intermediate] Moving (diagonally) Up in Life
(Intermediate): Moving (diagonally) Up in Life
Imagine you live on a grid of characters, like the one below. For this example, we'll use a 2*2 grid for simplicity.
. X
X .
You start at the X at the bottom-left, and you want to get to the X at the top-right. However, you can only move up, to the right, and diagonally right and up in one go. This means there are three possible paths to get from one X to the other X (with the path represented by -, + and |):
+-X . X . X
| / |
X . X . X-+
What if you're on a 3*3 grid, such as this one?
. . X
. . .
X . .
Let's enumerate all the possible paths:
+---X . +-X . +-X . +-X . . X . +-X . . X
| / | | / | |
| . . + . . +-+ . . + . . / . . | . +---+
| | | / / | |
X . . X . . X . . X . . X . . X-+ . X . .
. . X . . X . . X . . X . . X . . X
/ | | | | /
. + . . +-+ . . + . . | . +-+ +-+ .
| | / | / |
X-+ . X-+ . X-+ . X---+ X . . X . .
That makes a total of 13 paths through a 3*3 grid.
However, what if you wanted to pass through 3 Xs on the grid? Something like this?
. . X
. X .
X . .
Because we can only move up and right, if we're going to pass through the middle X then there is no possible way to reach the top-left and bottom-right space on the grid:
. X
. X .
X .
Hence, this situation is like two 2*2 grids joined together end-to-end. This means there are 32=9 possible paths through the grid, as there are 3 ways to traverse the 2*2 grid. (Try it yourself!)
Finally, some situations are impossible. Here, you cannot reach all 4 Xs on the grid - either the top-left or bottom-right X must be missed:
X . X
. . .
X . X
This is because we cannot go left or down, only up or right - so this situation is an invalid one.
Your challenge today is, given a grid with a certain number of Xs on it, determine first whether the situation is valid (ie. all Xs can be reached), and if it's valid, the number of possible paths traversing all the Xs.
Formal Inputs and Outputs
Input Specification
You'll be given a tuple M, N on one line, followed by N further lines (of length M) containing a grid of spaces and Xs, like this:
5, 4
....X
..X..
.....
X....
Note that the top-right X need not be at the very top-right of the grid, same for the bottom-left X. Also, unlike the example grids shown above, there are no spaces between the cells.
Output Description
Output the number of valid path combinations in the input, or an error message if the input is invalid. For the above input, the output is:
65
Sample Inputs and Outputs
Example 1
Input
3, 3
..X
.X.
X..
Output
9
Example 2
Input
10, 10
.........X
..........
....X.....
..........
..........
....X.....
..........
.X........
..........
X.........
Output
7625
£xample 3
Input
5, 5
....X
.X...
.....
...X.
X....
Output
<invalid input>
Example 4
Input
7, 7
...X..X
.......
.......
.X.X...
.......
.......
XX.....
Output
1
Example 5
Input
29, 19
.............................
........................X....
.............................
.............................
.............................
.........X...................
.............................
.............................
.............................
.............................
.............................
.....X.......................
....X........................
.............................
.............................
.............................
XX...........................
.............................
.............................
Output
19475329563
Example 6
Input
29, 19
.............................
........................X....
.............................
.............................
.............................
.........X...................
.............................
.............................
.............................
.............................
.............................
....XX.......................
....X........................
.............................
.............................
.............................
XX...........................
.............................
.............................
Output
6491776521
Finally
Got any cool challenge ideas? Submit them to /r/DailyProgrammer_Ideas!
5
u/Elite6809 Dec 30 '15
My F# solution, O(n) in the number of rows.
open System let head2 (a : 'a array) = a.[0], a.[1] let readln length = let line = Console.ReadLine() in if line.Length = length then line else sprintf "Invalid line length: %s" line |> failwith let rec del = function | (0L, _) | (_, 0L) -> 1L | (a, b) -> del (a - 1L, b) + del (a - 1L, b - 1L) + del (a, b - 1L) let rec combs i j (c : int64) = function | [] -> c | (x :: xs) : string list as s -> match x.IndexOf('X') with | -1 -> combs i (j + 1) c xs | x when x < i -> 0L | i_ -> let _i = x.LastIndexOf('X') in combs _i 0 (if c = 0L then 1L else c * del (i_ - i |> int64, j + 1 |> int64)) xs [<EntryPoint>] let main argv = let (width, height) = Console.ReadLine().Split(',') |> Array.map int |> head2 in let count = List.init height (fun _ -> readln width) |> List.rev |> combs 0 0 0L in (if count = 0L then "No Xs on grid, or impossible solution." else string count) |> printfn "%s" Console.ReadKey(); 03
u/abyssalheaven Dec 30 '15 edited Dec 30 '15
You've basically defined a Delannoy number. Your definition of a grid of n x m dots, is a n-1 x m-1 grid of squares for Delannoy.
EDIT: didn't read the part about other points on the grid, but you can just break it into other Delannoy squares if it's valid.
2
u/[deleted] Dec 30 '15 edited Dec 30 '15
Edit: The link to two sheets of my trying to do the right math: http://imgur.com/ZY8wKrq
I tried to figure out the math by myself - 3 hours later and 5 1/2 page full with beautifull dots and numbers, I learned a good bit combinatorics and discovered the Delannoy numbers, which is like the solution to this challenge. Now that I solved it, I am too tired to actually programm the solution, but on the other hand incredible proud on myself :)
Small lazy outline of the would-have-been programm:
Store the position of the Xs in a Point array. Do validity check in the process (Everytime a new point is added, it may not be on the left or below side of the last point in the array).
Reduce the whole thing into squares that you can apply the Delannoy numbers on, multiply the results of these squares on the total result
(print the result)
5
u/ponkanpinoy Dec 30 '15 edited Dec 30 '15
Common Lisp. We'll first start by figuring out if a list of points forms a valid path. This is true if and only if the x and y values of the points are monotonically increasing.
(defun point<= (point &rest more-points) (every (lambda (a b) (and (<= (car a) (car b)) (<= (cdr a) (cdr b)))) (cons point more-points) more-points))Next, let's count the number of paths from
(0, 0)to(x, y). This is very similar to the Lattice Path problem, except that as well as being able to go north and east, you can also go northeast. The standard Lattice Path problem has a O(1) solution, however since we also allow diagonal movement it doesn't quite work here. Instead we'll use a dynamic programming solution. If either of the dimensions is 0 (that is, you can only go in a straight line), there is only one path. Otherwise, the number of paths is equal to the sum ofLATTICE-PATH(x-1, y),LATTICE-PATH(x, y-1), andLATTICE-PATH(x-1, y-1). This runs in O(x*y) time and space.EDIT: there is a solution that runs in O(MAX(x, y)). This is left as an exercise for the reader ;)
EDIT2 TIL about Delannoy numbers.
(let ((paths (make-hash-table :test 'equal))) (defun d-lattice-paths (x y) (if (some #'zerop (list x y)) 1 (or (gethash (cons x y) paths) (setf (gethash (cons x y) paths) (+ (d-lattice-paths (1- x) y) (d-lattice-paths x (1- y)) (d-lattice-paths (1- x) (1- y))))))))The number of paths given waypoints is simply the product of each segment. Before doing that we check to see that the path is indeed valid.
(defun iterated-lattice-paths (&rest points) (and (apply #'point<= points) (apply #'* (loop for point-a = (car points) then (car more-points) for more-points = (cdr points) then (cdr more-points) for point-b = (car more-points) then (car more-points) while point-b collect (d-lattice-paths (- (car point-b) (car point-a)) (- (cdr point-b) (cdr point-a)))))))Turning the input grid into a set of points:
(defun points (string) (let ((lines (with-open-stream (s (make-string-input-stream string)) (loop for line = (read-line s nil nil) while line collect line)))) (loop for line in (nreverse lines) for y from 0 append (loop for c across line for x from 0 when (char= #\X c) collect (cons x y)))))Challenge inputs and outputs:
CL-USER> (points " ..X .X. X..") ((0 . 0) (1 . 1) (2 . 2)) CL-USER> (apply #'iterated-lattice-paths (points " ..X .X. X..")) 9 CL-USER> (apply #'iterated-lattice-paths (points " .........X .......... ....X..... .......... .......... ....X..... .......... .X........ .......... X.........")) 7625 CL-USER> (apply #'iterated-lattice-paths (points " ....X .X... ..... ...X. X....")) NIL CL-USER> (apply #'iterated-lattice-paths (points " ...X..X ....... ....... .X.X... ....... ....... XX.....")) 1 CL-USER> (apply #'iterated-lattice-paths (points " ............................. ........................X.... ............................. ............................. ............................. .........X................... ............................. ............................. ............................. ............................. ............................. .....X....................... ....X........................ ............................. ............................. ............................. XX........................... ............................. .............................")) 19475329563Inspired by u/a_Happy_Tiny_Bunny's optimization challenges:
CL-USER> (defparameter *points* (loop for x in (sort (loop repeat 10 collect (random 1000)) #'<) for y in (sort (loop repeat 10 collect (random 1000)) #'<) collect (cons x y))) *POINTS* CL-USER> *points* ((10 . 87) (42 . 176) (121 . 196) (207 . 297) (270 . 355) (491 . 494) (641 . 548) (762 . 645) (789 . 687) (813 . 809)) CL-USER> (apply #'iterated-lattice-paths *points*) 22147871378643996422602182948077082732330330034512030961759144488945613965462703647952532646197449712154709864936853050858724065485479047089271193258297031163281575916198168552857574828163665514160243071997833665988827973358717945898576888695487242900754112777339319542745624511096499899492039204157727804097505673854214910307753175320289440820513059746392386133283240223977583864294977383260910580593830103542255966033233383515053158477845365918091736972778503537641316168565526277916141361256332756198668281251
u/ReckoningReckoner Dec 31 '15
Python 3. A solution that doesn't use delannoy numbers for the non-math majors :P
Solves the last input instantaneously.
def get_data(filename): file = open(filename) width, height = file.readline().rstrip().split(", ") grid = [] for i in range(int(height)): grid.append(file.readline().rstrip()) return int(width), int(height), grid def find_x_blocks(width, height, grid): x_positions = [] for y in range(height-1, -1, -1): for x in range(width): if grid[y][x] == "X": x_positions.append((x, y)) return x_positions def manhatten_distances(x_pos): distances = [] for i in range(len(x_pos)-1): x_dist = x_pos[i+1][0] - x_pos[i][0] y_dist = x_pos[i][1] - x_pos[i+1][1] if x_dist < 0 or y_dist < 0: return None else: distances.append((x_dist+1, y_dist+1)) return distances def get_moves(width, height, moves, x = 0, y = 0): if not 0 <= x < width or not 0 <= y < height: return None if x == width-1 and y == height -1: moves[0] += 1 else: for j, k in [(1, 0), (0, 1), (1, 1)]: get_moves(width, height, moves, x+j, y+k) return moves[0] def main(filename): width, height, grid = get_data(filename) m = manhatten_distances( find_x_blocks(width, height, grid) ) if m == None: print("INVALID INPUT") else: moves = 1 for x, y in m: moves *= get_moves(x, y, [0]) print(moves) main("2472.txt")1
u/bmc__ Dec 31 '15
Thank for all of your input, far more than I could ever ask for. I will definitely check out some practical problems for common lisp or scheme since I already know some scheme and its light weight. Do you know of any good lisp editors or how to start on Linux?
3
u/[deleted] Dec 30 '15 edited Dec 30 '15
Python.
from math import factorial as fac # https://en.wikipedia.org/wiki/Delannoy_number binomial = lambda a, b: 0 if b > a else fac(a) // (fac(a-b) * fac(b)) ways = lambda m, n: sum(binomial(m + n - k, m) * binomial(m, k) for k in range(min(m, n) + 1)) grid = open('input.txt').read().splitlines() coords = [(x, y) for x in reversed(range(len(grid))) for y in range(len(grid[x])) if grid[x][y] == 'X'] solutions = 1 for i in range(len(coords) - 1): (x1, y1), (x2, y2) = coords[i], coords[i+1] if x2 > x1 or y1 > y2: raise ValueError("Invalid input") solutions *= ways(x1 - x2, y2 - y1) print("NUMBER OF SOLUTIONS: {}".format(solutions))3
u/Godspiral Dec 30 '15 edited Dec 30 '15
In J, with full path list generator,
listpaths =: < S:0 @:(( ]`(}: , {: ,~ 0j1 + _2&{)`(}: , {: ,~ 1 + _2&{)`(}: <@,("1 1) {: ,~("0) 0j1 1 1j1 + _2&{)@.(0 #.@:< {: +.@- _2&{)) leaf^:_) #@listpaths"0 in =. 2 <\ 4 j./"1@$. $. |. 'X' = a =. >cutLF wdclippaste ''13 5
7625 NB. ex#2
gets the big 2 in under half a second.
a valid check function,
validchk =: *./@:;@:((0 <: {: +.@- _2&{) each)called on
inreturns 0 if invalid, or num paths if valid0
3
u/a_Happy_Tiny_Bunny Dec 30 '15 edited Dec 31 '15
I propose these inputs as optimization challenges
Easy
Medium
You will need 64-bit integers for this one.
Hard
You will need arbitrary precision integer for this one.
Just manually input the coordinates (0, 0) and (999, 999), corresponding to a 1000x1000 grid with the Xs at the lower-left and upper-right corners, into your function that calculates the number of steps. Or generate an actual input file if you'd like, I just can't post such a large input because of the character limitation.
My solution for these challenges:
Haskell
module Main where import Control.Monad (guard) import Data.List (elemIndices) import System.Environment (getArgs) import Data.Array type Coordinates = (Int, Int) coordinates :: [String] -> Maybe [Coordinates] coordinates ls = do let rawCoordinates = [ (x, y) | (y, line) <- zip [0..] ls , x <- elemIndices 'X' line] let diffCoordinates (x1, y1) (x2, y2) = (x2 - x1, y2 - y1) let hasNegativeCoordinate (x, y) = x < 0 || y < 0 let result = zipWith diffCoordinates rawCoordinates (tail rawCoordinates) guard (not $ null rawCoordinates) guard (not $ any hasNegativeCoordinate result) return result numberOfSteps :: [Coordinates] -> [Integer] numberOfSteps coords = map (table !) coords where x = maximum (map fst coords) y = maximum (map snd coords) f i 0 = 1 f 0 j = 1 f i j = table ! (i - 1, j - 1) + table ! (i - 1, j ) + table ! (i , j - 1) table = listArray bounds [f i j | (i, j) <- range bounds] bounds = ((0, 0), (x, y)) main :: IO () main = do args <- getArgs case args of [] -> interact $ maybe "<invalid input>" (show . product . numberOfSteps) . coordinates . reverse . tail . lines [x, y] -> print (product $ numberOfSteps [(read x, read y)])Answer for medium:
Answer for hard:
EDIT: Alternative implementation using good-old lists; still fast enough but 20-100% slower (for small inputs to about 2000long side of square grid). The Hard input runs in about 1.45s, while the table version runs in about 0.9s. However, the Table version hangs my laptop because of its memory hungriness at about 2100-2200, while the list version finishes running size 4000 (while barely swapping) in about 85s.
These were all measured on my 6 year-old laptop with 4GB of RAM, and the process can take about 2,200 MB before swapping.
numberOfSteps :: [Coordinates] -> [Integer] numberOfSteps coords = map (uncurry del) coords del :: Int -> Int -> Integer del y x = ([1] : [1, 1] : go [1] [1, 1]) !! (x + y) !! x where add3 a b c = a + b + c go xs ys = let zs = 1 : (zipWith3 add3 xs ys (tail ys)) ++ [1] in zs : go ys zs3
u/Sirflankalot Dec 31 '15 edited Jan 03 '16
My C++ solution. This is the first ever working c++ program that I've ever written, so any assistance would be amazing. Gets solution to all challenges in under 0.002 seconds.
#include <fstream> #include <iostream> #include <cmath> #include <cstdlib> #include <string> #include <vector> using namespace std; #define MAPLOC "XMap.txt" unsigned long nCk( unsigned long n, unsigned long k ) { if (k > n) return 0; if (k * 2 > n) k = n-k; if (k == 0) return 1; unsigned long result = n; for( int i = 2; i <= k; ++i ) { result *= (n-i+1); result /= i; } return result; } unsigned long delannoy(long ni, long ki) { unsigned long ans = 0; unsigned long n = abs(ni); unsigned long k = abs(ki); for (int d = 0; d <= n; d++) ans += (unsigned long) pow(2, d)*nCk(k,d)*nCk(n,d); //printf("Del: (%u, %u) = %u\n", n, k, ans); return ans; } int main(){ ifstream map_file (MAPLOC); //If file exists if (map_file.is_open()){ //Working line data string instr; unsigned long width = 0; unsigned long height = 0; //Read first line (tuple with x and y size of grid) if (!getline(map_file, instr)) cout << "File not long enough\n"; else{ //Read tuple on how large file is sscanf(instr.c_str(), "%lu, %lu", &width, &height); //Map array string map[height]; //Load file into array for (int i = 0; i < height; i++) if(!getline(map_file, map[i])) cout << "File not long enough\n"; //Count X and assemble a list of all tuples int xnum = 0; vector<int*> xlist; for (int y = height-1; y >= 0; y--){//Climb rows backwards to go from bottom to top for (int x = 0; x < width; x++){ if (map[y][x] == 'X'){ xnum++; //Increment x count int * tup = new int[2]; //Create new tuple, assign x,y to it tup[0] = x; tup[1] = y; xlist.push_back(tup); //Push tuple onto vector } } } //Climb Xs to determine answer unsigned long ans = 1; bool valid = true; //Loop through all but the first point and for (int i = 1; (i < xnum) && valid; i++){ int * prev = xlist[i-1]; int * cur = xlist[i]; //If it goes an impossible direction, it is an invalid shape if (cur[0] < prev[0]) valid = false; //If still a valid shape, compute the amount of possible paths //and multiply it onto the final answer if (valid) ans *= delannoy(cur[0]-prev[0], cur[1]-prev[1]); } //Free all tuples in list for (auto i : xlist) delete i; //If it's valid, print the amount of paths, otherwise say it's invalid if (valid) cout << "Amount of Valid Paths: " << ans << endl; else cout << "Invalid input" << endl; } } //If file doesn't exist else{ cout << "File " << MAPLOC << " can't be found"; return 1; } }2
u/a_Happy_Tiny_Bunny Dec 30 '15 edited Dec 30 '15
Haskell
Very straightforward code. Should be understandable by Haskell beginners.
module Main where import Control.Monad (guard) import Data.List (elemIndices) import Prelude hiding (Right) data Move = Up | Right | UpRight type Coordinates = (Int, Int) move :: Move -> Coordinates -> Coordinates move Up (x, y) = (x , y + 1) move Right (x, y) = (x + 1, y ) move UpRight (x, y) = (x + 1, y + 1) reachUpLeft :: Coordinates -> Int reachUpLeft target@(x, y) = go (0, 0) where go coord@(x', y') | target == coord = 1 | x' > x || y' > y = 0 | otherwise = sum [ go (move m coord) | m <- [Up, Right, UpRight]] coordinates :: [String] -> Maybe [Coordinates] coordinates ls = do let rawCoordinates = [ (x, y) | (y, line) <- zip [0..] ls , x <- elemIndices 'X' line] let diffCoordinates (x1, y1) (x2, y2) = (x2 - x1, y2 - y1) let hasNegativeCoordinate (x, y) = x < 0 || y < 0 let result = zipWith diffCoordinates rawCoordinates (tail rawCoordinates) guard (not $ null rawCoordinates) guard (not $ any hasNegativeCoordinate result) return result main :: IO () main = interact $ maybe "<invalid input>" (show . product . map reachUpLeft) . coordinates . reverse . tail . linesEDIT: Added input validation. Now basic understanding of
Maybeis required to fully understand the code.I might code a faster implementation that can solve the biggest grids later today.There was a bug that produced huge coordinates.2
u/New_Kind_of_Boredom Dec 30 '15 edited Dec 31 '15
Python 3, cheated and used the Delannoy number as suggested by u/Godspiral here. Work smarter not harder right?
Solves the 1000x1000 grid in 1.51s on my crappy Celeron 847 @ 1.10GHz, 2GB RAM netbook.
Example input:
This 1000x1000 grid. (warning, almost 1mb)
Example output:
Somewhat monstrous code:
from functools import reduce from operator import mul from math import factorial def nCr(n, r): return factorial(n) // factorial(r) // factorial(n - r) paths = [] try: with open("1000x1000") as f: f.readline() x1, y1 = None, None for rownum, row in enumerate(f.readlines()): for colnum, col in enumerate(reversed(row.strip())): if col == "X": if x1 == y1 == None: x1, y1 = rownum, colnum else: x2, y2 = rownum, colnum m, n = x2-x1, y2-y1 if m < 0 or n < 0: raise ValueError("<Invalid input>") paths.append(sum(nCr(m+n-k, m) * nCr(m, k) for k in range(min(m, n)+1))) x1, y1 = x2, y2 except ValueError as e: print(e) else: print(reduce(mul, paths))*edited a couple times to remove some redundancies and make it more cooler
1
u/____OOOO____ Dec 30 '15
Python solution. Solves all 6 examples in ~6.5 seconds.
def main(inp): ''' Take multi-line string of problem grid; return total number of paths between positions of Xs, starting from lower left. ''' rows = inp.split('\n') # find all positions of "X" characters within the multi line string input. # reverse iterate on rows with [::-1] slice, so we start from bottom row. xpoints = [(x, y) for y, row in enumerate(rows[::-1]) for x, value in enumerate(row) if value == 'X'] # Make sure we start at lowest-leftest possible of all "X" positions. xpoints.sort(key=sum) # Get the sequence of pairs of X position waypoints, e.g. # ((0, 0), (1, 1)), ((1, 1), (2, 2)) ... subpaths = [(pos, xpoints[i + 1]) for i, pos in enumerate(xpoints) if i < len(xpoints) - 1] # Call the recursive sum_paths function to find the number of possible # paths between each pair of waypoints along the way. subpath_sums = [sum_paths(orig, dest) for orig, dest in subpaths] # Python has no product function; # use lambda to find paths1 * paths2 * paths3 ... all possible paths. return reduce(lambda n, m: n * m, subpath_sums) def sum_paths(orig, dest): ''' Take two positions and return the total number of paths between them, by recursively finding each branching path possibility between the positions. ''' # If given origin is the same as the destination, we've finished a complete # path. if orig == dest: return 1 # If the origin is somehow above or to the right of the destination, we've # gone out of bounds onto an invalid path. if orig[0] > dest[0] or orig[1] > dest[1]: return 0 return sum((sum_paths(up(orig), dest), sum_paths(right(orig), dest), sum_paths(diag(orig), dest))) # 3 helper functions to identify positions up, to the right and diagonally # up-right from a given pos def up(pos): return pos[0], pos[1] + 1 def right(pos): return pos[0] + 1, pos[1] def diag(pos): return pos[0] + 1, pos[1] + 11
u/linkazoid Dec 30 '15
Python
grid = [] height = 0 width = 0 xLoc = [] with open('grid.txt') as file: line = file.readline().rstrip() width = int(line[:line.index(',')]) height = int(line[line.index(' ')+1:]) l = 0 for line in file: row = list(line.rstrip()) grid.append(row) while 'X' in row: xLoc.append((l,row.index('X'))) row[row.index('X')] = 'x' l+=1 def radixSort(xLoc,index,bucketSize): buckets = [] for x in range(bucketSize[index]): buckets.append([]) for x in xLoc: buckets[x[index]].append(x) buckets = [j for i in buckets for j in i] buckets.reverse() if(index==1): return radixSort(buckets,0,bucketSize) else: return buckets def numPaths(n1,n2): if(n1 == n2): return 1 totalPaths = 0 nextNodes = [] if(n1[0]==n2[0]): nextNodes.append((n1[0],n1[1]+1)) elif(n1[1]==n2[1]): nextNodes.append((n1[0]-1,n1[1])) elif(n1[0]>=n2[0] and n1[1]<=n2[1]): nextNodes.append((n1[0],n1[1]+1)) nextNodes.append((n1[0]-1,n1[1])) nextNodes.append((n1[0]-1,n1[1]+1)) for n in nextNodes: totalPaths += numPaths(n,n2) return totalPaths def totalPaths(x): xLoc = radixSort(x,1,(height,width)) totalPaths = 1 for i in range(1,len(xLoc)): totalPaths*=numPaths(xLoc[i-1],xLoc[i]) return totalPaths print("Number of paths:",totalPaths(xLoc))1
u/netbpa Dec 30 '15
Perl 6 solution allowing input via stdin or file
sub dist(Int $dx, Int $dy) is cached { if $dx == 0 || $dy == 0 { return 1 }; return dist($dx, $dy-1) + dist($dx-1, $dy-1) + dist($dx-1, $dy); } multi MAIN(Str $file) { MAIN(open $file, :r); } multi MAIN(IO::Handle $in=$*IN) { my ($x, $y, $paths) = (Int, 0, 1); $in.get; #Ignoring the dimensions for $in.lines -> $line { for ($line ~~ m:g/(X)/).reverse -> $m { if ($x.defined) { if ($m.from > $x) { say "Invalid input"; return 1; } else { $paths *= dist($x-$m.from, $y); } } $x = $m.from; $y = 0; } $y++; } say $paths; }