Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

f# - looping through array

Tags:

f#

I have decided to take up f# as my functional language.

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

for example (simplified): 1234567890

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

Heres my problem, I read my file of numbers, I can split it using "\n" and now i have each line, and then I try to convert it to an char array, but the problem comes here. I can't access each element of that 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 array, i take the first array (for testing only), and i try to convert it to list, and then get the length of the list. But this length is the length of how many arrays i have (ie, 1). It should be 50 as thats how many elements there are in the array.

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

like image 763
masfenix Avatar asked Dec 03 '22 16:12

masfenix


2 Answers

Seq.take is still returning a seq<char array>. To get only the first array you could use Seq.nth 0.

like image 110
dahlbyk Avatar answered Jan 06 '23 06:01

dahlbyk


My final answer:

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

is what i got finally and it's working :).

Bascially after I convert it to charArray, i make it a sequence. So now i have a sequence of sequence. Then I can loop through each seqquence.

like image 24
masfenix Avatar answered Jan 06 '23 07:01

masfenix