I more or less agree with most of the criticisms of this idea that I've read, but I felt like writing a solution anyway.

sub geometric { my @known = @_; my $prev = shift @known; my $curr = shift @known; return undef if ! $prev; my $factor = $curr / $prev; while ( @known ) { $prev = $curr; $curr = shift @known; return undef if ! $prev; return undef if $factor != $curr / $prev; } return $curr * $factor; } sub arith { my @known = @_; my $prev = shift @known; my $curr = shift @known; my $diff = $curr - $prev; while ( @known ) { $prev = $curr; $curr = shift @known; return undef if $diff != $curr - $prev; } return $curr + $diff; } sub series { my @known = @_; return undef if scalar @known < 2; my @next_gen = ( \&arith, \&geometric ); my @next = grep { defined } map { $_->( @known ) } @next_gen; return undef if scalar @next != 1; return $next[0]; }

Note that this doesn't pass all tests or even some of the ones that look easy. I have series() written to look at a list of sub references and ask each one for a "next in list" for the proposed list. If exactly one of them gets an answer, I return that answer, otherwise undef.

If the list of guessers becomes large or expensive, it would be more efficient to ask each one and fail as soon as two return answers.

It's easy to add other guessers, and it won't ever give an answer if the question is ambiguous. This may be odd. The series "0, 0" has an answer because it won't detect as geometric, but "1, 1" does not have an answer because it could be either one, even though the next in sequence is '1' both ways.


In reply to Re: Challenge: Simple algorithm for continuing series of integers by kyle
in thread Challenge: Simple algorithm for continuing series of integers by moritz

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.