So I have to write a code that picks our random numbers from 1 to 100 and add them to a char[] array. But I'm having some difficulty doing so as I can only add the numbers to the array if I convert them to a char using (char) which changes the number. Can someone please help me?
Thanks,
public char[] CreationListe(int nmbrevaleurTirés)
{
char[] l = new char[nmbrevaleurTirés];
for (int i = 0; i < nmbrevaleurTirés; i++)
{
l[i] = (char)(new Random().Next(1, 101));
}
return l;
}
use ToChar() method of Convert class.
Convert.ToChar(new Random().Next(1, 101))
You cannot convert an integer larger then 9 into a char because it's considered as 2 chars, i.e. 10 will be considered as 1 and 0.
so I would recommend adding it to an array of strings
(except if your trying to get a random charcode which I dont think is the case, because why till 100?)
Personally, I'd use an int[] array instead
There shouldn't be any problem in storing ints up to 65535 in a char but you will have to cast it back to an int if you don't want it to be weird:
public static void Main()
{
var x = CreationListe(200);
foreach(var c in x)
Console.WriteLine((int)c); //need to cast to int!
}
public static char[] CreationListe(int nmbrevaleurTirés)
{
char[] l = new char[nmbrevaleurTirés];
for (int i = 0; i < nmbrevaleurTirés; i++)
{
l[i] = (char)(new Random().Next(1, 65536));
}
return l;
}
https://dotnetfiddle.net/z5yoBn
If you don't cast it back to int, then you'll get the char at that character index in the unicode table. If you've put 65 into a char, you'll get A when you print it, for example. This is because A is at position 65 in the table:
(ASCII table image posted for brevity's sake)
Related
I have converted string to char[], but now when I try to get a total of all the numbers in the array, I get a wrong output. The goal is that if the user enters a number as a string e.g - 12, the output should be 3 i.e 1 + 2, another example - 123 should be 1+2+3 = 6.
I am new to coding. My apologies for any inconvienence.
static void Main(string[] args)
{
int sum = 0;
String num = Console.ReadLine();
char[] sep = num.ToCharArray();
for (int i = 0; i < sep.Length; i++)
{
sum += (sep[i]);
}
Console.WriteLine(sum);
Console.ReadLine();
}
You are currently adding ascii values. The ascii value of 1 is 49 and that of 2 Is 50... You need to use int.TryParse to convert from char to int.
int value;
for (int i = 0; i < sep.Length; i++)
{
if (int.TryParse (sep[i].ToString(),out value))
sum += value;
}
If you want to calculate sum of digits, you need to convert each char to int first. Char needs to be converted to string and then parsed into int. Your original code contains implicit conversion, which converts 1 and 2 into 49 and 50 (ASCII), thus the sum ends up being 99.
Try this code instead:
static void Main(string[] args)
{
int sum = 0;
String num = Console.ReadLine();
char[] sep = num.ToCharArray();
for (int i = 0; i < sep.Length; i++)
{
sum += int.Parse(sep[i].ToString());
}
Console.WriteLine(sum);
Console.ReadLine();
}
Just for fun here is a LINQ solution.
var sum = num.Select( c => int.Parse((string)c) ).Sum();
This solution takes advantage of the fact that a string is also an IEnumerable<char> and therefore can be treated as a list of characters.
The Select statement iterates over the characters and converts each one to an integer by supplying a lambda expression (that's the => stuff) that maps each character onto its integer equivalent. The symbol is typically prounced "goes to". You might pronounce the whole expression "C goes to whatever integer can be parsed from it."
Then we call Sum() to convert the resulting list of integers into a numeric sum.
I'm currently just 2 errors away from a working program. I'll post the line that contains error and the definition of its variable and finally the errors. Please tell me where i got wrong. Thank you.
private Dictionary<string, bool[]> letterData = new Dictionary<string, bool[]>();
public char[] mapNeurons()
{
char[] map = new char[this.letters.Items.Count];
for (int i = 0; i < map.Length; i++)
{
map[i] = '?';
}
for (int i = 0; i < this.letters.Items.Count; i++)
{
double[] input = new double[Form1.DOWNSAMPLE_HEIGHT * Form1.DOWNSAMPLE_WIDTH];
char ch = ((string)(this.letters.Items[i]))[0];
bool[] data = this.letterData[ch]; //line contains errors
for (int j = 0; j < input.Length; j++)
{
input[j] = data[j] ? 0.5 : -0.5;
}
int best = this.network.Winner(input);
map[best] = ch;
}
return map;
}
and here are the error
Error 1 The best overloaded method match for 'System.Collections.Generic.Dictionary.this[string]' has some invalid arguments
Error 2 Argument '1': cannot convert from 'char' to 'string'
I used Char instead of String because if using String it will return the whole line of the string loaded, i just wants to return the first letter of the string
for example: data = A1:000001100000000110000000111000000011100000001
if use string it will return the whole line, i just wants it to return 'A'
NEW IDENTIFIED PROBLEM:
when i enter the data, i put the data into 'A1' key, which explain why im using string, so when it didnt find 'A1' because it is char, it just find 'A' thats why it returned '?', is it possible if i use string n just read the first character which is 'A' in the string line?
First of all, you need to add items to the dictionary with the Add() method.
Secondly, your dictionary's key is a string, so you need to use a string as the index ... you can get the string representation of a char by calling ToString() on the char instance.
char ch = 'x';
private Dictionary<string, bool[]> letterData = new Dictionary<string, bool[]>();
letterData.Add(ch.ToString(), new []{true, false});
bool[] data = this.letterData[ch.ToString()];
Or change the index to char:
char ch = 'x';
private Dictionary<char, bool[]> letterData = new Dictionary<char, bool[]>();
letterData.Add(ch, new []{true, false});
bool[] data = this.letterData[ch];
bool[] data = this.letterData[ch.ToString()];
To convert char to string, ToString() can be called. This is the solution for the question.
But hafizhans, was working on some program, for which he had asked question, where he converted the Dictionary<char, bool[]> to Dictionary<string, bool[]>. Now he was storing the data from dictionary to text file something like this
A1:001110000111100001010100
Now while reading this, he only needed A1 part, so Split function did the trick.
UPDATED
Try this:
if(this.letterData.ContainsKey(ch.ToString()))
bool[] data = this.letterData[ch.ToString()];
or
if(this.letterData.ContainsKey(ch.ToString()))
bool[] data = this.letterData[ch+""];
the variable ch is most likely a char you have to use a string instead
Try the following:
char charString = 'a';
if (letterData.ContainsKey(charString.ToString()))
{
// Found
}
How about changing to:
string sCh = ch.ToString();
bool[] data = null;
if (this.letterDate.ContainsKey(sCh)
{
data = this.letterData[sCh];
}
In addition, you may want consider changing the key on the dictionary to be Char instead.
I want to break down and rearranging a string into all possible combinations
Say I have a String: ABCDEF
I want to break it down and output all possible combinations
Combination(6,6) = 1
ABCDEF
Combination(6,5) = 6
BCDEF
ACDEF
ABDEF
ABCEF
ABCDF
ABCDE
Combination(6,4) = 15
BCDE
ACDE
ABDE
ABCE
....
....
....
etc.
Combination(6,3) = 20
BCD
ACD
...
etc.
Combination(6,2) = 15
BC
AB
etc.
However the ouptut must also be arranged into alphabetical order.
How will I do this?
Thanks! Any help will be appreciated!
You can get the algorithm (actually a few of them) from Knuth Volume 4, Fascicle 3 but you'll have to convert it from his math notation to C#.
Update: As I think about this more, Fascicle 2 (Generating Permutations) is actually more helpful. You can download it free from http://www-cs-faculty.stanford.edu/~knuth/fasc2b.ps.gz though you'll need gunzip and a PostScript previewer to read it. Generating the subsets of string "ABCDE" is the easy part. Convert it to an array {'A', 'B', 'C', 'D', 'E'}, run a for loop from 0 to 2^N-1 where N is the array length, and treat each value as a bitmask of the elements you're keeping. Thus 00001, 00010, 00011,... gives you "A", "B", "AB",...
The hard part is generating all the permutations of each subset, so you get "ABC", "BAC", "CAB", etc. A brute force algorithm (like in one of the other answers) will work but will get very slow if the string is long. Knuth has some fast algorithms, some of which will generate the permutations in alphabetical order if the original string was sorted in the first place.
Well, to expand on my comment, how I got past this problem was transforming the string into a hash that doesn't care the order of the letters. The hash works by taking each unique letter, then a :, then the number of times that letter occurs.
So test = e:1,s:1,t:2
Then if somebody looks for the world tset, it would generate the same hash (e:1,s:1,t:2), and bam you have a match.
I just ran a word list (of about 20 million words), generated a hash for each one of them, and put it in a mysql table, I can find all permutations of a word (that are still words themselves, aka ered will return deer and reed) in seconds.
You can generate each permutation by incrementing a counter and converting the counter value to base n where n is the number of letters in your input. Discard any values containing repeating letters and what you have left are the possible scrabble words in alphabetic order assuming your array was sorted.
You will have to count up to (n^(n-1))*(n+1) to get the e*n! possible scrabble words.
char[] Letters = new char[] { 'A', 'B', 'C', 'D', 'E', 'F' };
// calculate e*n! (int)Math.Floor(Math.E * Math.Factorial(Letters.Length))
int x = 0;
for (int i = 1; i <= Letters.Length; i++)
x = (x + 1) * i;
for (int i = 1; x > 0; i++)
{
string Word = BaseX(i, Letters.Length, Letters);
if (NoRepeat(Word))
{
Console.WriteLine(Word);
x--;
}
}
BaseX returns the string representation of Value for the given Base and specified Symbols:
string BaseX(int Value, int Base, char[] Symbols)
{
StringBuilder s = new StringBuilder();
while (Value > Base)
{
s.Insert(0, Symbols[Value % Base]);
Value /= Base;
}
s.Insert(0, Symbols[Value - 1]);
return s.ToString();
}
NoRepeat returns false if any letter occurs more than once:
bool NoRepeat(string s)
{
bool[] Test = new bool[256];
foreach (char c in s)
if (Test[(byte)c])
return false;
else
Test[(byte)c] = true;
return true;
}
Sort the string in alphabet order. Say ABCDEF (your example)
Prepare a map between index and character
map[0] = 'A'; map[1] = 'B'; ... map[5] = 'F'
3 . Now your job is a lot more simple: find all combinations of number in which the later number is larger than the former
Combination(6,3):
for (int i = 0; i < 6 - 2; i++)
for (int j = i + 1; j < 6 - 1; j++)
for (int k = j + 1; k < 6; k++)
{
string strComb = map[i] + map[j] + map[k];
}
This is mainly the idea, you could improve in your own way.
Contact me if you want more detail!
You can use this:
static List<string> list = new List<string>();
static string letters = "bcdehijkmnopqrstuvwxyz";
static void Combine(string combinatory)
{
if(combinatory.Length < letters.Length)
{
Parallel.ForEach(letters, l =>
{
if (!combinatory.Contains(l)) Combine(combinatory + l);
});
} else
{
list.Add(combinatory);
Console.WriteLine(combinatory);
}
}
It will add to the list List all the possible combinations.
Then you can use the Sort() method in order to sort the list.
How do I convert a word into a character array?
Lets say i have the word "Pneumonoultramicroscopicsilicovolcanoconiosis" yes this is a word ! I would like to take this word and assign a numerical value to it.
a = 1
b = 2
... z = 26
int alpha = 1;
int Bravo = 2;
basic code
if (testvalue == "a")
{
Debug.WriteLine("TRUE A was found in the string"); // true
FinalNumber = Alpha + FinalNumber;
Debug.WriteLine(FinalNumber);
}
if (testvalue == "b")
{
Debug.WriteLine("TRUE B was found in the string"); // true
FinalNumber = Bravo + FinalNumber;
Debug.WriteLine(FinalNumber);
}
My question is how do i get the the word "Pneumonoultramicroscopicsilicovolcanoconiosis" into a char string so that I can loop the letters one by one ?
thanks in advance
what about
char[] myArray = myString.ToCharArray();
But you don't actually need to do this if you want to iterate the string. You can simply do
for( int i = 0; i < myString.Length; i++ ){
if( myString[i] ... ){
//do what you want here
}
}
This works since the string class implements it's own indexer.
string word = "Pneumonoultramicroscopicsilicovolcanoconiosis";
char[] characters = word.ToCharArray();
Voilá!
you can use simple for loop.
string word = "Pneumonoultramicroscopicsilicovolcanoconiosis";
int wordCount = word.Length;
for(int wordIndex=0;wordIndex<wordCount; wordIndex++)
{
char c = word[wordIndex];
// your code
}
You can use the Linq Aggregate function to do this:
"wordsto".ToLower().Aggregate(0, (running, c) => running + c - 97);
(This particular example assumes you want to treat upper- and lower-case identically.)
The subtraction of 97 translates the ASCII value of the letters such that 'a' is zero. (Obviously subtract 96 if you want 'a' to be 1.)
you can use ToCharArray() method of string class
string strWord = "Pneumonoultramicroscopicsilicovolcanoconiosis";
char[] characters = strWord.ToCharArray();
How do I split a string into an array of characters in C#?
Example String word used is "robot".
The program should print out:
r
o
b
o
t
The orginal code snippet:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
namespace Testing
{
class Program
{
static void Main(string[] args)
{
String word = "robot";
String[] token = word.Split(); // Something should be placed into the () to
//print letter by letter??
foreach (String r in token)
{
Console.WriteLine(r);
}
}
}
}
How can the codes be correctly implemented?
Why not this?
public void WriteLetters(string s)
{
foreach (char c in s)
{
Console.WriteLine(c);
}
}
If you really want to see it in an explicit character array, do the following:
string s = "robot";
char[] charArray = s.ToCharArray();
If you then want to print that out (1 per line), do the following:
for (int i = 0; i < charArray.Length; i++)
{
Console.WriteLine(charArray[i]);
}
I'm not really sure what you're trying to do, so I may be way off base.
If by tokenize, you mean store the characters in an array, you already have that in a String object1.
1 Not actually true, because String uses an indexer to iterate through the character values, whereas in C/C++, a string is actually an array of characters. For our purposes, we can treat a string as if it is an array of characters
The class String implements IEnumerable<char> and therefore to run through the letters of a string, you can just grab an IEnumerator<char> and process the chars one at a time. One way to do this is using a foreach:
foreach(char c in "robot") {
Console.WriteLine(c);
}
If you need each char in an array you can just use String.ToCharArray:
char[] letters = "robot".ToCharArray();
Do you mean something like this?
foreach(var alpha in myString.Where(c => Char.IsLetter(c)))
{
Console.WriteLine(alpha);
}
You can using ToArray() method to return the char array.
string word = "robot";
char[] array = word.ToArray();
You are trying to do too much.
Try this:
String word = "robot";
foreach (char letter in word)
{
Console.WriteLine(letter);
}
Edit:
To split the string into character array, without a loop, you can do this: word.ToCharArray()
Seems everyone wants to convert a String into an Array of Chars.
How about
for(int i = 0; i < tmpString.Length; i++)
Console.WriteLine(tmpString[i]);
Now you have the speed of a char array without the extra memory of making a copy.
edit: A String is an array of chars internally, there just isn't a way to change their values because String are immutable. But you can read from that char array. String = Read-Only char array.
I can't think of any reason to convert a String into a Char[] unless you wanted to "edit" the string.
long lTicks;
char[] tmpChar = { 'a', 'b', 'c', 'd', 'e' };
String tmpString = "abcde";
char chRead;
lTicks = DateTime.Now.Ticks;
for (int i = 0; i < 100000000; i++)
chRead = tmpChar[i%5];
Console.WriteLine(((DateTime.Now.Ticks - lTicks) / 10000).ToString());
lTicks = DateTime.Now.Ticks;
for (int i = 0; i < 100000000; i++)
chRead = tmpChar[i % 5];
Console.WriteLine(((DateTime.Now.Ticks - lTicks) / 10000).ToString());
lTicks = DateTime.Now.Ticks;
for (int i = 0; i < 100000000; i++)
chRead = tmpString[i%5];
Console.WriteLine(((DateTime.Now.Ticks - lTicks) / 10000).ToString());
lTicks = DateTime.Now.Ticks;
for (int i = 0; i < 100000000; i++)
chRead = tmpString[i % 5];
Console.WriteLine(((DateTime.Now.Ticks - lTicks) / 10000).ToString());
Console.ReadLine();
Kind of funny, the String is actually consistently faster than the Char[]. I ran each twice to make sure there wasn't a load time issue affecting the results. Compiled as Release with optimizations. Char[] was ~1950ms and String ~1850ms every run for me.