How to Convert Javascript Code to C# Code - c#

I have a Javascript method. I wrote on C# but it dosen't work.
Javascript Code
var __AM = 65521;
function cc(a) {
var c = 1, b = 0, d, e;
for (e = 0; e < a.length; e++) {
d = a.charCodeAt(e);
c = (c + d) % __AM;
b = (b + c) % __AM;
}
return b << 16 | c;
}
My written C# Code
private string CC(string a)
{
var __AM = 65521;
int e;
long d;
long c = 1, b = 0;
for (e = 0; e < a.Length; e++)
{
var p = Encoding.Unicode.GetBytes(a[e].ToString());
d = Convert.ToInt32(p.First());
c = (c + d) % __AM;
b = (b + c) % __AM;
}
return b.ToString() + c.ToString();
}
JS Test
cc("4JipHEz53sU1406413803");
Result: 1132332429
C# Test
CC("4JipHEz53sU1406413803");
Result: 172781421
How Can I get JS value in C#?

This code works:
private string cc(string a)
{
var __AM = 65521;
int e;
long d;
long c = 1, b = 0;
for (e = 0; e < a.Length; e++)
{
d = (int)a[e];
c = (c + d) % __AM;
b = (b + c) % __AM;
}
return (b << 16 | c).ToString();
}

Related

ParameterizedThreadStart error, no overload for 'subroutine' matches delegate ParameterizedThreadStart

I am trying to create a thread which creates generates new RSA keys using my algorithm provided.
The algorithm may not be perfect but is fine by what i am doing - not the problem.
The problem lies with why doesnt the parts below work: from what i have gathered online i am using parameterizedthreadstart correctly?
Thread thread = new Thread(new ParameterizedThreadStart(GenerateKeys)); //issue here!!!!
thread.Start(RSA_KEYS, PublicKeysToDistribute);
it shows the error: no overload for 'GenerateKeys' matches delegate ParameterizedThreadStart.
Any help would be appreciated
static void Main(string[] args)
{
Dictionary<(BigInteger, BigInteger), (BigInteger, BigInteger)> RSA_KEYS = new Dictionary<(BigInteger, BigInteger), (BigInteger, BigInteger)>();
Queue<(BigInteger, BigInteger)> PublicKeysToDistribute = new Queue<(BigInteger, BigInteger)>();
Thread thread = new Thread(new ParameterizedThreadStart(GenerateKeys));
thread.Start(RSA_KEYS, PublicKeysToDistribute);
//recipitent receives public key in form e,n
//splits into Biginteger array : {e,n}
GenerateKeys(RSA_KEYS, PublicKeysToDistribute);
BigInteger[] PublicKey = Array.ConvertAll(PublicKeyRequest(PublicKeysToDistribute).Split(':'), BigInteger.Parse);
string input;
//creates message to encrypt
input = InputToAscii();
//encrypt using PublicKey
BigInteger a = encrypt(PublicKey, input);
BigInteger b = decrypt((RSA_KEYS[(PublicKey[0], PublicKey[1])]).Item1, (RSA_KEYS[(PublicKey[0], PublicKey[1])]).Item2, a);
Console.WriteLine(AsciiToOutput(b));
Console.ReadLine();
}
private static string PublicKeyRequest(Queue<(BigInteger, BigInteger)> PublicKeysToDistribute)
{
string publickey = PublicKeysToDistribute.Peek().Item1 + ":" +PublicKeysToDistribute.Peek().Item2;
PublicKeysToDistribute.Dequeue();
return publickey;
}
//create a key value pair where the publickey is key and private key is value
//publickey = {biginteger,biginteger} where {e,n}
//privatekey = {biginteger,biginteger} where {d,n}
public static void GenerateKeys(Dictionary<(BigInteger, BigInteger), (BigInteger, BigInteger)> RSA_KEYS, Queue<(BigInteger, BigInteger)> PublicKeysToDistribute)
{
int p = 4201; //default use 61 4201
int q = 4007; //default use 53 4007
int n = p * q;
// compute the totient, phi
int ϕn = (p - 1) * (q - 1);
//e for random number which 1 < e < ϕn and is co prime of ϕn
Random rn = new Random();
bool found = false;
BigInteger e = 0;
while (found == false)
{
e = rn.Next(1, ϕn);
if (Coprime(ϕn, e) == true)
{
break;
}
}
// where (d * e) mod ϕn = 1 find d
BigInteger d = 0;
for (int k = 1; k < ϕn; k++)
{
if ((k * e) % ϕn == 1)
{
d = k;
break;
}
}
Console.WriteLine("p="+p+",q="+q+",n="+n+",phi="+ϕn+",e="+e+",d="+d+",n="+n);
Console.WriteLine("Public key: e = " + e + " n = " + n);
Console.WriteLine("Private key: d = " + d + " n = " + n);
RSA_KEYS.Add((e, n), (d, n));
PublicKeysToDistribute.Enqueue((e, n));
Console.WriteLine("added new key to dictionary");
//return new KeyValuePair<(BigInteger, BigInteger), (BigInteger, BigInteger)>((e,n),(d,n));
}
private static BigInteger encrypt(BigInteger[] PublicKey, string input)
{
BigInteger m = BigInteger.Parse(input); //m = message
BigInteger c = eMod(m, PublicKey[0], PublicKey[1]); //cipher text = (message ^ e) mod n
return c;
}
private static BigInteger decrypt(BigInteger d, BigInteger n, BigInteger c)
{
BigInteger f = eMod(c, d, n); //result test = cipher ^ d mod n
return f;
}
private static BigInteger eMod(BigInteger a, BigInteger b, BigInteger c) //where a^b % c;
{
//base case
if (b == 0)
{
return 1;
}
else if (b % 2 == 0)
{
BigInteger d = eMod(a, b / 2, c);
//int result = d * d % c;
return ((d * d) % c);
}
else
{
return ((a % c) * eMod(a, b - 1, c)) % c;
}
}
private static BigInteger GetGCDByModulus(BigInteger value1, BigInteger value2)
{
while (value1 != 0 && value2 != 0)
{
if (value1 > value2)
value1 %= value2;
else
value2 %= value1;
}
return BigInteger.Max(value1, value2);
}
private static bool Coprime(BigInteger value1, BigInteger value2)
{
return GetGCDByModulus(value1, value2) == 1;
}
private static string InputToAscii()
{
Console.Write("Enter values to encrypt:");
char[] input = Console.ReadLine().ToCharArray(); //-1 < input < 999;
//char[] input = "-1".ToCharArray();
string AsciiInput = string.Empty;
for (int i = 0; i < input.Length; i++)
{
AsciiInput += ((int)input[i]).ToString();
}
Console.WriteLine(AsciiInput);
return AsciiInput;
}
private static string AsciiToOutput(BigInteger input)
{
string inputstring = input.ToString();
string output = string.Empty;
for (int i = 0; i < inputstring.Length / 2; i++)
{
output += (char)Convert.ToInt32((inputstring.Substring(i * 2, 2)));
}
return output;
}
}

Find the nth element in a tribonacci series

I found this as a Microsoft interview question (see Round 4). I am trying to solve it using C#. My attempt:
private static int NTerm_Tribonacci(int term)
{
int a = 0;
int b = 1;
int c = 1;
int result = 0;
if (term == 1) return a;
if (term == 2) return b;
if (term == 3) return c;
for (int i = 4; i <= term; i++)
{
a = a + b + c; if ((1 + 3 * i) % term == 0) { result = a; break; }
b = a + b + c; if ((2 * i + i - 1) % term == 0) { result = b; break; }
c = a + b + c; if ((3 * i) % term == 0) { result = c; break; }
}
return result;
}
But it is somehow not working var res = NTerm_Tribonacci(5);//should be 4 but getting 44
How can I solve this?
Tribonacci Number
Try this:
private static int NTerm_Tribonacci(int term)
{
int a = 0;
int b = 1;
int c = 1;
int result = 0;
if (term == 0) result = a;
if (term == 1) result = b;
if (term == 2) result = c;
while(term > 2)
{
result = a + b + c;
a = b;
b = c;
c = result;
term--;
}
return result;
}
Note that as per the definition in your link, I have assumed the first term to be T0, not T1.
Demo
I like the "LINQ way" of solving such things:
public IEnumerable<long> InfiniteTribonacciSequence()
{
long a = 0, b = 1, c = 1;
long nextTerm;
yield return a;
yield return b;
yield return c;
while (true)
{
nextTerm = a + b + c;
yield return nextTerm;
a = b;
b = c;
c = nextTerm;
}
}
But this has to be used carefully, because Methods like Min() will go crazy with this. But you can use e.g. InfiniteTribonacciSequence.Take(5).Last() to get the 5th element of the sequence.
I think the recursive way is too suitable for such cases:
example:
using System.IO;
using System;
class Program
{
static void Main()
{
int a=4, b;
b=tribo(a);
Console.WriteLine(b);
}
static public int tribo(int n)
{
if(n==0) return 0;
if(n==1) return 1;
if(n==2) return 1;
return(tribo(n-1)+tribo(n-2)+tribo(n-3));
}
}
this gives the series 0 1 1 2 4 7 13 24 ...

Converting C# code to Java code

I have to convert this little piece of C# code to Java:
const int AM = 65521;
int GetCCSufix(string a)
{
int c = 1, b = 0, d, e;
var chars = a.ToCharArray();
for(e =0; e< chars.Length; e ++)
{
d = chars[e];
c = (c + d) % AM;
b = (b + c) % AM;
}
return b << 16 | c;
}
And I made it this:
private int getSuffix(String a) {
int constant = 65521;
int c = 1;
int b = 0;
int d = 0;
int e = 0;
for(e = 0; e < a.length(); e++){
d = a.charAt(e);
c = (c + d) % constant;
b = (b + c) % constant;
}
return b << 16 | c;
}
However, this doesn't seem to give me the same output as the C# code. What am i doing wrong?
I did a verbatim translation of the original code, see if this gives the correct result. What values are you using for testing, that give different results?
private static final int AM = 65521;
int getCCSuffix(String a) {
int c = 1, b = 0, d = 0, e;
char[] chars = a.toCharArray();
for (e = 0; e < chars.length; e++) {
d = chars[e];
c = (c + d) % AM;
b = (b + c) % AM;
}
return b << 16 | c;
}

Rabin-Karp string matching algorithm by rolling hash

Here is an implementation of Rabin-Karp String matching algorithm in C#...
static void Main(string[] args)
{
string A = "String that contains a pattern.";
string B = "pattern";
ulong siga = 0;
ulong sigb = 0;
ulong Q = 100007;
ulong D = 256;
for (int i = 0; i < B.Length; i++)
{
siga = (siga * D + (ulong)A[i]) % Q;
sigb = (sigb * D + (ulong)B[i]) % Q;
}
if (siga == sigb)
{
Console.WriteLine(string.Format(">>{0}<<{1}", A.Substring(0, B.Length), A.Substring(B.Length)));
return;
}
ulong pow = 1;
for (int k = 1; k <= B.Length - 1; k++)
pow = (pow * D) % Q;
for (int j = 1; j <= A.Length - B.Length; j++)
{
siga = (siga + Q - pow * (ulong)A[j - 1] %Q) % Q;
siga = (siga * D + (ulong)A[j + B.Length - 1]) % Q;
if (siga == sigb)
{
if (A.Substring(j, B.Length) == B)
{
Console.WriteLine(string.Format("{0}>>{1}<<{2}", A.Substring(0, j),
A.Substring(j, B.Length),
A.Substring(j +B.Length)));
return;
}
}
}
Console.WriteLine("Not copied!");
}
but it has one problem if i change the position of second string than it shows result not copied but
string A = "String that contains a pattern.";
string B = "pattern";
here it shows not copied
string A = "String that contains a pattern.";
string B = "Matches contains a pattern ";
i want to check whether it is copy from first string or not even i would add something in it it or change the position but it shouldn't make difference so how to change it that it would just compare the hashes of each word in string than implement it............
Change
string B = "Matches contains a pattern ";
to
string B = "contains a pattern ";
and it will work

BetaInv function in SQL Server

similarly to the question: Inverted beta in MySQL I need to use the BetaInv function inside a SQL Server stored procedure.
function is described here: Excel's BETAINV
is anybody aware of anything similar in TSQL or would you wrap it in a CLR .NET managed SQL user defined function?
I really need to use it within the stored procedure and not as post executing code in the C# side after data has been retrieved with the stored procedure because I should keep all logic on the db server for better reuse.
can I assume that a .NET managed udf running in the SQL Server would perform as fast as a normal native TSQL function?
Thanks!
I've in the end implemented the whole function myself, here the source code in case somebody needs it:
public static class UDFs
{
private const int MAXIT = 100;
private const double EPS = 0.0000003;
private const double FPMIN = 1.0E-30;
[SqlFunction(Name = "BetaInv", DataAccess = DataAccessKind.Read)]
public static SqlDouble BetaInv(SqlDouble p, SqlDouble alpha, SqlDouble beta, SqlDouble A, SqlDouble B)
{
return InverseBeta(p.Value, alpha.Value, beta.Value, A.Value, B.Value);
}
private static double InverseBeta(double p, double alpha, double beta, double A, double B)
{
double x = 0;
double a = 0;
double b = 1;
double precision = Math.Pow(10, -6); // converge until there is 6 decimal places precision
while ((b - a) > precision)
{
x = (a + b) / 2;
if (IncompleteBetaFunction(x, alpha, beta) > p)
{
b = x;
}
else
{
a = x;
}
}
if ((B > 0) && (A > 0))
{
x = x * (B - A) + A;
}
return x;
}
private static double IncompleteBetaFunction(double x, double a, double b)
{
double bt = 0;
if (x <= 0.0)
{
return 0;
}
if (x >= 1)
{
return 1;
}
bt = System.Math.Exp(Gammln(a + b) - Gammln(a) - Gammln(b) + a * System.Math.Log(x) + b * System.Math.Log(1.0 - x));
if (x < ((a + 1.0) / (a + b + 2.0)))
{
// Use continued fraction directly.
return (bt * betacf(a, b, x) / a);
}
else
{
// Use continued fraction after making the symmetry transformation.
return (1.0 - bt * betacf(b, a, 1.0 - x) / b);
}
}
private static double betacf(double a, double b, double x)
{
int m, m2;
double aa, c, d, del, h, qab, qam, qap;
qab = a + b; // These q’s will be used in factors that occur in the coe.cients (6.4.6).
qap = a + 1.0;
qam = a - 1.0;
c = 1.0; // First step of Lentz’s method.
d = 1.0 - qab * x / qap;
if (System.Math.Abs(d) < FPMIN)
{
d = FPMIN;
}
d = 1.0 / d;
h = d;
for (m = 1; m <= MAXIT; ++m)
{
m2 = 2 * m;
aa = m * (b - m) * x / ((qam + m2) * (a + m2));
d = 1.0 + aa * d; //One step (the even one) of the recurrence.
if (System.Math.Abs(d) < FPMIN)
{
d = FPMIN;
}
c = 1.0 + aa / c;
if (System.Math.Abs(c) < FPMIN)
{
c = FPMIN;
}
d = 1.0 / d;
h *= d * c;
aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2));
d = 1.0 + aa * d; // Next step of the recurrence (the odd one).
if (System.Math.Abs(d) < FPMIN)
{
d = FPMIN;
}
c = 1.0 + aa / c;
if (System.Math.Abs(c) < FPMIN)
{
c = FPMIN;
}
d = 1.0 / d;
del = d * c;
h *= del;
if (System.Math.Abs(del - 1.0) < EPS)
{
// Are we done?
break;
}
}
if (m > MAXIT)
{
return 0;
}
else
{
return h;
}
}
public static double Gammln(double xx)
{
double x, y, tmp, ser;
double[] cof = new double[] { 76.180091729471457, -86.505320329416776, 24.014098240830911, -1.231739572450155, 0.001208650973866179, -0.000005395239384953 };
y = xx;
x = xx;
tmp = x + 5.5;
tmp -= (x + 0.5) * System.Math.Log(tmp);
ser = 1.0000000001900149;
for (int j = 0; j <= 5; ++j)
{
y += 1;
ser += cof[j] / y;
}
return -tmp + System.Math.Log(2.5066282746310007 * ser / x);
}
}
}
as you can see in the code, the SqlFunction is calling the InverseBeta private method which does the job using couple of other methods.
results are the same of Excel.BetaInv up to 5 or 6 digits after comma.

Categories