Create a graphic with Pascal - pascal

I'm trying to create a Kakuro with Pascal, the program should get the Kakuro empty (something like this) and return it completed (something like this). I already have loaded the data (from a file) and pass to one 2d array.
The problem I've found is related with the diagonally divided squares, I don't know how I can print this division and a number in each of the sides with Pascal console.
I've tried to use Pascal graphic libraries, but the alghoritm should run on several computers with diferent compilers and Pascal has not unified libraries, only crt and don't help with this (or I can't find it).
Also I try something like ASCII, creatings grid with -- and ’|` but when I print the values with two digits deform all the output, the code is this:
for c := 1 to maxc do
begin
for f := 1 to maxf do
begin
WriteLn('+---+');
WriteLn('|\',tablero[v,f,c],'|');
WriteLn('| \ |');
WriteLn('|', tablero[h,f,c], ' \|');
WriteLn('+---+');
end;
WriteLn();
end;
And the problem in the output you can see this:
+---+
|\-1|
| \ |
|23 \|
+---+
+---+
|\0|
| \ |
|0 \|
+---+
I thought of creating another 2d array inside my 2d array but if I do that I get something like:
+---+
| |
|---|
| |
+---+
Divided by half, and it need to be done diagonally, so doesn't work very well either.

Use the MinWidth specifier for your integer values.
WriteLn(intValue:2); // displays the number with a width of 2
For floating point values, you can also add a value for the number of decimals:
WriteLn(floatVal:5:2);
You can find documentation for the specifier in System.Write - it's Delphi documentation, but Delphi had its roots long ago in Turbo Pascal, and Write/WriteLn are legacy Pascal functions and haven't changed.
A write parameter has the form:
OutExpr [: MinWidth [: DecPlaces ] ]
where OutExpr is an output expression.
MinWidth and DecPlaces are type integer expressions:
MinWidth specifies the minimum field width, which must be greater than 0. Exactly MinWidth characters are written (using leading blanks if necessary) except when OutExpr has a value that must be represented in more than MinWidth characters. In that case, enough characters are written to represent the value of OutExpr. Likewise, if MinWidth is omitted, then the necessary number of characters is written to represent the value of OutExpr.
DecPlaces specifies the number of decimal places in a fixed-point representation of one of the Real types. It can be specified only if OutExpr is one of the Real types, and if MinWidth is also specified. When MinWidth is specified, it must be greater than or equal to 0.
Here's a quick sample:
NT = 12;
NB = -1;
WriteLn('+---+');
WriteLn('|\', NT:2, '|');
WriteLn('| \ |');
WriteLn('|', NB:2, '\|');
WriteLn('+---+');
ReadLn;
This produces
+---+
|\12|
| \ |
|-1\|
+---+
If you need more output than two wide, you'll need to enlarge your box:
+-----+
|\ 120|
| \ |
| \ |
| \ |
|123 \|
+-----+

Related

Find a subset with distinct values for each column

Given a simple table like this:
+---------+---------+---------+
| Column1 | Column2 | Column3 |
+---------+---------+---------+
| A | J | Q |
| A | K | S |
| B | M | R |
| B | N | S |
| B | J | Q |
| C | K | R |
| D | J | R |
| D | J | Q |
| E | L | Q |
+---------+---------+---------+
Is it possible to determine whether there is a subset of N rows in this table, such that for each column, all N values are distinct?
For example, with N = 3, the answer would be yes
+---------+---------+---------+
| Column1 | Column2 | Column3 |
+---------+---------+---------+
| A | J | Q |
| B | N | S |
| C | K | R |
+---------+---------+---------+
Is there a simple algorithm to conclude on such a question?
Is there a simple algorithm to conclude on such a question?
The answer to that is strictly "yes"; you can do a brute-force search over all (R choose K) subsets of K rows, where R is the number of rows in the whole table. That algorithm is quite simple, and could be implemented in a few lines in a language like Python.
But I don't think that is the answer you're looking for; I think you want to know if there is a simple algorithm that takes less than exponential time. The answer to that is almost certainly not; the problem is NP-hard, by reduction from the maximum independent set problem, so there is no known algorithm which gives correct answers in polynomial time, and it's very likely that no such algorithm is possible.
The reduction is as follows: given a graph, construct a table with one row for each vertex. For each edge in the graph, add one column to the table; in this column write the same letter in the two rows the edge joins, and then write distinct other letters in each of the remaining rows for that column. The resulting table has V rows and E columns, so its size is polynomial in the size of the original graph, and it is constructed in polynomial time.
Then, any set of K rows which have distinct values in each column gives K vertices in the original graph not connected by any edges. This means if you can answer yes/no to whether there is such a set of K rows, in polynomial time, then you can also answer the decision form of the maximum independent set problem in polynomial time. The latter is NP-complete, so therefore your problem is NP-hard.
Simple solution would be simply search (backtracking).
But every tool / library solving CSP (Constraint satisfaction problem) can find a solution.
Since you are explicitly asking for an algorithm to solve this:
If I understand the problem correctly (you are using N two times here,the first time for rows and the second time for values, what is a bit confusing), you want to find N rows with ALL DIFFERENT values in the given table.
I would start like this:
Create a data structure for a lookup if you already found a value (e.g. a hashmap)
Create a data structure to store your result rows which fit the match-condition (all values different)
Iterate the input table rows, until you reached your desired subset size or you reached the end of the table
Start with the first row
While iterating a row, check for each value, if it is in your structure (created in 1.), if yes -> abort, else add the value to the lookup-structure. When all row-values are checked, this row is okay and can be added to your result set.
Iterate next row, if existing
But as pointed out in the comment, this algorithm is a greedy one, that will not always find the possible solution

How do I organize these related indices into something that can be looked up efficiently in Rust?

Background
In an algorithm called finite element method, a continuous region is discretized into repeated sections with consistent geometry, over which linked equations are formed based on the assumption of continuity between them.
In this case, I have chosen to divide a shape up into an arbitrary grid, and am now trying to connect the elements' values together as I iterate through the elements. Here is an example of the kind of grid I am talking about:
Indices
There are a bunch of related indices:
The element index (teal numbers), linear, row-major, range 0..ROWS*2.
The node index (brown numbers), linear, row-major, range 0..ROWS*COLS.
The local element vertex index (lavender numbers), counter-clockwise by element, range 0..2.
The coordinates of the actual point in space (stored with the element's struct, as well as the grid's struct)
Problem
In order to get to the next step in the algorithm, I need to iterate over each node and compute some sums of values indexed by local element indices and store them in another matrix. If, for example, I'm on node 8, my element lookup/access function is generically V(el_index, start_vertex, end_vertex), and my matrix of outputs is S(start_node, end_node):
S(8,8) = V(el_14, vert_1, vert_1) + V(el_15, vert_1, vert_1) + V(el_04, vert_0, vert_0) + V(el_03, vert_0, vert_0) + V(el_2, vert_2, vert_2) + V(el_13, vert_2, vert_2)
S(8,9) = V(el_15, vert_1, vert_2) + V(el_4, vert_0, vert_2)
and so on, for all of the connections (teal lines) from node 8. (The connections are symmetric, so once I compute S(7,8), I don't need to compute S(8,7).)
The problem is, the grid (and therefore everything else) is parameterized at runtime, so which node index + adjacency direction corresponds to which element index is dynamically determined. I need to tell the program, "Get me the element indices where the node index of vert_x is my current node index." That's the instruction that tells the program which element to access in V().
Is there a way I can relate these indices in a simple and transparent manner in Rust?
Attempts
I tried computing some simple arithmetic functions modulo the row stride of the node matrix, but the result is messy and hard to debug, as well as requiring verbose bounds checking.
I tried creating three HashMaps keyed by the different vertices of each triangular element, holding the values at each vertex, but the problem is that adjacent triangles share vertex numbers as well as spatial coordinates.
I considered keying a HashMap with multiple keys, but the Rust docs didn't say anything about a HashMap with multiple keys.
I think this is a possible workaround, but I hope there's something better:
Nest one HashMap in another as per this question, with the node index as the first key, the element index as the second key/first value, and the element itself as the second value.
So, the iteration can look like this:
Iterate through grid node index N
Get all elements with N as the first key
Note that the vertex indices and (relative) element indices have the following patterns, depending on where you number from:
Node index numbering beginning from matrix top-left (usual in this programming domain):
| Element (index ordinal) | Vertex |
|-------------------------|--------|
| 0 (min) | 1 |
| 1 | 2 |
| 2 | 1 |
| 3 | 2 |
| 4 | 0 |
| 5 | 0 |
Node index numbering beginning as picture, from lower-left:
| Element (index ordinal) | Vertex |
|-------------------------|--------|
| 0 (min) | 2 |
| 1 | 0 |
| 2 | 0 |
| 3 | 2 |
| 4 | 1 |
| 5 | 1 |
Since you can hardcode the relative order of elements like this, it might be better to use a HashMap<usize, Vec<Element>>, or even HashMap<usize, [Element; 6]>.
This method brings up the question of how to relate node index to element indices dynamically. How do you know which elements to insert into that HashMap? One way to accomplish this is to record the nodes the element vertices correspond to in the element struct as well, in the same order.
At that point, you can compute a list like adjacent_elements as you iterate through the matrix, and use the above patterns to figure out what to access (sadly, with bounds checking).

Edit Distance (Dynamic Programming): Aren't insertion and deletion the same thing?

In looking through the dynamic programming algorithm for computing the minimum edit distance between two strings I am having a hard time grasping one thing. To me it seems like given the two strings s and t inserting a character into s would be the same as deleting a character from t. Why then do we need to consider these operations separately when computing the edit distance? I always have a hard time computing the indices in the recurrence relation because I can't intuitively understand this part.
I've read through Skiena and some other sources but they all don't explain this part well. This SO link explains the insert and delete operations better than elsewhere in terms of understanding what string is being inserted into or deleted from but I still can't figure out why they aren't one and the same.
Edit: Ok, I didn't do a very good job of detailing the source of my confusion.
The way Skiena explains computing the minimum edit distance m(i,j) of the first i characters of a string s and the first j characters of a string t based on already having computed solutions to the subproblems is as follows. m(i,j) will be the minimum of the following 3 possibilities:
opt[MATCH] = m[i-1][j-1].cost + match(s[i],t[j]);
opt[INSERT] = m[i][j-1].cost + indel(t[j]);
opt[DELETE] = m[i-1][j].cost + indel(s[i]);
The way I understand it the 3 operations are all operations on the string s. An INSERT means you have to insert a character at the end of string s to get the minimum edit distance. A DELETE means you have to delete the character at the end of string s to get the minimum edit distance.
Given s = "SU" and t = "SATU" INSERT and DELETE would be as follows:
Insert:
SU_
SATU
Delete:
SU
SATU_
My confusion was that an INSERT into s is the same as a DELETION from t. I'm probably confused on something basic but it's not intuitive to me yet.
Edit 2: I think this link kind of clarifies my confusion but I'd love an explanation given my specific questions above.
They aren't the same thing any more than < and > are the same thing. There is of course a sort of duality and you are correct to point it out. a < b if and only if b > a so if you have a good algorithm to test for b > a then it makes sense to use it when you need to test if a < b.
It is much easier to directly test if s can be obtained from t by deletion rather than to directly test if t can be obtained from s by insertion. It would be silly to randomly insert letters to s and see if you get t. I can't imagine that any implementation of edit-distance actually does that. Still, it doesn't mean that you can't distinguish between insertion and deletion.
More abstractly. There is a relation, R on any set of strings defined by
s R t <=> t can be obtained from s by insertion
deletion is the inverse relation. Closely related, but not the same.
The problem of edit distance can be restated as a problem of converting the source string into target string with minimum number of operations (including insertion, deletion and replacement of a single character).
Thus, in the process of converting a source string into a target string, if inserting a character from target string or deleting a character from the source string or replacing a character in the source string with a character from the target string yields the same (minimum) edit distance, then, well, all the operations can be said to be equivalent. In other words, it does not matter how you arrive at the target string as long as you have done minimum number of edits.
This is realized by looking at how the cost matrix is calculated. Consider a simpler problem where source = AT (represented vertically) and target = TA (represented horizontally). The matrix is then constructed as (coming from west, northwest, north in that order):
| ε | T | A |
| | | |
ε | 0 | 1 | 2 |
| | | |
A | 1 | min(2, 1, 2) = 1 | min(2, 1, 3) = 1 |
| | | |
T | 2 | min(3, 1, 3) = 1 | min(2, 2, 2) = 2 |
The idea of filling this matrix is:
If we moved east, we insert the current target string character.
If we moved south, we delete the current source string character.
If we moved southeast, we replace the current source character with current target character.
If all or any two of these impart the same cost in terms of editing, then they can be said to be equivalent and you can break the ties arbitrarily.
One of the first experiences with this comes when we find c(2, 2) in the cost matrix (c(0, 0) through c(0, 2) -- minimum costs of converting an empty string to "T", "TA" respectively, and c(0, 0) to c(2,0) -- costs of converting "A", "AT" respectively to empty string are clear).
Value of c(2, 2), can be realized either by:
inserting the current character in target, 'A' (we move east from c(2,1)) -- cost is 1 + 1 = 2, or
replacing the current character 'T' in source by current character in target 'A' -- cost is `1 + 1 = 2
deleting the current character in source, 'T' (we move south from c(1, 2)) -- cost is 1 + 1 = 2
Since all values are the same, which one are you going to choose?
If you choose to move from west, your alignment could be:
A T -
- T A
(one deletion, one 0-cost replacement, one insertion)
If you choose to move from north, your alignment could be:
- A T
T A -
(one insertion, one 0-cost replacement, one deletion)
If you choose to move from northwest, your alignment could be:
A T
T A
(Two 1-cost replacements).
All these edit graphs are equivalent in terms of given edit distance (under given cost function).
Edit distance is only interested in the minimum number of operations required to transform one sequence into another; it is not interested in the uniqueness of the transformation. In practice, there are often multiple ways to transform one string into another, that all have the minimum number of operations.

Add +/- to make a numeric string evaluated in 0

Given a string consisting of number, add + or - sign to make the expression values 0. Return the expression.
For example,
123 => 1 + 2 -3 = 0
173956 => 17 + 39 - 56 = 0
I have no clues to solve this problem other than a brute-force way.
Is there any suggestion?
This is a search problem. Search must be performed in the solution space.
Suppose we starting from '123' string, at this point, we can add + or - sign after '1', as result we get '1 + 23' or '1 - 23'. Every variant can be split further by adding a sign after next character. As result, all possible sign additions will form tree-like structure - the solution space. Your algorithm must search solution in this structure. I think A* can be used to do this.
Anders K draw nice ASCII graph of the solution space, you just need to search it for solution. Simple breadth first search or depth first search can do the work, but I think it will be slow if solution space is large.
Also, I think that is possible to find more optimal, specific solution that exploits properties of the solution space, for example - it's tree-like structure.
you can solve it in many ways for example using a recursive approach which becomes obvious if you structure it up as a tree
e.g. 123
since there can be two different signs after a digit digit (+|-) :
1
/ \
+ -
/ \
2 2
/ \ / \
+ - + -
| | | |
3 3 3 3

How can I better understand the one-comparison-per-iteration binary search?

What is the point of the one-comparison-per-iteration binary search? And can you explain how it works?
There are two reasons to binary search with one comparison per iteration. The
less important is performance. Detecting an exact match early using two
comparisons per iteration saves an average one iteration of the loop, whereas
(assuming comparisons involve significant work) binary searching with one
comparison per iteration almost halves the work done per iteration.
Binary searching an array of integers, it probably makes little difference
either way. Even with a fairly expensive comparison, asymptotically the
performance is the same, and the half-rather-than-minus-one probably isn't worth
pursuing in most cases. Besides, expensive comparisons are often coded as functions that return negative, zero or positive for <, == or >, so you can get both comparisons for pretty much the price of one anyway.
The important reason to do binary searches with one comparison per iteration is
because you can get more useful results than just some-equal-match. The main
searches you can do are...
First key > goal
First key >= goal
First key == goal
Last key < goal
Last key <= goal
Last key == goal
These all reduce to the same basic algorithm. Understanding this well enough
that you can code all the variants easily isn't that difficult, but I've not
really seen a good explanation - only pseudocode and mathematical proofs. This
is my attempt at an explanation.
There are games where the idea is to get as close as possible to a target
without overshooting. Change that to "undershooting", and that's what "Find
First >" does. Consider the ranges at some stage during the search...
| lower bound | goal | upper bound
+-----------------+-------------------------+--------------
| Illegal | better worse |
+-----------------+-------------------------+--------------
The range between the current upper and lower bound still need to be searched.
Our goal is (normally) in there somewhere, but we don't yet know where. The
interesting point about items above the upper bound is that they are legal in
the sense that they are greater than the goal. We can say that the item just
above the current upper bound is our best-so-far solution. We can even say this
at the very start, even though there is probably no item at that position - in a
sense, if there is no valid in-range solution, the best solution that hasn't
been disproved is just past the upper bound.
At each iteration, we pick an item to compare between the upper and lower bound.
For binary search, that's a rounded half-way item. For binary tree search, it's
dictated by the structure of the tree. The principle is the same either way.
As we are searching for an item greater-than our goal, we compare the test item
using Item [testpos] > goal. If the result is false, we have overshot (or
undershot) our goal, so we keep our existing best-so-far solution, and adjust
our lower bound upwards. If the result is true, we have found a new best-so-far
solution, so we adjust the upper bound down to reflect that.
Either way, we never want to compare that test item again, so we adjust our
bound to eliminate (only just) the test item from the range to search. Being
careless with this usually results in infinite loops.
Normally, half-open ranges are used - an inclusive lower bound and an exclusive
upper bound. Using this system, the item at the upper bound index is not in the
search range (at least not now), but it is the best-so-far solution. When you
move the lower bound up, you move it to testpos+1 (to exclude the item you just
tested from the range). When you move the upper bound down, you move it to
testpos (the upper bound is exclusive anyway).
if (item[testpos] > goal)
{
// new best-so-far
upperbound = testpos;
}
else
{
lowerbound = testpos + 1;
}
When the range between the lower and upper bounds is empty (using half-open,
when both have the same index), your result is your most recent best-so-far
solution, just above your upper bound (ie at the upper bound index for
half-open).
So the full algorithm is...
while (upperbound > lowerbound)
{
testpos = lowerbound + ((upperbound-lowerbound) / 2);
if (item[testpos] > goal)
{
// new best-so-far
upperbound = testpos;
}
else
{
lowerbound = testpos + 1;
}
}
To change from first key > goal to first key >= goal, you literally switch
the comparison operator in the if line. The relative operator and goal could be replaced by a single parameter - a predicate function that returns true if (and only if) its parameter is on the greater-than side of the goal.
That gives you "first >" and "first >=". To get "first ==", use "first >=" and
add an equality check after the loop exits.
For "last <" etc, the principle is the same as above, but the range is
reflected. This just means you swap over the bound-adjustments (but not the
comment) as well as changing the operator. But before doing that, consider the following...
a > b == !(a <= b)
a >= b == !(a < b)
Also...
position (last key < goal) = position (first key >= goal) - 1
position (last key <= goal) = position (first key > goal ) - 1
When we move our bounds during the search, both sides are being moved towards the goal until they meet at the goal. And there is a special item just below the lower bound, just as there is just above the upper bound...
while (upperbound > lowerbound)
{
testpos = lowerbound + ((upperbound-lowerbound) / 2);
if (item[testpos] > goal)
{
// new best-so-far for first key > goal at [upperbound]
upperbound = testpos;
}
else
{
// new best-so-far for last key <= goal at [lowerbound - 1]
lowerbound = testpos + 1;
}
}
So in a way, we have two complementary searches running at once. When the upperbound and lowerbound meet, we have a useful search result on each side of that single boundary.
For all cases, there's the chance that that an original "imaginary" out-of-bounds
best-so-far position was your final result (there was no match in the
search range). This needs to be checked before doing a final == check for the
first == and last == cases. It might be useful behaviour, as well - e.g. if
you're searching for the position to insert your goal item, adding it after the
end of your existing items is the right thing to do if all the existing items
are smaller than your goal item.
A couple of notes on the selection of the testpos...
testpos = lowerbound + ((upperbound-lowerbound) / 2);
First off, this will never overflow, unlike the more obvious ((lowerbound +
upperbound)/2). It also works with pointers as well as integer
indexes.
Second, the division is assumed to round down. Rounding down for non-negatives
is OK (all you can be sure of in C) as the difference is always non-negative
anyway.
This is one aspect that may need care if you use non-half-open
ranges, though - make sure the test position is inside the search range, and not just outside (on one of the already-found best-so-far positions).
Finally, in a binary tree search, the moving of bounds is implicit and the
choice of testpos is built into the structure of the tree (which may be
unbalanced), yet the same principles apply for what the search is doing. In this
case, we choose our child node to shrink the implicit ranges. For first match
cases, either we've found a new smaller best match (go to the lower child in hopes of finding an even smaller and better one) or we've overshot (go to the higher child in hopes of recovering). Again, the four main cases can be handled by switching the comparison operator.
BTW - there are more possible operators to use for that template parameter. Consider an array sorted by year then month. Maybe you want to find the first item for a particular year. To do this, write a comparison function that compares the year and ignores the month - the goal compares as equal if the year is equal, but the goal value may be a different type to the key that doesn't even have a month value to compare. I think of this as a "partial key comparison", and plug that into your binary search template and you get what I think of as a "partial key search".
EDIT The paragraph below used to say "31 Dec 1999 to be equal to 1 Feb 2000". That wouldn't work unless the whole range in-between was also considered equal. The point is that all three parts of the begin- and end-of-range dates differ, so you're not deal with a "partial" key, but the keys considered equivalent for the search must form a contiguous block in the container, which will normally imply a contiguous block in the ordered set of possible keys.
It's not strictly just "partial" keys, either. Your custom comparison might consider 31 Dec 1999 to be equal to 1 Jan 2000, yet all other dates different. The point is the custom comparison must agree with the original key about the ordering, but it might not be so picky about considering all different values different - it can treat a range of keys as an "equivalence class".
An extra note about bounds that I really should have included before, but I may not have thought about it this way at the time.
One way of thinking about bounds is that they aren't item indexes at all. A bound is the boundary line between two items, so you can number the boundary lines as easily as you can number the items...
| | | | | | | | |
| +-+ | +-+ | +-+ | +-+ | +-+ | +-+ | +-+ | +-+ |
| |0| | |1| | |2| | |3| | |4| | |5| | |6| | |7| |
| +-+ | +-+ | +-+ | +-+ | +-+ | +-+ | +-+ | +-+ |
| | | | | | | | |
0 1 2 3 4 5 6 7 8
Obviously the numbering of bounds is related to the numbering of the items. As long as you number your bounds left-to-right and the same way you number your items (in this case starting from zero) the result is effectively the same as the common half-open convention.
It would be possible to select a middle bound to bisect the range precisely into two, but that's not what a binary search does. For binary search, you select an item to test - not a bound. That item will be tested in this iteration and must never be tested again, so it's excluded from both subranges.
| | | | | | | | |
| +-+ | +-+ | +-+ | +-+ | +-+ | +-+ | +-+ | +-+ |
| |0| | |1| | |2| | |3| | |4| | |5| | |6| | |7| |
| +-+ | +-+ | +-+ | +-+ | +-+ | +-+ | +-+ | +-+ |
| | | | | | | | |
0 1 2 3 4 5 6 7 8
^
|<-------------------|------------->|
|
|<--------------->| | |<--------->|
low range i hi range
So the testpos and testpos+1 in the algorithm are the two cases of translating the item index into the bound index. Of course if the two bounds are equal, there's no items in that range to choose so the loop cannot continue, and the only possible result is that one bound value.
The ranges shown above are just the ranges still to be searched - the gap we intend to close between the proven-lower and proven-higher ranges.
In this model, the binary search is searching for the boundary between two ordered kinds of values - those classed as "lower" and those classed as "higher". The predicate test classifies one item. There is no "equal" class - equal-to-key values are part of the higher class (for x[i] >= key) or the lower class (for x[i] > key).

Resources