Can Someone help me?
I want to Iterate the Value of 'n' in This Manner. in any Language.
please explain the Concept.
if n = 5
sum = (5x5)+(4x4)-(3x3)+(2x2)-(1x1)
sum = 35;
I want to display like that value.
but it should iterate in this Manner
(nxn)+(n-1xn-1)-(n-2xn-2)+(n-3xn-3)-(n-4xn-4)+...;
When n-x==1 that time the iteration should get stop and Value should be printed.
for(i=1;i<=n;i+){
sum=0
for(j=1;j<=i;j++){
sum = sum+(j*j);
if(j<=i){
print(sum);
}
}
}
This Is the Answer which i got.
#include <iostream>
using namespace std;
int main()
{
int limit;
int sumOfSquare = 0;
cin>>limit;
sumOfSquare= limit*limit;
for(int num = 1; num<limit; num++)
{
if(limit%2==0){
if(num%2==0)
sumOfSquare = sumOfSquare - (num * num);
else
sumOfSquare = sumOfSquare + (num * num);
}else{
if(num%2==0)
sumOfSquare = sumOfSquare + (num * num);
else
sumOfSquare = sumOfSquare - (num * num);
}
}
cout<<"Output of " << limit << " is " << sumOfSquare;
return 0;
}
Related
I have an array which is constituted of only 0s and 1s. Task is to find index of a 0, replacing which with a 1 results in the longest possible sequence of ones for the given array.
Solution has to work within O(n) time and O(1) space.
Eg:
Array - 011101101001
Answer - 4 ( that produces 011111101001)
My Approach gives me a result better than O(n2) but times out on long string inputs.
int findIndex(int[] a){
int maxlength = 0; int maxIndex= -1;
int n=a.length;
int i=0;
while(true){
if( a[i] == 0 ){
int leftLenght=0;
int j=i-1;
//finding count of 1s to left of this zero
while(j>=0){
if(a[j]!=1){
break;
}
leftLenght++;
j--;
}
int rightLenght=0;
j=i+1;
// finding count of 1s to right of this zero
while(j<n){
if(a[j]!=1){
break;
}
rightLenght++;
j++;
}
if(maxlength < leftLenght+rightLenght + 1){
maxlength = leftLenght+rightLenght + 1;
maxIndex = i;
}
}
if(i == n-1){
break;
}
i++;
}
return maxIndex;
}
The approach is simple, you just need to maintain two numbers while iterating through the array, the current count of the continuous block of one, and the last continuous block of one, which separated by zero.
Note: this solution assumes that there will be at least one zero in the array, otherwise, it will return -1
int cal(int[]data){
int last = 0;
int cur = 0;
int max = 0;
int start = -1;
int index = -1;
for(int i = 0; i < data.length; i++){
if(data[i] == 0){
if(max < 1 + last + cur){
max = 1 + last + cur;
if(start != -1){
index = start;
}else{
index = i;
}
}
last = cur;
start = i;
cur = 0;
}else{
cur++;
}
}
if(cur != 0 && start != -1){
if(max < 1 + last + cur){
return start;
}
}
return index;
}
O(n) time, O(1) space
Live demo: https://ideone.com/1hjS25
I believe the problem can we solved by just maintaining a variable which stores the last trails of 1's that we saw before reaching a '0'.
int last_trail = 0;
int cur_trail = 0;
int last_seen = -1;
int ans = 0, maxVal = 0;
for(int i = 0; i < a.size(); i++) {
if(a[i] == '0') {
if(cur_trail + last_trail + 1 > maxVal) {
maxVal = cur_trail + last_trail + 1;
ans = last_seen;
}
last_trail = cur_trail;
cur_trail = 0;
last_seen = i;
} else {
cur_trail++;
}
}
if(cur_trail + last_trail + 1 > maxVal && last_seen > -1) {
maxVal = cur_trail + last_trail + 1;
ans = last_seen;
}
This can be solved by a technique that is known as two pointers. Most two-pointers use O(1) space and O(n) time.
Code : https://www.ideone.com/N8bznU
#include <iostream>
#include <string>
using namespace std;
int findOptimal(string &s) {
s += '0'; // add a sentinel 0
int best_zero = -1;
int prev_zero = -1;
int zeros_in_interval = 0;
int start = 0;
int best_answer = -1;
for(int i = 0; i < (int)s.length(); ++i) {
if(s[i] == '1') continue;
else if(s[i] == '0' and zeros_in_interval == 0) {
zeros_in_interval++;
prev_zero = i;
}
else if(s[i] == '0' and zeros_in_interval == 1) {
int curr_answer = i - start; // [start, i) only contains one 0
cout << "tried this : [" << s.substr(start, i - start) << "]\n";
if(curr_answer > best_answer) {
best_answer = curr_answer;
best_zero = prev_zero;
}
start = prev_zero + 1;
prev_zero = i;
}
}
cout << "Answer = " << best_zero << endl;
return best_zero;
}
int main() {
string input = "011101101001";
findOptimal(input);
return 0;
}
This is an implementation in C++. The output looks like this:
tried this : [0111]
tried this : [111011]
tried this : [1101]
tried this : [10]
tried this : [01]
Answer = 4
I have this code where I have to edit the works of M with 2 values when required .
Mat is a distance given by distancetrasform . If I try to start facciene release me so I do not how I want the value int 2 . I tried to cast but nothing . How do I change the pixel values of M ? with int value ?
Mat M = Mat::zeros(300, 300, CV_8U);
int i, j;
for (i = 0; i < distanza.cols ; i++)
{
for (j = 0; j < distanza.rows ; j++)
{
if ((int)distanza.at<float>(i,j) > 0 )
{
M.at <uchar>(i,j) = 2 ; //here as i write ?
cout << " " << M.at <uchar>(i, j) << endl;
}
}
}
#include<stdio.h>
#include<iostream.h>
#include<conio.h>
void quicks(int *arr,int x,int pivot,int lo,int hi);
void swap1(int *x,int *y);
int main()
{
int *arr = new int[7];
arr[0] = 23;
arr[1] = 3;
arr[2] = -23;
arr[3] = 45;
arr[4] = 12;
arr[5] = 76;
arr[6] = -65;
quicks(arr,7,0,1,6);
for(int i = 0;i<7;i++)
std::cout << arr[i] <<"\t";
getch();
return 0;
}
void quicks(int *arr,int x,int pivot,int lo,int hi)
{
int i = lo,j = hi;
if(pivot < x-1)
{
while(i <= hi)
{
if(arr[i] <= arr[pivot])
i++;
else
break;
}
while(j >= lo)
{
if(arr[j] >= arr[pivot])
j--;
else
break;
}
if( i > j)
{
swap1(&arr[j],&arr[pivot]);
lo = pivot+1;
hi = x - 1;
quicks(arr,x,pivot,lo,hi);
}
else if(i == j)
{
pivot = pivot + 1;
lo = pivot+1;
hi = x - 1;
quicks(arr,x,pivot,lo,hi);
}
else if(i < j)
{
swap1(&arr[j],&arr[i]);
lo = i + 1;
hi = j - 1;
quicks(arr,x,pivot,lo,hi);
}
}
else
{
printf("\nDONE\n");
}
}
void swap1(int *x,int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
Hi,
I have written a program to implement Quick sort.But the program is going into an infinite loop.In the Quicks function,the while loops for incrementing and decrementing i and j are the problem.Can anybody tell me what is wrong with this Implementation of QUick Sort.
Do a quick dry run using your input and the algorithm, you'll notice you run into an infinite cycle after a while.
You are starting the loop from quicks(arr,7,0,1,6);. Try instead by setting low to the "rightmost" element, that is 0. This won't definitely solve your problem as the algorithm seems really flawed, with the position of high not changing at all, and i moving all the way to high. You're trying to complicate a very simple task.
i would go from lo to pivot. And j from hi to pivot. After the pivot is found to be in the right place, you'll move forward pivot and lo by 1, and repeat the process.
Take a look at this image, you'll get an idea of the algo required:
I'm trying to construct an algorithm that runs at O(nb) time with the following input/question:
input: an array A[1..n] of n different integers and an integer b (i am assuming that the numbers in A are sequential, starting at 1 ending at n, i.e. for n=4 A[1,2,3,4].
question: in how many ways can b be written as the sum of elements of the array when elements in A[] can only be used once?
I've kind of hit a wall on this one. I'm looking for some kind of recursive solution, but I don't see how to avoid using repeat numbers. Like, for instance, if we started at 1 and stored all the ways to make one (just 1) then 2 (just 2) then three (3 or 2+1) etc, it shouldn't be hard to see how many ways we can make larger numbers. But if, for instance, we take 5, we will see that it can be broken into 4+1, and 4 can be further broken down into 3+1, so then we would see 2 solutions (4+1, and 3+1+1), but one of those has a repeat of a number. Am I missing something obvious? Thanks so much!
Recursive and dynamic solutions in C:
#include <stddef.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
typedef unsigned char uchar;
typedef unsigned int uint;
typedef struct tAddend
{
struct tAddend* pPrev;
uint Value;
} tAddend;
void findRecursiveSolution(uint n, uint maxAddend, tAddend* pPrevAddend)
{
uint i;
for (i = maxAddend; ; i--)
{
if (n == 0)
{
while (pPrevAddend != NULL)
{
printf("+%u", pPrevAddend->Value);
pPrevAddend = pPrevAddend->pPrev;
}
printf("\n");
return;
}
if (n >= i && i > 0)
{
tAddend a;
a.pPrev = pPrevAddend;
a.Value = i;
findRecursiveSolution(n - i, i - 1, &a);
}
if (i <= 1)
{
break;
}
}
}
void printDynamicSolution(uchar** pTable, uint n, uint idx, uint sum, tAddend* pPrevAddend)
{
uchar el = pTable[idx][sum];
assert((el != 0) && (el != 5) && (el != 7));
if (el & 2) // 2,3,6 - other(s)
{
printDynamicSolution(pTable,
n,
idx - 1,
sum,
pPrevAddend);
}
if (el & 4) // self + other(s)
{
tAddend a;
a.pPrev = pPrevAddend;
a.Value = idx + 1;
printDynamicSolution(pTable,
n,
idx - 1,
sum - (idx + 1),
&a);
}
if (el & 1) // self, found a solution
{
tAddend a;
a.pPrev = pPrevAddend;
a.Value = idx + 1;
pPrevAddend = &a;
while (pPrevAddend != NULL)
{
printf("+%u", pPrevAddend->Value);
pPrevAddend = pPrevAddend->pPrev;
}
printf("\n");
}
}
void findDynamicSolution(uint n)
{
uchar** table;
uint i, j;
if (n == 0)
{
return;
}
// Allocate the DP table
table = malloc(sizeof(uchar*) * n);
if (table == NULL)
{
printf("not enough memory\n");
return;
}
for (i = 0; i < n; i++)
{
table[i] = malloc(n + 1);
if (table[i] == NULL)
{
while (i > 0)
{
free(table[--i]);
}
free(table);
printf("not enough memory\n");
return;
}
}
// Fill in the DP table
for (i = 0; i < n; i++)
{
for (j = 0; j <= n; j++)
{
if (i == 0)
{
table[i][j] = (i + 1 == j); // self
}
else
{
table[i][j] = (i + 1 == j) + // self
2 * (table[i - 1][j] != 0) + // other(s)
4 * ((j >= i + 1) && (table[i - 1][j - (i + 1)] != 0)); // self + other(s)
}
}
}
printDynamicSolution(table, n, n - 1, n, NULL);
for (i = 0; i < n; i++)
{
free(table[i]);
}
free(table);
}
int main(int argc, char** argv)
{
uint n;
if (argc != 2 || sscanf(argv[1], "%u", &n) != 1)
{
n = 10;
}
printf("Recursive Solution:\n");
findRecursiveSolution(n, n, NULL);
printf("\nDynamic Solution:\n");
findDynamicSolution(n);
return 0;
}
Output:
for 10:
Recursive Solution:
+10
+1+9
+2+8
+3+7
+1+2+7
+4+6
+1+3+6
+1+4+5
+2+3+5
+1+2+3+4
Dynamic Solution:
+1+2+3+4
+2+3+5
+1+4+5
+1+3+6
+4+6
+1+2+7
+3+7
+2+8
+1+9
+10
See also on ideone.
Let F(x,i) be the number of ways elements of A[1:i] can be summed to get x.
F(x,i+1) = F(x-A[i+1],i) + F(x,i)
That is it!
This is not a dynamic programming solution though. Non-recursive.
Assumption that arr is sorted in your case like [i....j] where a[i] <= a[j]
That's easy enough
void summer(int[] arr, int n , int b)
{
int lowerbound = 0;
int upperbound = n-1;
while (lowerbound < upperbound)
{
if(arr[lowerbound]+arr[upperbound] == b)
{
// print arr[lowerbound] and arr[upperbound]
lowerbound++; upperbound--;
}
else if(arr[lowerbound]+arr[upperbound] < b)
lowerbound++;
else
upperbound--;
}
}
The above program is easily modifiable to a recursive you need to only change the function definition by passing lowerbound and upperbound.
Case for termination is still lowerbound < upperbound
Base case is if arr[lowerbound] +arr[upperbound] == b
Edited based on comments
You will need to use a modified version of integer knapsack problem. The values of [i,j] both need to be modified accordingly. You are having the problem because you are not most probably modifying your i carefully, Increase your i accordingly then their will not be repetition like the one you are having.
Given two strings, S1 & S2. given scoring scheme where gap penalty, mismatch score and match score.
Find the S1 which have a best match with S2.
My idea is to list all possible S1 and then match one by one with S2. List all possible S1 by using brute force. Then match each possible S1 with S2 by using dp.
Is there is any faster way to do so? or suggest any reference?
Using Wikipedia and a little bit of thinking one could code up something like this:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#ifndef MAX
#define MAX(a,b) ((a)>(b)?(a):(b))
#endif
#define MATCH_SCORE 2
#define MISMATCH_SCORE -1
#define GAP_SCORE 0
// Calculates the match score recursively.
long MatchScore(const char* p/* in: may contain 'x' */,
const char* s/* in: doesn't contain 'x' */)
{
long res;
if (*p && *s)
{
if ((*p == *s) ||
((*p == 'x') && (*s >= 'a') && (*s <= 'f')))
{
res = MatchScore(p + 1, s + 1) + MATCH_SCORE;
}
else
{
long s1 = MatchScore(p + 1, s + 1) + MISMATCH_SCORE;
long s2 = MatchScore(p, s + 1) + GAP_SCORE;
long s3 = MatchScore(p + 1, s) + GAP_SCORE;
res = MAX(s1, MAX(s2, s3));
}
}
else
{
res = GAP_SCORE * (long)(strlen(p) + strlen(s));
}
return res;
}
// Calculates the best matching string and the match score
// using dynamic programming, the score must be the same
// as returned by MatchScore().
void FindBestMatch(const char* p/* in: may contain 'x' */,
const char* s/* in: doesn't contain 'x' */,
long* score/* out: match score */,
char** match/* out: best matching string */)
{
size_t lp = strlen(p) + 1;
size_t ls = strlen(s) + 1;
size_t i, j;
long* table = (long*)malloc(lp * ls * sizeof(long));
for (i = 0; i < lp; i++)
table[0 * lp + i] = GAP_SCORE * i;
for (j = 0; j < ls; j++)
table[j * lp + 0] = GAP_SCORE * j;
for (j = 1; j < ls; j++)
{
for (i = 1; i < lp; i++)
{
if ((p[i-1] == s[j-1]) ||
((p[i-1] == 'x') && (s[j-1] >= 'a') && (s[j-1] <= 'f')))
{
table[j * lp + i] = table[(j-1) * lp + (i-1)] + MATCH_SCORE;
}
else
{
table[j * lp + i] =
MAX(table[(j-1) * lp + (i-1)] + MISMATCH_SCORE,
MAX(table[(j-1) * lp + i] + GAP_SCORE,
table[j * lp + (i-1)] + GAP_SCORE));
}
}
}
*score = table[lp * ls - 1];
// Now, trace back the score table and construct the best matching string
*match = (char*)malloc(lp);
(*match)[lp - 1] = '\0';
for (j = ls, i = lp; j || i;)
{
if ((p[i-1] == s[j-1]) ||
((p[i-1] == 'x') && (s[j-1] >= 'a') && (s[j-1] <= 'f')))
{
(*match)[i-1] = s[j-1];
j--;
i--;
}
else
{
if (table[(j-1) * lp + i] > table[j * lp + (i-1)])
{
j--;
}
else
{
(*match)[i-1] = p[i-1];
i--;
}
}
}
free(table);
}
int main(void)
{
const char* pattern = "acdxdcxecxf";
const char* str = "abdfdaaed";
long score;
char* match;
char* match2;
printf("pattern=\"%s\" str=\"%s\"\n", pattern, str);
FindBestMatch(pattern, str, &score, &match);
printf("score=%ld (recursive)\n", MatchScore(pattern, str));
printf("score=%ld best match=\"%s\"\n", score, match);
// Now repeat with the best match we've just found,
// the result must be the same
printf("\nRepeating with pattern=best match:\n\n");
printf("pattern=\"%s\" str=\"%s\"\n", match, str);
FindBestMatch(match, str, &score, &match2);
printf("score=%ld (recursive)\n", MatchScore(match, str));
printf("score=%ld best match=\"%s\"\n", score, match2);
free(match);
free(match2);
return 0;
}
Output:
pattern="acdxdcxecxf" str="abdfdaaed"
score=14 (recursive)
score=14 best match="acdfdcaecdf"
Repeating with pattern=best match:
pattern="acdfdcaecdf" str="abdfdaaed"
score=14 (recursive)
score=14 best match="acdfdcaecdf"
I wonder if there're any bugs (other than the apparent lack of error checking).