I'm trying to convert this MATLAB function into c#
but my results are not as expected.
MATLAB:
function check=CRC8(xa);
% xa is array of bits to be transmitted (column vector)
% Generates 8-bit CRC check with g(x) = x^8 + x^2 +x + 1
xae = [xa;0;0;0;0;0;0;0;0]; % Append 8 zeros to array containing bit-stream
g8x = [1;0;0;0;0;0;1;1;1] ; % Generator polynomial
xsa=xae(1:9);
for i=1:length(xa)
if xsa(1) = = g8x(1), xsa = xor(xsa,g8x); end;
xsa(1:8)=xsa(2:9);
if i<length(xa) xsa(9)=xae(i+9); end;
end;
check = xsa(1:8); % 8 bit CRC column vector
return;
C#
public static int[] checkCRC8(int[] xa)
{
int[] g8x = { 1, 0, 0, 0, 0, 0, 1, 1, 1 };
int[] xae = new int[xa.Length + 8];
xa.CopyTo(xae, 0);
//add zeros
for (int i = xa.Length; i < xae.Length; i++)
{
xae[i] = 0;
}
int[] xsa = new int[8];
for (int i = 0; i < 8; i++)
{
xsa[i] = xae[i];
}
for (int i = 0; i < xa.Length; i++)
{
if (xsa[0] == g8x[0])
{
//xor xsa with g8x
for (int j = 0; j < xsa.Length; j++)
{
xsa[j] = xsa[j] ^ g8x[j];
}
}
//shift array elements left
for (int j = 0; j < xsa.Length - 1; j++)
{
xsa[j] = xsa[j + 1];
}
if (i < xa.Length)
{
xsa[xsa.Length - 1] = xae[i + 8];
}
}
return xsa;
}
}
The matlab ranges like in xsa = xae(1:9) are inclusive, so xsa should have nine elements instead of eight. Also, since your i is already zero based, I think the last if should compare against xa.Length-1 and use the array element at i+9 instead of i+8:
if (i < xa.Length - 1)
{
xsa[xsa.Length - 1] = xae[i + 9];
}
Related
I want to shift elements in one array to right by only changing the index. Also I don't want to use built-in functions
For example, if we have
8,6,5,3,9
Then We will have
9,8,6,5,3
If the array doesn't have enough length. the rest of the elements shift will start from the first index of array.
int index = 0, temp = 0;
int[] myarray = new int[int.Parse(Console.ReadLine())];
for (int i = 0; i < myarray.Length; i++)
{
myarray[i] = int.Parse(Console.ReadLine());
}
for (int i = 0; i < myarray.Length; i++)
{
if (myarray.Length <= i + 5)
{
index = ((i + 5) % 5);
temp = myarray[index];
myarray[index] = myarray[i];
myarray[i] = temp;
}
else
{
temp = myarray[i + 5];
myarray[i + 5] = myarray[i];
myarray[i] = temp;
}
}
this is what i have tried but its not working
If shift count is less than or equal array size you can use this code (I edited answer by this link):
using System;
int M = 5;//shift count
int size; //size of array
int[] myarray = new int[int.Parse(Console.ReadLine())];
for (int i = 0; i < myarray.Length; i++)
{
myarray[i] = int.Parse(Console.ReadLine());
}
size = myarray.Length;
if (size >= M)
{
Array.Reverse(myarray, 0, size);
Array.Reverse(myarray, 0, M);
Array.Reverse(myarray, M, size - M);
for (int i = 0; i < myarray.Length; i++)
{
Console.Write(myarray[i]+"\t");
}
Console.Read();
}
So I am trying to solve this task "Digit Difference Sort" on Codefights
Given an array of integers, sort its elements by the difference of their largest and smallest digits.
In the case of a tie, that with the larger index in the array should come first.
Example
For a = [152, 23, 7, 887, 243], the output should be digitDifferenceSort(a) = [7, 887, 23, 243, 152].
Here are the differences of all the numbers:
152: difference = 5 - 1 = 4;
23: difference = 3 - 2 = 1;
7: difference = 7 - 7 = 0;
887: difference = 8 - 7 = 1;
243: difference = 4 - 2 = 2.
23 and 887 have the same difference, but 887 goes after 23 in a, so in the sorted array it comes first.
I have an issue with two numbers having the same difference. Here's what I wrote so far:
int[] digitDifferenceSort(int[] a) {
return a.OrderBy(x => difference(x)).ToArray();
}
int difference(int x)
{
int min = 9, max = 0;
do
{
int tmp = x % 10;
min = Math.Min(min, tmp);
max = Math.Max(max, tmp);
} while ((x /= 10) > 0);
return max - min;
}
Didn't do much (for example the output is still [7, 23, 887, 243, 152] rather than [7, 887, 23, 243, 152])
How do I make element with larger index come first in result? What should I use instead of OrderBy?
I don't consider your difference method, i assume it works fine.
To your question: you have to keep revered order of the array (that the items with the same difference arrive will be sorted reverse). To do it, you could just reverse you input array: all items with not identical difference will be ordered correctly, and with the same differece will be ordered reversed:
int[] digitDifferenceSort(int[] a)
{
return a.Reverse().OrderBy(x => difference(x)).ToArray();
}
Following is my code for the above question digit difference sort. I am also getting output when running in Eclipse but when I paste the code on code signal it gives me a null pointer exception.
package NormalPrograms;
import java.util.ArrayList;
import java.util.Collections;
public class DigitDifferenceSort {
// For index wise sorting in descending order
public static int[] sortingnumberindexwise(int[] a, ArrayList<Integer> index) {
int k = 0;
int[] res = new int[index.size()];
int[] finalres = new int[index.size()];
for (int i = a.length - 1; i >= 0; i--) {
for (int j = 0; j < index.size(); j++) {
if (a[i] == (int) index.get(j)) {
res[k] = i;
index.remove(j);
k++;
break;
}
}
}
int g = 0;
k = 0;
for (int i = 0; i < res.length; i++) {
finalres[g] = a[res[k]];
g++;
k++;
}
return finalres;
}
public static int[] finddigitDifferenceandSort(int[] p) {
int[] finres = new int[p.length];
for (int i = 0; i < finres.length; i++) {
finres[i] = p[i];
}
// This finres array act as an temp array and reused to make final result array
int digit = 0;
ArrayList<Integer> A = new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> B = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < 10; i++) {
B.add(new ArrayList<Integer>());
}
for (int i = 0; i < p.length; i++) {
int temp = 0;
temp = p[i];
while (p[i] > 0) {
digit = p[i] % 10;
p[i] /= 10;
A.add(digit);
}
int b = Collections.max(A);
int c = Collections.min(A);
int diff = b - c;
B.get(diff).add(temp);
A.clear();
}
for (int i = 0; i < B.size(); i++) {
if (B.get(i).size() > 1) {
ArrayList<Integer> C = new ArrayList<Integer>();
for (int k = 0; k < B.get(i).size(); k++) {
C.add(B.get(i).get(k));
}
B.get(i).clear();
for (int j : sortingnumberindexwise(finres, C)) {
B.get(i).add(j);
}
} else {
continue;
}
}
int k = 0;
for (int i = 0; i < B.size(); i++) {
for (int j = 0; j < B.get(i).size(); j++) {
if (B.get(i).size() == 0)
continue;
else {
finres[k] = B.get(i).get(j);
k++;
}
}
}
return finres;
}
public static void main(String[] args) {
int[] a = { 12, 21, 1, 1, 1, 2, 2, 3 };
for (int i : finddigitDifferenceandSort(a)) {
System.out.print(i + " ");
}
}
}
I want to "stretch" a one-dimensional float array into a bigger array.
//expected behaviour
float[] initialArray = {2.0, 6.5, 2.0}
float[] biggerArray = resample(initialArray, 7 /*new size*/)
//output: {2.0, 3.5, 5.0, 6.5, 5.0, 3.5, 2.0}
The new values should propobaly be calculated from linear interpolation of the previous array values but i can't figure out how to achieve that.
Any hint ?
Lets the length of a source array is N, and the length of a destination array is M where N < M and N > 1.
You can calculate the new index of the source i-th element by the formula:
j = i * (M - 1)/(N - 1);
When i == 0 then j == 0; and when i == N - 1 then j == M - 1. The external loop can looks like this:
float[] source = ...;
float[] destination = ...;
destination[0] = source[0];
for (int i = 1; i < source.Length; i++)
{
int j = i * (destination.Length - 1)/(source.Length - 1);
destination[j] = source[i];
// interpolation
}
To interpolation you should calculate intermediate values for each pair (source[i - 1], source[i]). You'll need to store previous value of j:
destination[0] = source[0];
int jPrevious = 0;
for (int i = 1; i < source.Length; i++)
{
int j = i * (destination.Length - 1)/(source.Length - 1);
Interpolate(destination, jPrevious, j, source[i - 1], source[i]);
jPrevious = j;
}
private static void Interpolate(float[] destination, int destFrom, int destTo, float valueFrom, float valueTo)
{
int destLength = destTo - destFrom;
float valueLength = valueTo - valueFrom;
for (int i = 0; i <= destLength; i++)
destination[destFrom + i] = valueFrom + (valueLength * i)/destLength;
}
This one works for both if source size is larger than destination and vice versa.
private double[] Resample(double[] source, int n)
{
//n destination length
int m = source.Length; //source length
double[] destination = new double[n];
destination[0] = source[0];
destination[n-1] = source[m-1];
for (int i = 1; i < n-1; i++)
{
double jd = ((double)i * (double)(m - 1) / (double)(n - 1));
int j = (int)jd;
destination[i] = source[j] + (source[j + 1] - source[j]) * (jd - (double)j);
}
return destination;
}
You can use List<float>:
float[] initialArray = { 2.0f, 6.5f, 2.0f };
List<float> initialArrayTemp = ToListFloat(initialArray);
private List<float> ToListFloat(float[] array)
{
List<float> list = new List<float>();
for (int i = 0; i < array.Length; i++)
{
list.Add(array[i]);
}
return list;
}
Now your array is a dynamic array and you can add your new nodes anywhere of your Array by using Insert() method.
As soon as you need a new static array, use below:
float[] newInitialArray = initialArrayTemp.ToArray();
I was just asking if there is a simple way of doing this.
i.e. Replacing two consecutive cell with one cell having different value.
For ex: - if my array =[0,3,1,2,3,4], and i want to replace index 0,and 1 with the value 5
to become like this array=[5,1,2,3,4]
Can you guys suggest some simple way for doing this.
i do this code but there is something wrong:
int J = 0;
if (max != 1)
{
for (int iii = 0; iii < output.Length -1; iii++)
{
if ((output[iii] == imax) && (output[iii + 1] == jmax))
{
temp = temp + 1;
output[J] = Convert.ToByte(temp);
J = J + 1;
iii = iii + 1;
}
else
{
output[J] = output[iii];
J = J + 1;
output[J] = output[iii + 1];
}
}
}
because when i want to check the 2 consecutive index ,i want to pass them to the anther 2 index
If you care about performance you want to do as little operations that can harm performance. Try this extension method:
public static int[] ReplaceConsecutiveCells(this int[] array, int startIndex, int replaceWith)
{
int[] targetArray = new int[array.Length - 1];
for (int i = 0; i < array.Length; i++)
{
if (i < startIndex)
{
targetArray[i] = array[i];
}
else if (i == startIndex)
{
targetArray[i] = replaceWith;
}
else if (i == startIndex + 1)
{
// no action
}
else
{
targetArray[i - 1] = array[i];
}
}
return targetArray;
}
Use it like this:
array = array.ReplaceConsecutiveCells(0, 5);
int[] array = new int[] { 0, 3, 1, 2, 3, 4 };
List<int> list = array.ToList();
list.RemoveRange(0,2);
list.Insert(0, 5);
array = list.ToArray();
Yet another variant
int[] array = new int[] { 0, 3, 1, 2, 3, 4 };
Array.Reverse(array);
Array.Resize(ref array, 5);
Array.Reverse(array);
array[0] = 5;
do
{
RNG_NXT =RNG +1;
for (int iii = 0; iii <Nold -1; iii++)
{
if ((output[iii] == imax) && (output[iii + 1] == jmax))
{
output[J] = Convert.ToByte(RNG_NXT);
J = J + 1;
iii = iii + 1;
}
else
{
output[J] = output[iii];
J = J + 1;
}
}
RNG++;
}
while( RNG < RNG_MAX) ;
My task is to migrate this Java code to a C# version, but I'm having trouble with the ValueOf method, since I can't seem to find a equivalent version for C# (because of the Radix parameter used on Java, 16 in this case).
public String decrypt_string(String s)
{
String s1 = "";
int i = s.length() / 2;
int[] ai = new int[i];
for (int j = 0; j < i; j++)
{
// This is the "problematic" line \/
ai[j] = Integer.valueOf(s.substring(j * 2, j * 2 + 2), 16).intValue();
}
int[] ai1 = decrypt_block(ai, i);
for (int k = 0; k < i; k++)
{
if (ai1[k] != 0)
s1 = s1 + (char)ai1[k];
}
return s1;
}
Here is my try, but it failed:
public String decrypt_string(String s)
{
String s1 = "";
int i = s.Length / 2;
int[] ai = new int[i];
for (int j = 0; j < i; j++)
{
int startIndex = j * 2;
string tmp = s.Substring(startIndex, 2);
ai[j] = Int32.Parse (tmp);
}
int[] ai1 = decrypt_block(ai, i);
for (int k = 0; k < i; k++)
{
if (ai1[k] != 0)
s1 = s1 + (char)ai1[k];
}
return s1;
}
Thanks in advance
If you are trying to parse a hexadecimal (base-16) number, use this:
int.Parse (tmp, NumberStyles.HexNumber);
You need to convert a string to an integer, given that the string is in a specific base.
int i = Convert.ToInt32(str, 16);
int j = Convert.ToInt32("A", 16); // 10
So:
for (int j = 0; j < i; j++)
{
int startIndex = j * 2;
ai[j] = Convert.ToInt32(s.Substring(startIndex, 2));
}
The radix is on Integer.valueOf(), not s.substring() in the java code you show there, so this would become:
ai[j] = Int32.Parse(s.Substring(j * 2, j * 2 + 2), 16);