I have two integer lists (List<int>). They contain the same elements, but List 1 contains elements that are not in the List 2.
How to find which elements of the List 1 ARE NOT in the List 2.
Thanks :)
PS. lang is c#
You can use IEnumerable.Except:
list1.Except(list2);
new HashSet<int>(l1).ExceptWith(l2);
A very easy solution:
HashSet<int> theSet1 = new HashSet<int>(List1);
theSet1.ExceptWith(List2);
For simplicity you can use the Contains method and check for one list not containing an element of the other:
for (int i = 0; i < list2.Count; ++i)
{
if (!list1.Contains(list2[i]) //current element is not in list 1
//some code
}
If your solution is that firs list contain second and to you hunting onli records added after first list ,
Maybe this is going to be useful
public static int DokleSuIsti(IList<string> prevzemNow, IList<string> prevzemOld)
{
int dobroja = 0;
int kolikohinaje;
if (prevzemOld.Count() < prevzemNow.Count())
{
kolikohinaje = prevzemOld.Count();
}
else
{
kolikohinaje = prevzemNow.Count();
}
for (int i = 0; i < kolikohinaje; i++)
{
if (!Object.Equals(prevzemNow[i], prevzemOld[i]))
{
dobroja = i;
return dobroja;
}
dobroja = i;
}
return dobroja;
}
After that you can use that int as starting point for walk trough your Ilist
If they are not sorted or something, you are going to have a hard time.
Either O(N^2) algorithm (a simple, stupid loop) or additional data structures, tell me which do you prefer.
Or, you can of course alter the source data by sorting, which I suppose is not an option.
Related
I am attempting to code a one dimensional array to display code allowing me to display multiples of seven, I'm not sure how to go through with this, thank you.
I hope I understood your question. You can use generate multiples of 7 using Linq as follows.
var result = Enumerable.Range(1, 100).Select(x => x * 7).ToArray();
Enumerable.Range allows you to generate a sequence of values in specified range (First parameter is the first number in sequence, the second parameter is number of items), while the Select statement (x=>x*7, multiply each value in generated sequence with 7) ensures you get the multiples of 7.
Complete Code:
var result = Enumerable.Range(1, 100).Select(x => x * 7).ToArray();
foreach (var item in result)
{
Console.WriteLine(item);
}
Console.ReadLine();
Due to the vagueness of the question, my answer may not be applicable, but I will attempt to answer based on my assumption of what you are asking.
If you have an array of int and you want to multiply the values of the individual array objects, you would do something like this:
int[] myArray= { 3,5,8};
for (int i = 0; i < myArray.Length; i++)
{
Console.WriteLine(myArray[i]*7);
}
//outputs 21,35,56
If you want to multiply based on the index of the array object, you would do it like this:
int[] myArray= { 3,5,8};
for (int i = 0; i < myArray.Length; i++)
{
Console.WriteLine(i*7);
}
//outputs 0,7,14
//or if you need to start with an index of 1 instead of 0
int[] myArray= { 3,5,8};
for (int i = 0; i < myArray.Length; i++)
{
Console.WriteLine((i+1)*7);
}
//outputs 7,14,21
Anu Viswan also has a good answer, but depending on what it is you are trying to do, it may be better to rely on loops. Hope my answer helps.
public static void FilterLockedThreads(List<string> Links, List<string> LockedLinks)
{
string number;
string number1;
for (int i = 0; i < Links.Count; i++)
{
number = Links[i].Substring(32, 6);
for (int x = 0; x < LockedLinks.Count; x++)
{
number1 = LockedLinks[x].Substring(61, 6);
if (Links[i].Contains(LockedLinks[x]))
{
if (number == number1)
{
string identical = number;
}
}
}
}
}
I used a breakpoint and there are numbers that are part of an item in LockedLinks that also exist in Links.
Both Lists LockedLinks and Links are
For example in Links i have 50 items and in LockedLinks 7 items. For example in Links the item in index 32 is:
http://rotter.net/forum/scoops1/115156.shtml
And in LockedLinks in index 3 :
http://rotter.net/cgi-bin/forum/dcboard.cgi?az=read_count&om=115156&forum=scoops1
In both items there is the same number: 115156
Since this number exist in Links in index 32 and also in LockedLinks in index 3 then i want to remove this indexs from Links and LockedLinks.
In Links remove index 32 and in LockedLinks index 3.
I used substring to get the number from each List each itertion but it's never get inside never get to the string identical.
How can i make the comparison to work with the loops ? And how to make the remove of both indexs if identical ?
I would use Linq to remove duplicates:
using System.Collections.Generic;
using System.Linq;
...
List<int> distinct = list.Distinct().ToList();
http://www.dotnetperls.com/remove-duplicates-list
It's because this line:
if (Links[i].Contains(LockedLinks[x]))
is likely always evaluating to false. I'm not sure why you have that if statement.
Also to remove the items at those indexes you could keep a list if indexes for each array and add the value of x and i to each of them respectively when you find a match in the loop and then use those indexes to remove the items from each array after.
in your example this line would prevent the number comparison:
if (Links[i].Contains(LockedLinks[x]))
{
I think you should simply remove it.
First use more correct methods to get the numbers:
var num1 = Path.GetFileNameWithoutExtension("http://rotter.net/forum/scoops1/115156.shtml"); //return 115156
var num2 = HttpUtility.ParseQueryString(new Uri("http://rotter.net/cgi-bin/forum/dcboard.cgi?az=read_count&om=115156&forum=scoops1").Query)["om"]; //return 115156
Using these methods you can get two Lists, and then check for common numbers to remove them
var newList = list1nums.Except(list2nums).ToList();
In the first part I am creating pairs out of array elements and the array is twice as short. The array is always even.
Here is the first part:
using System;
class Program
{
static void Main()
{
int[] Arr = new int[]{1, 2, 0, 3, 4, -1};
int[] newArr = new int[(Arr.Length / 2)];
int sum = 0;
for (int i = 0; i < Arr.Length; i+=2)
{
if (i + 1 < Arr.Length)
{
newArr[sum] = Arr[i] + Arr[i + 1];
}
else
{
newArr[sum] = Arr[i];
}
sum++;
}
in the second part I would like to check if the array elements are equal. What I want to do is to increment int counter each time the index in the for loop is equal to the next index in the array.
What I have as second part:
int counter = 0;
for (int i = 0; i < newArr.Length -1; i++)
{
if (newArr[i] == newArr[i + 1])
{
counter++;
}
else
{
Console.Write(" ");
}
}
What is wrong in this code. I cannot seem to understand how to write code that will work with int Arr[5] and int Arr[5000]
All you need to change is the termination condition in the for loop to
i < newArr.Length - 1
so that you can compare array[i] with array[i + 1]. This change makes sure you do not get past the upper bound of the array.
try this
for ( i=1;i<arr.Length;i++)
{
if(arr[0]==arr[i])
continue;
else
break;
}
if (i==arr.Length)
Console.WriteLine("All element in array are equal");
If there is no need to write so imperative code, other than to achieve your final goal – you don't have to. Almost always you can do it in a much more readable way.
I suggest using LINQ. For collections implementing IEnumerable<T>:
newArr.Distinct().Take(2).Count() == 1
LINQ is a built-in feature, just make sure you are using System.Linq; at the top of your .cs file.
What goes on here?
Distinct returns an IEnumerable<T>, its enumeration will give all distinct elements from your array, but no enumeration, and hence computation, happened yet.
Take returns new IEnumerable<T>, its enumeration will enumerate previous IEnumerable<T> internally, but it will give only first two distinct elements. Again, no enumeration happened yet.
At last, Count enumerates the last IEnumerable<T> and returns its elements count (in our case 0, 1 or 2).
As we used Take(2), the enumeration initiated by Count method will be stopped right when the second distinct element is found. If we don't use Take(2), our code will enumerate the whole array even if it is not needed.
Why is this approach better?
Much shorter and more readable;
Lazy evaluation – if an element is found out to be distinct from the other ones, the enumeration will be stopped immediately;
Flexible – you can pass a custom equality comparer to Distinct method. You can also call Select method before calling Distinct to choose what specific member your elements will be compared by;
Universal – Works with any collection which impletents IEnumerable<T> interface.
Other ways
The same result can be achieved in slightly other ways, for example:
!newArr.Distinct().Take(2).Skip(1).Any()
Experiment with LINQ and choose the way you and your team consider the most readable.
For collections implementing IList<T> you can also write (as #Alexander suggested):
newArr.All(x => x == newArr[0])
This variant is shorter but not as flexible and universal.
OFF TOPIC. Encapsulating common code
You should encapsulate code that does one simple thing into a separate method, it further improves your code readability and allows reusing your method in several places. I'd write an extension method for this one.
public static class CollectionExtensions {
public static bool AllElementsEqual<T>(this IEnumerable<T> items) {
return items.Distinct().Take(2).Count() == 1;
}
}
Later in your code you need just to call this method:
newArr.AllElementsEqual()
Try this..
for (int i = 0; i < newArr.Length-1; i++)
{
for(int j=0 ;j< newArr.Length-1; i++)
{
if (newArr[i] == newArr[j])
{
/////
}
}
}
else
{
Console.Write(" ");
}
}
Sorry for the newbie question. Could someone help me out? Simple array here. What's the best/easiest method to check all the user input is unique and not duplicated? Thanks
private void btnNext_Click(object sender, EventArgs e)
{
string[] Numbers = new string[5];
Numbers[0] = txtNumber1.Text;
Numbers[1] = txtNumber2.Text;
Numbers[2] = txtNumber3.Text;
Numbers[3] = txtNumber4.Text;
Numbers[4] = txtNumber5.Text;
foreach (string Result in Numbers)
{
lbNumbers.Items.Add(Result);
}
txtNumber1.Clear();
txtNumber2.Clear();
txtNumber3.Clear();
txtNumber4.Clear();
txtNumber5.Clear();
}
}
}
I should have added I need to check to happen before the numbers are output. Thanks
One simple approach is via LINQ:
bool allUnique = Numbers.Distinct().Count() == Numbers.Length;
Another approach is using a HashSet<string>:
var set = new HashSet<string>(Numbers);
if (set.Count == Numbers.Count)
{
// all unique
}
or with Enumerable.All:
var set = new HashSet<string>();
// HashSet.Add returns a bool if the item was added because it was unique
bool allUnique = Numbers.All(text=> set.Add(text));
Enunmerable.All is more efficient when the sequence is very large since it does not create the set completely but one after each other and will return false as soon as it detects a duplicate.
Here's a demo of this effect: http://ideone.com/G48CYv
HashSet constructor memory consumption: 50 MB, duration: 00:00:00.2962615
Enumerable.All memory consumption: 0 MB, duration: 00:00:00.0004254
msdn
The HashSet<T> class provides high-performance set operations.
A set is a collection that contains no duplicate elements, and whose
elements are in no particular order.
The easiest way, in my opinion, would be to insert all values inside a set and then check if its size is equal to the array's size. A set can't contain duplicate values, so if any value is duplicate, it won't be inserted into the set.
This is also OK in complexity if you don't have millions of values, because insertion in a set is done in O(logn) time, so total check time will be O(nlogn).
If you want something optimal in complexity, you can do this in O(n) time by going through the array, and putting each value found into a hash map while incrementing its value: if value doesn't exist in set, you add it with count = 1. If it does exist, you increment its count.
Then, you go through the hash map and check that all values have a count of one.
If you are just trying to make sure that your listbox doesn't have dups then use this:
if(!lbNumbers.Items.Contains(Result))
lbNumbers.Items.Add(Result);
What about this:
public bool arrayContainsDuplicates(string[] array) {
for (int i = 0; i < array.Length - 2; i++) {
for (int j = i + 1; j < array.Length - 1; j++) {
if (array[i] == array[j]) return true;
}
}
return false;
}
Note: This is part 2 of a 2 part question.
Part 1 here
I'm wanting to more about sorting algorithms and what better way to do than then to code! So I figure I need some data to work with.
My approach to creating some "standard" data will be as follows: create a set number of items, not sure how large to make it but I want to have fun and make my computer groan a little bit :D
Once I have that list, I'll push it into a text file and just read off that to run my algorithms against. I should have a total of 4 text files filled with the same data but just sorted differently to run my algorithms against (see below).
Correct me if I'm wrong but I believe I need 4 different types of scenarios to profile my algorithms.
Randomly sorted data (for this I'm going to use the knuth shuffle)
Reversed data (easy enough)
Nearly sorted (not sure how to implement this)
Few unique (once again not sure how to approach this)
This question is for generating a list with a few unique items of data.
Which approach is best to generate a dataset with a few unique items.
Answering my own question here. Don't know if this is the best but it works.
public static int[] FewUnique(int uniqueCount, int returnSize)
{
Random r = _random;
int[] values = new int[uniqueCount];
for (int i = 0; i < uniqueCount; i++)
{
values[i] = i;
}
int[] array = new int[returnSize];
for (int i = 0; i < returnSize; i++)
{
array[i] = values[r.Next(0, values.Count())];
}
return array;
}
It might be worth having a look at NBuilder. It's a framework designed to generate objects for testing with and sounds like just what you need.
You could deal with the "few unique" items with some code like this:
var products = Builder<YourClass>.CreateListOfSize(1000)
.WhereAll().AreConstructedWith("some fixed value")
.WhereRandom(20).AreConstructedWith("some other fixed value")
.Build();
There's plenty of other variations you can use as well to get the data like you want it. Have a look at some of the samples on the site for more ideas.
http://pages.cs.wisc.edu/~bart/fuzz/
Is all about fuzz testing which focuses on semi random data. It should be straight forward to adapt this approach to your problem
I guess your solution is ok. I would only modify it slighly:
public static int[] FewUnique(int uniqueCount, int low, int high, int returnSize)
{
Random r = _random;
int[] values = new int[uniqueCount];
for (int i = 0; i < uniqueCount; i++)
{
values[i] = r.Next(low, high);
}
int[] array = new int[returnSize];
for (int i = 0; i < returnSize; i++)
{
array[i] = values[r.Next(0, values.Count())];
}
return array;
}
For some algorithms this might make a difference.