Search code examples
f#gridmultiplication

Formatting multiplication table f# output


I am trying to create a N x M multiplication table program using f# where the n and m values are specified by the user and the table is calculated and stored in a 2D array and displayed on the console.

Any help would be much appreciated on getting my array to be displayed in a format similar to:

Desired Output

as opposed to the one in my program

Current Output

My Source Code is

open System

let func() =
        let multiplication  n m = Array2D.init n m (fun n m -> n * m)


        printf "Enter N Value: "
        let nValue = Console.ReadLine() |> System.Int32.Parse

        printf "\nEnter M Value: "
        let mValue = Console.ReadLine() |> System.Int32.Parse

        let grid = multiplication nValue mValue 


        printfn "\n\n%A" grid

func()

Also I would like to know how I can get my values to start from 1 as opposed to 0.

Any help much would be much appreciated as I'm a beginner in F#.


Solution

  • All you gotta do is add 1 to n and m before multiplying them together, such as

    let multiplication  n m = Array2D.init n m (fun n m -> (n + 1) * (m + 1))
    

    However we do have some parenthesis madness here, you could refactor it as following:

    let myMultFunction n m = (n + 1) * (m + 1)
    let multiplication n m = Array2D.init n m myMultFunction
    

    The formatting would be a bit trickier, and using for loops is kinda cheating, and not very F#, but given we are using 2d arrays which aren't functional in nature i figured I could sneak this by ;)

    printfn "A multiplication table:"
    printf "   "
    for col in 0 .. mValue - 1 do
        printf "%d\t" (col + 1)
    
    printfn ""
    for row in 0 .. nValue - 1 do
        for col in 0 .. mValue - 1 do
                if col = 0 then
                        printf "\n%d| " (row + 1)
                printf "%d\t" grid.[row, col]