Error when copying a word to array character by character - arrays

I'm trying to copy an unknown length of characters into an array, but I keep getting an error. I'm getting this from a website converted to text. Site is the position of the first character of the word (I want to copy 4 words), and result is the whole text file.
I keep getting this error:
Subscript indices must either be real positive integers or logicals.
for this line: webget = result(sites(i)+n);
for i = 0:3; %for finding first 4
webget = 'p'; %placeholder
website = []; %blank
while strcmp(webget,' ') == 0;
for n = 0:150; %letter by letter, arbitrary search length
webget = result(sites(i)+n);
website = strcat(website,webget);
end
end
website(i) = website;
end
Could anyone help?

Matlab arrays index starting from 1, not 0. On your first loop iteration, i=0, so your request for the 0th entry in the sites array is not valid.
Consider using i = 1:4.

Related

storing the longest string after strsplit

I am trying to store the longest resultant string after using the function strsplit unable to do so
eg: I have input strings such as
'R.DQDEGNFRRFPTNAVSMSADENSPFDLSNEDGAVYQRD.L'or
'L.TSNKDEEQRELLKAISNLLD'
I need store the string only between the dots (.)
If there is no dot then I want the entire string.
Each string may have zero, one or two dots.
part of the code which I am using:
for i=1:700
x=regexprep(txt(i,1), '\([^\(\)]*\)','');
y=(strsplit(char(x),'.'));
for j=1:3
yValues(1,j)=y{1,j};
end
end
But the string yValues is not storing the value of y, instead showing the following error:
Assignment has more non-singleton rhs dimensions than non-singleton subscripts
What am I doing wrong and are there any suggestions on how to fix it?
The issue is that y is a cell array and each element contains an entire string and it therefore can't be assigned to a single element in a normal array yvalues(1,j).
You need yvalues to be a cell array and then you can assign into it just fine.
yValues{j} = y{j};
Or more simply
% Outside of your loop
yValues = cell(1,3);
% Then inside of your loop
yValues(j) = y(j);
Alternately, if you just want the longest output of strsplit, you can just do something like this.
% Split the string
parts = strsplit(mystring, '.');
% Find the length of each piece and figure out which piece was the longest
[~, ind] = max(cellfun(#numel, parts));
% Grab just the longest part
longest = parts{ind};

Appending string much faster than appending character

I was doing https://www.hackerrank.com/challenges/30-review-loop problem on hacker rank and I was running into a time out issue that was resolved in round about way. I was hoping someone on here can explain to me why one is faster than the other. Or point me to documentation that explains this phenomenon
If you don't have an account here's a description of the issue you feed in the number of test cases and then a string which your code is to create a string with all the characters in the odd indices and a string with all the characters in the even indices. Example input
2
Hacker
Rank
returns
Hce akr
Rn ak
Simple right? Here's the code I made.
if let line = readLine(), numOftests = Int(line) {
for iter in 0..<numOftests {
var evenString = ""
var oddString = ""
var string = readLine()!
var arrChars = [Character](string.characters) //1
for idx in 0..<string.characters.count {
if idx % 2 == 0 {
oddString.append(arrChars[idx]) //1
//oddString.append(string[string.startIndex.advancedBy(idx)]) //2 <= Times out
}
else {
evenString.append(arrChars[idx]) //1
//evenString.append(string[string.startIndex.advancedBy(idx)]) //2 <= Times out
}
}
print("\(oddString) \(evenString)")
}
}
Originally I used the commented out code. This lead to a time out. To sum my problem is that using the subscripting system for a string, causes it to be a lot slower than indexing an array of characters. It caught me by surprise and if it wasn't for the discussion group in hacker rank I wouldn't have found a solution. Now it goads me because I don't know why this would make a difference.
The issue isn't the speed of appending a string vs. appending a character. The issue is how long it takes to locate the value you are appending.
Indexing an array is O(1) which means it happens in the same time whether you are accessing the first character or the 97th. It is efficient because Swift knows the size of the array elements, so it can just multiply the index by the size of the element to find the nth element.
string.startIndex.advancedBy(idx) is O(idx). It will take longer depending on how far you go into the string. Accessing the 97th character will take about 97 times as long as accessing the first character. Why? Because characters in Swift are not uniform in size. Swift strings are fully unicode compatible and a "😀" takes more bytes to represent than "A". So, it is necessary to look at every character from the startIndex to the one you are accessing.
That said, there is no reason for you to start at startIndex each time. If you kept the current index in a variable, you could advance it by 1 each time which would make the string indexing version about the same speed as the character array indexing version.
var currentIndex = string.startIndex
for idx in 0..<string.characters.count {
if idx % 2 == 0 {
oddString.append(string[currentIndex])
}
else {
evenString.append(string[currentIndex])
}
currentIndex = currentIndex.successor()
}
That said, I would probably write it like this:
for (idx, char) in string.characters.enumerate() {
if idx % 2 == 0 {
oddString.append(char)
}
else {
evenString.append(char)
}
}

Character x,y in password - LoadRunner

I'm doing a load test for a sign in page where the user needs to input 2 characters of their password.
I've created an array of characters to say 'password1'.
Using correlation parameters I'm able to get the character number required. What I'm now trying to do is get the character number and match the array i.e. -
Character 1 is required, it will scan the array and bring back char[0].
Character 2 is required, it will scan the array and bring back char[1] etc.
I was thinking of doing a for loop to go through the array and determine where in the array a character is stored. I can't think how to initiate this for loop:
char1 = (char1-1);
char2 = (char2-1);
for(i=0;i<10;i++){
lr_output_message("%s",p[i]);
if (p[i] == p[char1]){
char1 = p[i];
}
}
The for loop works but it equals 115 (s in ASCII), I need a way of converting the value to a character, but I keep getting memory violations.
Sorry if I've over-complicated this issue, but my head has been lost trying to think about how to solve a seemingly easy problem. No doubt some of you will look at it a different way and tell me I've over-complicated it a significant amount!
Closed - worked it out.
Using these buffers instead of for loop.
buf[0] = char1a;
buf[1] = ‘\0’;
buf2[0] = char2a;
buf2[1] = ‘\0’;

How to split sentences in an array

I have a string s which stores a very long sentence and I want to copy the content of s to an array C with each cell storing a sentence each. The following is my code which is not giving me any output, but the dimension of the cell:
while(i<6)
C(i)=s;
end
This is how I get as output when I print C:
C=
[1x76 char]
Can somebody please help me.
Another job for strsplit:
>> sentences = 'This is the first one. Then here is a second. Yet another here.';
>> C = strsplit(sentences,'. ')
C =
'This is the first one' 'Then here is a second' 'Yet another here.'
We are specifying a period followed by a space as the delimiter. Change this as needed.
Suppose Long string is:
longString = "This is first cell. This is second cell. this is third cell".
Now since . is delimiter here means it is acting as separator for sentences. so you can loop through longString character wise and whenever you encounter a . you just increase Array index count and keep storing in this Array index until you find another .
here is sudo code:
array[];
index = 0;
loop through(longString) character wise
{
if(currentChar equals to '.')
{
index++;
}
else
{
array[index] = currentChanracter;
}
}

Comparison of two array elements and calculation

I have an issue with a section of code I wish to write. My problem is based around two arrays and the elements they encompass.
I have two arrays filled with numbers (relating to positions in a string). I wish to select the substrings between the positions. The elements in the first array are the start of the substrings and the elements in the second array are the ends of the substrings.
The code I have supplied reads in the file and makes it a string:
>demo_data
theoemijono
milotedjonoted
dademimamted
String:
theoemijonomilotedjonoteddademimamted
so what I want to happen is to extract the substring
emijonomiloted
emimamted
The code I have written takes the the first element array and compares it with the second array corresponding element and then to ensure that there is no cross over and hence hold the substring to start with emi and end with tedas seen in the provided sequences
for($i=0; $i<=10; $i++)
{
if ($rs1_array[$i] < $rs2_array[$i] && $rs1_array[$i+1] > $rs2_array[$i])
{
my$size= $rs2_array[$i]-$rs1_array[$i]+ 3);
my$substr= substr($seq, $rs1_array[$i],$size);
print $substr."\n";
}
}
Using this code works for the first substring, but the second substring is ignored as the first array has fewer elements and hence the comparison cannot be completed.
UPDATE
Array structures:
#rs1_array = (4, 28);
#rs2_array = (15, 22, 34);
Hi borodin, You were absolutely correct.. I have edited the code now! Thank you for seeing that in relation to the length issue. The reason for the strange offset is that the value in #rs2_array is the start position and it does not take into consideration the remainder of the word "ted" in this case and I require this to complete the string.The Array is built correctly as for the elements in #rs1_array they represent the start position "emi" the #rs2_array elements also hold the start position for each "ted" so as there are 2 emi's and 3 ted's in the string this causes the unbalance.
my #starts = ( 4, 28 );
my #ends = map $_+3, ( 15, 22, 34 );
my $starts_idx = my $ends_idx = 0;
while ($starts_idx < #starts && $ends_idx < #ends) {
if ($starts[$start_idx] > $ends[$ends_idx]) {
++$start_idx;
next;
}
my $length = $ends[$ends_idx] - $starts[$start_idx];
say substr($seq, $starts[$start_idx], $length);
++$ends_idx;
++$start_idx;
}
Which, of course, gives the same output as:
say for $seq =~ /(emi(?:(?!emi|ted).)*ted)/sxg;

Resources