Compare a string to a range of integers [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have two integers, say 4 and 11, and I have a string for example Month04
I want to able to compare that string to the range of numbers between 11 and 4.
So in the other ways a loop which has (if Month04.contains(11,10,9,8,7,6,5,4) then
How can I solve that elegantly?
Regards

You can use any() to check if the number exists in the string and Enumerable.Range() to create the numbers list
string month = "Month04";
int num1 = 4;
int num2 = 11;
IEnumerable<int> numbersList = Enumerable.Range(num1, num2 - num1 + 1) ;
if (numbersList.Any(x => month.Contains(x.ToString())))
{
// then
}

I suggest you create a generic method for this:
public static bool CheckNameInRangeOfIntegers(int lowerBound, int upperBound, string inputString)
{
List<int> rangeOfIntegers=Enumerable.Range(lowerBound,(upperBound-lowerBound + 1)).ToList();
return rangeOfIntegers.Any(x=>inputString.Contains(x.ToString()));
}
Example can be called as :
Console.WriteLine(CheckNameInRangeOfIntegers(4,11,"Month4")); // true
Console.WriteLine(CheckNameInRangeOfIntegers(4,11,"Month1")); // false
Please note: Be clear about your scenarios, if you are processing with .Any() followed by a .Contains() then you will be in trouble in some cases, for example, lowerBound = 1, uppeBound=10, and inputString="Month11"

If your all months ends with digits then you can try below,
int startIndex = 4; //I used variables to define starting index and end index
int endIndex = 11;
List<int> numbers = Enumerable.Range(startIndex, (endIndex-startIndex + 1)).ToList();
if (numbers.Any(x => "Month04".EndsWith(x.ToString())))
{
//Your business logic
}

Here's yet another example using the Regex pattern \d+ which will match every digit group in the string (04 in this case). Then we can cast those matches to integers, and finally, Linq expressions Intersect() and .Any() will return true if any matching values exist between the two integer collections.
string s = "Month04";
Regex pattern = new Regex(#"\d+");
var numbersInString = pattern.Matches(s).Cast<Match>().Select(x = int.Parse(x.Value));
int lowerBound = 4;
int upperBound = 11;
var range = Enumerable.Range(lowerBound, upperBound - lowerBound + 1);
if (numbersInString.Intersect(range).Any())
{
//Match
}

This way:
int[] numbers = new int[] { 11, 10, 9, 8, 7, 6, 5, 4 };
string str = "Month04";
int number = int.Parse(str.Replace("Month", ""));
if (numbers.Contains(number))
{
Console.WriteLine("YEEE!");
}

Related

Have N elemnts of sum of a list and repeat until the end of the list [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm facing a problem when trying to play with C# list. Currently I have a list of integer. And I'm looking for a way to sum up every 5 integer, until the end of the list.
For example I have a list like this:
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
How to sum up every N elements (let's say 5) in the list and become:
[ 15, 40 ]
FYI, the list consist of hundred and thousand int elements.
Thanks.
Since noone's mentioned the simple way yet...
Note that if the input is not divisible by the group size, any extra elements will be ignored. For example, if the input is 11 elements, and the group size is 5, this will give 2 sums of 5 elements and then ignore the 11th input element.
public static int[] SumEvery(int[] input, int groupSize)
{
// The number of groups we have
int numGroups = input.Length / groupSize;
int[] result = new int[numGroups];
// For each group of numbers...
for (int group = 0; group < numGroups; group++)
{
// ... loop through each number in that group, adding to the sum ...
int sum = 0;
for (int i = 0; i < groupSize; i++)
{
sum += input[group * groupSize + i];
}
// ... then store that sum in our array of results
result[group] = sum;
}
return result;
}
int[] input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] result = SumEvery(input, 5);
If you want to stream the results as an IEnumerable<int>, rather than collecting them all into an array, then:
public static IEnumerable<int> SumEvery(int[] input, int groupSize)
{
int numGroups = input.Length / groupSize;
for (int group = 0; group < numGroups; group++)
{
int sum = 0;
for (int i = 0; i < groupSize; i++)
{
sum += input[group * groupSize + i];
}
yield return sum;
}
}
You could do this with a bit of Linq
var ints = new []{1,2,3,4,5,6,7,8,9,10};
var result = ints.Select((x,i) => new{Num = x,Index = i}) // Project to a list with the index and number
.GroupBy (i => i.Index/5) // group by the int division by 5
.Select(g => g.Sum(a => a.Num)); // sum the numbers in each group
Live example: https://dotnetfiddle.net/BabP5N
Note that is is by far the least efficient way - and with a large data set will not perform well. But for a small dataset will work fine. This code is possibly the clearest interpretation of the problem.

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)

Reverse Binary Numbers 4/8 test succeds [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
My task is to write a program for reversing numbers in binary. For instance, the binary representation of 13 is 1101, and reversing it gives 1011, which corresponds to number 11. Where the input contains a single line with an integer N, 1≤N≤1000000000.
I have to pass 8 tests, so far I've only passed 4/8. An input could be 13 where the expected is 11.
Sample input
13
Sample output
11
To clarify I do not get the output from the tests, only the results of them.
Any thoughts on how I can update the code?
public class Reversebinary
{
public static void Main()
{
//Convert Decimal to binary
int num;
string binary, reversed;
//Read integer value from console
num = int.Parse(Console.ReadLine());
//Console.WriteLine(num);
if (num > 1 && num < 1000000000)
{
//Convert the integer value to string binary
binary = Convert.ToString(num, 2);
//reverse string binary
reversed = reverseString(binary);
//Console.WriteLine("binary: " + binary);
//Convert reversed string binary to int32 and print out
Console.WriteLine(Convert.ToInt32(reversed, 2));
}
else
Console.WriteLine("Number is not between 1 or 1000000000");
}
static string reverseString(string str)
{
return new string(str.Reverse().ToArray());
}
}
EDIT1: clarification of the tests.
EDIT2: please understand I just want your opinion on the code so I can alter to it to succed the tests. I am not asking for you to provide me code.
EDIT3: Problem solved, I passed the tests after including greater/lesser or equals operator. Thanks for all your inputs.
At least, numbers are in 1≤N≤1000000000 and you are not considering 1 and 1000000000.
if (num >= 1 && num <= 1000000000)
{
//Convert the integer value to string binary
binary = Convert.ToString(num, 2);
//reverse string binary
reversed = reverseString(binary);
//Console.WriteLine("binary: " + binary);
//Convert reversed string binary to int32 and print out
Console.WriteLine(Convert.ToInt32(reversed, 2));
}
Also, you can use int.TryParse instead of int.Parse to avoid exceptions.
So your if condition should look like this
int num = 0;
if (int.TryParse(Console.ReadLine(), out num) && num >= 1 && num <= 1000000000)
{
...
}
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Reversebinary
{
class Reversebinary
{
static byte[] reverseBinary = new byte[] {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };
static void Main(string[] args)
{
//Convert Decimal to binary
int num;
int reversed;
//Read integer value from console
num = int.Parse(Console.ReadLine());
if (num >= 0 && num <= 15)
{
//reverse string binary
reversed = reverseBinary[num];
Console.WriteLine(reversed.ToString("x2"));
}
else
Console.WriteLine("Number is not between 0 and 15");
}
}
}
​

Auto Increment the number [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have a problem regarding create squence of number, but i face some problem like given below. I want a number Format Like UK 0000, there are some conditon applied:
It start from UK 0001
After reaches 9 record then 10th record is like UK 0010
If all digit fill Like UK 9999 then next record show like UK 10000 and so on
Please help me for this, It can use any platform like
jquery
c#
sql etc...
in c#, you can do this
string s = "UK";
int counter = 0;
if (counter < 10000)
result = s + counter++.ToString().PadLeft(4, '0');
else
result = s + counter++.ToString();
Output: UK0000,UK0001,UK0002......
IEnumerable<int> numbers= Enumerable.Range(1, 10000).Select(x=>x);
var list = squares.Select(numbers => "UK" + numbers.ToString("0000")).ToList();
try
List<string> lista = new List<string>();
for (int num = 0; num < 12000; num++)
{
lista.Add(string.Format("UK {0}", num > 999 ? num.ToString() : num.ToString().PadLeft(4, '0')));
}
USING JQUERY - Here is a working example : jsfiddle
Jquery :
$(document).ready(function () {
var prefix = "UK";
var max = 4;
var limit = 10004;
for (var i = 0; i < limit - 1; i++) {
var a = prefix + pad(i, max);
$("#msg").append(a);
$("#msg").append("<br/>");
}
function pad(str, max) {
str = str.toString();
return str.length < max ? pad("0" + str, max) : str;
}
});

list of ints transform to array of integers [duplicate]

This question already has answers here:
How to split a number into individual digits in c#? [duplicate]
(6 answers)
Closed 9 years ago.
I'm getting integeres to my controller as 123456 in one variable.
Now I want to transform each number to separated from other with comma between as array of numbers as { 1, 2, 3, 4, 5 }.
Try this
var integers = "123456";
var enumOfInts = integers.ToCharArray().Select(x => Char.GetNumericValue(x));
try this:
int[] array = new int["123456".ToArray().Count()];
int i = 0;
foreach (var item in "123456".ToArray())
{
array[i++] = int.Parse(item.ToString());
}
or
int[] array = "123456".ToArray().Select(data=>(int)data).ToArray();
{
string s = "1234567890";
var lst = new List<int>();
for (int n = 0; n < s.Length; n++)
{
int x;
if (int.TryParse(s[n].ToString(), out x))
lst.Add(x);
}
int[] arr = lst.ToArray();
}
If you are getting parameter as string then
The Linq Way :
string str_num = "123456"
var arrayOfInts = str_num.ToCharArray().Select(x => x - 48).ToArray();
for the above Linq expression it has been assumed that all character are between 48 & 57
Non Linq Way :
int[] GetIntArray(string str_num)
{
int num = Int32.Parse(str_num);
List<int> listOfInts = new List<int>();
while(num > 0)
{
listOfInts.Add(num % 10);
num = num / 10;
}
listOfInts.Reverse();
return listOfInts.ToArray();
}
Solution extended from : How to split a number into individual digits in c#?

Categories