2d array,adding it values in a weird pattern - c#

i started learning C# and programming a few months ago and have some problems. The idea here is we create a 2 dimensional array (the number of rows / columns are added by the user), the numbers need to be between 1 and 10.
Then when the array is created the number sequence ( 3-5-7-9-11 etc) is started in the first and finishes in the last column. The rest of the numbers in the columns are added via keyboard by the user starting with the first row (ignoring column 1 and the last column cause we have that added).
The questions are :
What will be the best way to check if the numbers of rows/columns are between 1 and 10? (I was thinking of IF-else but isn't there a better way ?)
How will i make it so that the number sequence 3-5-7 etc is started in the first and finishes in the last column?
Yeah i feel lost.
Where i am at the moment :
Console.WriteLine("Add row value of 1-10");
string s1
s1 = Console.ReadLine();
int k = int.Parse(s1);
Console.WriteLine("Add column value of 1-10");
string s2;
s2 = Console.ReadLine();
int p = int.Parse(s2);
int[,] M = new int[k, p];
Example : we added k(row) & p(coulmn) value of 4.So the array should look like :
3 x x 11
5 x x 13
7 x x 15
9 x x 17
Then the X's should be added again manually without overwriting the existing numbers .The value of the numbers doesnt matter.

So... If I get it right you want to ask user the "length and width" of dynamical 2d array?
To check if entered number is between 1 and 10 there's only 1 method:
int [,] M;
if (k >= 1 && k <= 10 && p >= 1 && p <= 10)
{
M = new int[k,p];
}
And better is to do int.TryParse() for case if user enters characters there instead of numbers, or else you can easily get an Exception.
Filling with numbers:
int num = 3;
for (int i = 0; i < k; ++i)
{
M[i,0] = num;
num+=2;
}
for (int i = 0; i < k; ++i)
{
M[i,p] = num;
num+=2;
}
This adds numbers in 1st and last column in each row. After that to fill other cells manually you check every cell thet it is not in firs or last column.
I hope I understood you correctly. Provided code may be simplified, but provided in such way for better understanding.

if(k>0 && k<11 && p>0 && p<11)
{
int i;
int M[,] = new int[k,p];
for (i=0;i<k;i++)
{
M[i,0]=i*2+3;
M[i,p-1]=(i+k)*2+3;
}
}

Related

C# Printing a 2D Array in Matrix Format Using a Foreach Loop

I am trying to create an array that will print out times tables. The first column is the 1 times table, the second is the 2 times table and so on. The user is asked for an input that will determine the number of rows and columns.
I want to print the array in matrix format using a foreach loop. It works fine when I use a for loop but I would like to know how to achieve the same output using a foreach loop.
Shown is the code:
int rows;
int columns;
Console.WriteLine("Enter the number of rows");
rows = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the number of columns");
columns = Convert.ToInt32(Console.ReadLine());
int[,] multiDim = new int[rows, columns];
for (int p = 0; p < multiDim.GetLength(0); p++)
{
for (int k = 0; k < multiDim.GetLength(1); k++)
{
multiDim[p, k] = (p + 1) * (k + 1);
}
Console.WriteLine();
Console.ReadLine();
}
foreach (int i in multiDim)
{
Console.Write(i + " ");
if (i == multiDim.GetLength(1))
{
Console.WriteLine();
}
}
Console.ReadLine();
When I enter a value for rows that is above 2 the program does does not print the array in a proper array format. For example when I have 3 rows and 5 columns the output is:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
I have read similar questions bu they do not seem to help. All help is appreciated.Thanks in advance.
Your code is looping over the values of the array, rather than the indexes. This means that it just happens to work initially since your values line up well.
I would suggest switching to using Jagged Arrays instead of Multidimensional arrays. This way you can do foreach (row in multiDim), then foreach (cell in row)
If you still need to use a multidimensional array, then you need some form of counter which keeps track of the position of the array you are in. This is why a regular for loop is better to use for this scenario rather than a foreach loop.

How to find subset of numbers in array that equals to 10? [duplicate]

This question already has answers here:
Find if pair of elements with given sum exists in large integer array
(6 answers)
Closed 8 years ago.
I want to find the sum of all subsets of adjacent numbers.
So if the set is 6 1 2 2 5
I want to find (the sum of)
6 1 2 2 5
6 1 2 2
1 2 2 5
6 1 2
1 2 2
2 2 5
6 1
1 2
2 2
2 5
So I want to find not anly subsets of 2 numbers,but more(example input: 6 1 2 2 5 -> 6+2+2=10 or 1+2+2+5=10) and print them.
using System;
class Subset
{
static void Main()
{
string[] num = Console.ReadLine().Split(' ');
int[] number = new int[num.Length];
for (int a = 0; a < 5; a++)
{
number[a] = Convert.ToInt32(num[a]);
}
int sum;
bool found = false;
for (int i = 0; i < 5; i++)
{
sum = 0;
for (int j = i; j < 5; j++)
{
sum = sum + number[j];
if (sum == 10)
{
found = true;
for (int k = i; k < j; k++)
{
Console.Write("{0} + ", number[k]);
}
Console.Write(number[j]);
Console.Write(" = 10\n");
}
}
}
if (found == false)
{
Console.WriteLine("no zero subset\n\n");
}
}
}
This is very similar to the subset sum problem. The only way to really find a combination that adds up to ten (or even all combinations), you will have to test all combinations. I am not sure if you want combinations of any size, or only two numbers. The examples you give only involve examples where two numbers add up to ten, which can be easily done by checking for all pairs.
for (int i = 1; i < numbers.Length; i++)
for (int j = 0, j < i; j++)
if (numbers[i] + numbers[j] == 10)
{
Console.WriteLine("{0} + {1} = 10", numbers[i], numbers[j];
return;
}
Console.WriteLine("no subset that sums up to 10");
If however you want to find any subset of numbers that add up to ten, you have to consider all subsets of the set you are given. The best way to do this is using dynamic programming. You loop through the array of numbers and for each number you make the decision to either include the element in the subset or not. Let's look at the following method:
bool SubsetSum(int[] numbers, int startIndex, int sum)
{
if (startIndex == numbers.Length - 1) // base case, only one element to consider
return numbers[startIndex] == sum || sum = 0;
return SubsetSum(numbers, startIndex + 1, sum) // don't take the current element
|| SubsetSum(numbers, startIndex + 1, sum - numbers[startIndex]; // take the current element
}
This method first checks if we arrived at the last element. In that case, we have two easy cases to consider: the sum we want to reach is 0, so we don't take the element, or the sum we want to reach is equal to the last element, in which case we do take it. Otherwise, there is no valid solution.
In all the other cases, we just branch into two paths, either taking or not taking the element into the subset.
This algorithm will run in exponential time in the amount of numbers as input. You can speed this up by using memorisation. You can create a huge table and save for every pair of startIndex and sum the outcome value. That way you are sure you will never evaluate the same thing twice. (Look up dynamic programming to learn more about this)
The method I described above only returns if a subset exists. To actually find the subset, you will also have to pass back the indices of the elements you have added to the subset. I won't work that out, as it makes the thing a lot more complicated. If you use a table in the dynamic programming approach, you are also able to use some backtracking techniques to find the right indices in linear time.

How to display all members of a given subsequence on the console?

I'm trying to understand why I can't print only the members of a subsequence of an array, that is equal to an integer from the input. The array is also read from the console. When i run the program only the first of these members does come up, but with him also a seemingly random number of zeros, while the rest of the subsequence is omitted. If there's a better way than to use a second array, I'll be grateful if you share it. Okay, to specify- I want to know how to print all the members of the aforementioned subsequence, can you please give me a useful advice or sample? Here's the input, output and code:
4 4 56 57 58
8
4 0 0 0 0
instead of 4 4
int v = int.Parse(Console.ReadLine());
int[] valueHolder = new int[arr1.Length];
int currentSum = 0;
for (int endIndex = 0; endIndex <= arr1.Length -1; endIndex++)
{
currentSum = 0;
for (int currentSumIndex = endIndex; currentSumIndex >= 0; currentSumIndex--)
{
currentSum += arr1[currentSumIndex];
if (currentSum == v)
{
valueHolder[currentSumIndex] = arr1[currentSumIndex];
}
if (currentSum == v)
{
for (int i = 0; i <= valueHolder.Length - 1; i++)
{
Console.Write(valueHolder[i] + " ");
}
}
}
I think you would be best served by putting a break point on the line of the first for loop then stepping through your code. If you take a pad of paper and write each of the variables states as you go through it then it will be pretty obvious what's going on.
However, just to help you out.
In the first pass of the outer loop (endIndex = 0), the inner loop does NOT execute. currentSumIndex = endIndex which equals zero, which does not pass the currentSumIndex >= 0 test. Therefore the first 4 is skipped.
In the second pass, the number 4 is emitted because currentSum equals 4. However, the values of 0 are also emitted because you are walking the entire valueHolder array and spitting all of the empty values out.
From the third pass forward, currentSum will never equal the number you typed in:
The first pass of the inner loop sets currentSum to 56, which does not equal v. The second pass of the inner loops sets it to 56+4 ( currentSum += arr1[currentSumIndex] ) which is 60. Therefore, nothing will ever be emitted again as currentSum will always be the sum of all numbers from the current array position going backward to the beginning array position and therefore will always be greater than v
You don't need a second array. You just need to pay attention to what your code is doing. Side note: I have absolutely no idea why you have that inner loop or even what the 8 is supposed to represent in your example entry above.
If I was writing this, I'd change it to (assuming you can't use LINQ):
int v = int.Parse(Console.ReadLine());
for (int i= 0; i <= arr1.Length -1; i++)
{
if (arr1[i] == v) {
Console.Write(arr1[i].ToString() + " ");
}
}
Console.WriteLine();

Project Euler - 1: Finding multiples of 3 and 5 [duplicate]

This question already has answers here:
Add all natural numbers that are multiples of 3 and 5 : What is the bug in the following code
(5 answers)
Project Euler: Problem 1 (Possible refactorings and run time optimizations)
(13 answers)
Closed 9 years ago.
Project Euler - Problem 1: Find the sum of all the multiples of 3 or 5 below 1000.
Looking through the questions here about the same problem I assume the way I tried to solve is is quite bad. What is the best way to solve this?
And my other question: The sum value doesn't match the answer. I think the problem is that when I use foreach to write out the list value its starts from 705 instead of 3, but I have no idea why. I would appreciate if someone could explain it to me.
This is the code that I'm using now:
List<int> numbers = new List<int>();
for (int i = 3; i < 1000; i += 3)
{
numbers.Add(i);
}
for (int j = 5; j < 1000; j += 5)
{
numbers.Add(j);
}
numbers.ForEach(Console.WriteLine);
int sum1 = numbers.Sum();
Console.WriteLine(sum1);
Console.ReadLine();
This is because numbers allows duplicates. Note that you are going to have some duplicates, there - for example, numbers 15, 30, 45, and so on, will be added twice.
Replace
List<int> numbers = new List<int>();
with
ISet<int> numbers = new HashSet<int>();
and it's going to work because a HashSet won't allow duplicate values.
This is the first problem on Project Euler.
Personally, I used a one liner :
Enumerable.Range(0, 1000).Where(n => n % 3 == 0 || n % 5 == 0).Sum()
But you can also use the long way for more readability :
int sum = 0;
for (int i = 0; i < 1000; i++)
{
if ((i % 3 == 0) || (i % 5 == 0))
{
sum = sum + i;
}
}
If you don't know how the modulo (%) operator works, I suggest you read it here
If you need more details about the problem itself, just create an account on Project Euler, enter the answer, and read the Problem Overview.
You're not accounting for numbers that are both multiples of 3 and 5
If I were you, I'd have something like the following
for(int i=1; i<1000; i++)
{
if(i is a multiple of 15)
//account for 15
else if(i is a multiple of 3)
//account for 3
else if(i is a multiple of 5)
//account for 5
}
The reason your output starts with 705 is because your list of numbers is quite long (532 numbers to be exact). Your Console window can only contain a couple of lines before it starts scrolling.
So you do start with the number 3, it's just not visible.
As others have pointed out, the issue is that your code counts multiples of 15 twice. Of course, this task is pretty easy using Linq's Range and Where methods:
var numbers = Enumerable.Range(0, 1000)
.Where(n => n % 3 == 0 || n % 5 == 0);
foreach(var n in numbers)
{
Console.WriteLine(n);
}
var sum = numbers.Sum();
Console.WriteLine(sum);
Console.ReadLine();
You have duplicate values in the list. Thats why total sum is invalid. You better change the Data Structure to HashSet which not allow duplicates.
If you can't do that or you have to proceed with this way, try below
call numbers = numbers.Distinct().ToList(); before numbers.ForEach(Console.WriteLine);
I think the problem is that when I use foreach to write out the list
value its starts from 705 instead of 3, but I have no idea why.
Problem is duplicate values, foreach will print correctly but you may not able to scroll console to beginning of printing.
try Console.WriteLine(string.Join(",", numbers));
You could also solve it with Linq. Use Enumerable.Range to get all numbers between 0 and 999 (inclusive). Then use Where to filter those out which are divisible by 3 or divisible by 5. Finally use Sum.

How to go about storing multiple values from a loop, and displaying asterisks based on input

This question asks to write a program that accepts input for five 'stores'. The input should ideally be a range from 100 to 2000. Each input should be divided by 100, and have that amount displayed in asterisks (i.e. 500 is *, etc.). I believe I have the first part, but I've got no idea how to go about doing the rest. I cannot use arrays, as I have not learned them yet, and I want to be learn this myself instead of just copy-pasting from another student. So far, I only have
int loop;
loop = 1;
while (loop <= 5)
{
string input1;
int iinput1, asteriskcount1;
Console.WriteLine("Input number of sales please!");
input1 = Console.ReadLine();
//store value?
loop = loop + 1;
input1 = Convert.ToInt32(input1);
asteriskcount1 = iinput1 / 10;
}
Not sure if I understand what you're trying to do. But maybe this will help. This is untested, but it should do what I THINK you are asking, but I am unsure what you wanted done with the asterisks. Please explain more if this isn't what you were getting at.
string Stored = "";
for (int i=0; i < 5; i++;)
{
string input1;
int iinput1, asteriskcount1;
Console.WriteLine("Input number of sales please!");
input1 = Console.ReadLine();
//Adds to existing Stored value
Stored += input1 + " is ";
//Adds asterisk
iinput1 = Convert.ToInt32(input1);
asteriskcount1 = iinput1 / 100;
for(int j = 0; j < asteriskcount1; j++)
{
Stored += "*";
}
//Adds Comma
if(i != 4)
Stored += ",";
}
Console.WriteLine(Stored); //Print Result
Don't want to write it out for you but here's some thoughts ...
first, you can do a for loop for the 5 stores:
for (int loop = 0; loop < 5; loop++)
You'll probably want asterickCount (not asterickCount1) since you're in a loop. You'll also want to divide by 100 since you're range is up to 2000 and you have 80 chars on a console. That means it will print up to 20 astericks.
You'll want a PrintAstericks(int count); function that you call right after calculating the asterickCount that you call. That function simply loos and calls Console.Write (not WriteLine) to write an asterick n times (new string has overload to take char and count).
But, that pattern will print the astericks after you take each input. If you want the pattern to be (1) accept the counts for the five stores and then (2) print the asterick rows for all five, you'll need an array with 5 slots to store the inputs then loop through the array and print the asterick rows.
Finally, you'll want to put some validation on the inputs. Look at Int32.TryParse:
http://msdn.microsoft.com/en-us/library/bb397679.aspx
Super easy
int asteriskCount = int.Parse(input1)/ 100;
string output = new string('*', asteriskCount );

Categories

Resources