Convert string[] to int - c#

I have an array of integers in string form.
string [] TriangleSideLengths
In this array there is going to be 3 int values which represent side length of a triangle. Is there a way from which I can extract individual all 3 values from my array TriangleSideLengths into three int objects like int intSideLengthOne,intSideLengthTwo and intSideLengthThree.
I want to be able to test if these three values actually form a valid triangle?
For instance, entering lengths 10, 10, 100000 wouldn't make it a valid isosceles triangle.
I wanna be able to do this check with the three values stored in my array TriangleSideLengths.
a + b > c
a + c > b
b + c > a
Any help is greatly appreciated.
Thanks a lot!! :)

You can use LINQ to parse the numbers from the string, like this:
var threeSides = TriangleSideLengths.Select(int.Parse).ToArray();
Here is a demo on ideone.
To do the check, sort the numbers in ascending order, then check that the sum of the first two is strictly greater than the third one:
Array.Sort(threeSides);
if (threeSides[0]+threeSides[1] > threeSides[2]) {
...
}
Note that it is not a sufficient condition for the numbers to define a triangle: you must also check that the numbers are strictly positive.

Try this
string [] TriangleSideLengths = new string[3];
int[] lengths = new int[3];
for(int i = 0; i<=2;i++)
{
lengths[i]=Convert.ToInt32(TriangleSideLengths[i]);
}
if(lengths[0]+lengths[1]>lengths[2])
//go crazy

string[] TriangleSideLengths = { "10", "20", "300"};
int[] sides = new int[TriangleSideLengths.Length];
for (int i = 0; i < TriangleSideLengths.Length; i++)
{
sides[i] = int.Parse(TriangleSideLengths[i]);
}

int[] sides = new int[TriangleSideLengths.Length];
int counter=0;
foreach(var str in TriangleSideLengths)
{
int.TryParse(str, out sides[counter++]);
}
if(sides[0] + sides[1] > sides[2]){...}

public int toInt(string text)
{
int tonumber = int.Parse(text);
return tonumber;
}

Related

Skipping a range of values in for loop C#

I'm trying to cycle through chars in a string.
string cycleMe = "Hi StackOverflow! Here is my string."
However, I want to skip over certain ranges of indexes. The ranges I want to skip over are stored in a List of objects, delims.
List<Delim> delims = delimCreator();
To retrieve each starting index and ending index for a range, I have to write a loop that accesses each "delim":
delims[0].getFirstIndex() //results in, say, index 2
delims[0].getLastIndex() //results in, say, index 4
delims[1].getFirstIndex() //results in, say, index 5
delims[1].getLastIndex() //results in, say, index 7
(there can be infinitely many "delim" objects in play)
If the above were my list, I'd want to print the string cycleMe, but skip all the chars between 2 and 4 (inclusive) and 5 and 7 (inclusive).
Expected output using the numbers above:
HiOverflow! Here is my string.
Here is the code I have written so far. It loops far more often than I'd expect (it loops ~x2 the number of characters in the string). Thanks in advance! =)
List<Delim> delims = delimAggregateInator(displayTextRaw);
for (int x = 0; x < cycleMe.Length;x++){
for (int i = 0; i < delims.Count; i++){
if (!(x >= delims[i].getFirstIndex() && x <= delims[i].getLastIndex())){
Debug.Log("test");
}
}
I assume that by skipping you meant you want to omit those characters from the original string. If that is the case, you can try Aggregate extension method like below.
string result = delims.Aggregate<Delim, string>(cycleMe, (str, d) => cycleMe = cycleMe.Remove(d.FirstIndex, (d.LastIndex - d.FirstIndex) + 1));
Make sure that the delim list is in the proper order.
Solution might be converting the string to char array, replacing the desired parts to spaces, and converting the output back to string.
Here is the modified version of your code:
string cycleMe = "Hi StackOverflow! Here is my string."
var charArray = cycleMe.ToCharArray(); // Converting to char array
List<Delim> delims = delimAggregateInator(displayTextRaw);
for (int x = 0; x < cycleMe.Length;x++){
for (int i = 0; i < delims.Count; i++){
// ORIGINAL: if (!(x >= delims[i].getFirstIndex() && x <= delims[i].getLastIndex())){
if (x >= delims[i].getFirstIndex() && x <= delims[i].getLastIndex()){
Debug.Log("test");
charArray[x] = ' '; // Replacing the item with space
}
}
string output = new string(charArray); // Converting back to string
P.S. This is probably not the most optimal solution but at least it should work.
You should use LINQ for that
struct Delim
{
public int First { get; set; }
public int Last { get; set; }
}
static void Main(string[] args)
{
string cycleMe = "Hi StackOverflow! Here is my string.";
var delimns = new List<Delim> { new Delim { First=2, Last=4}, new Delim { First = 5, Last = 7 } };
var cut = cycleMe.Where((c, i) =>
!delimns.Any(d => i >= d.First && i <= d.Last));
Console.WriteLine(new string(cut.ToArray());
}
That means I am basically only selecting letters, at positions which are not part of any cutting range.
Also: Fix your naming. A delimiter is a character, not a position (numeric)

Count how many numbers is between a range in a List<string> with C#

I'm beginner C# programmer and I find myself a problem in a Windows Form Application that I'm working on Microsoft Visual C# 2010 Express. I have a button that opens a file dialog to select a specific Excel workbook and then retrieve the values of the first column and the fith column to a string like this:
string x = {"120,123,125,128,130,140,157,189,220,230,243,250"}
Then I've transformed this string and add to a list of string. Here is the code:
var y = string.Join(string.Empty, x).Split(',');
List<string> listX = new List<string>();
foreach (var x1 in y)
{
listX.Add(x1);
}
The list format is like this:
listX1[0] = "120";
listX1[1] = "123";
listX1[2] = "125";
And so on. Now I have this method to count how many number are between, lets say, 123 and 150, which will give me the number of 5 (with 123 included). The method used is something like this:
public static int Count(IList<int> set, int min, int max)
{
int count = 0;
foreach (int i in set)
if( i <= max && i >= min)
count++
return count;
}
Where min in this case would be 123 and max would be 150.
Now I know that I can't use this method because my list (listX1) is a list of strings. How can I manage to count the numbers between min and max, using C#? Anyone can help me with that?
Hope you can help me. Many Thanks.
I believe you have string array like:
string[] x = { "120", "123", "125", "128", "130", "140", "157", "189", "220", "230", "243", "250" };
You have to parse each item to int and then sort them, later you can get the count like:
int start = 123;
int end = 150;
var result = x.Select(int.Parse)
.Count(r => r >= start && r < end);
If you want to use int.TryParse then you can do:
int start = 123;
int end = 150;
int temp;
var result = x.Select(r => { return int.TryParse(r, out temp) ? temp : -1; })
.Count(r => r >= start && r < end);
This looks like an array of strings. You need to remove the double quotes to end up with an array of integers. From there, you can either loop through the array and count the numbers fitting in the interval or use a LINQ or Lambda expression

How can I combine/concatenate elements of an array based on bits of an int?

I would like to concatenate strings (from an array) based on an input int value.
For example:
int Input = 3;
string[] Items = {"A", "B", "C", "D"};
// output = "A, B"
// example 2: input = 8
// output = "D"
The first element of the array (0) should be associated with the least significant bit of the input value. Values in the array are concatenated with a string such as "," or "+".
What's a good way to do this?
So, you want to treat your input value as a bitmask?
This should work:
int Input = 3;
string[] Items = {"A", "B", "C", "D"};
var bitMask = new BitArray(new[]{Input});
return Items.Where((c,i)=>bitMask.Get(i)).ToArray();
Basically what I'm doing is converting your number into a BitArray, which will allow me to easily tell what bits are set and not set in your number. I'm then using a little Linq to filter the Items array by index, based on whether the corresponding index of the BitArray is set.
Understand that this will only work if the array has less than sizeof(int)*8 (32) elements. Beyond that, the BitArray won't have indexes to Get() unless you specify additional integer values that can be chained together in the int[] array passed to the BitArray constructor.
var sb = new StringBuilder();
int input = 3;
for(int i=0; i<items.Length && input != 0; i++) {
if((input & 1) == 1) {
if(sb.Length > 0) sb.Append(',');
sb.Append(items[i]);
}
input >>= 1;
}
You can identify the least significant bit of an integer using arithmetic modulo 2.
3 % 2 => 1
4 % 2 => 0
Once you've determined the least significant bit of an integer, you can discard the least significant bit by doing integer division by 2.
3 / 2 => 1
4 / 2 => 2
After discarding the least significant bit, you can use the modulus operator again to get the new least significant bit. Wrap this in a loop and you're done.
If the array isn't absolutely necessary you could use an enumeration:
[Flags]
enum Items
{
A = 1,
B = 2,
C = 4,
D = 8
}
Then use:
string GetItems(int items)
{
string[] itemList = new string[4];
int currPos = 0;
foreach (Items item in Enum.GetValues(typeof(Items)))
{
if ((items & (int)item) == (int)item)
{
itemList[currPos] = item.ToString();
currPos++;
}
}
return String.Join(",", itemList, 0, currPos);
}

Need code for addition of 2 numbers

I am having the numbers follows taken as strings
My actual number is 1234567890123456789
from this i have to separate it as s=12 s1=6789 s3=3456789012345
remaining as i said
I would like to add as follows
11+3, 2+4, 6+5, 7+6, 8+7, 9+8 such that the output should be as follows
4613579012345
Any help please
public static string CombineNumbers(string number1, string number2)
{
int length = number1.Length > number2.Length ? number1.Length : number2.Length;
string returnValue = string.Empty;
for (int i = 0; i < length; i++)
{
int n1 = i >= number1.Length ? 0 : int.Parse(number1.Substring(i,1));
int n2 = i >= number2.Length ? 0 : int.Parse(number2.Substring(i,1));
int sum = n1 + n2;
returnValue += sum < 10 ? sum : sum - 10;
}
return returnValue;
}
This sounds an awful lot like a homework problem, so I'm not giving code. Just think about what you need to do. You are saying that you need to take the first character off the front of two strings, parse them to ints, and add them together. Finally, take the result of the addition and append them to the end of a new string. If you write code that follows that path, it should work out fine.
EDIT: As Ralph pointed out, you'll also need to check for overflows. I didn't notice that when I started typing. Although, that shouldn't be too hard, since you're starting with a two one digit numbers. If the number is greater than 9, then you can just subtract 10 to bring it down to the proper one digit number.
How about this LINQish solution:
private string SumIt(string first, string second)
{
IEnumerable<char> left = first;
IEnumerable<char> right = second;
var sb = new StringBuilder();
var query = left.Zip(right, (l, r) => new { Left = l, Right = r })
.Select(chars => new { Left = int.Parse(chars.Left.ToString()),
Right = int.Parse(chars.Right.ToString()) })
.Select(numbers => (numbers.Left + numbers.Right) % 10);
foreach (var number in query)
{
sb.Append(number);
}
return sb.ToString();
}
Tried something:
public static string NumAdd(int iOne, int iTwo)
{
char[] strOne = iOne.ToString().ToCharArray();
char[] strTwo = iTwo.ToString().ToCharArray();
string strReturn = string.Empty;
for (int i = 0; i < strOne.Length; i++)
{
int iFirst = 0;
if (int.TryParse(strOne[i].ToString(), out iFirst))
{
int iSecond = 0;
if (int.TryParse(strTwo[i].ToString(), out iSecond))
{
strReturn += ((int)(iFirst + iSecond)).ToString();
}
}
// last one, add the remaining string
if (i + 1 == strOne.Length)
{
strReturn += iTwo.ToString().Substring(i+1);
break;
}
}
return strReturn;
}
You should call it like this:
string strBla = NumAdd(12345, 123456789);
This function works only if the first number is smaller than the second one. But this will help you to know how it is about.
In other words, you want to add two numbers treating the lesser number like it had zeroes to its right until it had the same amount of digits as the greater number.
Sounds like the problem at this point is simply a matter of finding out how much you need to multiply the smaller number by in order to reach the number of digits of the larger number.

Defining Dynamic Array

How can I define a dynamic array in C#?
C# doesn't provide dynamic arrays. Instead, it offers List class which works the same way.
To use lists, write at the top of your file:
using System.Collections.Generic;
And where you want to make use of a list, write (example for strings):
List<string> mylist = new List<string>();
mylist.Add("First string in list");
Take a look at Array.Resize if you need to resize an array.
// Create and initialize a new string array.
String[] myArr = {"The", "quick", "brown", "fox", "jumps",
"over", "the", "lazy", "dog"};
// Resize the array to a bigger size (five elements larger).
Array.Resize(ref myArr, myArr.Length + 5);
// Resize the array to a smaller size (four elements).
Array.Resize(ref myArr, 4);
Alternatively you could use the List class as others have mentioned. Make sure you specify an initial size if you know it ahead of time to keep the list from having to resize itself underneath. See the remarks section of the initial size link.
List<string> dinosaurs = new List<string>(4);
Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
If you need the array from the List, you can use the ToArray() function on the list.
string[] dinos = dinosaurs.ToArray();
C# does provide dynamic arrays and dynamic array manipulation. The base of an array is dynamic and can be modified with a variable. You can find the array tutorial here (https://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx). I have also included code that demonstrates an empty set array and a dynamic array that can be resized at run time.
class Program
{
static void Main(string[] args)
{
int x = Convert.ToInt32(Console.ReadLine());
int y = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(x);
{
int[] dynamicArray1 = { };//empty array
int[] numbers;//another way to declare a variable array as all arrays start as variable size
numbers = new int[x];//setting this array to an unknown variable (will be user input)
for (int tmpInt = 0; tmpInt < x; tmpInt++)//build up the first variable array (numbers)
{
numbers[tmpInt] = tmpInt;
}
Array.Resize(ref numbers,y);// resize to variable input
dynamicArray1 = numbers;//set the empty set array to the numbers array size
for (int z = 0; z < y; z++)//print to the new resize
{
Console.WriteLine(numbers[z].ToString());//print the numbers value
Console.WriteLine(dynamicArray1[z].ToString());//print the empty set value
}
}
Console.Write("Dynamic Arrays ");
var name = Console.ReadLine();
}
}
Actually you can have Dynamic Arrays in C# it's very simple.
keep in mind that the response to your question above is also correct you could declare a
List Generic
The way to Create a Dynamic Array would be to declare your Array for example
string[] dynamicArry1 = { };//notice I did not declare a size for the array
List<String> tmpList = new List<string>();
int i = 1;
for(int tmpInt = 0; tmpInt < 5; tmpInt++)
{
tmpList.Add("Testing, 1.0." + tmpInt + ", 200, 3.4" + tmpInt +"," + DateTime.Now.ToShortDateString());
//dynamicArry1[tmpInt] = new string[] { tmpList[tmpInt].ToCharArray() };
}
dynamicArry1 = tmpList.ToArray();
how about ArrayList ?
If I'm not wrong ArrayList is an implementation of dynamic arrays
Example of Defining Dynamic Array in C#:
Console.WriteLine("Define Array Size? ");
int number = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter numbers:\n");
int[] arr = new int[number];
for (int i = 0; i < number; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < arr.Length; i++ )
{
Console.WriteLine("Array Index: "+i + " AND Array Item: " + arr[i].ToString());
}
Console.ReadKey();
like so
int nSize = 17;
int[] arrn = new int[nSize];
nSize++;
arrn = new int[nSize];

Categories