2D PHP Pattern Creator Altgorithm - algorithm

I'm looking for an algorithm to help me build 2D patterns based on rules. The idea is that I could write a script using a given site of parameters, and it would return a random, 2-dimensional sequence up to a given length.
My plan is to use this to generate image patterns based on rules. Things like image fractals or sprites for game levels could possibly use this.
For example, lets say that you can use A, B, C, & D to create the pattern. The rule is that C and A can never be next to each other, and that D always follows C. Next, lets say I want a pattern of size 4x4. The result might be the following which respects all the rules.
A B C D
B B B B
C D B B
C D C D
Are there any existing libraries that can do calculations like this? Are there any mathematical formulas I can read-up on?

While pretty inefficient concering runtime, backtracking is an often used algorithm for such a problem.
It follows a simple pattern, and if written correctly, you can easily replace a rule set into it.

Define your rule data structures; i.e., define the set of operations that the rules can encapsulate, and define the available cross-referencing that can be done. Once you've done this, you should have a clearer view of what type of algorithms to use to apply these rules to a potential result set.

Supposing that your rules are restricted to "type X is allowed to have type Y immediately to its left/right/top/bottom" you potentially have situations where generating possible patterns is computationally difficult. Take a look at Wang Tiles (a good source is the book Tilings and Patterns by Grunbaum and Shephard) and you'll see that with the states sets of rules you might define sets of Wang Tiles. Appropriate sets of these are Turing Complete.
For small rectangles, or your sets of rules, this may only be of academic interest. As mentioned elsewhere a backtracking approach might be appropriate for your ruleset - in which case you may want to consider appropriate heuristics for the order in which new components are added to your grid. Again, depending on your rulesets, other approaches might work. E.g. if your ruleset admits many solutions you might get a long way by randomly allocating many items to the grid before attempting to fill in remaining gaps.

Related

How can Clojure data-structures best be tagged with a type?

I'm writing a program that's manipulating polynomials. I'm defining polynomials recursively as either a term (base case) or a sum or product of polynomials (recursive cases).
Sums and products are completely identical as far as their contents are concerned. They just contain a sequence of polynomials. But they need to be processed very differently. So to distinguish them I have to somehow tag my sequences of polynomials.
Currently I have two records - Sum and Product - defined. But this is causing my code to be littered with the line (:polynomials sum-or-product) to extract the contents of polynomials. Also printing out even small polynomials in the REPL produces so much boilerplate that I have to run everything through a dedicated prettyprinting routine if I want to make sense of it.
Alternatives I have considered are tagging my sums and products using metadata instead, or putting a + or * symbol at the head of the sequence. But I'm not convinced that either of these approaches are good style and I'm wondering if there's perhaps another option I haven't considered yet.
Putting a + or * symbol at the head of the sequence sounds like it would print out nicely. I would try implementing the processing of these two different "types" via multimethods, which keeps the calling convention neat and extensible. That document starts from object-oriented programmin view, but the "area of a shape" is a very neat example on what this approach can accomplish.
In your case you'd use first of the seq to determine if you are dealing with a sum or a product of polynomials, and the multimethod would automagically use the correct implementation.

Why are epsilon transitions used in NFA?

I'm trying to understand how to create NFA-s from regular expressions, but I am really confused from epsilon transitions. I have this example in my textbook , but I don't understand why epsilon transitions are used and how does one know when to use them.
In general, espilon-transitions are used when they are convenient. For example, when constructing an NFA from a regular expression, you start by constructing small parts of the automaton corresponding to parts of the expression. To connect them, you need to put a transition. But if there is no symbol to be read there, an epsilon transition is a simple way to do this. They are, however never necessary, you can always find a solution without them.
In your example, just apply the algorithm described in your textbook. It tells you when to use them.
The epsilon transitions
from 1 to 2 probably connects the parts for (a|b)* and for ac
1->5 and 8->1 probably result from the *
5->6 and 5->7 probably result from the alternative in |
Epsilon-transitions in NFAs are a natural representation of choice or disjunction or union in regular expressions. That is, a regular expression like r + s (or r | s or r U s depending on your preferred notation) is naturally represented as an NFA consisting of two independent NFAs, one for r and one for s, joined using e-transitions as follows:
e
----->q0----->(r)
|
| e
|
V
(s)
When used to connect states in more complicated ways, the effect may not be as easy or natural to describe, but essentially these transitions let you choose unconditionally among multiple options. So, if I have seen a part of the input already and there are a few different ways the string could end, I can represent that by using e-transitions to states that handle the different possibilities.
In your example, the e-transitions are not really serving any very useful function and are merely artifacts of the conversion algorithm you have used. That algorithm includes them because, in the general case, they may be useful or necessary. In your specific case this was not true, so they look out of place.

Consistent formulations of sets in Coq?

I'm quite new at Coq and trying to develop a framework based on my research. My work is quite definition-heavy and I'm having trouble encoding it because of how Coq seems to treat sets.
There are Type and Set, which they call 'sorts', and I can use them to define a new set:
Variable X: Type.
And then there's a library encoding (sub)sets as 'Ensembles', which are functions from some Type to a Prop. In other words, they are predicates on a Type:
Variable Y: Ensemble X.
Ensembles feel more like proper mathematical sets. Plus, they are built upon by many other libraries. I've tried focussing on them: defining one universal set U: Set, and then limiting myself to (sub)Ensembles on U. But no. Ensembles cannot be used as types for other variables, nor to define new subsets:
Variable y: Y. (* Error *)
Variable Z: Ensemble Y. (* Error *)
Now, I know there are several ways to get around that. The question "Subset parameter" offers two. Both use coercions. The first sticks to Sets. The second essentially uses Ensembles (though not by name). But both require quite some machinery to accomplish something so simple.
Question: What is the recommended way of consistently (and elegantly) handling sets?
Example: Here's an example of what I want to do: Assume a set DD. Define a pair dm = (D, <) where D is a finite subset of DD and < is a strict partial order on D.
I'm sure that with enough tinkering with coercions or other structures, I could accomplish it; but not in a particularly readable way; and without a good intuition of how to manipulate the structure further. For example, the following type-checks:
Record OrderedSet {DD: Set} : Type := {
D : (Ensemble DD);
order : (relation {d | In _ D d});
is_finite : (Finite _ D);
is_strict_partial : (is_strict_partial_order order)
}.
But I'm not so sure it's what I want; and it certainly doesn't look very pretty. Note that I'm going backwards and forwards between Set and Ensemble in a seemingly arbitrary way.
There are plenty of libraries out there which use Ensembles, so there must be a nice way to treat them, but those libraries don't seem to be documented very well (or... at all).
Update: To complicate matters further, there appear to be a number of other set implementations too, like MSets. This one seems to be completely separate and incompatible with Ensemble. It also uses bool rather than Prop for some reason. There is also FSets, but it appears to be an outdated version of MSets.
It's been (literally) years since I used Coq, but let me try to help.
I think mathematically speaking U: Set is like saying U is an universe of elements and Ensemble U would then mean a set of elements from that universe. So for generic notions and definitions you will almost certainly use Set and Ensemble is one possible way about reasoning about subsets of elements.
I'd suggest that you take a look at great work by Matthieu Sozeau who introduced type classes to Coq, a very useful feature based on Haskell's type classes. In particular in the standard library you will find a class-based definition of a PartialOrder that you mention in your question.
Another reference would be the CoLoR library formalizing notions needed to prove termination of term rewriting. It has a fairly large set of generic purpose definitions on orders and what-not.

Function to detect conflicting mathematical operators in VB6

I've developed a program which generates insurance quotes using different types of coverages based on state criteria. Now I want to add the ability to specify 'rules'. For example we may have 3 types of coverage (we'll call them UM, BI, and PD). Well some states don't allow PD to be greater than BI and other states don't allow UM to exist without BI. So I've added the ability for the user to create these rules so that when the quote is generated the rule will be followed and thus no state regulations will be violated when the program generates the quote.
The Problem
I don't want the user to be able to select conflicting rules. The user can select any of the VB mathematical operators (>, <, >=, <=, =, <>) and set a coverage on either side. They can do this multiple times (but only one at a time) so they might end up with a list of rules like this:
A > B
B > C
C > A
As you can see, the last rule conflicts with the previously set rules. My solution to this was to validate the list each time the user clicks 'Add rule to list'.
Pretend the 3rd list item is not yet in the list but the user has clicked 'add rule' to put it in the list. The validation process first checks to see if both incoming variables have already been used on the same line. If not, it just searches for the left side incoming variable (in this case 'C') in the already created list. if it finds it, it then sets tmp1 equal to the variable across from the match (tmp1 = 'B'). It then does the same for the incoming variable on the right side (in this case 'A'). Then tmp2 is set equal to the variable across from A (tmp2 = 'B'). If tmp1 and tmp2 are equal then the incoming rule is either conflicting OR is irrelevant regardless of the operators used. I'm pretty sure this is solid logic given 3 variables. However, I found that adding any additional variables could easily bypass my validation. There could be upwards of 10 coverage types in any given state so it is important to be able to validate more than just 3.
Is there any uniform way to do a sound validation given any number of variables? Any ideas or thoughts are appreciated. I hope my explanation makes sense.
Thanks
My best bet is some sort of hierarchical tree of rules. When the user adds the first rule (say A > B), the application could create a data structure like this (lowerValues is a Map which the key leads to a list of values):
lowerValues['A'] = ['B']
Now when the user adds the next rule (B > C), the application could check if B is already in a any lowerValues list (in this case, A). If that happens, C is added to lowerValues['A'], and lowerValues['B'] is also created:
lowerValues['A'] = ['B', 'C']
lowerValues['B'] = ['C']
Finally, when the last rule is provided by the user (C > A), the application checks if C is in any lowerValues list. Since it's in B and A, the rule is invalid.
Hope that helps. I don't remember if there's some sort of mapping in VB. I think you should try the Dictionary object.
In order to this idea works out, all the operations must be internally translated to a simple type. So, for example:
A > B
could be translated as
B <= A
Good luck
In general this is a pretty hard problem. What you in fact want to know is if a set of propositional equations over (apparantly) some set of arithmetic is true. To do this you need what amounts to constraint solvers that "know" arithmetic. Not likely to find that in VB6, but you might be able to invoke one as a subprocess.
If the rules are propositional equations only over inequalities (AA", write them only one way).
Second, try solving the propositions for tautology (see for Wang's algorithm which you can likely implment awkwardly in VB6).
If the propositions are not a tautology, now you want build chains of inequalities (e.g, A > B > C) as a graph and look for cycles. The place this fails is when your propositions have disjunctions, e.g., ("A>B or B>Q"); you'll have to generate an inequality chain for each combination of disjunctions, and discard the inconsistent ones. If you discard all of them, the set is inconsistent. Watch out for expressions like "A and B"; by DeMorgans theorem, they're equivalent to "not A or not B", e.g., "A>B and B>Q" is the same as "A<=B or B<=Q". You might want to reduce the conditions to disjunctive normal form to avoid getting suprised.
There are apparantly decision procedures for such inequalities. They're likely hard to implement.

Prolog Beginner - Is This a Bad Idea?

The application I'm working on is a "configurator" of sorts. It's written in C# and I even wrote a rules engine to go with it. The idea is that there are a bunch of propositional logic statements, and the user can make selections. Based on what they've selected, some other items become required or completely unavailable.
The propositional logic statements generally take the following forms:
A => ~X
ABC => ~(X+Y)
A+B => Q
A(~(B+C)) => ~Q A <=> B
The symbols:
=> -- Implication
<=> -- Material Equivalence
~ -- Not
+ -- Or
Two letters side-by-side -- And
I'm very new to Prolog, but it seems like it might be able to handle all of the "rules processing" for me, allowing me to get out of my current rules engine (it works, but it's not as fast or easy to maintain as I would like).
In addition, all of the available options fall in a hierarchy. For instance:
Outside
Color
Red
Blue
Green
Material
Wood
Metal
If an item at the second level (feature, such as Color) is implied, then an item at the third level (option, such as Red) must be selected. Similarly if we know that a feature is false, then all of the options under it are also false.
The catch is that every product has it's own set of rules. Is it a reasonable approach to set up a knowledge base containing these operators as predicates, then at runtime start buliding all of the rules for the product?
The way I imagine it might work would be to set up the idea of components, features, and options. Then set up the relationships between then (for instance, if the feature is false, then all of its options are false). At runtime, add the product's specific rules. Then pass all of the user's selections to a function, retrieving as output which items are true and which items are false.
I don't know all the implications of what I'm asking about, as I'm just getting into Prolog, but I'm trying to avoid going down a bad path and wasting lots of time in the process.
Some questions that might help target what I'm trying to find out:
Does this sound do-able?
Am I barking up the wrong tree?
Are there any drawbacks or concerns to trying to create all of these rules at runtime?
Is there a better system for this kind of thing out there that I might be able to squeeze into a C# app (Silverlight, to be exact)?
Are there other competing systems that I should examine?
Do you have any general advice about this sort of thing?
Thanks in advance for your advice!
Sure, but Prolog has a learning curve.
Rule-based inference is Prolog's game, though you may have to rewrite many rules into Horn clauses. A+B => Q is doable (it becomes q :- a. q :- b. or q :- (a;b).) but your other examples must be rewritten, including A => ~X.
Depends on your Prolog compiler, specifically whether it supports indexing for dynamic predicates.
Search around for terms like "forward checking", "inference engine" and "business rules". Various communities keep inventing different terminologies for this problem.
Constraint Handling Rules (CHR) is a logic programming language, implemented as a Prolog extension, that is much closer to rule-based inference/forward chaining/business rules engines. If you want to use it, you'll still have to learn basic Prolog, though.
Keep in mind that Prolog is a programming language, not a silver bullet for logical inference. It cuts some corners of first-order logic to keep things efficiently computable. This is why it only handles Horn clauses: they can be mapped one-to-one with procedures/subroutines.
You can also throw in DCGs to generate bill of materials. The idea is
roughly that terminals can be used to indicate subproducts, and
non-terminals to define more and more complex combinations of a subproducts
until you arrive at your final configurable products.
Take for example the two attribute value pairs Color in {red, blue, green}
and Material in {wood, metal}. These could specify a door knob, whereby
not all combinations are possible:
knob(red,wood) --> ['100101'].
knob(red,metal) --> ['100102'].
knob(blue,metal) --> ['100202'].
You could then define a door as:
door ... --> knob ..., panel ...
Interestingly you will not see any logic formula in such a product specification,
only facts and rules, and a lot of parameters passed around. You can use the
parameters in a knowledge acquisition component. By just running uninstantiated
goals you can derive possible values for the attribute value pairs. The predicate
setof/3 will sort and removen duplicates for you:
?- setof(Color,Material^Bill^knob(Color,Material,Bill,[]),Values).
Value = [blue, red]
?- setof(Material,Color^Bill^knob(Color,Material,Bill,[]),Values).
Material = [metal, wood]
Now you know the range of the attributes and you can let the end-user successively
pick an attribute and a value. Assume he takes the attribute Color and its value blue.
The range of the attribute Material then shrinks accordingly:
?- setof(Material,Bill^knob(blue,Material,Bill,[]),Values).
Material = [metal]
In the end when all attributes have been specified you can read off the article
numbers of the subproducts. You can use this for price calculation, by adding some
facts that give you additional information on the article numbers, or to generate
ordering lists etc..:
?- knob(blue,metal,Bill,[]).
Bill = ['100202']
Best Regards
P.S.:
Oh it seems that the bill of materials idea used in the product configurator
goes back to Clocksin & Mellish. At least I find a corresponding
comment here:
http://www.amzi.com/manuals/amzi/pro/ref_dcg.htm#DCGBillMaterials

Resources