Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to convert binary value into integer array in c#.
For example consider binary value : 111 , it's integer equivalent is 7 (right most digit equals to integer 1, middle binary digit is equivalent to integer 2 and left most digit is 4, so 1+2+4 = 7).
how do I get each integer digit (i.e. 1, 2 ,4) in form of an array (or list) using c# ?
string bin = "1011";
var str = String.Join(",", bin.Reverse().Select((c, i) => (c - '0') * (1 << i)));
str will be 1,2,0,8. if you want the result as a list
var list = bin.Reverse().Select((c, i) => (c - '0') * (1 << i)).ToList();
Like this:
string binaryString = "111";
var integerValue = Convert.ToInt64(binaryString,2);
integerValue will be 7 now.
Update, thanks to the comments:
If you want to store each value then you need to go through the string step by step in a for loop and bit-shift (<< operator) to get to your desired outcome.
[Test]
public void BinaryStringToValues()
{
const string binaryString = "111";
var values = new List<int>();
for (var i = 0; i < binaryString.Length; i++)
{
if (binaryString[binaryString.Length - i - 1] == '0')
{
continue;
}
values.Add(1 << i);
}
Assert.AreEqual(1, values[0]);
Assert.AreEqual(2, values[1]);
Assert.AreEqual(4, values[2]);
}
The test will pass.
It's not entirely clear what you want, but let's assume that from this string:
"1011011"
you want to get this array:
64, 16, 8, 2, 1
then you can use this code (LINQPad program):
void Main()
{
string input = "1011011";
int[] values = input
.Select((value, idx) => value == '1'
? (1 << (input.Length - idx - 1))
: 0)
.Where(value => value > 0)
.ToArray();
values.Dump();
}
Output:
This will:
For each character that is '1'
Calculate the position, from the right, where the rightmost position is position 0
Then it will calculate 1 << x (x is that position), which will return 1 for the rightmost position, 2 for the one left of it, 4 for the one left of 2, 8 for the next, 16, 32, 64, and so on.
The array at this point would be [64, 0, 16, 8, 0, 2, 1] so we'll remove the zeroes
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
There is a number N (i.e., N = 3).
I create an array from -N to N (i.e. {-3, -2, -1, 0, 1, 2, 3})
I randomly remove a number from the array (i.e. {-3, -2, 0, 1, 2, 3}, removed -1)
I shuffle the Array (i.e. {-2, 0, 2, 3, -3, 1})
Write a function
public int FindMissing(int[] arr)
That takes the shuffled Array from the initial steps and identifies and returns the array's missing number.
I've done it like this, but I think I did it wrong:
public partial class findMissingNumber
{
public static int FindMissing(int[] arr, int N)
{
int summ = (N - 1) * N / 2;
int sumarr = 1;
for (int i = 1; i < arr.Length; i++)
{
sumarr += arr[i];
}
return summ - sumarr;
}
public static void Main()
{
Console.WriteLine(FindMissing(new int[] { -2, 0, 2, 3, -3, 1 }, 3));
Console.ReadLine();
}
}
The sum of all the numbers in an array [-N, N] is 0.
If an element is missing it'll be 0 minus the missing number.
If 1 is missing, sum = 0 - 1, therefore the missing number is -sum. Except when 0 is missing.
With LINQ is very easy:
using System.Linq;
class findMissingNumber
{
public static int FindMissing(int[] arr)
{
return (arr.Contains(0)) ? -arr.Sum() : 0;
}
public static void Main()
{
Console.WriteLine(FindMissing(new int[] { -2, 2, 1, 3, -3, -1 }));
}
}
Of course if you know that the array will always miss a number you don't even need to check if 0 is missing and it all boils down to -arr.Sum()
Without LINQ is a little longer, but works in the same way:
public static int FindMissing(int[] arr)
{
int sum = 0;
if (Array.FindIndex(arr, x => x == 0) < 0)
return 0;
Array.ForEach(arr, x => sum += x);
return -sum;
}
Again, if you know that an element will alwas be missing, you can avoid looking for zero
I used lambdas, but you can write your predicate as you like https://zetcode.com/csharp/predicate/
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
How to make output : 1 1 2 6 3 11 4 16 5 21. when i input start value = 1, and end value = 5
my code :
Console.Write("input start value : ");
start = int.Parse(Console.ReadLine());
Console.Write("input end value : ");
end = int.Parse(Console.ReadLine());
Console.WriteLine("");
for (int i = start; i <= end; i++)
{
Console.WriteLine(i);
for (int j = i; j <= end; j++)
{
int z = 1;
if (start != j)
{
z++;
Console.WriteLine((j * j) + z);
}
else
{
Console.WriteLine(start + " this j start value");
}
}
}
So it's not entirely clear to me if the 5 is used both as an end value for the 1,2,3,4,5 as well as a difference value for the 1,6,11,16,21 but I'll assume yes. Here's an algorithm for you to implement (this looks like homework, so think of this as a tip - you'll get more out of doing the coding yourself but this is how you should approach any coding exercise: write out the algorithm in the language you think in then translate it to c#)
ask the user for a start value and convert to int
ask the user for an end value and convert to int
work out a variable called n which is end minus start
make a for loop starting at x = 0, running while x is less than or equal to n ; incrementing x by 1
print out startValue plus x
print out startValue plus (endValue times x)
loop around
For a start and end of 1 and 5, the loop runs from 0 to 4. The first time the loop runs, x is 0, startValue is 1, so a 1+0 and a 1+(5*0) are printed - both 1. This continues up to the end value where x is 4, 4+1 is printed - which is 5 - and 1+(4*5) is printed - which is 21
As #dxiv has posted in the comments, the pattern for the set of numbers is to combine 1,2,3,4,5 and 1,6,11,16,21. The pattern that I see is that the gap between the second set of numbers is equal to the ending number.
We can define a function which generates these numbers:
IEnumerable<int> GetNumbers(int start, int end)
{
for (int number = start; number <= end; number++)
{
yield return number;
yield return start + ((number - 1) * end);
}
}
And can output the results like:
int start = 1;
int end = 5;
Console.WriteLine(string.Join(' ', GetNumbers(start, end)));
Output
1 1 2 6 3 11 4 16 5 21
I'd like to get numbers from user text box. There is no limit on the value. For each numbers' characters, I will first multiply by 2, 4 and 6 repeatedly and then add it together.
For example, if user input '12', then 1*2 + 2*4 = 10. if the user input '1111' the answer will be calculated like this: 1*2 + 1*4 + 1*6 + 1*2 = 12. First I've set the number in an array, but then I'm stuck on how to make it multiply different value (2, 4, and 6) every time each no is called in for loop.
Is it possible to achieve this in C#? Are there any examples that I can learn on this?
Or if you have loop OCD, here is a Linq solution
var result = input.Select((c, i) => array[i % array.Length] * (c - '0')).Sum();
Demo Here
The premise is
input is your string
array is your numbers
Select each char and index in the string (c,i)
Get the remainder after division i % array.Length for each element i % length will cycle through your array
Get the int value from the char, (c - '0') (think ascii table)
* them together
Sum the results
Additional Resources
Select(IEnumerable, Func)
Projects each element of a sequence into a new form by incorporating
the element's index.
Remainder operator %
The remainder operator % computes the remainder after dividing its
left-hand operand by its right-hand operand.
Update
However, i'm wondering what if the input is also an array (eg. {11,12}
in this case they will be calculated like this: 11*2 + 12*4 = 70)
var input = "34 5 234 54";
var result = input.Split(' ')
.Select((c, i) => array[i % array.Length] * int.Parse(x))
.Sum();
//int[] numDigitsArray // 1, 2 ,3 ,4
int[] twoFourSixArray = {2, 4, 6};
int current = 0;
int res = 0;
while (current < numDigitsArray.Length)
{
res += twoFourSixArray[current % twoFourSixArray.Length] * numDigistsArray[current];
current++;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Basically i want to count the number of consecutive 1 bits (1 bit groups) in a ulong. for example:
ulong x = 0x1BD11BDAA9FC1A22UL;
In binary it becomes: 1101111010001000110111101101010101001111111000001101000100010.
I need output as No of consecutive 1 bits = 16.
Convert to bitstring, split at 0 character while removing empty entries, count the number of groups.
static void Main()
{
long x = 0x1BD11BDAA9FC1A22;
var bitstring = Convert.ToString(x, 2) ;
Console.WriteLine("Bitstring: " + bitstring);
var oneBitGroups = bitstring.Split(new char[]{'0'}, StringSplitOptions.RemoveEmptyEntries).Length;
Console.WriteLine("The number of 1 bit groups is: " + oneBitGroups);
}
Output:
Bitstring: 1101111010001000110111101101010101001111111000001101000100010
The number of 1 bit groups is: 16
You can do that with bitshift and counting each time the least significant bit is 1 and the previous wasn't.
public static int BitGroupCount(long num)
{
int count = 0;
bool prevOne = false;
while (num != 0)
{
bool currOne = (num & 1) == 1;
if (currOne && !prevOne)
count++;
num = num >> 1;
prevOne = currOne;
}
return count;
}
If you run
Console.WriteLine(BitGroupCount((long)0x1BD11BDAA9FC1A22UL));
You will get 16 as the result
Something like this to get the value as a binary string then :
int consecutive = 0;
char? previous = null;
foreach (char c in str)
{
if (previous != null)
{
if (previous.Equals('1') && c.Equals('1'))
{
consecutive++;
}
}
previous = c;
}
return consecutive;
I think i found the solution based on Hamming Weight (thanks to PetSerAl):
public static int no_of_consecutive_one_bits(ulong x)
{
x = (x & ~(x << 1));
x -= (x >> 1) & 0x5555555555555555;
x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333);
x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f;
return ((int)((x * 0x0101010101010101) >> 56));
}
Some explanation: The x & ~(x<<1) is basically isolating the last bit in each "group". The rest is the Hamming Weight algorithm for summing the number of non-zero bits.
This should work:
ulong x = 0x1BD11BDAA9FC1A22UL;
bool last = false;
int count = 0;
for(int i = sizeof(ulong)*8-1; i >= 0; i--)
{
var c = x & (1UL<<i);
if(c != 0 && !last)
count ++;
last = c != 0;
}
count should be 16
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Good morning :) I'm working on C# and I want to write a code that can calculate the less number of hops from any point to particular point, as a picture show
click here to show the picture
I have points from 1 to 12, so if I want to calculate the less number of hops from the point 12 to 1 it will be 1 with counterclockwise not 11 hops with clockwise.
another example to clarify my question, if I want to calculate the less number of hops from the point 11 to 4 it will be 5 with counterclockwise not 6 hops with clockwise. notice : the number of points may be an odd number.
I hope you understand my question ..
Try clockwise, anticlockwise and take minimum:
private static int Hops(int a, int b) {
return Math.Min((12 + a - b) % 12, (12 + b - a) % 12);
}
Tests:
// 5
Console.WriteLine(Hops(11, 4));
// 1
Console.WriteLine(Hops(12, 1));
Edit: As Matthew Watson has mentioned in comments, you may want to know whether it clockwise or anticlockwise:
private static int ClockwiseHops(int a, int b) {
return (12 + b - a) % 12;
}
private static int AntiClockwiseHops(int a, int b) {
return (12 + a - b) % 12;
}
private static int Hops(int a, int b) {
return Math.Min(ClockwiseHops(a, b), AntiClockwiseHops(a, b));
}
private static String Solve(int a, int b) {
int hops = Hops(a, b);
if (hops == ClockwiseHops(a, b))
return String.Format("{0} -> {1} (clockwise) {2} hops", a, b, hops);
else
return String.Format("{1} -> {0} (anticlockwise) {2} hops", a, b, hops);
}
Tests:
// 12 -> 1 (clockwise) 1 hops
Console.WriteLine(Solve(12, 1));
// 11 -> 4 (clockwise) 5 hops
Console.WriteLine(Solve(11, 4));
Have you considered the % Modulo Operator? That will give you the remainder of of the first number divided by the second. For example:
6 % 3 = 0 (3 goes into 6 exactly twice so zero remaining)
10 % 4 = 2 (4 goes into 10 twice with a remainder of two)
So you will want to try both routes and then check which one is smaller.
so try:
int numberOfPositions = 12;
Math.Min ((numberOfPositions + b - a) % numberOfPositions, (numberOfPositions + a -b) % numberOfPositions);
If you would like to see how modulo calculations work then there's an online calculator here:
http://www.miniwebtool.com/modulo-calculator/
Is it this simple?
int NUM_OF_NODES = 12;
int numOfHops = NUM_OF_NODES;
int point1 = 11;
int point2 = 4;
int path1 = Math.Abs(point1 - point2);
int path2 = numOfHops - path1;
int result = path1 < path2 ? path1 : path2;
return result;
For simple function
public int getLeastPath(int point1, int point2)
{
int path1 = Math.Abs(point1 - point2);
int path2 = NUM_OF_NODES - path1;
return path1 < path2 ? path1 : path2;
}
EX : 11-8
1.Get the mod of first number and last number
11% 12 = 1
8 % 12 = 8
add the sum
if it is less than 12 > 1 + 8 = 9
else sub
subtract with the 12 -9 = 3
compare 9 with 3, lesser value will be the answer.
The easiest answers were already provided but here's a recursive function, that actually "jumps" from one number to the other:
Func<int, int, int, int> Hop = null;
Hop = (direction, start, end) =>
{
if (start < 1)
start = 12;
if (start != end)
return 1 + Hop(direction, (start + direction), end);
return 0;
};