I tried many option from what i could find here and on MSDN but none seems working.
So basicly i have to read a file, and then turn the content to char[][]
for example :
file:
ABCD
EFGH
QWER
Need to become :
{ { 'A','B','C','D' },{ 'E','F','G','H' },{ 'Q','W','E','R' } }
And this what i did so far:
private static char[][] ParseFile(string file)
{
string[] fileOne = File.ReadAllLines(file);
char[][] fileOut = {};
char[] fileOutLine;
for (int i = 0; i < fileTwo.Length ; i++)
{
string linew = fileTwo[i];
for (int j = 0; j < linew.Length; j++)
{
//Stuck here
}
}
return fileOut;
private static char TurntoChar(string s)
{
switch (s)
{
case "S":
return 'S';
break;
case "O":
return 'O';
break;
case "F":
return 'F';
break;
default:
return 'B';
break;
}
}
}
internal class Point
{
public Point(int x, int y)
{
X = x;
Y = y;
}
public int Y { get; set; }
public int X { get; set; }
}
}
Thanks in advance!
You could use Linq;
var fileOut = fileOne.Select(x => x.ToCharArray()).ToArray();
If you don't want to use Linq;
string[] fileOne = File.ReadAllLines(file);
char[][] fileOut = new char[fileOne.Length][];
for (int i = 0; i < fileOne.Length; i++)
{
fileOut[i] = fileOne[i].ToCharArray();
}
You should really give lambda a shot. It would make your life way easier.
Well, if you insist then here you go
string[] lines = File.ReadAllLines(#"yourpath");
char[][] charArray = new char[lines.Length][];
for (int i = 0; i < lines.Length; i++)
{
char[] lineChars = new char[lines[i].Length];
charArray[i] = lineChars;
for (int j = 0; j < lines[i].Length; j++)
{
charArray[i][j] = lines[i][j];
}
}
Related
Find whether the input string can form a valid English word. Ideally, we need to compare the input string in the English dictionary. Though an API dictionary is not required to search for the word, I have taken a hardcoded string array(which acts as an English dictionary here). Below is the code. Could you please help me with what's wrong with the code?
The output of the program should be the string of the dictionary if it matches the input string.
public class Program
{
public static string Jumble(string input)
{
string[] array = { "abstract", "car", "flight" };
Dictionary<char, int> inputDict = new Dictionary<char, int>();
for (int i = 0; i < input.Length; i++)
{
if (inputDict.ContainsKey(input[i]))
{
inputDict[input[i]]++;
}
else
{
inputDict.Add(input[i], 1);
}
}
Dictionary<char, int> arrayDict = new Dictionary<char, int>();
for (int j = 0; j < array.Length; j++)
{
for (int k = 0; k < array[j].Length; k++)
{
if (arrayDict.ContainsKey(array[j][k]))
{
arrayDict[array[j][k]]++;
}
else
{
arrayDict.Add(array[j][k], 1);
}
}
}
for (int j = 0; j < array.Length; j++)
{
for (int k = 0; k < array[j].Length; k++)
{
if(inputDict.ContainsKey(array[j][k]) && inputDict.ContainsValue(arrayDict[array[j][k]]) && array[j].Length == input.Length)
{
Console.WriteLine(array[j]);
}
else
{
Console.WriteLine("Doesn't match");
}
}
}
return "";
}
static void Main(string[] args)
{
string input = "tracabst";
Console.WriteLine(Jumble(input));
Console.ReadLine();
}
} ```
public class Program
{
// Jumble: "tracabst";
// Dictionary: "abstract", "car", "flight"
public static string Jumble(string input)
{
string[] array = { "abstract", "car", "flight" };
string result = "";
List<char> listOfChar = new List<char>(input);
for (int j = 0; j < array.Length; j++)
{
for (int k = 0; k < array[j].Length; k++)
{
if (listOfChar.Contains(array[j][k]) && array[j].Length == input.Length)
{
listOfChar.Remove(array[j][k]);
result = array[j];
}
}
}
if(listOfChar.Count > 0)
{
return "Doesn't Match";
}
return result;
}
static void Main(string[] args)
{
string input = "tracabst";
Console.WriteLine(Jumble(input));
Console.ReadLine();
}
}
So I am creating a hangman-type game in C# and I want the user's input to be recognized as a variable. So I am trying to use this variable(user input) and see if it is found in the word chosen. However, there is no .Contain function that works with "char" variables. Is there any way to make this work? (The part in asterisks is the portion I want to add this code to)
using System;
namespace Hangman
{
class WordChoice
{
static void Main(string[] args)
{
Random rand = new Random();
int numword = rand.Next(2);
string word = "";
char[] ltrlist = { ' ' };
char ltrchce = ' ';
int strlength = 0;
**void ltrcheck()
{
if
{
Console.WriteLine("Great you got a letter");
}
}**
if (numword == 1)
{
word = "Shrek";
strlength = word.Length;
ltrlist = new char[strlength];
for (int a = 0; a < strlength; a++)
{
ltrlist[a] = word[a];
}
}
if (numword == 2)
{
word = "Venom";
strlength = word.Length;
ltrlist = new char[strlength];
for (int a = 0; a < strlength; a++)
{
ltrlist[a] = word[a];
}
}
if (numword == 3)
{
word = "Avengers";
strlength = word.Length;
ltrlist = new char[strlength];
for (int a = 0; a < strlength; a++)
{
ltrlist[a] = word[a];
}
}
if (numword == 4)
{
word = "Inception";
strlength = word.Length;
ltrlist = new char[strlength];
for (int a = 0; a < strlength; a++)
{
ltrlist[a] = word[a];
}
}
if (numword == 5)
{
word = "Batman";
strlength = word.Length;
ltrlist = new char[strlength];
for (int a = 0; a < strlength; a++)
{
ltrlist[a] = word[a];
}
}
string undscr = "";
for (int i = 0; i < strlength; i++)
{
undscr = undscr + " _";
}
Console.WriteLine(undscr);
Console.WriteLine("");
Console.WriteLine("Pick a letter");
string ltrchcestr = Console.ReadLine();
ltrchce = Convert.ToChar(ltrchcestr);
ltrcheck();
}
}
}
You can do a function like this
static bool Contains(IEnumerable < char > items, char letter)
=> return items?.Any(c => c == letter) == true;
or just create a typeExtension, for Project wide use:
public static class CharExtensions {
public static bool Contains(this IEnumerable<char> items, char letter ){
return items?.Any(c => c == letter) == true;
}
}
this test will now work:
var chars = new []{'a','b','c'};
Console.WriteLine(chars.Contains('m'));
Console.WriteLine(chars.Contains('b'));
I'm stuck at "sorting" 2 different arrays.
My goal is to get rid of numbers that are included in array1 and array2.
Here is an example:
int [] arr1 = {1,2,3,4,5,6 } ;
int [] arr2 = {3,4} ;
Values in array arr1 should be like this : 1,2,5,6 (without 3 and 4)
My code so far:
static int[] test(int[]a,int[]b)
{
int i = 0;
int g = 0;
int d = 0;
int indexB = 0;
while( i < a.Length)
{
bool dvojnost = false;
int j = 0;
while (j<b.Length)
{
if (a[i] == b[j])
{
dvojnost = true;
indexB = j;
break;
}
else
j++;
}
int trenutniElementB = 0;
if(dvojnost==true)
{
while (trenutniElementB < b.Length)
{
if (trenutniElementB != indexB)
{
b[g] = b[trenutniElementB];
g++;
trenutniElementB++;
}
else
{
trenutniElementB++;
}
}
}
int h = 0;
if (dvojnost == true)
{
while (h < a.Length)
{
if (h != i)
{
a[d] = a[h];
d++;
h++;
}
else
{
h++;
}
}
}
i++;
}
return a;
}
This coding is only for extending my knowledge with arrays :)
Use LINQ :-)
int[] result = array1.Except(array2).ToArray();
If you are determined on using only loops and no Linq or Lists you could go for this...
static void Main(string[] args)
{
int[] arr1 = { 1, 2, 3, 4, 5, 6 };
int[] arr2 = { 3, 4 };
int[] result = test(arr1, arr2);
}
static int[] test(int[] a, int[] b)
{
int k = 0;
bool toAdd;
int[] output = new int[] { };
for (int i = 0; i < a.Length; i++)
{
toAdd = true;
for (int j = 0; j < b.Length; j++)
{
if (a[i] == b[j])
{
toAdd = false;
break;
}
}
if (toAdd)
{
Array.Resize(ref output, k + 1);
output[k] = a[i];
k++;
}
}
return output;
}
If you are treating second array as exclusion list for your result then maybe using generic List<> class will be enough to create simple code like this:
static int[] test(int[] a, int[] b)
{
List<int> result = new List<int>();
List<int> exclusion = new List<int>(b);
for (int i = 0; i < a.Length; i++)
{
if (exclusion.IndexOf(a[i]) >= 0)
continue;
result.Add(a[i]);
}
return result.ToArray();
}
Split your method into 2 parts.
First get rid of duplicates and then sort the array:
public int[] RemoveAndSort(int[] a, int[] b){
List<int> temp = new List<int>();
for(int i = 0; i < a.Length; i++){
bool found = false;
for(int j = 0; j < b.Length; j++){
if(a[i] == b[j]){
found = true;
}
}
if(!found) temp.Add(a[i]);
}
temp.Sort();
return temp.ToArray();
}
I used a List in my solution but you could also use a new empty array that is the same length of a at the start of the method.
Don't reinvent the wheel, use LINQ. Anyhow, if you are doing this as an excercise to understand arrays, here is an impementation that avoids LINQ altoghether:
public static T[] Except<T>(this T[] first, T[] second)
{
if (first == null)
throw new ArgumentNullException(nameof(first));
if (second == null)
throw new ArgumentNullException(nameof(second));
if (second.Length == 0)
return first;
var counter = 0;
var newArray = new T[first.Length];
foreach (var f in first)
{
var found = false;
foreach (var s in second)
{
if (f.Equals(s))
{
found = true;
break;
}
}
if (!found)
{
newArray[counter] = f;
counter++;
}
}
Array.Resize(ref newArray, counter);
return newArray;
}
You can try this, without any generics collections :) Only arrays:
public class Program
{
static void Main(string[] args)
{
int resultLength = 0;
int[] arr1 = { 1, 2, 3, 4, 5, 6 };
int[] arr2 = { 3, 4 };
int[] result = new int[resultLength];
for(int i = 0; i < arr1.Length; i++)
{
if(!arr2.Exists(arr1[i]))
{
resultLength++;
Array.Resize(ref result, resultLength);
result[resultLength- 1] = arr1[i];
}
}
}
}
public static class MyExtensions
{
public static bool Exists(this int[] array, int value)
{
for(int i = 0; i < array.Length; i++)
{
if (array[i] == value)
return true;
}
return false;
}
}
I am trying to generate a text file of distinct 5-card poker hands, very similar to this question (which I actually posted an answer to). The program I pieced together from this answer to that question mostly works. However, there are two major problems: The number of hands is incorrect, and every hand has the 2 of Hearts in it. Perhaps if the number of hands was correct, the hands would be correct as well.
The person that posted the answer I was working from stated that he got the correct number by not seeding the initial card. However, if you remove the seed you get an Invalid Exception error when it tries to do the ranking down the line. Seeding it makes the program work, but returns only half of the hands.
What do I need to do to this code to get all distinct 5 card poker hands?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace PokerHands
{
struct Card
{
public int Suit { get; set; }
public int Rank { get; set; }
}
class Hand
{
public List<Card> Cards { get; set; }
public string HandString { get; set; }
}
class Program
{
static int ranks = 13;
static int suits = 4;
static int cardsInHand = 5;
static List<Hand> possibleHands = new List<Hand>();
static void Main(string[] args)
{
List<Card> cards = new List<Card>();
cards.Add(new Card() { Rank = 0, Suit = 0 });
int numHands = GenerateAllHands(cards);
int counter = 0;
Console.WriteLine(numHands);
Console.WriteLine(possibleHands.Count);
possibleHands.Shuffle();
using (System.IO.StreamWriter file = new System.IO.StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "Hands.txt"))
{
foreach (Hand hand in possibleHands)
{
counter += 1;
hand.Cards.Shuffle();
foreach (Card card in hand.Cards)
{
hand.HandString += GetCardName(card) + " ";
}
file.WriteLine(hand.HandString.Trim());
}
}
Console.ReadLine();
}
static string GetCardName(Card card)
{
string cardName;
string cardFace;
string cardSuit;
switch (card.Rank)
{
case 0:
cardFace = "2";
break;
case 1:
cardFace = "3";
break;
case 2:
cardFace = "4";
break;
case 3:
cardFace = "5";
break;
case 4:
cardFace = "6";
break;
case 5:
cardFace = "7";
break;
case 6:
cardFace = "8";
break;
case 7:
cardFace = "9";
break;
case 8:
cardFace = "10";
break;
case 9:
cardFace = "J";
break;
case 10:
cardFace = "Q";
break;
case 11:
cardFace = "K";
break;
default:
cardFace = "A";
break;
}
switch (card.Suit)
{
case 0:
cardSuit = "H";
break;
case 1:
cardSuit = "D";
break;
case 2:
cardSuit = "S";
break;
default:
cardSuit = "C";
break;
}
cardName = cardFace + cardSuit;
return cardName;
}
static int GenerateAllHands(List<Card> cards)
{
if (cards.Count == cardsInHand)
{
Hand hand = new Hand();
hand.Cards = cards;
possibleHands.Add(hand);
return 1;
}
List<Card> possibleNextCards = GetPossibleNextCards(cards);
int numSubHands = 0;
foreach (Card card in possibleNextCards)
{
List<Card> possibleNextHand = cards.ToList(); // copy list
possibleNextHand.Add(card);
numSubHands += GenerateAllHands(possibleNextHand);
}
return numSubHands;
}
static List<Card> GetPossibleNextCards(List<Card> hand)
{
int maxRank = hand.Max(x => x.Rank);
List<Card> result = new List<Card>();
// only use ranks >= max
for (int rank = maxRank; rank < ranks; rank++)
{
List<int> suits = GetPossibleSuitsForRank(hand, rank);
var possibleNextCards = suits.Select(x => new Card { Rank = rank, Suit = x });
result.AddRange(possibleNextCards);
}
return result;
}
static List<int> GetPossibleSuitsForRank(List<Card> hand, int rank)
{
int maxSuit = hand.Max(x => x.Suit);
// select number of ranks of different suits
int[][] card = GetArray(hand, rank);
for (int i = 0; i < suits; i++)
{
card[i][rank] = 0;
}
int[][] handRep = GetArray(hand, rank);
// get distinct rank sets, then find which ranks they correspond to
IEnumerable<int[]> distincts = card.Distinct(new IntArrayComparer());
List<int> possibleSuits = new List<int>();
foreach (int[] row in distincts)
{
for (int i = 0; i < suits; i++)
{
if (IntArrayComparer.Compare(row, handRep[i]))
{
possibleSuits.Add(i);
break;
}
}
}
return possibleSuits;
}
class IntArrayComparer : IEqualityComparer<int[]>
{
#region IEqualityComparer<int[]> Members
public static bool Compare(int[] x, int[] y)
{
for (int i = 0; i < x.Length; i++)
{
if (x[i] != y[i]) return false;
}
return true;
}
public bool Equals(int[] x, int[] y)
{
return Compare(x, y);
}
public int GetHashCode(int[] obj)
{
return 0;
}
#endregion
}
static int[][] GetArray(List<Card> hand, int rank)
{
int[][] cards = new int[suits][];
for (int i = 0; i < suits; i++)
{
cards[i] = new int[ranks];
}
foreach (Card card in hand)
{
cards[card.Suit][card.Rank] = 1;
}
return cards;
}
}
public static class ThreadSafeRandom
{
[ThreadStatic]
private static Random Local;
public static Random ThisThreadsRandom
{
get { return Local ?? (Local = new Random(unchecked(Environment.TickCount * 31 + Thread.CurrentThread.ManagedThreadId))); }
}
}
static class MyExtensions
{
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = ThreadSafeRandom.ThisThreadsRandom.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
}
Change the start of GetPossibleNextCards() to:
static List<Card> GetPossibleNextCards(List<Card> hand)
{
int maxRank = (hand.Count == 0) ? 0 : hand.Max(x => x.Rank);
And remove the first line of GetPossibleSuitsForRank(), because you are not using the result. i.e. remove this line:
int maxSuit = hand.Max(x => x.Suit); // remove this
And also remove the line in Main() which is adding the 2H:
cards.Add(new Card() { Rank = 0, Suit = 0 }); // remove this
Can generate all distinct 5 card hard in 0.2 seconds.
You cannot read a file that fast.
Hand order does not matter - there are not 52! hands.
From combinations combin(52,5) there are 2,598,960 hands.
private byte[,] pokerHands;
public byte[,] PokerHands
{
get
{
if (pokerHands == null)
{
// easy to get rank and suite from a byte
// just store byte
// type can make a card class that you pass a byte constuctor
for (byte i = 0; i < 52; i++)
Debug.WriteLine("rank " + i % 13 + " suite " + i / 13);
Stopwatch sw = new Stopwatch();
sw.Start();
int counter = 0;
pokerHands = new byte[2598960, 5];
for (int i = 51; i >= 4; i--)
{
for (int j = i-1; j >= 3; j--)
{
for (int k = j-1; k >= 2; k--)
{
for (int m = k-1; m >= 1; m--)
{
for (int n = m-1; n >= 0; n--)
{
pokerHands[counter, 0] = (byte)i;
pokerHands[counter, 1] = (byte)j;
pokerHands[counter, 2] = (byte)k;
pokerHands[counter, 3] = (byte)m;
pokerHands[counter, 4] = (byte)n;
counter++;
}
}
}
}
}
sw.Stop();
System.Diagnostics.Debug.WriteLine("counter " + counter);
System.Diagnostics.Debug.WriteLine("sw " + sw.ElapsedMilliseconds.ToString("N0"));
}
return pokerHands;
}
}
I have some string in format like that
XXXX-XXXX-X_X_
All "_" should be replaced with Letters and numberst to prodce sth like that:
XXXX-XXXX-XAXA
XXXX-XXXX-XAXB
XXXX-XXXX-XAXC
XXXX-XXXX-XAXD
XXXX-XXXX-XAXE
XXXX-XXXX-XAXF
XXXX-XXXX-XAXG
(...)
XXXX-XXXX-XZX8
XXXX-XXXX-XZX9
XXXX-XXXX-X0XA
(...)
XXXX-XXXX-X2XA
XXXX-XXXX-X2XB
I know hoe to make it with one "_".
string alphaLetters = "ABCDEFGHIJKLMNOPQRSTUWXYZ0123456789ABCDEF";
foreach (char letter in alphaLetters.ToCharArray())
{
Numbers.Add(number.Replace('_', letter)));
}
I want this code to be working with unknown number of "_".
Can you help?
IMHO it must be recursive. (Note: that does not mean it must use recursive method call, although I used recursive call in the following code, it can be easily converted to internal recursion stack. )
public static void RunSnippet()
{
var r = new List<string>();
Replace("asd_asd_asd_".ToCharArray(), 0, r);
foreach(var s in r) { Console.WriteLine(s); }
}
public static char[] possibilities = new char[] { 'A', 'B', 'C' };
public static void Replace(char[] chars, int startIndex, IList<string> result)
{
for (int i = startIndex; i < chars.Length; i++)
{
if (chars[i] != '_')
{
continue;
}
// we found first '_'
for (int j = 0; j < possibilities.Length; j++)
{
chars[i] = possibilities[j];
Replace(chars, i + 1, result);
}
chars[i] = '_'; // take back what we replaced
return; //we're done here
}
// we didn't find any '_', so all were replaced and we have result:
result.Add(new string(chars));
}
Try this one:
var alphaIndexes = new List<int>();
string alphaLetters = "ABCDEFGHIJKLMNOPQRSTUWXYZ0123456789ABCDEF";
for(int n = 0; n<Numbers.Count; n++) {
char[] numberLetters = Numbers[n].ToCharArray();
int position = 0;
for(int i = numberLetters.Length - 1; i>=0; i--) {
if(numberLetters[i] == '_') {
int alphaIndex = 0;
if(alphaIndexes.Count <= position)
alphaIndexes.Add(0);
else {
alphaIndex = alphaIndexes[position];
}
numberLetters[i] = alphaLetters[alphaIndex];
position++;
}
}
if(alphaIndexes.Count > 0) {
alphaIndexes[0]++;
for(int j = 0; j < alphaIndexes.Count; j++) {
if(alphaIndexes[j] >= alphaLetters.Length) {
alphaIndexes[j] = 0;
if (j < alphaIndexes.Count)
alphaIndexes[j+1]++;
}
}
}
Numbers[n] = new String(numberLetters);
Numbers[n].Dump();
}