Arduino unable to match Char data - c++

I have an Arduino web server project going. Right now I'm trying to parse url parameters. For instance, I wish to make a GET request to http://(localip)/info and then have the "info" returned and displayed.
I don't know if I've been staring at the screen too long today, but I can't seem to match a simple char which is a single space... This shouldn't be complex in the slightest! All the advice I've found do not work. Yet, I need to break the loop on a space because that is an indicator where my url parameter ends. I want to be able to use /info as well as /something else.
char *data = (char *) Ethernet::buffer + pos;
String buff;
for (int x = 5; x<15; x++) {
Serial.print(x); Serial.print(" - |"); Serial.print(data[x]); Serial.println("|");
if ((data[x] == " ") || (data[x] == char(" ")) || (strcmp(data[x], " ") == 0)) {
x = 999;
break;
} else {
buff += data[x];
}
delay(5);
}
Serial monitor output. It should break on #9 and buff should equal just "info"
5 - |i|
6 - |n|
7 - |f|
8 - |o|
9 - | |
10 - |H|
11 - |T|
12 - |T|
13 - |P|
14 - |/|
buff -> info HTTP/

You are using double quote marks (") in your char comparisons. In C++, the double quote marks are used to define strings, not characters. Characters are defined using single quotes (')
testing for a space: if (c == ' ').
Unlike strings, you can also use chars in switch statements:
switch (c)
{
case 'a': case 'A':
Serial.println("I've got an A!!");
break;
}

if (data[x] == 0x20 || (isspace(data[x])))
{
//is a white space
}

Related

Don't allow consecutive same character and some different character together in TextFormField

I want to restrict the TextFormField to only accept numbers separated by commas and sometimes with dashes but I don't want them to come consecutive to each other and also don't want the same character consecutive.
Ex:-
1,3-4,9-11 is correct
1,,3--4,9-11 is wrong
1,-3-4,9-11 is wrong
1-,3-4,9-11 is wrong
To restrict things to only numbers, commas and dashes I'm using:-
FilteringTextInputFormatter(
RegExp("[0-9,-]"),
allow: true
)
But it is not restricting the consecutive behavior as shown in the wrong behavior in the examples.
So, how can I restrict my TextFormField to the correct behavior represented in the examples?
Thank you.
Update: I finally followed this approach for this problem.
If you want to validate on submit, you might write the pattern as:
^[0-9]+(?:[,-][0-9]+)*$
Regex demo
If a negative lookahead is supported, you an exclude matching 2 times one of - or , while validating on typing.
Note that this will allow , or - at the end:
^(?!.*[,-][,-])[0-9,-]*
Regex demo
For my problem above I finally combined FilteringTextInputFormatter with a custom TextInputFormatter specific to my case so I'm adding it below so that if anyone wants to do the same they can have a look at this approach:
class RangeTextInputFormatter extends TextInputFormatter {
#override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
TextSelection newSelection = newValue.selection;
String truncated = newValue.text;
int oldValueLength = oldValue.text.length;
int newValueLength = newValue.text.length;
// Blocks comma and dash at start.
if ((oldValue.text.isEmpty || oldValue.text == "") &&
(newValue.text[newValueLength - 1] == "," ||
newValue.text[newValueLength - 1] == "-")) {
truncated = oldValue.text;
newSelection = oldValue.selection;
}
// Allows numbers at start.
else if (oldValue.text.isEmpty || oldValue.text == "") {
truncated = newValue.text;
newSelection = newValue.selection;
} else {
// Blocks comma and dash after comma.
if (oldValue.text[oldValueLength - 1] == "," &&
(newValue.text[newValueLength - 1] == "," ||
newValue.text[newValueLength - 1] == "-")) {
truncated = oldValue.text;
newSelection = oldValue.selection;
}
// Blocks comma and dash after dash.
else if (oldValue.text[oldValueLength - 1] == "-" &&
(newValue.text[newValueLength - 1] == "," ||
newValue.text[newValueLength - 1] == "-")) {
truncated = oldValue.text;
newSelection = oldValue.selection;
}
// Blocks dash after number dash number. Ex: 48-58- <- this last dash is blocked
else if (oldValue.text.lastIndexOf('-') != -1) {
if (!(oldValue.text
.substring(oldValue.text.lastIndexOf('-'))
.contains(",")) &&
newValue.text[newValueLength - 1] == "-") {
truncated = oldValue.text;
newSelection = oldValue.selection;
}
}
}
return TextEditingValue(
text: truncated,
selection: newSelection,
composing: TextRange.empty,
);
}
}
Now use it just like FilteringTextInputFormatter:
inputFormatters: [
FilteringTextInputFormatter(RegExp("[0-9,-]"), allow: true),
RangeTextInputFormatter(),
]

Backspace String Compare Leetcode Question

I have a question about the following problem on Leetcode:
Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
Example 1:
Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac".
Example 2:
Input: S = "ab##", T = "c#d#"
Output: true
Explanation: Both S and T become "".
Example 3:
Input: S = "a##c", T = "#a#c"
Output: true
Explanation: Both S and T become "c".
Example 4:
Input: S = "a#c", T = "b"
Output: false
Explanation: S becomes "c" while T becomes "b".
Note:
1 <= S.length <= 200
1 <= T.length <= 200
S and T only contain lowercase letters and '#' characters.
Follow up:
Can you solve it in O(N) time and O(1) space?
My answer:
def backspace_compare(s, t)
if (s.match?(/[^#[a-z]]/) || t.match?(/[^#[a-z]]/)) || (s.length > 200 || t.length > 200)
return "fail"
else
rubular = /^[\#]+|([^\#](\g<1>)*[\#]+)/
if s.match?(/#/) && t.match?(/#/)
s.gsub(rubular, '') == t.gsub(rubular, '')
else
new_s = s.match?(/#/) ? s.gsub(rubular, '') : s
new_t = t.match?(/#/) ? t.gsub(rubular, '') : t
new_s == new_t
end
end
end
It works in the terminal and passes the given examples, but when I submit it on leetcode it tells me Time Limit Exceeded. I tried shortening it to:
rubular = /^[\#]+|([^\#](\g<1>)*[\#]+)/
new_s = s.match?(/#/) ? s.gsub(rubular, '') : s
new_t = t.match?(/#/) ? t.gsub(rubular, '') : t
new_s == new_t
But also the same error.
So far, I believe my code fulfills the O(n) time, because there are only two ternary operators, which overall is O(n). I'm making 3 assignments and one comparison, so I believe that fulfills the O(1) space complexity.
I have no clue how to proceed beyond this, been working on it for a good 2 hours..
Please point out if there are any mistakes in my code, and how I am able to fix it.
Thank you! :)
Keep in mind that with N <= 200, your problem is more likely to be linear coefficient, not algorithm complexity. O(N) space is immaterial for this; with only 400 chars total, space is not an issue. You have six regex matches, two of which are redundant. More important, regex is slow processing for such a specific application.
For speed, drop the regex stuff and do this one of the straightforward, brute-force ways: run through each string in order, applying the backspaces as appropriate. For instance, change both the backspace and the preceding letter to spaces. At the end of your checking, remove all the spaces in making a new string. Do this with both S and T; compare those for equality.
It may be easiest to start at the end of the string and work towards the beginning:
def process(str)
n = 0
str.reverse.each_char.with_object('') do |c,s|
if c == '#'
n += 1
else
n.zero? ? (s << c) : n -= 1
end
end.reverse
end
%w|ab#c ad#c ab## c#d# a##c #a#c a#c b|.each_slice(2) do |s1, s2|
puts "\"%s\" -> \"%s\", \"%s\" -> \"%s\" %s" %
[s1, process(s1), s2, process(s2), (process(s1) == process(s2)).to_s]
end
"ab#c" -> "ac", "ad#c" -> "ac" true
"ab##" -> "", "c#d#" -> "" true
"a##c" -> "c", "#a#c" -> "c" true
"a#c" -> "c", "b" -> "b" false
Let's look at a longer string.
require 'time'
alpha = ('a'..'z').to_a
#=> ["a", "b", "c",..., "z"]
s = (10**6).times.with_object('') { |_,s|
s << (rand < 0.4 ? '#' : alpha.sample) }
#=> "h####fn#fjn#hw###axm...#zv#f#bhqsgoem#glljo"
s.size
#=> 1000000
s.count('#')
#=> 398351
and see how long it takes to process.
require 'time'
start_time = Time.now
(u = process(s)).size
#=> 203301
puts (Time.now - start_time).round(2)
#=> 0.28 (seconds)
u #=> "ffewuawhfa...qsgoeglljo"
As u will be missing the 398351 pound signs in s, plus an almost equal number of other characters removed by the pound signs, we would expect u.size to be about:
10**6 - 2 * s.count('#')
#=> 203298
In fact, u.size #=> 203301, meaning that, at the end, 203301 - 203298 #=> 3 pound signs were unable to remove a character from s.
In fact, process can be simplified. I leave that as an exercise for the reader.
class Solution {
public boolean backspaceCompare(String s, String t) {
try {
Stack<Character> st1 = new Stack<>();
Stack<Character> st2 = new Stack<>();
st1 = convertToStack(s);
st2 = convertToStack(t);
if (st1.size() != st2.size()) {
return false;
} else {
int length = st1.size();
for (int i = 0; i < length; i++) {
if (st1.peek() != st2.peek())
return false;
else {
st1.pop();
st2.pop();
}
if (st1.isEmpty() && st2.isEmpty())
return true;
}
}
} catch (Exception e) {
System.out.print(e);
}
return true;
}
public Stack<Character> convertToStack(String s){
Stack<Character> st1 = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != '#') {
st1.push(s.charAt(i));
} else if (st1.empty()) {
continue;
} else {
st1.pop();
}
}
return st1;
}
}

regex matching dp

I was trying to understand one of the famous regex matching DP algorithm.
Just in case, people don't know this here is description and algorithm.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
static boolean isMatch(String s, String p) {
boolean[][] dp = new boolean[s.length() + 1][p.length() + 1];
dp[0][0] = true;
for (int i = 1; i < dp[0].length; i++) {
if (p.charAt(i - 1) == '*') {
dp[0][i] = dp[0][i - 2];
}
}
for (int i = 1; i < dp.length; i++) {
for (int j = 1; j < dp[0].length; j++) {
char schar = s.charAt(i - 1);
char pchar = p.charAt(j - 1);
if (schar == pchar || pchar == '.') {
dp[i][j] = dp[i - 1][j - 1];
} else if (pchar == '*') {
if (schar != p.charAt(j - 2) && p.charAt(j - 2) != '.') {
// - a b *
// - t f f f
// a f t f t // b != a and b != '.' thus treat b* as 0 match
dp[i][j] = dp[i][j - 2];
} else {
// - a b *
// - t f f f
// a f t f t
// b f f t t // dp[i][j - 2] 0 match or dp[i][j - 1] 1 math or dp[i - 1][j] 2+ match (not sure why)
dp[i][j] = dp[i][j - 2] || dp[i][j - 1] || dp[i - 1][j];
}
}
}
}
return dp[s.length()][p.length()];
}
I understand the most of part but this part I don't get it
dp[i][j] = dp[i][j - 2] || dp[i][j - 1] || dp[i - 1][j];
dp[i - 1][j] people said this will cover 2+ matches but don't understand this part. Can someone please explain why I need to check dp[i - 1][j]?
I'll use a bit more informal notation so bear with me.
Capitals will denote strings (in the pattern those could include the special characters) and lowercase letters, '.' and '*' will stand for themselves.
Let's say we're matching Ax to Bx, that is some string starting with A (which is itself a string, like xyzz) ending in 'x', with a pattern starting with B (which is itself a pattern, for example, x.*) ending in 'x'. The result is the same as that of matching A to B (as we have no other choice but to match x to x).
We could write that as follows:
isMatch(Ax, Bx) = isMatch(A, B)
Similarly, matching Ax to By is impossible.
isMatch(Ax, Bx) = false
Easy enough. So that would correspond to the first if statement in the two nested loops.
Now let's take the case of an asterisk.
Matching Ax to By* can only be done by ignoring the y* (taking zero y's), that is by matching Ax to B.
isMatch(Ax, By*) = isMatch(Ax, B)
If however the y is replaced by a dot or by x, there are choices.
We'll take the case of Ax and Bx*. The two options are matching Ax to B (means taking zero x's) or matching A to Bx* (means taking an x, but we can still take more so the pattern doesn't change):
isMatch(Ax, Bx*) = isMatch(Ax, B) || isMatch(A, Bx*)
The last one would, in your code, translate to:
dp[i][j] = dp[i][j - 2] || dp[i - 1][j]
So now I'm wondering if your question was really about dp[i][j - 1], as that's what would confuse me.
I might be wrong but that one seems unnecessary.
The meaning of it is to drop the asterisk, that is, changing "zero or more"
to "exactly one", which is already covered by the other two cases, taking the second followed by the first.
Assumption here that the string will not contain special characters ' . ' and ' * ' because otherwise the code presented won't work !!
What does dp[i][j] represents?
It represents that if only first i characters of string and j characters of pattern are considered, do they match ?
State transition in case we encounter '*' in pattern:
Case 1: Take only 0 number of character preceding ' * ' in pattern.
The ' * ' alone doesn't mean anything. It is dependent on its preceding character.
dp[i][j-2] will completely ignore the preceding character in pattern as it considers only first j-2 characters, so preceding character along with ' * ' (jth character) in pattern are ignored.
Now if it is a case that the ith character in string and character preceding ' * ' happen to be same or character preceding ' * ' in pattern is ' . ' then 1 more case add up.
Observation here: .* can match any string
If above condition is satisfied, then consider below case.
Case 2: Continuation of usage of character preceding ' * ' for one or more times.
dp[i-1][j] represents this. Remember jth character in pattern is ' * ' .
So if first i-1 characters of string match with first j characters in pattern where jth character is a ' * ' (which suggests that we have used character preceding ' * ' at least once), then we can say that first i characters in string match with first j characters of pattern as we have already ensured that ith character matches the preceding character to ' * ' in pattern.
The case dp[i][j-1] is redundant and covered in case 2.
Note: Explanation for redundancy of dp[i][j-1]
dp[i][j-1] matches only once for character preceding ' * '. It is already covered in dp[i-1][j].
Reason:
We know ith character is matching j-1th character (Remember, we checked before considering this case).
So dp[i][j-1] = dp[i-1][j-2] which is already considered in calculation of dp[i-1][j].
dp[i-1][j] is more powerful because dp[i-1][j] = dp[i-1][j-2] || dp[i-2][j] as jth character is ' * '. So this is what gives memory property which allows us to use a character more than once.

Regex: Any letters, digit, and 0 up to 3 special chars

It seems I'm stuck with a simple regex for a password check.
What I'd like:
8 up to 30 symbols (Total)
With any of these: [A-Za-z\d]
And 0 up to 3 of these: [ -/:-#[-`{-~À-ÿ] (Special list)
I took a look here and then I wrote something like:
(?=.{8,15}$)(?=.*[A-Za-z\d])(?!([ -\/:-#[-`{-~À-ÿ])\1{4}).*
But it doesn't work, one can put more than 3 of the special chars list.
Any tips?
After shuffling your regex around a bit, it works for the examples you provided (I think you made a mistake with the example "A#~` C:", it should not match as it has 6 special chars):
(?!.*(?:[ -\/:-#[-`{-~À-ÿ].*){4})^[A-Za-z\d -\/:-#[-`{-~À-ÿ]{8,30}$
It only needs one lookahead instead of two, because the length and character set check can be done without lookahead: ^[A-Za-z\d -/:-#[-`{-~À-ÿ]{8,30}$
I changed the negative lookahead a bit to be correct. Your mistake was to only check for consecutive special chars, and you inserted the wildcards .* in a way that made the lookahead never hit (because the wildcard allowed everything).
Will this work?
string characters = " -/:-#[-`{-~À-ÿ";
string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
string[] inputs = {
"AABBCCDD",
"aaaaaaaa",
"11111111",
"a1a1a1a1",
"AA####AA",
"A1C EKFE",
"AADE F"
};
foreach (string input in inputs)
{
var counts = input.Cast<char>().Select(x => new { ch = characters.Contains(x.ToString()) ? 1 : 0, letter = letters.Contains(x.ToString()) ? 1 : 0, notmatch = (characters + letters).Contains(x) ? 0 : 1}).ToArray();
Boolean isMatch = (input.Length >= 8) && (input.Length <= 30) && (counts.Sum(x => x.notmatch) == 0) && (counts.Sum(x => x.ch) <= 3);
Console.WriteLine("Input : '{0}', Matches : '{1}'", input, isMatch ? "Match" : "No Match");
}
Console.ReadLine();
I would use: (if you want to stick to Regex)
var specialChars = #" -\/:-#[-`{-~À-ÿ";
var regularChars = #"A-Za-z\d";
if (Regex.Match(password,$"^(.[{regularChars}{specialChars}]{7,29})$").Success && Regex.Matches(password, $"[{specialChars}]").Count<=3))
{
//Password OK
}
If consists of:
Check Length and if password contains illegal characters
Check if ony contains 3 times special char
A litle faster:
var specialChars = #" -\/:-#[-`{-~À-ÿ";
var regularChars = #"A-Za-z\d";
var minChars = 8;
var maxChars = 30;
if (password.Length >= minChars && password.Length <= maxChars && Regex.Match(password,$"^[{regularChars}{specialChars}]+$").Success && Regex.Matches(password, $"[{specialChars}]").Count<=3))
{
//Password OK
}
Newbie here..I think I've managed to get what you need but one of the test cases you shared was kinda weird..
A#~` C:
OK -- Match (3 specials, it's okay)
Shouldn't this be failed because it has more than 3 specials?
Could you perhaps try this? If it works I'll type out the explanations for the regex.
https://regex101.com/r/KCL6R1/2
(?=^[A-Za-z\d -\/:-#[-`{-~À-ÿ]{8,30}$)^(?:[A-Za-z\d]*[ -\/:-#[-`{-~À-ÿ]){0,3}[A-Za-z\d]*$

Looking for a regex for a password with at least one lowercase letter, at least one upper case letter, at least one digit & length between 6 and 14

I am looking for a regular expression for a validating a password. The password rules are:
at least one lowercase letter
at least one upper case letter
at least one digit
length between 6 and 14
I created following regular expression but it's not working
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,14}$
It's accepting
qwerty1
QWERTY1
but not qwERTy
i.e. it's fulfilling only 2 conditions
at least one digit
length between 6 and 14
I'm not sure that's possible, but I'm sure that if it is, and it turns out a long complicated regex string, it's a wrong design decision. It will be unmaintainable, unclear and very error prone.
At the same time, this is easy to do, understand and maintain:
function isValid(password)
{
if(password.length < 6 || password.length > 14)
return false;
var valid = { hasLower: false, hasUpper: false, hasDigit: false };
for(var i = 0; i < password.length; i++) {
var c = password[i];
var upperC = c.toUpperCase();
valid.hasLower |= c != upperC;
valid.hasUpper |= c == upperC;
valid.hasDigit |= c >= '0' && c <= '9';
}
return valid.hasLower && valid.hasUpper && valid.hasDigit;
}
alert('"123abcDEF" valid = ' + isValid('123abcDEF'));
alert('"123 DEF" valid = ' + isValid('123 DEF'));
You can use \S instead of . for restricting spaces:
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\S{6,14}$
^
See DEMO