Compare to string of names - string

I am trying to compare the names of two strings, and trying to pick out the name that are not included in the other string.
h = 1;
for i = 1:name_size_main
checker = 0;
main_name = main(i);
for j = 1:name_size_image
image_name = image(j);
temp = strcmpi(image_name, main_name);
if temp == 1;
checker = temp;
end
end
if checker == 0
result(h) = main_name;
h = h+1;
end
end
but it keeps returning the entire string as result, the main string contain roughly 1000 names, the images name contain about 300 names, so it should return about 700 names in result but it keep returning all 1000 names.

I tried your code with small vectors:
main = ['aaa' 'bbb' 'ccc' 'ddd'];
image = ['bbb' 'ddd'];
name_size_main = size(main,2);
name_size_image = size(image,2);
h = 1;
for i = 1:name_size_main
checker = 0;
main_name = main(i);
for j = 1:name_size_image
image_name = image(j);
temp = strcmpi(image_name, main_name);
if temp == 1;
checker = temp;
end
end
if checker == 0
result(h) = main_name;
h = h+1;
end
end
I get result = 'aaaccc', is it not what you want to get?
EDIT:
If you are using cell arrays, you should change the line result(h) = main_name; to result{h} = main_name; like that:
main = {'aaa' 'bbb' 'ccc' 'ddd'};
image = {'bbb' 'ddd'};
name_size_main = size(main,2);
name_size_image = size(image,2);
result = cell(0);
h = 1;
for i = 1:name_size_main
checker = 0;
main_name = main(i);
for j = 1:name_size_image
image_name = image(j);
temp = strcmpi(image_name, main_name);
if temp == 1;
checker = temp;
end
end
if checker == 0
result{h} = main_name;
h = h+1;
end
end

You can use cells of string along with setdiff or setxor.
A = cellstr(('a':'t')') % a cell of string, 'a' to 't'
B = cellstr(('f':'z')') % 'f' to 'z'
C1 = setdiff(A,B,'rows') % gives 'a' to 'e'
C2 = setdiff(B,A,'rows') % gives 'u' to 'z'
C3 = setxor(A,B,'rows') % gives 'a' to 'e' and 'u' to 'z'

Related

Getting all strings in a lua script

I'm trying to encode some strings in my lua script, and since that I have a lua script with over 200k characters, encrypting each string query in the script with a function such as this example below
local string = "stackoverflow"
local string = [[stackoverflow]]
local string = [==[stackoverflow]==]
local string = 'stackoverflow'
to
local string=decode("jkrtbfmviwcfn",519211)
Trying to provide all above results to thread through a gsub and have the gsub encode the string text with a random offset number.
So far, I was only capable of gsubbing full quotation marks through.
function encode(x,offset,a)
for char in string.gmatch(x, "%a") do
local encrypted = string.byte(char) + offset
while encrypted > 122 do
encrypted = encrypted - 26
end
while encrypted < 97 do
encrypted = encrypted + 26
end
a[#a+1] = string.char(encrypted)
end
return table.concat(a)
end
luacode=[==[thatstring.Value="Encryptme!" testvalue.Value=[[string with
a linebreak]] string.Text="STOP!"]==]
luacode=luacode:gsub([=["(.-)"]=],function(s)
print("Caught "..s)
local offset=math.random(1,4)
local encoded=encode(s,offset,{})
return [[decode("]]..encoded..[[",]]..offset..[[)]]
end)
print("\n"..luacode)
With its output being
Caught Encryptme!
Caught STOP!
thatstring.Value=decode("crgvctxqi",4) testvalue.Value=[[string with
a linebreak]] string.Text=decode("opkl",2)
Any better solutions?
local function strings_and_comments(lua_code, callback)
-- lua_code must be valid Lua code (an error may be raised on syntax error)
-- callback will be invoked as callback(object_type, value, start_pos, end_pos)
-- callback("comment", comment_text, start_pos, end_pos) -- for comments
-- callback("string", string_value, start_pos, end_pos) -- for string literals
local objects = {} -- possible comments and string literals in the code
-- search for all start positions of comments (with false positives)
for pos, br1, eq, br2 in lua_code:gmatch"()%-%-(%-*%[?)(=*)(%[?)" do
table.insert(objects, {start_pos = pos,
terminator = br1 == "[" and br2 == "[" and "]"..eq.."]" or "\n"})
end
-- search for all start positions of string literals (with false positives)
for pos, eq in lua_code:gmatch"()%[(=*)%[[%[=]*" do
table.insert(objects, {is_string = true, start_pos = pos,
terminator = "]"..eq.."]"})
end
for pos, quote in lua_code:gmatch"()(['\"])" do
table.insert(objects, {is_string = true, start_pos = pos, quote = quote})
end
table.sort(objects, function(a, b) return a.start_pos < b.start_pos end)
local end_pos = 0
for _, object in ipairs(objects) do
local start_pos, ok, symbol = object.start_pos
if start_pos > end_pos then
if object.terminator == "\n" then
end_pos = lua_code:find("\n", start_pos + 1, true) or #lua_code
-- exclude last spaces and newline
while lua_code:sub(end_pos, end_pos):match"%s" do
end_pos = end_pos - 1
end
elseif object.terminator then
ok, end_pos = lua_code:find(object.terminator, start_pos + 1, true)
assert(ok, "Not a valid Lua code")
else
end_pos = start_pos
repeat
ok, end_pos, symbol = lua_code:find("(\\?.)", end_pos + 1)
assert(ok, "Not a valid Lua code")
until symbol == object.quote
end
local value = lua_code:sub(start_pos, end_pos):gsub("^%-*%s*", "")
if object.terminator ~= "\n" then
value = assert((loadstring or load)("return "..value))()
end
callback(object.is_string and "string" or "comment", value, start_pos, end_pos)
end
end
end
local inv256
local function encode(str)
local seed = math.random(0x7FFFFFFF)
local result = '",'..seed..'))'
if not inv256 then
inv256 = {}
for M = 0, 127 do
local inv = -1
repeat inv = inv + 2
until inv * (2*M + 1) % 256 == 1
inv256[M] = inv
end
end
repeat
seed = seed * 3
until seed > 2^43
local K = 8186484168865098 + seed
result = '(decode("'..str:gsub('.',
function(m)
local L = K % 274877906944 -- 2^38
local H = (K - L) / 274877906944
local M = H % 128
m = m:byte()
local c = (m * inv256[M] - (H - M) / 128) % 256
K = L * 21271 + H + c + m
return ('%02x'):format(c)
end
)..result
return result
end
function hide_strings_in_lua_code(lua_code)
local text = { [[
local function decode(str, seed)
repeat
seed = seed * 3
until seed > 2^43
local K = 8186484168865098 + seed
return (str:gsub('%x%x',
function(c)
local L = K % 274877906944 -- 2^38
local H = (K - L) / 274877906944
local M = H % 128
c = tonumber(c, 16)
local m = (c + (H - M) / 128) * (2*M + 1) % 256
K = L * 21271 + H + c + m
return string.char(m)
end
))
end
]] }
local pos = 1
strings_and_comments(lua_code,
function (object_type, value, start_pos, end_pos)
if object_type == "string" then
table.insert(text, lua_code:sub(pos, start_pos - 1))
table.insert(text, encode(value))
pos = end_pos + 1
end
end)
table.insert(text, lua_code:sub(pos))
return table.concat(text)
end
Usage:
math.randomseed(os.time())
-- This is the program to be converted
local luacode = [===[
print"Hello world!"
print[[string with
a linebreak]]
local str1 = "stackoverflow"
local str2 = [[stackoverflow]]
local str3 = [==[stackoverflow]==]
local str4 = 'stackoverflow'
print(str1)
print(str2)
print(str3)
print(str4)
]===]
-- Conversion
print(hide_strings_in_lua_code(luacode))
Output (converted program)
local function decode(str, seed)
repeat
seed = seed * 3
until seed > 2^43
local K = 8186484168865098 + seed
return (str:gsub('%x%x',
function(c)
local L = K % 274877906944 -- 2^38
local H = (K - L) / 274877906944
local M = H % 128
c = tonumber(c, 16)
local m = (c + (H - M) / 128) * (2*M + 1) % 256
K = L * 21271 + H + c + m
return string.char(m)
end
))
end
print(decode("ef869b23b69b7fbc7f89bbe7",2686976))
print(decode("c2dc20f7061c452db49302f8a1d9317aad1009711e0984",1210253312))
local str1 = (decode("84854df4599affe9c894060431",415105024))
local str2 = (decode("a5d7db792f0b514417827f34e3",1736704000))
local str3 = (decode("6a61bcf9fd6f403ed1b4846e58",1256259584))
local str4 = (decode("cad56d9dea239514aca9c8b8e0",1030488064))
print(str1)
print(str2)
print(str3)
print(str4)
Output of output (output produced by the converted program)
Hello world!
string with
a linebreak
stackoverflow
stackoverflow
stackoverflow
stackoverflow

How do I only loop through certain parts of a cell array?

I am trying to figure out a way to make a for loop in which I can compare two cells that will give me two different means. One for class char and the other for class double.
This is what I have so far.
V = {2; 'tree'; 3; 'hope'};
W = {2; 'tree'; 3; 'hope'};
for i = 1:length(V);
if isequal(class(V{i}), 'double')
num = V{i}
elseif isequal(class(V{i}), 'char')
str = V{i}
end
end
for i = 1:length(W);
if isequal(class(W{i}), 'double')
acc_n(i) = isequal(V{i}, W{i})
elseif isequal(class(W{i}), 'char')
acc_s(i) = strcmp(V{i}, W{i})
end
end
mean_d = mean(acc_n)
mean_s = mean(acc_s)
The output I get is:
acc_n =
1 0 1
acc_s =
0 1 0 1
mean_d =
0.6667
mean_s =
0.5000
The output I want is:
1 1 for string, mean = 1. 1 1 for double, mean = 1
How can I do a loop where it only takes the numbers of the cell and the words of the cell separately?
Is there any possible way to only loop through the words or the numbers?
You can first extract strings and doubles and treat them separately, that will avoid loops.
V = {2; 'tree'; 3; 'hope'};
W = {2; 'tree'; 3; 'hope'};
VChar=V(cellfun(#ischar,V));
WChar=W(cellfun(#ischar,W));
acc_s=VChar==WChar;
VNum=cell2mat(V(cellfun(#isnumeric,V)));
WNum=cell2mat(W(cellfun(#isnumeric,W)));
acc_n=VNum==WNum;
Loop version: I haven't tested this but it should work.
%Assumes V and W have equal number of elements.
acc_n=[];
acc_s=[];
for i=1:numel(V)
if isequal(class(V{i}), 'double') && isequal(V{i},W{i})
acc_n=[acc_n true];
elseif isequal(class(V{i}), 'char') && strcmp(V{i},W{i})
acc_s=[acc_s true];
end
end

adding strings as numbers

I'm trying to add together two large numbers, stored as strings.
Here's what I have so far:
function addBigNums(a,b){
c = ""; // output
o = 0; // carryover
startLen = a.length-1;
for(i = startLen; i >= 0; i--) {
sum = parseInt(a[i], 10) + parseInt(b[i], 10) + o;
c = (sum % 10) + c;
o = sum >= 10;
}
if(o === true) c = "1" + c;
return c;
}
I'm running into two issues:
1 ) my carry is not always functioning properly, primarily when:
2 ) the numbers length differ.
Right now I think I would have to prepend 0's onto the shorter number in order to get this to function as expected.
Any better alternatives to this?
Simple, straightforward integer addition like you would do it manually:
a = "123456"; // input a
b = "123456"; // input b
c = ""; // target-string
o = 0; // overflow-bit
// traverse string from right to left
for(i = a.length - 1; i >= 0; i--) {
// do the calculation (with overflow bit)
sum = parseInt(a[i]) + parseInt(b[i]) + o;
// prepend resulting digit to target
c = (sum % 10) + c;
// set overflow bit for next round
o = sum >= 10;
}
// prepend another "1" if last overflow-bit is true
if(o == true) c = "1" + c;
If strings a and b are not equal length (but you stated that they are), you should prepend the shorter string with zeros before calculation.
Consider both numbers to be an array of digits. Add them up right-to-left handling overflow flag. Demo. Assuming your numbers are of the same length
function getNumber(len) {
return Array.apply(null, new Array(len)).map(function(){
return Math.floor(Math.random()*9);
}).join('');
}
var len = 600,
a = getNumber(len), //use your numbers here
b = getNumber(len),
flag = 0;
var c = [].reduceRight.call(a, function(acc, val, idx) {
val = +val + (+b.charAt(idx)) + flag;
flag = val / 10 | 0;
val %= 10;
return val + acc;
}, '');
c = (flag ? 1: '') + c;
console.log(a, b, c);

How to get SubstringValues from Textbox

len = int.Parse(tE1Clt.Text);
front=int.Prase(tE_Fstng.text);
string result = tE3_Series.Text.Substring(front, len);
tE1_Sub.Text = result.ToString();
I'm getting error
[index and length must refer to a location within the string. Parameter name: `length`]
if (TeInput.Text.Length > 1)
{
string Input = TeInput.Text, Store1 = string.Empty, store2 = string.Empty;
int Start = 0, End = 0;
Start = int.Parse(TeStart.Text);
End = int.Parse(TeEnd.Text);
string Output = TeOutput.Text;
Store1 = Input.Remove(0, Start).Trim();
store2 = Store1.Remove(Store1.Length-End).Trim();
TeOutput.Text = store2;
You can do like this,
var str = "----takemeout----";
var start = str.IndexOf('t'); // start index of first t
var length = 9; // length of takemeout string
var result = str.Substring(start, length);
Value or result will be "takemeout"

Counting substring that begin with character 'A' and ends with character 'X'

PYTHON QN:
Using just one loop, how do I devise an algorithm that counts the number of substrings that begin with character A and ends with character X? For example, given the input string CAXAAYXZA there are four substrings that begin with A and ends with X, namely: AX, AXAAYX, AAYX, and AYX.
For example:
>>>count_substring('CAXAAYXZA')
4
Since you didn't specify a language, im doing c++ish
int count_substring(string s)
{
int inc = 0;
int substring_count = 0;
for(int i = 0;i < s.length();i++)
{
if(s[i] == 'A') inc++;
if(s[i] == 'X') substring_count += inc;
}
return substring_count;
}
and in Python
def count_substring(s):
inc = 0
substring_count = 0
for c in s:
if(c == 'A'): inc = inc + 1
if(c == 'X'): substring_count = substring_count + inc
return substring_count
First count number of "A" in the string
Then count "X" in the string
using
Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
Dim cnt As Integer = 0
For Each c As Char In value
If c = ch Then cnt += 1
Next
Return cnt
End Function
then take each "A" as a start position and "X" as an end position and get the substring. Do this for each "X" and then start with second "A" and run that for "X" count times. Repeat this and you will get all the substrings starting with "A" and ending with "X".
Just another solution In python:
def count_substring(str):
length = len(str) + 1
found = []
for i in xrange(0, length):
for j in xrange(i+1, length):
if str[i] == 'A' and str[j-1] == 'X':
found.append(str[i:j])
return found
string = 'CAXAAYXZA'
print count_substring(string)
Output:
['AX', 'AXAAYX', 'AAYX', 'AYX']

Resources