I was able to solve the Collatz conjecture algorithm (no, i didn't try to prove it) in about 5 minutes using Java.
Now that I'm learning C# to make web apps, I'm running into trouble doing the same thing.
I simply want the user to enter a number, click a button, and print the output to a text box.
Here is the button Click event handler method I'm using:
protected void Button3_Click(object sender, EventArgs e)
{
string x = TextBox1.Text; //user entered a number
string y =collatz(x); //this function is below and returns a string
chatbox.Text = y; //output
}
And here is the Collatz method:
public static string collatz(string y)
{
if (y == null)
return null;
double x = double.Parse(y); //x is my "n"
y = x.ToString(); //output string
double large = x; //keep track of biggest number
// the algorithm
// the redundancies (like x==1.. x!= 1) are part of troubleshooting :/
while (x > 1)
{
if (x % 2 == 0)
{
x = x / 2;
if (x > large)
large = x;
if (x != 1)
y = y+" "+ x.ToString();
if (x == 1)
{
y = y + " " + x.ToString();
y = y + " largest number was " + large;
}
}
if (x % 2 != 0)
{
if (x == 1)
{
y = y+" "+ x.ToString();
y = y + " largest number was " + large;
}
x = (3 * x) + 1;
if (x > large)
large = x;
y = y+" "+ x.ToString();
}
}
return y;
}
EDIT
when I use the VS.net debugger and enter a number like 2, I get NO output and NO error. I'm just left waiting forever. If it were an infinite loop, I would get an error eventually, right?
and no, this is not a homework problem (it was 2 years ago when I did it in JAVA though :).) I'm learning C# independently.
You had an infinite loop. Try this:
public static string collatz(string y)
{
if (y == null)
{
return null;
}
int x = int.Parse(y); //x is my "n"
var results = new StringBuilder();
results.Append(x.ToString());
int largest = x; //keep track of biggest number
// the algorithm
// the redundancies (like x==1.. x!= 1) are part of troubleshooting :/
while (x > 1)
{
if (x % 2 == 0)
{
x = x / 2;
if (x > largest)
{
largest = x;
}
if (x != 1)
{
results.Append(" " + x.ToString());
}
if (x == 1)
{
results.Append(" " + x.ToString());
results.Append(" largest number was " + largest.ToString());
return results.ToString();
}
}
if (x % 2 != 0)
{
if (x == 1)
{
results.Append(" " + x.ToString());
results.Append(" largest number was " + largest.ToString());
return results.ToString();
}
x = (3 * x) + 1;
if (x > largest)
{
largest = x;
}
results.Append(" " + x.ToString());
}
}
return results.ToString();
}
Two notes:
When you're doing string concatenation in a loop, it's a good habit to use a StringBuilder rather than s = s + t. Lots, lots less memory allocations.
A lot of times you can't rely on == when it comes to double values. It seems to work in this case, but it might not when you get to higher numbers where there's less precision. Since all the numbers are going to be int's anyway, might as well use those.
if (x == 1)
{
y = y+" "+ x.ToString();
y = y + " largest number was " + large;
}
This part here (odd x) is redundant. For if x is 1, it will never enter the while loop. Your code seems logically. Maybe try using integer instead.
x = x / 2;
if (x > large)
large = x;
Redundant code again for even x part. How do you expect x to be bigger than large after division by 2? Just check it in the 3n+1 part will do.
if (x == 1)
{
y = y + " " + x.ToString();
y = y + " largest number was " + large;
}
You can just leave this part out and let the while loop handle this check.
public static string collatz(string y)
{
if (y == null)
return null;
double x = double.Parse(y);
y = x.ToString();
double large = x;
while (x > 1) {
if (x % 2 == 0) {
x = x / 2; // x reassigned
if (x > large)
large = x;
if (x != 1)
y = y + " " + x.ToString();
if (x == 1) {
y = y + " " + x.ToString();
y = y + " largest number was " + large;
}
}
// Infinite loop goes because of that
if (x % 2 != 0) { // double check on reassigned variable, use “else” instead
if (x == 1) {
y = y + " " + x.ToString();
y = y + " largest number was " + large;
}
x = (3 * x) + 1;
if (x > large)
large = x;
y = y + " " + x.ToString();
}
}
return y;
}
I tried it with fixed code (using else) and it works fine.
Also, you don't need double type since Collatz works with natural numbers. The following is a quick refactoring to add more .NET-ty to your code:
public static string collatz(string input)
{
int current = 0;
if (string.IsNullOrEmpty(input) || !int.TryParse(input, out current) || current < 1) {
return "Empty, not a number or less then 1";
}
int max = current;
while (current > 1) {
if (current % 2 == 0) {
current = current / 2; // current reassigned
if (current > max)
max = current;
if (current != 1)
input = input + " " + current.ToString();
if (current == 1) {
input = input + " " + current.ToString();
input = input + " largest number was " + max;
}
} else {
if (current == 1) {
input = input + " " + current.ToString();
input = input + " largest number was " + max;
}
current = (3 * current) + 1;
if (current > max)
max = current;
input = input + " " + current.ToString();
}
}
return input;
}
View Equation:
if the number is even: n/2
if the number is odd: 3n+1
Step One:
Add a method called Collazt which returns a collection of objects of type int of class List<?>
public static List<int> Collazt(int n) {
List<int> data = new List<int>();
data.Add(n);
int resul = 0;
while (true) {
if (n == 1) {
break;
}
if ((n % 2) == 0)
{
resul = n / 2;
n = resul;
}
else {
resul = (n * 3) + 1;
n = resul;
}
data.Add(n);
}
return data;
}
Step Two:
We call the method in our main class.
static void Main(string[] args)
{
Console.Write("N: ");
int r = int.Parse(Console.ReadLine());
List<int> result = Collazt(r);
Console.WriteLine("Lista:");
Console.WriteLine("[");
for (int i= 0; i<result.Count; i++) {
Console.Write(result[i]+"\n");
}
Console.WriteLine("]");
}
string restart;
do
{
Console.WriteLine("Type a Whole Number");
double n = Convert.ToDouble(Console.ReadLine());
do
{double a = n;
if (n % 2 == 0)
{
Console.WriteLine("Even");
n = a / 2;
Console.WriteLine(n);
}
else
{
Console.WriteLine("Odd");
n = (3*a) + 1;
Console.WriteLine(n);
}
}
while (n != 1);
Console.WriteLine("Yo Wanna Restart? Type y and press enter");
restart = Console.ReadLine();
Console.Clear();
}
while (restart == "y");
Console.ReadKey(true);
(not a professional programmer, made it for fun, i know there are better ways)
Related
I'm making an idle/click game in unity, and have a custom format that I'd like all the numbers in the game to display as. K for thousands, M for millions, B for billions, etc. See below example from a game called Tower of Heroes.
example
The displaying of these numbers and units works great. However, where I am running into an issue is with my decision to have arbitrarily large numbers in the game. I did not want to be limited by the constraints of double, and wanted the challenge of coming up with my own solution. I was able to do so, and even get most math operations to work with my solution. Addition, subtraction, multiplication, and exponents all work well enough. But I cannot figure out the logic/math for division...
So, I am using a list of doubles for each of my game variables.
Example: List<double> money = new List<double>(); would be a list containing the money the player currently has. Every position is limited to 0-999. Position 0 represents the "1's", position 1 the thousands, position 2 the millions, etc, with the list growing as large as it needs to. So if we had:
List<double> money = new List<double>()
{
10, //1's
50, //thousands (K)
200 //millions (M)
//etc.
};
that would be $200,050,010, or in my game's notation: 200M050K. (I only display the largest unit, or sometimes the largest two units)
For example, here is the addition method I have working:
//SuperAdd
public List<double> SuperAdd(List<double> baseValue, List<double> valueBeingAdded)
{
//declairing a new list to house the result
List<double> resultValue = new List<double>();
//making copies to not affect originals
List<double> baseValueCopy = baseValue;
List<double> valueBeingAddedCopy = valueBeingAdded;
//increase the # of tiers in our result list until it matches the largest of the two being added
while (resultValue.Count < Mathf.Max(valueBeingAddedCopy.Count, baseValueCopy.Count))
{
resultValue.Add(0);
//if needed adjust the size of the two lists being added together so they match
if (valueBeingAddedCopy.Count < baseValueCopy.Count) valueBeingAddedCopy.Add(0);
if (valueBeingAddedCopy.Count > baseValueCopy.Count) baseValueCopy.Add(0);
}
//add all the respective tiers together
for (int i = 0; i < resultValue.Count; i++)
{
//add all the tiers together
resultValue[i] = baseValueCopy[i] + valueBeingAddedCopy[i];
}
//check for any carry overs needed (>=1000)
for (int i = 0; i < resultValue.Count; i++)
{
//where this is true we need to carry over to next tier
if(resultValue[i] >= 1000)
{
//check if we are on the last existing tier
if(i + 1 == resultValue.Count)
{
//add an empty tier
resultValue.Add(0);
}
//calculate how many thousands need to be carried over, and what the remainder is
double nextTierAdder = Math.Floor(resultValue[i] / 1000);
double currentTierRemainder = resultValue[i] % 1000;
//apply both
resultValue[i] = currentTierRemainder;
resultValue[i + 1] += nextTierAdder;
}
}
//remove any empty blanks from the ends of the resultValue list
for (int i = resultValue.Count - 1; i > 0; i--)
{
if (resultValue[i] == 0) resultValue.RemoveAt(i);
else break;
}
//return resultValue
return resultValue;
}
So, what I'm looking to achieve is a similar method for division, pseudo code:
public List<double> SuperDivide(List<double> baseValue1, List<double> baseValue2)
{
//code goes here
return result;
}
What I have so far is some junk code as a placeholder until I figure out a correct solution that will return a List.
//SuperDivide result = bv1 / bv2
//this is currently only useful when the values are near one another in size
public double SuperDivide(List<double> baseValue1, List<double> baseValue2)
{
double result;
//check if one input list is way bigger than the other, and return a simplified result
//the 100 is because double has a max of 1.7x10^308, each position in our lists holds 1x10^3
if(baseValue1.Count - 100 > baseValue2.Count)
{
result = Math.Pow(10, 300);
return result;
}
if(baseValue2.Count - 10 > baseValue1.Count)
{
result = 0.00000000001; //arbitrary small # that isn't quite 0
return result;
}
//get the stopping position for the for loops (clamped at 5 due to double having a precision of 15 digits)
int stopPos1 = baseValue1.Count - Mathf.Clamp(baseValue1.Count, 1, 5);
int stopPos2 = baseValue2.Count - Mathf.Clamp(baseValue2.Count, 1, 5);
//empty strings to hold the #'s
string bv1String = "";
string bv2String = "";
//create a string of the largest digits in bv1
if (stopPos1 > 1)
{
//create a string of the largest digits in bv1
for (int i = baseValue1.Count - 1; i >= stopPos1; i--)
{
if (i == baseValue1.Count - 1)
{
bv1String = baseValue1[i].ToString();
}
else
{
if (baseValue1[i] < 10) bv1String = bv1String + "00" + baseValue1[i].ToString();
else if (baseValue1[i] < 100) bv1String = bv1String + "0" + baseValue1[i].ToString();
else bv1String = bv1String + baseValue1[i].ToString();
}
}
}
else
{
//create a string of the largest digits in bv1
for (int i = baseValue1.Count - 1; i >= 0; i--)
{
if (i == baseValue1.Count - 1)
{
bv1String = baseValue1[i].ToString();
}
else
{
if (baseValue1[i] < 10) bv1String = bv1String + "00" + baseValue1[i].ToString();
else if (baseValue1[i] < 100) bv1String = bv1String + "0" + baseValue1[i].ToString();
else bv1String = bv1String + baseValue1[i].ToString();
}
}
}
//create a string of the largest digits in bv1
if (stopPos2 > 1)
{
//create a string of the largest digits in bv2
for (int i = baseValue2.Count - 1; i >= stopPos2; i--)
{
if (i == baseValue2.Count - 1)
{
bv2String = baseValue2[i].ToString();
}
else
{
if (baseValue2[i] < 10) bv2String = bv2String + "00" + baseValue2[i].ToString();
else if (baseValue2[i] < 100) bv2String = bv2String + "0" + baseValue2[i].ToString();
else bv2String = bv2String + baseValue2[i].ToString();
}
}
}
else
{
//create a string of the largest digits in bv2
for (int i = baseValue2.Count - 1; i >= 0; i--)
{
if (i == baseValue2.Count - 1)
{
bv2String = baseValue2[i].ToString();
}
else
{
if (baseValue2[i] < 10) bv2String = bv2String + "00" + baseValue2[i].ToString();
else if (baseValue2[i] < 100) bv2String = bv2String + "0" + baseValue2[i].ToString();
else bv2String = bv2String + baseValue2[i].ToString();
}
}
}
//create numbers for the input lists
double bv1Double = double.Parse(bv1String);
double bv2Double = double.Parse(bv2String);
//adjust for one being bigger than the other, only by relative amount though
//only needed when one of them has 6+ tiers
if (baseValue1.Count > 5 && baseValue2.Count > 5)
{
if (baseValue1.Count > baseValue2.Count)
{
bv1Double *= Math.Pow(1000, baseValue1.Count - baseValue2.Count);
}
else if (baseValue1.Count < baseValue2.Count)
{
bv1Double *= Math.Pow(1000, baseValue2.Count - baseValue1.Count);
}
}
//calculate result
result = bv1Double / bv2Double;
return result;
}
Questions:
(1) If anyone can point me in the right direction for the math/logic of the special division, I can probably handle the coding.
(2) Would it be appropriate to make another post / add to this one my other math methods, looking for code suggestions? (I'm a self-taught novice and know there are a lot of improvements I could make to these methods)
If you want to keep your custom formatting and not switch to BigInteger, there might be a viable way to divide by using your existing addition and subtraction operators.
Since your values are stored in a list of integers, you should run through that list for each number and perform long divison.
I'm on my phone so I can't provide a code example, but the logic is somewhat straightforward.
https://en.wikipedia.org/wiki/Long_division
Let's say the calculation is 300/20
First step is to find the first subset of 300 that is equal to or larger than the 20.
That will be 30.
Then you find the qoutient and calculate the remainder, which is 1 and 10 respectively.
You then append the next number from the 300 (which is a 0) to the remainder (10). This will give you 100.
Then you do the same thing resulting in a qoutient of 5 and remainder of 0.
The remainder being zero means that the calculation is complete.
Then you append all the qoutients you've calculated and you have the result ("1" + "5" = "15")
For finding the qoutient and remainder you can use Euclidean Division that also only uses your existing addition and subtraction operators.
https://en.wikipedia.org/wiki/Division_algorithm
N / D = (Quotient, Remainder)
Algorithm:
R = N, Q = 0
while(N > D)
{
R= R - D
Q ++
}
Wikipedia has some nice visualisations and probably explains it clearer.
The main takeaway is that you should be able to implement this algorithm using your existing operators while only using addition and subtraction.
With the suggestion from Nicklas, I was able to put together the following chunk of code. I did a fair bit of testing and am fairly confident it is mostly / all correct. The follow-up question was going to be that during testing I found that operations resulting in a very large answer (ex: 10 trillion / 5) would take a long time. After thinking for a few minutes I came up with a decent solution for massive time savings. Now it will spit out stupidly big results instantly.
//assumes both inputs are positive and > 0
public List<double> SuperDivide(List<double> numerator, List<double> denominator)
{
//here we are going to adopt the notation used on the wiki page for long division
//inputs are numerator/denominator
//outputs are (Q,R) quotient and remainder
//create and set the Q to 0
List<double> quotient = new List<double>
{
0
};
//create a list of value 1
List<double> one = new List<double>
{
1
};
//declairing a new list to house the result
List<double> resultValue = new List<double>();
//empty strings to hold the #'s
string denomString = "";
string remainderString = "";
//create and set the R = N
List<double> remainder = new List<double>();
for (int i = 0; i < numerator.Count; i++)
{
remainder.Add(numerator[i]);
}
//getting a starting value
string compareResult = WhichIsBigger(remainder, denominator);
//calculate Q and R: while R >= D
while(compareResult =="A" || compareResult == "Equal")
{
//get the multiplier we can use to save calcs on big # results (xxxxxxxxxxxxxxxxxxx / yyyy)
List<double> testResult = DivTester(remainder, denominator);
//create a var for D * X, where X is the testResult
List<double> denomMult = SuperMultiply(denominator, testResult);
//Q = Q + X
quotient = SuperAdd(quotient, testResult);
//R = R - DX
remainder = SuperSubtract(remainder, denomMult);
compareResult = WhichIsBigger(remainder, denominator);
}
//if R = 0, return Q
if(remainder.Count == 1 && remainder[0] == 0)
{
return quotient;
}
//else return Q + (R/D)
else
{
//get the stopping position for the for loops (clamped at 5 due to double having a precision of 15 digits)
int stopPosR = remainder.Count - Mathf.Clamp(remainder.Count, 1, 5);
int stopPosD = denominator.Count - Mathf.Clamp(denominator.Count, 1, 5);
//create a string of the largest digits in R
if (stopPosR > 1)
{
for (int i = remainder.Count - 1; i >= stopPosR; i--)
{
//starting tier (largest #)
if (i == remainder.Count - 1)
{
remainderString = remainder[i].ToString();
}
else
{
if (remainder[i] < 10) remainderString = remainderString + "00" + remainder[i].ToString();
else if (remainder[i] < 100) remainderString = remainderString + "0" + remainder[i].ToString();
else remainderString = remainderString + remainder[i].ToString();
}
}
}
else
{
for (int i = remainder.Count - 1; i >= 0; i--)
{
//starting tier (largest #)
if (i == remainder.Count - 1)
{
remainderString = remainder[i].ToString();
}
else
{
if (remainder[i] < 10) remainderString = remainderString + "00" + remainder[i].ToString();
else if (remainder[i] < 100) remainderString = remainderString + "0" + remainder[i].ToString();
else remainderString = remainderString + remainder[i].ToString();
}
}
}
//create a string of the largest digits in D
if (stopPosD > 1)
{
for (int i = denominator.Count - 1; i >= stopPosD; i--)
{
if (i == denominator.Count - 1)
{
denomString = denominator[i].ToString();
}
else
{
if (denominator[i] < 10) denomString = denomString + "00" + denominator[i].ToString();
else if (denominator[i] < 100) denomString = denomString + "0" + denominator[i].ToString();
else denomString = denomString + denominator[i].ToString();
}
}
}
else
{
for (int i = denominator.Count - 1; i >= 0; i--)
{
if (i == denominator.Count - 1)
{
denomString = denominator[i].ToString();
}
else
{
if (denominator[i] < 10) denomString = denomString + "00" + denominator[i].ToString();
else if (denominator[i] < 100) denomString = denomString + "0" + denominator[i].ToString();
else denomString = denomString + denominator[i].ToString();
}
}
}
//create numbers for divsion of R/D
double remainderDoub = double.Parse(remainderString);
double denomDoub = double.Parse(denomString);
//adjust for one being bigger than the other, only by relative amount though
//only needed when one of them has 6+ tiers
if (remainder.Count > 5 && denominator.Count > 5)
{
if (remainder.Count > denominator.Count)
{
remainderDoub *= Math.Pow(1000, remainder.Count - denominator.Count);
}
else if (remainder.Count < denominator.Count)
{
denomDoub *= Math.Pow(1000, denominator.Count - remainder.Count);
}
}
resultValue.Add(remainderDoub / denomDoub);
resultValue = SuperAdd(resultValue, quotient);
return resultValue;
}
}
And the DivTester method:
//I'm sure there are much more effecient ways to determine this multiplier...
private List<double> DivTester(List<double> rem, List<double> denom)
{
//declairing a new list for testing, starting value of 1
List<double> ten = new List<double>()
{
10
};
//create and set the dCopy = denom
List<double> dCopy = new List<double>();
for (int i = 0; i < denom.Count; i++)
{
dCopy.Add(denom[i]);
}
//create and set the testerPass = 1
List<double> testerPass = new List<double>()
{
1
};
//getting a starting value
string compareResult = WhichIsBigger(rem, dCopy);
while(compareResult == "A")
{
dCopy = SuperMultiply(dCopy, ten);
//check and see if it is still successfull
compareResult = WhichIsBigger(rem, dCopy);
//if it passes, multiple testerPass by ten
if (compareResult == "A")
{
testerPass = SuperMultiply(testerPass, ten);
}
}
//return the largest multipler (10^X) that can be safely used
return testerPass;
}
IN C# i am trying to solve a problem :
Write a program that checks whether the product of the odd elements is equal to the product of the even elements.
The only thing left is:
On the second line you will receive N numbers separated by a whitespace.
I am unable to get this working. I have tried with Split but it keeps breaking. Can someone help?
Example:
Input
5
2 1 1 6 3
Output
yes 6
static void Main(string[] args)
{
long N = long.Parse(Console.ReadLine());
long[] array = new long[N];
long ODD = 1;
long EVEN = 1;
for (int i = 0; i < N; i++)
{
array[i] = int.Parse(Console.ReadLine());
if ((i + 1) % 2 == 0)
{
EVEN *= array[i];
}
else
{
ODD *= array[i];
}
}
if (EVEN == ODD)
{
Console.WriteLine("yes" + " " +
ODD);
}
else
{
Console.WriteLine("no" + " " + ODD + " " + EVEN);
}
}
Read from console input and keep it to an string array, Then convert each array element to long and apply the Odd Even logic like below:
static void Main(string[] args)
{
string input = Console.ReadLine();
string[] inputArray = input.Split(' ');
long element;
long odd = 1;
long even = 1;
foreach (var i in inputArray)
{
element = long.Parse(i);
if (element % 2 == 0)
{
even *= element;
}
else
{
odd *= element;
}
}
Console.WriteLine("\nOdd product = " + odd + ", Even product = " + even);
if (odd == even)
{
Console.WriteLine("ODD == EVEN \n");
Console.WriteLine("Yes" + " " + odd);
}
else
{
Console.WriteLine("ODD != EVEN \n");
Console.WriteLine("No" + " " + odd + " " + even);
}
Console.ReadKey();
}
long[] nums = input.Split(' ').Select(x => long.Parse(x))..ToArray(); //split numbers by space and cast them as int
int oddProduct = 1, evenProduct = 1; // initial values
foreach(long x in nums.Where(a => a%2 == 1))
oddProduct *= x; // multiply odd ones
foreach(long x in nums.Where(a => a%2 == 0))
evenProduct *= x; // multiply even ones
So I'm at the final stage of my Noughts and Crosses project and I'm quite dearly stuck, I have done move validation subroutine as well as a subroutine that is solely based on changing the blank space in the box into an " X " or an " O ",
yet my code seems to tell me that some part of my code does not exist in the current context and I am completely baffled
The code is:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[,] grid = new string[3, 3] {{" "," "," "},
{" "," "," "},
{" "," "," "}};
string board = System.IO.File.ReadAllText("E:\\BoardGame.txt");
Console.WriteLine(board);
int player = 0;
var XCoordinate = 0;
var YCoordinate = 0;
int x, y;
GetMoveCoordinates(ref XCoordinate, ref YCoordinate);
if (player == 0)
{
grid[XCoordinate, YCoordinate] = " X ";
player++;
}
else
{
grid[XCoordinate, YCoordinate] = " O ";
player--;
}
UpdateGrid(grid, box);
if (player == 1)
{
}
}
public static void GetMoveCoordinates(ref int XCoordinate, ref int YCoordinate)
{
int CommaLocation;
bool GameHasBeenWon = false;
string CoordinatesInput;
string XChar, YChar;
while (GameHasBeenWon == false)
{
try
{
Console.Write("Enter your coordinates: (x,y) ");
CoordinatesInput = Console.ReadLine();
CommaLocation = CoordinatesInput.IndexOf(",".ToString());
XChar = CoordinatesInput.Substring(CommaLocation - 1, CommaLocation);
YChar = CoordinatesInput.Substring(CommaLocation + 1);
XCoordinate = int.Parse(XChar);
YCoordinate = int.Parse(YChar);
}
catch
{
Console.WriteLine("Invalid Input- Please Try Again");
}
}
}
public static bool CheckValidMove(int XCoordinate, int YCoordinate, string[,] Board)
{
if ((XCoordinate >= 1) || (XCoordinate <= 3))
{
if ((YCoordinate >= 1) || (YCoordinate <= 3))
{
if ((Board[XCoordinate, YCoordinate]) == " ")
{
return true;
}
else return false;
}
else return false;
}
else return false;
}
public static void UpdateGrid(string[,] grid, string box)
{
Console.Clear();
for (int x = 0; x < grid.GetLength(0); x++)
{
for (int y = 0; y < grid.GetLength(1); y++)
{
box = box.Replace((x + 1) + "," + (y + 1), grid[y, x]);
}
}
// In the case not required as clearning the console default the cursor back to 0,0, but left in
// as an example
Console.SetCursorPosition(0, 0);
Console.WriteLine(box);
}
}
}
Yet the problem I seem to have is under Main, under the if statement where the code seems to tell me that box in the Update(grid,box), does not exist in the current context, yet it should do in the last subroutine? Am I supposed to do it as a ref statement or am I missing something? Also if you have any tips on how to tidy up the code I'd gladly appreciate it (yes I will add win parameters but I'd like to draw my symbols first).
This is what the grid looks like this:
+---+---+---+
| | | |
+---+---+---+
| | | |
+---+---+---+
| | | |
+---+---+---+
There are several bugs here. First, the following won't compile:
UpdateGrid(grid, box);
As Andrew Whitaker indicated in the comments, there is no "box" variable in your main method (you never declared or initialized it). Define what that variable is and initialize it properly and that'll compile again.
Next, a quick stylistic note on the following:
while (GameHasBeenWon == false)
Don't explicitly compare to true and false - the correct way to do this is
while (!GameHasBeenWon)
The next line to comment on has several bugs:
(XCoordinate >= 1) || (XCoordinate <= 3)
This means that XCoordinate >= 1 OR it's less than or equal to 3, which isn't at all what you meant. Actually, by this logic, any integer is valid because it's either greater than 1, equal to 1, less than 3, or equal to 3. (Think about it - for what integers could a statement like this possibly be false?) Also, 3 is specifically not a valid index, but 0 is. Keep in mind that arrays are zero-indexed. Thus, this should actually be
(XCoordinate >= 0) && (XCoordinate < 3)
In terms of your if statements:
if ((Board[XCoordinate, YCoordinate]) == " ")
{
return true;
}
else return false;
returns true exactly when (Board[XCoordinate, YCoordinate]) == " " is true and false exactly when that statement is false. You could just do
return (Board[XCoordinate, YCoordinate]) == " ";
In fact, you could do that for the whole "if" statement. (I'm not sitting in front of an IDE right now so I apologize if my syntax isn't perfect here).
return ((XCoordinate >= 0) && (XCoordinate < 3) &&
((YCoordinate >= 0) && (YCoordinate < 3)) &&
((Board[XCoordinate, YCoordinate]) == " "));
im working on minimax algoritm now, i have a problem to compare each node and cant return the best node. once i can compare it, it still choose the bottom of the node, can someone help me to fix my codes ?
here is my codes:
public Node minimax(ArrayList newBoard, int depth, Player p, Node n)
{
int value = 0;
if (depth == 0 || StatePosition.PlayerWins(p, newBoard))
{
n.Score = StatePosition.getScore(newBoard); //the heuristic value of node
Debug.Log(n.Pos + " - " + n.Des + " " + n.MinMax + " " + n.Score);
return n; //out n
}
else
{
Children(p, newBoard, n); //generate possible moves
foreach (Node anak in n.Child)
{ //foreach moves
ArrayList Board = (ArrayList)newBoard.Clone(); //make a clone of board
Debug.Log(anak.Pos + " " + anak.Des + " move applied");
applyMove(Board, anak.Pos, anak.Des, p); //try current move
Node b = minimax((ArrayList)Board.Clone(), depth - 1, p == Player.H ? Player.C : Player.H, anak);
if (anak.MinMax == MiniMaxValue.MAX)
{
value = -1000;
if (value < anak.Score)
{
n = anak;
}
}
else
{
value = 1000;
if (value > anak.Score)
{
n = anak;
}
}
}
}
return n;
}
Trying to determine if my list of integer is made of odd or even numbers, my desired output is a list of true an/or false. Can I perform the following operation on the list lst or do I need to create a loop? A is the output.
List <int> lst = new List <int>();
A = IsOdd(lst);
You could try using Linq to project the list:
var output = lst.Select(x => x % 2 == 0).ToList();
This will return a new list of bools such that {1, 2, 3, 4, 5} will map to {false, true, false, true, false}.
Just use the modulus
loop through the list and run the following on each item
if(num % 2 == 0)
{
//is even
}
else
{
//is odd
}
Alternatively if you want to know if all are even you can do something like this:
bool allAreEven = lst.All(x => x % 2 == 0);
There's at least 7 different ways to test if a number is odd or even. But, if you read through these benchmarks, you'll find that as TGH mentioned above, the modulus operation is the fastest:
if (x % 2 == 0)
//even number
else
//odd number
Here are a few other methods (from the website) :
//bitwise operation
if ((x & 1) == 0)
//even number
else
//odd number
//bit shifting
if (((x >> 1) << 1) == x)
//even number
else
//odd number
//using native library
System.Math.DivRem((long)x, (long)2, out outvalue);
if ( outvalue == 0)
//even number
else
//odd number
#region even and odd numbers
for (int x = 0; x <= 50; x = x + 2)
{
int y = 1;
y = y + x;
if (y < 50)
{
Console.WriteLine("Odd number is #{" + x + "} : even number is #{" + y + "} order by Asc");
Console.ReadKey();
}
else
{
Console.WriteLine("Odd number is #{" + x + "} : even number is #{0} order by Asc");
Console.ReadKey();
}
}
//order by desc
for (int z = 50; z >= 0; z = z - 2)
{
int w = z;
w = w - 1;
if (w > 0)
{
Console.WriteLine("odd number is {" + z + "} : even number is {" + w + "} order by desc");
Console.ReadKey();
}
else
{
Console.WriteLine("odd number is {" + z + "} : even number is {0} order by desc");
Console.ReadKey();
}
}
--simple codes--
#region odd / even numbers order by desc
//declaration of integer
int TotalCount = 50;
int loop;
Console.WriteLine("\n---------Odd Numbers -------\n");
for (loop = TotalCount; loop >= 0; loop--)
{
if (loop % 2 == 0)
{
Console.WriteLine("Even numbers : #{0}", loop);
}
}
Console.WriteLine("\n---------Even Numbers -------\n");
for (loop = TotalCount; loop >= 0; loop--)
{
if (loop % 2 != 0)
{
Console.WriteLine("odd numbers : #{0}", loop);
}
}
Console.ReadLine();
#endregion