How to check if an array contains sequential, evenly spaced numbers? - c#

I'm creating a program to determine who wins a game of poker.
For context, the input data was in the format:
8C TS KC 9H 4S 7D 2S 5D 3S AC
Where the first character indicates the strength of the card (A = Ace, T = 10, J = Jack etc) and the second indicates the suit. The first 5 cards are player one and the last 5 are player two.
The data has been read into an array, split into two arrays containing each player's hands, playerOneHands and playerTwoHands. Then this array is further split into an array describing the strengths of the cards (converting the string into integers and turning "T" into int 10, "J" into int 11 etc), playerOneCardStrengths and playerTwoCardStrengths, as well as the suits, playerOneCardSuits and playerTwoCardSuits. The strengths array was then sorted in order from highest to lowest using
Array.Sort(playerOneCardStrengths, playerOneCardSuits);
I would now like to pass these values through a function which checks whether or not a royal flush has occured. It would input these two arrays and output a boolean describing whether a royal flush had occured.
A royal flush is defined in poker as a hand containing an Ace, King, Queen, Jack and Ten all of the same suit.
This is what I have so far:
static bool determineRoyalFlush(int[] cardStrengths, string[] cardSuits)
{
bool royalFlush = false;
if (cardSuits[0] != cardSuits[1])
{
return royalFlush = false;
}
else
{
if (cardStrengths[0] != 14)
{
return royalFlush = false;
}
else
{
if (cardStrengths[0] - cardStrengths[1] == 1
&& cardStrengths[1] - cardStrengths[2] == 1
&& cardStrengths[2] - cardStrengths[3] == 1
&& cardStrengths[3] - cardStrengths[4] == 1)
{
return royalFlush = true;
}
else
{
royalFlush = false;
}
}
}
}
My two questions:
Is there a neater way to check whether whether the cardStrengths array contains sequential numbers in a number line? the last bit of code above essentially checks whether cardStrengths[0] = 14 and [1] = 13 and [2] = 12 etc. But I would like to reuse this code to check for a regular flush, and I'm just curious about how I could check, say, an array a million integers long whether or not they all count up 1 2 3 4 .. etc, or count down again.
Secondly, and more importantly, I'm getting the error "Not all code paths return a value", but I can't see any scenario where this doesn't return true or false? I'm overlooking something somewhere.
Thanks!

To Solve Your Second Question :
Your last else statement (royalFlush = False ) does not return anything . Changing the code to return False should it .

You can use a for loop to compare the items to the previous ones by starting the loop with the second one (i.e. with index 1 instead of 0).
if (cardStrengths[0] != 14) {
return false;
}
for (int i = 1; i < cardStrengths.Length; i++) {
if (cardStrengths[i - 1] - cardStrengths[i] != 1) {
return false;
}
}
return true;
The variable royalFlush is not needed.
It would add much clarity if you structured the game by adding some types representing the concepts of the game
public enum Suit
{
Club,
Diamond,
Heart,
Spade
}
public enum Rank
{
Two = 2, Three = 3, Four = 4, Five = 5, Six = 6, Seven = 7, Eight = 8, Nine = 9, Ten = 10,
Jack = 11, Queen = 12, King = 13, Ace = 14
}
Comparing with rank == Rank.Ace is more understandable than comparing rank == 14.
Cards could be represented like this:
public class Card
{
public Rank Rank { get; }
public Suit Suit { get; }
public Card(Rank rank, Suit suit)
{
Rank = rank;
Suit = suit;
}
public Card(string s)
{
switch (s[0]) {
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
Rank = (Rank)(s[0] - '0');
break;
case 'T':
Rank = Rank.Ten;
break;
case 'J':
Rank = Rank.Jack;
break;
case 'Q':
Rank = Rank.Queen;
break;
case 'K':
Rank = Rank.King;
break;
case 'A':
Rank = Rank.Ace;
break;
}
switch (s[1]) {
case 'C':
Suit = Suit.Club;
break;
case 'D':
Suit = Suit.Diamond;
break;
case 'H':
Suit = Suit.Heart;
break;
case 'S':
Suit = Suit.Spade;
break;
}
}
}
Note that I added 2 constructors. One allows you to define a card directly by specifying the values. The other one parses a string like "8C" and converts it to corresponding values.
A Hand class allows you to put the scoring methods somewhere and to abstract from bare arrays. Here again 2 constructors.
public class Hand
{
public Hand(params Card[] cards)
{
Cards = cards;
}
public Hand(string s)
{
// E.g. s = "8C TS KC 9H 4S"
string[] parts = s.Split();
Cards = parts
.Select(p => new Card(p))
.ToArray();
}
public Card[] Cards { get; }
public bool IsRoyalFlush()
{
if (Cards[0].Rank != Rank.Ace) {
return false;
}
for (int i = 1; i < Cards.Length; i++) {
if (Cards[i - 1].Rank - Cards[i].Rank != 1) {
return false;
}
}
return true;
}
//TODO: Add more scoring methods.
}
On Code Review the user Glitch presented an already very well-structured game (2048 console game (C#)).
In my answer I suggested even more structure by separating different aspects of the game. It first seems like more works, but once you have established a good structure, it is much easier to work on the code.

Related

Determine if a number can be made with prepicked numbers and times

I have 2 arrays one of the types of numbers that will be used and the 2nd array is how many times that number can be used. I have a letter that determines what kind of method will be used I need to figure out how many times I can use a certain number from an array to determine a letter+number The ‘number’ is what I have to make with all the available numbers I can use. If the number cannot be made I would like to just say number cant be made or anything but allow the program to move on.
Here is what I have
int[] picksToUse = { 100, 50, 20, 10, 5, 1 };
int[] timesToUse = { 10, 10, 10, 10, 10, 10 };
string choice = Console.ReadLine();
string input = "";
if(choice.Length > 2)
{
input = choice.Substring(choice.IndexOf("$") + 1);
}
if(...){
}
else if (choice.Equals("D"))
{
int amt = Convert.ToInt32(input);
// code here to determine if number can be made with above choices
Dispense(amt, timesToUse);
}
Assuming picksToUse and timesToUse are exactly the same as you declared them, here's a way to know if you have enough of everything in stock to "pay up". It's a boolean function, which uses recursion. You would call it with the amount needed as parameter, and it would tell you right there if you have enough of everything.
Private Function HasCashInStock(amount As Integer, Optional index As Integer = 0) As Boolean
Dim billsNeeded As Integer = amount \ picksToUse(index)
If billsNeeded > timesToUse(index) Then
Return False
End If
amount -= picksToUse(index) * billsNeeded
If amount = 0 Then
Return True
End If
Return HasCashInStock(amount, index + 1)
End Function
The \ is an integer division operator (in VB.NET, at least - I'm shamelessly letting you translate this code). If you're not familiar with the integer division operator, well, when you use it with integer it gets rid of the floating numbers.
3 / 2 is not valid on integers, because it would yield 1.5.
3 \ 2 is valid on integers, and will yield 1.
That's all there is to it, really. Oh yeah, and recursion. I like recursion, but others will tell you to avoid it as much as you can. What can I say, I think that a nice recursive function has elegance.
You can also totally copy this function another time, modify it and use it to subtracts from your timesToUse() array once you know for sure that there's enough of everything to pay up.
If HasCashInStock(HereIsTheAmountAsInteger) Then
GivesTheMoney(HereIsTheAmountAsInteger)
End If
Having two functions is not the leanest code but it would be more readable. Have fun!
This is what I used to finish my project.
public static bool Validate(int amount, int[] total, int[] needed)
{
int[] billCount = total;
int[] cash = { 100, 50, 20, 10, 5, 1 };
int total = amount;
bool isValid = true;
for (int i = 0; i < total.Length; i++)
{
if(total >= cash[i])
{
billCount[i] = billCount[i] - needed[i];
}
if(billCount[i] < 0)
{
isValid = false;
break;
}
}
return isValid;
}
I got some working code. I did it with a class. I remember when I couldn't see what good classes were. Now I can't brush my teeth without a class. :-)
I force myself to do these problems to gain a little experience in C#. Now I have 3 things I like about C#.
class ATM
{
public int Denomination { get; set; }
public int Inventory { get; set; }
public ATM(int denom, int inven)
{
Denomination = denom;
Inventory = inven;
}
}
List<int> Bills = new List<int>();
List<ATM> ATMs = new List<ATM>();
private void OP2()
{
int[] picksToUse = { 100, 50, 20, 10, 5, 1 };
foreach (int d in picksToUse )
{
ATM atm = new ATM(d, 10);
ATMs.Add(atm);
}
//string sAmtRequested = Console.ReadLine();
string sAmtRequested = textBox1.Text;
if (int.TryParse(sAmtRequested, out int AmtRequested))
{
int RunningBalance = AmtRequested;
do
{
ATM BillReturn = GetBill(RunningBalance);
if (BillReturn is null)
{
MessageBox.Show("Cannot complete transaction");
return;
}
RunningBalance -= BillReturn.Denomination;
} while (RunningBalance > 0);
}
else
{
MessageBox.Show("Non-numeric request.");
return;
}
foreach (int bill in Bills)
Debug.Print(bill.ToString());
Debug.Print("Remaining Inventory");
foreach (ATM atm in ATMs)
Debug.Print($"For Denomination {atm.Denomination} there are {atm.Inventory} bills remaining");
}
private ATM GetBill(int RequestBalance)
{
var FilteredATMs = from atm in ATMs
where atm.Inventory > 0
orderby atm.Denomination descending
select atm;
foreach (ATM bill in FilteredATMs)
{
if (RequestBalance >= bill.Denomination )
{
bill.Inventory -= 1;
Bills.Add(bill.Denomination);
return bill;
}
}
return null;
}

C# - Choosing a Random Value From an Array with Spesific Range and Times

I'm working on a fixture program which is at Console Application phase for now. I arranged the teams thanks to all of you :) but I can't organize the days that teams will play with each other. So I created an array named DaysReprep with 4 elements which they represents the days of the week.(i.e. 0 represents Monday,4 represents Friday,5 represents Saturday and 6 represents Sunday which teams can play match at these days.)I also created an array named dayCounts that holds how many times they created randomly. I want to choose them randomly but, when 0 chose randomly I don't want it to create randomly again. Like that, I want to generate randomly 1 for 3 times (not in a row.), 2 for 4 times (not in a row.) and 3 for 1 times.
Here’s my code and my output,
Any help would be appreciated.
int[] daysReprep = new int[4] { 0, 4, 5, 6 }; //holds the representation of days(0-monday,4-friday,5-saturday,6-sunday)
int RandomChosenDay; //random value
int[] dayCounters = new int[4]; //which counts which element of the daysReprep array generated by RandomChosenDay(0.element holds 0.element of daysReprep and goes so on.)
for (int i = 0; i < weeklyMatched.GetLength(1); i++)
{
RandomChosenDay = randomNum.Next(3);
switch (RandomChosenDay)
{
case 0:
if (dayCounters[0] != 1)
{
dayCounters[0]++;
break;
}
else {
RandomChosenDay = randomNum.Next(3);
}
break;
case 1:
if (dayCounters[1] != 3)
{
dayCounters[1]++;
break;
}
else {
RandomChosenDay=randomNum.Next(3);
}
break;
case 2:
if (dayCounters[2] != 4)
{
dayCounters[2]++;
break;
}
else {
RandomChosenDay = randomNum.Next(3);
}
break;
case 3:
if (dayCounters[3] != 1)
{
dayCounters[3]++;
break;
}
else {
RandomChosenDay = randomNum.Next(3);
}
break;
}
for(int a = 0; a < daysReprep.Length; a++) //Writes the elemts of the dayCounters
{
Console.WriteLine(dayCounters[a] + " ");
}

I have created a Black Jack game in c # for one player. How can I create it for two or more players?

I have to alter this in order for more than one player to be available. Do I change something in the Player class? Or do I create a new class for all Players? I am on the right track? Here is the code so far:
namespace Blackjack
{
class Program
{
static Player[] players = new Player[5];
static int pointer = 0;
class PlayingCard
{
public string Suit;
public int Value;
public int Points;
// Alternate Constructor with 2 parameters - Int for Suit, Int for Value
// We use this in the generateDeck() function
public PlayingCard(int s, int v)
{
Value = v; // Sets the Value of the card to the value of v (The second argument)
switch (s) // Case statement based on the value of s
{
case 1: // If s == 1, then set the Suit to Clubs
Suit = "♣";
break;
case 2: // If s == 2, then set the Suit to Diamonds
Suit = "♦";
break;
case 3: // If s == 3, then set the Suit to Hearts
Suit = "♥";
break;
case 4: // If s == 4, then set the Suit to Spades
Suit = "♠";
break;
}
if (Value > 10)
{
Points = 10;
}
else if (Value == 1) // If it's an ace
{
Points = 11; // Set the points to 11
}
else
{
Points = Value;
}
}
}
class Player
{
public PlayingCard[] hand;
public int cardsInHand;
public int points;
public string name;
public Player()
{
hand = new PlayingCard[5];
cardsInHand = 0;
points = 0;
}
}
static void Main(string[] args)
{
onePlayer();
Console.ReadLine();
}
// Generates the deck of 52 cards
static PlayingCard[] generateDeck()
{
PlayingCard[] deck = new PlayingCard[52]; // Declares an array of PlayingCards with a size of 52
int counter = 0; // Tells us where to save the next value into the array
// Nested for loop to generate all 52 cards - 4 possible suits with 13 possible values each
for (int suit = 1; suit < 5; suit++) // Loop through the 4 possible suits
{
for (int value = 1; value < 14; value++) // Loop through the 13 possible values
{
deck[counter] = new PlayingCard(suit, value); // Generate new card and store it in the deck
counter++; // Increment the counter
}
}
return deck; // Returns the completed deck
}
// Procedure to shuffle the deck of cards
static void shuffleDeck(ref PlayingCard[] deck)
{
Random rnd = new Random(); // Creates new Random object
PlayingCard temp; // Creates a variable for temporarily storing a PlayingCard
int num; // Creates an integer variable for storing the randomly generated numbers
for (int i = 0; i < deck.Length; i++) // Loop through each index in the array
{
num = rnd.Next(0, deck.Length); // Generate random num between 0 & 51
// Swap the contents of deck[i] and deck[num]
temp = deck[i];
deck[i] = deck[num];
deck[num] = temp;
}
// As deck is passed by reference, we do not need to return it to the main program
// The changes will have automatically been applied to the deck in the main program
}
static void outputCard(PlayingCard card)
{
switch (card.Value) // Case statement based on the value of card
{
// Case for 1 - "The Ace of ..."
case 1:
Console.WriteLine("The Ace of {0}", card.Suit);
break;
// Case for 11 - "The Jack of ..."
case 11:
Console.WriteLine("The Jack of {0}", card.Suit);
break;
// Case for 12 - "The Queen of ..."
case 12:
Console.WriteLine("The Queen of {0}", card.Suit);
break;
// Case for 13 - "The King of ..."
case 13:
Console.WriteLine("The King of {0}", card.Suit);
break;
// Case for everything else
default:
Console.WriteLine("The {0} of {1}", card.Value, card.Suit);
break;
}
}
// Output the details of a card using symbols - eg/ A♠
// Used to output the player's hand on the same line (See outputHand procedure below)
static void outputCardSymbol(PlayingCard card)
{
switch (card.Value) // Case statement based on the value of card
{
// Case for 1 - "The Ace of ..."
case 1:
Console.Write("A{0} ", card.Suit);
break;
// Case for 11 - "The Jack of ..."
case 11:
Console.Write("J{0} ", card.Suit);
break;
// Case for 12 - "The Queen of ..."
case 12:
Console.Write("Q{0} ", card.Suit);
break;
// Case for 13 - "The King of ..."
case 13:
Console.Write("K{0} ", card.Suit);
break;
// Case for everything else
default:
Console.Write("{0}{1} ", card.Value, card.Suit);
break;
}
}
// Outputs all of the cards in a player's hand along with their point total
static void outputHand(Player player)
{
// Print "Current Hand: "
Console.Write("Current Hand: ");
// Loop through all cards in hand
for (int i = 0; i < player.cardsInHand; i++)
{
outputCardSymbol(player.hand[i]);
}
Console.WriteLine("Current points: {0}.", player.points);
}
static void drawCard(PlayingCard[] deck, ref Player player)
{
PlayingCard nextCard = deck[pointer];
// Add the next card in the deck to the player's hand
if (player.cardsInHand < 5)
{
player.hand[player.cardsInHand] = nextCard;
// Increment the number of cards in the player's hand
player.cardsInHand++;
// Add the point value of the new card to the player's total
player.points += nextCard.Points;
// Output the details of the card
//outputCard(nextCard);
// Increment the pointer
pointer++;
}
}
// Check if the player has exceeded 21 points
// Output the player's point total
static bool checkPoints(Player player)
{
// Output the player's point total
//Console.WriteLine("Current Points: {0}", player.points);
// Check if the player is bust
if (player.points > 21)
{
Console.WriteLine("Bust!");
return false;
}
// Return true if the player is still alive
return true;
}
// Compare the player & the dealer
static void calculateWinner(Player player, Player dealer)
{
// Player wins if...
if (dealer.points > 21 || player.cardsInHand == 5 && dealer.cardsInHand != 5)
{
Console.WriteLine("{0} Wins!", player.name);
}
// The game ends in a draw if...
else if (dealer.points == player.points)
{
Console.WriteLine("Draw!");
}
// Otherwise, the dealer has won
else if (dealer.points == 21 && player.points != 21 || player.cardsInHand < 5)
{
Console.WriteLine("{0} wins", dealer.points);
}
else if (player.cardsInHand == 5 && dealer.cardsInHand == 5)
{
if (player.points > dealer.points)
{
Console.WriteLine("{0} wins! 5 card trick: higher than dealers. ", player.name);
}
else if (player.points == dealer.points)
{
Console.WriteLine("It's a draw! 5 card trick: same! ");
}
Console.WriteLine("{0} wins! 5 card trick: less than dealers. ", dealer.name);
}
}
// Checks if the player has any aces with a point value of 11 (high)
// If the player is about to go bust, change the ace to a point value of 1 (low)
// Then update the player's score
static void checkAces(ref Player player)
{
bool changed = false; // Flags up if we've changed an ace already
if (player.points > 21)
{
for (int i = 0; i < player.cardsInHand; i++)
{
if (player.hand[i].Points == 11 && changed == false) // If it's a high ace
{
player.hand[i].Points = 1; // Change it to a low ace
player.points -= 10; // Take 10 away from player's points
changed = true;
}
}
}
}
static void onePlayer()
{
string playAgain = "Undefined";
do
{
// Generate the deck of cards & shuffle it
PlayingCard[] deck = generateDeck();
shuffleDeck(ref deck);
// Create the two player objects
Player player = new Player();
Console.Write("Please enter your name: ");
player.name = Console.ReadLine();
Player dealer = new Player();
Console.Write("Please enter a name for the dealer: ");
dealer.name = Console.ReadLine();
// Draw the first two cards for the Player
drawCard(deck, ref player);
drawCard(deck, ref player);
checkAces(ref player); // Call checkAces to see if we can stop player going bust
outputHand(player);
checkPoints(player); // Output the player's point total
bool alive = true;
string choice = "Undefined";
while (alive == true && choice != "STICK")
{
Console.Write("Hit or Stick? ");
choice = Console.ReadLine().ToUpper();
if (choice == "HIT") // If the user asks to hit then...
{
drawCard(deck, ref player);
// If player still has a valid point total, alive will remain true
// If the player is now bust, alive will become false and the loop will exit
checkAces(ref player); // Call checkAces to see if we can stop player going bust
outputHand(player);
alive = checkPoints(player);
}
}
// If the player isn't bust, it's time for the dealer's turn
if (alive == true)
{
bool dealerAlive = true;
Console.WriteLine();
Console.WriteLine("*** Dealer's Turn ***");
drawCard(deck, ref dealer);
drawCard(deck, ref dealer);
checkAces(ref dealer); // Call checkAces to see if we can stop dealer going bust
outputHand(dealer);
checkPoints(dealer);
while (dealerAlive == true)
{
Console.WriteLine("Press Enter to Continue");
Console.ReadLine();
// Draw the dealer's next card and check if they are still alive
drawCard(deck, ref dealer);
checkAces(ref dealer); // Call checkAces to see if we can stop dealer going bust
outputHand(dealer);
dealerAlive = checkPoints(dealer);
}
}
// Calculate & output the winner
calculateWinner(player, dealer);
Console.Write("Do you want to play again? Y/N ");
playAgain = Console.ReadLine().ToUpper();
} while (playAgain == "Y");
}
}
}
Add each player to a List<Player> as this will keep each Player object to allow more than just two players as you can include the Dealer as a Player.
Also try to seperate your class rather than having multiple internal classes. It makes an easier read and makes navigation easier.
Player.cs
namespace Blackjack
{
public class Player
{
public PlayingCard[] hand;
public int cardsInHand;
public int points;
public string name;
public Player()
{
hand = new PlayingCard[5];
cardsInHand = 0;
points = 0;
}
}
}
Your game also has one slight problem, the dealer sticks from 17

Stack overflow error with recursion

I am currently developing a game in Unity and I decided to use a depth-first search to generate a maze. This involves recursion, the dreaded beast, and I keep getting a stack overflow error even though I seem to have set up the recursion correctly. I've been looking through it for a while, but I can't seem to find the error.
Here is the code:
private void MazeDigger(int[,] maze, int r, int c){
int[] directions = new int[] {1, 2, 3, 4};
Shuffle(directions);
for(int i = 0; i < directions.Length; i++){
switch(directions[i]){
case 1:
if(r-2 <= 0)
{
continue;
}
if(maze[r-2, c] != 0)
{
maze[r-2, c] = 2;
maze[r-1, c] = 2;
MazeDigger(maze, r-2, c);
}
break;
case 2:
if(c+2 >= MazeWidth - 1)
{
continue;
}
if(maze[r, c+2] != 0)
{
maze[r, c+2] = 2;
maze[r, c+1] = 2;
MazeDigger(maze, r, c+1);
}
break;
case 3:
if(r+2 >= MazeHeight - 1)
{
continue;
}
if(maze[r+2, c] != 0)
{
maze[r+2, c] = 2;
maze[r+1, c] = 2;
MazeDigger(maze, r+2, c);
}
break;
case 4:
if(c-2 <= 0)
{
continue;
}
if(maze[r, c-2] != 0)
{
maze[r, c-2] = 2;
maze[r, c-1] = 2;
MazeDigger(maze, r, c-2);
}
break;
}
}
}
It's pretty simple really. I create an array with four directions, I randomly shuffle through them and then use a for loop to run through the array. There is a switch statement inside which will basically mark different points in the maze as being = 2. This is because a different section of the code uses modulus to generate cubes at those locations. Any help would be appreciated and please let me know if I did not provide enough information thank you!
There is no exit condition or you messed up the check.
You mark every visited cell with 2, but you will visit it again if it is unequal to 0. Never ending story :)
The 3x3 maze works, because every cell fails your border check and no recursion happens.
The 4x4 maze should already fail, but it may work for certain starting conditions.

Reversed if check

I have a huge list of checks that checks for example if integer is 4 or 10, if it is 4 it changes this int to 10 and Vice versa so my if check would be something like this:
int i = getval();
if (i == 4)
{
i = 10;
}
else if (i == 10)
{
i = 4;
}
My question is there another way to do this without the need to check for each condition.
If you have a huge list you might consider some list structure.
static Dictionary<int, int> exchange = new Dictionary<int, int>();
static Constructor()
{
AddExchangePair(4, 10);
AddExchangePair(3, 12);
...
}
static void AddExchangePair(int a, int b)
{
exchange.Add(a,b);
exchange.Add(b,a);
}
public staic bool Exchange(ref int value)
{
int newValue = 0;
bool exchanged = exchange.TryGetValue(value, out newValue);
if (exchanged) value = newValue;
return exchanged;
}
This works for huge lists of exchange pairs.
If you call AddExchangePair with a duplicate number e.g. (7,14) and (14, 16) you will get an exception. You might have to consider what to do in that case.
You are looking for the switch statement.
int i = getval();
switch(i)
{
case 4:
i = 10;
break;
case 10:
i = 4;
break;
default:
Console.WriteLine("Invalid selection. Please select 4 or 10.");
break;
}
I disagree with using a switch given that you have a "huge list of checks". I would make the checks its own class backed by a Dictionary. This will help minimize the size of your switch statement, and enforce a separation of the checks and the rest of your code:
class Cases
{
private static readonly Dictionary<int, int>
List = new Dictionary<int, int>
{
{9, 5},
{3, 2},
{7, 12},
{4, 10}
};
public static int GetCaseValue (int v)
{
int result = 0;
return List.TryGetValue(v, out result) ? result : v;
}
}
class Program
{
public static void Main()
{
var test = Cases.GetCaseValue(4);
test = Cases.GetCaseValue(12);
}
}
switch(i)
{
case 4 : i=10; break;
case 10: i=4; break;
}
You won't get around some sort of if / switch statement, since there is no easy way to go from 4 to 10 and back.
If it is 0 and X you swap between, you can go variable = X - variable; which swaps it just fine, but for 4 and 10 the above code is fine.
Try this:
int i = getval() == 4 ? 10 : 4;
That should check if getval() is 4 and then toggle between 4 and 10.
This is what you want.
int i = getval();
switch (i)
{
case 4:
i=10;
break;
case 10:
i=4;
break;
}
Someone beat me to this (and wrote it arguable better) but since I wrote the code I'm posting it anyway.
I'll also throw in that the use of ref here is probably in both our answers only to maintain compliance with your question and in reality something like this would probably use a functional approach so instead of calling Swap(ref i) it would call i = Swap(i) and Swap would return it's input if it found no match. Of course there might be a reason you need to use ref - I just can't think of an obvious one off the top of my head.
void Main()
{
int i;
i = 1;
Swap(ref i); // no swap
Console.WriteLine (i);
i = 10;
Swap(ref i); // swap with 4
Console.WriteLine (i);
i = 4;
Swap(ref i); // swap with 10
Console.WriteLine (i);
}
void Swap(ref int i)
{
if(swaps == null)
{
swaps = new List<Tuple<int, int>>();
swaps.Add(Tuple.Create(4, 10));
}
int compareTo = i;
var swap1 = from c in swaps where c.Item1 == compareTo select c.Item2;
var swap2 = from c in swaps where c.Item2 == compareTo select c.Item1;
if(swap1.Any())
i = swap1.Single();
else if(swap2.Any())
i = swap2.Single();
}
List<Tuple<int, int>> swaps;
Output:
1
4
10

Categories

Resources