From: Niklas Holsti <niklas.holsti@tidorum.invalid>
Subject: Re: Inefficient algorithms
Date: Sat, 11 Sep 2010 09:54:30 +0300
Date: 2010-09-11T09:54:30+03:00 [thread overview]
Message-ID: <8f0nd6F8ucU1@mid.individual.net> (raw)
In-Reply-To: <1f6f73cd-f5ff-4408-a1d7-c9ca7dfa70ee@m35g2000prn.googlegroups.com>
Rick wrote:
> I am working on a class in algorithmic efficiency and, to make a
> point, need an algorithm that runs O(2^n) - a factoring algorithm
> perhaps. All I can find is 'C' code I can't decipher. Can someone
> please help with an Ada example.
Perhaps the canonical example is this: you are given a Boolean formula
containing n Boolean variables. Find a valuation (a value, True or
False, for each variable) that makes the formula True. The O(2^n)
algorithm tries each of the 2^n valuations in some order, evaluates the
formula for this valuation, and stops when True.
In Ada, something like:
N : constant := ...;
type Valuation is array (1 .. N) of Boolean;
-- Valuation(k) is the value of Boolean variable number k.
function Formula (Inputs : Valuation) return Boolean
is begin
return <complex formula>;
end Formula;
The search through all possible valuations is logically like an n-deep
nested loop of the form
for Value1 in Boolean loop
for Value2 in Boolean loop
...
for Value_n in Boolean loop
if Formula ((Value1, Value2, ..., Value_n)) then
<exit and report success>.
end if;
end loop;
...
end loop;
end loop;
Since N is a variable, you cannot write out this N-deep loop nest in the
Ada program. Instead, use a recursive function that is given a partial
valuation, for example a valuation that gives the values for the
variables 1 .. k, and then extends the valuation by trying both False
and True values for variable k+1, calling itself recursively until it
has a full valuation, when it calls Formula to see if this full
valuation is a solution.
HTH,
--
Niklas Holsti
Tidorum Ltd
niklas holsti tidorum fi
. @ .
next prev parent reply other threads:[~2010-09-11 6:54 UTC|newest]
Thread overview: 23+ messages / expand[flat|nested] mbox.gz Atom feed top
2010-09-11 4:24 Inefficient algorithms Rick
2010-09-11 6:51 ` J-P. Rosen
2010-09-13 3:45 ` Robert A Duff
2010-09-11 6:54 ` Niklas Holsti [this message]
2010-09-11 7:07 ` Niklas Holsti
2010-09-11 9:07 ` Rick
2010-09-11 15:05 ` Niklas Holsti
2010-09-17 5:26 ` Rick
2010-09-11 9:20 ` Ludovic Brenta
2010-09-11 9:23 ` Ludovic Brenta
2010-09-11 11:20 ` Niklas Holsti
2010-09-11 18:29 ` Peter C. Chapin
2010-09-11 14:28 ` stefan-lucks
2010-09-12 1:04 ` Wilson
2010-09-12 1:53 ` Rick
2010-09-12 8:35 ` Georg Bauhaus
2010-09-12 11:56 ` stefan-lucks
2010-09-15 1:11 ` BrianG
-- strict thread matches above, loose matches on Subject: below --
2010-09-15 8:51 Rick
2010-09-15 21:45 ` John B. Matthews
2010-09-16 12:05 ` Chad R. Meiners
2010-09-16 20:19 ` John B. Matthews
2010-09-17 5:24 ` Rick
replies disabled
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox