I was trying to brute force my way through the Grid Game problem on LeetCode without knowing what prefix sum was. And I thought my solution was good, not optimal but should get the job done. However, it failed on the 9th test case in a way that I don't understand.
Testcase
using solutions;
int[][] testCase = new int [2][];
testCase[0] = new int[] {20,3,20,17,2,12,15,17,4,15};
testCase[1] = new int[] {20,10,13,14,15,5,2,3,14,3};
SolutionV2 SLN = new SolutionV2();
Console.WriteLine(SLN.GridGame(testCase));
My Solution
namespace solutions;
public class SolutionV2 {
public long GridGame(int[][] grid)
{
long returnValue = 0;
long maxValue = 0;
int[] currentPosition = new int[] {0,0};
int maxCol = grid[0].GetLength(0);
Console.WriteLine("[{0}]", string.Join(", ", grid[0]));
Console.WriteLine("[{0}]", string.Join(", ", grid[1]));
for(int k=0;k<maxCol;k++) //find the highest path sum for the first robot
{
int sum = 0;
for(int i=0;i<maxCol;i++)
{
if(i<k)
{
sum += grid[0][i]; //sum up the first row until it is time to move down
}
else if(i==k)
{
sum += grid[0][i];
for(int j=i;j<maxCol;j++)
{
sum += grid[1][j];
}
if(sum>maxValue)
{
maxValue = sum;
}
break;
}
}
}
for(int k=0;k<maxCol;k++) //there has to be a better way to set the sum path to zero
{
int sum = 0;
for(int i=0;i<maxCol;i++)
{
if(i<k)
{
sum += grid[0][i]; //sum up the first row until it is time to move down
}
else if(i==k)
{
sum += grid[0][i];
for(int j=i;j<maxCol;j++)
{
sum += grid[1][j];
}
if(sum==maxValue) //found it, now set the path to zero
{
for(int a=0;a<=i;a++)
{
grid[0][a] = 0;
}
for(int a=i;a<maxCol;a++)
{
grid[1][a] = 0;
}
}
break;
}
}
}
Console.WriteLine("[{0}]", string.Join(", ", grid[0]));
Console.WriteLine("[{0}]", string.Join(", ", grid[1]));
for(int k=0;k<maxCol;k++) //find the highest path sum for the second robot
{
int sum = 0;
for(int i=0;i<maxCol;i++)
{
if(i<k)
{
sum += grid[0][i]; //sum up the first row until it is time to move down
}
else if(i==k)
{
sum += grid[0][i];
for(int j=i;j<maxCol;j++)
{
sum += grid[1][j];
}
if(sum>returnValue)
{
returnValue = sum;
}
break;
}
}
}
return returnValue;
}
}
The expected value for this particular test case was 63, which I don't understand where they got it from.
i have got questions.
my problem is The user is asked to enter 20 exam grades. If the grades entered are less than 0 or greater than 100, you should be asked to enter again. How can I do that?
int not;
bool test = true;
for (int i = 0; i < 20; i++)
{
Console.Write((i + 1) + (".Not:"));
not = Convert.ToInt32(Console.ReadLine());
if (not < 0 || not > 100)
{
test = false;
Console.Write("Try again!");
}
else
{
test = true;
}
}
I want to use bool while doing this. would be glad if you help. thank you in advance
i changed code but i used goto. I dont want use to goto. How can i use bool doing this ?
int not;
int temp = 0;
for (int i = 0; i < 20; i++)
{
Console.Write("Add Not : ");
backtoAdd:
not = Convert.ToInt32(Console.ReadLine());
if (not < 0 || not > 100)
{
Console.WriteLine("Try Again!");
goto backtoAdd;
}
Console.WriteLine((i+1)+". Not : "+not);
temp = temp + not;
}
Console.Write("sum of not : "+temp);
Console.ReadKey();
As you mentioned it can be done with a while loop and condition to stop the loop. You can simplify it, I have added comments in the code example:
// declarations
int counter = 0;
int maxExamGradesInputCount = 20;
int highestGrade = 100;
int lowestGrade = 0;
// as long as counter is not equal to maxExamGradesInputCount continue
while (counter != maxExamGradesInputCount)
{
// we give input
string? input = Console.ReadLine();
// we try to parse our input
var parsed = int.TryParse(input, out var grade);
// if our input is parsed correctly
if (parsed)
{
// we check if the input value between the given range
if (grade < lowestGrade || grade > highestGrade)
{
Console.WriteLine("Try Again!");
}
else
{
// if with in range count
counter++;
}
}
}
I tried to solve projecteuler 4th project with C# but I don't receive the correct answer, I get 90909. Can someone spot my mistake?
The problem goes like this:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
namespace Largest_palindrome_product{
class Program
{
static void Main(string[] args)
{
string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
int result = 0;
string rev= "hello";
string palindrome = "hello";
string bingo = "hello";
int j = 1;
for (int i = 1; i< 1000; i++)
{
for (int y = 1; y< 1000; y++)
{
result = i * y;
bingo = result.ToString();
rev = Reverse(bingo);
j = int.Parse(bingo);
}
if (rev == bingo)
{
palindrome = bingo;
}
}
Console.Write(palindrome);
Console.Read();
}
}
}
I think what has caused so much confusion is the use of String this just complicates thing having to convert them back and forth.
Your program works fine (if the if is moved as per John's comment) if only you'd checked the new number was larger!
here is my take on it:
// stolen from https://www.geeksforgeeks.org/reverse-digits-integer-overflow-handled/
int Reverse(int num)
{
int rev_num = 0;
while (num > 0)
{
rev_num = rev_num * 10 + num % 10;
num = num / 10;
}
return rev_num;
}
int result = 0;
int palindrome = 0;
int j = 1;
for (int i = 999; i > 0; i--)
{
for (int y = 999; y > 0; y--)
{
result = i * y;
if (result == Reverse(result))
{
if (result > palindrome)
{
palindrome = result;
}
}
}
}
Console.Write(palindrome);
Console.Read();
I have temperature data stored in an array, but need to use that data for a while loop. What I have so far is:
public int BelowValueCounter(string tempValueIn)
{
int.TryParse(tempValueIn, out tempValueOut);
int checkValue = tempData[0];
while (tempValueOut > checkValue)
{
belowCounter++;
}
return belowCounter;
}
I just don't know how to increment tempData[0] so that it moves on to tempData[1] to repeat until the while loop condition is satisfied. Thanks!
If you want to keep the while loop, you need a variable for counting - here i - to get access to the desired array entry:
public int BelowValueCounter(string tempValueIn)
{
int.TryParse(tempValueIn, out tempValueOut);
int i = 0;
int checkValue = tempData[i];
while (tempValueOut > checkValue)
{
belowCounter++;
i++;
checkValue = tempData[i];
}
return belowCounter;
}
Or consider using a for loop:
public int BelowValueCounter(string tempValueIn)
{
int.TryParse(tempValueIn, out tempValueOut);
for (int i = 0; i < tempData.Length; i++)
{
if (tempValueOut > tempData[i])
{
belowCounter++;
continue;
}
break;
}
return belowCounter;
}
You can use a for loop, foreach loop, or a linq query.
void Main()
{
var counter = BelowValueCounter_UsingFor(46);
//var counter = BelowValueCounter_UsingLinq(46);
Console.WriteLine(counter);
}
decimal[] temperatures = new decimal[] { 40, 40, 45, 60, 70 };
public int BelowValueCounter_UsingLinq(decimal tempValueIn)
{
return temperatures.Count(a => a < tempValueIn);
}
public int BelowValueCounter_UsingFor(decimal tempValueIn)
{
int counter = 0;
for (int i = 0; i < temperatures.Length; i++)
{
if (temperatures[i] < tempValueIn)
counter++;
}
return counter;
}
I need to calculate the factorial of numbers up to around 100! in order to determine if a series of coin flip-style data is random, as per this Wikipedia entry on Bayesian probability. As you can see there, the necessary formula involves 3 factorial calculations (but, interestingly, two of those factorial calculations are calculated along the way to the third).
I saw this question here, but I'd think that integer is going to get blown out pretty quickly. I could also make a function that is more intelligent about the factorial calculation (ie, if I have 11!/(7!3!), as per the wiki example, I could go to (11*10*9*8)/3!), but that smacks of premature optimization to me, in the sense that I want it to work, but I don't care about speed (yet).
So what's a good C# library I can call to calculate the factorial in order to get that probability? I'm not interested in all the awesomeness that can go into factorial calculation, I just want the result in a way that I can manipulate it. There does not appear to be a factorial function in the Math namespace, hence the question.
You could try Math.NET - I haven't used that library, but they do list Factorial and Logarithmic Factorial.
There has been a previous question on a similar topic. Someone there linked the Fast Factorial Functions web site, which includes some explanations of efficient algorithms and even C# source code.
Do you want to calculate factorials, or binomial coefficients?
It sounds like you want to calculate binomial coefficients - especially as you mention 11!/(7!3!).
There may be a library that can do this for you, but as a (presumably) programmer visiting stack overflow there's no reason not to write one yourself. It's not too complicated.
To avoid memory overflow, don't evaluate the result until all common factors are removed.
This algorithm still needs to be improved, but you have the basis for a good algorithm here. The denominator values need to be split into their prime factors for the best result. As it stands, this will run for n = 50 quite quickly.
float CalculateBinomial(int n, int k)
{
var numerator = new List<int>();
var denominator = new List<int>();
var denominatorOld = new List<int>();
// again ignore the k! common terms
for (int i = k + 1; i <= n; i++)
numerator.Add(i);
for (int i = 1; i <= (n - k); i++)
{
denominator.AddRange(SplitIntoPrimeFactors(i));
}
// remove all common factors
int remainder;
for (int i = 0; i < numerator.Count(); i++)
{
for (int j = 0; j < denominator.Count()
&& numerator[i] >= denominator[j]; j++)
{
if (denominator[j] > 1)
{
int result = Math.DivRem(numerator[i], denominator[j], out remainder);
if (remainder == 0)
{
numerator[i] = result;
denominator[j] = 1;
}
}
}
}
float denominatorResult = 1;
float numeratorResult = 1;
denominator.RemoveAll(x => x == 1);
numerator.RemoveAll(x => x == 1);
denominator.ForEach(d => denominatorResult = denominatorResult * d);
numerator.ForEach(num => numeratorResult = numeratorResult * num);
return numeratorResult / denominatorResult;
}
static List<int> Primes = new List<int>() { 2, 3, 5, 7, 11, 13, 17, 19,
23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 };
List<int> SplitIntoPrimeFactors(int x)
{
var results = new List<int>();
int remainder = 0;
int i = 0;
while (!Primes.Contains(x) && x != 1)
{
int result = Math.DivRem(x, Primes[i], out remainder);
if (remainder == 0)
{
results.Add(Primes[i]);
x = result;
i = 0;
}
else
{
i++;
}
}
results.Add(x);
return results;
}
I can estimate n = 110, k = 50 (returns 6x10^31) but cannot run n = 120, k = 50.
The following can calculate the factorial of 5000 in 1 second.
public class Number
{
#region Fields
private static long _valueDivision = 1000000000;
private static int _valueDivisionDigitCount = 9;
private static string _formatZeros = "000000000";
List<long> _value;
#endregion
#region Properties
public int ValueCount { get { return _value.Count; } }
public long ValueAsLong
{
get
{
return long.Parse(ToString());
}
set { SetValue(value.ToString()); }
}
#endregion
#region Constructors
public Number()
{
_value = new List<long>();
}
public Number(long value)
: this()
{
SetValue(value.ToString());
}
public Number(string value)
: this()
{
SetValue(value);
}
private Number(List<long> list)
{
_value = list;
}
#endregion
#region Public Methods
public void SetValue(string value)
{
_value.Clear();
bool finished = false;
while (!finished)
{
if (value.Length > _valueDivisionDigitCount)
{
_value.Add(long.Parse(value.Substring(value.Length - _valueDivisionDigitCount)));
value = value.Remove(value.Length - _valueDivisionDigitCount, _valueDivisionDigitCount);
}
else
{
_value.Add(long.Parse(value));
finished = true;
}
}
}
#endregion
#region Static Methods
public static Number operator +(Number c1, Number c2)
{
return Add(c1, c2);
}
public static Number operator *(Number c1, Number c2)
{
return Mul(c1, c2);
}
private static Number Add(Number value1, Number value2)
{
Number result = new Number();
int count = Math.Max(value1._value.Count, value2._value.Count);
long reminder = 0;
long firstValue, secondValue;
for (int i = 0; i < count; i++)
{
firstValue = 0;
secondValue = 0;
if (value1._value.Count > i)
{
firstValue = value1._value[i];
}
if (value2._value.Count > i)
{
secondValue = value2._value[i];
}
reminder += firstValue + secondValue;
result._value.Add(reminder % _valueDivision);
reminder /= _valueDivision;
}
while (reminder > 0)
{
result._value.Add(reminder % _valueDivision);
reminder /= _valueDivision;
}
return result;
}
private static Number Mul(Number value1, Number value2)
{
List<List<long>> values = new List<List<long>>();
for (int i = 0; i < value2._value.Count; i++)
{
values.Add(new List<long>());
long lastremain = 0;
for (int j = 0; j < value1._value.Count; j++)
{
values[i].Add(((value1._value[j] * value2._value[i] + lastremain) % _valueDivision));
lastremain = ((value1._value[j] * value2._value[i] + lastremain) / _valueDivision);
//result.Add(();
}
while (lastremain > 0)
{
values[i].Add((lastremain % _valueDivision));
lastremain /= _valueDivision;
}
}
List<long> result = new List<long>();
for (int i = 0; i < values.Count; i++)
{
for (int j = 0; j < i; j++)
{
values[i].Insert(0, 0);
}
}
int count = values.Select(list => list.Count).Max();
int index = 0;
long lastRemain = 0;
while (count > 0)
{
for (int i = 0; i < values.Count; i++)
{
if (values[i].Count > index)
lastRemain += values[i][index];
}
result.Add((lastRemain % _valueDivision));
lastRemain /= _valueDivision;
count -= 1;
index += 1;
}
while (lastRemain > 0)
{
result.Add((lastRemain % _valueDivision));
lastRemain /= _valueDivision;
}
return new Number(result);
}
#endregion
#region Overriden Methods Of Object
public override string ToString()
{
string result = string.Empty;
for (int i = 0; i < _value.Count; i++)
{
result = _value[i].ToString(_formatZeros) + result;
}
return result.TrimStart('0');
}
#endregion
}
class Program
{
static void Main(string[] args)
{
Number number1 = new Number(5000);
DateTime dateTime = DateTime.Now;
string s = Factorial(number1).ToString();
TimeSpan timeSpan = DateTime.Now - dateTime;
long sum = s.Select(c => (long) (c - '0')).Sum();
}
static Number Factorial(Number value)
{
if( value.ValueCount==1 && value.ValueAsLong==2)
{
return value;
}
return Factorial(new Number(value.ValueAsLong - 1)) * value;
}
}
using System;
//calculating factorial with recursion
namespace ConsoleApplication2
{
class Program
{
long fun(long a)
{
if (a <= 1)
{
return 1;}
else
{
long c = a * fun(a - 1);
return c;
}}
static void Main(string[] args)
{
Console.WriteLine("enter the number");
long num = Convert.ToInt64(Console.ReadLine());
Console.WriteLine(new Program().fun(num));
Console.ReadLine();
}
}
}
hello everybody according to this solution i have my own solution where i calculate factorial of array 1D elements. the code is `int[] array = new int[5]
{
4,3,4,3,8
};
int fac = 1;
int[] facs = new int[array.Length+1];
for (int i = 0; i < array.Length; i++)
{
for (int j = array[i]; j > 0; j--)
{
fac *= j;
}
facs[i] = fac;
textBox1.Text += facs[i].ToString() + " ";
fac = 1;
}`
copy and paste the code above ^ in the button , it solves factorial of elements of array 1D. best regards.