A little different multiplication table - c#

I'm struggling to create a multiplication table that would look like this:
1 x 9 + 2 = 11
12 x 9 + 3 = 111
123 x 9 + 4 = 1111
......
123456 x 9 + 8 = 11111111
Currently I managed do to this:
#region MTABLE
for (int i = 2; i <= 8; i++)
{
int number = 1 * 9 + i;
Console.WriteLine("{0} X {1} + {2} = {3} ", 1, 9, i, number);
}
Console.ReadKey();
#endregion
And output that I get now:
1 X 9 + 2 = 11
1 X 9 + 3 = 12
1 X 9 + 4 = 13
1 X 9 + 5 = 14
1 X 9 + 6 = 15
1 X 9 + 7 = 16
1 X 9 + 8 = 17
The problem is that I don't know how to add number to 1 so next will be 12 and than next one 123...
If someone can give me any advice how to continue.

Concatenating a digit to a number can also be performed with multiplying with 10 and adding the digit:
int firstPart = 1;
for (int i = 2; i <= 8; i++)
{
int number = firstPart * 9 + i;
Console.WriteLine("{0} X {1} + {2} = {3} ", firstPart, 9, i, number);
firstPart = firstPart * 10 + i;
}

The first part of your formula (which is now set to 1) should be a variable outside the for loop scope and of type string. Each time you concatenate the i to this and then you do a Int.Parse of the string so you can multiply with it.

Related

c# sum of the sums in the array

Got stuck on quite simple problem in my code. I need to count what I would call a nested sums of an array. Let's take as an example the array:
[1,2,2,3,6]
I want to sum them as:
0 + 1 = 1
1 + 2 = 3
1 + 2 + 2 = 5
1 + 2 + 2 + 3 = 8
1 + 2 + 2 + 3 + 6 = 14
sum = 1 + 3 + 5 + 8 + 14 = 31
Edit:
I tried to do it with stack, but it failed
int sums = 0;
Stack<int> sum = new Stack<int>();
for (int i = 0; i < queries.Length; i++)
{
sum.Push(queries[i]);
}
for (int i = 0; sum.Count != 0; i++)
{
if(i != 0)
{
sums += sum.Pop();
}
}
You can run this task in a single loop considering when you have an array of size 5, the first element is repeating 5 times, second element repeating 4 times and etc.
int[] arr = { 1, 2, 2, 3, 6 };
int mysum = 0;
for (int i = 0; i < arr.Length; i++)
mysum += (arr.Length - i) * arr[i];
Console.WriteLine(mysum);
Output:
31
Explanation:
1 = 1
1 + 2 = 3
1 + 2 + 2 = 5
1 + 2 + 2 + 3 = 8
1 + 2 + 2 + 3 + 6 = 14
========================
5*1 + 4*2 + 3*2 + 2*3 + 1*6 = 31
You can do this much more efficiently and more easily, by multiplying each value by its reversed index + 1
For example, using LINQ
int[] arr = { 1, 2, 2, 3, 6 };
var result = arr.Reverse().Select((val, i) => val * (i + 1)).Sum();
Note that .Reverse on an array (or other Collection<T>) does not actually move any items, it just reads them backwards. So this is therefore an O(n) operation, as opposed to your original solution which is O(n2 / 2)
dotnetfiddle
You can also do this procedurally, this is almost the same as #aminrd's answer.
int[] arr = { 1, 2, 2, 3, 6 };
var result = 0;
for (var i = arr.Length - 1; i >= 0; i--)
result += arr[i] * (i + 1);
Take advantage of Linq! .Sum() will add up everything in your collection. You run that twice, once per each slice, and once per each subtotal.
var input = new [] { 1, 2, 2, 3, 6 };
var totalSum = Enumerable.Range(1, input.Length).Sum(len => input[0..len].Sum());
// totalSum is 31
Enumerable.Range gets you a collection of numbers between (and including) 1 and 5 - the possible lengths of each slice of your sub arrays. You then use the range operator [0..#] to get increasingly larger slices.
Yes, this is not as clever as aminrd's solution - it's doing all the computations manually and you're performing many slices.

Sum combinations that add up to a given natural number

I've been struggling with this pretty tricky problem for the past week :( I have to find all combinations of numbers that sum up to a given natural number using recursion. I'm not allowed to use LINQ or anything else besides "using system"
For example if the input is 7 then the output should look like this:
1 + 1 + 1 + 1 + 1 + 1 + 1
2 + 1 + 1 + 1 + 1 + 1
2 + 2 + 1 + 1 + 1
2 + 2 + 2 + 1
3 + 1 + 1 + 1 + 1
3 + 2 + 1 + 1
3 + 2 + 2
3 + 3 + 1
4 + 1 + 1 + 1
4 + 2 + 1
4 + 3
5 + 1 + 1
5 + 2
6 + 1
The numbers from the combination should be listed exactly in that order so for an input of 3 for example the output should be exactly as follows:
1 + 1 + 1
2 + 1
For an input of 4 the output should look like this:
1 + 1 + 1 + 1
2 + 1 + 1
2 + 2
3 + 1
For every new list of combinations we increment the first number in the list and then we continue with the remaining part of the previous list until the sum will be equal with the input.
Just positive numbers are allowed between 1 (1 included) and input - 1.
My code so far gives me the following output for the same given input of 7:
+ 1
+ 1 + 1 + 2
+ 1 + 1 + 1
+ 2 + 2 + 3
+ 1 + 1 + 1
+ 1 + 1 + 2
+ 2 + 1
+ 1 + 1 + 2
+ 2 + 2 + 1
+ 3 + 3 + 4
+ 1 + 1 + 1
+ 1 + 1 + 2
+ 1 + 1 + 1
+ 2 + 2 + 3
+ 2 + 1
+ 1 + 1 + 2
+ 1 + 1 + 1
+ 2 + 2 + 3
...
Can you please help me with some suggestions?
static string GenerateCombinations(int n)
{
string combinationList = "";
for (int index = 1; index < n - 1; index++)
{
string intermediaryList = GenerateCombinations(n - index, index) + " + " + index;
combinationList += intermediaryList;
}
return combinationList + "\n";
}
static string GenerateCombinations(int n, int index)
{
string combinationList = "";
for (int i = 1; i < n - 1; i++)
{
if (i <= index)
{
string intermediaryList = GenerateCombinations(n) + " + " + index;
combinationList += intermediaryList;
}
}
return combinationList;
}
static void Main()
{
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(GenerateCombinations(n));
}
Here is a solution not using collections (only using System;) and generating the output in the required order.
public static void PrintCombinations(int n)
{
PrintRest("", 0, n, n - 1);
}
private static void PrintRest(string listStart, int startSum, int n, int max)
{
for (int i = 1; i <= max; i++) {
string list = listStart.Length > 0
? listStart + " + " + i.ToString()
: i.ToString();
int sum = startSum + i;
if (sum == n) {
Console.WriteLine(list);
} else if (sum < n) {
PrintRest(list, sum, n, i);
}
}
}
You would call it as
PrintCombinations(7);
It starts by taking all possible start summands and calling itself to construct the rest of the sum. The combinations up to the current point are passed as string parameter listStart. The sum it represents is passed as int startSum. The target sum is n. max is the biggest summand allowed.
Try following :
class Program
{
static List<string> combinationList = new List<string>();
const int SUM = 7;
static void Main(string[] args)
{
List<int> numbers = new List<int>();
GenerateCombinations(numbers, 0);
combinationList.Sort();
Console.WriteLine(string.Join("\n", combinationList));
Console.ReadLine();
}
static void GenerateCombinations(List<int> numbers, int sum)
{
int start = 1;
if (numbers.Count > 0) start = numbers[0];
for (int i = start; i <= SUM; i++)
{
int newSum = sum + i;
if (newSum > SUM) break;
List<int> newList = new List<int>(numbers);
newList.Insert(0,i);
if (newSum == SUM)
{
combinationList.Add(string.Join(" + ", newList));
break;
}
else
{
GenerateCombinations(newList, newSum);
}
}
}
}
Since you are looking for a recursive solution, let's do it recursively without Linq and other mean.
Let's start from the basic: when given 0, we have an empty solution:
private static int[][] Solutions(int value) {
if (value <= 0)
return new int[][] { new int[0] };
//TODO: other cases for 1, 2, ...
}
Time to do the next step: if we know how to solve for some n - 1 (n - 1 >= 0) we can solve for n as follow:
all solutions start from m (m < n) are in form
`m + solutions for n - m which uses m .. 1 only`
E.g.
6 + 1 <- starts from 6, solves for 7 - 6 = 1, uses 6..1 only
5 + 2 ...
5 + 1 + 1
4 + 3
4 + 2 + 1
4 + 1 + 1 + 1 ...
3 + 3 + 1 <- starts from 3, solves for 7 - 3 = 4, uses 3..1 only
3 + 2 + 2 <- starts from 3, solves for 7 - 3 = 4, uses 3..1 only
3 + 2 + 1 + 1 <- starts from 3, solves for 7 - 3 = 4, uses 3..1 only
3 + 1 + 1 + 1 + 1 ...
2 + 2 + 2 + 1
2 + 2 + 1 + 1 + 1
2 + 1 + 1 + 1 + 1 + 1 ...
1 + 1 + 1 + 1 + 1 + 1 + 1 <- starts from 1, solves for 7 - 1 = 6, uses 1..1 only
This recursion can be encoded as
private static int[][] Solutions(int value, int startWith = -1) {
if (value <= 0)
return new int[][] { new int[0] };
if (startWith < 0)
startWith = value - 1;
List<int[]> solutions = new List<int[]>();
for (int i = Math.Min(value, startWith); i >= 1; --i)
foreach (int[] solution in Solutions(value - i, i)) {
int[] next = new int[solution.Length + 1];
Array.Copy(solution, 0, next, 1, solution.Length);
next[0] = i;
solutions.Add(next);
}
// Or just (if we are allow a bit of Linq)
// return solutions.ToArray();
int[][] answer = new int[solutions.Count][];
for (int i = 0; i < solutions.Count; ++i)
answer[i] = solutions[i];
return answer;
}
Demo
var result = Solutions(7);
// A pinch of Linq for demonstration
string report = string.Join(Environment.NewLine, result
.Select(solution => string.Join(" + ", solution)));
Console.Write(report);
Outcome:
6 + 1
5 + 2
5 + 1 + 1
4 + 3
4 + 2 + 1
4 + 1 + 1 + 1
3 + 3 + 1
3 + 2 + 2
3 + 2 + 1 + 1
3 + 1 + 1 + 1 + 1
2 + 2 + 2 + 1
2 + 2 + 1 + 1 + 1
2 + 1 + 1 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1 + 1 + 1

Can you please help me with a clue on how can I find all possible combinations for a given set of number from 1 to N, using +- operators [duplicate]

This question already has answers here:
Linq query to get all numbers (positive and negative) up to N that sum up to number K
(5 answers)
Listing all permutations of a string/integer
(28 answers)
Closed 1 year ago.
Given input: N = 6, X = 3
The output should be:
1 + 2 + 3 - 4 - 5 + 6 = 3
1 + 2 - 3 + 4 + 5 - 6 = 3
1 - 2 - 3 - 4 + 5 + 6 = 3
So far I could manage this:
//returns a string of numbers from 1 to N
static string Numbers(int maxNumber) => maxNumber > 1 ? Numbers(maxNumber - One) + maxNumber :"1";
and a function that generates all possible combinations for +- but the problem is that I want to combine the +- resulted string with numbers from 1 to N:
static void Permute(char[] arry, int i, int n)
{
int j;
if (i == n)
Console.WriteLine(arry);
else
{
for (j = i; j <= n; j++)
{
Swap(ref arry[i], ref arry[j]);
Permute(arry, i + 1, n);
Swap(ref arry[i], ref arry[j]); //backtrack
}
}
}
static void Swap(ref char a, ref char b)
{
char tmp;
tmp = a;
a = b;
b = tmp;
}
This looks like a very different form of "permute". For N integers, you have D=N-1 decisions to make, each of which can be either a + or a -. Two options is: "binary", so, if this is me, I would compute (2^D)-1 (which gives us the upper bound), then do a for loop from zero to that number (inclusive), and do the math: each binary digit is a decision point, and we could say 0===- and 1===+; see what the result is: if it is the number you wanted: log it.
For N=6 we have D=5, and 32 attempts to do; 0 thru 31:
int N = 6, X = 3;
// how many decisions is that?
var decisions = N - 1;
// treat each -/+ as one of "decisions" binary digits
var binaryUpperLimit = (1 << decisions) - 1;
for (int i = 0; i <= binaryUpperLimit; i++)
{
// compute the sum
int sum = 1; // the 1 is a permenant fixture, it seems
// determine each decision using binary arithmetic
for (int place = 0; place < decisions; place++)
{
int digit = place + 2;
if ((i & (1 << place)) == 0)
{
sum -= digit;
}
else
{
sum += digit;
}
}
// is that what we wanted?
if (sum == X)
{
// we have a "hit"; repeat the above to output this
Console.Write("1");
for (int place = 0; place < decisions; place++)
{
if ((i & (1 << place)) == 0)
{
Console.Write(" - ");
}
else
{
Console.Write(" + ");
}
int digit = place + 2;
Console.Write(digit);
}
Console.Write(" = ");
Console.WriteLine(sum);
}
}
(if the initial 1 can be negative, you'll need to adjust to add an extra decision, start the sum at zero, and make digit be +1 instead of +2)

array with positive double-digit random numbers

Write a program that fills a 15-byte array with positive double-digit random numbers. in each number, the sum of the two digits is equal to 9.
Here's what I've done so far:
int one = 0;
int two = 0;
int[] arr = new int[15];
Random rnd = new Random();
for (int i = 0; i < arr.Length; i++)
{
arr[i] = rnd.Next(10, 99);
one = arr[0] % 10;
two = arr[0] / 10;
if (arr[i] % 2 == 0 && one + two == 9)
Console.WriteLine(arr[i]);
}
The problem with your solution is that rnd.Next(10, 99) will not always produce number with the properties that you want. you should write a code that always works.
We know that sum of digits of a number should be 9. if we assume our two-digit number to be a*10+b where a and b are digits and a + b = 9, we can randomly generate a from 1 to 9.
Then we can calculate other digit b = 9 - a.
therefor our final result would be a*10 + 9 - a which will be simplified to a*9 + 9 where a is random number from 1 to 9, here are two examples.
a=7 then 7 * 9 + 9 = 72, 7 + 2 = 9
a=3 then 3 * 9 + 9 = 36, 3 + 6 = 9
note that a is in this range 1 <= a < 9

How to increment i in for loop in C#

I'm trying to modify the code below so each first number in column is based on the row number.
int i, sum = 0;
for (int row = 0; row < 7; row++)
{
for (i = 1; i < 6; i++)
{
sum = sum + i;
Console.Write("{0} ", i);
}
Console.WriteLine(sum);
sum = 0;
}
Console.Read();
presents this in console:
1 2 3 4 5 15
1 2 3 4 5 15
1 2 3 4 5 15
1 2 3 4 5 15
1 2 3 4 5 15
1 2 3 4 5 15
1 2 3 4 5 15
But I'm trying get like this:
1 2 3 4 5 sum
2 3 4 5 6 sum
3 4 5 6 7 sum
4 5 6 7 8 sum
and so on..
......
....
Any idea on how to solve this?
Change the inner loop to be
for (int i = row + 1; i < row + 6; i++)
Replace
sum = sum + i;
Console.Write("{0} ", i);
enter code here
with
number = number + row
sum = sum + number;
Console.Write("{0} ", number);
This way you use the variable row to keep track of the starting number for the row.
If you don't need the console statements and just the sum, you can just use no inner loop and:
sum = Enumerable.Sum(Enumerable.Range(row+1, 5));
It's LINQ
or, if you need the console statement:
Enumerable.Range(row+1, 5).ToList().ForEach(c => sum += c; Console.Write(c));

Categories