How to decompress RLE in C#? - c#

So basically I want to input something such as "05A03R02B" and for the program to return "AAAAARRRBB".
I'm relatively new to coding and it's a task I've been set so I have really no idea how to do it and haven't known what to try.

This snipped does your job:
private byte blockLength = 3;
private byte numLength = 2;
private void StringWorker(string input, out string output)
{
var len = input.Length;
if(len%blockLength!=0)
{
throw new ArgumentException("len has to be a multiple of blockLength");
}
var keys = new char[len/blockLength];
var values = new byte[len/blockLength];
var buffer = input.SubString(0,blockLength); //fill 1st block
//parse string into keys and values
for (var i = blockLength+1; i < s.Length; i++)
{
int index = i/blockLength;
//check for new block
if((i-1)%blockLength==0)
{
//assign values
values[index] = Int32.Parse(buffer.SubString(i-blockLength-1,numLength);
keys[index] = buffer[i-1];
//clear buffer
buffer="";
}
//add new char to buffer
buffer+=input[i];
}
//compose new string from keys and values
var sb = enw StringBuilder();
for(var i = 0; i < keys.Length; i++)
{
var value = values[i];
var key = keys[i];
for(var j = 0; j < value; j++)
{
sb.Append(key);
}
}
output = sb.ToString();
}

Related

Arrange strings in alphabetical order

//code with problem (maybe)
numberArray = NameNumEquv;
listStringArray = NamesArray;
string[] sortedArray = new string[NamesArray.Length];
for (int arrayItemCounter = 0; arrayItemCounter < NamesArray.Length; arrayItemCounter++)
{
compareArrayCount = 1;
initialArrayCount = 0;
while (compareArrayCount < numberArray.Length)
{
for (int doubleArrayLength = 0; doubleArrayLength < numberArray[compareArrayCount].Length; doubleArrayLength++)
{
if (numberArray[initialArrayCount][doubleArrayLength] < numberArray[compareArrayCount][doubleArrayLength])
{
initialArrayCount = compareArrayCount;
break;
}
}
compareArrayCount = compareArrayCount + 1;
}
sortedArray[arrayItemCounter] = listStringArray[initialArrayCount];
List<string> tempArrayValues = new List<string>();
List<int[]> tempNumArrayValues = new List<int[]>();
for (int tempArrayCount = 0; tempArrayCount < listStringArray.Length; tempArrayCount++)
{
if (tempArrayCount != initialArrayCount)
{
tempArrayValues.Add(listStringArray[tempArrayCount]);
tempNumArrayValues.Add(numberArray[tempArrayCount]);
}
}
listStringArray = tempArrayValues.ToArray();
numberArray = tempNumArrayValues.ToArray();
tempArrayValues.Clear();
tempNumArrayValues.Clear();
}
//till here
foreach (string nums in sortedArray)
{
Console.WriteLine(nums);
}
}
public static int[] AlphaNumericConversion(string stringValue, int arrayLength)
{
string Alphabets = "abcdefghijklmnopqrstuvwxyz";
char[] alphabetArray = Alphabets.ToCharArray();
string lowerCaseConv = stringValue.ToLower();
char[] stringArray = lowerCaseConv.ToCharArray();
int[] numericalConvertedArray = new int[arrayLength];
for (int valueArrayCount = 0; valueArrayCount < numericalConvertedArray.Length; valueArrayCount++)
{
numericalConvertedArray[valueArrayCount] = 0;
}
for (int letterCounter= 0;letterCounter < stringArray.Length;letterCounter++)
{
for (int alphabetCounter = 0; alphabetCounter < Alphabets.Length; alphabetCounter++)
{
if (stringArray[letterCounter] == alphabetArray[alphabetCounter])
numericalConvertedArray[letterCounter] = alphabetCounter + 1;
}
}
return numericalConvertedArray;
}
}
}
I want to arrange strings in ascending order. It is arranging the single letter strings(a, b, c,d, e.....) in reverse alphabetical order as in Z-A and string containing 2 or more letters randomly such as "Aayush", "Ayush", "Aayusha", "Ayusha" to "Aayusha","Ayusha","Aayush","Ayush". What is wrong with the code. Don't suggest to simply use List.Sort() because I want to write it in algorithmic manner. I'm trying to understand how it works rather than using Sort().

Replacing all the empty elements in an array with a String value

I have an array which can hold 10 elements:
string[] Ar = new string[10];
But it has only 5 items added to it. I need to insert The string value "NULL" to the rest of the empty slots in the array and thus making the array 'full' with string elements (that, being my objective).
This is what I've attempted as of now:
int entityCount = 5;
if (entityCount < 10)
{
for (int i = entityCount; i < 10; i++)
{
Ar[i] = "NULL";
}
}
And thus, when printed should output the values:
A, B, C, D, E, NULL, NULL, NULL, NULL, NULL
But this does not seem to do the trick, Still prints out ONLY the 5 items and not the 5 new strings.
I am not from C# background but I think this is what you want:
string[] Ar = new string[10];
for (int i = 0; i < 10; i++)
{
if(String.IsNullOrEmpty(Ar[i]))
{
Ar[i]="NULL";
}
}
for (int i = 0; i < 10; i++)
{
Console.WriteLine(Ar[i]);
}
You can read about String.IsNullOrEmpty(Ar[i]) here.
static void Main(string[] args)
{
int arraySize = 10;
string[] Ar = new string[arraySize];
Ar[0] = "A";
Ar[1] = "B";
Ar[2] = "C";
Ar[3] = "D";
for (int i = 0; i < arraySize; i++)
{
if (Ar[i]==null)
{
Ar[i] = "NULL";
}
}
for (int i = 0; i < Ar.Length; i++)
{
Console.Write(Ar[i]+" ");
}
}
}
this works fine.
int entityCount = 5;
string[] Ar = new string[10];
Ar[0] = "A";
Ar[1] = "B";
Ar[2] = "C";
Ar[3] = "D";
Ar[4] = "E";
if(entityCount < 10) {
for(int i = entityCount; i < 10; i++) {
Ar[i] = "NULL";
}
}
foreach(string s in Ar) {
Console.WriteLine(s);
}
using System;
using System.Linq;
class Program
{
private static void Main(string[] args)
{
string[] Ar = new string[10];
var item = from f in Ar
select string.IsNullOrWhiteSpace(f) ? "NULL" : f;
foreach (var i in item)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
Here item is iterator in string of array replace all with null if not contains value
string multiplayer = new string[5];
foreach (var item in multiplayers)
{
if (item == null) { Console.WriteLine("Empty"); }
Console.WriteLine(item);
}
remember string of array is not nullable here

Array to new string

I'm making a webshop for school and had a quick question.
I'm trying to write a code that generates a random coupon code and it actually works (did some extreme programming in Console Application), but it's simply not efficient.
static void Main(string[] args)
{
Random r = new Random();
string ALphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int size = 4;
char[] code1 = new char[size]
char[] code2 = new char[size]
char[] code3 = new char[size]
for (int i = 0; i < size; i++)
{
code1[i] = Alphabet[r.Next(Alphabet.Length)];
code2[i] = Alphabet[r.Next(Alphabet.Length)];
code3[i] = Alphabet[r.Next(Alphabet.Length)];
}
string code4 = new string(code1);
string code5 = new string(code2);
string code6 = new string(code3);
Console.WriteLine(code4 + " - " + code5 + " - " + code6);
Console.ReadLine();
}
This works.. somehow. But I would like to see it more efficient, because when I want to generate 100 coupons... this isn't really the way to do that.
I did see something on joining strings, use string.Insert to get that " - " in between and loop it multiple times, but I couldn't get a clear tutorial on how to do that with... well this kind of code.
Anyone got a efficient and (preferable) easy solution?
=======
UPDATE!
this does end up in a database eventually
You could be using a StringBuilder for this:
StringBuilder sb = new StringBuilder();
Random r = new Random();
string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int size = 16;
for (var i = 0; i < size; i++)
{
sb.Append(Alphabet[r.Next(Alphabet.Length)]);
}
Console.WriteLine(sb.ToString());
If you want less code you can make use of a GUID and format it.
Guid.NewGuid().ToString("N").Substring(0, 16);
Update, just saw you needed some formatting between each part of the coupon, so I changed it a litle bit:
StringBuilder sb = new StringBuilder();
Random r = new Random();
string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int pieces = 3, pieceSize = 4;
for (var i = 0; i < pieces; i++)
{
if(i != 0)
sb.Append(" - ");
for (var j = 0; j < pieceSize; j++)
{
sb.Append(Alphabet[r.Next(Alphabet.Length)]);
}
}
Console.WriteLine(sb.ToString());
Code is not quite good, but for school app will play I guess )
static string GenerateCoupon(Random r)
{
string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int size = 4;
char[] code1 = new char[size];
char[] code2 = new char[size];
char[] code3 = new char[size];
for (int i = 0; i < size; i++)
{
code1[i] = Alphabet[r.Next(Alphabet.Length)];
code2[i] = Alphabet[r.Next(Alphabet.Length)];
code3[i] = Alphabet[r.Next(Alphabet.Length)];
}
string code4 = new string(code1);
string code5 = new string(code2);
string code6 = new string(code3);
return string.Format("{0}-{1}-{2}", code4, code5, code6);
}
static void Main(string[] args)
{
Random rnd = new Random();
for (int i = 0; i < 100;i++ )
Console.WriteLine(GenerateCoupon(rnd));
Console.ReadLine();
}

convert string[] to doube[,] in C#

i have text file consist of data like:
1,2
2,3
3,4
4,5
Now I want to save the data into an array. So i do split:
using (streamreader sr = new streamreader("file.txt")) {
string[] data = sr.ReadLine().Split(',');
}
however my data save in string[] while I have a GlobalDataClass array declared as double[,]. Something like this:
static class GlobalDataClass
{
public static double[,] Array = new double[4, 2];
}
I need to assign the data to the GlobalDataClass:
GlobalDataClass.Array = data;
So my question is how to convert the string[] to double[,]?
Since you have a 2-d array, you'd need to iterate over each line and extract the values, then assign it into the proper position. You can use Select and double.Parse to convert the string values to double.
using (var reader = new StreamReader("file.txt"))
{
string line;
for (var count = 0; count < 4; ++count)
{
var data = reader.ReadLine()
.Split(',')
.Select(v => double.Parse(v))
.ToArray();
GlobalDataClass.Array[count,0] = data[0];
GlobalDataclass.Array[count,1] = data[1];
}
}
Now if your array was really double[][], then you could do something more like:
GlobalDataClass.Array = File.ReadAllLines("file.txt")
.Select(l => l.Split(',')
.Select(v => double.Parse(v))
.ToArray())
.ToArray();
Note: I think it's like a really bad idea to make it a global variable. There's probably a much better way to handle this.
I think that the best way is to use Array.ConvertAll.
Example:
string[] strs = new string[] { "1.00", "2.03" };
Array.ConvertAll(strs, Double.Parse);
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
int counter =0 ;
while((line = file.ReadLine()) != null)
{
var lineData= line.Split(',');
GlobalDataClass.Array[counter,0] = double.Parse(lineData[0]);
GlobalDataClass.Array[counter,1] = double.Parse(lineData[1]);
counter++;
}
Try This:
String [] words;
int lineCount=0;
String [] Lines=File.ReadAllLines(#"C:\Data.txt");
for (int i=0;i<Lines.Length;i++)
{
words = Lines[i].Split(',');
for (int j = 0; j < 2; j++)
{
GlobalDataClass.Array[i,j] = Convert.ToDouble(words[j].Trim());
}
}
I am using some part of your code to show you how you do this task.
int mCount = 0;
using (streamreader sr = new streamreader("file.txt")) {
string[] data = sr.ReadLine().Split(',');
GlobalDataClass.Array[mCount , 0] = Double.Parse(data[0]);
GlobalDataClass.Array[mCount , 1] = Double.Parse(data[1]);
mCount += 1;
}
double[] doubleArray = strArray.Select(s => Double.Parse(s)).ToArray();
int k = 0;
for (int i = GlobalDataClass.Array.GetLowerBound(0); i <= GlobalDataClass.Array.GetUpperBound(0); i++)
{
for (int j = GlobalDataClass.Array.GetLowerBound(1); j <= GlobalDataClass.Array.GetUpperBound(1); j++)
{
double d = doubleArray[k];
GlobalDataClass.Array.SetValue(d, i, j);
k++;
}
}
If the number of lines can vary:
var lines = File.ReadAllLines("file.txt");
var data = new double[lines.Length, 2];
for (var i = 0; i < lines.Length; i++)
{
var temp = lines[i].Split(',');
data[i,0] = double.Parse(temp[0]);
data[i,1] = double.Parse(temp[1]);
}
GlobalDataClass.Array = data;
..or, if the number of lines is a constant value:
using (var sr = new StreamReader("file.txt"))
{
var i = 0;
var len = GlobalDataClass.GetLength(0);
while (sr.Peak() >= 0 && i < len)
{
var temp = sr.ReadLine().Split(',');
GlobalDataClass.Array[i,0] = double.Parse(temp[0]);
GlobalDataClass.Array[i,1] = double.Parse(temp[1]);
i++;
}
}

custom encryption #2

I wrote a code for custom encryption. It is a challenge. Right now it doesn't work for some reasons like:
Encrypt("abc", "hello everyone")
Returns: sdfhsjfjs
Decrypt("abc", "sdfhsjfjs")
Retruns: diuifidu
public int CountCharInStringAccordingToArray(string Text)
{
int Count = 0;
foreach (char x in Text)
{
Count++;
}
return Count - 1;
}
public int CountCharInString(string Text)
{
int Count = 0;
foreach (char x in Text)
{
Count++;
}
return Count;
}
public string Encrypt(string Key, string PlainText)
{
int[] TempKey = new int[CountCharInString(Key)];
int[] TempText = new int[CountCharInString(PlainText)];
int[] EncryptedInt = new int[CountCharInString(PlainText)];
char[] EncryptedChar = new char[CountCharInString(PlainText)];
for (int i = 0; i < CountCharInStringAccordingToArray(Key); i++)
{
TempKey[i] = (int)Key[i];
}
for (int i = 0; i < CountCharInStringAccordingToArray(PlainText); i++)
{
TempText[i] = (int)PlainText[i];
}
int Index = 0;
for (int i = 0; i < CountCharInStringAccordingToArray(PlainText); i++)
{
if (Index == CountCharInStringAccordingToArray(Key))
{
Index = 0;
}
EncryptedInt[i] = TempKey[Index] + TempText[i];
Index++;
EncryptedChar[i] = (char)EncryptedInt[i];
}
return new string(EncryptedChar);
}
public string Decrypt(string Key, string EncryptedText)
{
int[] TempKey = new int[CountCharInString(Key)];
int[] TempText = new int[CountCharInString(EncryptedText)];
int[] DecryptedInt = new int[CountCharInString(EncryptedText)];
char[] DecryptedChar = new char[CountCharInString(EncryptedText)];
for (int i = 0; i < CountCharInStringAccordingToArray(Key); i++)
{
TempKey[i] = (int)Key[i];
}
for (int i = 0; i < CountCharInStringAccordingToArray(EncryptedText); i++)
{
TempText[i] = (int)EncryptedText[i];
}
int Index = 0;
for (int i = 0; i < CountCharInStringAccordingToArray(EncryptedText); i++)
{
if (Index == CountCharInStringAccordingToArray(Key))
{
Index = 0;
}
DecryptedInt[i] = TempText[i] - TempKey[Index];
Index++;
DecryptedChar[i] = (char)DecryptedInt[i];
}
return new string(DecryptedChar);
}
Also I know that string have a length property it just I forget to correct it.
Change the line
return Count - 1;
in CountCharInStringAccordingToArray to
return Count;
A representation of your code:
String That(String key, String text, int sign) {
return new String(Enumerable.Range(0, text.Length).Select((x, i) => (char)(text.ToArray()[i]+sign*key.ToArray()[i%key.Length])).ToArray());
}
public String Encrypt(String key, String text) {
return That(key, text, 1);
}
public String Decrypt(String key, String text) {
return That(key, text, -1);
}
The principle of how it works is easy. Look at the graph:
The characters in the key are used repeatedly to add to the text and resulting a sequence that considered encrypted. The decryption is just a reverse operation by subtracting.
The maximum value can store in a byte is 0x0ff, but the maximum value of visible characters is 0x7e, that is ~, and 0x7e+0x7e=0xfc.
So as long as your key and text are in the range of visible characters, it will not cause overflowing. That is, you can decrypt the encrypted sequence to the original correctly.
Get string length and output string
using System;
class MainClass {
public static void Main() {
string str1 = "ABCDEabcde1234567890";
Console.WriteLine("str1: " + str1);
Console.WriteLine("Length of str1: " + str1.Length);
}
}

Categories

Resources