Printing Reverse Triangle with Alphabets - c#

I have to print the following pattern in C# -
A B C D E F G F E D C B A
A B C D E F E D C B A
A B C D E D C B A
A B C D C B A
A B C B A
A B A
A
I'm able to print the pattern in C but not in C# because the character input does not work in C#. I tried converting it but I'm not able to convert it properly and facing the problems with for loops. Please tell me how to write equivalent C# code.
Thanks in advance.
C code is:
#include<stdio.h>
#include<conio.h>
int main()
{
char ch,r,c;
int sp;
printf("\nEnter last character of triangle : ");
scanf("%c",&ch);
if(ch>='a' && ch<='z')
ch=ch-32;
printf("\n");
for(r='A'; 'A'<=ch; ch--,r++)
{
for(sp=r; sp>'A'; sp--)
printf(" ");
for(c='A'; c<=ch; c++)
printf("%c",c);
for(c=ch-1; c>='A'; c--)
printf("%c",c);
printf("\n");
}
getch();
return 0;
}
Edited
My C# Code:
public class Pascal_Triangle
{
public void printPascal()
{
char ch, r, c;
int sp;
Console.WriteLine("\nEnter last character of triangle : ");
ch = Convert.ToChar(Console.ReadLine());
if (ch >= 'a' && ch <= 'z')
ch = Convert.ToChar(ch - 32);
for (r = 'A'; 'A' <= ch; ch--, r++)
{
for (sp = r; sp > 'A'; sp--)
Console.WriteLine(" ");
for (c = 'A'; c <= ch; c++)
Console.Write(c);
for (c = Convert.ToChar(ch - 1); c >= 'A'; c--)
Console.Write(c);
}
Console.ReadLine();
}
}
The Output I'm getting:

C# does support looping through alphabet...
char c = 'A';
++c;
Where c would grow to 'B'
But of course, you can't increase/deacrease a string, only a character.
Your code is a way too complicated, try this. It's easy to understand, just go step by step.
Console.WriteLine("\nEnter last character of triangle : ");
char ch = Convert.ToChar(Console.ReadLine());
if (ch >= 'a' && ch <= 'z')
{
ch = Convert.ToChar(ch - 32);
}
int numberOfLines = ch - 'A' + 1;
var graphic = "";
for (var i = 0; i < numberOfLines; i++, ch--)
{
var line = "";
var tmp = "";
for (var j = 0; j < i; j++)
{
tmp += " ";
}
line += tmp;
for (var j = 'A'; j < ch; j++)
{
line += j.ToString();
}
for (var j = ch; j >= 'A'; j--)
{
line += j.ToString();
}
line += tmp;
graphic += line + "\n";
}
Console.WriteLine(graphic);
Console.ReadLine();

Related

Sequence of marching chars in 2 strings

I have to write searching algorithm, For example I have to compare str="giorgi" to str2="grigol". I'm trying to find longest matching sequence of chars, so that the order of chars is the same and string which I should get is "grg"... with this c# code I'm getting "grig".
int k=0;
string s="";
string str = "giorgi";
string str2 = "grigol";
for(int i=0;i<str.Length;i++)
{
for (int j = k; j < str2.Length; j++)
{
if (str[i] == str2[j])
{
s += str2[k];
k++;
goto endofloop;
}
}
endofloop:;
}
Console.WriteLine(s);
The solution:
using System;
class GFG
{
/* Returns length of LCS for X[0..m-1], Y[0..n-1] */
static int lcs( char[] X, char[] Y, int m, int n )
{
int [,]L = new int[m+1,n+1];
/* Following steps build L[m+1][n+1]
in bottom up fashion. Note
that L[i][j] contains length of
LCS of X[0..i-1] and Y[0..j-1] */
for (int i = 0; i <= m; i++)
{
for (int j = 0; j <= n; j++)
{
if (i == 0 || j == 0)
L[i, j] = 0;
else if (X[i - 1] == Y[j - 1])
L[i, j] = L[i - 1, j - 1] + 1;
else
L[i, j] = GFG.max(L[i - 1, j], L[i, j - 1]);
}
}
return L[m, n];
}
static int max(int a, int b)
{
return (a > b)? a : b;
}
}
And now the program to test it:
public static void Main()
{
String s1 = "giorgi";
String s2 = "grigol";
char[] X=s1.ToCharArray();
char[] Y=s2.ToCharArray();
int m = X.Length;
int n = Y.Length;
Console.Write("Length of LCS is" + " " +lcs( X, Y, m, n ) );
}
}

Atbash Cipher in C#

I'm new to programming and C# and i'm trying to make Atbash Cipher in C#.
So I'm stuck at this problem: the cipher ran good, but they don't put spacing, or special characters (that not need to encode) in the result. I tried to make it but it got repeated.
So is there a way to let it skip the non-alphabet characters and put it on result ?
Here is my code
using System;
namespace AtbashCipher
{
class Program
{
static void Main()
{
Console.WriteLine("Atbash cipher v1.0");
Console.WriteLine();
Console.Write("Enter messages: ");
string userInput = Console.ReadLine();
Console.WriteLine();
string Alphabet = "abcdefghijklmnopqrstuvwxyz";
string AlphabetUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string result = "";
Boolean SpecialChar = false;
foreach (char c in userInput)
{
for (int i = 0; i < Alphabet.Length; i++)
{
if (c == Alphabet[i])
{
result += Alphabet[Alphabet.Length - 1 - i];
}
if (c == AlphabetUpper[i])
{
result += AlphabetUpper[AlphabetUpper.Length - 1 - i];
}
}
}
//Print result for user
Console.WriteLine("Encoded messages: " + result);
Console.WriteLine();
Console.Write("Press any key to exit.");
Console.ReadKey();
}
}
}
I had the same task recently and here is my approach:
private string GetAtbash(string s)
{
var charArray = s.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
char c = charArray[i];
if (c >= 'a' && c <= 'z')
{
charArray[i] = (char) (96 + (123 - c));
}
if (c >= 'A' && c <= 'Z')
{
charArray[i] = (char) (64 + (91 - c));
}
}
return new String(charArray);
}
You forgot to append the character if it's not between a-z or A-Z. You can check if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') and simply append c to result if that's not the case.

How to write a code for my decrypt without special character

I am only able to encrypt, but i do not how to decrypt. Someone please help. Do I have to declare a bool variable?
Or is that any other better way to do it?
string UserInput = "";
int shift;
Shift OBSHIFT = new Shift();
Console.Write("\nType a string to encrypt:");
UserInput = Console.ReadLine();
Console.Write("How many chars would you like to shift?: ");
shift = int.Parse(Console.ReadLine());
Console.WriteLine("\nApplying Caesar cipher ... ");
Console.Write("Your encrypted string is: ");
Console.WriteLine(OBSHIFT.Cshift(UserInput, shift));
Console.Read();
}
}
class Shift
{
public string Cshift(string str, int shift )
{
string UserOutput = "";
char[] A = null;
A = str.ToCharArray();
int temp;
for (int i = 0; i < str.Length; i++)
{
char c = A[i];
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
{
temp = (int)(A[i] + shift);
if ((c >= 'A' && c <= 'Z' && temp > 'Z') || (c >= 'a' && c <= 'z' && temp > 'z'))
temp = temp - 26;
else
temp = (int)(A[i] + (shift));
}
else
temp = c;
UserOutput += (char)temp;
}
return UserOutput;
}
}
}
}
Talking about Caesar cipher, you can simply negate the shift and get the original string.
I.e., cshift(cshift(string, x), -x) == string.
Using your Shift class:
int sh = 17;
string original = "abcdefgh";
string encrypted = shift.Cshift(original, sh);
string decrypted = shift.Cshift(shifted, -sh);
Console.WriteLine(decrypted == original); // true
For convenience, you can create a method Decrypt, which will do this:
class Shift
{
public string Encrypt(string originalString, int shift)
{
string userOutput = "";
char[] a = originalString.ToCharArray();
for (int i = 0; i < originalString.Length; i++)
{
char c = a[i];
int temp;
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
{
temp = (int)(a[i] + shift);
if ((c >= 'A' && c <= 'Z' && temp > 'Z') || (c >= 'a' && c <= 'z' && temp > 'z'))
temp = temp - 26;
else
temp = (int)(a[i] + (shift));
}
else
temp = c;
userOutput += (char)temp;
}
return userOutput;
}
public string Decrypt(string cipherString, int shift)
{
return Encrypt(cipherString, -shift);
}
}
Note that I have also done some little code improvements like:
combined declaration and assignment of A
moved temp into the inner scope
gave the proper names to the local variables (lower-case)

Run length decoder in C#

Is it possible that anyone around here might have a run-length DECODER in C#? I'm in real need of said code. Thanks.
using System;
class RLDEC
{
static void Main()
{
int t = int.Parse(Console.ReadLine());
for (int k = 0; k < t; k++)
{
string s = Console.ReadLine();
s = runLengthDecoder(s);
Console.WriteLine(s);
}
}
static string runLengthDecoder(string s)
{
string d = ""; // decoded string
int cv; // current value
for(int k = 0; k < s.Length; k++)
{
cv = Convert.ToInt32(s[k]) - 48;
if (k + 1 < s.Length && cv != 1 && cv >= 2 && cv <= 9)
{
for(int v = 0; v < cv; v++)
d += s[k+1];
}
if (cv == 1)
{
int z = k + 1;
while(k < s.Length && z < s.Length && Convert.ToInt32(s[z]) - 48 != 1)
{
d += s[z];
z++;
k++;
}
k++;
}
}
return d;
}
}
It's hard to solve this without the specification for your encoding, but in this code
if (k + 1 < s.Length && cv != 1 && cv >= 2 && cv <= 9)
{
for(int v = 0; v < cv; v++)
d += s[k+1];
}
I would expect k to be incremented before leaving the if block.
Also, I would expect that the next if (cv==1) is an else if instead.
In that cv==1 block, I think you should just process then next character and let the outer for loop do its work.
I also don't understand how that block could work at all

Create all permutations of a string incrementally c#

I am trying to create a function that will create all permutations of a string in an incremental fashion. I would like to start at:
AAAAA
...
AAAAB
...
ACCCC
...
...
ZZZZZ
I have looked around, and can't seem to find anything of that sort. I tried to create it, but it wasn't incrementally.
Any suggestions?
The "permutation" you are describing is better known as the Cartesian product. If you have an arbitrary number of sequences that you need to form the Cartesian product of, see my answer to this question on the subject:
Generating all Possible Combinations
Normally I wouldn't help these brute force type results... but seeing how many useless result you will get out of the set I figured I'd just toss this in.
var query = from c0 in Enumerable.Range(0, 26)
from c1 in Enumerable.Range(0, 26)
from c2 in Enumerable.Range(0, 26)
from c3 in Enumerable.Range(0, 26)
from c4 in Enumerable.Range(0, 26)
select new string(
new [] {
(char)('A' + c0),
(char)('A' + c1),
(char)('A' + c2),
(char)('A' + c3),
(char)('A' + c4),
}
);
BTW... if you just want the next value you can do something like this...
public static string Increment(string input)
{
var array = input.ToCharArray();
if (array.Any(c => c < 'A' || c > 'Z'))
throw new InvalidOperationException();
for (var i = array.Length-1; i >= 0; i--)
{
array[i] = (char)(array[i] + 1);
if (array[i] > 'Z')
{
array[i] = 'A';
if (i == 0)
return 'A' + new string(array);
}
else
break;
}
return new string(array);
}
A different variant where I had the idea of using modulo arithmetic. Note that I lowered the character to {A,B,C} to test it, since going up to Z for 5 letters is a lot of strings.
public IEnumerable<char[]> AlphaCombinations(int length = 5, char startChar = 'A', char endChar = 'C')
{
int numChars = endChar - startChar + 1;
var s = new String(startChar, length).ToCharArray();
for (int it = 1; it <= Math.Pow(numChars, length); ++it)
{
yield return s;
for (int ix = 0; ix < s.Length; ++ix)
if (ix == 0 || it % Math.Pow(numChars, ix) == 0)
s[s.Length - 1 - ix] = (char)(startChar + (s[s.Length - 1 - ix] - startChar + 1) % numChars);
}
}
...
foreach (var s in AlphaCombinations(5))
{
Console.WriteLine(s);
}
Bashed out quickly - I expect this could be done better:
public static IEnumerable<string> GenerateStrings(int length = 5)
{
var buffer = new char[length];
for (int i = 0; i < length; ++i)
{
buffer[i] = 'A';
}
for(;;)
{
yield return new string(buffer);
int cursor = length;
for(;;)
{
--cursor;
if (cursor < 0)
{
yield break;
}
char c = buffer[cursor];
++c;
if (c <= 'Z')
{
buffer[cursor] = c;
break;
}
else
{
buffer[cursor] = 'A';
}
}
}
}
Here is the LINQPad friendly code and it uses lambda expression.
void Main()
{
var chars = Enumerable.Range(65, 26);
var strings = chars.SelectMany (a =>
{
return chars.SelectMany (b => chars.SelectMany (c =>
{
return chars.SelectMany (d =>
{
return chars.Select (e => {return new string(new char[] {(char)a, (char)b, (char)c, (char)d, (char)e});});
});
}));
});
strings.Dump();
}

Categories

Resources