Iterate through Tuple Cplex - tuples

I have a tuple:
`tuple Torder{
string part;
int period;
}
{Torder} order = {<i, h> | i in part, h in period};`
Then:
{string} operation = ...;
I'm trying to create a new tuple:
string step[k in operation] = k;
tuple Twip
{
Torder order;
string operation;
}
{Twip} status = {<<i, h>, o> | <i, h> in order, k in operation, o in 1.. step[k]};
But the code o in 1.. step[k] outputs
operation is not integer

This syntax should work fine:
tuple Torder{
string part;
int period;
}
range period=1..2;
{string} part={"A","B"};
{Torder} order = {<i, h> | i in part, h in period};
{string} operation = {"Y","Z"};
string step[k in operation] = k;
{string} steps=union (k in operation) {step[k]};
tuple Twip
{
Torder order;
string operation;
}
{Twip} status = {<<i, h>, o> | <i, h> in order, k in operation, o in steps: ord(steps,o) <= ord(operation,k)};
execute
{
status;
}

Related

Appending a number to enum to get other enum

I want to get the enum value in a for loop, by appending a number, like
enum example
{
Example_1,
Example_2,
Example_3,
.
.
.
Example_n
};
example x;
for (i = 0; i < n; i++
{x = Example_ + i; // if i = 5, I need Example_5
}
I want this implementation in C++11
If you have an Example_0 in the enum, then Example_0 + 5 will give you an integer value equivalent to Example_5. Enums are just integers.
All this assuming that you don't explicitly assign a value to a certain enumeration constant - that's another story.
You cannot concatenate name with number to retrieve enum name and use enum value.
With contiguous enum, you can use simple arithmetic.
you can create operator++ for your enum, resolve by switch:
example operator++(example e)
{
switch (e) {
case Example_1: return Example_2;
case Example_2: return Example_3;
case Example_3: return Example_4;
// ...
case Example_n: return Last;
};
throw std::runtime("value out of range");
}
and so, possibly
for (example e = Example_1: e != Last; ++e) {/*..*/}
using array to provide enum list:
constexpr auto AllExamples() {
constexpr std::array res{{Example_1,
Example_2,
/*..*/,
Example_n}};
return res;
}
which allows:
for (auto ex : AllExamples()) {/*..*/}
f(AllExamples()[5]);
or use map if you really have to play with names:
std::map<std::string, example> ExamplesAsMap() {
return {
{"Example_1", Example_1},
{"Example_2", Example_2},
/*..*/
{"Example_n", Example_n},
{"Value_1", Value_1},
{"Value_2", Value_2},
/*..*/
{"Value_n", Value_n}
/**/
};
}
And then
const auto m = ExamplesAsMap();
example x;
for (int i = 0; i < n; i++) {
x = m.at("Example_" + std::to_string(i));
// ...
}

How to validate input based on CFG?

Consider this grammar:
expr ::= LP expr RP
| expr PLUS|MINUS expr
| expr STAR|SLASH expr
| term
term ::= INTEGER|FLOAT
Context-free grammar is defined as G = ( V, Σ, R, S ), where (in this case):
V = { expr, term }
Σ = { LP, RP, PLUS, MINUS, STAR, SLASH, INTEGER, FLOAT }
R = //was defined above
S = expr
Now let's define a small class called Parser which definition is (code samples are provided in C++):
class Parser
{
public:
Parser();
void Parse();
private:
void parseRecursive(vector<string> rules, int ruleIndex, int startingTokenIndex, string prevRule);
bool isTerm(string token); //returns true if token is in upper case
vector<string> split(...); //input: string; output: vector of words splitted by delim
map<string, vector<string>> ruleNames; //contains grammar definition
vector<int> tokenList; //our input set of tokens
};
To make it easier to go between rules, every grammar rule is split into 2 parts: a key (before ::=) and its rules (after ::=), so for my grammar from above the following map takes place:
std::map<string, vector<string>> ruleNames =
{
{ "expr", {
"LP expr RP",
"expr PLUS|MINUS expr",
"expr STAR|SLASH expr",
"term"
}
},
{ "term", { "INTEGER", "FLOAT" } }
};
For testing purposes, string (2 + 3) * 4 has been tokenized to the following set
{ TK_LP, TK_INTEGER, TK_PLUS, TK_INTEGER, TK_RP, TK_STAR, TK_INTEGER }
and been used as an input data for Parser.
Now for the hardest part: the algorithm. From what I understand, I was thinking about this:
1) Taking first rule from starting symbol vector (LP expr RP) and split it into words.
2) Check if first word in rule is terminal.
If the word is terminal, compare it with first token.
If they are equal, increase token index and move to next word in rule
If they are not equal, keep token index and move to next rule
If the word is not terminal and it was not used in previous recursion, increase token index and go into recursive parsing (passing new rules and non-terminal word)
While I am not sure in this algorithm, I still tried to make and implementation of it (of course, unsuccessful):
1) Outter Parse function that initiates recursion:
void Parser::Parse()
{
int startingTokenIndex = 0;
string word = this->startingSymbol;
for (int ruleIndex = 0; ruleIndex < this->ruleNames[word].size(); ruleIndex++)
{
this->parseRecursive(this->ruleNames[word], ruleIndex, startingTokenIndex, "");
}
}
2) Recursive function:
void Parser::parseRecursive(vector<string> rules, unsigned ruleIndex, unsigned startingTokenIndex, string prevRule)
{
printf("%s - %s\n", rules[ruleIndex].c_str(), this->tokenNames[this->tokenList[startingTokenIndex]].c_str());
vector<string> temp = this->split(rules[ruleIndex], ' ');
vector<vector<string>> ruleWords;
bool breakOutter = false;
for (unsigned wordIndex = 0; wordIndex < temp.size(); wordIndex++)
{
ruleWords.push_back(this->split(temp[wordIndex], '|'));
}
for (unsigned wordIndex = 0; wordIndex < ruleWords.size(); wordIndex++)
{
breakOutter = false;
for (unsigned subWordIndex = 0; subWordIndex < ruleWords[wordIndex].size(); subWordIndex++)
{
string word = ruleWords[wordIndex][subWordIndex];
if (this->isTerm(word))
{
if (this->tokenNames[this->tokenList[startingTokenIndex]] == this->makeToken(word))
{
printf("%s ", word.c_str());
startingTokenIndex++;
} else {
breakOutter = true;
break;
}
} else {
if (prevRule != word)
{
startingTokenIndex++;
this->parseRecursive(this->ruleNames[word], 0, startingTokenIndex, word);
prevRule = word;
}
}
}
if (breakOutter)
break;
}
}
What changes should I perform to my algorithm to make it work?
Depending on what you want to implement a one-time parser or compiler compiler, different methods are used. For compiler compilers are used mainly LR, for manual implementation of LL.
Basically, for LL, a manual implementation uses recursive descent (for each non-terminal, a function is created that implements it).
For example, for grammar:
S -> S + A | A
A -> a | b
Let us kill the left recursion and the left factorization (LL grammars do not work with the left recursion):
S -> As
s -> + As | epsilon
A -> a | b
Such an implementation is possible:
void S (void)
{
    A ();
    s ();
}
void s (void)
{
    if (get_next_token (). value! = '+')
        return;
    A ();
    s ();
}
void A (void)
{
    token * tok = get_next_token ();
    if (tok.value! = 'a' && tok.value! = 'b')
            syntax_error ();
}
If you want to add SDD, then the inherited attributes are passed through the arguments, and the synthesized attributes as output values.
Comment:
do not collect all the tokens at one time, get them as needed: get_next_token ().

Hashing with linear probing in c++

Can anyone explain me, what DeletedNode class is doing what the purpose of DeletedNode():HashNode(-1, -1){}.
Please explain the pointer concept here
HashNode ** htable = new HashNode*[Tablesize];
const int Tablesize=10;
class HashNode {
public:
int key;
int value;
HashNode(int key, int value) {
this->key=key;
this->value=value;
}
};
class DeletedNode : public HashNode {
private:
static DeletedNode * entry;
DeletedNode() : HashNode(-1, -1) {} // Please explain this
public:
static DeletedNode * getNode() {
if (entry == NULL)
entry = new DeletedNode();
return entry;
}
};
DeletedNode * DeletedNode::entry = NULL; //Why this?
class HashMap {
public:
HashNode ** htable;
HashMap() {
htable = new HashNode*[Tablesize]; // Please explain the pointer concept here
for (int i = 0; i < Tablesize; i++)
htable[i] = NULL;
}
int HashFunc(int key) { return key % Tablesize; }
};
Consider what happens when you delete an entry from the hash table which is part of a "collision cluster", a contiguous block of elements that happen to have the same hash value.
Let's say elements A, B, and C all hash to the same value h. In this case, they will be inserted into the table at positions h, h + 1 and h + 2, respectively:
--------
A h
--------
B h + 1
--------
C h + 2
--------
Now what happens if you delete B? If we do the deletion naively, then there will be a hole between A and C:
--------
A h
--------
h + 1
--------
C h + 2
--------
Now if you try to look up C in the hash table, its hash value will be h, so the search for it will begin at position h. However, the next entry at position h + 1 is now empty, hence the linear probing search will terminate prematurely, and you will get the wrong result that C isn't in the table.
In order to prevent the premature termination of the search, a special "dummy" node needs to be inserted in the empty place, which says "there was something here some day which has now been deleted, but I'm part of a collision cluster anyway, so keep searching".

How construct hash function for a user defined type?

For example, in the following struct:
1) editLine is a pointer to a data line which has CLRF,
2) nDisplayLine is the display line index of this editLine,
3) start is the offset in the display line,
4) len is the length of the text;
struct CacheKey {
const CEditLine* editLine;
int32 nDisplayLine;
int32 start;
int32 len;
friend bool operator==(const CacheKey& item1, const CacheKey& item2) {
return (item1.start == item2.start && item1.len == item2.len && item1.nDisplayLine == item2.nDisplayLine &&
item1.editLine == item2.editLine);
}
CacheKey() {
editLine = NULL;
nDisplayLine = 0;
start = 0;
len = 0;
}
CacheKey(const CEditLine* editLine, int32 dispLine, int32 start, int32 len) :
editLine(editLine), nDisplayLine(dispLine), start(start), len(len)
{
}
int hash() {
return (int)((unsigned char*)editLine - 0x10000) + nDisplayLine * nDisplayLine + start * 2 - len * 1000;
}
};
Now I need to put it into a std::unordered_map<int, CacheItem> cacheMap_
The problem is how to design the hash function for this structure, is there any guidelines?
How could i make sure the hash function is collision-free?
To create a hash function, you can use std::hash, which is defined for integers. Then, you can combine them "as the boost guys does" (because doing a good hash is something non trivial) as explained here : http://en.cppreference.com/w/cpp/utility/hash.
Here is a hash_combine method :
inline void hash_combine(std::size_t& seed, std::size_t v)
{
seed ^= v + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
So the "guideline" is more or less what's is shown on cppreference.
You CAN'T be sure your hash function is colision free. Colision free means that you do not loose data (or you restrict yourself to a small set of possibilities for your class). If any int32 value is allowed for each fields, a collision free hash is a monstrously big index, and it won't fit in a small table. Let unordered_map take care of collisions, and combine std::hash hash as explained above.
In you case, it will look something like
std::size_t hash() const
{
std::size_t h1 = std::hash<CEditLine*>()(editLine);
//Your int32 type is probably a typedef of a hashable type. Otherwise,
// you'll have to static_cast<> it to a type supported by std::hash.
std::size_t h2 = std::hash<int32>()(nDisplayLine);
std::size_t h3 = std::hash<int32>()(start);
std::size_t h4 = std::hash<int32>()(len);
std::size_t hash = 0;
hash_combine(hash, h1);
hash_combine(hash, h2);
hash_combine(hash, h3);
hash_combine(hash, h4);
return hash;
}
Then, you can specialize the std::hash operator for your class.
namespace std
{
template<>
struct hash<CacheKey>
{
public:
std::size_t operator()(CacheKey const& s) const
{
return s.hash();
}
};
}

Cannot declare map with integer keys in C++

I was attempting to write a Longest Common Substring program using Rabin Karp and Binary search. For that I wrote a method which basically create a hash table for one of the strings and the key would be the hash value of the pattern of length M starting at index i . The value of they key would be index i .
I have written the following code :
#include <iostream>
#include <string>
#include<map>
#include<math.h>
#define BASE 10
#define BASE2 10.0
#define M 99999989
using namespace std;
map<int, int> hashmap;
int pHash=0;
int mod(int a, int b) {
return (a%b + b)%b;
}
int getHash(string & pattern) {
int hashVal = 0;
for ( int i =0 ; i<pattern.length();i++) {
int val = (int) pattern[i];
hashVal = mod(hashVal*BASE + val, M);
}
return hashVal;
}
int rabinKarp(string &pattern, string & text)
{
pHash = getHash(pattern);
cout<<"P HASH : "<<pHash<<endl;
int m = pattern.size();
int fHash = getHash(text.substr(0, pattern.size()));
int newKey = fHash;
hashmap.insert(newKey, 0);
if(fHash==pHash)
cout<<"Rabin Karp found a match at index : 0 "<< endl;
for(int i = 1; i <=text.size()-pattern.size();i++) {
int val = (int)text[i-1];
double sz = (double)pattern.size()-1.0;
int temp = pow(BASE2, sz);
int mult= mod(temp,M);
fHash = mod(fHash - mod(val*mult,M),M);
fHash= mod(fHash*BASE, M);
fHash= mod(fHash+(int)text[i+m-1], M);
int key = fHash ;
hashmap.insert(key, i);
if(fHash==pHash)
cout<<"Rabin Karp found a match at index : "<< i<<endl;
}
return 1;
}
int main() {
string pattern;
string text;
cout<<"Please enter the pattern "<<endl;
getline(cin, pattern) ;
cout<<"Please enter the text " <<endl;
getline(cin, text);
int index = rabinKarp(pattern, text) ;
}
The problem is that I am unable to insert the keys into the map . I am getting the following error of which I can make no sense . Anyone can help me understand what this is ?
Error 3 error C2664: 'std::pair<_Ty1,_Ty2> std::_Tree<_Traits>::insert(const std::pair<_Kty,_Ty> &)' : cannot convert parameter 1 from 'int' to 'const std::pair<_Ty1,_Ty2> &' c:\program files\microsoft visual studio 9.0\vc\include\xtree 760 SPOJ
Error 2 error C2100: illegal indirection c:\program files\microsoft visual studio 9.0\vc\include\xtree 760 SPOJ
If you are trying to insert a key-value pair, you need to insert an std::pair<K, V>, where K and V are the key and value types respectively. See std::map:insert. You need something like
hashmap.insert(std::make_pair(newKey, 0));
If you want to insert a value for a given key, and you don't mind about potentially overwriting a previously existing value, you can use operator[]:
hashmap[newKey] = someValue;
Since C++11, you can also use emplace(key, value). This constructs a pair for you using the given arguments, and then inserts it into the map.
hashmap.emplace(newKey, 0);
You should call
result = hashmap.insert(map<int, int>::value_type (newKey, 0));
// or
result = hashmap.insert(std::make_pair(newKey, 0));
insert als0 returns std::pair<iterator, bool> - you can check with result.second if you have successfully inserted the element (for instance if there were element with the same key , it would not insert it and return false.