C
C#7d ago
zzz

changing a boolean value outside a loop from inside a loop

so im doing a leetcode challenge to detect duplicate numbers in an array, im trying to use the duplicate bool value so when a duplicate is detected, it edits the duplicate value to true and exits the loop, no matter what i try the output is always false however
public class Solution
{

int[] nums ={1, 2, 3, 1};

public bool ContainsDuplicate(int[] nums)
{
bool running = true;
bool duplicate = false;
int count = 0;
int count2 = 0;

while (running == true)
{
foreach (int x in nums)
{
foreach (int z in nums)
{

if (z == nums[count])
{
count2++;
break;
}

count++;
}
if (count2 > 1)
{
running = false;
duplicate = true;
}
count2 = 0;

}
running = false;
}
return duplicate;
}
}
public class Solution
{

int[] nums ={1, 2, 3, 1};

public bool ContainsDuplicate(int[] nums)
{
bool running = true;
bool duplicate = false;
int count = 0;
int count2 = 0;

while (running == true)
{
foreach (int x in nums)
{
foreach (int z in nums)
{

if (z == nums[count])
{
count2++;
break;
}

count++;
}
if (count2 > 1)
{
running = false;
duplicate = true;
}
count2 = 0;

}
running = false;
}
return duplicate;
}
}
11 Replies
zzz
zzz7d ago
from what i can see when i try and set duplicate to true it is not accessing the variable outside the loop any help appreciated im still new
Angius
Angius7d ago
Or, what is much more likely than the language completely breaking, count2 is never more than 1
zzz
zzz7d ago
its probably not the most efficient way of solving the problem how? it loops through whole array and increases count everytime there is a same number
Angius
Angius7d ago
Well, the easiest way to figure it out is to place some breakpoints and debug it
zzz
zzz7d ago
leetcode isnt good for that is it i dont have vs on this pc it only shows me my outputs for each test case when i run it ill try it on studio tomorrow
Angius
Angius7d ago
Then trying to figure it out really won't be easy
zzz
zzz7d ago
yh
Angius
Angius7d ago
You can run this code on Sharplab and do some good ol' Console.WriteLine() debugging
zzz
zzz7d ago
ill just watch a tutorial ig p[robably a more efficient way anyway thx tho
Dinosaure
Dinosaure7d ago
As stated, when a duplicate is found, count2 is incremented once; then, the condition for the bool change is count2 > 1, which won’t happen ever. Maybe the condition could be count2 >= 1? Or maybe you can use LINQ, with bool duplicate = nums.ToLookup(n => n).Any(g => g.Count() > 1); (requires using System.Linq as a header), instead of the entire while block?
Dinosaure
Dinosaure7d ago
@zzz if you want to briefly test some C# code, you can use sharplab.io, it’s an online dev pad, where you'll find nearly everything you need for proof of concepts.
SharpLab
C#/VB/F# compiler playground.
Want results from more Discord servers?
Add your server