Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to use dynamic programming to determine the minimum edits required on one string
to transform it into another string
The code below does this, but I'm trying to find a way to keep track of the edits (d=delete, r=replace, i=insert).
For example:
string 1: sunflower
d rrrr <---Changes applying to string 1 (tracking minimum edits necessary to transform it into string 2)
string 2: sunlight
I'm not certain how to accomplish this, but I suspect it might have something to do with backtracking through the minimum distance table which is created. The code below finds the minimum distance perfectly fine, but I'm not certain how to approach keeping track of the necessary edits. Any ideas?
#include<iostream>
#include<cstring>
#define INSERT_COST 1
#define DELETE_COST 1
#define REPLACE_COST 1
using namespace std;
int min(int a,int b) {
return ((a < b) ? a : b);
}
/* convert str1 to str2 with minimum edits(insert,delete,replace)
suppose length(str1) = m and length(str2) = n
cost(i,j) -> cost of converting str1[0...i-1] to str2[0...j-1]
cost(m,n) -> cost of converting str1 to str2
Standard recursive formula for computing cost(m,n) :-
cost(i,j) = min[cost(i-1,j)+D, cost(i,j-1)+I, cost(i-1,j-1)+R]
D -> delete cost, I -> insert cost, R -> replace cost */
int editDistance(char str1[],int size1,char str2[],int size2) {
// cost matrix
// row -> str1 & col -> str2
int cost[size1][size2];
int i,j;
// initialize the cost matrix
for (i=0;i<size1;i++) {
for(j=0;j<size2;j++) {
if (i == 0) {
// source string is NULL
// so we need 'j' insert operations
cost[i][j] = j*INSERT_COST;
} else if (j == 0) {
// target string is NULL
// so we need 'i' delete operations
cost[i][j] = i*DELETE_COST;
} else {
cost[i][j] = -1;
}
}
} //initialization done
//compute cost(i,j) and eventually return cost(m,n)
for(i=1;i<size1;i++) {
for(j=1;j<size2;j++) {
int x = cost[i-1][j] + DELETE_COST;
int y = cost[i][j-1] + INSERT_COST;
// if str1(i-1) != str2(j-1), add the replace cost
// we are comparing str1[i-1] and str2[j-1] since
// the array index starts from 0
int z = cost[i-1][j-1] + (str1[i-1] != str2[j-1])*REPLACE_COST;
// as per our recursive formula
cost[i][j] = min(x, min(y,z));
}
}
// last cell of the matrix holds the answer
return cost[size1-1][size2-1];
}
//main
int main() {
char str1[] = "sunflower";
char str2[] = "sunlight";
int size1 = strlen(str1);
int size2 = strlen(str2);
int min_cost = editDistance(str1,size1+1,str2,size2+1);
cout<<"\nMinimum edits required to convert "<<str1<<
" to "<<str2<<" is "<<min_cost;
cout<<endl;
return 0;
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
I need to find the largest sequence of identical digits in a given integer using a recursive function.
For example:
input: "2221", output: 3
input: "2223333", output: 4
input: "222333", output: 3
For some reason the code sometimes works correctly and sometimes it doesn't. when I input "1112" then it gives me the correct output (3), but when I input "1111555", I expected to get the output 4, but instead got 6.
Also, I can't change the parameters that the function receives so if someone knows how can I insert the parameters inside the function instead of outside (if I insert them inside the function then the output I receive is always 0)
I'd really appreciate the help so thank you in advance :)
My code:
int currentLength = 0, maxLength = 0;
int currentDigit = -1;
int maxSequence(int num)
{
if (num <= 0)
return maxLength;
int digit = num % 10;
if (digit == currentDigit) {
maxLength= 1 + maxSequence(num / 10);
}
else {
currentDigit = digit;
if (maxLength > 1)
{
maxLength = 0;
}
else
{
maxLength = 1;
}
return maxSequence(num / 10);
}
}
Recursion and mutable global variables is a nasty combination.
You can add the parameters to a different function and call that instead.
Something like this:
// Since you can't use std::max.
int max(int a, int b) { return a > b ? a : b; }
int maxSequenceHelper(int number, int last, int length, int maximum)
{
int digit = number % 10;
if (digit == last)
{
length += 1;
maximum = max(length, maximum);
}
else
{
length = 1;
}
return number < 10
? maximum
: maxSequenceHelper(number / 10, digit, length, maximum);
}
int maxSequence(int number)
{
return maxSequenceHelper(number / 10, number % 10, 1, 1);
}
And here is a version without any assignments, making it slightly easier to reason about:
int maxSequenceHelper(int number, int last, int length, int maximum)
{
const int digit = number % 10;
const int new_length = digit == last ? length + 1 : 1;
const int new_maximum = max(new_length, maximum);
return number < 10
? new_maximum
: maxSequenceHelper(number / 10, digit, new_length, new_maximum);
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
You are given a number, at a time either you can increase a number by 1 or decrease by 1 it is considered as one move find the minimum number of moves required to convert a given into a lucky number. A number is called lucky if all the digits in it are even.
I have writtern the code but I am not sure if it is correct. Can anybody please confirm me?
#include<bits/stdc++.h>
using namespace std;
int count(int n)
{
int count = 0;
while (n != 0)
{
n = n / 10;
++count;
}
return count;
}
int firstDigit(int n)
{
// Remove last digit from number
// till only one digit is left
while (n >= 10)
n /= 10;
// return the first digit
return n;
}
int main()
{
int n;
cin >> n;
int i,j,ans=0;
int x = count(n);
while(x--)
{
if(firstDigit(n)%2 != 0)
{
if(firstDigit(n) == 9)
{
ans = ans + pow(10,x);
n = n-pow(10,x);
}
else
{
ans = ans + pow(10,x);
n = n + pow(10,x);
}
}
else
n = n - pow(10,x);
}
cout << ans << endl;
}
Edit:
I found it is giving wrong answer at 100. Can you please help me in finding out the mistake
Not all code can easily be tested, thats why you should strive to write testable code right from the start (instead of first writing it all and then try to confirm correctness). In your case testability could benefit a lot from moving most logic from main into a dedicated function:
int minimal_steps(int input) {
....
}
Once you have that, you can either call it in main with user supplied input just as you do it now, but you can also write tests more easily:
void test() {
assert( minimal_steps(2222) == 0);
assert( minimal_steps(2221) == 1);
...etc...
}
Once you got into the habit of testing your code (you should also write tests for count and firstDigit) you may consider to use a testing framework to automate tests.
PS: It isnt wrong, but it is such a waste of CPU cycles that it is worth mentioning (actually it was already mentioned in a comment). You do not need to compute pow(10,x) in a loop where x is the loop counter. Consider that you are computing 10^2 almost as many times as the loop has iterations. Also 10^3 is the same in every iteration. Instead you should only update with *10 (in case x is incremented) or /10 when x decrements between iterations. Moreover, pow is for floating-points, not for integers.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Consider an array arr.
s1 and s2 are any two sub sets of our original array arr. We should partition our original array such that these two sub sets have the minimum difference, i.e., min(sum(s1) - sum(s2)) where sum(s1) >= sum(s2).
I'm supposed to print these two sub sets, i.e., s1 and s2, as my output.
You can store these sub sets in a vector.
For example if arr[] = [0,1,5,6], then the minimal difference is 0 and my two sub sets are s1[] = [0,1,5] and s2[] = [6].
Another example could be arr[] = [16,14,13,13,12,10,9,3], and the two sub sets would be s1[]=[16,13,13,3] and s2[] = [14,12,10,9] with a minimum difference of 0 again.
I can't seem to figure out how to get to these two sub sets.
Much appreciated!
Note: I know how to obtain the minimum difference from the two sub sets using DP but I am unable to proceed further. It's getting the two sub sets (with the minimal difference) that I'm unable to do.
Just an algorithm with a nudge along the right direction would do.
#include<iostream>
#include<vector>
using namespace std;
int min_subset_sum_diff(int a[], int n,int sum) {
vector<vector<bool>> go(n + 1, vector<bool>(sum + 1, false));
for (int i = 0; i < n + 1; ++i) {
go[i][0] = true;
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= sum; ++j) {
if (a[i - 1] <= j) {
go[i][j] = go[i - 1][j - a[i - 1]] || go[i - 1][j];
}
else {
go[i][j] = go[i - 1][j];
}
}
}
for (int j = (sum / 2); j >= 0; --j) {
if (go[n][j]) { // only need the last row as I need all the elements, which is n
return sum - 2 * j;
}
}
return INT_MAX;
}
int main() {
int a[] = { 3,100,4,4 };
int n = sizeof(a) / sizeof(a[0]);
int sum = 0;
for (auto i : a) {
sum += i;
}
cout << min_subset_sum_diff(a, n,sum);
}
s1 = sum(first_subset)
s2= sum(second_subset)
Assuming s2>=s1,
s1 + s2 = sum_arr
s2 = sum_arr - s1 //using this in the next equation
s2-s1 = difference
(sum_arr - s1) - s1 = difference
sum_arr - 2*s1 = difference
This is my underlying logic.
sum(s1) and sum(s2) lie between 0..sum_arr
Since I assume s1 < s2, s1 can have values only between 0..(sum_arr/2)
And my aim is to minimum value of sum_arr - 2*s1, this will be true for the largest s1 that is true
Make parallel table of int T[][] with the same dimensions as go[][]
When you make a decision here
if (a[i - 1] <= j)
put in T[i][j] some kind of information pointing onto true precursor coordinates for go[i][j]
After filling the tables you search for the best true entry in go[n] row of boolean table. When it is found, get value from the same cell of T table and follow to precursor, then to precursor of prcursor and so on ("unwind" subset information)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to make a c++ program that merges the elements of an array For example we have three elements that are 2 5 7 and we want merge them make a number 257
Most efficient solution:
#include <iostream>
using namespace std;
int main()
{
const int N = 3;
int a[N] = {2,5,7};
int num = 0;
for(int i=0;i<N;i++)
num = num * 10 + a[i];
cout << num << endl;
return 0;
}
steps:
num -> 0
num -> 2
num -> 25
num -> 257
The simplest way is to use the range based for statement. For example
int a[] = { 2, 5, 7 };
int x = 0;
for ( int digit : a ) x = 10 * x + digit;
Here is demonstrative program
#include <iostream>
int main()
{
int a[] = { 2, 5, 7 };
int x = 0;
for ( int digit : a ) x = 10 * x + digit;
std::cout << "x = " << x << std::endl;
return 0;
}
The output is
x = 257
The same can be done using standard algorithm std::accumulate declared in header <algorithm>
Take into account that the array has to have acceptable values like digits and that the resulted number would not overflow the acceptable range of values for the given type of the accumulator.
#include <iostream>
#include <cmath>
int main()
{
const int N = 3; // the size of the array
int a[N] = {2,5,7};
// define the number that will hold our final "merged" number
int nbr = 0;
// loop through the array and multiply each number by the correct
// power of ten and add it to the merged number
for(int i=N-1;i>=0;--i){
nbr += a[i] * pow(10, N-1-i);
}
// print the number
std::cout << nbr << std::endl;
return 0;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have to make this C++ code in Dart, but I find it really difficult. I tryed watching Darts video and searching on the web, but with no success.Could someone be able to give me a hand?
This is the code:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
if (n < 0) return 1;
int sum = 0;
int i = 0;
while (i <= n) sum += i*i;
cout << sum;
return 0;
}
something like
library x;
import 'dart:io';
void main(List<String> args) {
int n;
print('input a number');
String input = stdin.readLineSync();
n = int.parse(input);
print('n: $n');
if(n < 0) {
exit(1);
}
int sum = 0;
int i = 0;
while(i <= n) {
print(sum);
sum += i * i;
}
print(sum);
}
But don't expect to much.
When reaching the while loop sum and i are 0.
This way you have produced a nice endless loop to busy your computer ;-)
You could do the calculation bit (sum of squares of all numbers from 1 to n inclusive) with a recursive function like:
int recur(int n) => (n > 0) ? (n * n) + recur(n - 1) : 0;
Then it's a simple matter of figuring out how to enter n and output recur(n). That can be done with stdin.readLineSync and print. That would be along the following lines:
int recur(int n) => (n > 0) ? (n * n) + recur(n - 1) : 0;
void main( List<String> args ) {
int inNum;
String input = stdin.readLineSync();
inNum = int.parse( input );
if (inNum < 0) {
exit( 1 );
}
print( recur( sum ) );
}
Just be careful with large input values, I'm not sure whether Dart is smart enough to do tail end recursion optimisation. If not, stack space may be an issue.