Multiple while conditions - c#

I want to output a timer in console which goes from 00h00m00s to 23h59m59s.
My code only outputs until 00h00m59s.
Must be the conditions in after the while, but i think it is correct.
Who knows how to solve this ?
static void Main(string[] args)
{
int uur = 0;
int min = 0;
int sec = 0;
while (uur != 23 && min!=60 && sec!=60)
{
if (sec == 60)
{
min++;
sec = 0;
}
if (min == 60)
{
uur++;
min = 0;
}
string strSec = String.Format("{0:00}", sec);
string strMin = String.Format("{0:00}", min);
string strUur = String.Format("{0:00}", uur);
Console.WriteLine(strUur + "h" + strMin + "m" + strSec + "s");
sec++;
}
Console.ReadLine();
}

Use the following condition:
while (uur != 23 || min != 59 || sec != 60)
You might also want to try this simpler approach:
int total_second_in_day = 24*60*60;
for (int second_in_day = 0; second_in_day < total_second_in_day; second_in_day++)
{
int uur = second_in_day / 3600;
int min = (second_in_day % 3600) / 60;
int sec = (second_in_day % 3600) % 60;
string strSec = String.Format("{0:00}", sec);
string strMin = String.Format("{0:00}", min);
string strUur = String.Format("{0:00}", uur);
Console.WriteLine(strUur + "h" + strMin + "m" + strSec + "s");
}
Console.ReadLine();

Although your question is basically about understanding while conditions this is how you could achieve printing all times:
using System;
public class Program
{
public static void Main()
{
var time = new TimeSpan(0,0,0,0);
var oneSec = new TimeSpan(0,0,0,1);
var wakeywakey = new TimeSpan(0,23,59,59);
while (time <= wakeywakey)
{
Console.WriteLine(time);
time += oneSec;
}
}
}

Related

C# How can I get timer to tick properly?

Making an application that can take Youtube links and add them to a queue and then play them until the queue is empty. Currently my timer1_Tick doesn't seem to be executing and I'm not sure why :(
//timer1_Tick
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
Video.Movie = "";
q.Dequeue();
qq.Dequeue();
}
Here is the meat and potatoes
if (e.ChatMessage.Message.StartsWith("!songrequest"))
{
var myString = e.ChatMessage.Message.ToString();
var newString = myString.Remove(0, myString.IndexOf(' ') + 1);
var getID = newString.Remove(0, newString.IndexOf('=') + 1);
var vUrl = "https://www.youtube.com/v/" + getID + "&autoplay=1";
var vUrlString = vUrl.ToString();
q.Enqueue(vUrlString);
qq.Enqueue(getID.ToString());
string[] array = new string[q.Count];
string[] array2 = new string[qq.Count];
q.CopyTo(array, 0);
qq.CopyTo(array2, 0);
if (timer1.Enabled == false)
{
for (int i = 0; i < array.Length; i++)
{
YouTubeVideo video = new Helix.YouTubeVideo(array2[i]);
var gDur = getDuration(video.duration);
string[] time = gDur.ToString().Split(' ');
int min = int.Parse(time[0]);
int sec = int.Parse(time[1]);
int msm = min * 60000;
int mss = sec * 1000;
int dur = msm + mss;
timer1.Interval = dur;
Video.Movie = array[i];
timer1.Start();
client.SendMessage("Now playing: " + video.title + ".");
client.SendMessage($"Timer set to { dur } ms.");
}
}
else
{
client.SendMessage("It's still running somehow.");
}
here you are checking disabled timer and only if it is not enabled it will go into condition..
if (timer1.Enabled == false)
{
for (int i = 0; i < array.Length; i++)
{
YouTubeVideo video = new Helix.YouTubeVideo(array2[i]);
var gDur = getDuration(video.duration);
string[] time = gDur.ToString().Split(' ');
int min = int.Parse(time[0]);
int sec = int.Parse(time[1]);
int msm = min * 60000;
int mss = sec * 1000;
int dur = msm + mss;
timer1.Interval = dur;
Video.Movie = array[i];
timer1.Start();
client.SendMessage("Now playing: " + video.title + ".");
client.SendMessage($"Timer set to { dur } ms.");
}
}
so if you are starting timer, on timer1.Start(), you need to enable it first.
try
if (timer1.Enabled == false)
{
timer1.Enabled = true;
for (int i = 0; i < array.Length; i++)
{
YouTubeVideo video = new Helix.YouTubeVideo(array2[i]);
var gDur = getDuration(video.duration);
string[] time = gDur.ToString().Split(' ');
int min = int.Parse(time[0]);
int sec = int.Parse(time[1]);
int msm = min * 60000;
int mss = sec * 1000;
int dur = msm + mss;
timer1.Interval = dur;
Video.Movie = array[i];
timer1.Start();
client.SendMessage("Now playing: " + video.title + ".");
client.SendMessage($"Timer set to { dur } ms.");
}
}
You need to enable the timer, its defaulted to false.

Need to convert Amount written in English language into Arabic language. Is there any possible way using C#?

I am trying to convert amount entered in digits into English language and it works fine. Now I want to convert it into Arabic language also. As user will type an amount in the text box it will convert it into English language or Arabic language on the basis of Culture code provided.
Below is my code to which runs on button click.
protected void btnConvert_Click(object sender, EventArgs e)
{
// CreateDatabase();
//txtBoxs.Text = sb.ToString();
string decimalPart = "";
string fractionPart = "";
string value = txtBoxs.Text;
string value1 = txtBoxs.Text;
string currency = "paisas";
string cultureCode = "ar-SA";
int index = 0;
if (value.Contains("."))
{
decimalPart = value.Substring(0, value.IndexOf("."));
fractionPart = value.Substring(value.IndexOf(".") + 1, value.Length - value.IndexOf(".") - 1);
if (cultureCode == "ar-SA")
{
//value = "";
//foreach (char c in decimalPart)
//{
// value += ToIndicDigits(c.ToString());
//}
//if (fractionPart != "")
//{
// value += ".";
// foreach (char c in fractionPart)
// {
// value += ToIndicDigits(c.ToString());
// }
//}
}
else
{
value = words(Convert.ToInt32(decimalPart));
if (fractionPart != "")
{
sb.Clear();
value += " and " + words(Convert.ToInt32(fractionPart)) + " " + currency;
}
}
}
else
{
if (cultureCode == "ar-SA")
{
//foreach (char c in value1)
//{
// value += ToIndicDigits(c.ToString());
//}
}
else
{
value = words(Convert.ToInt32(value));
index = value.ToString().LastIndexOf(" ");
int index2 = index > 0 ? value.LastIndexOf(" ", index - 1) : -1;
value = value.Insert(index2, " and ");
}
}
lblWords.InnerHtml = value;
}
Here is my method which i am using to convert amount into English language.
public string words(int number)
{
//int number = numbers;
if (number == 0)
return "Zero";
if (number == -2147483648) return "Minus Two Hundred and Fourteen Crore Seventy Four Lakh Eighty Three Thousand Six Hundred and Forty Eight";
int[] num = new int[4];
int first = 0;
int u, h, t;
if (number < 0)
{
sb.Append("Minus ");
number = -number;
}
string[] words0 = {"" ,"One ", "Two ", "Three ", "Four ",
"Five " ,"Six ", "Seven ", "Eight ", "Nine "};
string[] words1 = {"Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ",
"Fifteen ","Sixteen ","Seventeen ","Eighteen ", "Nineteen "};
string[] words2 = {"Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ",
"Seventy ","Eighty ", "Ninety "};
string[] words3 = { "Thousand ", "Lakh ", "Crore " };
num[0] = number % 1000; // units
num[1] = number / 1000;
num[2] = number / 100000;
num[1] = num[1] - 100 * num[2]; // thousands
num[3] = number / 10000000; // crores
num[2] = num[2] - 100 * num[3]; // lakhs
for (int i = 3; i > 0; i--)
{
if (num[i] != 0)
{
first = i;
break;
}
}
for (int i = first; i >= 0; i--)
{
if (num[i] == 0)
continue;
u = num[i] % 10; // ones
t = num[i] / 10;
h = num[i] / 100; // hundreds
t = t - 10 * h; // tens
if (h > 0) sb.Append(words0[h] + "Hundred ");
if (u > 0 || t > 0)
{
//if (h > 0 || i == 0)
// sb.Append("and ");
if (t == 0)
sb.Append(words0[u]);
else if (t == 1)
sb.Append(words1[u]);
else
sb.Append(words2[t - 2] + words0[u]);
}
if (i != 0) sb.Append(words3[i - 1]);
}
return sb.ToString().TrimEnd();
}

How to show in a label first 100 even numbers using While and Do While ? c#

Actually i have a button to display the first 100 even numbers using For
int a = 100;
int res = 0;
int i;
string npares = "";
for (i = 0; i <= a; i++)
{
if (i % 2 == 0)
{
res = res + i;
if (i < a)
npares += i + ",";
else
npares += i;
}
}
LBLstatus.MaximumSize = new Size(200, 0);
LBLstatus.Text = npares;
But i need to make the same with more two buttons using While and Do While , how i can make this ?
EDIT >>>>>>
Using while i got this way :
int a = 100;
int i = 0;
string npares = "";
int res = 0;
while (i <= a)
{
i++;
if
(i % 2 == 0)
{
res = res + i;
if (i < a)
npares += i + ",";
else
npares += i;
}
LBLstatus.Text = npares;
(This answer shows the relationship between constructs, but does not otherwise attempt to provide a solution.)
The construct
for (init;cond;post)
{
body;
}
can be generally rewritten as / considered equivalent to
init;
while (cond) {
body;
post;
}
On the other hand a do-while has no analogous simple for form, because it delays evaluation of cond until after the body has been executed once, but it can be written as
for (init;;post) {
body;
if (!cond) break;
}
Using Take
List<int> ints;
List<int> positiveInts = ints.Where(i => i % 2 == 0).Take(100).ToList();
Using Aggregate
List<int> ints;
string positiveInts = ints.Where(i => i % 2 == 0).Take(100).Select(i => i.ToString()).Aggregate((a,b) => b += String.IsNullOrEmpty(b) ? a : "," + a);

How to add or subtract very large numbers without bigint in C#?

So let me start by saying that I'm a newbie with little to moderate knowledge about C#.
Coming to the topic: I need to make a program that is able to add/subtract very large integers. Initially, used BigInt only to find out it's not allowed. There should be a logical workaround for this? I have an idea which is using "elementary school method" where you add each digit starting from right to left.
I made a string which I split into char array and added each digit from right to left(GetUpperBound-i). But it doesn't seem to work.
My Code:
string s, s2;
char[] c_arr, c_arr2;
int i, erg;
s = "1234";
s2 = "5678";
c_arr = s.ToCharArray();
c_arr2 = s2.ToCharArray();
for (i = 0; i <= c_arr.GetUpperBound(0); i++)
{
erg = c_arr[c_arr.GetUpperBound(0)-i]+c_arr2[c_arr2.GetUpperBound(0)-i];
Console.Write(erg);
}
Console.ReadKey();
There are a few things wrong with your code for the 'elementary school method'. You don't account for carry, you're adding up ascii values rather than actual values between 0-9, and you're outputting the results in the wrong order.
The code below, whilst not very elegant, does produce the correct results:
var s1 = "12345";
var s2 = "5678";
var carry = false;
var result = String.Empty;
if(s1.Length != s2.Length)
{
var diff = Math.Abs(s1.Length - s2.Length);
if(s1.Length < s2.Length)
{
s1 = String.Join("", Enumerable.Repeat("0", diff)) + s1;
}
else
{
s2 = String.Join("", Enumerable.Repeat("0", diff)) + s2;
}
}
for(int i = s1.Length-1;i >= 0; i--)
{
var augend = Convert.ToInt32(s1.Substring(i,1));
var addend = Convert.ToInt32(s2.Substring(i,1));
var sum = augend + addend;
sum += (carry ? 1 : 0);
carry = false;
if(sum > 9)
{
carry = true;
sum -= 10;
}
result = sum.ToString() + result;
}
if(carry)
{
result = "1" + result;
}
Console.WriteLine(result);
The following program can be used to add two large numbers, I have used string builder to store the result. You can add numbers containing digits upto '2,147,483,647'.
Using System;
using System.Text;
using System.Linq;
public class Test
{
public static void Main()
{
string term1="15245142151235123512352362362352351236";
string term2="1522135123612646436143613461344";
StringBuilder sum=new StringBuilder();
int n1=term1.Length;
int n2=term2.Length;
int carry=0;
int n=(n1>n2)?n1:n2;
if(n1>n2)
term2=term2.PadLeft(n1,'0');
else
term1=term1.PadLeft(n2,'0');
for(int i=n-1;i>=0;i--)
{
int value=(carry+term1[i]-48+term2[i]-48)%10;
sum.Append(value);
carry=(carry+term1[i]-48+term2[i]-48)/10;
}
char[] c=sum.ToString().ToCharArray();
Array.Reverse(c);
Console.WriteLine(c);
}
}
string Add(string s1, string s2)
{
bool carry = false;
string result = string.Empty;
if(s1[0] != '-' && s2[0] != '-')
{
if (s1.Length < s2.Length)
s1 = s1.PadLeft(s2.Length, '0');
if(s2.Length < s1.Length)
s2 = s2.PadLeft(s1.Length, '0');
for(int i = s1.Length-1; i >= 0; i--)
{
var augend = Convert.ToInt64(s1.Substring(i,1));
var addend = Convert.ToInt64(s2.Substring(i,1));
var sum = augend + addend;
sum += (carry ? 1 : 0);
carry = false;
if(sum > 9)
{
carry = true;
sum -= 10;
}
result = sum.ToString() + result;
}
if(carry)
{
result = "1" + result;
}
}
else if(s1[0] == '-' || s2[0] == '-')
{
long sum = 0;
if(s2[0] == '-')
{
//Removing negative sign
char[] MyChar = {'-'};
string NewString = s2.TrimStart(MyChar);
s2 = NewString;
if(s2.Length < s1.Length)
s2 = s2.PadLeft(s1.Length, '0');
for (int i = s1.Length - 1; i >= 0; i--)
{
var augend = Convert.ToInt64(s1.Substring(i,1));
var addend = Convert.ToInt64(s2.Substring(i,1));
if(augend >= addend)
{
sum = augend - addend;
}
else
{
int temp = i - 1;
long numberNext = Convert.ToInt64(s1.Substring(temp,1));
//if number before is 0
while(numberNext == 0)
{
temp--;
numberNext = Convert.ToInt64(s1.Substring(temp,1));
}
//taking one from the neighbor number
int a = int.Parse(s1[temp].ToString());
a--;
StringBuilder tempString = new StringBuilder(s1);
string aString = a.ToString();
tempString[temp] = Convert.ToChar(aString);
s1 = tempString.ToString();
while(temp < i)
{
temp++;
StringBuilder copyS1 = new StringBuilder(s1);
string nine = "9";
tempString[temp] = Convert.ToChar(nine);
s1 = tempString.ToString();
}
augend += 10;
sum = augend - addend;
}
result = sum.ToString() + result;
}
//Removing the zero infront of the answer
char[] zeroChar = {'0'};
string tempResult = result.TrimStart(zeroChar);
result = tempResult;
}
}
return result;
}
string Multiply(string s1, string s2)
{
string result = string.Empty;
//For multipication
bool Negative = false;
if(s1[0] == '-' && s2[0] == '-')
Negative = false;
else if(s1[0] == '-' || s2[0] == '-')
Negative = true;
char[] minusChar = {'-'};
string NewString;
NewString = s2.TrimStart(minusChar);
s2 = NewString;
NewString = s1.TrimStart(minusChar);
s1 = NewString;
List<string> resultList = new List<string>();
for(int i = s2.Length - 1; i >= 0; i--)
{
string multiplycation = string.Empty;
for (int j = s1.Length - 1; j >= 0; j--)
{
var augend = Convert.ToInt64(s1.Substring(j,1));
var addend = Convert.ToInt64(s2.Substring(i,1));
long multiply = augend * addend;
// print(multiply);
multiplycation = multiply.ToString() + multiplycation;
}
//Adding zero at the end of the multiplication
for (int k = s2.Length - 1 - i; k > 0; k--)
{
multiplycation += "0";
}
resultList.Add(multiplycation);
}
for (int i = 1; i < resultList.Count; i++)
{
resultList[0] = Add(resultList[0],resultList[i]);
}
//Finally assigning if negative negative sign in front of the number
if(Negative)
result = resultList[0].Insert(0,"-");
else
result = resultList[0];
return result;
}
string Divide(string dividend, string divisor)
{
string result = string.Empty;
int remainder = 0;
int intNumberstoGet = divisor.Length;
int currentInt = 0;
int dividing = int.Parse(dividend.Substring(currentInt,intNumberstoGet));
int intDivisor = int.Parse(divisor);
while(currentInt < dividend.Length)
{
if(dividing == 0)
{
currentInt++;
result += "0";
}
else
{
while(dividing < intDivisor)
{
intNumberstoGet++;
dividing = int.Parse(dividend.Substring(currentInt,intNumberstoGet));
}
if (dividing > 0)
{
remainder = dividing % intDivisor;
result += ((dividing - remainder) / intDivisor).ToString();
intNumberstoGet = 1;
if(currentInt < dividend.Length - 2)
currentInt += 2;
else
currentInt++;
if(currentInt != dividend.Length)
{
dividing = int.Parse(dividend.Substring(currentInt,intNumberstoGet));
remainder *= 10;
dividing += remainder;
}
}
}
}
return result;
}
Here you go. Another example. It's 10 to 30 times faster than the accepted answer.
static string AddNumStr(string v1, string v2)
{
var v1Len = v1.Length;
var v2Len = v2.Length;
var count = Math.Max(v1Len, v2Len);
var answ = new char[count + 1];
while (count >= 0) answ[count--] = (char)((v1Len > 0 ? v1[--v1Len] & 0xF:0) + (v2Len>0 ? v2[--v2Len]&0xF : 0));
for (var i = answ.Length - 1; i >= 0; i--)
{
if (answ[i] > 9)
{
answ[i - 1]++;
answ[i] -= (char)10;
}
answ[i] = (char)(answ[i] | 48);
}
return new string(answ).TrimStart('0');
}
Below SO question has some interesting approaches. Though the answer is in Java, but you will surely get to know what needs to be done.
How to handle very large numbers in Java without using java.math.BigInteger
public static int[] addTwoNumbers(string s1, string s2)
{
char[] num1 = s1.ToCharArray();
char[] num2 = s2.ToCharArray();
int sum = 0;
int carry = 0;
int size = (s1.Length > s2.Length) ? s1.Length + 1 : s2.Length + 1;
int[] result = new int[size];
int index = size - 1;
int num1index = num1.Length - 1;
int num2index = num2.Length - 1;
while (true)
{
if (num1index >= 0 && num2index >= 0)
{
sum = (num1[num1index]-'0') + (num2[num2index]-'0') + carry;
}
else if(num1index< 0 && num2index >= 0)
{
sum = (num2[num2index]-'0') + carry;
}
else if (num1index >= 0 && num2index < 0)
{
sum = (num1[num1index]-'0') + carry;
}
else { break; }
carry = sum /10;
result[index] = sum % 10;
index--;
num1index--;
num2index--;
}
if(carry>0)
{
result[index] = carry;
}
return result;
}

C# Make a sum with two random numbers but it must equal the users input

I was wondering if it is possible to make a sum from a user input int but the sum must be radom every time.
This is the code that I made :
public static string genSum(int askedNumber)
{
string outputStr = null;
bool switchOneTwo = false;
int neededSum = 0;
int intOne = 0;
int intTwo = 0;
while (askedNumber != neededSum)
{
if (switchOneTwo == true)
{
intOne += 1;
switchOneTwo = false;
}
else
{
intTwo += 1;
switchOneTwo = true;
}
neededSum = intOne + intTwo;
if (neededSum == askedNumber)
{
if (neededSum >= 4)
{
Random randomInt = new Random();
int tmpIntOne = intOne;
int tmpIntTwo = intTwo;
int method;
//For now only one method
method = randomInt.Next(1, 1);
if (method == 1)
{
tmpIntOne = tmpIntOne / 2;
tmpIntTwo = (tmpIntTwo * 2) - tmpIntOne;
}
intOne = tmpIntOne;
intTwo = tmpIntTwo;
}
outputStr = "(" + intOne.ToString() + "+" + intTwo.ToString() + ")";
return outputStr;
}
}
return outputStr;
}
so what I want is that if a user eneters a number for example 20 it will then make a sum :
User enters 20 and presses GO! :
Result :
10 + 10 = 20
12 + 8 = 20
5 + 15 = 20
1 + 19 = 20
3 + 17 = 20
User enters 500 and presses GO! :
Result :
9 + 491 = 500
263 + 237 = 500
300 + 200 = 500
250 + 250 = 500
109 + 391 = 500
Create a random number less than the input and the other one will be User-YourRandom
void Foo(int userNumber)
{
Random r = new Random();
int firstNumber = r.Next(userNumber - 1);
int secondNumber = userNumber - firstNumber;
}
You can extend this to support negatives also.
edit getting true randoms
as I4V points out, if you put this in a loop you might get same set of numbers, so instead of calling Random you can use this approach:
void Foo(int userNumber)
{
int userNumber = 500;
for (int i = 0; i < 10; i++ )
{
int firstNumber = Next(0, userNumber - 1);
int secondNumber = userNumber - firstNumber;
Console.WriteLine(firstNumber + "+" + secondNumber);
}
}
internal static int RandomExt(int min, int max)
{
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buffer = new byte[4];
rng.GetBytes(buffer);
int result = BitConverter.ToInt32(buffer, 0);
return new Random(result).Next(min, max);
}
foreach (var s in genSum(500).Take(5))
{
Console.WriteLine(s);
}
public static IEnumerable<string> genSum(int askedNumber)
{
Random r = new Random();
while (true)
{
var i = r.Next(0, askedNumber);
yield return i + "+" + (askedNumber - i);
}
}

Categories