How do I add 1 number to a array? [duplicate] - c#

This question already has answers here:
Add new item in existing array in c#.net
(20 answers)
Closed 1 year ago.
I do not have anything other than the normal
using System;
namespace TryStuff
{
class Program
{
static void Main(string[] args)
{
}
}
}
And I know that having nothing at the start and still asking questions isnt highly looked on but STILL...
Im trying to create a code that asks you for an integer, and if you answer anything over 0, it ADDS the given number to an array, once you stop giving numbers (example type some "stop") it prints out ALL the numbers given to the array.
I DO NOT need the full code for something like this, just an answer to how do I append to an array without making it insanely complicated (things ive found on the google are like 20 lines of code but im pretty sure its not that hard).
Sorry for the long post and in short, how do I append to an array? If you can provide me a code, please implement it in the C# code or give me a "explanation" how to do it. Thank you very much!

You probably don't want to use an array, you want a different data structure that allows easy expansion, like List<T>. For List<T>, you simply call .Add, like:
using System;
using System.Collections.Generic;
namespace TryStuff
{
class Program
{
static void Main(string[] args)
{
var myList = new List<int>();
while(int.TryParse(Console.ReadLine(), out int x))
{
if (x > 0)
{
myList.Add(x);
}
}
Console.WriteLine("You entered: " + string.Join(",", myList));
}
}
}
This should keep allowing you to enter integer numbers and add them to the list if the number is greater than 0. It ignores all numbers 0 or less than 0. If you type anything that is not a number, it will stop and print out the list you entered.

Related

C# Creating a list that takes user input and after prints the number from the list within a certain value range.(please explain how and why it works)

using System;
using System.Collections.Generic;
namespace exercise_69
{
class Program
{
public static void Main(string[] args)
{
List<int> numbers = new List<int>();
//creating a list called numbers
while (true)
{
int input = Convert.ToInt32(Console.ReadLine());
if (input == -1)
{
break;
}
numbers.Add(input);
}
//fills a list called numbers until user enters " -1 "
Console.WriteLine("from where");
int lownum = Convert.ToInt32(Console.ReadLine());
//lowest number to get printed
Console.WriteLine("where to");
int highnum = Convert.ToInt32(Console.ReadLine());
//highest number to get printed
foreach(int number in numbers)
{
if(lownum < number || highnum > number)
{
Console.WriteLine(numbers);
} //trying to filter the numbers and print them
}
}
}
}
Blockquote
the issue i am having is when i run the program the console just tells me this
"System.Collections.Generic.List`1[System.Int32]"
so my question is how do i properly filter or remove numbers from a list within a certain value ( not index )
the console just tells me this "System.Collections.Generic.List`1[System.Int32]"
That's because you did this:
Console.WriteLine(numbers);
numbers is a List<int>, it's a whole collection of numbers not just a single number. Console.WriteLine has many varaitions ("overloads") that know how to do all different kinds of things. It has a large quantity of specific variations for numbers, strings, etc and there is one variation that's like a "catch-all" - it accepts an object which means it can accept pretty much anything in the C# universe. The only thing it does with it, if you do manage to end up using this variation (overload), is call ToString() on whatever you passed in, and then print the string it gets back.
Because you passed a List<int> in, and Console.WriteLine doesn't have any variation that does anything cool with a List specifically, it means your passed-in List gets treated by the catch-all version of WriteLine; "call ToString on what was passed in and print the result". Because List doesn't have a very specific or interesting ToString() of its own, it just inherits a version of ToString() from object, the most simple root of all things in C#. Object's ToString() doesn't do very much - it just returns the type of the object which, in this case, is a "System.Collections.Generic.List`1[System.Int32]".. and that's why you see what you see in the console
Now that you know why your code is printing the type of the List, because you're passing in a List, can you see how to change it so you're passing in something else (like, e.g. an actual number you want to print) ?
Console.WriteLine(numbers);
^^^^^^^
this needs to be something else - can you work out what?

Resolve a Perfect Sum with Predicate

Hi everyone I'm trying to resolve this c# exercise but I couldn't find the way to do it. Even without doing with the suggested tip below.
Make a perfect sum with the following examples
Example 1:
input1: 5
input2: {9,6,3,12,7}
input3: 14
Output: 1
Explanation:
Here, the sum of elements 7+7=14. Hence, the number of perfect sums in
the given array is 1. Therefore, 1 is returned as the output.
Example 2:
input1: 5 input2: (4,7,8,2,3} input3: 12
Output: 2
Explanation:
Here, the sum of elements 8+4=12 and 7+3+2=12. Hence, the number of
perfect sums in the given array is 2. Therefore, 2 is returned as the
output
Tip: I rather like seeing Predicate in a function signature. It illustrates that the passed method makes a decision rather than just returns a success code or a different sort of bool.
Base Code:
class Program
{
static void Main(string[] args)
{
//Call the method here
Console.ReadKey();
}
static int PerfectSums(int input, int[] input2, int input3)
{
throw new NotImplementedException();
}
}

Sorting not working properly

I am trying to figure out why this works, but when I can the numbers around it doesn't. What the code is suppose to do is have two stacks, the program is suppose to sort in ascending order, which it does, but if I change the:
first.Push(7)
to something like
first.Push(80)
it doesn't work.
Can someone explain this, please?
Here is what I have:
using System;
using System.Collections;
namespace Project03_03
{
class Program
{
static void Main(string[] args)
{
Stack first = new Stack();
first.Push(50);
first.Push(45);
first.Push(11);
first.Push(7);
Stack second = new Stack();
second.Push(67);
second.Push(65);
second.Push(32);
second.Push(12);
ProcessInOrder(first, second);
Console.WriteLine(
"Press any key to continue...");
Console.ReadKey();
}
static void ProcessInOrder(Stack first,
Stack second)
{
while (first.Count > 0 || second.Count > 0)
{
if (first.Count == 0)
{
Console.WriteLine(second.Pop());
continue;
}
if (second.Count == 0)
{
Console.WriteLine(first.Pop());
continue;
}
if ((int)first.Peek()
>= (int)second.Peek())
{
Console.WriteLine(
second.Pop());
}
else
{
Console.WriteLine(first.Pop());
}
}
}
}
}
what your code is doing is merging two already sorted stacks. So it pretty much just traverses the stack and sees which value is smaller and then displays that one. Thus is you have two already sorted stacks it can merge them into one larger stack that is also already sorted.
By changing your code so the last item pushed into the first stack is 80 vs 7 it breaks this state and thus your logic is flawed. A different approach to solve this code might be to first merge the two stacks then pop them and sort them at that time. Here is a some code to sort a stack (dont click it if you want to try and figure it out yourself first)
You can also write some unit tests to confirm these scenarios are fixed as you modify your code.
Lastly if you compare your new sorting code to one of the examples maybe you can measure the difference in performance between the two like this example did

How to get all possible classes combinations in C#

Let say we have the fallowing classes 'X','Y','Z',
The result so I need will be like this
(X),(X,Y),(X,Z),(X,Y,Z),(Y),(Y,Z),(Z)
And if we have 'X','Y','Z','J',
The result so I need will be like this
(X), (X,Y),(X,Z),(X,J), (Y), (Y,Z),(Y,J), (Z),(Z,J)
(X,Y,Z), (X,Y,Z,J), (Y,Z,J), (Z,J,X)
What algorithm do I need to accomplish this?
What you are looking for is called a power set. There are both recursive and iterative ways to calculate it; it should not be difficult to google one.
Have a try at implementing an algorithm and come back to update the question if you have specific trouble.
If that is a power set, you missed out the empty set (which is always a member of a power set, of course!).
Anyway, something like this might work for you:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Demo
{
class Program
{
static void Main()
{
string[] classes = {"X", "Y", "Z"};
foreach (var combination in PowerSet(classes))
{
foreach (var item in combination)
{
Console.Write(item + ", ");
}
Console.WriteLine("");
}
}
public static IEnumerable<IEnumerable<T>> PowerSet<T>(T[] sequence)
{
return from m in Enumerable.Range(0, 1 << sequence.Length)
select
from i in Enumerable.Range(0, sequence.Length)
where (m & (1 << i)) != 0
select sequence[i];
}
}
}
This algorithm works by "pretending" that the combinations are binary numbers. See http://en.wikipedia.org/wiki/Power_set for details (especially the section titled "Representing subsets as functions").

Recursive woes - reducing an input string

I'm working on a portion of code that is essentially trying to reduce a list of strings down to a single string recursively.
I have an internal database built up of matching string arrays of varying length (say array lengths of 2-4).
An example input string array would be:
{"The", "dog", "ran", "away"}
And for further example, my database could be made up of string arrays in this manner:
(length 2) {{"The", "dog"},{"dog", "ran"}, {"ran", "away"}}
(length 3) {{"The", "dog", "ran"}.... and so on
So, what I am attempting to do is recursively reduce my input string array down to a single token. So ideally it would parse something like this:
1) {"The", "dog", "ran", "away"}
Say that (seq1) = {"The", "dog"} and (seq2) = {"ran", "away"}
2) { (seq1), "ran", "away"}
3) { (seq1), (seq2)}
In my sequence database I know that, for instance, seq3 = {(seq1), (seq2)}
4) { (seq3) }
So, when it is down to a single token, I'm happy and the function would end.
Here is an outline of my current program logic:
public void Tokenize(Arraylist<T> string_array, int current_size)
{
// retrieve all known sequences of length [current_size] (from global list array)
loc_sequences_by_length = sequences_by_length[current_size-min_size]; // sequences of length 2 are stored in position 0 and so on
// escape cases
if (string_array.Count == 1)
{
// finished successfully
return;
}
else if (string_array.Count < current_size)
{
// checking sequences of greater length than input string, bail
return;
}
else
{
// split input string into chunks of size [current_size] and compare to local database
// of known sequences
// (splitting code works fine)
foreach (comparison)
{
if (match_found)
{
// update input string and recall function to find other matches
string_array[found_array_position] = new_sequence;
string_array.Removerange[found_array_position+1, new_sequence.Length-1];
Tokenize(string_array, current_size)
}
}
}
// ran through unsuccessfully, increment length and try again for new sequence group
current_size++;
if (current_size > MAX_SIZE)
return;
else
Tokenize(string_array, current_size);
}
I thought it was straightforward enough, but have been getting some strange results.
Generally it appears to work, but upon further review of my output data I'm seeing some issues. Mainly, it appears to work up to a certain point...and at that point my 'curr_size' counter resets to the minimum value.
So it is called with a size of 2, then 3, then 4, then resets to 2.
My assumption was that it would run up to my predetermined max size, and then bail completely.
I tried to simplify my code as much as possible, so there are probably some simple syntax errors in transcribing. If there is any other detail that may help an eagle-eyed SO user, please let me know and I'll edit.
Thanks in advance
One bug is:
string_array[found_array_position] = new_sequence;
I don't know where this is defined, and as far as I can tell if it was defined, it is never changed.
In your if statement, when if match_found ever set to true?
Also, it appears you have an extra close brace here, but you may want the last block of code to be outside of the function:
}
}
}
It would help if you cleaned up the code, to make it easier to read. Once we get past the syntactic errors it will be easier to see what is going on, I think.
Not sure what all the issues are, but the first thing I'd do is have your "catch-all" exit block right at the beginning of your method.
public void Tokenize(Arraylist<T> string_array, int current_size)
{
if (current_size > MAX_SIZE)
return;
// Guts go here
Tokenize(string_array, ++current_size);
}
A couple things:
Your tokens are not clearly separated from your input string values. This makes it more difficult to handle, and to see what's going on.
It looks like you're writing pseudo-code:
loc_sequences_by_length is not used
found_array_position is not defined
Arraylist should be ArrayList.
etc.
Overall I agree with James' statement:
It would help if you cleaned up the
code, to make it easier to read.
-Doug

Categories

Resources