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 4 years ago.
Improve this question
I have a large group of Hindi numbers which i want to convert into numeric values but i don't know how to convert them . Please suggest me appropriate way to achieve this.
Note Please don't suggest me replace method.
eg. convert this number २०७४ to equivalent to 2074.
I believe this is what you're after but be aware that this code is written by someone who doesn't speak Hindi, read Hindi or know Hindi.
I found the digits on the wikipedia page but I absolutely have no idea what I'm doing.
The google page (which I found by just googling for the individual digits from the original string in the question) seems to indicate the following:
The digits for 0-9 are ०१२३४५६७८९
I clicked on a link and used the last character of the url as the digit
Note that 4 had to be gotten as the second digit of 14, and there seems to be a disambiguity suffix on that link as well
They have unicode code points ranging from 2406 through 2415, in that order
The double digits numbers follow the system to a tee, so it seems to be just a 10-digit numeric system using different code points
But note that there are far too few examples for me to be absolutely certain this holds true for all numbers
If anyone pokes hole in this answer I will take it down but feel free to grab all the code from it first if you think it can be improved.
Also bear in mind that the OP explicitly asked for a non-replace method. The whole thing can probably be written in a oneliner with that but since that doesn't seem to be an acceptable answer then here we are.
With all that said, here's a non-string-replace version that mimicks basic numeric parsing using different symbols:
Note: There's about 7 tons of error-handling that isn't present here, such as empty strings, etc.
public static bool TryParseHindiToInt32(string text, out int value)
{
const int codePointForZero = 2406;
const int codePointForNine = codePointForZero + 9;
int sign = +1;
int index = 0;
if (index < text.Length && text[index] == '-') // todo: hindi minus?
{
index++;
sign = -1;
}
value = 0;
while (index < text.Length)
{
char c = text[index];
if (c < codePointForZero || c > codePointForNine)
{
value = 0;
return false;
}
if ((uint)value > 214748364u)
{
value = 0;
return false;
}
value *= 10;
value += (c - codePointForZero);
index++;
}
value *= sign;
return true;
}
Test:
string digits = "२०७४";
TryParseHindiToInt32(digits, out int i);
Console.WriteLine(i);
Outputs:
2074
Related
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 need to count sum of the numbers found in a string, not digits. For example, there are string = "abc12df34", and the answer must be 46 (12+34), not 10. Also maybe negative numbers for string = "abc10gf-5h1" answer must be 6. I can not understand how to implement this.
RegEx approach:
string input = "abc10gf-5h1";
int result = Regex.Matches(input, "-?[0-9]+").Cast<Match>().Sum(x =>int.Parse(x.Value));
While the above answer is elegant, it's not really something to understand what to do or how to approach the problem. Here is another, more explicit solution.
In words, you iterate through your string, collect digits as long as there are any, if you find a nondigit, your number is finished, you convert the number to integer and sum it up, clear the number string. The same you do if you find the end of the string. On the next found digit you start collecting digits again.
This algorithm will fail on any number larger than than 10 digits in multiple ways (as the other answer will also), but this is just for demonstration anyway.
string input = "abc10gf-5-1h1";
var number = new char[10];
int numberlength = 0;
int pos = 0;
int sum = 0;
while (pos < input.Length)
{
char c = input[pos++];
if (char.IsDigit(c))
{
number[numberlength++]=c;
}
else
{
if (numberlength > 0)
{
sum += int.Parse(new String(number, 0, numberlength));
numberlength = 0;
}
if (c=='-')
number[numberlength++]=c;
}
}
if (numberlength > 0)
sum += int.Parse(new String(number, 0, numberlength));
Console.WriteLine(sum);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
So I am doing an online coding challenge and have come across this issue that has me stumped:
This is my code:
static void Main(String[] args)
{
int noOfRows = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < noOfRows; i++)
{
string odds = "";
string evens = "";
//get the input word from console
string word = Console.ReadLine();
for (int j = 0; j < word.Length; j++)
{
//if the string's current char is even-indexed...
if (word[j] % 2 == 0)
{
evens += word[j];
}
//if the string's current char is odd-indexed...
else if (word[j] % 2 != 0)
{
odds += word[j];
}
}
//print a line with the evens + odds
Console.WriteLine(evens + " " + odds);
}
}
Essentially, the question wants me to get the string from the console line and print the even-indexed characters (starting from index=0) on the left, followed by a space, and then the odd-indexed characters.
So when I try the word 'Hacker', I should see the line printed as "Hce akr". When I debugged it, I saw the code successfully put the letter 'H' on the left (because it is index=0, thus even), and put the letter 'a' on the right (odd index). But then when it got to the letter 'c', instead of going through the first IF path (even index), it skips it and goes to the odd index path, and places it on the right hand side?
The funny thing is when I try the word 'Rank' it works fine and prints the correct statement: "Ra nk", yet other words do not.
Its just bizarre that I'm getting different results.
What am I missing?
word[j] is a character in your string; j is the index you want to check the evenness of.
if (j%2) should provide the correct path. You're using if( word[j] %2) which is doing modular arithmetic on a character, not an index. Most likely using modulo on the ASCII value. Hope this helps.
you want to check if the index is even,yet you compare word[j] % 2 == 0 which is not an index.
what you should do:
if(j % 2 == 0){
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
I tried to make a FizzBuzz code in C# but the error code it gives me is that I'm missing a " , " somewhere but I can't find where to place it
Also I know there are other underlying programs in the code I just need this fixed so I can compile and fix them
using System;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
float i = 0;
if (i != 101)
{
i = i + 1;
float i3 = i / 3;
float i5 = i / 5;
float i15 = i / 15;
string Print = Convert.ToString(i)
else ; if ((i3 %1) > 0)
{
string Hold = ("Fizz");
Print = Hold;
}
else if ((i3 % 1) > 0)
{
string Hold = ("Buzz");
Print = Hold;
}
else if ((i15 % 1) > 0)
{
string Hold = ("FizzBuzz");
Print = Hold;
}
Console.WriteLine(Print)
; Console.WriteLine("Done");
Console.ReadLine();
}
}
}
}
Fizz-Buzz was originally a game designed to teach children division, it worked like this:
The player designated to go first says the number "1", and each player counts one number in turn. However, any number divisible by three is replaced by the word fizz and any divisible by five by the word buzz. Numbers divisible by both become fizz buzz.
So your program has a number of errors, first one is that you use an if where you should be looping. Your first if statement:
if (i != 101)
{ ... }
Really doesn't do anything. You set i=0 in the previous statement, so i will never equal 101. What you need to do instead is a while loop:
float i = 0.0f;
while (i < 101.0f)
{
//Run the program
}
The next problem you have is that it is OK to use i for an iterator, or even x or y if iterating dimensions, but that is really where the single letter variables should stop. Use meaningful names, it makes things much easier:
So, again we need to check if i is divisible by 3, 5, or both. We can do that with simple boolean variables, no need to make things more complicated.
bool divisibleBy3 = i % 3.0f == 0.0f;
bool divisibleBy5 = i % 5.0f == 0.0f;
The next thing you have wrong is that you have ; in strange places, namely you seem to mix them in on separate lines. Try not to do this. There are very few reasons that a ; should not be on the end of every code line, and there should really only be one per line. So this:
string Print = Convert.ToString(i)
else ; if ((i3 %1) > 0)
Is an error because it treats it all as one line until it hits the ;, so your code really becomes:
string Print = Convert.ToString(i) else;
if (...)
And it should be obvious what the problem with that is.
The last problem I'll touch on really isn't a code issue, but a form one. You have a lot of "holding" variables that don't do anything but temporarily put things in places then put them somewhere else, like this:
if ((i3 %1) > 0)
{
string Hold = ("Fizz");
Print = Hold;
}
What is the purpose of Hold? You could just write:
Print = "Fizz";
The ( and ) are also unnecessary. So lets take all these lessons and put them into the Fizz-Buzz program:
int i = 0; //No reason to use float here, int is just fine
while (i <= 100)
{
bool divisibleBy3 = i % 3 == 0;
bool divisibleBy5 = i % 5 == 0;
if (divisibleBy3 && divisibleBy5)
Console.WriteLine("FizzBuzz");
else if (divisibleBy3)
Console.WriteLine("Fizz");
else if (divisibleBy5)
Console.WriteLine("Buzz");
else
Console.WriteLine(i.ToString());
i += 1;
}
Console.WriteLine("Done");
Console.ReadKey(true);
Or, it can be written with a for loop:
for (int i = 0; i <= 100; i++)
{
bool divisibleBy3 = i % 3 == 0;
bool divisibleBy5 = i % 5 == 0;
if (divisibleBy3 && divisibleBy5)
Console.WriteLine("FizzBuzz");
else if (divisibleBy3)
Console.WriteLine("Fizz");
else if (divisibleBy5)
Console.WriteLine("Buzz");
else
Console.WriteLine(i.ToString());
}
Console.WriteLine("Done");
Console.ReadKey(true);
So you can see how giving variables meaningful names, paying attention to indenting/formatting, and understanding of the ; can help you make debugging easier. Clean, well formatted code is easy to read and debug, and giving variables meaningful names means you can tell what the purpose is without having to read through the entire use of the variable.
Note: Some programmers will argue that Fizz-Buzz can be condensed down to 1-3 lines of code. While it is possible, I would argue that it doesn't demonstrate good programming practices. There is a big difference between readable code that can be maintained, and just making something short for the sake of it being short.
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 6 years ago.
Improve this question
In my organization, users must generate a password from numbers only (keypads are used to access), minimum length is 8 numbers. How can I make sure the password the user generats is not too weak (using c# on server procossing password change request), applying the following rule:
3 following numbers (even a part of password) are not sequential or repeated (9451238401 or 543555784)
The regular expression is:
^((?!(?<ch>.)\k<ch>\k<ch>)(?!012|123|234|345|456|567|678|789|890)[0-9]){8,}$
The (?!(?<ch>.)\k<ch>\k<ch>) will check for the same character repeated thrice. Note that for the various contiguous sequences I had to put them in a list of possible sequences, (?!012|123|234|345|456|567|678|789|890). [0-9] is the character that will be accepted as valid. The {8,} is for the minimum length.
If you want a general-purpose approach which tells you the number of repeated, ascending and descending digits:
static void checkStrength(string text, out int maxRepeats, out int maxAscending, out int maxDescending)
{
maxRepeats = 0;
maxAscending = 0;
maxDescending = 0;
int currRepeats = 0;
int currAscending = 0;
int currDescending = 0;
for (int i = 1; i < text.Length; ++i)
{
char curr = text[i];
char prev = text[i-1];
if (curr - prev == -1)
maxDescending = Math.Max(maxDescending, ++currDescending);
else
currDescending = 1;
if (curr - prev == 1)
maxAscending = Math.Max(maxAscending, ++currAscending);
else
currAscending = 1;
if (curr == prev)
maxRepeats = Math.Max(maxRepeats, ++currRepeats);
else
currRepeats = 1;
}
}
You would have to call this and then do what you want with the results:
int maxRepeats, maxAscending, maxDescending;
checkStrength(text, out maxRepeats, out maxAscending, out maxDescending);
if (maxRepeats > REPEAT_LIMIT || maxAscending > ASCENDING_LIMIT || maxDescending > DESCENDING_LIMIT)
{
// ... report error or whatever
}
If you don't need to vary the allowed number of repeated or ascending digits, then xanatos' regex is clearly by far the shortest code. This code is only needed if you need to vary the allowed counts at runtime.
I'm trying to write a program in C# that takes in an int x and decides if it has exactly 7 digits. Right now I'm using x.toString().Length == 7 to check, but I noticed that if the number starts with 0, it automatically gets omitted and I get an incorrect answer (ie the program thinks the input length is less than 7)
Is there a way to fix this? Thanks in advance.
Edit: Sorry I should have mentioned, this was a program to collect and validate the format of ID numbers (so I didn't want something like 0000001 to default to 1) Thanks for the string input suggestion, I think I'm going to try that.
If you want to preserve the input formatting, you must not convert the input to an int. You must store it in a String.
You say your program takes an int. At that point you have already lost. You need to change that interface to accept String inputs.
If you don't care about leading zeros, you're really looking for 7 digits or less. You can check for:
x.toString().Length <= 7
or better:
x < 10000000
Maybe I'm wrong, but to me, 0000001 == 1, and 1 has one digit, not seven. So that's mathematically correct behaviour.
I think you could format it as a string:
int myInt=1;
myInt.ToString("0000000");
prints:
0000001.
so you could do:
if (myInt.ToString("0000000").Length==7)
You can simply write:
int input = 5;
if(input.ToString("0000000").Length == 7)
{
//do your stuff
}
No. It is perfectly valid for a numeric literal to have leading 0s, but a) many languages consider this to be an octal literal, and b) the leading 0s don't actually exist as part of the number. If you need a string then start with a string literal.
You should use string to check length count including 0.
Then I would like to ask "Why do you want to show 0000007? For What?"
You said you're asking for a int, but I suppose you're receiving it as string:
int i = 0;
string number = Console.ReadLine();
if (Int32.TryParse(number, out i))
{
//if (i.ToString().Length == 7) // you can try this too
if (i > 999999 && i < 10000000)
{
Console.WriteLine("Have exactly 7 digits");
}
else
{
Console.WriteLine("Doesn't have exactly 7 digits");
}
}
else
{
Console.WriteLine("Not an Int32 number");
}
This way you try to cast that received number as Int32 and, so, compare its length.
You can let the number be saved as an int with the omitted zeros. but then if you want the number displayed with the zeros then you can use an if statement and a while loop. for example,
Let's assume the values are stored in a numbers array and you need them to be stored as int so you can sort them but displayed as string so you can display with the leading zeros.
int[] numbers = new int[3];
numbers[0] = 001;
numbers[1] = 002;
numbers[2] = 123;
String displayed_Number;
for (int i = 0; i < numbers.Length; i++)
{
displayed_Number = numbers[i].ToString();
if (displayed_Number.Length == 3)
{
listBox.Items.Add(displayed_Number);
}
else if (displayed_Number.Length < 3)
{
while (displayed_Number.Length < 3)
{
displayed_Number = "0" + displayed_Number;
}
listBox.Items.Add(displayed_Number);
}
}
The output is 001 002 123
That way you can maintain the zeros in the numbers when displayed. and they can be stored as int in case you have to store them as int.