this code always returns false
I tried to pass lambda parameter by reference and I had the same result
any tip please
vector<int> v1;
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v1.push_back(5);
for (int x : v1)
{
auto it = find_if(v1.begin(), v1.end(), [x](int y){ return x == y; });
if (it != v1.end())
return false;
return true;
}
To check for duplicates (not remove them, just check for them) then you can do something like this:
Get the first value, and check for it in the rest of the container. You should not check the first element again because that's the element we are checking currently.
If a duplicate is not found then go on to the second element, and check from the third element forward. WE don't need to check the first element because that was done in the previous step.
Then continue like that for all elements.
If you find a duplicate then stop the searching and return true. If none are found then continue until the end, and then return false.
This can be done easily using iterators:
// Outer loop, current element to check
for (auto const i = v1.begin(); i != v1.end(); ++i)
{
// Inner loop, the element to check against
for (auto const j = i + 1; j != v1.end(); ++j)
{
if (*i == *j)
return true; // Duplicate found
}
}
// No duplicates found
return false;
The above code shows the principle, you could of course use std::find_if instead of the inner loop. The important thing is to start looking at the next element. All the previous have already been checked, and you should not compare the current value with itself.
Look at your condition in the if. What you meant it to do and what it actually does?
From using for it looks like you want it to go over all the container. Can you find a case where the body of the loop doesn't return immediately on the first iteration?
Related
I've spend some time working on the problem and got this close
fun lengthOfLongestSubstring(s: String): Int {
var set = HashSet<Char>()
var initalChar = 0
var count = 0
s.forEach {r ->
while(!set.add(s[r]))
set.remove(s[r])
initalChar++
set.add(s[r])
count = maxOf(count, r - initialChar + 1)
}
return count
}
I understand that a HashSet is needed to answer the question since it doesn't allow for repeating characters but I keep getting a type mismatch error. I'm not above being wrong. Any assistance will be appreciated.
Your misunderstanding is that r represents a character in the string, not an index of the string, so saying s[r] doesn't make sense. You just mean r.
But you are also using r on its own, so you should be using forEachIndexed, which lets you access both the element of the sequence and the index of that element:
s.forEach { i, r ->
while(!set.add(r))
set.remove(r)
initialChar++
set.add(r)
count = maxOf(count, i - initialChar + 1)
}
Though there are still some parts of your code that doesn't quite make sense.
while(!set.add(r)) set.remove(r) is functionally the same as set.add(r). If add returns false, that means the element is already in the set, you remove it and the next iteration of the loop adds the element back into the set. If add returns true, that means the set didn't have the element and it was successfully added, so in any case, the result is you add r to the set.
And then you do set.add(r) again two lines later for some reason?
Anyway, here is a brute-force solution that you can use as a starting point to optimise:
fun lengthOfLongestSubstring(s: String): Int {
val set = mutableSetOf<Char>()
var currentMax = 0
// for each substring starting at index i...
for (i in s.indices) {
// update the current max from the previous iterations...
currentMax = maxOf(currentMax, set.size)
// clear the set to record a new substring
set.clear()
// loop through the characters in this substring
for (j in i..s.lastIndex) {
if (!set.add(s[j])) { // if the letter already exists
break // go to the next iteration of the outer for loop
}
}
}
return maxOf(currentMax, set.size)
}
I have a short code which I can't seem to figure out. The biggest problem which I have is that I don't understand the error and cannot seem to find how I can change the type of my array.
int [][] spawnLocatiesCoins = new int [20][2];
void collectenVanCoins () {
if (gameState == 1) {
for (int i = 0; i<10; i++) {
if (key == 's' && dist(spawnLocatiesCoins[i][0], spawnLocatiesCoins[i][1], xPosPlayer1, yPosPlayer1) < 20) {
println("catch" + i);
score++;
spawnLocatiesCoins.splice(i, 1);
}
}
}
}
What I am trying to do is remove the spawnLocationsCoins[i] from my array. The error message which I get here is Cannot invoke splice(int, int) on the array type int[][]. I have tried several different approaches for the splice method. I have also tried using the remove method with no result.
Could someone explain to me how I can remove an item from a int [][] array.
You are probably trying to use Processing splice function, however, that doesn't do what you want ("Inserts a value or an array of values into an existing array").
I'd say you are best off using an ArrayList instead of an array, where you can then just use the .remove function like this:
list.remove(index);
Because you want to store 2 values (x and y), you could make an ArrayList of int arrays
ArrayList<int[]> spawnLocatiesCoins = new ArrayList<int[]>();
You can add values like this:
spawnLocatiesCoins.add(new int[]{x_value, y_value});
And access them like this:
spawnLocatiesCoins.get(index)[index_in_the_array];
You could also use PVectors (variables that can store 2/3 values (depending on whether you are making a 3D program)) instead of arrays, but you probably don't need them at this point.
I had an Interview, a day before.
The Interviewer told me to , " Write a program to add a node at the end of a linked list ".
I had given him a solution. but he told me to implement it in one pass (one scan).
Can Anybody explain me, whats the meaning of one pass, and how to find the program written is in one pass or two pass?
Here is my code
public void atLast(int new_data)
{
Node new_node=new Node(new_data);
if(head==null)
{
head=new Node(new_data);
return;
}
new_node.next=null;
Node last=head;
while(last.next!=null)
{
last=last.next;
}
last.next=new_node;
return;
}
If that is the code you gave the interviewer must have misread it because it is a single pass.
In your case a "pass" would be your while loop. It could also be done with recursion, for, or any other type of loop that goes through the elements in the array (or other form of a list of items).
In your code you run through the list of Node and insert the element at the end. This is done in one loop making it a single pass.
Now to look at a case with two passes. Say for example you were asked to remove the element with the largest value and wrote something similar to this:
int index = 0;
int count = 0;
int max = 0;
while(temp_node != null)
{
if(temp_node.data > max)
{
index = count;
max = temp_node.data;
}
count++;
temp_node = temp_node.next;
}
for(int i = 0; i < count; i++)
{
if(i == index)
{
//Functionality to remove node.
}
}
The first pass (while) detects the Node which has the maximum value. The second pass (for) removes this Node by looping through all the elements again until the correct one is found.
I'd imagine "two passes" here means that you iterated through the whole list twice in your code. You shouldn't need to do that to add a new node.
map < string , int > M;
M["Top"] = 1;
M["Coder"] = 2;
M["SRM"] = 10;
int x = M["Top"] + M["Coder"];
if(M.find("SRM") != M.end()) {
M.erase(M.find("SRM")); // or even M.erase("SRM")
}
If no element is found in the M, find() returns M.end(). M.end() points to the element following the last element of the container, it is a
boundary iterator (no data is at this position).
See:
http://en.cppreference.com/w/cpp/container/map/find
http://en.cppreference.com/w/cpp/container/map/end
The code works fine, when the string "SRM" is found in the map, it will be erased from it. Because when method find() does not finds the value it returns an iterator pointing to the end of container.
Maybe you could reformulate question, to be more precise what you want to achieve.
I'm customising a code I found over the internet (it's the Adafruit Tweet Receipt). I cannot understand many parts of the code but the most perplexing to me is the for-loop with two semicolons inside the parentheses
boolean jsonParse(int depth, byte endChar) {
int c, i;
boolean readName = true;
for(;;) { //<---------
while(isspace(c = timedRead())); // Scan past whitespace
if(c < 0) return false; // Timeout
if(c == endChar) return true; // EOD
if(c == '{') { // Object follows
if(!jsonParse(depth + 1, '}')) return false;
if(!depth) return true; // End of file
if(depth == resultsDepth) { // End of object in results list
What does for(;;) mean? (It's an Arduino program so I guess it's in C).
for(;;) {
}
functionally means
while (true) {
}
It will probably break the loop/ return from loop based on some condition inside the loop body.
The reason that for(;;) loops forever is because for has three parts, each of which is optional. The first part initializes the loop; the second decides whether or not to continue the loop, and the third does something at the end of each iteration. It is full form, you would typically see something like this:
for(i = 0; i < 10; i++)
If the first (initialization) or last (end-of-iteration) parts are missing, nothing is done in their place. If the middle (test) part is missing, then it acts as though true were there in its place. So for(;;) is the same as for(;true;)', which (as shown above) is the same as while (true).
The for loop has 3 components, separated by semi-colons. The first component runs before the looping starts and is commonly used to initialize a variable. The second is a condition. The condition is checked at the beginning of each iteration, and if it evaluates to true, then the code in the loop runs. The third components is executed at the end of the loop, before another iteration (starting with condition check) begins, and is often used to increment a variable.
In your case for(;;) means that it will loop forever since the condition is not present. The loop ends when the code returns or breaks.
Each clause of a for loop is optional. So when they are excluded, it still loops. for loops compile into while loops.
The end result becomes a check to initialize any variables, which concludes after nothing happening since it is empty, a check to the boolean condition in the second clause, which is not present so the loop starts, and once the loop hits the end bracket, a check to see if there is any code to run before checking the boolean condition again.
In code it looks like:
while(true){
}
Here's What Wikipedia Says About it
Use as infinite loops
This C-style for-loop is commonly the source of an infinite loop since the fundamental steps of iteration are completely in the control of the programmer. In fact, when infinite loops are intended, this type of for-loop can be used (with empty expressions), such as:
for (;;)
//loop body
This style is used instead of infinite while(1) loops to avoid a type conversion warning in some C/C++ compilers.Some programmers prefer the more succinct for(;;) form over the semantically equivalent but more verbose while (true) form.