Read/Insert array elements in a matrix - c#

I have an array with binary values which I exploded it and inserted them into an array, but now I want to move this elements into an [8, 8] matrix (line-per-line), how may I do this?
I've been trying but I couldn't find any good example
static void Main(string[] args)
{
string textonorm, textobin = "", textobin1 = "", textocod = "";
int textval, quant, result, txtvalor;
Console.WriteLine("Digite a frase que deseja criptografar!");
textonorm = Console.ReadLine();
textval = System.Text.ASCIIEncoding.UTF8.GetByteCount(textonorm);
byte[] phrase = Encoding.ASCII.GetBytes(textonorm);
foreach (byte b in phrase)
{
textobin += Convert.ToString(b, 2);
textval = textobin.Length;
}
if (textval < 64)
{
quant = 64 - textval;
foreach (byte b in phrase)
{
textobin1 += Convert.ToString(b, 2);
}
textocod = textobin1.PadLeft(quant, '0');
txtvalor = textobin1.Length;
Console.WriteLine(textocod.ToString() + "\r\n " + "\r\n " + txtvalor.ToString());
string[] textarray = textocod.Split('0', '1');
int[,] matrizval = new int[8,8];
foreach (var substr in textarray)
{
Console.WriteLine(Convert.ToString());
}
}
else
{
Console.WriteLine("ok");
}
}

The code could be improved if you explain exactly what you expect of it, but to copy the values to the matrix:
using System;
using System.Text;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string textonorm, textobin = "", textobin1 = "", textocod = "";
int textval, quant, result, txtvalor;
Console.WriteLine("Digite a frase que deseja criptografar!");
textonorm = Console.ReadLine();
textval = System.Text.ASCIIEncoding.UTF8.GetByteCount(textonorm);
byte[] phrase = Encoding.ASCII.GetBytes(textonorm);
foreach (byte b in phrase)
{
textobin += Convert.ToString(b, 2);
textval = textobin.Length;
}
if (textval < 64)
{
quant = 64;
foreach (byte b in phrase)
{
textobin1 += Convert.ToString(b, 2);
}
textocod = textobin1.PadLeft(quant, '0');
txtvalor = textobin1.Length;
Console.WriteLine(textocod.ToString() + "\r\n " + "\r\n " + txtvalor.ToString());
char[] chararray = textocod.ToCharArray();
int[,] matrizval = new int[8, 8];
if (chararray.Length == 64)
for (int i = 0; i < 8; ++i)
{
for (int j = 0; j < 8; ++j)
{
int val = chararray[i * 8 + j] - '0';
Console.Write(val);
matrizval[i, j] = val;
}
Console.WriteLine();
}
}
else
{
Console.WriteLine("ok");
}
Console.Write("\nPress any key...");
Console.ReadKey();
}
}
}

Related

Binary manipulation

I am trying to code up the SHA-256 algorithm as shown by https://blog.boot.dev/cryptography/how-sha-2-works-step-by-step-sha-256/. From what I can tell, my code is perfect up until this algorithm:
for (int i = 16; i < 64; i++)
{
s0 = s1 = "";
right7 = rotate(w[i - 15], 7);
right18 = rotate(w[i - 15], 18);
right3 = "000" + w[i - 15].Remove(29);
s0 = xor(xor(right7, right18), right3);
right17 = rotate(w[i - 2], 17);
right19 = rotate(w[i - 2], 19);
right10 = "0000000000" + w[i - 2].Remove(22);
s1 = xor(xor(right17, right19), right10);
w[i] = add(add(add(s0, s1), w[i - 16]), w[i-7]);
}
Here are the sub-routines for add, rotate and xor:
static string rotate(string input, int amount)
{
return input.Substring(32-amount) + input.Remove(32-amount);
}
static string add(string input1, string input2)
{
string output = "";
Int64 one = Convert.ToInt64(input1, 2);
Int64 two = Convert.ToInt64(input2, 2);
Int64 total = one + two;
if (total > (Math.Pow(2, 32)))
{
total -= Convert.ToInt64(Math.Pow(2, 32));
}
output = Convert.ToString(total, 2);
if (output.Length < 32)
{
output = new string('0', 32 - output.Length) + output;
}
return output;
}
static string xor(string input1, string input2)
{
int total;
string output = "";
for (int i = 0; i < 32; i++)
{
total = Convert.ToInt32(Convert.ToString(input1[i])) + Convert.ToInt32(Convert.ToString(input2[i]));
if (total == 1)
{
output += '1';
}
else
{
output += '0';
}
}
return output;
}
The first iteration of I works, but then the second one doesn't by a couple of binary digits, and past the number 22, it's completely wrong. Any ideas or guidance would be greatly appreciated

C# implementation of Ascii Minimum Delete Distance

How do you implement the ASCII Minimum Delete Distance in C#?
See description here with a Python solution.
Deletion distance between 2 strings
I derived the C# solution from this Java solution.
https://leetcode.com/articles/minimum-ascii-delete-sum-for-two-strings/#
static void TestAscMinDelDist()
{
List<string[]> l = new List<string[]> {
new string[]{"cat", "at", "99"},
new string[]{"aunt","ant", "117"},
new string[]{"sea", "eat", "231"},
new string[]{"boat", "got", "298"},,
new string[]{"toradol", "tramadol", "317"},
new string[]{"tattoo","platoon", "562"},
new string[]{"delete", "leet", "403"},
new string[]{"flomax", "volmax", "436"},
new string[]{"clozapine", "olanzapine", "522"},
new string[]{"Sam", "Samantha", "524"},
new string[]{"kitten", "sitting", "531" },
new string[]{"sloughs", "thought", "674"}, };
foreach (string[] a in l) {
CalcPrint(a[0], a[1], a[2]);
CalcPrint(a[1], a[0], a[2]);
}
}
static int AsciiMinimumDeleteDistance(String s1, String s2) {
int s1Len = s1.Length, s2Len = s2.Length;
int[,] dp = new int[s1Len + 1, s2Len + 1];
for (int i = s1Len - 1; i >= 0; i--) {
dp[i, s2Len] = dp[i + 1, s2Len] + (int)s1[i]; }
for (int j = s2Len - 1; j >= 0; j--) {
dp[s1Len, j] = dp[s1Len, j+1] + (int)s2[j]; }
for (int i = s1Len - 1; i >= 0; i--) {
for (int j = s2Len - 1; j >= 0; j--) {
if (s1[i] == s2[j]) {
dp[i, j] = dp[i+1, j+1];
} else {
dp[i, j] = Math.Min(dp[i+1, j] + (int)s1[i],
dp[i, j+1] + (int)s2[j]);
}
}
}
return dp[0,0];
}
static void CalcPrint(string s1, string s2, string s3)
{
int cost = AsciiMinimumDeleteDistance(s1, s2);
string result = cost == int.Parse(s3) ? "Passed" : "Failed: Expected: " + s3;
Console.WriteLine($"{s1} -> {s2} {cost} \t {result}");
}

Function Anagram

An anagram is a word formed from another by rearranging its letters, using all the original letters exactly once; for example, orchestra can be rearranged into carthorse.
I want to write a function to return all anagrams of a given word (including the word itself) in any order.
For example GetAllAnagrams("abba") should return a collection containing "aabb", "abab", "abba", "baab", "baba", "bbaa".
Any help would be appreciated.
Here is a working function, making use of a GetPermutations() extension found elsewhere on stack overflow
public static List<string> GetAnagrams(string word)
{
HashSet<string> anagrams = new HashSet<string>();
char[] characters = word.ToCharArray();
foreach (IEnumerable<char> permutation in characters.GetPermutations())
{
anagrams.Add(new String(permutation.ToArray()));
}
return anagrams.OrderBy(x => x).ToList();
}
Here is the GetPermutations() extension and it's other necessary extensions:
public static IEnumerable<IEnumerable<T>> GetPermutations<T>(this IEnumerable<T> enumerable)
{
var array = enumerable as T[] ?? enumerable.ToArray();
var factorials = Enumerable.Range(0, array.Length + 1)
.Select(Factorial)
.ToArray();
for (var i = 0L; i < factorials[array.Length]; i++)
{
var sequence = GenerateSequence(i, array.Length - 1, factorials);
yield return GeneratePermutation(array, sequence);
}
}
private static IEnumerable<T> GeneratePermutation<T>(T[] array, IReadOnlyList<int> sequence)
{
var clone = (T[])array.Clone();
for (int i = 0; i < clone.Length - 1; i++)
{
Swap(ref clone[i], ref clone[i + sequence[i]]);
}
return clone;
}
private static int[] GenerateSequence(long number, int size, IReadOnlyList<long> factorials)
{
var sequence = new int[size];
for (var j = 0; j < sequence.Length; j++)
{
var facto = factorials[sequence.Length - j];
sequence[j] = (int)(number / facto);
number = (int)(number % facto);
}
return sequence;
}
static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
private static long Factorial(int n)
{
long result = n;
for (int i = 1; i < n; i++)
{
result = result * i;
}
return result;
}
}
Here is a screenshot of the result:
And, finally, a github repository of the complete Visual Studio solution: Github
import java.util.Scanner;
import java.lang.String;
public class KrishaAnagram
{
public static void main(String[] args) {
Scanner Scan = new Scanner(System.in);
String s1, s2;
int sum1, sum2;
sum1 = sum2 = 0;
System.out.print("Enter fisrt string: ");
s1 = Scan.next();
System.out.print("Enter Second string: ");
s2 = Scan.next();
if (s1.length() != s2.length()) {
System.out.println("NOT ANAGRAM");
} else {
for (int i = 0; i < s1.length(); i++) {
char ch1 = s1.charAt(i);
char ch2 = s2.charAt(i);
sum1 += (int) ch1;
sum2 += (int) ch2;
}
if (sum1 == sum2)
System.out.println("IT IS AN ANAGRAM : s1 = " + sum1 + "s1 = " + sum2);
else
System.out.println("IT IS NOT AN ANAGRAM : s1 = " + sum1 + "s1 = " + sum2);;
}
}
}
//This is My way of solving anagram in java,Hope it helps.

C# Dynamic Arrays and its Calculation

I have 2 dynamic textboxes which stores users input in the form of an array Int32[] iA1 = new Int32[3];
and also have a combo box, which has mathematical operator.
My question is how to get the following output when user fills the number of rows and column dynamically at run time and make an appropriate selection from the combo box.
Thanks in advanceenter image description here
string output = "";
Int32[] array = new Int32[3] { 25, 4, 1 };
int rows = array[0];
int cols = array[1];
int op = array[2];
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
int value = 0;
string opStr = "";
if (op == 1) // +
{
opStr = "+";
value = r + c;
}
else if (op == 2) // -
{
opStr = "-";
value = r - c;
}
else if (op == 3) // *
{
opStr = "*";
value = r * c;
}
// ...
output += string.Format("{0} {1} {2} = {3}\t", r, opStr, c, value);
}
output += System.Environment.NewLine;
}
System.Console.Write(output);
System.Diagnostics.Debug.Write(output);
textarea.Text = output;
Here is a small console app which does what you want:
class Program
{
static void Main(string[] args)
{
var firstNumber = 24;
var secondNumber = 4;
var op = "+";
var result = new List<List<string>>();
for (int i = 0; i <= firstNumber; i++)
{
var list = new List<string>();
for (int j = 0; j < secondNumber; j++)
{
list.Add(i.ToString());
list.Add(op);
list.Add(j.ToString());
list.Add("=");
list.Add((i + j).ToString());
}
result.Add(list);
}
foreach (var item in result)
{
Console.WriteLine(string.Join(" ", item));
}
Console.ReadLine();
}
}
You need to take the numbers and the operator from your textboxes.

Looping through an array without throwing exception

Say I have an array of values:
string[] text = new string[] { "val1", "val2", "val3", "val4", "val5" };
Then I have a basic loop:
for (int i = 0; i <= 30; i++)
{
Console.WriteLine(i + " = " + text[i])
}
Obviously, this will cause an out of bounds exception, so what I want to do is when the counter reaches the upper bound of the array then go back to the start.
So
0 = val1
1 = val2
2 = val3
3 = val4
4 = val5
5 = val1
6 = val2
7 = val3
etc..
You could use the modulus operator:
Console.WriteLine(i + " = " + text[i % 5])
Take the modulus of the array length:
for (int i = 0; i < 30; ++i)
{
Console.WriteLine(i + " = " + text[i % text.Length]);
}
Try
for(int i=0;i<=30;i++)
{
Console.WriteLine(i + " = " + string[i % 5])
}
Shouldn't it be:
Console.WriteLine(i + " = " + text[i % text.length])
?
As a slightly less specific solution...
class Program
{
static void Main(string[] args)
{
string[] text = new string[] { "val1", "val2", "val3", "val4", "val5" };
int count = 0;
foreach (string t in text.ContinuousLoopTo(30))
{
Console.WriteLine(count.ToString() + " = " + t);
count++;
}
Console.ReadLine();
}
}
public static class Extensions
{
public static IEnumerable<T> ContinuousLoopTo<T>(this IList<T> list, int number)
{
int loops = number / list.Count;
int i = 0;
while (i < loops)
{
i++;
foreach (T item in list)
{
yield return item;
}
}
for (int j = 0; j < number % list.Count; j++)
{
yield return list[j];
}
}
}
what? like forever?
bool run = true;
int i = 0;
string[] text = new string[] {"val1", "val2", "val3", "val4", "val5"};
while(run)
{
Console.WriteLine(i + " = " + text[i])
i++;
if(i>=text.Length) i=0;
}
The writeline should be:
Console.WriteLine(i + " = " + text[i%5]);

Categories