F # - loop through an array

I decided to use f # as my functional language.

My problem: give a bunch of 50digits in the file, get the first 10 digits of the sum of each line. (Euler's problem for those who know)

e.g. (simplified): 1234567890

The sum is 45
The first "ten" digits or in our case the "first" digit is 4.

Here is my problem, I read my numbers file, I can split it with "\ n", and now I have each line, and then I try to convert it to a char array, but the problem is here. I cannot access every element of this array.

let total =
    lines.Split([|'\n'|])
    |> Seq.map  (fun line -> line.ToCharArray())
    |> Seq.take 1
    |> Seq.to_list  
    |> Seq.length

I get each line, convert it to an array, I take the first array (for testing only), and I try to convert it to a list, and then get the length of the list. But this length is the length of the number of arrays (i.e. 1). This should be 50, because the number of elements in the array.

Does anyone know how to bind it to access each char?

+3
source share
5 answers

My final answer is:

let total =
    lines.Split([|'\n'|])
    |> Seq.map (fun line -> line.ToCharArray() |> Array.to_seq)      
    |> Seq.map (fun eachSeq -> eachSeq 
                               |> Seq.take 50 //get rid of the \r
                               |> Seq.map (fun c -> Double.Parse(c.ToString()))
                               |> Seq.skip 10
                               |> Seq.sum                                
                               )
    |> Seq.average

- this is what I finally got, and it works :).

After I convert it to charArray, I make it sequential. So now I have a sequence of sequence. Then I can go through each sequence.

+4
source

Seq.takestill returns seq<char array>. To get only the first array, you can use Seq.nth 0.

+5

100%, , , - :

lines.Split([|'\n'|) |> Seq.map (fun line -> line.Length)

This converts each line into a sequence of integers representing the length of each line.

+3
source

Here is my solution:

string(Seq.sumBy bigint.Parse (data.Split[|'\n'|])).Substring(0, 10)
+3
source

I copied the data to a line, each line separated by x. Then the answer is one line (wrapped for SO):

let ans13 = data |> String.split ['x'] |> Seq.map Math.BigInt.Parse 
                                                      |> Seq.reduce (+)

If you are reading it from a file, you must add the code to read the file:

let ans13 = IO.File.ReadAllLines("filename") |> Seq.map Math.BigInt.Parse
                                                            |> Seq.reduce (+)

Edit: Actually, I'm not sure we're talking about the same Euler problem - this is for 13, but your description sounds a little different. To get the first 10 digits after summing, do:

printfn "%s" <| String.sub (string ans13) 0 10
+1
source

Source: https://habr.com/ru/post/1702870/


All Articles