Integer decode porting from Java to C# - c#

I am trying to port some code from java to C#, I have faced 2 problems so far. Here is the Java code:
public static void main(String[] args)
{
var ia = new byte[args.length];
for (int i = 0; i < args.length; i++)
try
{
ia[i] = Integer.decode(args[i]).byteValue();
}
catch (NumberFormatException e)
{
}
System.out.
println(Integer.toHexString(Calc(ia, ia.length)));
}
Obviously I have to change main to Main, length to Length but no idea about:
Integer.decode(args[i]).byteValue()
and
Integer.toHexString(Calc(ia, ia.length)).
Can someone tell me please what are the avilable options in .NET in these cases?!

Possible conversion code from java to c#.Net:
public static void Main(string[] args)
{
var ia = new byte[args.Length];
for (int i = 0; i < args.Length; i++)
try
{
ia[i] = Convert.ToByte(args[i]);
}
catch (FormatException e)
{
}
System.Console.WriteLine(String.Format("{0:X}",Calc(ia, ia.Length))); /// I assume Calc is function return something
}

You can use Convert.toInt32(string) or Parse.Int32(string)

Related

~ no response on stdout ~ C# Error while submitting code in HackerRank

I am practicing C# code on HackerRank online website, when I want to submit my code then it gives an error:
Below is my code:
for(int i=0;i<input.Count-1;i++){
string evenData="",oddData="";
string data=input[i];
for(int j=0;j<data.Length-1;j++){
if(i%2==0){
evenData += data[j].ToString();
}else{
oddData +=data[j].ToString();
}
}
Console.WriteLine(evenData + " " +oddData);
}
I have already search over the internet for this issue but everyone says just add Console.WriteLine because stdout and Console.writeLine both are just like same but it doesn't resolve my problem.
Kindly provide me a better solution.
Thanks
Use Console.In.ReadLine() and Console.Out.WriteLine() for stdin and stdout.
using System;
using System.Collections.Generic;
using System.IO;
class Solution {
public static void Result(string s)
{
var sarry = s.ToCharArray();
if(sarry.Length >1)
{
var evenstr = "";
var oddstr = "";
for(int i=0 ;i<=sarry.Length-1 ; i++)
{
if(i%2==0)
oddstr=oddstr+sarry[i];
else
evenstr=evenstr+sarry[i];
}
var result =oddstr+" "+evenstr;
Console.Out.WriteLine(result);
}
}
static void Main(String[] args) {
int T=int.Parse(Console.In.ReadLine());
for (int i = 0; i < T; i++)
{
var inp=Console.In.ReadLine();
Solution.Result(inp);
}
}
}

How to parse a multi-lined lambda statement string into DynamicExpression.ParseLambda?

I want to pass a multi-statement lambda string (a little program in fact) into DynamicExpression.ParseLambda but I fear I may have reached its limitations. I have written code to feed small lambda expressions but I think it will choke on a full program.
Here is MCVE so far. It shows the original algorithm BuildSieve() and also it shows the beginning of lambda equivalent but it fails on first line with exception Unknown identifier 'long'
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using diag=System.Diagnostics;
using myAlias = System.Linq.Dynamic; //install package 'System.Linq.Dynamic' v.1.0.7 with NuGet
namespace LambdaStatement
{
class Program
{
static void Main(string[] args)
{
BuildSieveLambda();
Console.ReadKey();
}
static void BuildSieveLambda()
{
try
{
var pList = new List<ParameterExpression>();
pList.Add(Expression.Parameter(typeof(int), "x"));
LambdaExpression e = myAlias.DynamicExpression.ParseLambda(pList.ToArray(), null, "long n = 2000000;");
}
catch (Exception ex)
{
string msg = GetExMessage(ex);
diag.Debug.WriteLine("DEBUGME: " + msg);
throw new Exception(msg);
}
}
public static string GetExMessage(Exception ex)
{
string ret = ex.Message;
if (ex.InnerException!=null)
{
ret= ret+ ": " + GetExMessage(ex.InnerException);
}
return ret;
}
static void BuildSieve()
{
//https://gist.github.com/gideondsouza/1978926 Sieve of Eratosthenes C# implementation by code Gideon Israel Dsouza
long n = 2000000;
bool[] e = new bool[n];//by default they're all false
for (int i = 2; i < n; i++)
{
e[i] = true;//set all numbers to true
}
//weed out the non primes by finding mutiples
for (int j = 2; j < n; j++)
{
if (e[j])//is true
{
for (long p = 2; (p * j) < n; p++)
{
e[p * j] = false;
}
}
}
}
You may think this is impossible but I've seen some really complicated lambda expressions in C# code, full method implementations in fact. So if the C# compiler or Visual Studio can do this then is there access to that API to programmers?
You need to add n the same way you added x:
pList.Add(Expression.Parameter(typeof(long), "n"));
LamdaExpression e = myAlias.DynamicExpression.ParseLamda(pList.ToArray(), null, "n = 200000");
Although, I admit, I have no idea what this program does, but this is why you get that error. It is reading long in the string as an identifier, instead of a type.

NHAPI 2.5.1 xx.(0).Components values, how to use

I have figured out most (I think) of the values for PID and RAX using NHapi for hl7 2.5.1.
What I am having difficulties on are the ones that (I am assuming) use components such as rxa.AdministeredCode.Components[5].
How do I set that value?
I assume same thing for rxa.GetSubstanceManufacturerName(0).Components? and
rxa.GetAdministrationNotes(0).
Gina
Try this
class Program
{
static void Main(string[] args)
{
EncodingCharacters enchars = new EncodingCharacters('|', "^~\\&");
IModelClassFactory theFactory = new DefaultModelClassFactory();
NHapi.Model.V251.Segment.RXA rxa = new NHapi.Model.V251.Segment.RXA(new VXU_V04(theFactory), theFactory);
IType[] t = rxa.GetSubstanceManufacturerName(0).Components;
SetRXA(t);
Debug.Print(PipeParser.Encode(rxa, enchars));
Console.Read();
}
public static void SetRXA(IType[] components)
{
for (int i = 0; i < components.Length; i++)
{
if (components[i] is IPrimitive)
{
IPrimitive prim = (IPrimitive)components[i];
prim.Value = "Component"+i;
}
else if (components[i] is IComposite)
SetRXA(((IComposite)components[i]).Components);
//if Varies do something else
}
}
}

How to print object of type List<string> in C#

I am new to c# and I want to print object which is of List type. How can I print this object and display list in console?
Below is my code:
class Program{
public List<double> GetPowersOf2(int input)
{
var returnList = new List<double>();
for (int i = 0; i < input + 1; i++)
{
returnList.Add(Math.Pow(2, i));
}
returnList.ForEach(Console.WriteLine);//display list from method.
return returnList;
}
static void Main(String[] args)
{
Program p = new Program();
Console.WriteLine(p.GetPowersOf2(2));//not display list...
}
}
It gives error: System.Collections.Generic.List`1[System.Double]
Please suggest solution.
Thanks in advance.
Try a simple Linq and Join the outcome into a single string:
// Let's use BigInteger instead of Double to represent 2's powers
using System.Numerics;
...
int input = 12;
string report = string.Join(Environment.NewLine, Enumerable
.Range(0, input)
.Select(index => BigInteger.Pow(2, index)));
Console.Write(report);
Outcome:
1
2
4
8
16
32
64
128
256
512
1024
2048
Using Linq:
public class Program{
public List<double> GetPowersOf2(int input)
{
var returnList = new List<double>();
for (int i = 0; i < input + 1; i++)
{
returnList.Add(Math.Pow(2, i));
}
return returnList;
}
public static void Main(String[] args)
{
Program p = new Program();
p.GetPowersOf2(2).ForEach(Console.WriteLine);
}
}
So you are aware of displaying a list in the console, as you did within the method(returnList.ForEach(Console.WriteLine);). Now you returning the list object to the calling method and now you don't know how to display it, right? Why don't you try the same here, like this:
p.GetPowersOf2(2).ForEach(Console.WriteLine);
Because the variable returnList is returning from the method, so definitely the same will receive in the calling method.
Dont return the List and just call it like that:
class Program{
public void GetPowersOf2(int input)
{
var returnList = new List<double>();
for (int i = 0; i < input + 1; i++)
{
returnList.Add(Math.Pow(2, i));
}
returnList.ForEach(Console.WriteLine);//display list from method.
//return returnList;
}
static void Main(String[] args)
{
Program p = new Program();
p.GetPowersOf2(2);
}
}
OR return it like that:
class Program{
public List<double> GetPowersOf2(int input)
{
var returnList = new List<double>();
for (int i = 0; i < input + 1; i++)
{
returnList.Add(Math.Pow(2, i));
}
//returnList.ForEach(Console.WriteLine);//display list from method.
return returnList;
}
static void Main(String[] args)
{
Program p = new Program();
p.GetPowersOf2(2).ForEach(Console.WriteLine);//not display list...
}
}
var powers=p.GetPowersOf2(2);
foreach(double power in powers) Console.Writeline(power+", ");
The reason why your original code did not work is is because the default implementation of .ToString() is to simply print the name of class. Only in certain classes is this overridden.
If you want to change the default behavior of .ToString for your list you will have to derive a class from List.
public class PrintableList<T> : List<T>
{
public override string ToString()
{
string result = "";
foreach (T obj in this)
{
result += obj.ToString() + "\n";
}
return result;
}
}
Use this in place of your list in your code, and your code will work fine.

Rookie C# problem

I am a rookie to C# and here is my question
class myClass
{
int start;
int end;
.......
}
class program
{
public void main()
{
myClass[] a= new myClass[10];
for (int i = 1; i < a.length; i++)
{
myClass b = new myClass();
a[i] = b;
a[i].start = 1;
... (keep populating)
...
}
console.writeline(a[1].start) // NO PROBLEM WITH THIS LINE, THE VALUE WAS OUTPUTED
subMethod(a);
}
public void subMethod(myClass[] a)
{
console.write(a[1].start); // NO PROBLEM WITH THIS LINE, OUTPUT NORMALLY
for (int i = 1; i < a.length, i++)
{
int h = a[i].start; ????? OBJECT NOT INSTANTIATED
}
}
}
The error is as indicated above and I have difficulty to understand it. Anyone can help me out. Thanks in advance
The problem seems to be in the code that you haven't posted.
myClass[] a= new myClass[10];
// (populate this array)
I've no idea what you have written there but it clearly isn't working. It should be this:
myClass[] a = new myClass[10];
for (int i = 0; i < a.Length; i++)
{
a[i] = new myClass();
}
The code you posted won't compile. Please copy + paste the actual code - don't try to write it from memory.
You should notice that the first index in an array is 0, not 1.
I'd also suggest that you read the Microsoft naming guidelines, for example class names should be in Pascal case.
You've instantiated an array but new need to instantiate each object in the array. You are not showing how you do that bit in the example above.
Please post code that compiles. The error is probably in your transcribing of the code, because this code works perfectly fine:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RandomArrayTest
{
class MyClass
{
public int start;
}
class Program
{
static void Main(string[] args)
{
MyClass[] a = new MyClass[10];
for(int i=1; i<a.Length; i++)
{
MyClass b = new MyClass();
a[i] = b;
a[i].start = 1;
}
MyFunction(a);
}
static void MyFunction(MyClass[] a)
{
for (int i = 1; i < a.Length; i++)
{
int h = a[i].start;
Console.WriteLine(h);
}
}
}
}

Categories

Resources