Grabbing a subset of a range if a particular value is found?

Ali Çehreli acehreli at yahoo.com
Tue Sep 24 14:20:29 PDT 2013


On 09/24/2013 02:10 PM, Gary Willoughby wrote:

 > import std.algorithm;
 > import std.range;
 > import std.stdio;
 >
 > /**
 >   * Each new term in the Fibonacci sequence is generated by adding the
 > previous
 >   * two terms. By starting with 1 and 2, the first 10 terms will be: 1,
 > 2, 3, 5,
 >   * 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci
 >   * sequence whose values do not exceed four million, find the sum of the
 >   * even-valued terms.
 >   */
 > void main()
 > {
 >      recurrence!("a[n-1] + a[n-2]")(1, 2)
 >          .until!("a > 4_000_000")
 >          .filter!(a => a % 2 == 0)
 >          .reduce!("a + b")
 >          .writeln;
 > }
 >
 > I love chaining stuff up like this, it makes the solution easy to
 > understand and read. As Walter said in one of his talks, the code looks
 > like the problem being solved. I'm loving it! :)

Awesome! :) And if you want to stick with non-string functions:

     recurrence!((a, n) => a[n-1] + a[n-2])(1, 2)
         .until!(a => a > 4_000_000)
         .filter!(a => a % 2 == 0)
         .reduce!((sum, a) => sum + a)
         .writeln;

Ali



More information about the Digitalmars-d-learn mailing list