C# Multiplication Table logic - c#

I'm making a c# program that shows the multiplication table, by using my code I can print only complete table, how can I print random table as below.
my code bit:
using System;
public class Exer
{
public static void Main()
{
int j,n;
Console.Write("\n\n");
Console.Write("Display the multiplication table:\n");
Console.Write("-----------------------------------");
Console.Write("\n\n");
Console.Write("Input the number (Table to be calculated) : ");
n= Convert.ToInt32(Console.ReadLine());
Console.Write("\n");
for(j=1;j<=10;j++)
{
Console.Write("{0} X {1} = {2} \n",n,j,n*j);
}
}
}
Expected Output:
1 x 2 = 2
2 x 2 = 4
3 x 2 = 6
1 x 4 = 4
2 x 4 = 8
3 x 4 = 12
1 x 6 = 6
2 x 6 = 12
3 x 6 = 18
1 x 8 = 8
2 x 8 = 16
3 x 8 = 24
1 x 10 = 10
2 x 10 = 20
3 x 10 = 30

The tables in your picture are NOT random, though. There is a definite pattern. The function, DisplayMath(), is receiving an integer parameter; 3, 4, and 5 in the picture.
The output in the pictures is most likely produced by two NESTED for loops.
The integer parameter is controlling the INNER for loop, which goes from 1 to the parameter, incrementing by 1.
The OUTER loop goes from 2 to 10, incrementing by 2.
Possible code:
public static void Main() {
DisplayMath(4);
}
public static void DisplayMath(int x) {
for(int y=2; y<=10; y=y+2) {
for(int z=1; z<=x; z++) {
Console.WriteLine("{0} X {1} = {2}",z,y,z*y);
}
}
}
Output:
1 X 2 = 2
2 X 2 = 4
3 X 2 = 6
4 X 2 = 8
1 X 4 = 4
2 X 4 = 8
3 X 4 = 12
4 X 4 = 16
1 X 6 = 6
2 X 6 = 12
3 X 6 = 18
4 X 6 = 24
1 X 8 = 8
2 X 8 = 16
3 X 8 = 24
4 X 8 = 32
1 X 10 = 10
2 X 10 = 20
3 X 10 = 30
4 X 10 = 40

As per the required output, you need to change the for loop logic a little.
Because there is a logic in the expected result that you need to get before start coding, that isn't a 'random' table
for(j=2; j<=10; j=j+2 )
{
for (mathNumber = 1; mathNumber <= n; mathNumber++ )
{
Console.Write("{0} X {1} = {2} \n",mathNumber,j,mathNumber*j);
}
}
As you can see the result must be the result of the n first numbers (being n the parameter you get from Console, but perhaps is better that you get it as argument) multiplyed by the numbers 2,4,6,8,10

Related

Google OR-Tools: Employee Scheduling | Minimze the deviation between how many hours an employee is assigned and how many hours he is supposed to work

I am new to or-tools and I am trying to implement something similar to the employee scheduling example from here.
I have a matrix that represents which employee is assigned to which shift:
IntVar[,] assign = new IntVar[numEmployees, numShifts];
An employee has a number of hours he is supposed to work per week and a shift has an individual duration. These numbers are stored in two separate arrays.
How would I create an objective function to minimize the deviation between the sum of the assigned shifts' durations and the employee's hours per week, so that each employee comes as close to his goal as possible?
Thanks in advance :)
You can compute the total number of hours per employee per week in another set of IntVar's and then compute the square of the difference of them to the target hours per week. The objective would be to minimize the sum of the deviations. (Least squares principle).
Here is an example code of how to do it:
using Google.OrTools.Sat;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace SO69498730_MinimizeDeviation
{
class Program
{
static void Main(string[] args)
{
try
{
Google.OrTools.Sat.CpModel model = new CpModel();
ORModel myModel = new ORModel();
myModel.initModel(model);
IntVar[] decisionVariables = myModel.decisionVariables;
// Creates a solver and solves the model.
CpSolver solver = new CpSolver();
VarArraySolutionPrinter solutionPrinter = new VarArraySolutionPrinter(myModel.variablesToPrintOut);
solver.SearchAllSolutions(model, solutionPrinter);
Console.WriteLine(String.Format("Number of solutions found: {0}",
solutionPrinter.SolutionCount()));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
throw;
}
Console.WriteLine("OK");
Console.ReadKey();
}
}
class ORModel
{
const int numEmployees = 3;
const int numShifts = 21;
long[] hoursPerShift = new long[numShifts] { 9, 8, 7, 9, 8, 7, 9, 8, 7, 9, 8, 7, 9, 8, 7, 9, 8, 7, 9, 8, 7 };
long[] targetWeeklyHours = new long[numEmployees] { 40, 40, 24 };
const long totalShiftsNeeded = 15;
IntVar[,] assign = new IntVar[numEmployees, numShifts];
IntVar[] hoursPerWeek = new IntVar[numEmployees];
IntVar[] diff = new IntVar[numEmployees];
IntVar[] deviation = new IntVar[numEmployees];
IntVar objective;
public IntVar[] decisionVariables
{
get
{
return assign.Cast<IntVar>().ToArray();
}
}
public IntVar[] variablesToPrintOut
{
get
{
List<IntVar> vars = new List<IntVar>(assign.Cast<IntVar>());
vars.AddRange(hoursPerWeek);
vars.AddRange(diff);
vars.AddRange(deviation);
vars.Add(objective);
return vars.ToArray();
}
}
public void initModel(CpModel model)
{
// Shifts per employee
for (int i = 0; i < numEmployees; i++)
{
for (int j = 0; j < numShifts; j++)
{
assign[i, j] = model.NewBoolVar($"Employee {i} shift {j}");
}
}
// Total shifts to cover
model.Add(LinearExpr.Sum(assign.Cast<IntVar>()) == totalShiftsNeeded);
// Sum of hours for each employee
long maxHours = hoursPerShift.Max() * numShifts;
for (int i = 0; i < numEmployees; i++)
{
hoursPerWeek[i] = model.NewIntVar(0L, maxHours, $"Hours for employee {i}");
List<LinearExpr> thisEmployeesHours = new List<LinearExpr>();
for (int j = 0; j < numShifts; j++)
{
thisEmployeesHours.Add(hoursPerShift[j] * assign[i, j]);
}
model.Add(LinearExpr.Sum(thisEmployeesHours) == hoursPerWeek[i]);
}
// Deviation = (hours per week for an employee - target hours per week) squared
long maxDev = maxHours * maxHours;
for (int i = 0; i < numEmployees; i++)
{
deviation[i] = model.NewIntVar(0L, maxDev, $"Deviation for employee {i}");
diff[i] = model.NewIntVar(-maxDev, maxDev, $"Diff for employee {i}");
model.Add(diff[i] == hoursPerWeek[i] - targetWeeklyHours[i]);
IntVar[] multiplicands = new IntVar[] { diff[i], diff[i] };
model.AddMultiplicationEquality(deviation[i], multiplicands);
}
// Objective: minimize sum of deviations
objective = model.NewIntVar(0L, numEmployees * maxDev, "Objective");
model.Add(LinearExpr.Sum(deviation) == objective);
model.Minimize(objective);
}
}
public class VarArraySolutionPrinter : CpSolverSolutionCallback
{
private int solution_count_;
private IntVar[] variables;
public VarArraySolutionPrinter(IntVar[] variables)
{
this.variables = variables;
}
public override void OnSolutionCallback()
{
using (TextWriter sw = Console.Out)
{
sw.WriteLine(String.Format("Solution #{0}: time = {1:F2} s;",
solution_count_, WallTime()));
foreach (IntVar v in variables)
{
sw.Write(
String.Format(" {0} = {1}\r\n", v.ShortString(), Value(v)));
}
solution_count_++;
sw.WriteLine();
}
if (solution_count_ >= 10)
{
StopSearch();
}
}
public int SolutionCount()
{
return solution_count_;
}
}
}
If all the shifts have the same length, and you only need to ensure each employee has roughly the same number of shifts, then you could eliminate the deviation variable and simply minimize the sum of the squares of the number of shifts for each employee.
Here is a sample output of the above; the solver found 9 solutions with continually decreasing objective, the last one reported was:
...
Solution #8: time = 0,62 s;
Employee 0 shift 0 = 0
Employee 0 shift 1 = 0
Employee 0 shift 2 = 1
Employee 0 shift 3 = 0
Employee 0 shift 4 = 0
Employee 0 shift 5 = 1
Employee 0 shift 6 = 0
Employee 0 shift 7 = 0
Employee 0 shift 8 = 1
Employee 0 shift 9 = 0
Employee 0 shift 10 = 0
Employee 0 shift 11 = 1
Employee 0 shift 12 = 0
Employee 0 shift 13 = 0
Employee 0 shift 14 = 0
Employee 0 shift 15 = 0
Employee 0 shift 16 = 0
Employee 0 shift 17 = 1
Employee 0 shift 18 = 0
Employee 0 shift 19 = 0
Employee 0 shift 20 = 1
Employee 1 shift 0 = 0
Employee 1 shift 1 = 0
Employee 1 shift 2 = 1
Employee 1 shift 3 = 0
Employee 1 shift 4 = 0
Employee 1 shift 5 = 1
Employee 1 shift 6 = 0
Employee 1 shift 7 = 0
Employee 1 shift 8 = 0
Employee 1 shift 9 = 0
Employee 1 shift 10 = 0
Employee 1 shift 11 = 1
Employee 1 shift 12 = 0
Employee 1 shift 13 = 0
Employee 1 shift 14 = 1
Employee 1 shift 15 = 0
Employee 1 shift 16 = 0
Employee 1 shift 17 = 1
Employee 1 shift 18 = 0
Employee 1 shift 19 = 0
Employee 1 shift 20 = 1
Employee 2 shift 0 = 0
Employee 2 shift 1 = 1
Employee 2 shift 2 = 0
Employee 2 shift 3 = 0
Employee 2 shift 4 = 1
Employee 2 shift 5 = 0
Employee 2 shift 6 = 0
Employee 2 shift 7 = 0
Employee 2 shift 8 = 0
Employee 2 shift 9 = 0
Employee 2 shift 10 = 0
Employee 2 shift 11 = 0
Employee 2 shift 12 = 0
Employee 2 shift 13 = 0
Employee 2 shift 14 = 0
Employee 2 shift 15 = 0
Employee 2 shift 16 = 0
Employee 2 shift 17 = 0
Employee 2 shift 18 = 0
Employee 2 shift 19 = 1
Employee 2 shift 20 = 0
Hours for employee 0 = 42
Hours for employee 1 = 42
Hours for employee 2 = 24
Diff for employee 0 = 2
Diff for employee 1 = 2
Diff for employee 2 = 0
Deviation for employee 0 = 4
Deviation for employee 1 = 4
Deviation for employee 2 = 0
Objective = 8
Number of solutions found: 9
OK
You'll have to add any other constraints you need such as each shift being covered only once, etc.
Edit: After posting, I realized there are some issues with AddMultiplicationEquality when the operands span positive and negative values, which is the case here (deviations to target working week can be both positive and negative). During some testing the model here indicated infeasibility where there were obvious solutions.
By changing the objective to "Minimize the maximum absolute value of the deviations" instead of "Minimize the sum of the squares of the deviations" this problem can be avoided. This would then be the required code section to compute the objective:
// Deviation = Abs(hours per week for an employee - target hours per week)
for (int i = 0; i < numEmployees; i++)
{
deviation[i] = model.NewIntVar(0, maxHours, $"Absolute deviation for employee {i}");
diff[i] = model.NewIntVar(-maxHours, maxHours, $"Deviation for employee {i}");
model.Add(diff[i] == hoursPerWeek[i] - targetWeeklyHours[i]);
IntVar minusDiff = model.NewIntVar(-maxHours, maxHours, $"-Deviation for employee {i}");
model.Add(minusDiff == -diff[i]);
IntVar[] operands = new IntVar[] { diff[i], minusDiff };
model.AddMaxEquality(deviation[i], operands);
}
// Objective: minimize the maximum deviation
objective = model.NewIntVar(0L, numEmployees * maxHours, "Objective");
model.AddMaxEquality(objective, deviation);
model.Minimize(objective);

C# store and display calculated iteration in one line using messagebox.show

I am working on this program. My purpose is to Store the result of calculated input data in one int[] variable and display it in one line using messagebox.show.
int[] data = new int[] { 65, 66, 67, 32, 100, 90 }; // I declare int[] data it contain my data that I want to work with the length change.
int[] array = new int[6]; // i declare a table length of 6
foreach (var b in data) // for every element in my data I want to do this operations and build my array.
{
array[0] = b / 200;
array[1] = b / 79;
array[2] = b / 27;
array[3] = b / 19;
array[4] = b / 21;
array[5] = b / 3;
Console.WriteLine("{0}", string.Join(" ", array)); // this line is for console application
// output of this line is :
/*
0 0 2 3 3 21
0 0 2 3 3 22
0 0 2 3 3 22
0 0 1 1 1 10
0 1 3 5 4 33
0 1 3 4 4 30 */
MessageBox.Show(" "+ string.Join(" ", array)); // this line is for windowsform application
My purpose is in windowsform application to display my variable using messagebox.show. I aim the calculated to store them in one variable and to display them like this one :
0 0 2 3 3 21 0 0 2 3 3 22 0 0 2 3 3 22 0 0 1 1 1 10 0 1 3 5 4 33 0 1 3 4 4 30
I really appreciate any help.
kind regards
You can simply join the string in loop and then display them outside of the loop in your message box. Use StringBuilder class for appending results.
StringBuilder sb = new StringBuilder();
for(...)
{
...
...
sb.AppendFormat("{0} ", string.Join(" ", array).Trim())
}
MessageBox.Show(sb.ToString());

c# Hackerrank code terminated due to time out but there is no way to optimize this code further?

I was doing a hacker rank challenge in c# to try and bring some of my c skills over to c#. Now I know hacker rank is notoriously stupid with killing programs due to time out (in this case if it lasts more than 3 seconds). But I honestly cannot think of a way to optimize this code further.
Here are the instructions:
https://www.hackerrank.com/challenges/ctci-array-left-rotation
Basically the challenge is to shift an array of numbers some x amount of times over in the left direction inside the array.
To my knowledge this code is as minimal as it can get and still do the thing they requested. The only way I can think to optimize this code further is to merge the constraint "if(a[i] > 1000000 || a[i] < 1 )" with the writeline forloop at the end of the code, but I tried that and it didn't work.
To me this is literally the minimum number of operations to move the array over by an amount x. But the code fails in test case 7 and 8 (out of 8) due to time out. Am I missing something?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
int i, j;
int temp = 0;
string[] tokens_n = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(tokens_n[0]);
int k = Convert.ToInt32(tokens_n[1]);
string[] a_temp = Console.ReadLine().Split(' ');
int[] a = Array.ConvertAll(a_temp,Int32.Parse);
//constraints
if(n >= 100000 || n < 1 )
{
System.Environment.Exit(1);
}
if(k > n || n < 1 )
{
System.Environment.Exit(1);
}
for(i = 0; i< n; i++)
{
if(a[i] > 1000000 || a[i] < 1 )
{
System.Environment.Exit(1);
}
}
//double for loop. one adjust position by one. then repeat k number of times.
for(j = 0; j<k; j++)
{
for(i = 0; i< n-1; i++)
{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
}
//view array
for(i = 0; i< n; i++)
{
Console.Write(a[i] + " " );
}
}
}
I used a queue mechanism to get this working. That way you don't have to do any array copy and just rotating the string to the end.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
static int[] leftRotation(int[] arr, int rotation) {
Queue<int> queue = new Queue<int>(arr);
for (int i = 0; i < rotation; i++)
{
queue.Enqueue(queue.Dequeue());
}
return queue.ToArray();
}
static void Main(String[] args) {
string[] tokens_n = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(tokens_n[0]);
int d = Convert.ToInt32(tokens_n[1]);
string[] a_temp = Console.ReadLine().Split(' ');
int[] a = Array.ConvertAll(a_temp,Int32.Parse);
int[] result = leftRotation(a, d);
Console.WriteLine(String.Join(" ", result));
}
}
Shuffling the values one at a time is very slow. There is no need to do this. One can think of the rotation as moving 2 blocks - the values to the left of the rotation point and the values including and to the right of the rotation point
1 2 3 4 5 6 7 8 9
Rotate this 3 times is
move 1-3 to a temp variable
move 4-9 to the start of the array
move 1-3 to the end of 4-9
Edit: Add a bit more detail
We want to rotate the array 3 places.
move 1 2 3 to a temporary array
1 2 3
1 2 3 4 5 6 7 8 9
move 4-9 to the start of the array
1 2 3
4 5 6 7 8 9 7 8 9
move 1-3 to the end of the array
1 2 3
4 5 6 7 8 9 1 2 3
We can get away without the temp array for the left hand block if we create a new target array and copy everything to it. The following passes all the tests for the problem
var result = new int[a.Length];
var block2Length = a.Length - k;
Array.Copy(a, k, result, 0, block2Length);
Array.Copy(a, 0, result, block2Length, k);
Console.WriteLine(string.Join(" ", result.Select(v => v.ToString())));
Other Points
The constraints in HackerRank are part of the problem definition - they are telling us what the values can/will do so that we don't have to worry about solving a more general problem
e.g.
1 <= a[i] < 10^6
tells us the numbers will all be within the range for standard integers, no need to use long or BigInteger. As part of the solution we don't need to confirm these. In a real world situation different rules apply but here we have as much code checking values that cannot be wrong as we have solving the problem.
This has already been answered but there is a different solution that is very fast:
The idea is that you use the periodicity of the shifting. Shifting an element n+1 times is the same as shifting it 1 time which boils down to k % n.
Thus, you can simply create a new array and move the "old" elements directly to the correct spot. See the sample code below:
static void Main(String[] args) {
string[] tokens_n = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(tokens_n[0]);
int k = Convert.ToInt32(tokens_n[1]);
string[] a_temp = Console.ReadLine().Split(' ');
int[] a = Array.ConvertAll(a_temp,Int32.Parse);
// use the periodicity of the shifting creating a shift between 0 and n - 1.
int shifts = k % n;
// Create a new array to hold the elements at their new positions.
int[] newPositions = new int[a.Length];
// You only need to iterate of the array once assigning each element its new position.
for(int i= 0; i < a.Length; ++i)
{
// Here is the magic: (for clarification see table below)
int position = (i - shifts + n)%n;
newPositions[position] = a[i];
}
foreach(var element in newPositions)
Console.Write($"{element} ");
}
This is more intuitive once you write it down on paper. The table might prints more values than the array contains to show the actual positions in the array.
-4 -3 -2 -1 | 0 1 2 3 4 (array indices)
=============================
2 3 4 5 | 1 2 3 4 5 (array contents without shift)
3 4 5 1 | 2 3 4 5 1 (shifted 1 time)
4 5 1 2 | 3 4 5 1 2 (shifted 2 times)
5 1 2 3 | 4 5 1 2 3 (shifted 3 times)
1 2 3 4 | 5 1 2 3 4 (shifted 4 times)
formula: i - k + n
results:
i=0: 0 - 4 + 5 = 1
i=1: 1 - 4 + 5 = 2
i=2: 2 - 4 + 5 = 3
i=3: 3 - 4 + 5 = 4
i=4: 4 - 4 + 5 = 5
i=5: 5 - 4 + 5 = 6 => 0
EDIT: I skipped the parts to check the boundaries for the sake of simplicity.
Updated answer.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
int i, j, z;
string[] tokens_n = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(tokens_n[0]);
int k = Convert.ToInt32(tokens_n[1]);
string[] a_temp = Console.ReadLine().Split(' ');
int[] a = Array.ConvertAll(a_temp,Int32.Parse);
int[] temparray = new int[2*n];
//constraints
if(n >= 100000 || n < 1 )
{
System.Environment.Exit(1);
}
if(k > n || n < 1 )
{
System.Environment.Exit(1);
}
for(i = 0; i< n; i++)
{
if(a[i] > 1000000 || a[i] < 1 )
{
System.Environment.Exit(1);
}
}
for(j = 0; j<n; j++)
{
z = (j-k) %n;
if(z != 0)
{
z= (n+ z) %n;
}
temparray[z] = a[j];
}
//view array
for(i = 0; i< n; i++)
{
Console.Write(temparray[i] + " " );
}
}
}

Cycle a decimal digit by 1 in c#

I'd like to cycle a decimal digit by 1 using a single operation of possible.
if x is 0 - 8 then x = x + 1
if x is 9 then x = 0
or the opposite
if x is 1 - 9 then x = x - 1
if x is 0 then x = 9
Is there a way to do this with C# in one line of code? If not C# are there any other languages that could?
What if I wanted to cycle it by more than one (2 or 3 or whatever)?
I think what you're looking for is
var y = (x + 1) % 10;
This gives:
x y
------
0 1
1 2
...
8 9
9 0
To decrement
var y = (i + 9) % 10;
Obviously to change the amount, just change 1 or 9 respectively
int Cycle(int x)
{
return x+1 % 10;
}
int result = Cycle(0); // result is 1
int result = Cycle(8); // result is 9
int result = Cycle(9); // result is 0
int Cycle(int x, int by = 1)
{
return (x+by) % 10;
}
now you can call Cycle(9, 3) which should give you 2

Algorithm to represent a sequence of numbers

I have a sequence of numbers to generate, and I want to generate it using some sort of algorithm (iterative or recursive, doesn't matter).
Contextualizing: This numbers are indexes to iterative over a list of lists. I need to do a permutation (combination, i don't know exactly), but I need to generate all combinations of all positions of that list of lists.
The sequence and the output I am trying to get is:
1 1
2 1
3 1
4 1
5 1
1 2
2 1
3 1
4 1
5 1
1 3
2 1
3 1
4 1
5 1
1 4
2 1
3 1
4 1
5 1
1 5
2 1
3 1
4 1
5 1
1 1
2 2
3 1
4 1
5 1
1 2
2 2
3 1
4 1
5 1
1 3
2 2
3 1
4 1
5 1
1 4
2 2
3 1
4 1
5 1
1 5
2 2
3 1
4 1
5 1
1 1
2 3
3 1
4 1
5 1
1 2
2 3
3 1
4 1
5 1
1 3
2 3
3 1
4 1
5 1
1 4
2 3
3 1
4 1
5 1
1 5
2 3
3 1
4 1
5 1
1 1
2 4
3 1
4 1
5 1
and so on... the last state is:
1 5
2 5
3 5
4 5
5 5
Note that at each line break is a step of iteration or recursion. The algorithm must be generic. This code that i wrote can help, but it isn't what I want. :(
List<List<int>> lstDays = new List<List<int>>
{
new List<int>{1,2,3,4,5}, //day 18
new List<int>{1,2,3,4,5}, //day 19
new List<int>{1,2,3,4,5}, //day 22
new List<int>{1,2,3,4,5}, //day 23
new List<int>{1,2,3,4,5}, //day 24
};
for(int i=0;i<lstDays.Count;i++)
{
for(int j=0;j<lstDays[i].Count;j++)
{
for(int k=0;k<lstDays.Count;k++)
{
Console.Write(k+1);
//Console.Write(j+1);
Console.Write('\n');
}
Console.Write('\n');
}
}
I hope that you can help me ! (:
You can do it like this:
int[] second = new[] {0,0,0,0,0};
bool finish = false;
while (true) {
for (int i = 0 ; i != 5 ; i++) {
Console.WriteLine("{0} {1}", i+1, second[i]+1);
}
Console.WriteLine();
int p = 0;
do {
second[p]++;
if (second[p] == 5) {
second[p] = 0;
p++;
} else {
break;
}
} while (p != 5);
if (p == 5) break;
}
The sequence of the second digits is stored in the array "creatively" named second. The do/while loop "increments" this array as if it were a base-5 number stored as five separate digits.
Here is a demo on ideone.
Based on comments below by the venerable Eric Lippert, edits for the OPs original intent:
public void OutputSequence(int length){
Recurse(length-1, Enumerable.Range(1, length).ToArray(), new int[length]);
}
public void Recurse(int position, int[] arr, int[] state){
if (position == -1){
PrintState(state);
return;
}
for (int i = 0; i < arr.Length; i++)
{
state[position] = arr[i];
Recurse(position-1, arr, state);
}
}
public void PrintState(int[] state){
for (int i = 0; i < state.Length; i++)
Console.WriteLine ("{0} {1}",i+1, state[i]);
Console.WriteLine ();
}
OutputSequence(5); will give the output the OP originally asked for.
Old Answer
What you're looking for is called a Cartesian Product. LINQ is your friend:
var pairs = from i in Enumerable.Range(1, 5)
from j in Enumerable.Range(1, 5)
select new {i, j};
foreach(var p in pairs)
Console.WriteLine ("{0} {1}", p.i, p.j);
EDIT: Just for fun, here's a way to do N-Ary cartesian products.
public IEnumerable<IEnumerable<int>> NAryCartesianProduct(int upper, int times){
if (times == 0)
return Enumerable.Empty<IEnumerable<int>>();
var nums = Enumerable.Range(1, upper);
IEnumerable<IEnumerable<int>> products = nums.Select(i => new[]{i});
for (int i = 1; i < times; i++)
{
products = from p in products
from n in nums
select p.Concat(new [] {n});
}
return products;
}
And now you can get what you had before with:
var p = NAryCartesianProduct(5, 2);
foreach(var i in p)
Console.WriteLine (i);
I'm sure there's a more efficient way than creating new arrays all of the time but I just hacked this up quick :)
Here's a much more informative answer on this: Generating all Possible Combinations
EDIT2: Apparently the original link is the origination of the answer from that SO post. I didn't read through to the end until now.

Categories