Convert string to char error message [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Cannot convert string to char error message. I am trying to be able to write a program that will, for example, allow the user to input 1800HIETHC and it will give them back all digits.
I am already stuck.... Any help or advise on what to do?
static void Main(string[] args)
{
char number = ' ';
int numb = 0;
Console.WriteLine("Please enter the telephone number...");
number = Console.ReadLine();
while (number <= 10)
{
if (number == 'A')
{
numb = 2;
}
}
Console.WriteLine(numb);
}
}
}

Console.ReadLine gives you a string
a string is, among other things, a collection of chars
try this
string number = "";
int numb = 0;
Console.WriteLine("Please enter the telephone number...");
number = Console.ReadLine();
for(int i=0; i<number.Count; i++)
{
if (number[i] == 'A')
{
//...
}
}

Console.ReadLine() returns a string not a character. So you cannot assign it to the variable number.
Once you have assigned it to a string you can get characters out of the string by doing myString[0]

If I understand you correctly,
string number = "1800HIETHC"; //Console.ReadLine() reads whole line, not a single char.
int[] nums = Digits(number);
static int[] Digits(string number)
{
return number.Where(char.IsLetterOrDigit).Select(ToNum).ToArray();
}
static int ToNum(char c)
{
int[] nums = { 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9 };
if (char.IsDigit(c)) return c - '0';
c = char.ToUpper(c);
return nums[c - 'A'];
}

Related

For loop with ref array in C# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
how does this loop work that i get the result of 11, 2, 13, 4, 15?
What i mean is to explain how one number enters the for loop and what happens
static void Main(string[] args)
{
int[] arr = new int[] { 1, 2, 3, 4, 5 };
fun1(ref arr);
Console.ReadLine();
}
static void fun1 (ref int[] array)
{
for (int i = 0; i < array.Length; i = i + 2)
{
array[i] = array[i] + 10;
}
Console.WriteLine(string.Join(",", array));
}
}
You loop statement
for (int i = 0; i < array.Length; i = i + 2)
Assuming array's length is 5, your loop variable i starts from 0. It them gets incremented by 2 every iteration. This is because you have defined the expression i = i+2. So i go from 0 -> 2 -> 4, when it gets to 6, it doesn't enter the loop.
Thus, you only access the odd elements of the array

Missing number -n to n [closed]

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/

Finding the highest pair in int array [closed]

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 8 years ago.
Improve this question
I have a dice game, where I need to find the highest pair of 5 dices and get the total of it.
I have made this code so far which counts the numbers into pairs. Now I want to find the highest pair.
Code:
int Pair[];
Pair = new int[7] {0, 0, 0, 0, 0, 0, 0} //Seven pairs because i dont want to use Pair[0]
int TT[];
TT = new int[5] { 1, 6, 3, 1, 3 }; //five dice
int t = 1;
for(int i = 0; i < 5; i++)
{
if ( TT[i] == t)
{
Pair[t] = Pair[t] + 1;
t = t + 1;
}
}
If I understand your problem correctly, I think you are overcomplicating it. If you think about it, what you want are the two highest numbers from an arry. Simply sort it, and reverse it, and take the two first numbers.
class Program
{
static void Main(string[] args)
{
int[] Dice = new int[5] { 1, 6, 3, 1, 3 };
Array.Sort(Dice);
Array.Reverse(Dice);
Console.WriteLine("The largest pair is ({0}, {1})", Dice[0], Dice[1]);
}
}
The other possibility for the largets pair (as mentioned in a comment) is that you want to find the highest number in the list that occurs twice. You can do this by sorting the Array, reversing it, so you read from the highest number. Then incrementally check if the current number matches the next number, and if this is the case, you found the highest pair.
class Program
{
static void Main(string[] args)
{
int[] Dice = new int[5] { 1, 6, 3, 1, 3 };
Array.Sort(Dice);
Array.Reverse(Dice);
for (int i = 1; i < Dice.Length; i++)
{
if (Dice[i] == Dice[i - 1])
{
Console.WriteLine("The largest pair is ({0}, {1})", Dice[i], Dice[i-1]);
break;
}
}
}
}

convert binary string to integer array in c# [closed]

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

Efficient algorithm to find a combination, which summation is equal to a known number, in a set of number

Let's say there is a set of number
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
I want to find out several combinations in the set of number such that the summation of it equal to a known number, for example, 18. We can find out that 5, 6, 7 is matched (5+6+7=18).
Numbers in a combination cannot be repeated and the number in a set may not be consecutive.
I've wrote a C# program to do that. The program is random to pick up number to form a combination and check whether the summation of combination is equal to a known number. However, the combination the program found may be repeated and it makes the progress not effective.
I am wondering whether there is any efficient algorithm to find out such combination.
Here's part of my code.
int Sum = 0;
int c;
List<int> Pick = new List<int>();
List<int> Target = new List<int>() {some numbers}
Target.Sort();
while (!Target.Contains(Sum))
{
if (Sum > Target[Target.Count - 1])
{
Pick.Clear();
Sum = 0;
}
while (true)
{
if (Pick.IndexOf(c = Math0.rand(0, Set.Count - 1)) == -1)
{
Pick.Add(c);
}
//Summation Pick
Sum = 0;
for (int i = 0; i < Pick.Count; i++)
Sum += Set[Pick[i]];
if (Sum >= Target[Target.Count - 1])
break;
}
}
Result.Add(Pick);
You can use recursion. For any given number in the set, find the combinations of smaller numbers that adds up to the number:
public static IEnumerable<string> GetCombinations(int[] set, int sum, string values) {
for (int i = 0; i < set.Length; i++) {
int left = sum - set[i];
string vals = set[i] + "," + values;
if (left == 0) {
yield return vals;
} else {
int[] possible = set.Take(i).Where(n => n <= sum).ToArray();
if (possible.Length > 0) {
foreach (string s in GetCombinations(possible, left, vals)) {
yield return s;
}
}
}
}
}
Usage:
int[] set = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
foreach (string s in GetCombinations(set, 18, "")) {
Console.WriteLine(s);
}
Output:
1,2,4,5,6,
3,4,5,6,
1,2,3,5,7,
2,4,5,7,
2,3,6,7,
1,4,6,7,
5,6,7,
1,2,3,4,8,
2,3,5,8,
1,4,5,8,
1,3,6,8,
4,6,8,
1,2,7,8,
3,7,8,
2,3,4,9,
1,3,5,9,
4,5,9,
1,2,6,9,
3,6,9,
2,7,9,
1,8,9,
1,3,4,10,
1,2,5,10,
3,5,10,
2,6,10,
1,7,10,
8,10,
A possible alternative method. With a small set like this, you could use brute force. Your set {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} has 10 elements, and each element can be present or not present. That can be mapped to a binary number between 0 (= 0b0000000000) and 1023 (= 0b1111111111). Loop through the numbers from 0 to 1023, inclusive, and check the sum for the subset corresponding to the set bits of the binary representation of the number.
Maybe not the most useful for this particular question, but a good way to generate all possible subsets of a given set.

Categories

Resources