Replacing non frequent elements in sequencial c# - c#

I have an array that contains integers
1,1,2,1,1,2,2,2,3,3,3,2,4,4,4,4
I want to be able to replace elements that don't complete the repeated order of the sequence so from the example above it would be like
1,1,1,1,1,2,2,2,3,3,3,3,4,4,4,4.
I have tried playing around with a few ugly sprawling functions but I am like looping through but it was all in vein so am.
wondering if there is a neat LINQ- way to do it.
Any suggestions?

It would be hard if not impossible to implement this in just only LINQ. You would have to implement the following method if you would like to have functionallity like the one you described:
using System;
namespace LinqSequence
{
class Program
{
static void Main(string[] args)
{
var arr = new int[]
{
1,1,2,2,2,1,2,3,3,3,2,4,4,4,5,5,4,4
};
var newArr = SequenceReplace(arr);
Console.WriteLine(String.Join(", ",newArr));
//OUT: 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5
}
static int[] SequenceReplace(int[] arr)
{
int length = arr.Length;
var newArr = new int[length];
int previous = 0;
for (int i = 0; i < length; i++)
{
if (newArr[previous] > arr[i])
{
newArr[i] = newArr[previous];
}
else
{
newArr[i] = arr[i];
}
previous = i;
}
return newArr;
}
}
}
EDIT:
The previous program was not correct because it didn't look at both adjectant fields. So the program didn't work for the test case in your question. So this is the new answer. It looks at both adjectant fields and if current is diffrent than both it replaces current with the one on the left. Also it takes care of edge cases. If the length is less than 2 it just returns that array, if length is 2 it returns array with 2 element 0's. If there is no next element it replaces that element with the previous one.
using System;
namespace LinqSequence
{
class Program
{
static void Main(string[] args)
{
var arr1 = new int[]
{
1,1,2,1,1,2,2,2,3,3,3,2,4,4,4,4
};
var newArr1 = SequenceReplace(arr1);
Console.WriteLine(String.Join(",",newArr1));
//OUT: 1,1,1,1,1,2,2,2,3,3,3,3,4,4,4,4
var arr2 = new int[]
{
1,1,2,2,2,1,2,3,3,3,2,4,4,4,5,5,4,4
};
var newArr2 = SequenceReplace(arr2);
Console.WriteLine(String.Join(",",newArr2));
//OUT: 1,1,2,2,2,2,2,3,3,3,3,4,4,4,5,5,4,4
}
static int[] SequenceReplace(int[] arr)
{
int length = arr.Length;
if (length == 2) return new int[] { arr[0], arr[0] };
else if (length < 2) return arr;
var newArr = new int[length];
newArr[0] = arr[0];
int previous = 0, next = 2;
for (int i = 1; i < length; i++)
{
if ((next < length &&
newArr[previous] != arr[i] &&
arr[next] != arr[i]) ||
next >= length)
{
newArr[i] = newArr[previous];
}
else
{
newArr[i] = arr[i];
}
previous++;
next++;
}
return newArr;
}
}
}
Here's ideone.

Just use orderBy func like this:
List<int> list = new List<int>() { //your data };
list = list.OrderBy(i=> i);

Use sort and regex like this
static void Main(string[] args)
{
string input = "00H1,00H1,00H2,00H1,00H1,00H2,00H2,00H2,00H3,00H3,00H2,00H3";
List<string> array = input.Split(new char[] { ',' }).ToList();
array.Sort((x,y) => GetSuffix(x).CompareTo(GetSuffix(y)));
string output = string.Join(",",array);
}
static int GetSuffix(string input)
{
string pattern = "H(?'suffix'\\d*)";
Match match = Regex.Match(input, pattern);
return int.Parse(match.Groups["suffix"].Value);
}​
Here is Linq solution
static void Main(string[] args)
{
string input = "00H1,00H1,00H2,00H1,00H1,00H2,00H2,00H2,00H3,00H3,00H2,00H3";
List<string> array = input.Split(new char[] { ',' }).ToList();
array = array.Select(x => new
{
suffix = GetSuffix(x),
item = x
}).OrderBy(x => x.suffix).Select(x => x.item).ToList();
string output = string.Join(",",array);
}
static int GetSuffix(string input)
{
string pattern = "H(?'suffix'\\d*)";
Match match = Regex.Match(input, pattern);
return int.Parse(match.Groups["suffix"].Value);
}​

Related

Fisher–Yates shuffle in C#

I have this method Shuffle that supposes to return a set of random numbers which was displayed in the above method but the numbers need to be displayed in a mixed format.
The first method works well since the number are being displayed correctly in the set of range but this method Shuffle is not returning them in a mixed format.
Example:
The first method returned: 1, 2, 3, 4, 5
This method needs to return 2, 1, 4, 5, 3
public int[] Shuffle(int[] Sequence)
{
int[] Array = new int[Sequence.Length];
for(int s=0; s < Array.Length-1; s++){
int GenObj = GenerateAnotherNum (0, Array.Length + 1);
Array[s] = Sequence[GenObj];
Sequence[GenObj] = Array[s];
}
return Sequence;
}
You have several problems here: all zeroes array, range and swap procedure
Algorithm:
https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
Code:
// probably "static" should be added (depends on GenerateAnotherNum routine)
public int[] Shuffle(int[] Sequence)
{
// public method's arguments validation
if (null == Sequence)
throw new ArgumentNullException(nameof(Sequence));
// No need in Array if you want to modify Sequence
for(int s = 0; s < Sequence.Length - 1; s++)
{
int GenObj = GenerateAnotherNum(s, Sequence.Length); // pleace, note the range
// swap procedure: note, var h to store initial Sequence[s] value
var h = Sequence[s];
Sequence[s] = Sequence[GenObj];
Sequence[GenObj] = h;
}
return Sequence;
}
Demo:
// Random(0) - we want to reproduce the results in the demo
private static Random random = new Random(0);
// Let unknown GenerateAnotherNum be a random
private static int GenerateAnotherNum(int from, int to) => random.Next(from, to);
...
int[] array = new int[] { 1, 2, 3, 4, 5 };
string result = string.Join(", ", Shuffle(array));
Console.Write(result);
Outcome:
4, 5, 2, 3, 1
public static class Shuffler<T>
{
private static Random r = new Random();
public static T[] Shuffle(T[] items)
{
for(int i = 0; i < items.Length - 1; i++)
{
int pos = r.Next(i, items.Length);
T temp = items[i];
items[i] = items[pos];
items[pos] = temp;
}
return items;
}
public static IList<T> Shuffle(IList<T> items)
{
for(int i = 0; i < items.Count - 1; i++)
{
int pos = r.Next(i, items.Count);
T temp = items[i];
items[i] = items[pos];
items[pos] = temp;
}
return items;
}
}

Permutations with constant prefix numbers

I have an array of integers where each value will have distinct meanings.The first value means the length of permutation, the second value represent the length of initial prefix and rest of integers are single integer that make up prefix of all permutations.
For e.g. if the array has elements {5,2,1,4}
where 5 is the number of elements in the permutation array.
and 2 is the length of the integer that will makeup the first 2 elements prefix in the array permutation. 1,4 are the prefix integers i.e. length 2 in 5 element permutation combination so missing elements are 2,3,5 where 1&4 being common prefix across all permutations as below
[14235][14253][14325][14352][14523][14532] where input array is {5,2,1,4}
How to achieve this?
I have below code to get the permutation of one missing elements 2,3 & 5 but I am not getting how to program the entire the solution
static void Main(string[] args)
{
int output;
int ip1;
ip1 = Convert.ToInt32(Console.ReadLine());
int ip2_size = 0;
ip2_size = Convert.ToInt32(Console.ReadLine());
int[] ip2 = new int[ip2_size];
int ip2_item;
for (int ip2_i = 0; ip2_i < ip2_size; ip2_i++)
{
ip2_item = Convert.ToInt32(Console.ReadLine());
ip2[ip2_i] = ip2_item;
}
output = correctResult(ip1, ip2);
Console.WriteLine(output);
}
static int correctResult(int n, int[] arr)
{
int permLength = 0;
int prefLength = 0;
int result = 0;
permLength = n;
prefLength = arr.Length;
int[] permArray = new int[permLength];
int len = 0;
var missingNum = Enumerable.Range(1,
permLength).Except(arr).ToArray<int>();
if (permLength < (missingNum.Length + len))
{
result = -1;
}
else
{
for (int i = 0; i < missingNum.Length; i++)
{
permArray[prefLength + i] = missingNum[i];
}
result = permute(missingNum, 0, missingNum.Length - 1);
}
return result;
}
static int permute(int[] arry, int i, int n)
{
int j;
if (i == n)
{
int s1, s2;
s1 = s2 = 0;
for (int a = 0; a < n - 1; a++)
{
for (int b = a + 1; b < n; b++)
{
if (arry[a] > arry[b])
{
s1++;
}
}
s2 = s2 + Math.Max(0, a + 1 - arry[a]);
}
int count = 0;
if (s1 == s2)
count++;
return count;
}
else
{
int count = 0;
for (j = i; j <= n; j++)
{
swap(ref arry[i], ref arry[j]);
count += permute(arry, i + 1, n);
swap(ref arry[i], ref arry[j]);
}
return count;
}
}
static void swap(ref int a, ref int b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
}
Try solving this with immutable types, its easier to reason about them. If, after solving the problem, you have a performance goal you haven't met then you can start trying to optimize the code.
Consider the following approach with an immutable stack that keeps track of the current permutation:
static IEnumerable<IEnumerable<int>> GetPermutations(IList<int> input)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
if (input.Count < 2)
throw new ArgumentException("Input does not have a valid format.");
var setSize = input[0];
var prefixSize = input[1];
if (prefixSize != input.Count - 2)
throw new ArgumentException("Input does not have a valid format.");
if (input.Skip(2).Any(i => i > setSize)) //we are assuming, per example, that valid range starts at 1.
throw new ArgumentException("Input does not have a valid format.");
//Ok, we've got a valid input, interesting stuff starts here.
var prefix = input.Skip(2).ToArray();
var initialSet = Enumerable.Range(1, setSize)
.Except(prefix)
.ToArray();
foreach (var p in getPermutations(ImmutableStack<int>.Empty, initialSet))
{
yield return prefix.Concat(p);
}
IEnumerable<IEnumerable<int>> getPermutations(ImmutableStack<int> permutation, IEnumerable<int> set)
{
if (permutation.Count == setSize - prefixSize)
{
yield return permutation;
}
else
{
foreach (var i in set)
{
foreach (var p in getPermutations(permutation.Push(i), set.Except(new[] { i })))
{
yield return p;
}
}
}
}
}
And that is it, solving your problem was about 10-12 lines of real code (not considering input validation). Note that I am using some c#7 features here, but its easily translatable to previous versions of the language. Also I'd like to underline the argument validation we are doing upfront; make sure you have a valid input before trying out anything.
For ImmutableStack<T> you can use the one in System.Collections.Immutable (you have to download the NuGet package) or implement your own, its simple:
private class ImmutableStack<T>: IEnumerable<T>
{
public static readonly ImmutableStack<T> Empty = new ImmutableStack<T>();
private readonly T head;
private readonly ImmutableStack<T> tail;
private ImmutableStack() { }
private ImmutableStack(T head, ImmutableStack<T> tail)
{
Debug.Assert(tail != null);
this.head = head;
this.tail = tail;
Count = tail.Count + 1;
}
public int Count { get; }
public T Peek() =>
this != Empty ? head : throw new InvalidOperationException("Empty stack.");
public ImmutableStack<T> Pop() =>
this != Empty ? tail : throw new InvalidOperationException("Empty stack.");
public ImmutableStack<T> Push(T item) => new ImmutableStack<T>(item, this);
public IEnumerator<T> GetEnumerator()
{
var current = this;
while (current != Empty)
{
yield return current.head;
current = current.tail;
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
If you use the collections in System.Collections.Immutable, then you'll probably want to use some kind of immutable set for initalSet and set.
You can rewrite your permute method (based on this answer):
private static IEnumerable<IEnumerable<T>> Permute<T>(List<T> prefix, List<T> suffix)
{
for (var i = 0; i < suffix.Count; ++i)
{
var newPrefix = new List<T>(prefix) {suffix[i]};
var newSuffix = new List<T>(suffix.Take(i).Concat(suffix.Skip(i + 1)));
if (newSuffix.Count == 0)
{
yield return newPrefix;
continue;
}
foreach (var permutation in Permute(newPrefix, newSuffix))
yield return permutation;
}
}
And use it like this:
public static void PrintAllPermutations()
{
var input = new[] {5, 2, 1, 4};
var prefix = input.Skip(2).Take(input[1]).ToList();
var suffx = Enumerable.Range(1, input[0]).Except(prefix).ToList();
foreach (var permutation in Permute(prefix, suffx))
Console.WriteLine(string.Join(", ", permutation));
}
Reult would be:
1, 4, 2, 3, 5
1, 4, 2, 5, 3
1, 4, 3, 2, 5
1, 4, 3, 5, 2
1, 4, 5, 2, 3
1, 4, 5, 3, 2

Move duplicate numbers at end in integer array

I want to move all duplicate numbers at the end of array like this.
{4,1,5,4,3,1,6,5}
{4,1,5,3,6,4,1,5}
also i want to know number of dups. that i will use to resize array.
here is the code i tried but this code is not compatible when i insert more than 2 dups at starting.
static void RemoveRepeated(ref int[] array)
{
int count = 0; bool flag;
for (int i = 0; i < array.Length; i++)
{
flag = true;
for (int j = i+1; j < array.Length-1; j++)
{
if (array[i] == array[j] )
{
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
if (flag)
{
count++;
flag = false;
}
}
}
}
Array.Resize(ref array,array.Length-count);
}
Thanks in advance :)
A good solution will be to use a fitting data-structure. It will not fix your algorithm but replace it. Here a HashSet<T> is perfect. A HashSet<T> remove itself all duplicate. Check the msdn for more informations.
Demo on .NETFiddle
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var array = new int[]{ 4,1,5,4,3,1,6,5 };
RemoveRepeated(ref array);
foreach (var item in array)
Console.WriteLine(item);
}
static void RemoveRepeated(ref int[] array)
{
array = new HashSet<int>(array).ToArray();
}
}
By the way you don't really need ref here. I would remove it and change void RemoveRepeated(ref int[] array) to int[] RemoveRepeated(int[] array). See ref parameter or return value?
What you are doing is equivalent to leaving only the unique elements in their original order. Here is simpler way to do this:
static void RemoveRepeated(ref int[] array)
{
HashSet<int> seen = new HashSet<int>();
List<int> newArray = new List<int>(array.Length);
foreach(int x in array)
{
if(!seen.Contains(x))
{
seen.Add(x);
newArray.Add(x);
}
}
array = newArray.ToArray();
}
Don't use an array here. You can try to (just one example) group a List<int> and Count() all groups that have more than one element. When you have the count, you can use Distinct() to get only the distinct elements.
In my opinion, resizing an array like this is always a very bad idea.
Edit:
Well, like the other answers already stated, a HashSet is a even better way of doing it.
class Program
{
static void Main(string[] args)
{
int[] arr = new int[] { 4, 1, 5, 4, 3, 1, 6, 5 };
RemoveRepeated(ref arr);
foreach (int i in arr)
{
Console.WriteLine(i);
}
Console.ReadKey();
}
private static void RemoveRepeated(ref int[] array)
{
int count =0;
for (int i = 0; i < array.Length; i++)
{
for (int j = i + 1; j < array.Length; j++)
{
if (array[i] == array[j])
{
int temp = array[j];
count++;
for (int k = j; k < array.Length-1; k++)
{
array[k] = array[k + 1];
}
array[array.Length - 1] = temp;
j = array.Length;
}
}
}
Array.Resize(ref array, array.Length - count);
}
}
Try this:
class Program
{
static void Main(string[] args)
{
int[] ints = {4,1,5,4,3,1,6,5};
var query = ints.GroupBy(x => x).OrderBy(x => x.Count()).Select(x => x);
// print ordered array showing dupes are last
query.ToList().ForEach(x => Console.WriteLine(x.Key.ToString()));
// Get number of dupes
int dupeCount = query.Where(x => x.Count() > 1).Count();
// put unique items into a new array
var newArray = query.Where(x => x.Count() == 1).Select(x => x.Key).ToArray();
// put distinct items into an array
var distinctArray = ints.Distinct().ToArray();
Console.ReadKey();
}
}
Edit: Added distinct elements
If you want to move the duplicates to the end of array (but preserve order) you can do this:
static void RemoveRepeated(ref int[] array)
{
var lookup = array.ToLookup(x => x);
var maxdupes = lookup.Select(x => x.Count()).Max();
var reordered =
Enumerable
.Range(0, maxdupes)
.SelectMany(x => lookup.SelectMany(y => y.Skip(x).Take(1)))
.ToArray();
Array.Copy(reordered, array, reordered.Length);
}
This would turn { 4, 1, 5, 4, 3, 1, 6, 5 } into { 4, 1, 5, 3, 6, 4, 1, 5 }
You can easily get the number of duplicates by doing this:
lookup
.Select(x => new
{
Value = x.Key,
Count = x.Count(),
});
This returns:
4 2
1 2
5 2
3 1
6 1

Algorithm for finding a group of numbers in a list that equal a target

So here is what I'm trying to do. I have a list of integers:
List<int> myList = new List<int>() {5,7,12,8,7};
And I also got a target:
int target = 20;
What I'm trying to do is find a way to create a new list of integer that when added together equal my target. So if my target is 20, I need a list like this:
{ 12, 8 }
If my target is 26, then I'll have this:
{ 7, 12, 7 }
Each number can only be used one time (7 is used twice because its in the list twice). If there is no solution, it should return an empty list. Anyone have any idea how I can do something like this?
That's a statistical problem. You want to find all possible combinations with a matching sum. I can recommend this project which is also worth reading:
http://www.codeproject.com/Articles/26050/Permutations-Combinations-and-Variations-using-C-G
Then it's easy and efficient:
List<int> myList = new List<int>() { 5, 7, 12, 8, 7 };
var allMatchingCombos = new List<IList<int>>();
for (int lowerIndex = 1; lowerIndex < myList.Count; lowerIndex++)
{
IEnumerable<IList<int>> matchingCombos = new Combinations<int>(myList, lowerIndex, GenerateOption.WithoutRepetition)
.Where(c => c.Sum() == 20);
allMatchingCombos.AddRange(matchingCombos);
}
foreach(var matchingCombo in allMatchingCombos)
Console.WriteLine(string.Join(",", matchingCombo));
Output:
12,8
5,7,8
5,8,7
Using recursion. Note that this solution will favor solutions that can be acquired by using the first items from the list. So for a target of 20, you won’t get 12+8 as the solution but 5+7+8.
List<int> findSum(List<int> numbers, int target, int index = 0)
{
// loop through all numbers starting from the index
for (var i = index; i < numbers.Count; i++)
{
int remainder = target - numbers[i];
// if the current number is too big for the target, skip
if (remainder < 0)
continue;
// if the current number is a solution, return a list with it
else if (remainder == 0)
return new List<int>() { numbers[i] };
else
{
// otherwise try to find a sum for the remainder later in the list
var s = findSum(numbers, remainder, i + 1);
// if no number was returned, we could’t find a solution, so skip
if (s.Count == 0)
continue;
// otherwise we found a solution, so add our current number to it
// and return the result
s.Insert(0, numbers[i]);
return s;
}
}
// if we end up here, we checked all the numbers in the list and
// found no solution
return new List<int>();
}
void Main()
{
List<int> myList = new List<int>() { 5, 7, 12, 8, 7 };
Console.WriteLine(findSum(myList, 12)); // 5, 7
Console.WriteLine(findSum(myList, 20)); // 5, 7, 8
Console.WriteLine(findSum(myList, 31)); // 5, 7, 12, 7
}
You can find all the solutions given below here: https://github.com/Mr-Zoidberg/Find-Possible-Combinations
1. Using recursion
static void Main(string[] args)
{
const int target = 20;
var numbers = new List<int> { 1, 2, 5, 8, 12, 14, 9 };
Console.WriteLine($"Number of Combinations: {SumCounter(numbers, target)}");
Console.ReadKey();
}
private static int SumCounter(IReadOnlyList<int> numbers, int target)
{
var result = 0;
RecursiveCounter(numbers, target, new List<int>(), ref result);
return result;
}
private static void RecursiveCounter(IReadOnlyList<int> numbers, int target, List<int> partial, ref int result)
{
var sum = partial.Sum();
if (sum == target)
{
result++;
Console.WriteLine(string.Join(" + ", partial.ToArray()) + " = " + target);
}
if (sum >= target) return;
for (var i = 0; i < numbers.Count; i++)
{
var remaining = new List<int>();
for (var j = i + 1; j < numbers.Count; j++) remaining.Add(numbers[j]);
var partRec = new List<int>(partial) { numbers[i] };
RecursiveCounter(remaining, target, partRec, ref result);
}
}
2. Get subsets using Linq
static void Main(string[] args)
{
const int target = 20;
var numbers = new int[] { 1, 2, 5, 8, 12, 14, 9 };
var matches = numbers.GetSubsets().Where(s => s.Sum() == target).ToArray();
foreach (var match in matches) Console.WriteLine(match.Select(m => m.ToString()).Aggregate((a, n) => $"{a} + {n}") + $" = {target}");
Console.WriteLine($"Number of Combinations: {matches.Length}");
Console.ReadKey();
}
}
public static class Extension
{
public static IEnumerable<IEnumerable<T>> GetSubsets<T>(this IEnumerable<T> collection)
{
if (!collection.Any()) return Enumerable.Repeat(Enumerable.Empty<T>(), 1);
var element = collection.Take(1);
var ignoreFirstSubsets = GetSubsets(collection.Skip(1));
var subsets = ignoreFirstSubsets.Select(set => element.Concat(set));
return subsets.Concat(ignoreFirstSubsets);
}
3. Another recursive method...
static void Main(string[] args)
{
const int target = 20;
var numbers = new [] { 1, 2, 5, 8, 12, 14, 9 };
var result = GetSubsets(numbers, target, "");
foreach (var subset in result) Console.WriteLine($"{subset} = {target}");
Console.WriteLine($"Number of Combinations: {result.Count()}");
Console.ReadLine();
}
public static IEnumerable<string> GetSubsets(int[] set, int sum, string values)
{
for (var i = 0; i < set.Length; i++)
{
var left = sum - set[i];
var vals = values != "" ? $"{set[i]} + {values}" : $"{set[i]}";
if (left == 0) yield return vals;
else
{
int[] possible = set.Take(i).Where(n => n <= sum).ToArray();
if (possible.Length <= 0) continue;
foreach (string s in GetSubsets(possible, left, vals)) yield return s;
}
}
}
4. Using binary search. Linear time.
static void Main(string[] args)
{
const int target = 20;
var numbers = new [] { 1, 2, 5, 8, 12, 14, 9 };
var subsets = GetSubsets(numbers, target);
foreach (var s in subsets) Console.WriteLine($"{s} = {target}");
Console.WriteLine($"Number of Combinations: {subsets.Count()}");
Console.ReadKey();
}
private static IEnumerable<string> GetSubsets(int[] array, int target)
{
Array.Sort((Array)array);
List<string> result = new List<string>();
for (int i = array.Length-1; i >= 0; i--)
{
var eq = $"{array[i]}";
var sum = array[i];
var toAdd = 0;
while (sum != target)
{
var mid = Array.BinarySearch(array, 0, sum <= target / 2 && sum != array[i] ? array.Length - 1 : i, target - sum);
mid = mid < 0 ? ~mid - 1 : mid;
if (mid == i || mid < 0 || toAdd == array[mid] ) break;
toAdd = array[mid];
sum += array[mid];
eq += $" + {array[mid]}";
if (sum == target) result.Add(eq);
}
}
return result;
}
This implementation of mine in C# will return all combinations(including repetitive use of same number) that equals a given number.
string r;
List<int> l = new List<int>();
void u(int w, int s, int K, int[] A) {
// If a unique combination is found
if (s == K) {
r += "(" + String.Join(" ", l) + ")";
return;
}
// For all other combinations
for (int i=w; i<A.Length; i++){
// Check if the sum exceeds K
int x = A[i];
if (s + x <= K){
l.Add(x);
u(i, s + x, K,A);
l.Remove(x);
}
}
}
string combinationSum(int[] a, int s) {
r = "";
u(0, 0, s, a.Distinct().OrderBy(x=>x).ToArray());
return r.Any() ? r : "Empty";
}
for a: [2, 3, 5, 9] and s = 9
the result will be :
"(2 2 2 3)(2 2 5)(3 3 3)(9)"

Check for missing number in sequence

I have an List<int> which contains 1,2,4,7,9 for example.
I have a range from 0 to 10.
Is there a way to determine what numbers are missing in that sequence?
I thought LINQ might provide an option but I can't see one
In the real world my List could contain 100,000 items so performance is key
var list = new List<int>(new[] { 1, 2, 4, 7, 9 });
var result = Enumerable.Range(0, 10).Except(list);
Turn the range you want to check into a HashSet:
public IEnumerable<int> FindMissing(IEnumerable<int> values)
{
HashSet<int> myRange = new HashSet<int>(Enumerable.Range(0,10));
myRange.ExceptWith(values);
return myRange;
}
Will return the values that aren't in values.
Using Unity i have tested two solutions on set of million integers. Looks like using Dictionary and two "for" loops gives better result than Enumerable.Except
FindMissing1 Total time: 0.1420 (Enumerable.Except)
FindMissing2 Total time: 0.0621 (Dictionary and two for loops)
public static class ArrayExtension
{
public static T[] FindMissing1<T>(T[] range, T[] values)
{
List<T> result = Enumerable.Except<T>(range, values).ToList<T>();
return result.ToArray<T>();
}
public static T[] FindMissing2<T>(T[] range, T[] values)
{
List<T> result = new List<T>();
Dictionary<T, T> hash = new Dictionary<T, T>(values.Length);
for (int i = 0; i < values.Length; i++)
hash.Add(values[i], values[i]);
for (int i = 0; i < range.Length; i++)
{
if (!hash.ContainsKey(range[i]))
result.Add(range[i]);
}
return result.ToArray<T>();
}
}
public class ArrayManipulationTest : MonoBehaviour
{
void Start()
{
int rangeLength = 1000000;
int[] range = Enumerable.Range(0, rangeLength).ToArray();
int[] values = new int[rangeLength / 5];
int[] missing;
float start;
float duration;
for (int i = 0; i < rangeLength / 5; i ++)
values[i] = i * 5;
start = Time.realtimeSinceStartup;
missing = ArrayExtension.FindMissing1<int>(range, values);
duration = Time.realtimeSinceStartup - start;
Debug.Log($"FindMissing1 Total time: {duration:0.0000}");
start = Time.realtimeSinceStartup;
missing = ArrayExtension.FindMissing2<int>(range, values);
duration = Time.realtimeSinceStartup - start;
Debug.Log($"FindMissing2 Total time: {duration:0.0000}");
}
}
List<int> selectedNumbers = new List<int>(){8, 5, 3, 12, 2};
int firstNumber = selectedNumbers.OrderBy(i => i).First();
int lastNumber = selectedNumbers.OrderBy(i => i).Last();
List<int> allNumbers = Enumerable.Range(firstNumber, lastNumber - firstNumber + 1).ToList();
List<int> missingNumbers = allNumbers.Except(selectedNumbers).ToList();
foreach (int i in missingNumbers)
{
Response.Write(i);
}
LINQ's Except method would be the most readable. Whether it performs adequately for you or not would be a matter for testing.
E.g.
range.Except(listOfValues);
Edit
Here's the program I used for my mini-benchmark, for others to plug away with:
static void Main()
{
var a = Enumerable.Range(0, 1000000);
var b = new List<int>();
for (int i = 0; i < 1000000; i += 10)
{
b.Add(i);
}
Stopwatch sw = new Stopwatch();
sw.Start();
var c = a.Except(b).ToList();
sw.Stop();
Console.WriteLine("Milliseconds {0}", sw.ElapsedMilliseconds );
sw.Reset();
Console.ReadLine();
}
An alternative method which works in general for any two IEnunumerable<T> where T :IComparable. If the IEnumerables are both sorted, this works in O(1) memory (i.e. there is no creating another ICollection and subtracting, etc.) and in O(n) time.
The use of IEnumerable<IComparable> and GetEnumerator makes this a little less readable, but far more general.
Implementation
/// <summary>
/// <para>For two sorted IEnumerable<T> (superset and subset),</para>
/// <para>returns the values in superset which are not in subset.</para>
/// </summary>
public static IEnumerable<T> CompareSortedEnumerables<T>(IEnumerable<T> superset, IEnumerable<T> subset)
where T : IComparable
{
IEnumerator<T> supersetEnumerator = superset.GetEnumerator();
IEnumerator<T> subsetEnumerator = subset.GetEnumerator();
bool itemsRemainingInSubset = subsetEnumerator.MoveNext();
// handle the case when the first item in subset is less than the first item in superset
T firstInSuperset = superset.First();
while ( itemsRemainingInSubset && supersetEnumerator.Current.CompareTo(subsetEnumerator.Current) >= 0 )
itemsRemainingInSubset = subsetEnumerator.MoveNext();
while ( supersetEnumerator.MoveNext() )
{
int comparison = supersetEnumerator.Current.CompareTo(subsetEnumerator.Current);
if ( !itemsRemainingInSubset || comparison < 0 )
{
yield return supersetEnumerator.Current;
}
else if ( comparison >= 0 )
{
while ( itemsRemainingInSubset && supersetEnumerator.Current.CompareTo(subsetEnumerator.Current) >= 0 )
itemsRemainingInSubset = subsetEnumerator.MoveNext();
}
}
}
Usage
var values = Enumerable.Range(0, 11);
var list = new List<int> { 1, 2, 4, 7, 9 };
var notIncluded = CompareSortedEnumerables(values, list);
If the range is predictable I suggest the following solution:
public static void Main()
{
//set up the expected range
var expectedRange = Enumerable.Range(0, 10);
//set up the current list
var currentList = new List<int> {1, 2, 4, 7, 9};
//get the missing items
var missingItems = expectedRange.Except(currentList);
//print the missing items
foreach (int missingItem in missingItems)
{
Console.WriteLine(missingItem);
}
Console.ReadLine();
}
Regards,
y00daa
This does not use LINQ but it works in linear time.
I assume that input list is sorted.
This takes O(list.Count).
private static IEnumerable<int> get_miss(List<int> list,int length)
{
var miss = new List<int>();
int i =0;
for ( i = 0; i < list.Count - 1; i++)
{
foreach (var item in
Enumerable.Range(list[i] + 1, list[i + 1] - list[i] - 1))
{
yield return item;
}
}
foreach (var item in Enumerable.Range(list[i]+1,length-list[i]))
{
yield return item;
}
}
This should take O(n) where n is length of full range.
static void Main()
{
List<int> identifiers = new List<int>() { 1, 2, 4, 7, 9 };
Stopwatch sw = new Stopwatch();
sw.Start();
List<int> miss = GetMiss(identifiers,150000);
sw.Stop();
Console.WriteLine("{0}",sw.ElapsedMilliseconds);
}
private static List<int> GetMiss(List<int> identifiers,int length)
{
List<int> miss = new List<int>();
int j = 0;
for (int i = 0; i < length; i++)
{
if (i < identifiers[j])
miss.Add(i);
else if (i == identifiers[j])
j++;
if (j == identifiers.Count)
{
miss.AddRange(Enumerable.Range(i + 1, length - i));
break;
}
}
return miss;
}
Ok, really, create a new list which parallels the initial list and run the method Except over it...
I have created a fully linq answer using the Aggregate method instead to find the missings:
var list = new List<int>(new[] { 1, 2, 4, 7, 9 }); // Assumes list is ordered at this point
list.Insert(0, 0); // No error checking, just put in the lowest and highest possibles.
list.Add(10); // For real world processing, put in check and if not represented then add it/them.
var missing = new List<int>(); // Hold any missing values found.
list.Aggregate ((seed, aggr) => // Seed is the previous #, aggr is the current number.
{
var diff = (aggr - seed) -1; // A difference between them indicates missing.
if (diff > 0) // Missing found...put in the missing range.
missing.AddRange(Enumerable.Range((aggr - diff), diff));
return aggr;
});
The missing list has this after the above code has been executed:
3, 5, 6, 8
for a List L a general solution (works in all programming languages) would be simply
L.Count()*(L.Count()+1)/2 - L.Sum();
which returns the expected sum of series minus the actual series.
for a List of size n the missing number is:
n(n+1)/2 - (sum of list numbers)
this method here returns the number of missing elements ,sort the set , add all elements from range 0 to range max , then remove the original elements , then you will have the missing set
int makeArrayConsecutive(int[] statues)
{
Array.Sort(statues);
HashSet<int> set = new HashSet<int>();
for(int i = statues[0]; i< statues[statues.Length -1]; i++)
{
set.Add(i);
}
for (int i = 0; i < statues.Length; i++)
{
set.Remove(statues[i]);
}
var x = set.Count;
return x;
// return set ; // use this if you need the actual elements + change the method return type
}
Create an array of num items
const int numItems = 1000;
bool found[numItems] = new bool[numItems];
List<int> list;
PopulateList(list);
list.ForEach( i => found[i] = true );
// now iterate found for the numbers found
for(int count = 0; i < numItems; ++numItems){
Console.WriteList("Item {0} is {1}", count, found[count] ? "there" : "not there");
}
This method does not use LINQ and works in general for any two IEnunumerable<T> where T :IComparable
public static IEnumerable<T> FindMissing<T>(IEnumerable<T> superset, IEnumerable<T> subset) where T : IComparable
{
bool include = true;
foreach (var i in superset)
{
foreach (var j in subset)
{
include = i.CompareTo(j) == 0;
if (include)
break;
}
if (!include)
yield return i;
}
}
int sum = 0,missingNumber;
int[] arr = { 1,2,3,4,5,6,7,8,9};
for (int i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
Console.WriteLine("The sum from 1 to 10 is 55");
Console.WriteLine("Sum is :" +sum);
missingNumber = 55 - sum;
Console.WriteLine("Missing Number is :-"+missingNumber);
Console.ReadLine();

Categories