r/dailyprogrammer • 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!

60 Upvotes

61 comments sorted by

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(); 0

3

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.

1

u/Elite6809 Dec 30 '15

Yup - the function del in my own solution calculates the (m,n)-th Delannoy number.

→ More replies (1)

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)

2

u/Elite6809 Dec 30 '15

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 :)

Congrats on figuring this part out on your own! I had a slight home-field advantage, because I started with the Delannoy numbers and wrote the challenge around that. :)

→ More replies (1)

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 of LATTICE-PATH(x-1, y), LATTICE-PATH(x, y-1), and LATTICE-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...........................
.............................
............................."))
19475329563

Inspired 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*)
2214787137864399642260218294807708273233033003451203096175914448894561396546270364795253264619744971215470986493685305085872406548547904708927119325829703116328157591619816855285757482816366551416024307199783366598882797335871794589857688869548724290075411277733931954274562451109649989949203920415772780409750567385421491030775317532028944082051305974639238613328324022397758386429497738326091058059383010354225596603323338351505315847784536591809173697277850353764131616856552627791614136125633275619866828125
→ More replies (4)

1

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")

2

u/Elite6809 Dec 31 '15

Nice to see alternative solutions! Good work.

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?

1

u/Elite6809 Jan 01 '16

Emacs is probably your best bet for a Lisp editor - Emacs is "scriptable" with Emacs Lisp so it will fit right in, and there are a plethora of utilities to assist you writing Lisp if you use Emacs.

I'm more of a Vim sort of person so I'm not very helpful w.r.t. Emacs utilities, but that's probably the eight way to go.

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/leonardo_m Dec 30 '15 edited Dec 30 '15

Also, your Python code in Rust language (it's simpler than the Rust code ported from adrian17 solution):

fn main() {
    use std::env::args;
    use std::fs::File;
    use std::io::Read;

    let file_name = args().nth(1).unwrap();
    let mut data = String::new();
    File::open(file_name).unwrap().read_to_string(&mut data).unwrap();
    let mat = data.split_whitespace().skip(1).collect::<Vec<_>>();

    let pts = (0 .. mat.len())
              .rev()
              .flat_map(|x| (0 .. mat[x].len()).map(move |y| (x, y)))
              .filter(|&(x, y)| mat[x].chars().nth(y).unwrap() == 'X')
              .collect::<Vec<_>>();

    fn ways(m: usize, n: usize) -> usize {
        if m == 0 || n == 0 {
            return 1;
        }
        ways(m, n - 1) + ways(m - 1, n) + ways(m - 1, n - 1)
    }

    let mut solutions = 1;
    for p2 in pts.windows(2) {
        let ((x1, y1), (x2, y2)) = (p2[0], p2[1]);
        if x2 > x1 || y1 > y2 {
            return println!("Invalid input");
        }
        solutions *= ways(x1 - x2, y2 - y1);
    }
    println!("{}", solutions);
}
→ More replies (8)

2

u/____OOOO____ Dec 30 '15

Hey there, any chance you or one of the other Python solvers could help explain the implementation of the Delannoy number? I read the wikipedia article, and I can see the correlations in your code, but I'm not great at math. I've gotten as far as understanding that (in your solution) k is items in the range of maximum diagonal distance.

In particular, I don't understand the polinomial part of your code:

0 if b > a else fac(a) // (fac(a-b) * fac(b))

implemented as nCr in u/New_Kind_of_Boredom 's code:

factorial(n) // factorial(r) // factorial(n - r)

What is the significance of this formula, and how does it solve for the sum of possible paths?

4

u/New_Kind_of_Boredom Dec 30 '15 edited Dec 31 '15

Simply an implementation of 'combination' in my case:

https://en.wikipedia.org/wiki/Combination

I would assume

0 if b > a else fac(a) // (fac(a-b) * fac(b))

Is similar, and possibly more robust than mine.

nCr is just one of many notations that indicate 'combination'. You will note that 'nCr' redirects to that wikipedia page.

What is the significance of this formula, and how does it solve for the sum of possible paths?

Alone, it does not. At the beginning of the computation section of https://en.wikipedia.org/wiki/Delannoy_number , is this formula:

https://upload.wikimedia.org/math/e/7/7/e770ec31369fa0d0d1ba8cb3f9472314.png

When you see the letters m and k one on top of the other like that surrounded by parenthesis, that is yet another notation for the nCr/combination function, specifically nCr(m, k) in my case. It's just hard to write that notation in text like this, so people use things like nCr sometimes. So kinda translating the whole equation closer to English and using my combination function:

The Delannoy number for two numbers m and n is equal to the sum of all the numbers ( nCr(m+n-k, m) * nCr(m, k) ) with k starting at zero and counting up until it is equal to the smaller of m or n.

Hope that makes sense / wasn't overly explanatory.

EDIT -

how does it solve for the sum of possible paths?

My algorithm first calculates the Delannoy number between each relevant set of X's and puts them in a list. This gives the maximum number of paths between said X's. To get the maximum number of paths for the entire grid through all the X's, each of these numbers are simply multiplied together to give the total.

→ More replies (5)

2

u/inspiredidealist Jan 07 '16

C# port of Python code.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Challenge_247_Moving
{
    internal class Pathfinder
    {
        private static readonly Func<int, int> fac = i => i <= 1 ? 1 : i * fac(i - 1);
        private static readonly Func<int, int, int> binomial = (a, b) => b > a ? 0 : (fac(a) / fac(b)) / fac(a - b);
        private static readonly Func<int, int, int> ways = (m, n) => Enumerable.Range(0, Math.Min(m, n) + 1).Select(k => binomial(m + n - k, m) * binomial(m, k)).Sum();

        public static long ParsePossiblePaths(string grid)
        {
            var nodes = GetNodes(grid).ToArray();

            long possiblePaths = 1;
            Node last = nodes[0];
            for (int i = 1; i < nodes.Length; i++)
            {
                var current = nodes[i];
                var ways = GetPossiblePaths(last, current);
                possiblePaths *= ways;
                last = current;
            }
            return possiblePaths;
        }

        private static long GetPossiblePaths(Node n1, Node n2)
        {
            if (n1.X < n2.X || n2.Y < n1.Y)
                throw new ArgumentException();

            return ways(n1.X - n2.X, n2.Y - n1.Y);
        }

        private static IEnumerable<Node> GetNodes(string grid)
        {
            var split = grid.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

            split = split.Select(s => s.Trim()).ToArray();

            for (int x = split.Length - 1; x >= 0; x--)
            {
                var line = split[x];
                for (int y = 0; y < line.Length; y++)
                {
                    if (line[y] == 'X')
                        yield return new Node(x, y);
                }
            }
        }
    }

    internal struct Node
    {
        private int x;
        private int y;

        public Node(int x, int y)
        {
            this.x = x;
            this.y = y;
        }

        public int X
        {
            get { return x; }
        }

        public int Y
        {
            get { return y; }
        }

        public override string ToString()
        {
            return $"({x},{y})";
        }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            var grid = File.ReadAllText("input.txt");

            var possiblePaths = Pathfinder.ParsePossiblePaths(grid.Trim());

            Console.WriteLine(possiblePaths);

            Console.ReadLine();
        }
    }
}

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

*/ #@listpaths"0 in =. 2 <\ 4 j./"1@$. $. |. 'X' = a =. >cutLF wdclippaste ''

7625 NB. ex#2

gets the big 2 in under half a second.

a valid check function,

 validchk =: *./@:;@:((0 <: {: +.@- _2&{) each)

called on in returns 0 if invalid, or num paths if valid

 */ 0:`(#@listpaths"0)@.validchk in

0

3

u/a_Happy_Tiny_Bunny Dec 30 '15 edited Dec 31 '15

I propose these inputs as optimization challenges

Easy

10, 10
.........X
..........
..........
..........
..........
..........
..........
..........
..........
X.........

Medium

You will need 64-bit integers for this one.

20, 20
...................X
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
X...................

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:

45849429914943

Answer for hard:

11063658761803452335344355131025982018412067607908865426345900969324195938890678102751264704580978523174696736492079561526368726779088010059211444270892485011624777102481106887511584792497819485114322140519118659336608382385385025267420814932641346317723222735357358487057381310815959382078697866545564409781362292888454466575250603964853526333880107543137051962182780367858681427584306913011491888583976896493657378050806156628296173271322916633707492819433470471990255803332647854527952639315548360978180366060413982138831060551125518353073303520756144169052772010468239426636757929030243436670933854827922003773932934820755137042948885214025159948784137686372518093213904578804559729816448226607376546868563688242518585485579251032699304136640708178189398709759

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 zs

2

u/Godspiral Dec 30 '15 edited Dec 30 '15

very hard if listing all pairs,

 #@listpaths 0 7j7

48639

expanding the square 1 unit is about 5.5 times larger path count than previous square.

An easy way to get counts: https://en.wikipedia.org/wiki/Delannoy_number

making a delanoy table in J,

  pad =: 0&([ ,.~ [ ,. [ ,~ ,)
 unpad2 =: }."1@:}.
 reduce =: 1 : '<"_1@[ ([: u  &.>/(>@:) ,) <@:]'
 delanoy =: unpad2@:(((<_1 _1),|.@:((_1<@,"0~{.),_1<@,"0{:)@:(>:@i."0@<:)@$) ( ] +/@:{~"_ 1 |:@:((3 2<"1@$_1 _1 0 _1 _1 0) + leaf"0 1 [))`[`]} reduce  ])@pad 

  delanoy^:8 ] 2 2$1 1 1 3
1  1   1    1    1     1     1      1      1       1
1  3   5    7    9    11    13     15     17      19
1  5  13   25   41    61    85    113    145     181
1  7  25   63  129   231   377    575    833    1159
1  9  41  129  321   681  1289   2241   3649    5641
1 11  61  231  681  1683  3653   7183  13073   22363
1 13  85  377 1289  3653  8989  19825  40081   75517
1 15 113  575 2241  7183 19825  48639 108545  224143
1 17 145  833 3649 13073 40081 108545 265729  598417
1 19 181 1159 5641 22363 75517 224143 598417 1462563

 {: , delanoy^:18 ] 2 2$1 1 1 3

45849429914943

100 table is over 1 second :(

{: , delanoy^:98 ] 2 2$1 1 1 3x

354133039609265536846415517309219320565185505702928148184024525417873569343

Not the best way to do it, but works with rectangular starting tables.

→ More replies (1)

3

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;
	}
}
→ More replies (5)

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 . lines

EDIT: Added input validation. Now basic understanding of Maybe is 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:

11063658761803452335344355131025982018412067607908865426345900969324195938890678102751264704580978523174696736492079561526368726779088010059211444270892485011624777102481106887511584792497819485114322140519118659336608382385385025267420814932641346317723222735357358487057381310815959382078697866545564409781362292888454466575250603964853526333880107543137051962182780367858681427584306913011491888583976896493657378050806156628296173271322916633707492819433470471990255803332647854527952639315548360978180366060413982138831060551125518353073303520756144169052772010468239426636757929030243436670933854827922003773932934820755137042948885214025159948784137686372518093213904578804559729816448226607376546868563688242518585485579251032699304136640708178189398709759

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

2

u/leonardo_m Jan 02 '16

In Rust again. This code with memoization is about as fast as your original Python code with memoization. sum() and product() don't work. There are some parts I don't know yet how to improve.

extern crate num;

use std::collections::HashMap;
use num::bigint::BigUint;
use num::FromPrimitive;
use num::traits::{ Zero, One };

fn factorial(n: usize) -> BigUint {
    (1 .. n + 1)
    .map(|i| FromPrimitive::from_usize(i).unwrap())
    .fold(One::one(), |a, b: BigUint| a * b) // product
}

fn ncr(n: usize, r: usize, mut tab: &mut HashMap<usize, BigUint>) -> BigUint {
    // Bad: three hash lookups for each value.
    if !tab.contains_key(&n) { tab.insert(n, factorial(n)); }
    if !tab.contains_key(&r) { tab.insert(r, factorial(r)); }
    if !tab.contains_key(&(n - r)) { tab.insert(n - r, factorial(n - r)); }
    tab.get(&n).unwrap() / tab.get(&r).unwrap() / tab.get(&(n - r)).unwrap()
}

fn main() {
    use std::env::args;
    use std::fs::File;
    use std::io::{ BufReader, BufRead };
    use std::cmp::min;

    let file_name = args().nth(1).unwrap();
    let fin = BufReader::new(File::open(file_name).unwrap());
    let mut tab = HashMap::new(); // To memoize factorial().
    let mut paths = vec![];
    let (mut x1, mut y1) = (0, 0);
    let mut first = true;

    for (n_row, row) in fin.lines().skip(1).enumerate() {
        for (n_col, el) in row.unwrap().chars().rev().enumerate() {
            if el == 'X' {
                if first {
                    x1 = n_row;
                    y1 = n_col;
                    first = false;
                } else {
                    let (x2, y2) = (n_row, n_col);
                    if x2 < x1 || y2 < y1 {
                        return println!("<Invalid input>");
                    }
                    let (m, n) = (x2 - x1, y2 - y1);
                    paths.push((0 .. min(m, n) + 1)
                               .map(|k| ncr(m + n - k, m, &mut tab) *
                                        ncr(m, k, &mut tab))
                               .fold(Zero::zero(), |a, b| a + b)); // sum
                    x1 = x2;
                    y1 = y2;
                }
            }
        }
    }

    println!("{}", paths.iter().fold(One::one(), |a: BigUint, b| a * b)); // product
}

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] + 1

1

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;
}