Its a program using a bitwise operators - c#

The number of can types to be distinguished is N, and each can has L types of characteristics that can be answered with 1 or 0. Your objective is to distinguish between all N types of can by memorizing the characteristics of as few of the L types as possible.
All test cases satisfy the following conditions:
2 ≤ N ≤ 100
1 ≤ L ≤ 8・0 ≤ X_{i, j} ≤ 1(1 ≤ i ≤ N
1 ≤ j ≤ L)
definitely distinguishable.
using System;
namespace CanDistinguisher
{
class Program
{
static void Main(string[] args)
{
// Read the number of can types and number of features
string[] input = Console.ReadLine().Split();
int N = int.Parse(input[0]);
int L = int.Parse(input[1]);
// Read the answers to the questions for each feature
int[,] cans= new int[N, L];
for (int i = 0; i < N; i++)
{
input = Console.ReadLine().Split();
for (int j = 0; j < L; j++)
{
cans[i, j] = int.Parse(input[j]);
}
}
// Find the minimum number of features required to distinguish all N types of can
int result = L;
for (int i = 0; i < (1 << L); i++)
{
int[] group = new int[N];
for (int j = 0; j < N; j++)
{
for (int k = 0; k < L; k++)
{
if (((i >> k) & 1) == 1)
{
group[j] |= (cans[j, k] << k);
}
}
}
bool flag = true;
for (int j = 0; j < N; j++)
{
for (int k = j + 1; k < N; k++)
{
if (group[j] == group[k])
{
flag = false;
break;
}
}
}
if (flag)
{
int count = 0;
for (int j = 0; j < L; j++)
{
if (((i >> j) & 1) == 1)
{
count++;
}
}
result = Math.Min(result, count);
}
}
// Output the result
Console.WriteLine(result);
}
}
}
In this program I did not understand the logic. If someone can help me understand the logic. For example why are they doing this particular line.
if (((i >> k) & 1) == 1)
{
group[j] |= (cans[j, k] << k);
}
I still don't understand the bitwise operators and its use cases. If someone can help me understand the complete code and its logic would be very helpful.
Thank you in advance.

Related

How to write recursive function for nested loops in C#

How can I write recursive function for this for loops I am making sum of this array elements.
int[,,,] exampleArray = new int[1,2,3,4];
int sum = 0;
for (int i = 0; i < 1; i++)
{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 4; l++)
{
sum += exampleArray[i, j, k, l];
}
}
}
}
Console.WriteLine(sum);
it is actually quite simple, just need a way to represent all 4 indexes as single variable:
static int recursiveSum(int[,,,] a, int index = 0)
{
int ti = index;
int l = ti % a.GetLength(3); ti /= a.GetLength(3);
int k = ti % a.GetLength(2); ti /= a.GetLength(2);
int j = ti % a.GetLength(1); ti /= a.GetLength(1);
int i = ti % a.GetLength(0); ti /= a.GetLength(0);
if (ti > 0) {
return 0;
}
return a[i, j, k, l] + recursiveSum(a, index + 1);
}
static void Main(string[] args)
{
int[,,,] exampleArray = new int[1, 2, 3, 4];
int sum = recursiveSum(exampleArray);
Console.WriteLine(sum);
}

C# : Find the largest palindromic number made from product of 3-digit numbers

I'm writing a program to find the largest palindromic number made from product of 3-digit numbers. Firstly,i Create a method which has ability to check if it is a palindromic number. Here is my code :
static int check(string input_number)
{
for (int i = 0; i < input_number.Length/2; i++)
if (input_number[i] != input_number[input_number.Length - i])
return 0;
return 1;
}
After that, it's my main code:
static void Main(string[] args)
{
int k = 0;
for (int i = 0; i < 999; i++)
for (int j = 0; j < 999; j++)
{
k = i * j;
if (check(k.ToString()) == 1)
Console.Write(k + " ");
}
}
But when it has a problem that the length of input_number is zero. So my code doesn't run right way. What can I do to solve the length of input_number?
You have a few bugs in your code:
1. 3-digit-numbers range from `100` to `999`, not from `0` to `998` as your loops currently do.
So your Main method should look like this:
static void Main(string[] args)
{
int k = 0;
for (int i = 100; i <= 999; i++)
for (int j = 100; j <= 999; j++)
{
k = i * j;
if (check(k.ToString()) == 1)
Console.Write(k + " ");
}
}
Now all pairs of three digit numbers are checked. But to improve performance you can let j start at i, because you already checked e.g. 213 * 416 and don't need to check 416 * 213 anymore:
for (int i = 100; i <= 999; i++)
for (int j = i; j <= 999; j++) // start at i
And since you want to find the largest, you may want to start at the other end:
for (int i = 999; i >= 100; i--)
for (int j = 999; j >= 100; j--)
But that still does not guarantee that the first result will be the largest. You need to collect the result and sort them. Here is my LINQ suggestion for your Main:
var results = from i in Enumerable.Range(100, 900)
from j in Enumerable.Range(i, 1000-i)
let k = i * j
where (check(k.ToString() == 1)
orderby k descending
select new {i, j, k};
var highestResult = results.FirstOrDefault();
if (highestResult == null)
Console.WriteLine("There are no palindromes!");
else
Console.WriteLine($"The highest palindrome is {highestResult.i} * {highestResult.j} = {highestResult.k}");
2. Your palindrome-check is broken
You compare the character at index i to input_number[input_number.Length - i], which will throw an IndexOutOfRangeException for i = 0. Strings are zero-based index, so index of the last character is Length-1. So change the line to
if (input_number[i] != input_number[input_number.Length - i - 1])
Finally, I suggest to make the check method of return type bool instead of int:
static bool check(string input_number)
{
for (int i = 0; i < input_number.Length/2; i++)
if (input_number[i] != input_number[input_number.Length - i - 1])
return false;
return true;
}
This seems more natural to me.
You can use method below. Because you are trying to find the largest number you start from 999 and head backwards, do multiplication and check if its palindrome.
private void FindProduct()
{
var numbers = new List<int>();
for (int i = 999; i > 99; i--)
{
for (int j = 999; j > 99; j--)
{
var product = i * j;
var productString = product.ToString();
var reversed = product.Reverse();
if (product == reversed)
{
numbers.Add(product);
}
}
}
Console.WriteLine(numbers.Max());
}

Displaying result of KMP compute prefix function

I'm trying to solve homework for school, it concerns KMP algorithm. Here is my compute prefix function, it is suppose to output a prefix table, however all it does is every time it returns all 0s. Could help me understand what am I doing wrong? Thanks!
static int[] computePrefixFunction(string P)
{
int m = P.Length;
int[] pi = new int[m];
pi[1] = 0;
int k = 0;
for (int j = 2; j < m; j++)
{
while (k > 0 && P[k + 1] != P[j])
{
k = pi[k];
}
if (P[k+1] == P[j])
{ k = k + 1; };
pi[j] = k;
}
for (int i = 0; i < pi.Length; i++)
{
Console.WriteLine(pi[i]);
}
return pi;
}
You a have messed up indexes offsets. Here is fixed version:
static int[] computePrefixFunction(string P)
{
int m = P.Length;
int[] pi = new int[m];
int k = 0;
for (int j = 1; j < m; j++)
{
k = pi[j - 1];
while (k > 0 && P[k] != P[j])
k = pi[k-1];
if (P[k] == P[j])
k = k + 1;
pi[j] = k;
}
return pi;
}
Live demo: https://dotnetfiddle.net/YQknMp

I am making a sudoku on c#

enter code here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace testing_random
{
class Program
{
static void Main(string[] args)
{
int n = 4;
int[,] a = new int[n,n];//declaring the matrix
Random o = new Random();
a[0,0] = o.Next(n);
for (int i = 1; i < n; i++)//filling the first line
{
int d = 1;
while (d != 0)
{
a[i,0] = o.Next(n);
d = 0;
for (int j = 0; j < i; j++)
if (a[i,0] == a[j,0])
d++;
}
}
for (int i = 1; i < n; i++)//filing the first column
{
int d = 1;
while (d != 0)
{
a[0, i] = o.Next(n);
d = 0;
for (int j = 0; j < i; j++)
if (a[0, i] == a[0, j])
d++;
}
}
for (int k = 1; k < n; k++)//filling the rest of the matrix
for (int i = 1; i < n; i++)
{
int d = 1;
while (d != 0)
{
a[i, k] = o.Next(n);
d = 0;
for (int j = 0; j < i; j++)
if (a[i, k] == a[j, k])
d++;
for (int j = 0; j < k; j++)
if (a[i, k] == a[i, j])
d++;
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
Console.Write("{0} ", a[i, j]);
Console.WriteLine();
}
Console.ReadLine();
}
}
}
The output should be a matrix of 4*4 where each column and each line contains each number once.
The problem is when i run the code, not every time i get an output, i think the problem is not every set of first line and column can give a matrix as required the i get into an unending loop.
what i want to do is limit the running time of the application to 100 ms per example,so if the matrix is not filled,the program restarts
What piece of code am i missing?
replace the while( d != 0 ) with a loop which counts up to a certain very large maximum number of iterations. (Try 1000, 100000, whatever.)
Are you trying to randomly insert numbers between 1-4 in the first line of the array? If so there is a much easier way to do it.
You can generate the 4 numbers to be inserted into the array and then just look through the first line of the array and set each value.
Random rnd = new Random();
var randomNumbers = Enumerable.Range(1, 4).OrderBy(i => rnd.Next()).ToArray();
for (int i = 0; i < n; i++)
{
a[i, 0] = randomNumbers[i];
}

C# FFT Implementation not producing expected results

I'm trying to implement, in C#, for my own learning, an FFT algorithm described here:
https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm
under "Data reordering, bit reversal, and in-place algorithms".
My code is as follows, with some background operator overloading for the "cplx" structure to allow me to do arithmetic on these objects.
Bitreverse seems to work fine, and so does the "twiddle factor" calculation, so I'm not sure where I've gone wrong. The code looks awfully similar to the pseudocode given on the wiki page.
public cplx[] FFT(cplx[] x)
{
//Bitreverse Copy
cplx[] a = BitReverse(x);
//Number of points
int n = a.Length;
for (int s = 1; s <= Math.Log(n); s++)
{
int m = (int)Math.Pow(2,s);
cplx w_m = Omega(m);
for (int k = 0; k < n; k += m)
{
cplx w = new cplx(1, 0);
for(int j = 0; j < m/2; j++)
{
cplx t = w * a[k + j + (m / 2)];
cplx u = a[k + j];
a[k + j] = u + t;
a[k + j + (m / 2)] = u - t;
w = w * w_m;
}
}
}
return a;
}
I'm testing it with an input array of an origin-impulse with 8 samples, which should produce a constant output.
Instead, I'm getting 4 ones and 4 zeros, in that order.
As an aside, I assume that in the pseudocode:
for k = 0 to n-1 by m
Refers to for(k = 0; k < n; k += m) although I'm not sure that's right.
Hopefully someone can shed some light on my incompetence!
Cheers.
Here's the code for bitreversal and the omega calculation.
private int Rev(int x, int k)
{
int reversed = 0;
for (int i = 0; i < k; i++)
{
reversed |= (x & (1 << i)) != 0 ? 1 << (k - 1 - i) : 0;
}
return reversed;
}
public cplx[] BitReverse(cplx[] x)
{
cplx[] r = new cplx[x.Length];
int bits = (int)Math.Log(x.Length, 2);
for(int k = 0; k < x.Length; k++)
{
r[Rev(k, bits)] = x[k];
}
return r;
}
private cplx Omega(int m)
{
float x = (- 2 * (float)Math.PI) / m;
return new cplx((float)Math.Cos(x), (float)(Math.Sin(x)));
}
I should have been using log2(n) when I was using Math.Log().

Categories