How to restart a for loop in kotlin - for-loop

I have this nested loop situation in Kotlin, imagine there are two strings "abcdef" and "bfihja". I'm comparing these two character by character using for loop. If there's a match, that character is to be removed from each string and the iteration for "S2" should start from beginning.
var S1 = "abcdef"
var S2 = "bfihja"
for(i in S1.indices) {
for(j in S2.indices){
if(S1[i]==S2[j]) {
"character removed from each"
}
What I'm having issues in is, when the character matches, the comparison for "S2" string should start from the beginning again. I can't find way restart it.

You can use a labeled outer while loop. By using continue on the outer loop, you restart your iteration. You can put break after the outer iteration so we can exit the while loop when complete.
outer#while (true) {
for (i in S1.indices) {
for (j in S2.indices) {
if (S1[i] == S2[j]) {
S1 = StringBuilder(S1).deleteCharAt(i).toString()
S2 = StringBuilder(S2).deleteCharAt(j).toString()
continue#outer
}
}
}
break
}

You should use a regular for-loop that ranges from 0 to length-of-S2 in the inner for-loop, and just reset the iterator variable to 0 when you want to "reset" the for-loop.

Related

How to check if there is a space in an input line in C++

I am trying to check if there is a space in an input line.
I have indexed the input but I got an error: "Expected ';' expected ')' "
string mike20;
int count = 0;
while (getline(cin, mike20))
for (mike20[0]); (isspace(mike20[0]); ++mike20[0])
return 0;
Firstly they are syntax error in your code, it is more like that for (mike20[0]; isspace(mike20[0]); ++mike20[0]). Secondly you seem don't understand how the for loop work. As is nothing change, so the loop is infinite.
You need a variable to browse each char of the string and do your test on each of them.
int cursor;
for (cursor = 0; cursor < number_of_char_in_mike20; ++cursor)
{
isspace(mike20[i]);
}
this code is incomplet you need to declare and initialise the number_of_char_in_mike20 variable and the isspace() function must be define if is not.
PS: don't forget braces {} for while loop and for loop, without only the first instruction is repeated.
for (initialisation(only once); test(each time); increment(each time))
first_instruction; // each time
second_instruction; // after the loop end
third_instruction; // after the loop end
fourth_instruction; // after the loop end
fifth_instruction; // after the loop end
for (initialisation(only once); test(each time); increment(each time))
{
first_instruction; // each time
second_instruction; // each time
third_instruction; // each time
}
fourth_instruction; // after the loop end
fifth_instruction; // after the loop end

What's the range of this for loop? [duplicate]

This question already has answers here:
for loop missing initialization
(6 answers)
Closed 3 years ago.
I'm new to CS, and found this code online. What does this blank between two semicolons indicate? What's the range of this for loop? Thanks.
for (int i = 0, temp; ; i++)
This is the typical structure of a for loop:
for(initialization; condition ; increment/decrement)
{
statement(s);
}
but yours is as follows:
for(initialization; ; increment)
{
statement(s);
}
As you can see the condition part is removed which is completely valid, but this just means that the loop will run infinitely.
Typically in cases like this, some logic inside the loop block will be responsible to break out of the loop given some condition is met.
If you look at the reference for for at learn.microsoft.com you can see the following example.
The following example defines the infinite for loop:
for ( ; ; )
{
// Body of the loop.
}
The infinity comes from the "the condition section" being empty. Again from the reference:
The condition section, if present, must be a boolean expression. That expression is evaluated before every loop iteration. If the condition section is not present or the boolean expression evaluates to true, the next loop iteration is executed; otherwise, the loop is exited.
Here's a bad clock implemented via a never-ending loop to show the difference between how i and temp change as the loop progresses.
public async static Task Main(string[] args)
{
var start = DateTime.Now;
for (int i = 0, temp; ; i++)
{
// 'i' is a) initalised and b) incremented after each
// 'temp' is a) *un*initialised and b) doesn't automatically change
temp = 666;
Console.WriteLine($"It's now {DateTime.Now.TimeOfDay} and this is about {i} seconds after {start.TimeOfDay}. 'temp' is {temp}");
await Task.Delay(TimeSpan.FromSeconds(1));
}
}
Output:
It's now 09:07:02.9269857 and this is about 0 seconds after 09:07:02.9246017. 'temp' is 666
It's now 09:07:04.0195240 and this is about 1 seconds after 09:07:02.9246017. 'temp' is 666
It's now 09:07:05.0223953 and this is about 2 seconds after 09:07:02.9246017. 'temp' is 666
It's now 09:07:06.0379706 and this is about 3 seconds after 09:07:02.9246017. 'temp' is 666
It's now 09:07:07.0482980 and this is about 4 seconds after 09:07:02.9246017. 'temp' is 666
See the docs for for:
The for statement defines initializer, condition, and iterator sections:
for (initializer; condition; iterator)
body
All three sections are optional.
Also, from the same source:
If the condition section is not present or the boolean expression evaluates to true, the next loop iteration is executed; otherwise, the loop is exited.
(emphasis mine)

Distance edit array output

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!

llvm Branch instruction using SplitBlockAndInsertIfThenElse

I'm trying to build an LLVM pass that splits the BasicBlock and make a decision using "SplitBlockAndInsertIfThenElse" every time a binary operation is encountered, however this only allows me to split once (split at the 1st binop). could you please help me make it iterate through all the binop instructions?
Knowing that changing the position of "break;" gives me errors when running the pass. same thing happens when I put the "SplitBlockAndInsertIfThenElse" in a nested loop.
Here is my code:
for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
{
if (auto *op = dyn_cast<BinaryOperator>(&*I))
{
IRBuilder<> Builder(op);
Value *lhs = op->getOperand(0);
Value *rhs = op->getOperand(1);
Value *xpv = Builder.CreateAlloca(llvm::Type::getInt32Ty(llvm::getGlobalContext()), nullptr, "x");
Value *xpv2 = Builder.CreateAlloca(llvm::Type::getInt32Ty(llvm::getGlobalContext()), nullptr, "x2");
Value *add1 = Builder.CreateAdd(lhs, rhs);
Value *add2 = Builder.CreateAdd(lhs, rhs);
Value *icmp1 = Builder.CreateICmpEQ(add1, add2);
TerminatorInst *ThenTerm , *ElseTerm ;
SplitBlockAndInsertIfThenElse(icmp1, op, &ThenTerm, &ElseTerm,nullptr);
Builder.SetInsertPoint(ThenTerm);
Value *xp1 = Builder.CreateStore(add1, xpv);
Builder.SetInsertPoint(ElseTerm);
break ;
}
}
Don't perform concurrent iteration and modification of the instruction list. Iterate until you find the first instruction you care about, then break out of the loop, perform the modification, and restart the loop, starting from the next instruction after the split-before one (so the next instruction after op, in your case).

For loop won't end. Don't know why

I'm writing a for loop for a project that prompts the user to input a number and keeps prompting, continually adding the numbers up. When a string is introduced, the loop should stop. I've done it with a while loop, but the project states that we must do it with a for loop also. The problem is that the prompt keeps running even when 'a = false'. Could someone explain javascript's thinking process? I want to understand why it keeps running back through the loop even though the condition isn't met. Thank you
var addSequence2 = function() {
var total = 0;
var a;
for (; a = true; ) {
var input = prompt("Your current score is " +total+ "\n" + "Next number...");
if (!isNaN(input)) {
a = true;
total = +total + +input;
}
else if (isNaN(input)) {
a = false;
document.write("Your total is " + total);
}
}
};
There is a difference between a = true and a == true.
Your for-loop is basically asking "can I set 'a' to true?", to which the answer is yes, and the loop continues.
Change the condition to a == true (thus asking "Is the value of 'a' true?")
To elaborate, in most programming languages, we distinguish between assignment ("Make 'x' be 4") and testing for equality ("Is 'x' 4?"). By convention (at least in languages that derive their syntax from C), we use '=' to assign/set a value, and '==' to test.
If I'm understanding the specification correctly (no guarantee), what happens here is that the condition condenses as follows:
Is (a = true) true?
Complete the bracket: set a to true
Is (a) true? (we just set it to true, so it must be!)
Try using the equal to operator, i.e. change
for (; a = true; ) {
to
for (; a == true; ) {
You should use a == true instead of a = true......= is an assignment operator
for (; a = true; ), you are assigning the value to the variable "a" and it will always remain true and will end up in infinite loop. In JavaScript it should a===true.
I suspect you want your for to look like this :
for(;a==true;)
as a=true is an assignment, not a comparison.
a == true. The double equal sign compares the two. Single equal assigns the value true to a so this always returns true.
for (; a = true; ) <-- this is an assignation
for (; a == true; ) <-- this should be better
Here's your fixed code :
var addSequence2 = function() {
var total = 0;
var a = true;
for(;Boolean(a);) {
var input = prompt("Your current score is " +total+ "\n" + "Next number...");
if (!isNaN(input)) {
total = total + input;
}
else{
a = false;
document.write("Your total is " + total);
}
}
};

Resources