vector iterator not dereferncable....? - vector

`void calc_distance(vector fingerTips, CvPoint palmCenter,IplImage *source)
{
double distance = 0;
vector<CvPoint>::iterator p;
if (fingerTips.size() != NULL && fingerTips.size() <= 5 && fingerTips.size() >= 1)
{
if ((fingerTips.size() > 1) || (fingerTips.size() <= 5))
{
distance = 0;
p = fingerTips.begin();
CvPoint forefinger = *p;
CvPoint secondfinger;
for( ;p != fingerTips.end(); )
{
p++;
secondfinger = *p;
distance += sqrt(double((forefinger.x - secondfinger.x) *
(forefinger.x - secondfinger.x) + (forefinger.y - secondfinger.y) * (forefinger.y - secondfinger.y)) );
cvLine(source,forefinger,secondfinger,cvScalar(1.0,1.0,1.0),3,8);
forefinger = secondfinger;
}
}
}
}
//as parameters i passed the the vector of fingertips co-ordinate and the center of the palm along with image source
but still im getting the error: "vector iterator not differefercable"....
the error occurs in the 2nd iteration at " secondfinger = *p;" line.....
please help me.....
here i am trying to get distance between each fingers and summing each of the them to get
the final distance....
please help me...

You check p != end, then P++, then dereference. You should just do a standard for loop:
for(; p != fingerTips.end(); p++)
{
//p++ //This is gone now. It's up in the for loop
...
}
instead of having p++ in your for loop

You need to dereference p before you increment it; otherwise, you end up trying to dereference fingertips.end() when you get to the end of the collection, which cannot be dereferenced.
for( ;p != fingerTips.end(); ++p)
{
secondfinger = *p;
distance += sqrt(double((forefinger.x - secondfinger.x) * (forefinger.x - secondfinger.x) + (forefinger.y - secondfinger.y) * (forefinger.y - secondfinger.y)) );
cvLine(source,forefinger,secondfinger,cvScalar(1.0,1.0,1.0),3,8);
forefinger = secondfinger;
}

Related

Find the Elements within the given distance within Tree

I have a tree which as certain elements, I have a method essentially returns a list of elements that are within the distance.
Example
In the tree above, once I have my method, I should be able to input a data and distance. Lets say the data I input is 1 and the distance is 2. In this case, the method should output elements, [2,3,4] because I should be able to output data that is less than or equal to the given distance.
I know how to output data that have a distance of 2 away, but I am struggling to include data that includes data that is 1 away as well.
void printkdistanceNodeDown(Node node, int k)
{
if (node == null || k < 0)
return;
if (k == 0)
{
System.out.print(node.data);
System.out.println("");
return;
}
// Recur for left and right subtrees
printkdistanceNodeDown(node.left, k - 1);
printkdistanceNodeDown(node.right, k - 1);
}
int printkdistanceNode(Node node, Node target, int k)
{
if (node == null)
return -1;
if (node == target)
{
printkdistanceNodeDown(node, k);
return 0;
}
// Recur for left subtree
int dl = printkdistanceNode(node.left, target, k);
// Check if target node was found in left subtree
if (dl != -1)
{
if (dl + 1 == k)
{
System.out.print(node.data);
System.out.println("");
}
else
printkdistanceNodeDown(node.right, k - dl - 2);
// Add 1 to the distance and return value for parent calls
return 1 + dl;
}
// MIRROR OF ABOVE CODE FOR RIGHT SUBTREE
// Note that we reach here only when node was not found in left
// subtree
int dr = printkdistanceNode(node.right, target, k);
if (dr != -1)
{
if (dr + 1 == k)
{
System.out.print(node.data);
System.out.println("");
}
else
printkdistanceNodeDown(node.left, k - dr - 2);
return 1 + dr;
}
// If target was neither present in left nor in right subtree
return -1;
}

OpenCL function calls

I'm working on an openCL kernel that loads up some points, decides which is the highest, and returns it. All good there, but I want to add a calculation before the highest evaluation. This compares the point to a pair of lines. I have it written and working to a degree, as follows:
size_t i = group_id * group_stride + local_id;
while (i < n){
//load up a pair of points using the index to locate them within a massive dataSet
int ia = LOAD_GLOBAL_I1(input, i);
float4 a = LOAD_GLOBAL_F4(dataSet, ia);
int ib = LOAD_GLOBAL_I1(input, i + group_size);
float4 b = LOAD_GLOBAL_F4(dataSet, ib);
//pre-assess the points relative to lines
if(pass == 0){
float px = a.x;
float py = a.y;
int checkAnswer;
//want to write this section as a function
float x1 = tri_input[0].x; float y1 = tri_input[0].y;
float x2 = tri_input[2].x; float y2 = tri_input[2].y;
float check = sign((x1-x2) * (py-y1) - (y2-y1) * (px-x1));
if(check != tri_input[3].x){ //point is outside line 1
checkAnswer = 1;
}
else{
x1 = tri_input[2].x; y1 = tri_input[2].y;
x2 = tri_input[1].x; y2 = tri_input[1].y;
check = sign((x1-x2)*(py-y1) - (y2-y1)*(px-x1));
if(check != tri_input[3].y){ //point is outside line 2
checkAnswer = 2;
}
else{
checkAnswer = 0; //point is within both lines
}}}
//later use the checkAnswer result to change the following
//find the highest of the pair
float4 result;
if(a.z>b.z) result = a;
else result = b;
//load up the previous highest result locally
float4 s = LOAD_LOCAL_F4(shared, local_id);
//if the previous highest beat this, stick, else twist
if(s.z>result.z){ STORE_LOCAL_F4(shared, local_id, s);}
else{ STORE_LOCAL_F4(shared, local_id, result);}
i += local_stride;
}
What I would like to do is call the line check twice as a function, i.e the code becomes:
size_t i = group_id * group_stride + local_id;
while (i < n){
//load up a pair of points using the index to locate them within a massive dataSet
int ia = LOAD_GLOBAL_I1(input, i);
float4 a = LOAD_GLOBAL_F4(dataSet, ia);
int ib = LOAD_GLOBAL_I1(input, i + group_size);
float4 b = LOAD_GLOBAL_F4(dataSet, ib);
//pre-assess the points relative to lines
if(pass == 0){
float px = a.x;
float py = a.y;
int checkA = pointCheck( px, py, tri_input);
px = b.x;
py = b.y;
int checkB = pointCheck( px, py, tri_input);
}
//later use the checkAnswer result to change the following
//find the highest of the pair
float4 result;
if(a.z>b.z) result = a;
else result = b;
//load up the previous highest result locally
float4 s = LOAD_LOCAL_F4(shared, local_id);
//if the previous highest beat this, stick, else twist
if(s.z>result.z){ STORE_LOCAL_F4(shared, local_id, s);}
else{ STORE_LOCAL_F4(shared, local_id, result);}
i += local_stride;
}
In this instance the function is:
int pointCheck( float *px, float *py, float2 *testLines){
float x1 = testLines[0].x; float y1 = testLines[0].y;
float x2 = testLines[2].x; float y2 = testLines[2].y;
float check = sign((x1-x2) * (py-y1) - (y2-y1) * (px-x1));
if(check != testLines[3].x){ //point is outside line 1
return 1;
}
else{
x1 = testLines[2].x; y1 = testLines[2].y;
x2 = testLines[1].x; y2 = testLines[1].y;
check = sign((x1-x2)*(py-y1) - (y2-y1)*(px-x1));
if(check != testLines[3].y){ //point is outside line 2
return 2;
}
else{
return 0; //point is within both lines
}}}
Whilst the longhand version runs fine and returns a normal 'highest point' result, the function version returns an erroneous result (not detecting the highest point I have hidden in the data set). It produces a wrong result even though the function as yet has no overall effect.
What am I doing wrong?
S
[Update]:
This revised function works as far as the commented out line, then hangs on something:
int pointCheck(float4 *P, float2 *testLines){
float2 *l0 = &testLines[0];
float2 *l1 = &testLines[1];
float2 *l2 = &testLines[2];
float2 *l3 = &testLines[3];
float x1 = l0->x; float y1 = l0->y;
float x2 = l2->x; float y2 = l2->y;
float pX = P->x; float pY = P->y;
float c1 = l3->x; float c2 = l3->y;
//float check = sign((x1-x2) * (pY-y1) - (y2-y1) * (pX-x1)); //seems to be a problem with sign
// if(check != c1){ //point is outside line 1
// return 1;
// }
// else{
// x1 = l2->x; y1 = l2->y;
// x2 = l1->x; y2 = l1->y;
// check = sign((x1-x2) * (pY-y1) - (y2-y1) * (pX-x1));
// if(check != c2){ //point is outside line 2
// return 2;
// }
// else{
// return 0; //point is within both lines
// }}
}
One immediate issue is how you pass the parameters to the called function:
int checkA = pointCheck( px, py, tri_input);
whereas the function itself expects pointers for px and py. You should instead call the function as:
int checkA = pointCheck(&px, &py, tri_input);
It is surprising that OpenCL does not give build errors for this kernel.
In my experience, some OpenCL runtimes do not like multiple return statements in a single function. Try to save the return value into a local variable and use a single return statement at the end of the function. This is because OpenCL does not support real function calls, but rather inlines all functions directly into the kernel. A best practice is therefore to mark all non __kernel functions as inline, and treat them as such (i.e. make it easier for the compiler to inline your function by not using multiple return statements).

Inside boundaries

I'm using this article to write a fluid simulation application.
I can't manage to implement the inside boundaries. As far as i know when I'm setting the boundaries (in the set_bnd function) for each cell that is inside the boundary I should calculate the average value from the adjacent non-boundary cells like this:
for (i = 0 ; i < n ; i++)
{
for (j = 0 ; j < n ; j++)
{
if (isBoundary(i,j)
{
sum = 0;
count = 0;
if (!isBoundary(i+1,j) {
sum += x[i+1][j];
}
if (!isBoundary(i-1,j) {
sum += x[i-1][j];
}
if (!isBoundary(i,j+1) {
sum += x[i][j+1];
}
if (!isBoundary(i,j-1) {
sum += x[i-1][j];
}
x[i][j] = sum / 4;
}
}
}
Unfortunately the smoke is absorbed and disappears in contact with boundary surface.
My math background is not sufficient to understand every part of the calculation, so I'll be very grateful if someone points me the right direction.
Here is some code to explain further.
insideBound is array (1 - boundary, 0 - empty, the fluid can pass trough)
#define FOR_EACH_CELL for ( i=1 ; i<=N ; i++ ) { for ( j=1 ; j<=N ; j++ ) {
void set_bnd ( int N, int b, float * x, int * insideBound )
{
int i, j;
float sum;
int count;
for ( i=1 ; i<=N ; i++ ) {
x[IX(0 ,i)] = b==1 ? -x[IX(1,i)] : x[IX(1,i)];
x[IX(N+1,i)] = b==1 ? -x[IX(N,i)] : x[IX(N,i)];
x[IX(i,0 )] = b==2 ? -x[IX(i,1)] : x[IX(i,1)];
x[IX(i,N+1)] = b==2 ? -x[IX(i,N)] : x[IX(i,N)];
}
x[IX(0 ,0 )] = 0.5f*(x[IX(1,0 )]+x[IX(0 ,1)]);
x[IX(0 ,N+1)] = 0.5f*(x[IX(1,N+1)]+x[IX(0 ,N)]);
x[IX(N+1,0 )] = 0.5f*(x[IX(N,0 )]+x[IX(N+1,1)]);
x[IX(N+1,N+1)] = 0.5f*(x[IX(N,N+1)]+x[IX(N+1,N)]);
if (!b) return;
FOR_EACH_CELL
sum = 0.0f;
count = 0;
if (insideBound[IX(i,j)] == 1)
{
if (insideBound[IX(i-1,j)] != 1)
{
count++;
sum = sum + x[IX(i-1,j)];
}
if (insideBound[IX(i+1,j)] != 1)
{
count++;
sum = sum + x[IX(i+1,j)];
}
if (insideBound[IX(i,j-1)] != 1)
{
count++;
sum = sum + x[IX(i, j-1)];
}
if (insideBound[IX(i,j+1)] != 1)
{
count++;
sum = sum + x[IX(i, j+1)];
}
if (count > 0)
{
x[IX(i,j)] = -sum / count;
} else {
x[IX(i,j)] = 0;
}
}
END_FOR
}
Per book (working):
In the first loop are set top, right, bottom and left boundary cells.
Since for them there is only one adjacent cell that is not bound the cell get its value. (I don't know why its opposite for U and the same value for V)
After the first loop, the corner boundary values are set. Here they get average values from their adjacent cells (i guess since there is no adjacent cell that is not boundary they use boundary cells).
Mine, not working properly:
if (!b) return - ignores calculations for density and updates only velocity.
The loop calculates the values for all boundary cells (again, average values from the adjacent cells that are not boundaries themselves).
I get almost realistic result from this methods, but there is big loses in the density and some bugs with too big boundaries where the fluid disappears completely.
I've managed to find a solution, here it is for potential people with the same problem
void set_bnd ( int N, int b, float * x, int * insideBound )
{
int i, j;
float sum, tmp;
int count;
for ( i=1 ; i<=N ; i++ ) {
x[IX(0 ,i)] = b==1 ? -x[IX(1,i)] : x[IX(1,i)];
x[IX(N+1,i)] = b==1 ? -x[IX(N,i)] : x[IX(N,i)];
x[IX(i,0 )] = b==2 ? -x[IX(i,1)] : x[IX(i,1)];
x[IX(i,N+1)] = b==2 ? -x[IX(i,N)] : x[IX(i,N)];
}
x[IX(0 ,0 )] = 0.5f*(x[IX(1,0 )]+x[IX(0 ,1)]);
x[IX(0 ,N+1)] = 0.5f*(x[IX(1,N+1)]+x[IX(0 ,N)]);
x[IX(N+1,0 )] = 0.5f*(x[IX(N,0 )]+x[IX(N+1,1)]);
x[IX(N+1,N+1)] = 0.5f*(x[IX(N,N+1)]+x[IX(N+1,N)]);
if (!b) return;
for ( i=1 ; i<=N ; i++ ) {
for ( j=1 ; j<=N ; j++ ) {
sum = 0.0f;
count = 0;
if (insideBound[IX(i,j)] == 1)
{
if (insideBound[IX(i-1,j)] != 1)
{
count++;
if (b == 2)
tmp = -x[IX(i-1,j)];
else
tmp = x[IX(i-1,j)];
sum = sum + tmp;
}
if (insideBound[IX(i+1,j)] != 1)
{
count++;
if (b == 2)
tmp = -x[IX(i+1,j)];
else
tmp = x[IX(i+1,j)];
sum = sum + tmp;
}
if (insideBound[IX(i,j-1)] != 1)
{
count++;
if (b == 1)
tmp = - x[IX(i, j-1)];
else
tmp = x[IX(i, j-1)];
sum = sum + tmp;
}
if (insideBound[IX(i,j+1)] != 1)
{
count++;
if (b == 1)
tmp = -x[IX(i, j+1)];
else
tmp = x[IX(i, j+1)];
sum = sum + tmp;
}
if (count > 0)
{
x[IX(i,j)] = -sum / count;
} else {
x[IX(i,j)] = 0;
}
}
}
}
}
insideBound is boolean array (0,1) which indicates the cells that are boundaries. Works with one or more boundary areas, but they should be at least 3 cells wide and high.

Object reference not set to an instance of an object - but it is?

I am creating a Sudoku Puzzle in asp and I'm having trouble with some classes. When I create a function to display all the numbers in the text box, I get this error: Object reference not set to an instance of an object. I know that it means that my object is null, but here is my code. The line that I am getting the error on is the line that says: stbNumber.setNumber(currentSolution[3 * i + m, 3 * k + n]);
private SudokuTextBox stb;
private Puzzle puzzle;
private Box box;
private Number stbNumber;
public void displayAll(object sender,EventArgs e)
{
puzzle = new Puzzle();
for (int i = 0; i < 3; i++)
{
for (int k = 0; k < 3; k++)
{
box = new Box();
for (int m = 0; m < 3; m++)
{
for (int n = 0; n < 3; n++)
{
stbNumber = new Number();
stb = new SudokuTextBox();
stbNumber.setNumber(currentSolution[3 * i + m, 3 * k + n]);
stb.setTextBoxValue(stbNumber);
stb.setVisibility(true);
box.setItem(stb, m, n);
}// end forth for
}//end third for
puzzle.setItem(box, i, k);
}//end second for
}//end first for
generateBoxes();
}
I have initialized stbNumber at the very top of my code, and I have made sure that currentSolution is not null or empty. I'm therefore unsure as to what I am doing wrong. I also should mention that I have this exact code elsewhere to generate new puzzles and it works just fine, but this section of code specifically gets called when I click a button.
you essentially have 3 possibilities:
stbNumber.setNumber(currentSolution[3 * i + m, 3 * k + n]);
stbNumber could be null
currentSolution could be null
the element you are trying to index could be null--just because currentSolution is not null does not mean the item is at that index is not null--so new one up or take appropriate action
since you new up an instance of stbNumber, it is unlikely to be the culprit (but it could be)
you say you are checking currentSolution is null, I don't see the code for that and from the code you did post it is most likely the culprit here. what you COULD do is add a check for null before you access it, and if your test fails writing an error message somewhere:
stbNumber = new Number();
stb = new SudokuTextBox();
if ( currentSolution != null )
{
// if the item does not exist, new it up
if ( currentSolution[3 * i + m, 3 * k + n] == null ) currentSolution[3 * i + m, 3 * k + n] = new someObject()
stbNumber.setNumber(currentSolution[3 * i + m, 3 * k + n]);
stb.setTextBoxValue(stbNumber);
}
else
{
WriteSomeErrorMessage("currentSolution is null");
}

String Reduction - Programming Contest . Solution needed

I have a question which asks us to reduce the string as follows.
The input is a string having only A, B or C. Output must be length of
the reduced string
The string can be reduced by the following rules
If any 2 different letters are adjacent, these two letters can be
replaced by the third letter.
Eg ABA -> CA -> B . So final answer is 1 (length of reduced string)
Eg ABCCCCCCC
This doesn't become CCCCCCCC, as it can be reduced alternatively by
ABCCCCCCC->AACCCCCC->ABCCCCC->AACCCC->ABCCC->AACC->ABC->AA
as here length is 2 < (length of CCCCCCCC)
How do you go about this problem?
Thanks a lot!
To make things clear: the question states it wants the minimum length of the reduced string. So in the second example above there are 2 solutions possible, one CCCCCCCC and the other AA. So 2 is the answer as length of AA is 2 which is smaller than the length of CCCCCCCC = 8.
The way this question is phrased, there are only three distinct possibilities:
If the string has only one unique character, the length is the same as the length of the string.
2/3. If the string contains more than one unique character, the length is either 1 or 2, always (based on the layout of the characters).
Edit:
As a way of proof of concept here is some grammar and its extensions:
I should note that although this seems to me a reasonable proof for the fact that the length will reduce to either 1 or 2, I am reasonably sure that determining which of these lengths will result is not as trivial as I originally thought ( you would still have to recurse through all options to find it out)
S : A|B|C|()
S : S^
where () denotes the empty string, and s^ means any combination of the previous [A,B,C,()] characters.
Extended Grammar:
S_1 : AS^|others
S_2 : AAS^|ABS^|ACS^|others
S_3 : AAAS^|
AABS^ => ACS^ => BS^|
AACS^ => ABS^ => CS^|
ABAS^ => ACS^ => BS^|
ABBS^ => CBS^ => AS^|
ABCS^ => CCS^ | AAS^|
ACAS^ => ABS^ => CS^|
ACBS^ => AAS^ | BBS^|
ACCS^ => BCS^ => AS^|
The same thing will happen with extended grammars starting with B, and C (others). The interesting cases are where we have ACB and ABC (three distinct characters in sequence), these cases result in grammars that appear to lead to longer lengths however:
CCS^: CCAS^|CCBS^|CCCS^|
CBS^ => AS^|
CAS^ => BS^|
CCCS^|
AAS^: AAAS^|AABS^|AACS^|
ACS^ => BS^|
ABS^ => CS^|
AAAS^|
BBS^: BBAS^|BBBS^|BBCS^|
BCS^ => AS^|
BAS^ => CS^|
BBBS^|
Recursively they only lead to longer lengths when the remaining string contains their value only. However we have to remember that this case also can be simplified, since if we got to this area with say CCCS^, then we at one point previous had ABC ( or consequently CBA ). If we look back we could have made better decisions:
ABCCS^ => AACS^ => ABS^ => CS^
CBACS^ => CBBS^ => ABS^ => CS^
So in the best case at the end of the string when we make all the correct decisions we end with a remaining string of 1 character followed by 1 more character(since we are at the end). At this time if the character is the same, then we have a length of 2, if it is different, then we can reduce one last time and we end up with a length of 1.
You can generalize the result based on individual character count of string. The algo is as follows,
traverse through the string and get individual char count.
Lets say if
a = no# of a's in given string
b = no# of b's in given string
c = no# of c's in given string
then you can say that, the result will be,
if((a == 0 && b == 0 && c == 0) ||
(a == 0 && b == 0 && c != 0) ||
(a == 0 && b != 0 && c == 0) ||
(a != 0 && b == 0 && c == 0))
{
result = a+b+c;
}
else if(a != 0 && b != 0 && c != 0)
{
if((a%2 == 0 && b%2 == 0 && c%2 == 0) ||
(a%2 == 1 && b%2 == 1 && c%2 == 1))
result = 2;
else
result = 1;
}
else if((a == 0 && b != 0 && c != 0) ||
(a != 0 && b == 0 && c != 0) ||
(a != 0 && b != 0 && c == 0))
{
if(a%2 == 0 && b%2 == 0 && c%2 == 0)
result = 2;
else
result = 1;
}
I'm assuming that you are looking for the length of the shortest possible string that can be obtained after reduction.
A simple solution would be to explore all possibilities in a greedy manner and hope that it does not explode exponentially. I'm gonna write Python pseudocode here because that's easier to comprehend (at least for me ;)):
from collections import deque
def try_reduce(string):
queue = deque([string])
min_length = len(string)
while queue:
string = queue.popleft()
if len(string) < min_length:
min_length = len(string)
for i in xrange(len(string)-1):
substring = string[i:(i+2)]
if substring == "AB" or substring == "BA":
queue.append(string[:i] + "C" + string[(i+2):])
elif substring == "BC" or substring == "CB":
queue.append(string[:i] + "A" + string[(i+2):])
elif substring == "AC" or substring == "CA":
queue.append(string[:i] + "B" + string[(i+2):])
return min_length
I think the basic idea is clear: you take a queue (std::deque should be just fine), add your string into it, and then implement a simple breadth first search in the space of all possible reductions. During the search, you take the first element from the queue, take all possible substrings of it, execute all possible reductions, and push the reduced strings back to the queue. The entire space is explored when the queue becomes empty.
Let's define an automaton with the following rules (K>=0):
Incoming: A B C
Current: --------------------------
<empty> A B C
A(2K+1) A(2K+2) AB AC
A(2K+2) A(2K+3) AAB AAC
AB CA CB ABC
AAB BA ACB BC
ABC CCA AAB AAC
and all rules obtained by permutations of ABC to get the complete definition.
All input strings using a single letter are irreducible. If the input string contains at least two different letters, the final states like AB or AAB can be reduced to a single letter, and the final states like ABC can be reduced to two letters.
In the ABC case, we still have to prove that the input string can't be reduced to a single letter by another reduction sequence.
Compare two characters at a time and replace if both adjacent characters are not same. To get optimal solution, run once from start of the string and once from end of the string. Return the minimum value.
int same(char* s){
int i=0;
for(i=0;i<strlen(s)-1;i++){
if(*(s+i) == *(s+i+1))
continue;
else
return 0;
}
return 1;
}
int reduceb(char* s){
int ret = 0,a_sum=0,i=0;
int len = strlen(s);
while(1){
i=len-1;
while(i>0){
if ((*(s+i)) == (*(s+i-1))){
i--;
continue;
} else {
a_sum = (*(s+i)) + (*(s+i-1));
*(s+i-1) = SUM - a_sum;
*(s+i) = '\0';
len--;
}
i--;
}
if(same(s) == 1){
return strlen(s);
}
}
}
int reducef(char* s){
int ret = 0,a_sum=0,i=0;
int len = strlen(s);
while(1){
i=0;
while(i<len-1){
if ((*(s+i)) == (*(s+i+1))){
i++;
continue;
} else {
a_sum = (*(s+i)) + (*(s+i+1));
*(s+i) = SUM - a_sum;
int j=i+1;
for(j=i+1;j<len;j++)
*(s+j) = *(s+j+1);
len--;
}
i++;
}
if(same(s) == 1){
return strlen(s);
}
}
}
int main(){
int n,i=0,f=0,b=0;
scanf("%d",&n);
int a[n];
while(i<n){
char* str = (char*)malloc(101);
scanf("%s",str);
char* strd = strdup(str);
f = reducef(str);
b = reduceb(strd);
if( f > b)
a[i] = b;
else
a[i] = f;
free(str);
free(strd);
i++;
}
for(i=0;i<n;i++)
printf("%d\n",a[i]);
}
import java.io.*;
import java.util.*;
class StringSim{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
StringTokenizer st = new StringTokenizer(sc.nextLine(), " ");
int N = Integer.parseInt(st.nextToken());
String op = "";
for(int i=0;i<N;i++){
String str = sc.nextLine();
op = op + Count(str) + "\n";
}
System.out.println(op);
}
public static int Count( String str){
int min = Integer.MAX_VALUE;
char pre = str.charAt(0);
boolean allSame = true;
//System.out.println("str :" + str);
if(str.length() == 1){
return 1;
}
int count = 1;
for(int i=1;i<str.length();i++){
//System.out.println("pre: -"+ pre +"- char at "+i+" is : -"+ str.charAt(i)+"-");
if(pre != str.charAt(i)){
allSame = false;
char rep = (char)(('a'+'b'+'c')-(pre+str.charAt(i)));
//System.out.println("rep :" + rep);
if(str.length() == 2)
count = 1;
else if(i==1)
count = Count(rep+str.substring(2,str.length()));
else if(i == str.length()-1)
count = Count(str.substring(0,str.length()-2)+rep);
else
count = Count(str.substring(0,i-1)+rep+str.substring(i+1,str.length()));
if(min>count) min=count;
}else if(allSame){
count++;
//System.out.println("count: " + count);
}
pre = str.charAt(i);
}
//System.out.println("min: " + min);
if(allSame) return count;
return min;
}
}
Wouldn't a good start be to count which letter you have the most of and look for ways to remove it? Keep doing this until we only have one letter. We might have it many times but as long as it is the same we do not care, we are finished.
To avoid getting something like ABCCCCCCC becoming CCCCCCCC.
We remove the most popular letter:
-ABCCCCCCC
-AACCCCCC
-ABCCCCC
-AACCCC
-ABCCC
-AACC
-ABC
-AA
I disagree with the previous poster who states we must have a length of 1 or 2 - what happens if I enter the start string AAA?
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Sample {
private static char[] res = {'a', 'b', 'c'};
private char replacementChar(char a, char b) {
for(char c : res) {
if(c != a && c != b) {
return c;
}
}
throw new IllegalStateException("cannot happen. you must've mucked up the resource");
}
public int processWord(String wordString) {
if(wordString.length() < 2) {
return wordString.length();
}
String wordStringES = reduceFromEnd(reduceFromStart(wordString));
if(wordStringES.length() == 1) {
return 1;
}
String wordStringSE = reduceFromStart(reduceFromEnd(wordString));
if(wordString.length() == 1) {
return 1;
}
int aLen;
if(isReduced(wordStringSE)) {
aLen = wordStringSE.length();
} else {
aLen = processWord(wordStringSE);
}
int bLen;
if(isReduced(wordStringES)) {
bLen = wordStringES.length();
} else {
bLen = processWord(wordStringES);
}
return Math.min(aLen, bLen);
}
private boolean isReduced(String wordString) {
int length = wordString.length();
if(length < 2) {
return true;
}
for(int i = 1; i < length; ++i) {
if(wordString.charAt(i) != wordString.charAt(i - 1)) {
return false;
}
}
return wordString.charAt(0) == wordString.charAt(length - 1);
}
private String reduceFromStart(String theWord) {
if(theWord.length() < 2) {
return theWord;
}
StringBuilder buffer = new StringBuilder();
char[] word = theWord.toCharArray();
char curChar = word[0];
for(int i = 1; i < word.length; ++i) {
if(word[i] != curChar) {
curChar = replacementChar(curChar, word[i]);
if(i + 1 == word.length) {
buffer.append(curChar);
break;
}
} else {
buffer.append(curChar);
if(i + 1 == word.length) {
buffer.append(curChar);
}
}
}
return buffer.toString();
}
private String reduceFromEnd(String theString) {
if(theString.length() < 2) {
return theString;
}
StringBuilder buffer = new StringBuilder(theString);
int length = buffer.length();
while(length > 1) {
char a = buffer.charAt(0);
char b = buffer.charAt(length - 1);
if(a != b) {
buffer.deleteCharAt(length - 1);
buffer.deleteCharAt(0);
buffer.append(replacementChar(a, b));
length -= 1;
} else {
break;
}
}
return buffer.toString();
}
public void go() {
Scanner scanner = new Scanner(System.in);
int numEntries = Integer.parseInt(scanner.nextLine());
List<Integer> counts = new LinkedList<Integer>();
for(int i = 0; i < numEntries; ++i) {
counts.add((processWord(scanner.nextLine())));
}
for(Integer count : counts) {
System.out.println(count);
}
}
public static void main(String[] args) {
Sample solution = new Sample();
solution.go();
}
}
This is greedy approach and traversing the path starts with each possible pair and checking the min length.
import java.io.*;
import java.util.*;
class StringSim{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
StringTokenizer st = new StringTokenizer(sc.nextLine(), " ");
int N = Integer.parseInt(st.nextToken());
String op = "";
for(int i=0;i<N;i++){
String str = sc.nextLine();
op = op + Count(str) + "\n";
}
System.out.println(op);
}
public static int Count( String str){
int min = Integer.MAX_VALUE;
char pre = str.charAt(0);
boolean allSame = true;
//System.out.println("str :" + str);
if(str.length() == 1){
return 1;
}
int count = 1;
for(int i=1;i<str.length();i++){
//System.out.println("pre: -"+ pre +"- char at "+i+" is : -"+ str.charAt(i)+"-");
if(pre != str.charAt(i)){
allSame = false;
char rep = (char)(('a'+'b'+'c')-(pre+str.charAt(i)));
//System.out.println("rep :" + rep);
if(str.length() == 2)
count = 1;
else if(i==1)
count = Count(rep+str.substring(2,str.length()));
else if(i == str.length()-1)
count = Count(str.substring(0,str.length()-2)+rep);
else
count = Count(str.substring(0,i-1)+rep+str.substring(i+1,str.length()));
if(min>count) min=count;
}else if(allSame){
count++;
//System.out.println("count: " + count);
}
pre = str.charAt(i);
}
//System.out.println("min: " + min);
if(allSame) return count;
return min;
}
}
Following NominSim's observations, here is probably an optimal solution that runs in linear time with O(1) space usage. Note that it is only capable of finding the length of the smallest reduction, not the reduced string itself:
def reduce(string):
a = string.count('a')
b = string.count('b')
c = string.count('c')
if ([a,b,c].count(0) >= 2):
return a+b+c
elif (all(v % 2 == 0 for v in [a,b,c]) or all(v % 2 == 1 for v in [a,b,c])):
return 2
else:
return 1
There is some underlying structure that can be used to solve this problem in O(n) time.
The rules given are (most of) the rules defining a mathematical group, in particular the group D_2 also sometimes known as K (for Klein's four group) or V (German for Viergruppe, four group). D_2 is a group with four elements, A, B, C, and 1 (the identity element). One of the realizations of D_2 is the set of symmetries of a rectangular box with three different sides. A, B, and C are 180 degree rotations about each of the axes, and 1 is the identity rotation (no rotation). The group table for D_2 is
|1 A B C
-+-------
1|1 A B C
A|A 1 C B
B|B C 1 A
C|C B A 1
As you can see, the rules correspond to the rules given in the problem, except that the rules involving 1 aren't present in the problem.
Since D_2 is a group, it satisfies a number of rules: closure (the product of any two elements of the group is another element), associativity (meaning (x*y)*z = x*(y*z) for any elements x, y, z; i.e., the order in which strings are reduced doesn't matter), existence of identity (there is an element 1 such that 1*x=x*1=x for any x), and existence of inverse (for any element x, there is an element x^{-1} such that x*x^{-1}=1 and x^{-1}*x=1; in our case, every element is its own inverse).
It's also worth noting that D_2 is commutative, i.e., x*y=y*x for any x,y.
Given any string of elements in D_2, we can reduce to a single element in the group in a greedy fashion. For example, ABCCCCCCC=CCCCCCCC=CCCCCC=CCCC=CC=1. Note that we don't write the element 1 unless it's the only element in the string. Associativity tells us that the order of the operations doesn't matter, e.g., we could have worked from right to left or started in the middle and gotten the same result. Let's try from the right: ABCCCCCCC=ABCCCCC=ABCCC=ABC=AA=1.
The situation of the problem is different because operations involving 1 are not allowed, so we can't just eliminate pairs AA, BB, or CC. However, the situation is not that different. Consider the string ABB. We can't write ABB=A in this case. However, we can eliminate BB in two steps using A: ABB=CB=A. Since order of operation doesn't matter by associativity, we're guaranteed to get the same result. So we can't go straight from ABB to A but we can get the same result by another route.
Such alternate routes are available whenever there are at least two different elements in a string. In particular, in each of ABB, ACC, BAA, BCC, CAA, CBB, AAB, AAC, BBA, BBC, CCA, CCB, we can act as if we have the reduction xx=1 and then drop the 1.
It follows that any string that is not homogeneous (not all the same letter) and has a double-letter substring (AA, BB, or CC) can be reduced by removing the double letter. Strings that contain just two identical letters can't be further reduced (because there is no 1 allowed in the problem), so it seems safe to hypothesize that any non-homogeneous string can be reduced to A, B, C, AA, BB, CC.
We still have to be careful, however, because CCAACC could be turned into CCCC by removing the middle pair AA, but that is not the best we can do: CCAACC=AACC=CC or AA takes us down to a string of length 2.
Another situation we have to be careful of is AABBBB. Here we could eliminate AA to end with BBBB, but it's better to eliminate the middle B's first, then whatever: AABBBB=AABB=AA or BB (both of which are equivalent to 1 in the group, but can't be further reduced in the problem).
There's another interesting situation we could have: AAAABBBB. Blindly eliminating pairs takes us to either AAAA or BBBB, but we could do better: AAAABBBB=AAACBBB=AABBBB=AABB=AA or BB.
The above indicate that eliminating doubles blindly is not necessarily the way to proceed, but nevertheless it was illuminating.
Instead, it seems as if the most important property of a string is non-homogeneity. If the string is homogeneous, stop, there's nothing we can do. Otherwise, identify an operation that preserves the non-homogeneity property if possible. I assert that it is always possible to identify an operation that preserves non-homogeneity if the string is non-homogeneous and of length four or greater.
Proof: if a 4-substring contains two different letters, a third letter can be introduced at a boundary between two different letters, e.g., AABA goes to ACA. Since one or the other of the original letters must be unchanged somewhere within the string, it follows that the result is still non-homogeneous.
Suppose instead we have a 4-substring that has three different elements, say AABC, with the outer two elements different. Then if the middle two elements are different, perform the operation on them; the result is non-homogeneous because the two outermost elements are still different. On the other hand, if the two inner elements are the same, e.g., ABBC, then they have to be different from both outermost elements (otherwise we'd only have two elements in the set of four, not three). In that case, perform either the first or third operation; that leaves either the last two elements different (e.g., ABBC=CBC) or the first two elements different (e.g., ABBC=ABA) so non-homogeneity is preserved.
Finally, consider the case where the first and last elements are the same. Then we have a situation like ABCA. The middle two elements both have to be different from the outer elements, otherwise we'd have only two elements in this case, not three. We can take the first available operation, ABCA=CCA, and non-homogeneity is preserved again.
End of proof.
We have a greedy algorithm to reduce any non-homogeneous string of length 4 or greater: pick the first operation that preserves non-homogeneity; such an operation must exist by the above argument.
We have now reduced to the case where we have a non-homogeneous string of 3 elements. If two are the same, we either have doubles like AAB etc., which we know can be reduced to a single element, or we have two elements with no double like ABA=AC=B which can also be reduced to a single element, or we have three different elements like ABC. There are six permutations, all of which =1 in the group by associativity and commutativity; all of them can be reduced to two elements by any operation; however, they can't possibly be reduced below a homogeneous pair (AA, BB, or CC) since 1 is not allowed in the problem, so we know that's the best we can do in this case.
In summary, if a string is homogeneous, there's nothing we can do; if a string is non-homogeneous and =A in the group, it can be reduced to A in the problem by a greedy algorithm which maintains non-homogeneity at each step; the same if the string =B or =C in the group; finally if a string is non-homogeneous and =1 in the group, it can be reduced by a greedy algorithm which maintains non-homogeneity as long as possible to one of AA, BB or CC. Those are the best we can do by the group properties of the operation.
Program solving the problem:
Now, since we know the possible outcomes, our program can run in O(n) time as follows: if all the letters in the given string are the same, no reduction is possible so just output the length of the string. If the string is non-homogeneous, and is equal to the identity in the group, output the number 2; otherwise output the number 1.
To quickly decide whether an element equals the identity in the group, we use commutativity and associativity as follows: just count the number of A's, B's and C's into the variables a, b, c. Replace a = a mod 2, b = b mod 2, c = c mod 2 because we can eliminate pairs AA, BB, and CC in the group. If none of the resulting a, b, c is equal to 0, we have ABC=1 in the group, so the program should output 2 because a reduction to the identity 1 is not possible. If all three of the resulting a, b, c are equal to 0, we again have the identity (A, B, and C all cancelled themselves out) so we should output 2. Otherwise the string is non-identity and we should output 1.
//C# Coding
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
/*
Keep all the rules in Dictionary object 'rules';
key - find string, value - replace with value
eg: find "AB" , replace with "AA"
*/
Dictionary<string, string> rules = new Dictionary<string, string>();
rules.Add("AB", "AA");
rules.Add("BA", "AA");
rules.Add("CB", "CC");
rules.Add("BC", "CC");
rules.Add("AA", "A");
rules.Add("CC", "C");
// example string
string str = "AABBCCCA";
//output
Console.WriteLine(fnRecurence(rules, str));
Console.Read();
}
//funcation for applying all the rules to the input string value recursivily
static string fnRecurence(Dictionary<string, string> rules,string str)
{
foreach (var rule in rules)
{
if (str.LastIndexOf(rule.Key) >= 0)
{
str = str.Replace(rule.Key, rule.Value);
}
}
if(str.Length >1)
{
int find = 0;
foreach (var rule in rules)
{
if (str.LastIndexOf(rule.Key) >= 0)
{
find = 1;
}
}
if(find == 1)
{
str = fnRecurence(rules, str);
}
else
{
//if not find any exit
find = 0;
str = str;
return str;
}
}
return str;
}
}
}
Here is my C# solution.
public static int StringReduction(string str)
{
if (str.Length == 1)
return 1;
else
{
int prevAns = str.Length;
int newAns = 0;
while (prevAns != newAns)
{
prevAns = newAns;
string ansStr = string.Empty;
int i = 1;
int j = 0;
while (i < str.Length)
{
if (str[i] != str[j])
{
if (str[i] != 'a' && str[j] != 'a')
{
ansStr += 'a';
}
else if (str[i] != 'b' && str[j] != 'b')
{
ansStr += 'b';
}
else if (str[i] != 'c' && str[j] != 'c')
{
ansStr += 'c';
}
i += 2;
j += 2;
}
else
{
ansStr += str[j];
i++;
j++;
}
}
if (j < str.Length)
{
ansStr += str[j];
}
str = ansStr;
newAns = ansStr.Length;
}
return newAns;
}
}
Compare two characters at a time and replace if both adjacent characters are not same. To get optimal solution, run once from start of the string and once from end of the string. Return the minimum value.
Rav solution is :-
int same(char* s){
int i=0;
for(i=0;i<strlen(s)-1;i++){
if(*(s+i) == *(s+i+1))
continue;
else
return 0;
}
return 1;
}
int reduceb(char* s){
int ret = 0,a_sum=0,i=0;
int len = strlen(s);
while(1){
i=len-1;
while(i>0){
if ((*(s+i)) == (*(s+i-1))){
i--;
continue;
} else {
a_sum = (*(s+i)) + (*(s+i-1));
*(s+i-1) = SUM - a_sum;
*(s+i) = '\0';
len--;
}
i--;
}
if(same(s) == 1){
return strlen(s);
}
}
}
int reducef(char* s){
int ret = 0,a_sum=0,i=0;
int len = strlen(s);
while(1){
i=0;
while(i<len-1){
if ((*(s+i)) == (*(s+i+1))){
i++;
continue;
} else {
a_sum = (*(s+i)) + (*(s+i+1));
*(s+i) = SUM - a_sum;
int j=i+1;
for(j=i+1;j<len;j++)
*(s+j) = *(s+j+1);
len--;
}
i++;
}
if(same(s) == 1){
return strlen(s);
}
}
}
int main(){
int n,i=0,f=0,b=0;
scanf("%d",&n);
int a[n];
while(i<n){
char* str = (char*)malloc(101);
scanf("%s",str);
char* strd = strdup(str);
f = reducef(str);
b = reduceb(strd);
if( f > b)
a[i] = b;
else
a[i] = f;
free(str);
free(strd);
i++;
}
for(i=0;i<n;i++)
printf("%d\n",a[i]);
}
#Rav
this code will fail for input "abccaccba".
solution should be only "b"
but this code wont give that. Since i am not getting correct comment place(due to low points or any other reason) so i did it here.
This problem can be solved by greedy approach. Try to find the best position to apply transformation until no transformation exists. The best position is the position with max number of distinct neighbors of the transformed character.
You can solve this using 2 pass.
In the first pass you apply
len = strlen (str) ;
index = 0 ;
flag = 0 ;
/* 1st pass */
for ( i = len-1 ; i > 0 ; i -- ) {
if ( str[i] != str[i-1] ) {
str[i-1] = getChar (str[i], str[i-1]) ;
if (i == 1) {
output1[index++] = str[i-1] ;
flag = 1 ;
break ;
}
}
else output1[index++] = str[i] ;
}
if ( flag == 0 )
output1[index++] = str[i] ;
output1[index] = '\0';
And in the 2nd pass you will apply the same on 'output1' to get the result.
So, One is forward pass another one is backward pass.
int previous = a.charAt(0);
boolean same = true;
int c = 0;
for(int i = 0; i < a.length();++i){
c ^= a.charAt(i)-'a'+1;
if(a.charAt(i) != previous) same = false;
}
if(same) return a.length();
if(c==0) return 2;
else return 1;
import java.util.Scanner;
public class StringReduction {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int length = str.length();
String result = stringReduction(str);
System.out.println(result);
}
private static String stringReduction(String str) {
String result = str.substring(0);
if(str.length()<2){
return str;
}
if(str.length() == 2){
return combine(str.charAt(0),str.charAt(1));
}
for(int i =1;i<str.length();i++){
if(str.charAt(i-1) != str.charAt(i)){
String temp = str.substring(0, i-1) + combine(str.charAt(i-1),str.charAt(i)) + str.substring(i+1, str.length());
String sub = stringReduction(temp);
if(sub.length() < result.length()){
result = sub;
}
}
}
return result;
}
private static String combine(char c1, char c2) {
if(c1 == c2){
return "" + c1 + c2;
}
else{
if(c1 == 'a'){
if(c2 == 'b'){
return "" + 'c';
}
if(c2 == 'c') {
return "" + 'b';
}
}
if(c1 == 'b'){
if(c2 == 'a'){
return "" + 'c';
}
if(c2 == 'c') {
return "" + 'a';
}
}
if(c1 == 'c'){
if(c2 == 'a'){
return "" + 'b';
}
if(c2 == 'b') {
return "" + 'a';
}
}
return null;
}
}
}
JAVASCRIPT SOLUTION:
function StringChallenge(str) {
// code goes here
if(str.length == 1) {
return 1;
} else {
let prevAns = str.length;
let newAns = 0;
while(prevAns != newAns) {
prevAns = newAns;
let ansStr = "";
let i = 1;
let j = 0;
while(i < str.length) {
if(str[i] !== str[j]) {
if(str[i] != 'a' && str[j] != 'a') {
ansStr += 'a';
} else if(str[i] != 'b' && str[j] !='b') {
ansStr +='b';
} else if(str[i] != 'c' && str[j] != 'c') {
ansStr += 'c';
}
i += 2;
j += 2;
} else {
ansStr += str[j];
j++;
i++;
}
}
if(j < str.length) {
ansStr += str[j];
}
str = ansStr;
newAns = ansStr.length;
}
return newAns;
}
}

Resources