Swap two characters in the cell array of strings - string

I have a cell array of string and I want to swap A and B in a percentage of the cell array , like 20%, 30% of the total number of strings in the cell array
For example :
A_in={ 'ABCDE'
'ACD'
'ABCDE'
'ABCD'
'CDE' };
Now, we need to swap A and B in 40% of the sequences in A (2/5 sequences ). There are some sequences which do not contain A and B so we just skip them, and we will swap the sequences which contain AB . The pickup sequences in A are chosen randomly. I appropriate someone can tell me how to do this . The expected output is:
A_out={ 'ABCDE'
'ACD'
'BACDE'
'BACD'
'CDE' }

Get the random precent index with randsample and swap with strrep
% Input
swapStr = 'AB';
swapPerc = 0.4; % 40%
% Get index to swap
hasPair = find(~cellfun('isempty', regexp(A_in, swapStr)));
swapIdx = randsample(hasPair, ceil(numel(hasPair) * swapPerc));
% Swap char pair
A_out = A_in;
A_out(swapIdx) = strrep(A_out(swapIdx), swapStr, fliplr(swapStr));

you can use strfind, like:
A_in={ 'ABCDE';
'ACD';
'ABCDE';
'ABCD';
'CDE' };
ABcells = strfind(A_in,'AB');
idxs = find(~cellfun(#isempty,ABcells));
n = numel(idxs);
perc = 0.6;
k = round(n*perc);
idxs = randsample(idxs,k);
A_out = A_in;
A_out(idxs) = cellfun(#(a,idx) [a(1:idx-1) 'BA' a(idx+2:end)],A_in(idxs),ABcells(idxs),'UniformOutput',false);

Related

Calculate total number of characters in all substrings of a string without loops or recursion

A string like ADAM has the following substrings
A
AD
ADA
ADAM
D
DA
DAM
A
AM
M
To calculate the total number of substrings I can do a O(1) operation as follows ADAM -> 10.
function calcNumSubstrings(strlen) {
return (strlen * (strlen + 1) / 2);
}
What I need is the sum of all characters in all of those substrings. In the case of ADAM this is 20. To get this I can do an O(N) operation like this:
function calcTotalLettersInAllSubstrings(strlen) {
let total = 0;
for (let i = 1; i <= strlen; i++) {
total += calcNumSubstrings(i);
}
return total;
}
This is basically: ((1*(1+1))/2) + ((2*(2+1))/2) + ((3*(3+1))/2) + ((4*(4+1))/2)
Is there an O(1) way of calculating this or am I breaking my head over nothing?
Just do some math. Let n be length of string and let sum(expr) be the sum from r=1 to r=n of the given expression, then for a given substring length r you have (n+1-r) possible substrings, hence :
sum(r(n+1-r)) = (n+1)sum(r) - sum(r^2)
Now refer to standard sums of series here, which gives :
sum(r) = n(n+1)/2
sum(r^2) = n(n+1)(2n+1)/6
Therefore :
sum(r(n+1-r)) = n(n+1)^2 / 2 - n(n+1)(2n+1)
checking for n=4
sum(r(5-r)) = 50 - 30 = 20
Simplifying this expression gives :
sum(r(n+1-r)) = n(n+1)/2( (n+1) - (2n+1)/3)
= n(n+1)/6( 3n+3 -2n -1)
= n(n+1)(n+2)/6
As above
The general case is : n*(n+1)*(n+2)/6
Where n is the number of characters in the string.
So in this case, the number of characters is 4: 4*(4+1)*(4+2)/6 = 20

total substrings with k ones

Given a binary string s, we need to find the number of its substrings, containing exactly k characters that are '1'.
For example: s = "1010" and k = 1, answer = 6.
Now, I solved it using binary search technique over the cumulative sum array.
I also used another approach to solve it. The approach is as follows:
For each position i, find the total substrings that end at i containing
exactly k characters that are '1'.
To find the total substrings that end at i containing exactly k characters that are 1, it can be represented as the set of indices j such that substring j to i contains exactly k '1's. The answer would be the size of the set. Now, to find all such j for the given position i, we can rephrase the problem as finding all j such that
number of ones from [1] to [j - 1] = the total number of ones from 1 to i - [the total number of ones from j to i = k].
i.e. number of ones from [1] to [j - 1] = C[i] - k
which is equal to
C[j - 1] = C[i] - k,
where C is the cumulative sum array, where
C[i] = sum of characters of string from 1 to i.
Now, the problem is easy because, we can find all the possible values of j's using the equation by counting all the prefixes that sum to C[i] - k.
But I found this solution,
int main() {
cin >> k >> S;
C[0] = 1;
for (int i = 0; S[i]; ++i) {
s += S[i] == '1';
++C[s];
}
for (int i = k; i <= s; ++i) {
if (k == 0) {
a += (C[i] - 1) * C[i] / 2;
} else {
a += C[i] * C[i - k];
}
}
cout << a << endl;
return 0;
}
In the code, S is the given string and K as described above, C is the cumulative sum array and a is the answer.
What is the code exactly doing by using multiplication, I don't know.
Could anybody explain the algorithm?
If you see the way C[i] is calculated, C[i] represents the number of characters between ith 1 and i+1st 1.
If you take an example S = 1001000
C[0] = 1
C[1] = 3 // length of 100
C[2] = 4 // length of 1000
So coming to your doubt, Why multiplication
Say your K=1, then you want to find out the substring which have only one 1, now you know that after first 1 there are two zeros since C[1] = 3. So number of of substrings will be 3, because you have to include this 1.
{1,10,100}
But when you come to the second part: C[2] =4
now if you see 1000 and you know that you can make 4 substrings (which is equal to C[2])
{1,10,100,1000}
and also you should notice that there are C[1]-1 zeroes before this 1.
So by including those zeroes you can make more substring, in this case by including 0 once
0{1,10,100,1000}
=> {01,010,0100,01000}
and 00 once
00{1,10,100,1000}
=> {001,0010,00100,001000}
so essentially you are making C[i] substrings starting with 1 and you can append i number of zeroes before this one and make another C[i] * C[i-k]-1 substrings. i varies from 1 to C[i-k]-1 (-1 because we want to leave that last one).
((C[i-k]-1)* C[i]) +C[i]
=> C[i-k]*C[i]

Modified longest common substring

Given two strings what is an efficient algorithm to find the number and length of longest common sub-strings with the sub-strings being called common if :
1) they have at-least x% characters same and at same position.
2) the start and end indexes of the sub-strings being same.
Ex :
String 1 -> abedefkhj
String 2 -> kbfdfjhlo
suppose the x% being asked is 40,then, ans is,
5 1
where 5 is the longest length and 1 is the number of sub-strings in each string satisfying the given property. Sub-String is "abede" in string 1 and "kbfdf" in string 2.
You can use smth like Levenshtein distance without deleting and inserting.
Build the table, where every element [i, j] is error for substring from position [i] to position [j].
foo(string a, string b, int x):
len = min(a.length, b.length)
error[0][0] = 0 if a[0] == b[0] else 1;
for (end: [1 -> len-1]):
for (start: [end -> 0]):
if a[end] == b[end]:
error[start][end] = error[start][end - 1]
else:
error[start][end] = error[start][end - 1] + 1
best_len = 0;
best_pos = 0;
for (i: [0 -> len-1]):
for (j: [i -> 0]):
len = i - j + 1
error_percent = 100 * error[i][j] / len
if (error_percent <= x and len > best_len):
best_len = len
best_pos = j
return (best_len, best_pos)

Return all subsequences of a String

I'm trying to write pseudo-code and an algorithm in Matlab, to return all the subsequences of a string.
So the string X = {ABCD} will return XSubSequence = {A, B, C, D, AB, AC, AD, BC, BD, CD, ABC, ABD, BCD, ABCD}, order does not matter of course.
clear
x = 'ABC';
XSize = length(x);
count = 1;
i=1;
for i=1:XSize
ZSubSequence{count} = x(i);
count = count + 1;
for j=i+1:XSize
temp = strcat(x(i),x(j));
ZSubSequence{count} = temp;
count = count + 1;
for k=i+2:XSize
if j ~= k
temp = strcat(x(i), x(j), x(k));
ZSubSequence{count} = temp;
count = count + 1;
end
end
end
end
Is there any way to make this more dynamic, so I can add X of any size and it will be able to deal with it?
You might want to consider a completely different approach.
This this is a binary representation of decimal numbers from 1 to 2^length(x)-1. Meaning for your example 1100=12 will be AB and 0011=3 will be CD, 1000 will be A and 1111=2^4-1=15 will be ABCD and so on.
You might want to create this sequence and then translate it into the input output you have.
Example code:
x = 'ABCD';
XSize = length(x);
seq=dec2bin([1:2^XSize-1]);
And now all have left is translate it back to letters
for i=1:1:2^XSize-1
for j=1:1:XSize
if seq(i,j)=='1'
seq(i,j)=x(j);
else
seq(i,j)='_';
end
end
end
Obviously the '_' should be removed and the output formatted the way you want them to be.
This should do it. It only has one loop (no nesting), so it shoud be pretty fast.
x = 'ABCD';
n = length(x);
subseq = x.';
for ii = 2:n
subseq = strvcat(subseq, x(nchoosek(1:n,ii)));
end
subseq_deblanked = deblank(mat2cell(subseq, ones(size(subseq,1),1), n));
The results are:
subseq: char matrix where each row contains a subsequence padded with blank spaces.
subseq_deblanked: cell array of strings with the blank spaces removed, as you specified

Finding minimum moves required for making 2 strings equal

This is a question from one of the online coding challenge (which has completed).
I just need some logic for this as to how to approach.
Problem Statement:
We have two strings A and B with the same super set of characters. We need to change these strings to obtain two equal strings. In each move we can perform one of the following operations:
1. swap two consecutive characters of a string
2. swap the first and the last characters of a string
A move can be performed on either string.
What is the minimum number of moves that we need in order to obtain two equal strings?
Input Format and Constraints:
The first and the second line of the input contains two strings A and B. It is guaranteed that the superset their characters are equal.
1 <= length(A) = length(B) <= 2000
All the input characters are between 'a' and 'z'
Output Format:
Print the minimum number of moves to the only line of the output
Sample input:
aab
baa
Sample output:
1
Explanation:
Swap the first and last character of the string aab to convert it to baa. The two strings are now equal.
EDIT : Here is my first try, but I'm getting wrong output. Can someone guide me what is wrong in my approach.
int minStringMoves(char* a, char* b) {
int length, pos, i, j, moves=0;
char *ptr;
length = strlen(a);
for(i=0;i<length;i++) {
// Find the first occurrence of b[i] in a
ptr = strchr(a,b[i]);
pos = ptr - a;
// If its the last element, swap with the first
if(i==0 && pos == length-1) {
swap(&a[0], &a[length-1]);
moves++;
}
// Else swap from current index till pos
else {
for(j=pos;j>i;j--) {
swap(&a[j],&a[j-1]);
moves++;
}
}
// If equal, break
if(strcmp(a,b) == 0)
break;
}
return moves;
}
Take a look at this example:
aaaaaaaaab
abaaaaaaaa
Your solution: 8
aaaaaaaaab -> aaaaaaaaba -> aaaaaaabaa -> aaaaaabaaa -> aaaaabaaaa ->
aaaabaaaaa -> aaabaaaaaa -> aabaaaaaaa -> abaaaaaaaa
Proper solution: 2
aaaaaaaaab -> baaaaaaaaa -> abaaaaaaaa
You should check if swapping in the other direction would give you better result.
But sometimes you will also ruin the previous part of the string. eg:
caaaaaaaab
cbaaaaaaaa
caaaaaaaab -> baaaaaaaac -> abaaaaaaac
You need another swap here to put back the 'c' to the first place.
The proper algorithm is probably even more complex, but you can see now what's wrong in your solution.
The A* algorithm might work for this problem.
The initial node will be the original string.
The goal node will be the target string.
Each child of a node will be all possible transformations of that string.
The current cost g(x) is simply the number of transformations thus far.
The heuristic h(x) is half the number of characters in the wrong position.
Since h(x) is admissible (because a single transformation can't put more than 2 characters in their correct positions), the path to the target string will give the least number of transformations possible.
However, an elementary implementation will likely be too slow. Calculating all possible transformations of a string would be rather expensive.
Note that there's a lot of similarity between a node's siblings (its parent's children) and its children. So you may be able to just calculate all transformations of the original string and, from there, simply copy and recalculate data involving changed characters.
You can use dynamic programming. Go over all swap possibilities while storing all the intermediate results along with the minimal number of steps that took you to get there. Actually, you are going to calculate the minimum number of steps for every possible target string that can be obtained by applying given rules for a number times. Once you calculate it all, you can print the minimum number of steps, which is needed to take you to the target string. Here's the sample code in JavaScript, and its usage for "aab" and "baa" examples:
function swap(str, i, j) {
var s = str.split("");
s[i] = str[j];
s[j] = str[i];
return s.join("");
}
function calcMinimumSteps(current, stepsCount)
{
if (typeof(memory[current]) !== "undefined") {
if (memory[current] > stepsCount) {
memory[current] = stepsCount;
} else if (memory[current] < stepsCount) {
stepsCount = memory[current];
}
} else {
memory[current] = stepsCount;
calcMinimumSteps(swap(current, 0, current.length-1), stepsCount+1);
for (var i = 0; i < current.length - 1; ++i) {
calcMinimumSteps(swap(current, i, i + 1), stepsCount+1);
}
}
}
var memory = {};
calcMinimumSteps("aab", 0);
alert("Minimum steps count: " + memory["baa"]);
Here is the ruby logic for this problem, copy this code in to rb file and execute.
str1 = "education" #Sample first string
str2 = "cnatdeiou" #Sample second string
moves_count = 0
no_swap = 0
count = str1.length - 1
def ends_swap(str1,str2)
str2 = swap_strings(str2,str2.length-1,0)
return str2
end
def swap_strings(str2,cp,np)
current_string = str2[cp]
new_string = str2[np]
str2[cp] = new_string
str2[np] = current_string
return str2
end
def consecutive_swap(str,current_position, target_position)
counter=0
diff = current_position > target_position ? -1 : 1
while current_position!=target_position
new_position = current_position + diff
str = swap_strings(str,current_position,new_position)
# p "-------"
# p "CP: #{current_position} NP: #{new_position} TP: #{target_position} String: #{str}"
current_position+=diff
counter+=1
end
return counter,str
end
while(str1 != str2 && count!=0)
counter = 1
if str1[-1]==str2[0]
# p "cross match"
str2 = ends_swap(str1,str2)
else
# p "No match for #{str2}-- Count: #{count}, TC: #{str1[count]}, CP: #{str2.index(str1[count])}"
str = str2[0..count]
cp = str.rindex(str1[count])
tp = count
counter, str2 = consecutive_swap(str2,cp,tp)
count-=1
end
moves_count+=counter
# p "Step: #{moves_count}"
# p str2
end
p "Total moves: #{moves_count}"
Please feel free to suggest any improvements in this code.
Try this code. Hope this will help you.
public class TwoStringIdentical {
static int lcs(String str1, String str2, int m, int n) {
int L[][] = new int[m + 1][n + 1];
int i, j;
for (i = 0; i <= m; i++) {
for (j = 0; j <= n; j++) {
if (i == 0 || j == 0)
L[i][j] = 0;
else if (str1.charAt(i - 1) == str2.charAt(j - 1))
L[i][j] = L[i - 1][j - 1] + 1;
else
L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]);
}
}
return L[m][n];
}
static void printMinTransformation(String str1, String str2) {
int m = str1.length();
int n = str2.length();
int len = lcs(str1, str2, m, n);
System.out.println((m - len)+(n - len));
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str1 = scan.nextLine();
String str2 = scan.nextLine();
printMinTransformation("asdfg", "sdfg");
}
}

Resources