Creating all possible arrays without nested for loops [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I would like to generate all the possible numbers that have length n and each digit of my number has a value from the set {1,2,...,n-1}, as an array. In other words, I would like to list all the base n numbers with length n that do not include 0.
Right now, the only way I can think to do it is by nesting n for loops, and assigning myArray[i] with the (i+1)th loop, i.e.
int n;
int[] myArray = new int[n];
for (int i1 = 1; i1 < n; i1++)
myArray[0]=i1;
for (int i2 = 1; i2 < n; i2++)
myArray[1]=i2;
// and so on....
for (int in = 1; in < n; in++)
{
myArray[n]=in;
foreach (var item in myArray)
Console.Write(item.ToString());
Console.Write(Environment.NewLine);
}
and then printing each array at the innermost loop. The obvious issue is that for each n, I need to manually write n for loops.
From what I've read, recursion seems to be the best way to replace nested for loops, but I can't seem figure out how to make a general method for recursion either.
EDIT
For example, if n=3, I would like to write out 1 1 1, 1 1 2, 1 2 1, 1 2 2, 2 1 1, 2 1 2, 2 2 1, 2 2 2.
We are not limited to n<11. For example, if n=11, we would output
1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 2
1 1 1 1 1 1 1 1 1 1 3
...
1 1 1 1 1 1 1 1 1 1 10
1 1 1 1 1 1 1 1 1 2 1
1 1 1 1 1 1 1 1 1 2 2
1 1 1 1 1 1 1 1 1 2 3
...
1 1 1 1 1 1 1 1 1 9 10
1 1 1 1 1 1 1 1 1 10 1
1 1 1 1 1 1 1 1 1 10 2
1 1 1 1 1 1 1 1 1 10 3
...
10 10 10 10 10 10 10 10 10 9 10
10 10 10 10 10 10 10 10 10 10 1
10 10 10 10 10 10 10 10 10 10 2
...
10 10 10 10 10 10 10 10 10 10 10
So, a digit of a number may be any value between and including 1 and 10. The array myArray is simply used to get one of these numbers, then we print it, and go on to the next number and repeat.

As always, when thinking in recursive solutions, try to solve the problem using immutable structures; everything is much simpler to understand.
So first of all, lets build ourselves a fast little immutable stack that will help us keep track of the number we are currently generating (while not worrying about what other numbers are being generated in the recursive call...remember, immutable data can't change!):
public class ImmutableStack<T>: IEnumerable<T>
{
public static readonly ImmutableStack<T> Empty = new ImmutableStack<T>();
private readonly T first;
private readonly ImmutableStack<T> rest;
public int Count { get; }
private ImmutableStack()
{
Count = 0;
}
private ImmutableStack(T first, ImmutableStack<T> rest)
{
Debug.Assert(rest != null);
this.first = first;
this.rest = rest;
Count = rest.Count + 1;
}
public IEnumerator<T> GetEnumerator()
{
var current = this;
while (current != Empty)
{
yield return current.first;
current = current.rest;
}
}
public T Peek()
{
if (this == Empty)
throw new InvalidOperationException("Can not peek an empty stack.");
return first;
}
public ImmutableStack<T> Pop()
{
if (this == Empty)
throw new InvalidOperationException("Can not pop an empty stack.");
return rest;
}
public ImmutableStack<T> Push(T item) => new ImmutableStack<T>(item, this);
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
That's easy. Note how the stack reuses data. How many empty immutable structs will there be in our little program? Only one. And stacks containing the sequence 1->2->4? Yup, only one.
Now, we implement a recursive function that just keeps adding numbers to the stack until we reach our "bail out" condition. Which is? When the stack contains n elements. Easy peasy:
private static IEnumerable<int> generateNumbers(ImmutableStack<string> digits, IEnumerable<string> set, int length)
{
if (digits.Count == length)
{
yield return int.Parse(string.Concat(digits));
}
else
{
foreach (var digit in set)
{
var newDigits = digits.Push(digit);
foreach (var newNumber in generateNumbers(newDigits, set, length))
{
yield return newNumber;
}
}
}
}
Ok, and now we just need to tie it alltogether with our public method:
public static IEnumerable<int> GenerateNumbers(int length)
{
if (length < 1)
throw new ArgumentOutOfRangeException(nameof(length));
return generateNumbers(ImmutableStack<string>.Empty,
Enumerable.Range(1, length - 1).Select(d => d.ToString(CultureInfo.InvariantCulture)),
length);
}
And sure enough, if we call this thing:
var ns = GenerateNumbers(3);
Console.WriteLine(string.Join(Environment.NewLine,
ns.Select((n, index) => $"[{index + 1}]\t: {n}")));
We get the expected output:
[1] : 111
[2] : 211
[3] : 121
[4] : 221
[5] : 112
[6] : 212
[7] : 122
[8] : 222
Do note that the total amount of numbers generated of a specified length n is (n - 1) ^ n which means that for relatively small values of length you are going to get quite an amount of numbers generated; n = 10 generates 3 486 784 401...

Related

Lookup from a 3-column table and interpolate one of the columns?

I have a table with 3 columns: Temperature, Pressure, and Gain.
interface IEntry
{
public float Temperature {get;}
public int Pressure {get;}
public float Gain {get;}
}
Given a certain "input" pair (Temperature_input, Pressure_input), I would like to match this pair with the ones in the table and lookup the corresponding gains, interpolating in certain cases.
Example:
T P G
3 1 0
3 2 1
3 3 2
3 5 4
6 1 0
6 2 2
6 3 3
8 1 0
8 2 3
9 1 0
Input pair (T = 4, P = 2):
Step 1: As the exact temperature T = 4 is not in the table, the immediate lower and upper temperatures 3 and 6 are examined (8 table entries)
Step 2: The pairs for T = 3, T = 6 are sorted by Pressure (which is an int)
3 1 0
6 1 0
3 2 1
6 2 2
3 3 2
6 3 3
3 5 4
3 5 4
Step 3: Linear interpolation between temperatures of the same pressure:
3 2 1
6 2 2
Result is the interpolated Gain = 1 + (2-1)/(6-3) = 1.33
What is an efficient way of implementing the lookup part of the table, that will be accessed millions of times?

True pixel quantity

I know that my question will be a littel strange but i need realy some help. I have an algorithme to calculate true pixel quantity in a binary image. Her is an example how it work:
Binary Image :
0 0 1 0 0 1
1 1 1 1 0 1
1 1 1 1 1 1
1 1 0 0 0 1
0 1 0 0 0 1
Her is the result :
18 15 11 8 6 5
16 13 9 7 5 4
11 9 6 5 4 3
5 4 2 2 2 2
2 2 1 1 1 1
And this is how it work :
Result (i,j) = result (i+1, j) + result (i, j+1) - result(i + 1, j + 1) + Image(i,j)
Her an example for the 18 value:
18 = 16 + 15 - 13 + 0
My question :
What is the name of this algorithm because I need to get some more information about it?
Thank you for help.
This is called an integral image, or summed area table. It is used to speedup box filtering, among others. It is a 2D generalization of a prefix sum.

Choose one element from each row and column in matrix and the sum is minimized

If you have a NxN matrix of positive integers, and you are asked to select exactly one element from each row and column, so that the sum of the selected elements is minimized, how can it be solved?
I think it is about Dynamic Programming. I have tried to minimize the time O(n!) using memoization:
Dictionary<byte[,], int>[] memo = new Dictionary<byte[,], int>[17];
int rec(byte[,] arr)
{
if (arr.Length == 1) return arr[0, 0];
int opt = find(arr);
if (opt != -1) return opt;
opt = 1 << 25;
for (int i = 0; i < arr.GetLength(1); ++i)
opt = Math.Min(opt, arr[0, i] + rec(divide(arr, i)));
add(arr, opt);
return opt;
}
This chooses an element from row 0 of the current matrix and then divides the matrix and calls itself recursively to solve the submatrix. Function divide divides the current matrix according to the selected element. The sub-matrix size is then (N-1)x(N-1). Function find performs linear search in memo[n], and add adds the solution to memo[n] But this is too slow as it will compare each matrix with other.
Do you have some inhancements? Is there a faster DP algorithm? Any help is appreciated
EXAMPLE
1 2 3 4
8 7 6 5
9 11 10 12
13 14 16 15
The optimal solution: 1 + 5 + 10 + 14
Steps:
7 6 5
11 10 12
14 16 15
11 10
14 16
14
This is actually the assignment problem. It can be solved in polynomial time using the Hungarian algorithm, among other methods.

Generate N random and unique numbers within a range

What is an efficient way of generating N unique numbers within a given range using C#? For example, generate 6 unique numbers between 1 and 50. A lazy way would be to simply use Random.Next() in a loop and store that number in an array/list, then repeat and check if it already exists or not etc.. Is there a better way to generate a group of random, but unique, numbers?
To add more context, I would like to select N random items from a collection, using their index.
thanks
Take an array of 50 elements: {1, 2, 3, .... 50}
Shuffle the array using any of the standard algorithms of randomly shuffling arrays. The first six elements of the modified array is what you are looking for. HTH
For 6-from-50, I'm not too sure I'd worry about efficiency since the chance of a duplicate is relatively low (30% overall, from my back-of-the-envelope calculations). You could quite easily just remember the previous numbers you'd generated and throw them away, something like (pseudo-code):
n[0] = rnd(50)
for each i in 1..5:
n[i] = n[0]
while n[1] == n[0]:
n[1] = rnd(50)
while n[2] == any of (n[0], n[1]):
n[2] = rnd(50)
while n[3] == any of (n[0], n[1], n[2]):
n[3] = rnd(50)
while n[4] == any of (n[0], n[1], n[2], n[3]):
n[4] = rnd(50)
while n[5] == any of (n[0], n[1], n[2], n[3], n[4]):
n[5] = rnd(50)
However, this will break down as you move from 6-from-50 to 48-from-50, or 6-from-6, since the duplicates start getting far more probable. That's because the pool of available numbers gets smaller and you end up throwing away more and more.
For a very efficient solution that gives you a subset of your values with zero possibility of duplicates (and no unnecessary up-front sorting), Fisher-Yates is the way to go.
dim n[50] // gives n[0] through n[9]
for each i in 0..49:
n[i] = i // initialise them to their indexes
nsize = 50 // starting pool size
do 6 times:
i = rnd(nsize) // give a number between 0 and nsize-1
print n[i]
nsize = nsize - 1 // these two lines effectively remove the used number
n[i] = n[nsize]
By simply selecting a random number from the pool, replacing it with the top number from that pool, then reducing the size of the pool, you get a shuffle without having to worry about a large number of swaps up front.
This is important if the number is high in that it doesn't introduce an unnecessary startup delay.
For example, examine the following bench-check, choosing 10-from-10:
<------ n[] ------>
0 1 2 3 4 5 6 7 8 9 nsize rnd(nsize) output
------------------- ----- ---------- ------
0 1 2 3 4 5 6 7 8 9 10 4 4
0 1 2 3 9 5 6 7 8 9 7 7
0 1 2 3 9 5 6 8 8 2 2
0 1 8 3 9 5 6 7 6 6
0 1 8 3 9 5 6 0 0
5 1 8 3 9 5 2 8
5 1 9 3 4 1 1
5 3 9 3 0 5
9 3 2 1 3
9 1 0 9
You can see the pool reducing as you go and, because you're always replacing the used one with an unused one, you'll never have a repeat.
Using the results returned from that as indexes into your collection will guarantee that no duplicate items will be selected.
var random = new Random();
var intArray = Enumerable.Range(0, 4).OrderBy(t => random.Next()).ToArray();
This array will contain 5 random numbers from 0 to 4.
or
var intArray = Enumerable.Range(0, 10).OrderBy(t => random.Next()).Take(5).ToArray();
This array will contain 5 random numbers between 0 to 10.
int firstNumber = intArray[0];
int secondNumber = intArray[1];
int thirdNumber = intArray[2];
int fourthNumber = intArray[3];
int fifthNumber = intArray[4];
For large sets of unique numbers, put them in an List..
Random random = new Random();
List<int> uniqueInts = new List<int>(10000);
List<int> ranInts = new List<int>(500);
for (int i = 1; i < 10000; i++) { uniqueInts.Add(i); }
for (int i = 1; i < 500; i++)
{
int index = random.Next(uniqueInts.Count) + 1;
ranInts.Add(uniqueInts[index]);
uniqueInts.RemoveAt(index);
}
Then randomly generate a number from 1 to myInts.Count. Store the myInt value and remove it from the List. No need to shuffle the list nor look to see if the value already exists.
instead of using List use Dictionary!!
In case it helps anyone else, I prefer allocating the minimum number of items necessary. Below, I make use of a HashSet, which ensures that new items are unique. This should work with very large collections as well, up to the limits of what HashSet plays nice with.
public static IEnumerable<int> GetRandomNumbers(int numValues, int maxVal)
{
var rand = new Random();
var yieldedValues = new HashSet<int>();
int counter = 0;
while (counter < numValues)
{
var r = rand.Next(maxVal);
if (yieldedValues.Add(r))
{
counter++;
yield return r;
}
}
}
generate unique random nos from 1 to 40 :
output confirmed :
class Program
{
static int[] a = new int[40];
static Random r = new Random();
static bool b;
static void Main(string[] args)
{
int t;
for (int i = 0; i < 20; i++)
{
lab: t = r.Next(1, 40);
for(int j=0;j<20;j++)
{
if (a[j] == t)
{
goto lab;
}
}
a[i] = t;
Console.WriteLine(a[i]);
}
Console.Read();
}
}
sample output :
7
38
14
18
13
29
28
26
22
8
24
19
35
39
33
32
20
2
15
37

Paging through an IEnumerable

I have an IEnumerable object (IEnumerable<Class>) and I would like to retrieve a specified line from the object. So if I'm on page two I would like to select row two from the IEnumerable object and then pass it on to another class etc.
I'm a bit stuck at the moment, any ideas?
Look at the functions .Take() and .Skip(). I normally do something like this:
IEnumerable<object> GetPage(IEnumerable<object> input, int page, int pagesize)
{
return input.Skip(page*pagesize).Take(pagesize);
}
If I understand your requirements correctly, something like this paging mechanism should work:
int pageSize = 10;
int pageCount = 2;
iEnumerable.Skip(pageSize*pageCount).Take(pageSize);
This example shows 10 rows per page and a page number of 2. So, it will skip to page 2 and take the first row on that page.
Assuming that pages and rows start at 1, and there is a fixed number of rows per page (say 10), you need to transform the page number and the row to an index as follows:
Page 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 ...
Row 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 ...
↓
Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 ...
Code:
int page = 2;
int row = 2;
int rowsPerPage = 10;
IEnumerable<MyClass> source = ...
MyClass result = source.ElementAt((page - 1) * rowsPerPage + (row - 1));
So to get row 2 on page 2, you need to skip the first page (10 elements) and then take the second element (index 1 in that page).
I've implemented a dynamic solution in vb.net, i hope helpful:
<Runtime.CompilerServices.Extension()>
Public Function Paginate(Of T As {Class})(source As T, skip As Integer, take As Integer) As T
If source IsNot Nothing AndAlso TypeOf source Is IEnumerable Then
Dim chunk = (From c In DirectCast(source, IEnumerable)).Skip(skip).Take(take).ToList
If chunk.Count = 0 Then Return Nothing
Return AutoMapper.Mapper.Map(chunk, GetType(T), GetType(T))
End If
Return source
End Function

Categories

Resources