char list list -> bool - sml

Does anyone know how to declare a function
rscheck : char list list -> bool
, that checks, if the number 1-9 are used once in every row and every list... so it returns true?
like in a sudoku game..
Thnx.

It could be done like this (also there is a better way for sure, just some training for me):
http://pastebin.com/ViJM48LV

Related

Multiple condition on a sort (c++)

I'm trying to do this LeetCode problem using only the c++ sort function, but I can seem to find the correct way to sort elements depending on multiple condition.
The problem wants you to return the destination city which don't have any path outgoing to another city. In my sorting, I want this city to be the last element of my vector. Right now, this is the code that I have :
class Solution {
public:
string destCity(vector<vector<string>>& paths) {
sort(paths.begin(), paths.end(),[](vector<string> a, vector<string> b ){return (a[1] == b[0]);});
return (paths[paths.size() -1][1]);
}
};`
The input is a vector of paths ([cityA -> cityB], [cityM -> city N] , ... ).
In the following picture, we can see the input, output, my stdout and the expected result of the function :
You can withness that my sort only insures that two paths will be consecutive if the outgoing city of a path equal to the ingoing city of another path [cityA-> cityB], [cityB -> cityC], ... . But my issue is that my sort doesn't treat the case of a city (aka the destination city) that don't have any path outgoing to another city. I would like to place it this particular city as the last element of my vector. Can I do this by adding some code (conditions) to my sort function ? If yes, how ?
Thank you.
You cannot do it with the std::sort. The sort function requires a total order over the elements. You only have a partial one. Once you put all your pairs in, the sort might decide to compare two unrelated elements. It won't try to find a way to compare them in the "right" order.
You need to find a new algorithm. May I suggest:
std::map<string, string> destinations;
And simply following the destination until you get to the end?
Sorting is O(N Log N), even though you might find ways to sort, we'd ideally want to avoid sorting here, and reduce the time complexity to O(N) for this problem.
This'll pass through:
#include <string>
#include <unordered_set>
struct Solution {
static std::string destCity(
const std::vector<std::vector<std::string>>& paths
) {
std::unordered_set<std::string> starts_map;
for (const auto& path : paths) {
starts_map.insert(path[0]);
}
for (const auto& path : paths) {
if (!starts_map.count(path[1])) {
return path[1];
}
}
return "";
}
};
References
For additional details, you can see the Discussion Board. There are plenty of accepted solutions with a variety of languages and explanations, efficient algorithms, as well as asymptotic time/space complexity analysis1, 2 in there.

Is it possible to write an empty list as a difference list in Prolog?

Empty lists are ... strange, to a Prolog beginner like myself. I would say that it isn't possible to write an empty list [] as a difference list T1-T2 just as it isn't possible to write an atom as a difference list. However, I would guess that to use recursion, there must be a way to use [] in a difference list setting. I have Google'd for this but I cannot find an answer, and Bratko (Prolog Programming for AI) only briefly touches the subject.
So, is it possible to write an empty list as a difference list in Prolog, if so how and when would it be useful?
Problems with understanding this topic are typically due to using misleading terminology.
As recommended in tutorial.pdf and especially pap95.pdf, use for example list difference or simply difference.
Section 5 of Teaching beginners Prolog contains relevant reasons for this.
The empty list is uniquely denoted by the atom [].
Note that a list difference always means reasoning about two lists, and due to this categorical difference between a single and multiple lists, you can at best find some correspondence or analogy, but not identity between the empty list and a list difference.
I completely support the view expressed in the paper above that you should focus on using DCGs, at least at first. Reasoning about differences explicitly will come naturally later to you.
Appending two list differences means just a unification of first diff's end pointer with the second one's head. With regular lists it requires retracing of the whole list structure of the first list. Thus repeated concatenation on the right is linear with the list difference technique, and quadratic with plain lists.
When all the intended concatenations are done, to return the whole structure as a plain list to a caller we just unify the "end pointer" logvar with [].
In C terms, list difference is a portion of singly-linked list where we maintain two variables: its head pointer but also its tail pointer:
// typedef struct { int payload; node* next } node;
typedef struct { node** head; node** tail } list_diff;
Now each concatenation is just an assignment of the end pointer:
void diff_concat( list_diff* a, list_diff* b)
{
*(a -> tail) -> next = *(b -> head);
a -> tail = b -> tail;
}
And finalization is
void diff_finalize( list_diff* a)
{
*(a -> tail) = NULL; // or some sentinel value, whatever
}
In Prolog we could represent it as a binary term like -/2, e.g. -(A,B) or A-B.
But (as in C also) there's no actual need to build an actual structure in memory just for holding the two pointers; we can just maintain two logvars individually. Or let DCGs do it for us.
The above was the motivational introduction to list difference technique, "what are they good for?". It also makes clear that the representation of empty difference is
list_diff* d;
*(d -> head) = *(d -> tail);
Or in Prolog, a pair of logvars unified with each other: L-L, var(L). To see why, see what happens when empty diff is appended with some other diff on its right (it is always on the right that we append things, thus growing the lists in the top-down manner). My C may be off here, the idea being that by setting the tail the appending to an empty diff will also update its head.

C++ Generate Permutations of a set recursively

I've been assigned the task of writing a C++ function that returns all possible permutations from a group of integers. I've done a bit of research but all algorithms I find show the permutation being printed out.
The problem I'm running in to is I don't know how to set up the function, specifically, how I should handle receiving data from recursive calls. My first guess was to use a linked list, but I know if I try to return a pointer to a Node I'll end up with a pointer to invalid memory.
My other guess was to use some sort of global linked list of vectors, but I can't imagine how I could add to the linked list from a function itself. Further, this is more sidestepping the problem than actually solving it, and I'd like to actually solve it if at all possible.
As this is a homework problem, I don't expect anyone to hand me an answer outright. I'm just lost and would greatly appreciate someone pointing me in the right direction.
You could use std::next_permutation. It operates on the data structure so you can do anything you want with the data structure after each iteration.
If you're implementing your own permutation logic, suppose you're operating on vector<int>& data, you could add a parameter like vector<vector<int> >& result in your recursive function. Each time a permutation is generated you could simply do result.push_back(data).
One possible approach: store the set in an array, then call a function giving it an array (a ptr to the first item) and the array length as parameters. Make sure the array is initially sorted, say in ascending order, then reorder it to a 'lexically next' permutation on each call.
You can use next_permutation and accumulate copies of all the permutations:
template<class T>
vector<vector<T>> permutations(vector<T> input) {
vector<vector<T>> result{input};
while (next_permutation(begin(input), end(input)))
result.push_back(input);
return result;
}
Since this is a homework problem, I expect you have to generate the permutations yourself. But this points to an approach—have an accumulator of type vector<vector<T>>, and pass it as a reference parameter to the recursive version of your algorithm:
template<class T>
vector<vector<T>> permutations(const vector<T>& input) {
vector<vector<T>> output;
collect_permutations(input, output);
return output;
}
template<class T>
void collect_permutations(const vector<T>& input, vector<vector<T>>& output) {
// Instead of printing, simply write to output using push_back() etc.
}
If you in fact want just the combinations (order of the items in the returned set doesn't matter), then I would use the binary counter approach - for a source set of N items, define an N-bit binary counter and count from 0 to 2^N-1 - each bit in the counter corresponds to one of the N items, and each number represents a combination where only the items that have a 1 bit are present in the combination.
For permutations, you would then have to generate all possible orderings of the items in each individual combination, along with some way to eliminate duplicates if necessary.

Returning elements of a row in a list using Scala

I need to write a method that will return the contents of a particular row (index of it is inputted as method parameter). I have to use recursion and no loops.
So far I have attempted this uncompleted code (and I have no idea how to continue it):
class Sudoku(val grid: List[List[Int]]) {
def r(r: Int): Set[Int] = {
if (grid.isEmpty) Set()
else
}
}
I also do not know how Set works. Any help would be really appreciated. PS: I am not asking for complete code, an algorithm explanation would be more than enough!
This is the answer to the literal interpretation of the question:
class Sudoku(val grid: List[List[Int]]) {
def row(n: Int): List[Int] =
if (grid.size > n) grid(n) else Nil
}
The apply method on List, here applied on the value grid, which can be written either grid apply n, or simply grid(n) returns the n'th element of the list. If that element does not exist (e.g. grid(1000000)), it throws an exception, therefore we check the size of the list first.
I have no idea why you should return a Set, but you could simple call .toSet on the result. A Set is a collection with distinct elements (each element only occurs once) with no guarantee of ordering.
I also don't know why you would need recursion for this, so I reckon the question is part of a larger problem.

C++: How does set know when two items are equal?

I have created a set of C-strings, supplying my own comparator function because I wanted it to only take take the first three characters into account. Here's its definition:
struct set_object {
bool operator()(const char* first, const char* second) {
return strncmp(first, second, 3) > 0;
}
};
std::set<const char*, set_object> c_string_set;
It works as I wanted it to, sorting the strings as I add them the way I outlined in the set_object class. But the interesting part begins when I try to add a string that compares equal to one already added. For example, if I try to add "aaab" when there is already "aaa" in the set, it doesn't add it into the set. If I add "aaab" first, then try to add "aaa", it only lists "aaab". But how does it know when they are equal if I only provided a function that returns true when one of the strings is greater? It should return false when it's either equal or smaller!
To clarify, it's not a problem, just trying to figure out how C++ works.
You're right that set_object(x, y) returning false doesn't say whether x is less than y or they are equal. So set then calls set_object(y, x) to find out.
if (!less(first,second) && !less(second,first)) // equivalent!
If neither one is less than the other, they are equivalent (not equal, there's a very subtle difference).
If an item x is not greater nor smaller than another item y. it means that x and y are the same...
The items are deemed equivalent if a<b and b<a are both false.
See http://www.sgi.com/tech/stl/StrictWeakOrdering.html.