Reverse polish notation C# don't work correctly - c#

I write an rpn, with a struktogram.
Newest Problem: It is'nt work correctly now.
If input string is "5 + ((1 + 2) * 4) - 3"
My output is:
5 1 2 + 4 * 3 - +
I have to got this result:
5 1 2 + 4 * + 3 -
Edited the source
*That was the original problem, but helped me, and now the original mistakes fixed: *,
At the debug when the loop or
int i = 12, the c value is 0\0 or something else
and this value is added to output (name: formula) string as a '(' bracket. And I don't know why.
And the last '-' operation symbol, don't added to (or not look) at the end of output string (formula)
I misgave this problem cause by the '('.
I tried the program with other string input value, but always put an '(' to my string, and I don't know why... I saw that It was independt about the numbers of bracket. Always only one '(' add to my string...*)
Yes, in english LengyelFormula = rpn (it is hungarian)*
static void Main(string[] args)
{
String str = "5 + ( ( 1 + 2 ) * 4 ) −3";
String result=LengyelFormaKonvertalas(str);
Console.WriteLine(result.ToString());
Console.ReadLine();
}
static String LengyelFormaKonvertalas(String input) // this is the rpn method
{
Stack stack = new Stack();
String str = input.Replace(" ",string.Empty);
StringBuilder formula = new StringBuilder();
for (int i = 0; i < str.Length; i++)
{
char x=str[i];
if (x == '(')
stack.Push(x);
else if (IsOperandus(x)) // is it operand
{
formula.Append(x);
}
else if (IsOperator(x)) // is it operation
{
if (stack.Count>0 && (char)stack.Peek()!='(' && Prior(x)<=Prior((char)stack.Peek()) )
{
char y = (char)stack.Pop();
formula.Append(y);
}
if (stack.Count > 0 && (char)stack.Peek() != '(' && Prior(x) < Prior((char)stack.Peek()))
{
char y = (char)stack.Pop();
formula.Append(y);
}
stack.Push(x);
}
else
{
char y=(char)stack.Pop();
if (y!='(')
{
formula.Append(y);
}
}
}
while (stack.Count>0)
{
char c = (char)stack.Pop();
formula.Append(c);
}
return formula.ToString();
}
static bool IsOperator(char c)
{
return (c=='-'|| c=='+' || c=='*' || c=='/');
}
static bool IsOperandus(char c)
{
return (c>='0' && c<='9' || c=='.');
}
static int Prior(char c)
{
switch (c)
{
case '=':
return 1;
case '+':
return 2;
case '-':
return 2;
case '*':
return 3;
case '/':
return 3;
case '^':
return 4;
default:
throw new ArgumentException("Rossz paraméter");
}
}
}

using System;
using System.Collections.Generic;
using System.Text;
class Sample {
static void Main(string[] args){
String str = "5 + ( ( 1 + 2 ) * 4 ) -3";
String result=LengyelFormaKonvertalas(str);
Console.WriteLine(result);
Console.ReadLine();
}
static String LengyelFormaKonvertalas(String input){
Stack<char> stack = new Stack<char>();
String str = input.Replace(" ", string.Empty);
StringBuilder formula = new StringBuilder();
for (int i = 0; i < str.Length; i++){
char x=str[i];
if (x == '(')
stack.Push(x);
else if (x == ')'){
while(stack.Count>0 && stack.Peek() != '(')
formula.Append(stack.Pop());
stack.Pop();
} else if (IsOperandus(x)){
formula.Append(x);
} else if (IsOperator(x)) {
while(stack.Count>0 && stack.Peek() != '(' && Prior(x)<=Prior(stack.Peek()) )
formula.Append(stack.Pop());
stack.Push(x);
}
else {
char y= stack.Pop();
if (y!='(')
formula.Append(y);
}
}
while (stack.Count>0) {
formula.Append(stack.Pop());
}
return formula.ToString();
}
static bool IsOperator(char c){
return (c=='-'|| c=='+' || c=='*' || c=='/');
}
static bool IsOperandus(char c){
return (c>='0' && c<='9' || c=='.');
}
static int Prior(char c){
switch (c){
case '=':
return 1;
case '+':
return 2;
case '-':
return 2;
case '*':
return 3;
case '/':
return 3;
case '^':
return 4;
default:
throw new ArgumentException("Rossz parameter");
}
}
}

In IsOperator, you check c == '-'.
But in the string, you write −3.
− isn't the same character than -
I don't know about Polish stuff so maybe I'm missing something, but that's why no '-' operator is printed, it fails the IsOperator check and goes into the else clause, which doesn't add it to formula.

When you get a ), you should pop all operators and add them to your formula until you reach a (, and pop that '(' as well.
When you get an operator, you should only pop the stack and add this operator to the formula if its priority is greater than or equal to that of x. Your second check is redundant because it is already covered by the first.
As a general rule: try your program with some simple inputs like 1+2+3, 1+2-3, 1*2+3 and 1+2*3 and see if you get the right result. Testing systematically like that should help you find errors faster.

Related

Getting all unique permutations of a set filled with 2 different characters w/ limits [duplicate]

This came up while talking to a friend and I thought I'd ask here since it's an interesting problem and would like to see other people's solutions.
The task is to write a function Brackets(int n) that prints all combinations of well-formed brackets from 1...n. For Brackets(3) the output would be
()
(()) ()()
((())) (()()) (())() ()(()) ()()()
Took a crack at it.. C# also.
public void Brackets(int n) {
for (int i = 1; i <= n; i++) {
Brackets("", 0, 0, i);
}
}
private void Brackets(string output, int open, int close, int pairs) {
if((open==pairs)&&(close==pairs)) {
Console.WriteLine(output);
} else {
if(open<pairs)
Brackets(output + "(", open+1, close, pairs);
if(close<open)
Brackets(output + ")", open, close+1, pairs);
}
}
The recursion is taking advantage of the fact that you can never add more opening brackets than the desired number of pairs, and you can never add more closing brackets than opening brackets..
Python version of the first voted answer.
def foo(output, open, close, pairs):
if open == pairs and close == pairs:
print output
else:
if open<pairs:
foo(output+'(', open+1, close, pairs)
if close<open:
foo(output+')', open, close+1, pairs)
foo('', 0, 0, 3)
The number of possible combinations is the Catalan number of N pairs C(n).
This problem was discussed on the joelonsoftware.com forums pretty exentsively including iterative, recursive and iterative/bitshifting solutions. Some pretty cool stuff there.
Here is a quick recursive solution suggested on the forums in C#:
C#
public void Brackets(int pairs) {
if (pairs > 1) Brackets(pairs - 1);
char[] output = new char[2 * pairs];
output[0] = '(';
output[1] = ')';
foo(output, 1, pairs - 1, pairs, pairs);
Console.writeLine();
}
public void foo(char[] output, int index, int open, int close,
int pairs) {
int i;
if (index == 2 * pairs) {
for (i = 0; i < 2 * pairs; i++)
Console.write(output[i]);
Console.write('\n');
return;
}
if (open != 0) {
output[index] = '(';
foo(output, index + 1, open - 1, close, pairs);
}
if ((close != 0) && (pairs - close + 1 <= pairs - open)) {
output[index] = ')';
foo(output, index + 1, open, close - 1, pairs);
}
return;
}
Brackets(3);
Output:
()
(()) ()()
((())) (()()) (())() ()(()) ()()()
F#:
Here is a solution that, unlike my previous solution, I believe may be correct. Also, it is more efficient.
#light
let brackets2 n =
let result = new System.Collections.Generic.List<_>()
let a = Array.create (n*2) '_'
let rec helper l r diff i =
if l=0 && r=0 then
result.Add(new string(a))
else
if l > 0 then
a.[i] <- '('
helper (l-1) r (diff+1) (i+1)
if diff > 0 then
a.[i] <- ')'
helper l (r-1) (diff-1) (i+1)
helper n n 0 0
result
Example:
(brackets2 4) |> Seq.iter (printfn "%s")
(*
(((())))
((()()))
((())())
((()))()
(()(()))
(()()())
(()())()
(())(())
(())()()
()((()))
()(()())
()(())()
()()(())
()()()()
*)
Here's another F# solution, favoring elegance over efficiency, although memoization would probably lead to a relatively well performing variant.
let rec parens = function
| 0 -> [""]
| n -> [for k in 0 .. n-1 do
for p1 in parens k do
for p2 in parens (n-k-1) ->
sprintf "(%s)%s" p1 p2]
Again, this only yields a list of those strings with exactly n pairs of parens (rather than at most n), but it's easy to wrap it.
F#:
UPDATE: this answer is wrong. My N=4 misses, for example "(())(())". (Do you see why?) I will post a correct (and more efficient) algorithm shortly.
(Shame on all you up-voters, for not catching me! :) )
Inefficient, but short and simple.
(Note that it only prints the 'nth' line; call in a loop from 1..n to get the output asked for by the question.)
#light
let rec brackets n =
if n = 1 then
["()"]
else
[for s in brackets (n-1) do
yield "()" ^ s
yield "(" ^ s ^ ")"
yield s ^ "()"]
Example:
Set.of_list (brackets 4) |> Set.iter (printfn "%s")
(*
(((())))
((()()))
((())())
((()))()
(()(()))
(()()())
(()())()
(())()()
()((()))
()(()())
()(())()
()()(())
()()()()
*)
Simple solution in C++:
#include <iostream>
#include <string>
void brackets(string output, int open, int close, int pairs)
{
if(open == pairs && close == pairs)
cout << output << endl;
else
{
if(open<pairs)
brackets(output+"(",open+1,close,pairs);
if(close<open)
brackets(output+")",open,close+1,pairs);
}
}
int main()
{
for(int i=1;i<=3;i++)
{
cout << "Combination for i = " << i << endl;
brackets("",0,0,i);
}
}
Output:
Combination for i = 1
()
Combination for i = 2
(())
()()
Combination for i = 3
((()))
(()())
(())()
()(())
()()()
Damn - everyone beat me to it, but I have a nice working example :)
http://www.fiveminuteargument.com/so-727707
The key is identifying the rules, which are actually quite simple:
Build the string char-by-char
At a given point in the string
if brackets in string so far balance (includes empty str), add an open bracket and recurse
if all open brackets have been used, add a close bracket and recurse
otherwise, recurse twice, once for each type of bracket
Stop when you get to the end :-)
Common Lisp:
This doesn't print them, but does produce a list of lists of all the possible structures. My method is a bit different from the others'. It restructures the solutions to brackets(n - 1) such that they become brackets(n). My solution isn't tail recursive, but it could be made so with a little work.
Code
(defun brackets (n)
(if (= 1 n)
'((()))
(loop for el in (brackets (1- n))
when (cdr el)
collect (cons (list (car el)) (cdr el))
collect (list el)
collect (cons '() el))))
Here is a solution in C++. The main idea that I use is that I take the output from the previous i (where i is the number of bracket pairs), and feed that as input to the next i. Then, for each string in the input, we put a bracket pair at each location in the string. New strings are added to a set in order to eliminate duplicates.
#include <iostream>
#include <set>
using namespace std;
void brackets( int n );
void brackets_aux( int x, const set<string>& input_set, set<string>& output_set );
int main() {
int n;
cout << "Enter n: ";
cin >> n;
brackets(n);
return 0;
}
void brackets( int n ) {
set<string>* set1 = new set<string>;
set<string>* set2;
for( int i = 1; i <= n; i++ ) {
set2 = new set<string>;
brackets_aux( i, *set1, *set2 );
delete set1;
set1 = set2;
}
}
void brackets_aux( int x, const set<string>& input_set, set<string>& output_set ) {
// Build set of bracket strings to print
if( x == 1 ) {
output_set.insert( "()" );
}
else {
// For each input string, generate the output strings when inserting a bracket pair
for( set<string>::iterator s = input_set.begin(); s != input_set.end(); s++ ) {
// For each location in the string, insert bracket pair before location if valid
for( unsigned int i = 0; i < s->size(); i++ ) {
string s2 = *s;
s2.insert( i, "()" );
output_set.insert( s2 );
}
output_set.insert( *s + "()" );
}
}
// Print them
for( set<string>::iterator i = output_set.begin(); i != output_set.end(); i++ ) {
cout << *i << " ";
}
cout << endl;
}
A simple F#/OCaml solution :
let total_bracket n =
let rec aux acc = function
| 0, 0 -> print_string (acc ^ "\n")
| 0, n -> aux (acc ^ ")") (0, n-1)
| n, 0 -> aux (acc ^ "(") (n-1, 1)
| n, c ->
aux (acc ^ "(") (n-1, c+1);
aux (acc ^ ")") (n, c-1)
in
aux "" (n, 0)
Provider C# version based on recursive backtracking algorithm, hope it's helpful.
public List<String> generateParenthesis(int n) {
List<String> result = new LinkedList<String>();
Generate("", 0, 0, n, result);
return result;
}
private void Generate(String s, int l, int r, int n, List<String> result){
if(l == n && r == n){
result.add(s);
return;
}
if(l<n){
Generate(s+"(", l+1, r, n, result);
}
if(r < l)
Generate(s+")", l , r+1, n, result);
}}
def #memo brackets ( n )
=> [] if n == 0 else around( n ) ++ pre( n ) ++ post( n ) ++ [ "()" * n) ]
def #memo pre ( n )
=> map ( ( s ) => "()" ++ s, pre ( n - 1 ) ++ around ( n - 1 ) ) if n > 2 else []
def #memo post ( n )
=> map ( ( s ) => s ++ "()", post ( n - 1 ) ++ around ( n - 1 ) ) if n > 2 else []
def #memo around ( n )
=> map ( ( s ) => "(" ++ s ++ ")", brackets( n - 1 ) )
(kin, which is something like an actor model based linear python with traits. I haven't got round to implementing #memo but the above works without that optimisation)
Haskell:
I tried to come up with an elegant list monad-y way to this:
import Control.Applicative
brackets :: Int -> [String]
brackets n = f 0 0 where
f pos depth =
if pos < 2*n
then open <|> close
else stop where
-- Add an open bracket if we can
open =
if depth < 2*n - pos
then ('(' :) <$> f (pos+1) (depth+1)
else empty
-- Add a closing bracket if we can
close =
if depth > 0
then (')' :) <$> f (pos+1) (depth-1)
else empty
-- Stop adding text. We have 2*n characters now.
stop = pure ""
main = readLn >>= putStr . unlines . brackets
why cant this is as simple as this, this idea is quite simple
brackets(n) --> '()' + brackets(n-1) 0
'(' + brackets(n-1) + ')' 0
brackets(n-1) + '()'
where 0 is the concatenation operation above
public static Set<String> brackets(int n) {
if(n == 1){
Set<String> s = new HashSet<String>();
s.add("()");
return s;
}else{
Set<String> s1 = new HashSet<String>();
Set<String> s2 = brackets(n - 1);
for(Iterator<String> it = s2.iterator(); it.hasNext();){
String s = it.next();
s1.add("()" + s);
s1.add("(" + s + ")");
s1.add(s + "()");
}
s2.clear();
s2 = null;
return s1;
}
}
Groovy version based on markt's elegant c# solution above. Dynamically checking open and close (information was repeated in output and args) as well as removing a couple of extraneous logic checks.
3.times{
println bracks(it + 1)
}
def bracks(pairs, output=""){
def open = output.count('(')
def close = output.count(')')
if (close == pairs) {
print "$output "
}
else {
if (open < pairs) bracks(pairs, "$output(")
if (close < open) bracks(pairs, "$output)")
}
""
}
Not the most elegant solution, but this was how I did it in C++ (Visual Studio 2008). Leveraging the STL set to eliminate duplicates, I just naively insert new () pairs into each string index in every string from the previous generation, then recurse.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <set>
using namespace System;
using namespace std;
typedef set<string> StrSet;
void ExpandSet( StrSet &Results, int Curr, int Max )
{
if (Curr < Max)
{
StrSet NewResults;
for (StrSet::iterator it = Results.begin(); it != Results.end(); ++it)
{
for (unsigned int stri=0; stri < (*it).length(); stri++)
{
string NewStr( *it );
NewResults.insert( NewStr.insert( stri, string("()") ) );
}
}
ExpandSet( NewResults, Curr+1, Max );
Results = NewResults;
}
}
int main(array<System::String ^> ^args)
{
int ParenCount = 0;
cout << "Enter the parens to balance:" << endl;
cin >> ParenCount;
StrSet Results;
Results.insert( string("()") );
ExpandSet(Results, 1, ParenCount);
cout << Results.size() << ": Total # of results for " << ParenCount << " parens:" << endl;
for (StrSet::iterator it = Results.begin(); it != Results.end(); ++it)
{
cout << *it << endl;
}
return 0;
}
//C program to print all possible n pairs of balanced parentheses
#include<stdio.h>
void fn(int p,int n,int o,int c);
void main()
{
int n;
printf("\nEnter n:");
scanf("%d",&n);
if(n>0)
fn(0,n,0,0);
}
void fn(int p,int n,into,int c)
{
static char str[100];
if(c==n)
{
printf("%s\n",str);
return;
}
else
{
if(o>c)
{
str[p]='}';
fn(p+1,n,o,c+1);
}
if(o<n)
{
str[p]='{';
fn(p+1,n;o+1,c);
}
}
}
ruby version:
def foo output, open, close, pairs
if open == pairs and close == pairs
p output
else
foo(output + '(', open+1, close, pairs) if open < pairs
foo(output + ')', open, close+1, pairs) if close < open
end
end
foo('', 0, 0, 3)
validParentheses: function validParentheses(n) {
if(n === 1) {
return ['()'];
}
var prevParentheses = validParentheses(n-1);
var list = {};
prevParentheses.forEach(function(item) {
list['(' + item + ')'] = null;
list['()' + item] = null;
list[item + '()'] = null;
});
return Object.keys(list);
}
public static void printAllValidBracePermutations(int size) {
printAllValidBracePermutations_internal("", 0, 2 * size);
}
private static void printAllValidBracePermutations_internal(String str, int bal, int len) {
if (len == 0) System.out.println(str);
else if (len > 0) {
if (bal <= len / 2) printAllValidBracePermutations_internal(str + "{", bal + 1, len - 1);
if (bal > 0) printAllValidBracePermutations_internal(str + "}", bal - 1, len - 1);
}
}
Another inefficient but elegant answer =>
public static Set<String> permuteParenthesis1(int num)
{
Set<String> result=new HashSet<String>();
if(num==0)//base case
{
result.add("");
return result;
}
else
{
Set<String> temp=permuteParenthesis1(num-1); // storing result from previous result.
for(String str : temp)
{
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)=='(')
{
result.add(insertParen(str, i)); // addinng `()` after every left parenthesis.
}
}
result.add("()"+str); // adding "()" to the beginning.
}
}
return result;
}
public static String insertParen(String str,int leftindex)
{
String left=str.substring(0, leftindex+1);
String right=str.substring(leftindex+1);
return left+"()"+right;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(permuteParenthesis1(3));
}
An attempt with memoization:
void push_strings(int i, int j ,vector<vector <string>> &T){
for (int k=0; k< T[j].size(); ++k){
for (int l=0; l< T[i - 1 - j].size(); ++l){
string s = "(" + T[j][k] + ")" + T[i-1 - j][l];
T[i].push_back(s);
}
}
}
vector<string> generateParenthesis(int n) {
vector<vector <string>> T(n+10);
T[0] = {""};
for (int i =1; i <=n; ++i){
for(int j=0; j<i; ++j){
push_strings(i,j, T);
}
}
return T[n];
}
def form_brackets(n: int) -> set:
combinations = set()
if n == 1:
combinations.add('()')
else:
previous_sets = form_brackets(n - 1)
for previous_set in previous_sets:
for i, c in enumerate(previous_set):
temp_string = "{}(){}".format(previous_set[:i+1], previous_set[i+1:])
combinations.add(temp_string)
return combinations
void function(int n, string str, int open, int close)
{
if(open>n/2 || close>open)
return;
if(open==close && open+close == n)
{
cout<<" "<<str<<endl;
return;
}
function(n, str+"(", open+1, close);
function(n, str+")", open, close+1);
}
Caller - function(2*brackets, str, 0, 0);
I was asked this question in an interview today.
I always skipped this question in Cracking The Coding because I thought it is a silly question for an interview. The interviewer didn't share my opinion though.
Below is the solution that I could come up with in the interview. The interviewer was looking at the more performant method that is already given above. He passed me though for this solution.
//This method is recursive. It simply returns all the possible arrangements by going down
//and building all possible combinations of parenthesis arrangements by starting from "()"
//Using only "()" for n == 1, it puts one "()" before, one "()" after and one "()" around
//each paren string returned from the call stack below. Since, we are adding to a set, the
//set ensure that any combination is not repeated.
private HashSet<string> GetParens(int num)
{
//If num < 1, return null.
if (num < 1) return null;
//If num == 1, there is only valid combination. Return that.
if (num == 1) return new HashSet<string> {"()"};
//Calling myself, by subtracting 1 from the input to get valid combinations for 1 less
//pair.
var parensNumMinusOne = GetParens(num - 1);
//Initializing a set which will hold all the valid paren combinations.
var returnSet = new HashSet<string>();
//Now generating combinations by using all n - 1 valid paren combinations one by one.
foreach (var paren in parensNumMinusOne)
{
//Putting "()" before the valid paren string...
returnSet.Add("()" + paren);
//Putting "()" after the valid paren string...
returnSet.Add(paren + "()");
//Putting paren pair around the valid paren string...
returnSet.Add("(" + paren + ")");
}
return returnSet;
}
The space complexity of other more performant solution is O(1) but for this one is O(Cn), where Cn is Catalan Number.
The time complexity of this code is same as the other high performant solution, which is same as O(Cn).
In javascript / nodejs.
The program was originally meant to answer the Ultimate Question, but it is just perfect to enumerate the valid brackets combinations.
function* life(universe){
if( !universe ) yield '';
for( let everything = 1 ; everything <= universe ; ++everything )
for( let meaning of life(everything - 1) )
for( let question of life(universe - everything) )
yield question + '(' + meaning + ')';
}
let love = 5;
let answer = [...life(love)].length;
console.log(answer);
function brackets(n){
for( k = 1 ; k <= n ; k++ ){
console.log(...life(k));
}
}
brackets(5);
public class Solution {
public IList<string> GenerateParenthesis(int n) {
List<string> combinations = new List<string>();
generateAll(new char[2 * n], 0, combinations);
return combinations;
}
public void generateAll(char[] current, int pos, List<string> result) {
if (pos == current.Length) {
if (valid(current))
result.Add(new string(current));
} else {
current[pos] = '(';
generateAll(current, pos+1, result);
current[pos] = ')';
generateAll(current, pos+1, result);
}
}
public bool valid(char[] current) {
int balance = 0;
foreach (char c in current) {
if (c == '(')
balance++;
else balance--;
if (balance < 0)
return false;
}
return (balance == 0);
}
}
Another Solution to handle this issue.
correct string: (){}[]
incorrect string: ([{)]}
private static boolean isEqualBracket(String str) {
Stack stack = new Stack();
if (str != null && str.length() > 0) {
for (int i = 0; i < str.length(); i++) {
char nextChar = str.charAt(i);
if (nextChar == '(' || nextChar == '{' || nextChar == '[') {
stack.push(nextChar);
} else if (nextChar == ')' || nextChar == '}' || nextChar == ']') {
char startChar = stack.peek().toString().charAt(0);
if ((startChar == '(' && nextChar == ')') || (startChar == '{' && nextChar == '}') || (startChar == '[' && nextChar == ']')) {
stack.pop();
} else {
return false;
}
} else {
return false;
}
}
} else {
return false;
}
return stack.empty();
}
In C#
public static void CombiParentheses(int open, int close, StringBuilder str)
{
if (open == 0 && close == 0)
{
Console.WriteLine(str.ToString());
}
if (open > 0) //when you open a new parentheses, then you have to close one parentheses to balance it out.
{
CombiParentheses(open - 1, close + 1, str.Append("{"));
}
if (close > 0)
{
CombiParentheses(open , close - 1, str.Append("}"));
}
}

Improving a double conversion method

I currently have the following 2 methods:
public static Point[] PolygonFromFile(string file)
{
string[] GBfile = File.ReadAllLines(file);
// remove unnecessary data from first 2 lines, never contains any polygon data
GBfile[0] = string.Empty;
GBfile[1] = string.Empty;
const string delim = " ";
List<string> points = (from s in GBfile where !string.IsNullOrEmpty(s) from i in s.Split(delim.ToCharArray()) where !string.IsNullOrEmpty(i) && i != "END" select i).ToList();
List<Point> polygon = new List<Point>();
for (int i = 0; i < points.Count / 2; i++)
{
polygon.Add(new Point
{
X = PointParse(points[i]),
Y = PointParse(points[i + 1])
});
}
return polygon.ToArray();
}
private static double PointParse(string value)
{
string[] parsed = value.Split("E".ToCharArray());
char function = '\0';
bool met = false;
foreach (char c in parsed[1])
{
if (c == '-' || c == '+')
{
function = c;
break;
}
}
var splitMultiplier = parsed[1].Split(function);
double decimalPlaces = Convert.ToDouble(splitMultiplier[1]);
if (decimalPlaces == 0) return Convert.ToDouble(parsed[0]);
switch (function)
{
case '+':
return Convert.ToDouble(parsed[0]) * Math.Pow(10, decimalPlaces);
case '-':
return Convert.ToDouble(parsed[0]) / Math.Pow(10, decimalPlaces);
}
return 0;
}
That will convert a value such as 5.807600E-02 to the true value of 0.058076.
I feel like this is an extremely verbose way of achieving what I need to, is there a function in C# to achieve this or do I need to go through the above process to convert the given value to the necessary one?
.NET can parse these values on its own
Double.Parse("5.807600E-02");
will return the value 0.058076 as a double.
What about this?
double d = Double.Parse("1.2345E-03", System.Globalization.NumberStyles.Float);
You can use parse function. Try this.
decimal d = Decimal.Parse("5.807600E-02",System.Globalization.NumberStyles.Float);

Method in C# to return the immediate text character of a given character

How can I implement a function in c# that return the immediate text character of a given text character. The characters should be in alphabetic order.
Example: given the character "C" the method should return the character "D".
char c = 'C';
char i = (char)(c + 1);
System.Diagnostics.Debug.WriteLine(i);
It will output 'D' to the Debug Output window.
Here's a method that should do what you want. There is no checking for non-alpha characters though.
public static string ToNextAlpha(string str)
{
if (str == null)
{
throw new ArgumentNullException("str");
// Or you can just return "a";
}
var end = new StringBuilder();
for (int index = str.Length - 1; index >= 0; index--)
{
char c = str[index];
bool isZed = c == 'z' || c == 'Z';
c = (char)(isZed ? c - 25 : c + 1);
end.Insert(0, c);
if (!isZed)
{
return str.Substring(0, index) + end;
}
}
return "a" + end;
}
Note: This will turn "zz" into "aaa" and "ZZ" into "aAA". If you want to prepend an upper case "A" just change the last line with whatever logic you need.
I think I have found the solution:
public static string GetNextLetter(string letter = null)
{
if (IsStringNullOrEmpty(letter))
return "A";
char lastLetter = letter.Last();
if (lastLetter.ToString() == "Z")
return GetNextLetter(RemoveLastCharacter(letter)) + "A";
else
return RemoveLastCharacter(letter) + (char)(lastLetter + 1);
}
Any better solutions are welcome.

Increment Of Variable in another way in c# win. form

I am inventing an algorithm in which i have created a new number which is "z" (not actually z) and i am using it with the old numbers (0123456789) and my new series of number looks like this (0123456789z) but the problem here is that how to write a program that gives "19 + 1" as "z" and "z + 1" as "20".
Try something like this, though you'd have to implement additional coding for parameter checking and incrementing the second to last character if the last character reaches 0.
This is the basic logic:
private const string DIGITS = "0123456789z";
static void Main(string[] args)
{
Console.WriteLine(NextValue("9"));
Console.ReadKey();
}
private static string NextValue(string value)
{
char nextChar = '\0';
if(!string.IsNullOrEmpty(value))
{
char lastChar = value[value.Length - 1];
int nextCharIndex = DIGITS.IndexOf(lastChar) + 1;
if (nextCharIndex > DIGITS.Length)
nextChar = DIGITS[0];
else
nextChar = DIGITS[nextCharIndex];
}
return nextChar.ToString();
}
After you edited your question, I think what you're after is this
public int incrementNumber(string number)
{
var lastNumber = int.Parse(number.Last());
return (number.Length - 1) + ((lastNumber + 1) % 10).ToString();
}
% 10 or Mod 10 takes the reminder of the number divided by 10. So if you pass in 9 it will increment to 10 then wrap around to 0. When you pass in 5 it will increment to 6 and stay as 6 because it's not divisible by 10.
This may not be optimized but works if you allow +1 to increment.
public static string NextValue(string Counting)
{
int nextVal;
if(int.TryParse(Counting, out nextVal))
{
return (nextVal + 1).ToString();
}
else
{
char[] numbers = Counting.ToCharArray();
StringBuilder incremented = new StringBuilder();
foreach (char digit in numbers.Reverse())
{
if (digit == 'z')
{
incremented.Append("0");
}
else if (int.TryParse(digit.ToString(), out nextVal))
{
nextVal = nextVal + 1;
if (nextVal == 10)
{
incremented.Append("z");
}
else
{
incremented.Append(nextVal.ToString());
}
incremented.Append(string.Concat(numbers.Reverse().Skip(incremented.Length)));
break;
}
else
{
//Invalid character in number except for z
return string.Empty;
}
}
if (incremented[incremented.Length - 1] == '0')
incremented.Append("1");
return Reverse(incremented.ToString());
}
}
public static string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}

How to make next step of a string. C#

The question is complicated but I will explain it in details.
The goal is to make a function which will return next "step" of the given string.
For example
String.Step("a"); // = "b"
String.Step("b"); // = "c"
String.Step("g"); // = "h"
String.Step("z"); // = "A"
String.Step("A"); // = "B"
String.Step("B"); // = "C"
String.Step("G"); // = "H"
Until here its quite easy, But taking in mind that input IS string it can contain more than 1 characters and the function must behave like this.
String.Step("Z"); // = "aa";
String.Step("aa"); // = "ab";
String.Step("ag"); // = "ah";
String.Step("az"); // = "aA";
String.Step("aA"); // = "aB";
String.Step("aZ"); // = "ba";
String.Step("ZZ"); // = "aaa";
and so on...
This doesn't exactly need to extend the base String class.
I tried to work it out by each characters ASCII values but got stuck with strings containing 2 characters.
I would really appreciate if someone can provide full code of the function.
Thanks in advance.
EDIT
*I'm sorry I forgot to mention earlier that the function "reparse" the self generated string when its length reaches n.
continuation of this function will be smth like this. for example n = 3
String.Step("aaa"); // = "aab";
String.Step("aaZ"); // = "aba";
String.Step("aba"); // = "abb";
String.Step("abb"); // = "abc";
String.Step("abZ"); // = "aca";
.....
String.Step("zzZ"); // = "zAa";
String.Step("zAa"); // = "zAb";
........
I'm sorry I didn't mention it earlier, after reading some answers I realised that the problem was in question.
Without this the function will always produce character "a" n times after the end of the step.
NOTE: This answer is incorrect, as "aa" should follow after "Z"... (see comments below)
Here is an algorithm that might work:
each "string" represents a number to a given base (here: twice the count of letters in the alphabet).
The next step can thus be computed by parsing the "number"-string back into a int, adding 1 and then formatting it back to the base.
Example:
"a" == 1 -> step("a") == step(1) == 1 + 1 == 2 == "b"
Now your problem is reduced to parsing the string as a number to a given base and reformatting it. A quick googling suggests this page: http://everything2.com/title/convert+any+number+to+decimal
How to implement this?
a lookup table for letters to their corresponding number: a=1, b=2, c=3, ... Y = ?, Z = 0
to parse a string to number, read the characters in reverse order, looking up the numbers and adding them up:
"ab" -> 2*BASE^0 + 1*BASE^1
with BASE being the number of "digits" (2 count of letters in alphabet, is that 48?)
EDIT: This link looks even more promising: http://www.citidel.org/bitstream/10117/20/12/convexp.html
Quite collection of approaches, here is mine:-
The Function:
private static string IncrementString(string s)
{
byte[] vals = System.Text.Encoding.ASCII.GetBytes(s);
for (var i = vals.Length - 1; i >= 0; i--)
{
if (vals[i] < 90)
{
vals[i] += 1;
break;
}
if (vals[i] == 90)
{
if (i != 0)
{
vals[i] = 97;
continue;
}
else
{
return new String('a', vals.Length + 1);
}
}
if (vals[i] < 122)
{
vals[i] += 1;
break;
}
vals[i] = 65;
break;
}
return System.Text.Encoding.ASCII.GetString(vals);
}
The Tests
Console.WriteLine(IncrementString("a") == "b");
Console.WriteLine(IncrementString("z") == "A");
Console.WriteLine(IncrementString("Z") == "aa");
Console.WriteLine(IncrementString("aa") == "ab");
Console.WriteLine(IncrementString("az") == "aA");
Console.WriteLine(IncrementString("aZ") == "ba");
Console.WriteLine(IncrementString("zZ") == "Aa");
Console.WriteLine(IncrementString("Za") == "Zb");
Console.WriteLine(IncrementString("ZZ") == "aaa");
public static class StringStep
{
public static string Next(string str)
{
string result = String.Empty;
int index = str.Length - 1;
bool carry;
do
{
result = Increment(str[index--], out carry) + result;
}
while (carry && index >= 0);
if (index >= 0) result = str.Substring(0, index+1) + result;
if (carry) result = "a" + result;
return result;
}
private static char Increment(char value, out bool carry)
{
carry = false;
if (value >= 'a' && value < 'z' || value >= 'A' && value < 'Z')
{
return (char)((int)value + 1);
}
if (value == 'z') return 'A';
if (value == 'Z')
{
carry = true;
return 'a';
}
throw new Exception(String.Format("Invalid character value: {0}", value));
}
}
Split the input string into columns and process each, right-to-left, like you would if it was basic arithmetic. Apply whatever code you've got that works with a single column to each column. When you get a Z, you 'increment' the next-left column using the same algorithm. If there's no next-left column, stick in an 'a'.
I'm sorry the question is stated partly.
I edited the question so that it meets the requirements, without the edit the function would end up with a n times by step by step increasing each word from lowercase a to uppercase z without "re-parsing" it.
Please consider re-reading the question, including the edited part
This is what I came up with. I'm not relying on ASCII int conversion, and am rather using an array of characters. This should do precisely what you're looking for.
public static string Step(this string s)
{
char[] stepChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
char[] str = s.ToCharArray();
int idx = s.Length - 1;
char lastChar = str[idx];
for (int i=0; i<stepChars.Length; i++)
{
if (stepChars[i] == lastChar)
{
if (i == stepChars.Length - 1)
{
str[idx] = stepChars[0];
if (str.Length > 1)
{
string tmp = Step(new string(str.Take(str.Length - 1).ToArray()));
str = (tmp + str[idx]).ToCharArray();
}
else
str = new char[] { stepChars[0], str[idx] };
}
else
str[idx] = stepChars[i + 1];
break;
}
}
return new string(str);
}
This is a special case of a numeral system. It has the base of 52. If you write some parser and output logic you can do any kind of arithmetics an obviously the +1 (++) here.
The digits are "a"-"z" and "A" to "Z" where "a" is zero and "Z" is 51
So you have to write a parser who takes the string and builds an int or long from it. This function is called StringToInt() and is implemented straight forward (transform char to number (0..51) multiply with 52 and take the next char)
And you need the reverse function IntToString which is also implementet straight forward (modulo the int with 52 and transform result to digit, divide the int by 52 and repeat this until int is null)
With this functions you can do stuff like this:
IntToString( StringToInt("ZZ") +1 ) // Will be "aaa"
You need to account for A) the fact that capital letters have a lower decimal value in the Ascii table than lower case ones. B) The table is not continuous A-Z-a-z - there are characters inbetween Z and a.
public static string stepChar(string str)
{
return stepChar(str, str.Length - 1);
}
public static string stepChar(string str, int charPos)
{
return stepChar(Encoding.ASCII.GetBytes(str), charPos);
}
public static string stepChar(byte[] strBytes, int charPos)
{
//Escape case
if (charPos < 0)
{
//just prepend with a and return
return "a" + Encoding.ASCII.GetString(strBytes);
}
else
{
strBytes[charPos]++;
if (strBytes[charPos] == 91)
{
//Z -> a plus increment previous char
strBytes[charPos] = 97;
return stepChar(strBytes, charPos - 1); }
else
{
if (strBytes[charPos] == 123)
{
//z -> A
strBytes[charPos] = 65;
}
return Encoding.ASCII.GetString(strBytes);
}
}
}
You'll probably want some checking in place to ensure that the input string only contains chars A-Za-z
Edit Tidied up code and added new overload to remove redundant byte[] -> string -> byte[] conversion
Proof http://geekcubed.org/random/strIncr.png
This is a lot like how Excel columns would work if they were unbounded. You could change 52 to reference chars.Length for easier modification.
static class AlphaInt {
private static string chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static string StepNext(string input) {
return IntToAlpha(AlphaToInt(input) + 1);
}
public static string IntToAlpha(int num) {
if(num-- <= 0) return "a";
if(num % 52 == num) return chars.Substring(num, 1);
return IntToAlpha(num / 52) + IntToAlpha(num % 52 + 1);
}
public static int AlphaToInt(string str) {
int num = 0;
for(int i = 0; i < str.Length; i++) {
num += (chars.IndexOf(str.Substring(i, 1)) + 1)
* (int)Math.Pow(52, str.Length - i - 1);
}
return num;
}
}
LetterToNum should be be a Function that maps "a" to 0 and "Z" to 51.
NumToLetter the inverse.
long x = "aazeiZa".Aggregate((x,y) => (x*52) + LetterToNum(y)) + 1;
string s = "";
do { // assertion: x > 0
var c = x % 52;
s = NumToLetter() + s;
x = (x - c) / 52;
} while (x > 0)
// s now should contain the result

Categories

Resources