previous, current and next 3 quarters? - c#

I am trying to get previous, current and next 3 quarters base on current quarter and year.
Example : Current Quarter = 3 & Year = 2014
I want Output,
Q2-2014
Q3-2014
Q4-2014
Q1-2015
Q2-2015
I am trying as under but output is NOT correct and also how to club previous quarter?
static void Main(string[] args)
{
int generateQuater = 5;
int currentQuater = 3;
int currentYear = DateTime.Now.Year;
List<string> lstQuaterYear = new List<string>();
for (int i = generateQuater; i > 0; i--)
{
lstQuaterYear.Add(string.Format("Q{0}-{1}", currentQuater, currentYear));
if (--currentQuater == 0)
{
currentQuater = 4;
currentYear++;
}
}
Console.ReadLine();
}

Change your loop as follows:
for (int i = 0; i < generateQuater; i++)
{
if(currentQuater%5 ==0)
{
currentQuater = 1;
currentYear++;
}
lstQuaterYear.Add(string.Format("Q{0}-{1}", currentQuater%5, currentYear));
currentQuater++;
}
Modulo 5 will return values in the range [0,4]. Quarter 0 can be interpreted as quarter 1 of the next year. Therefore, we handle that case by setting currentQuater to 1 and incrementing currentYear. This will go through the 4 quarters of each year, and on the 5th one, it will move to next year and restart counting from 1.
Demo

Finally this code with help of Tieson.
Question : Any other/linq approach for subjected problem also welcome.
int generateQuater = 4;
int currentQuater = 3;
int currentYear = DateTime.Now.Year;
List<string> lstQuaterYear = new List<string>();
//previous Quater
lstQuaterYear.Add(String.Format("Q{0}-{1}", (currentQuater - 1) + (((1) / 4) * 4), currentYear - ((1) / 4)));
for (int i = 0; i < generateQuater; i++)
{
if (currentQuater % 5 == 0)
{
currentQuater = 1;
currentYear++;
}
//current and next 3 Quater
lstQuaterYear.Add(string.Format("Q{0}-{1}", currentQuater % 5, currentYear));
currentQuater++;
}

Related

Calculating the correct length of string per line with Page X/Y

I got asked a question and now I am kicking myself for not being able to come up with the exact/correct result.
Imagine we have a function that splits a string into multiple lines but each line has to have x number of characters before we "split" to the new line:
private string[] GetPagedMessages(string input, int maxCharsPerLine) { ... }
For each line, we need to incorporate, at the end of the line "x/y" which is basically 1/4, 2/4 etc...
Now, the paging mechanism must also be part of the length restriction per line.
I have been overworked and overthinking and tripping up on things and this seems pretty straight forward but for the life of me, I cannot figure it out! What am I not "getting"?
What am I interested in? The calculation and some part of the logic but mainly the calculation of how many lines are required to split the input based on the max chars per line which also needs to include the x/y.
Remember: we can have more than a single digit for the x/y (i.e: not just 1/4 but also 10/17 or 99/200)
Samples:
input = "This is a long message"
maxCharsPerLine = 10
output:
This i 1/4 // << Max 10 chars
s a lo 2/4 // << Max 10 chars
ng mes 3/4 // << Max 10 chars
sage 4/4 // << Max 10 chars
Overall the logic is simple but its just the calculation that is throwing me off.
The idea: First, find how many digits is the number of lines:
(n = input.Length, maxCharsPerLine = 10)
if n <= 9*(10-4) ==> 1 digit
if n <= 9*(10-5) + 90*(10-6) ==> 2 digits
if n <= 9*(10-6) + 90*(10-7) + 900*(10-8) ==> 3 digits
if n <= 9*(10-7) + 90*(10-8) + 900*(10-9) + 9000*(10-10) ==> No solution
Then, subtract the spare number of lines. The solution:
private static int GetNumberOfLines(string input, int maxCharsPerLine)
{
int n = input.Length;
int x = maxCharsPerLine;
for (int i = 4; i < x; i++)
{
int j, sum = 0, d = 9, numberOfLines = 0;
for (j = i; j <= i + i - 4; j++)
{
if (x - j <= 0)
return -1; // No solution
sum += d * (x - j);
numberOfLines += d;
d *= 10;
}
if (n <= sum)
return numberOfLines - (sum - n) / (x - j + 1);
}
return -2; // Invalid
}
Usage:
private static string[] GetPagedMessages(string input, int maxCharsPerLine)
{
int numberOfLines = GetNumberOfLines(input, maxCharsPerLine);
if (numberOfLines < 0)
return null;
string[] result = new string[numberOfLines];
int spaceLeftForLine = maxCharsPerLine - numberOfLines.ToString().Length - 2; // Remove the chars of " x/y" except the incremental 'x'
int inputPosition = 0;
for (int line = 1; line < numberOfLines; line++)
{
int charsInLine = spaceLeftForLine - line.ToString().Length;
result[line - 1] = input.Substring(inputPosition, charsInLine) + $" {line}/{numberOfLines}";
inputPosition += charsInLine;
}
result[numberOfLines-1] = input.Substring(inputPosition) + $" {numberOfLines}/{numberOfLines}";
return result;
}
A naive approach is to start counting the line lengths minus the "pager"'s size, until the line count changes in size ("1/9" is shorter than "1/10", which is shorter than "11/20", and so on):
private static int[] GetLineLengths(string input, int maxCharsPerLine)
{
/* The "pager" (x/y) is at least 4 characters (including the preceding space) and at most ... 8?
* 7/9 (4)
* 1/10 (5)
* 42/69 (6)
* 3/123 (6)
* 42/420 (7)
* 999/999 (8)
*/
int charsRemaining = input.Length;
var lineLengths = new List<int>();
// Start with " 1/2", (1 + 1 + 2) = 4 length
var highestLineNumberLength = 1;
var lineNumber = 0;
do
{
lineNumber++;
var currentLineNumberLength = lineNumber.ToString().Length; // 1 = 1, 99 = 2, ...
if (currentLineNumberLength > highestLineNumberLength)
{
// Pager size changed, reset
highestLineNumberLength = currentLineNumberLength;
lineLengths.Clear();
lineNumber = 0;
charsRemaining = input.Length;
continue;
}
var pagerSize = currentLineNumberLength + highestLineNumberLength + 2;
var lineLength = maxCharsPerLine - pagerSize;
if (lineLength <= 0)
{
throw new ArgumentException($"Can't split input of size {input.Length} into chunks of size {maxCharsPerLine}");
}
lineLengths.Add(lineLength);
charsRemaining -= lineLength;
}
while (charsRemaining > 0);
return lineLengths.ToArray();
}
Usage:
private static string[] GetPagedMessages(string input, int maxCharsPerLine)
{
if (input.Length <= maxCharsPerLine)
{
// Assumption: no pager required for a message that takes one line
return new[] { input };
}
var lineLengths = GetLineLengths(input, maxCharsPerLine);
var result = new string[lineLengths.Length];
// Cut the input and append the pager
var previousIndex = 0;
for (var i = 0; i < lineLengths.Length; i++)
{
var lineLength = Math.Min(lineLengths[i], input.Length - previousIndex); // To cater for final line being shorter
result[i] = input.Substring(previousIndex, lineLength) + " " + (i + 1) + "/" + lineLengths.Length;
previousIndex += lineLength;
}
return result;
}
Prints, for example:
This 1/20
is a 2/20
long 3/20
strin 4/20
g tha 5/20
t wil 6/20
l spa 7/20
n mor 8/20
e tha 9/20
n te 10/20
n li 11/20
nes 12/20
beca 13/20
use 14/20
of i 15/20
ts e 16/20
norm 17/20
ous 18/20
leng 19/20
th 20/20

Want to find date based on input number C#

I want to be able to find date based on input number(between 1-365). For e.g., if number entered as 40 then my program should output - Date:9 Month:2
I have tried the below code and was able to find dates for all months except January -
static void Main(string[] args)
{
int[] arryofdays = new int[] {31,28,31,30,31,30,31,31,30,31,30,31};
int num = Int32.Parse(Console.ReadLine());
int temp = num;
string date, month;
for (int i = 0; i < arryofdays.Length; i++)
{
temp = temp - arryofdays[i];
if (temp < arryofdays[i + 1])
{
Console.WriteLine("Date:" + temp.ToString());
Console.WriteLine("Month:" + (i+2).ToString());
break;
}
}
Console.ReadLine();
}
Please help!
Why don't you just try like this;
var datetime = new DateTime(2017, 1, 1).AddDays(40 - 1);
var month = datetime.Month; //2
var day = datetime.Day; //9
The reason why your code is not working for JAN month is, because on temp = temp - arryofdays[i]; statement you are getting negative values if your inout is less than 31.
You can modify your code like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
//Your code goes here
Console.WriteLine("Hello, world!");
int[] arryofdays = new int[] {31,28,31,30,31,30,31,31,30,31,30,31};
int num = Int32.Parse(Console.ReadLine());
int temp = num;
string date, month;
for (int i = 0; i < arryofdays.Length; i++)
{
temp =(temp - arryofdays[i]);
if (temp < arryofdays[i + 1] && temp >0)
{
Console.WriteLine("Date:" + temp.ToString());
Console.WriteLine("Month:" + (i+2).ToString());
break;
}else{//for handling first month
Console.WriteLine("Date:" +num);
Console.WriteLine("Month:" + 1);
break;
}
}
Console.ReadLine();
}
}
}
Working code : http://rextester.com/PAJQ64015
Hope that helps.
try like this ,take arugment and also check it you can able to convert in int form or not, make your program type safe
and also check validation that days value will be between 1 and 365
public static void Main(string[] args)
{
int days = 0;
if (args.Length > 0 && int.TryParse(args[0], out days))
{
if (!(days < 1 || days > 366))
{
DateTime date = new DateTime(DateTime.Now.Year, 1, 1).AddDays(days - 1);
Console.WriteLine("Date: {0}", date.Day);
Console.WriteLine("Date: {0}", date.Month);
}
}
else
{
Console.WriteLine("input vlaue is not correct or not present");
}
}
You can try it like this
static void Main(string[] args)
{
int[] arryofdays = new int[] {31,28,31,30,31,30,31,31,30,31,30,31};
int num = Int32.Parse(Console.ReadLine());
int days = 0;
int months = 0;
for (int i = 0; i < arryofdays.Length; i++) {
if (num > arryofdays[i]) {
num -= arryofdays[i];
months++;
} else {
days = num;
break;
}
}
Console.WriteLine("Date:" + days.ToString());
Console.WriteLine("Month:" + (months+1).ToString());
Console.ReadLine();
}
Assuming num = 40, on the first iteration of the for loop, it'll check if num > arryofdays[0] which is if 40 > 31. That'll return true, so 31 will be decremented from num making the value of num to be 9. months will be incremented. On the next iteration (i = 1), it'll check if num > arryofdays[1] which is if 9 > 28 which means there are only 9 days and we break because we don't need to go any further.
Your output will be
Date:9
Month:2

Find N consecutive integers on a array, whose sum(of consecutive integers) S is a integer that i have

explanation
I have been staring at the problem for a few of minutes.
And i did some research before i ask this quest , but it were in different cases and they didn't included what i really need.
I found this piece of code in SO.
static int GetLargestSum(int[] array, int n, int sum)
{
int largestSum = 0;
int previousSum = 0;
for (int i = 0; i <= array.Length - n; i++)
{
if (i == 0)
{
for (int j = 0; j < n; j++)
{
largestSum += array[j];
}
previousSum = largestSum;
}
else
{
int currentSum = previousSum - array[i - 1] + array[i + n - 1];
if (currentSum > largestSum)
{
largestSum = currentSum;
}
previousSum = currentSum;
}
}
return largestSum;
}
And yes this works but if works for only the largest sum.
I tried to modify it to add the sum var into the code but that didn't actually went that well.
So i would really appreciate if someone helps me, bcs i am stuck in this algorithm.
Thank you!
The way to solve it would be to iterate over each segment of the array and evaluate its sum. A crude first draft would look something like this
public static int ConsecutiveSumArrangements(int[] vals, int count, int sum)
{
var number = 0;
for (int i = 0; i < (vals.Length - count); i++)
{
var segSum = vals.Skip(i).Take(count).Sum();
if (segSum == sum)
{
number++;
}
}
return number;
}
Maybe it is easier think in another way than try to correct this code. An idea is using slide window. Pseudo code look like
sum = 0
sol = 0
start = 0
end = 0
// sum of the first m elements
while end < m
sum = sum + s[end]
end = end + 1
If sum == d
sol = sol + 1
while end < n
sum = sum + s[end]
sum = sum - s[start]
end = end + 1
start = start + 1
if sum == d
sol = sol + 1
// in the loop we add the next element and subtract the first element
//so, we keep the length of m elements

Find the 10001st prime

I took a look at the following question from project euler:
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
I tried to take the square root of the number and than find all the prime numbers below the square root of the number and then divide the number by all the square roots and see if there is 0 left each time. If the number is not divisible by all the primes under its square root its a prime number. I did this to lower the itterations the programm has to make. Here is what I have now, I am not sure why it isn't working. Anybody knows what i did wrong?
List<int> primeNumbers = new List<int>();
bool prime = true;
bool MainPrime = true;
int check = 1;
for (long i = 3; i < long.MaxValue; i++)
{
if ((i % 2) != 0)
{
int root = Convert.ToInt32(Math.Sqrt(i));
for (int j = 1; j < root; j++)
{
for (int k = 2; k < j; k++)
{
if ((j% k) == 0)
{
prime = false;
}
}
if (prime)
{
primeNumbers.Add(j);
}
prime = true;
}
}
foreach (var item in primeNumbers)
{
if ((i%item) == 0)
{
MainPrime = false;
}
}
primeNumbers.Clear();
if (MainPrime)
{
check++;
}
if (check == 10001)
{
Console.WriteLine(i);
break;
}
}
Console.ReadKey();
Several points:
When finding possible prime divisors, you need to check all numbers up to the square root included, so your condition j < root is incorrect.
You don't have to recalculate the primes again for every number. Keep the list as you go and add new primes to it.
As soon as you find a divisor, you can break out of the foreach loop.
Improved code:
List<long> primeNumbers = new List<long>() { 2 };
for (long i = 3; i < long.MaxValue; i += 2)
{
if(!primeNumbers.Any(p => (i % p) == 0))
{
primeNumbers.Add(i);
if (primeNumbers.Count == 10001)
{
Console.WriteLine(i);
break;
}
}
}
Gives 104743 as the 10001st prime.
What we can do is we can use SieveOfEratosthenes to make an bool array in which all the prime numbers value are set to be true than after that;
1.As we found any prime number increment the count with 1;
2.And as count get equal to 10001 we print its value and break through the loop.
Have a Look at code in C++ (I recommend you to learn SieveOfEratosthenes first)
#include <bits/stdc++.h>
using namespace std;
void SieveOfEratosthenes(long long unsigned n)
{
bool prime[n];
memset(prime, true, sizeof(prime)); //This is SieveOfEratosthenes
for (long long p = 2; p * p <= n; p++)
{
if (prime[p] == true)
{
for (long long i = p * p; i <= n; i += p)
prime[i] = false;
}
}
long long count=0; //initializing count as 0;
for (long long p = 2; p <= n; p++) //running the loop form 2 to n
{
if (prime[p]) //we have bool array in which all prime number set to true using sieve
count++; //increment the count because we found a prime number
if(count==10001) // and as count reaches to 10001 we found our number
{
cout<<p;break;} // print the answer and also break form the loop
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long unsigned n=999999;
SieveOfEratosthenes(n); //pass the value of n in sieve function
return 0;
}
Try this one out using python
sp=2
cnt = 1
while cnt <= 10001:
primeflag = 0
for j in range(2,sp):
if(sp%j == 0):
primeflag = 1
break;
if(primeflag == 1):
pass
else:
print(cnt ,sp)
cnt = cnt +1
sp =sp+1
#which Gives
#10001 104743

Looping - amount of years from months

I have a int months (84 for example) and I need to work out how many years that equals so using 84 = 7 years
I need to loop through the initial number and see how many full years are in there and print the result
example:
int count = 84;
for (int i = 12; i <= count; i++)
{
years = i;
}
This doesn't work of course, it produces '84 years' where I should produce 7 years. I also need to get the remaining months after the year calculation so if the initial number was 85 for example it would result in 7 years 1 month.
Use standard mathematical operations instead of a loop:
int count = 84;
int years = count / 12;
int months = count % 12;
First one is division, second is modulus.
Because both count and 12 are integers count/12 returns an integer as well. So for 85 it will return 7, not 7.1.
Update
Loop version could look like that:
count = 84;
years = 0;
for (int i = 12; i <= count; i += 12)
{
years++;
}
Doing that with a loop would look like this:
int years = 0;
while (count >= 12) {
count -= 12;
years++;
}
However, you can do the same without looping:
int years = count / 12;
count %= 12;
Try this:
DateTime t = new DateTime();
t = t.AddMonths(84);
int year = t.Year; // year = 8
int month = t.Month; // month = 1
Surely you just need basic math operations:
int count = 84;
int years = (int)(count / 12);
int months = count % 12;
int years = count / 12;
int remainingMonths = count % 12;
thanks to everyone who gave a answer :D much appreciated
i got it working like this in the end
int employmentInMonthsAmount = this.MaxEmploymentHistoryInMonths;
var intcounter = 0;
int years = 0;
for (var i = 0; i < employmentInMonthsAmount; i++)
{
if (intcounter >= 12)
{
years++;
intcounter = 0;
}
intcounter++;
}
var monthsleft = intcounter;

Categories

Resources