Distance edit array output - processing

I am doing an edit distance with the user input. I am storing my values in array. then the edit distance will compare the user input with my array of strings. I am doing a loop that if the edit distance is more than 2 it will display invalid else valid.
The only problem I've got is that although the program is working out fine, the output is the result of all the '28' strings that I have in my array. I would like to display only invalid or valid once.
Test is my array of strings and user is - String user - the user input.
void testingLD()
{
for (int i=0; i<test.length; i++)
{
if(getLevenshteinDistance(test[i],user) > 2)
{
println ("Invalid re-input");
}
else
{
println ("Valid");
}
}
}

You have your print line functions inside your loop so they get printed once per iteration.
Try this.
void testingLD()
{
boolean isValid = true; // assume true, check each and update
// begin loop
for (int i=0; i<test.length; i++)
{
if(getLevenshteinDistance(test[i],user) > 2)
{
isValid = false;
break; // don't need to test the rest of the loop if we already found a false
}
}
// end loop
if(isValid){
println("Valid");
}else{
println("Invalid re-input");
}
}
Similarly you could count the number of valid int validCount = 0; validCount++ and then display stats about how many were valid, the percentage etc. Or keep an array of the invalid strings and display those as the ones that fail etc!
Wrap up:
When you want to check an entire collection or array for some condition and output one answer make sure to have your output outside of the loop!

Related

Filtering return on serial port

I have a CO2 sensor on my Arduino Mega and sometimes randomly when I'm reading the CO2 measurement, the sensor will return a "?". The question mark causes my program to crash and return "input string was not in a correct format".
I haven't tried anything because I don't know what approach would be the best for this. The CO2 sensor returns the measurement in the form of "Z 00000" but when this question mark appears it shows that all that returned was a "\n". Currently, I have the program just reading the 5 digits after the Z.
if (returnString != "")
{
val = Convert.ToDouble(returnString.Substring(returnString.LastIndexOf('Z')+ 1));
}
What I expect to return is the digits after Z which works but every so often I will get a random line return which crashes everything.
According to the C# documentation the ToDouble method throws FormatException whenever the input string is invalid. You should catch the exception to avoid further issues.
try {
val = Convert.ToDouble(returnString.Substring(returnString.LastIndexOf('Z')+ 1));
}
catch(FormatException e) {
//If you want to do anything in case of an error
//Otherwise you can leave it blank
}
Also I'd recommend using some sort of statemachine for parsing the data in your case, that could discard all invalid characters. Something like this:
bool z_received = false;
int digits = 0;
int value = 0;
//Called whenever you receive a byte from the serial port
void onCharacter(char input) {
if(input == 'Z') {
z_received = true;
}
else if(z_received && input <= '9' && input >= '0') {
value *= 10;
value += (input - '0');
digits++;
if(digits == 5) {
onData(value);
value = 0;
z_received = false;
digits = 0;
}
}
else {
value = 0;
z_received = false;
digits = 0;
}
}
void onData(int data) {
//do something with the data
}
This is just a mock-up, should work in your case if you can direct the COM port's byte stream into the onCharacter function.

kotlin, how dynamically change the for loop pace

sometime based on some condition it may want to jump (or move forward) a few steps inside the for loop,
how to do it is kolin?
a simplified use case:
val datArray = arrayOf(1, 2, 3......)
/**
* start from the index to process some data, return how many data has been
consumed
*/
fun processData_1(startIndex: Int) : Int {
// process dataArray starting from the index of startIndex
// return the data it has processed
}
fun processData_2(startIndex: Int) : Int {
// process dataArray starting from the index of startIndex
// return the data it has processed
}
in Java it could be:
for (int i=0; i<datArray.lenght-1; i++) {
int processed = processData_1(i);
i += processed; // jump a few steps for those have been processed, then start 2nd process
if (i<datArray.lenght-1) {
processed = processData_2(i);
i += processed;
}
}
How to do it in kotlin?
for(i in array.indices){
val processed = processData(i);
// todo
}
With while:
var i = 0
while (i < datArray.length - 1) {
var processed = processData_1(i)
i += processed // jump a few steps for those have been processed, then start 2nd process
if (i < datArray.length - 1) {
processed = processData_2(i)
i += processed
}
i++
}
You can do that with continue as stated in the Kotlin docs here: https://kotlinlang.org/docs/reference/returns.html
Example:
val names = arrayOf("james", "john", "jim", "jacob", "johan")
for (name in names) {
if(name.length <= 4) continue
println(name)
}
This would only print names longer than 4 characters (as it skips names with a length of 4 and below)
Edit: this only skips one iteration at a time. So if you want to skip multiple, you could store the process state somewhere else and check the status for each iteration.

C++ Ensuring that user input value is int only [duplicate]

This question already has answers here:
How to test whether stringstream operator>> has parsed a bad type and skip it
(5 answers)
Closed 8 years ago.
I am a little new to C++ and would really appreciate any input or suggestions! So with our intro course projects I have been looking for a way to ensure that when the prog. is asking for int values it correctly responds! That is it states its invalid in cases of both a double as well as string being entered! So if cin >> intVariable ... intVariable will not accept cin entry of "abdf" or 20.01.
So to achieve this I wrote the following function...It works but I am looking for your thoughts on how this process can be further improved!
void getIntegerOnly(int& intVariable, string coutStatement)
{
bool isInteger; // Check if value entered by user is int form or not
string tmpValue; // Variable to store temp value enetered by user
cout << coutStatement; // Output the msg for the cin statement
do
{
cin >> tmpValue; // Ask user to input their value
try // Use try to catch any exception caused by what user enetered
{
/* Ex. if user enters 20.01 then the if statement converts the
string to a form of int anf float to compare. that is int value
will be 20 and float will be 20.01. And if values do not match
then user input is not integer else it is. Keep looping untill
user enters a proper int value. Exception is 20 = 20.00 */
if (stoi(tmpValue) != stof(tmpValue))
{
isInteger = false; // Set to false!
clear_response(); // Clear response to state invalid
}
else
{
isInteger = true; //Set to true!
clear_cin(); // Clear cin to ignore all text and space in cin!
}
}
catch (...) // If the exception is trigured!
{
isInteger = false; // Set to false!
clear_response(); // Clear response to state invalid
}
} while (!isInteger); //Request user to input untill int clause met
//Store the int value to the variable passed by reference
intVariable = stoi(tmpValue);
}
This is simply an example of getting users age and age is greater than zero when running a Win32 console based application! Thank you for the feedback :)
One way would be something like the following:
std::string str;
std::cin >> str;
bool are_digits = std::all_of(
str.begin(), str.end(),
[](char c) { return isdigit(static_cast<unsigned char>(c)); }
);
return are_digits ? std::stoi(str) : throw std::invalid_argument{"Invalid input"};
and catch the exceptions on the calling side (stoi can also throw std::out_of_range).
You can leverage the second parameter of stoi().
string tmpValue;
size_t readChars;
stoi(tmpValue, &readChars);
if(readChars == tmpValue.length())
{
// input was integer
}
EDIT: this will not work for strings containing "." (for example integers passed in scientific notation).
This is not my work, but the answer to this question is what you want. Pass the string to it as a reference. It will return true is your string is an integer.
How do I check if a C++ string is an int?

RNG giving same number after second interation in loop

So, I'm trying to make a game that requires randomly colored pictureboxes. I've been trying to make the random color generator, but I'm running into an issue that I can't explain.
When this code runs (inside of Form1_Load event):
for(int i=0; i<6, i++)
{
DateTime moment = DateTime::Now;
Random^RNG=gcnew Random(moment.Millisecond);
color[i]=RNG->Next(16);
if(color[i]<=9)
{
colorStr[i]=color[i].ToString();
}
else if(color[i]==10)
{
colorStr[i]="A";
}
else if(color[i]==11)
{
colorStr[i]="B";
}
else if(color[i]==12)
{
colorStr[i]="C";
}
else if(color[i]==13)
{
colorStr[i]="D";
}
else if(color[i]==14)
{
colorStr[i]="E";
}
else if(color[i]==15)
{
colorStr[i]="F";
}
FullColor+=colorStr[i]; //FullColor was initialized with a value of "#";
}
this->textBox1->Text=FullColor;
this->Player->BackColor = System::Drawing::ColorTranslator::FromHTML(FullColor);
The textbox displays either all the same number (i.e. #000000), or the first number will be unique, but the other five will be equal to each other (i.e. #A22222).
Random generator should not be re-created every time. Try to do it once, before the loop:
Random^RNG=gcnew Random(moment.Millisecond);
for(int i=0; i<6, i++)
{
....
(In your case, it seems that the moment.Millisecond is the same for sequential calls. But even if it would be different, the generator is not supposed to be re-created.)
Instead of the loop, you may consider the following code:
Random^ RNG = gcnew Random(); // somewhere at the beginning
....
int color = RNG->Next(0x1000000);
String^ colorStr = color.ToString("X6");

Deleting Particular repeated field data from Google protocol buffer

.proto file structure
message repetedMSG
{
required string data = 1;
}
message mainMSG
{
required repetedMSG_id = 1;
repeated repetedMSG rptMSG = 2;
}
I have one mainMSG and in it too many (suppose 10) repetedMSG are present.
Now i want to delete any particular repetedMSG (suppose 5th repetedMSG )from mainMSG. For this i tried 3 ways but none of them worked.
for (int j = 0; j<mainMSG->repetedMSG_size(); j++){
repetedMSG reptMsg = mainMsg->mutable_repetedMSG(j);
if (QString::fromStdString(reptMsg->data).compare("deleteMe") == 0){
*First tried way:-* reptMsg->Clear();
*Second tried Way:-* delete reptMsg;
*Third tried way:-* reptMsg->clear_formula_name();
break;
}
}
I get run-time error when i serialize the mainMSG for writing to a file i.e. when execute this line
mainMSG.SerializeToOstream (std::fstream output("C:/A/test1", std::ios::out | std::ios::trunc | std::ios::binary)) here i get run-time error
You can use RepeatedPtrField::DeleteSubrange() for this. However, be careful about using this in a loop -- people commonly write code like this which is O(n^2):
// BAD CODE! O(n^2)!
for (int i = 0; i < message.foo_size(); i++) {
if (should_filter(message.foo(i))) {
message.mutable_foo()->DeleteSubrange(i, 1);
--i;
}
}
Instead, if you plan to remove multiple elements, do something like this:
// Move all filtered elements to the end of the list.
int keep = 0; // number to keep
for (int i = 0; i < message.foo_size(); i++) {
if (should_filter(message.foo(i))) {
// Skip.
} else {
if (keep < i) {
message.mutable_foo()->SwapElements(i, keep)
}
++keep;
}
}
// Remove the filtered elements.
message.mutable_foo()->DeleteSubrange(keep, message.foo_size() - keep);

Resources