I have a pagination issue :
I have a large number of pages as results in my table ~50.000 pages and my pagination logic is something like :
1 2 3 ...50000
I would like to do something like :
1 2 3 10 100 500 1000 5000 10000 50000
And when i click for example 1111 :
1 1109 1110 1111 1112 1113 1114 1120 1200 1700 2200 3000 8000 10000 50000
so far I;ve tried something like this :
int Max_count = (int)Math.Floor(Math.Log10(totalPages) + 1);
for (int index = start; index <= end; index++)
{
if (index == pageNumber)
{
header.Items.Add(new PagingHeaderModelItem(PageHeaderItemType.CurrentPage, pageNumber));
}
else if (index == start)
{
header.Items.Add(new PagingHeaderModelItem(PageHeaderItemType.StartPage, 0));
}
else if (index == end)
{
header.Items.Add(new PagingHeaderModelItem(PageHeaderItemType.EndPage, totalPages - 1));
}
else if ((index == start + 1) && (index > 1))
{
header.Items.Add(new PagingHeaderModelItem(PageHeaderItemType.MorePages, -1));
}
else if ((index == end - 1) && (index < totalPages - 2))
{
header.Items.Add(new PagingHeaderModelItem(PageHeaderItemType.MorePages, -1));
}
else if ((index > 100) && (index > totalPages / 2))
{
header.Items.Add(new PagingHeaderModelItem(PageHeaderItemType.SimplePage, index));
}
else if ((pageNumber + 2 > index) && index + 10 < totalPages && !isSecond)
{
for (int temp = 1; temp < Max_count; temp++)
{
int power_var = (int)Math.Pow(10, temp);
int power_var_prev = (int)Math.Pow(10, temp - 1);
if ((pageNumber > power_var) || pageNumber < 10)
{
header.Items.Add(new PagingHeaderModelItem(PageHeaderItemType.SimplePage, power_var - 1));
header.Items.Add(new PagingHeaderModelItem(PageHeaderItemType.SimplePage, power_var - 1 + power_var_prev));
temp++;
}
}
isSecond = true;
}
else if (index - start < 3)
{
header.Items.Add(new PagingHeaderModelItem(PageHeaderItemType.SimplePage, index));
}
But i Feel like I'm not close to this at all. I'm not asking for a solution more of a hint or a formula I could use to do this by myself
LATER EDIT
The pattern should be like :
n-3, // 1 //1
n-2, // 2 //1109
n-1, // 3 //1110
**n**, // **4** //1111
n+1, //5 //1112
n+2, //6 //1113
n+3, //7 //1114
Math.Floor((index + 10)) / 10) * 10, //10 //1120
Math.Floor((index + 10)) / 10) * 10 +50, //60 //1170
Math.Floor((index + 100)) / 100) * 100, //100 //1200
Math.Floor((index + 100)) / 100) * 100+500,//600 //1700
Math.Floor((index + 1000)) / 1000) * 1000,//1000 //2000
Math.Floor((index + 1000)) / 1000) * 1000+5000,//6000/7000
....
Here's some code to print the desired values:
(it does print 1108 as well, but that should be easy enough to work around)
(changed +50, +500, etc. to +40, +400, etc. because I prefer that)
int min = 1, max = 50000;
if (val-3 > min)
Console.WriteLine(min);
for (int i = Math.Max(min, val-3); i <= Math.Min(max, val+3); i++)
Console.WriteLine(i);
int last = -1;
for (int i = 10; ; i *= 10)
{
int next = (val+3 + i) / i * i;
if (next > max)
break;
// prevent printing something like 90, 130, 100, 500 (100 won't print)
if (next > last)
Console.WriteLine(next);
next += 4*i;
if (next > max)
break;
Console.WriteLine(next);
last = next;
}
Live demo.
If you want to print it from the value to the minimum as well, it could be a simple case of copying the for-loop and inverting the values: (it will print the values from the largest, changing this will require a stack data structure)
for (int i = 10; ; i *= 10)
{
int next = (val-3 - i) / i * i;
if (next < min)
break;
if (next < last)
Console.WriteLine(next);
next -= 4*i;
if (next < min)
break;
Console.WriteLine(next);
last = next;
}
if (last != min)
Console.WriteLine(min);
Here's another idea:
Taking 1111 in 1..50000 as an example.
Take the 2 values before and the 2 values after - 1109, 1110, 1111, 1112, 1113.
Let's say we want an exponential growth towards the target, with 5 points in between.
The range of values upwards would be 50000 - 1113 = 48887 (starting from biggest value above).
Then we want to find x such that (5x)^2 = 48887. This is fairly easy to calculate, just square root 48887 and divide by 5 - sqrt(48887) / 5 = 44.22
Then the values would be:
1113 + (1 * 44.22) ^ 2 = 3068
1113 + (2 * 44.22) ^ 2 = 8934
1113 + (3 * 44.22) ^ 2 = 18712
1113 + (4 * 44.22) ^ 2 = 32400
1113 + (5 * 44.22) ^ 2 = 50000
Similarly for downwards.
You can probably base the number of values in between on how far the target is, if you wish.
If you'd prefer more round numbers, I'd have to think about that a bit more.
Related
I have a method that calculates the waiting time in a queue. It works fine for a small range. However, you can quickly see that this would become very tedious to do with a large range. In this example, if you are #1 in the queue, your wait time is 'very soon'. If it's greater than 1 and less than 5: 0 to 1 weeks, and so on... How can I loop through this list to dynamically find the place in the queue?
if ((PlaceInQueue) <= 1)
{
result = "Very soon!";
}
if ((PlaceInQueue) > 1 & (PlaceInQueue) < 5)
{
result = "From 0 to 1 weeks.";
}
if ((PlaceInQueue) >= 5 & (PlaceInQueue) < 11)
{
result = "From 1 to 2 weeks.";
}
if ((PlaceInQueue) >= 11 & (PlaceInQueue) < 17)
{
result = "From 2 to 3 weeks.";
}
if ((PlaceInQueue) >= 17 & (PlaceInQueue) < 23)
{
result = "From 3 to 4 weeks.";
}
Here's what I've started and what I'm trying to accomplish. The first few if statements before the while loop may need to be hard coded as the math isn't exact and the rest would be dynamic. So, in this example, the results are correct up until the place in the queue is 11 or greater (inside the while loop).
int n = 1;
int max = 300; // Stop calculating when the max is reached
var PlaceInQue = (Convert.ToInt32(placeInQueue)); // This is the position in the Que
foreach (var item in PlaceInQue)
{
if (PlaceInQue <= 1)
{
result = "Very soon!";
}
if (PlaceInQue > 1 & PlaceInQue < 5)
{
result = "From 0 to 1 weeks.";
}
if (PlaceInQue >= 5 & PlaceInQue < 11)
{
result = "From 1 to 2 weeks.";
}
while (n < max)
{
if (PlaceInQue >= (should increment from 11 and then 17 then 23 then 29 and so on...) & PlaceInQue < (increment from 17 then 23 then 29 then 35 and so on...)
{
result = (should increment from "2 to 3 weeks" and then "3 to 4 weeks" and so on until max is reached...)
}
n++;
}
}
I think you need something like this:
if (PlaceInQue <= 1)
{
result = "Very soon!";
}
else if (PlaceInQue < 5)
{
result = "From 0 to 1 weeks.";
}
else if (PlaceInQue < 11)
{
result = "From 1 to 2 weeks.";
}
else if
{
for (int n = 11; n <= max; n += 5)
{
if (PlaceInQue >= n && PlaceInQue < n + 5)
{
int weeks = n / 5;
result = $"From {weeks} to {(weeks + 1)} weeks.";
break;
}
}
}
Below code works for me for which I have checked the probable edge cases. Let me know if it doesn't work for you.
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
Queue<int> queue = new Queue<int>(Enumerable.Range(1, 300));
foreach (var placeInQueue in queue)
{
if(placeInQueue <= 1)
Console.WriteLine($"Place: {placeInQueue}. Very soon!");
else if(placeInQueue < 300)
{
var fromTo = GetFromTo(placeInQueue);
Console.WriteLine($"Place: {placeInQueue}. From {fromTo.Item1} to {fromTo.Item2} weeks.");
}
}
}
private static Tuple<int,int> GetFromTo(int place)
{
if (place < 5)
return new Tuple<int, int>(0, 1);
var q1 = place / 5;
var q2 = 0;
if((place + 1) % 6 == 0)
{
q2 = (place + 1) / 6;
q1 = int.MaxValue;
}
else
q2 = (place/6) == 0 ? q1 : (place/6);
var from = Math.Min(q1, q2);
var to = from + 1;
return new Tuple<int, int>(from, to);
}
}
Two (2 digit) numbers are written together, so they form one 4 digit number. This 4 digit number can be divided by the multiplication of this two numbers. The problem is that I have to find this numbers.
I wrote an algorithm and get 2 pair of these numbers.
1) 13 and 52, so 1352 can be divided by 13 * 52.
2) 17 and 34, so 1734 can be divided by 17 * 34.
My algorithm looks like this:
for (int i = 1010; i <= 9999; i++)
{
int mult = (i / 100) * (i % 100);
if ((i % 100) > 9 && i % mult == 0)
{
Console.WriteLine(i / 100 + " <--> " + i % 100);
}
}
Edit: with this algorithm (based on mentallurg answer) I find this numbers a bit faster
for (int i = 10; i < 99; i++)
{
for (int j = 10; j < 99; j++)
{
int mult = i * j;
int num = i * 100 + j;
if (num % mult == 0)
{
Console.WriteLine(i + " <--> " + j);
}
}
}
I am interested in how I can make this algorithm more efficient.
This is very efficient:
var query =
from x in Enumerable.Range(10, 90)
from n in Enumerable.Range(1, 10).TakeWhile(w => w * x < 100)
let v = x * (100 + n)
where v % (n * x * x) == 0
select new { x, y = n * x };
It computes all possible first digits. It then computes all of the possible second digits that are multiples of the first digit that are greater than zero and less than 100. It then produces the a candidate value at checks if it is divisible by the product of both digits.
It gives both of the possible answers.
Here's the equivalent using for loops:
for (int x = 10; x <= 99; x++)
{
for (int n = 1; x * n < 100; n++)
{
var j = x * n;
int v = x * 100 + j;
int d = x * j;
if (v % d == 0)
{
Console.WriteLine(x + " <--> " + j);
}
}
}
Supposed one of the pairs are a and b, and so the four digits number can be expressed as 100a + b. Do a little math
100a + b = m * a * b
Divided by a on both sides, we have
100 + b / a = m * b
We can conclude that
b can be divided by a, let's say (b == n * a);
b must be greater than a, since 101 is a prime. And it cannot be 3/7/9 times of a, since 103/107/109 are also primes, but let’s neglect this to make the for loop simpler. This can be easily handled in the inner loop of the following code.
So the for loop can be written like this
for (int a = 10; a < 50; a++)
{
for (int n = 2; n * a < 100; n++)
{
if ((100 + n) % (n * a) == 0)
Console.WriteLine(a + " " + n * a);
}
}
The number of iteration of the loop is reduced to a few dozens, from almost 10 thousand.
Use 2 nested cycles from 1 to 99 and you will avoid two division operations on each step.
I saw this function on Percentile calculation, so I copied it and pasted it into the compiler, and it gives me an OutOfRange exception at
else
{
int k = (int)n;
double d = n - k;
return sequence[k - 1] + d * (sequence[k] - sequence[k - 1]);//EXCEPTION
}
What could be the source of the problem, and how do I solve it?
Function:
public double Percentile(double[] sequence, double excelPercentile)
{
Array.Sort(sequence);
int N = sequence.Length;
double n = (N - 1) * excelPercentile + 1;
// Another method: double n = (N + 1) * excelPercentile;
if (n == 1d) return sequence[0];
else if (n == N) return sequence[N - 1];
else
{
int k = (int)n;
double d = n - k;
return sequence[k - 1] + d * (sequence[k] - sequence[k - 1]);
}
}
The issue is that k is a number larger than the number of items in the array.
As was mentioned, the function is designed to work with values between 0 and 1. Restricting the input should correct the problem.
public double Percentile(double[] sequence, double excelPercentile)
{
//if(excelPercentile > 1)
//excelPercentile = 1;
//else if(excelPercentile < 0)
//excelPercentile = 0;
//Depending on how you validate the input you can assume that it's a whole number percentage. Then you only need to check for the number to be between 0 and 100
if(excelPercentile > 100)
excelPercentile = 100;
else if(excelPercentile < 0)
excelPercentile = 0;
excelPercentile /= 100;
Array.Sort(sequence);
int N = sequence.Length;
double n = (N - 1) * excelPercentile + 1;
// Another method: double n = (N + 1) * excelPercentile;
if (n == 1d) return sequence[0];
else if (n == N) return sequence[N - 1];
else
{
int k = (int)n;
double d = n - k;
return sequence[k - 1] + d * (sequence[k] - sequence[k - 1]);
}
}
This is the background to this question:
Background
Take any integer n greater than 1 and apply the following algorithm
If n is odd then n = n × 3 + 1 else n = n / 2
If n is equal to 1 then stop, otherwise go to step 1
The following demonstrates what happens when using a starting n of 6
6 - 3 - 10 - 5 - 16 - 8 - 4 - 2 - 1
After 8 generations of the algorithm we get to 1.
It is conjectured that for every number greater than 1 the repeated application of this algorithm will
eventually get to 1.
The question is how can I find a number that takes exactly 500 generations to reduce to 1?
The code below is my version but appearntly got some wrong logic. Could you help me correct this? Thanks in advance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sequence1
{
class Program
{
static void Main(string[] args)
{
int start = 1;
int flag = 0;
int value;
while(true){
int temp = (start - 1) / 3;
string sta = temp.ToString();
if (Int32.TryParse(sta, out value) )
{
if (((start - 1) / 3) % 2 == 1)
{
start = (start - 1) / 3;
flag++;
if (flag == 500)
{
break;
}
}
else
{
start = start * 2;
flag++;
if (flag == 500)
{
break;
}
}
}
else
{
start = start * 2;
flag++;
if (flag == 500)
{
break;
}
}
}
Console.WriteLine("result is {0}", start);
Console.ReadLine();
}
}
}
Since your question's title is "A recursion related issue", I will give you a recursive solution.
int Process(int input, int maxRecursionDepth)
{
// condition to break recursion
if (maxRecursionDepth == 0 || input == 1)
return input;
if (input % 2 == 1) // odd case
return Process(input * 3 + 1, maxRecursionDepth - 1);
else // even case
return Process(input / 2, maxRecursionDepth - 1);
}
Now to find all number in a specified range, that return 1 after exactly 500 recursions:
int startRange = 1, endRange = 1000;
int maxDepth = 500;
List<int> resultList = new List<int>();
for (int i = startRange; i <= endRange; i++)
{
if (Process(i, maxDepth) == 1)
resultList.Add(i);
}
Your problem is a part of Collatz conjecture (about recursively defined function) which has not been solved yet:
http://en.wikipedia.org/wiki/Collatz_conjecture
so I think brute force is a good way out:
public static int GetMinNumber(int generations) {
if (generations < 0)
throw new ArgumentOutOfRangeException("generations");
// Memoization will be quite good here
// but since it takes about 1 second (on my computer) to solve the problem
// and it's a throwaway code (all you need is a number "1979515")
// I haven't done the memoization
for (int result = 1; ; ++result) {
int n = result;
int itterations = 0;
while (n != 1) {
n = (n % 2) == 0 ? n / 2 : 3 * n + 1;
itterations += 1;
if (itterations > generations)
break;
}
if (itterations == generations)
return result;
}
}
...
int test1 = GetMinNumber(8); // <- 6
int test2 = GetMinNumber(500); // <- 1979515
Observing the problem,
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
In the third iteration we hit the number 10, which is smaller than 13
So instead of calculating the sequence count every time we can use a cache.
static int GetMinCollatz(int maxChain)
{
const long number = 1000000;
int minNumber = 0;
// Temporary values
int tempCount = 0;
long temp = 0;
// Cache
int[] sequenceCache = new int[number + 1];
// Fill the array with -1
for (int index = 0; index < sequenceCache.Length; index++)
{
sequenceCache[index] = -1;
}
sequenceCache[1] = 1;
for (int index = 2; index <= number; index++)
{
tempCount = 0;
temp = index;
// If the number is repeated then we can find
// sequence count from cache
while (temp != 1 && temp >= index)
{
if (temp % 2 == 0)
temp = temp / 2;
else
temp = temp * 3 + 1;
tempCount++;
}
sequenceCache[index] = tempCount + sequenceCache[temp];
if (sequenceCache[index] == maxChain)
{
minNumber = index;
}
}
return minNumber;
}
For more details refer project euler and this.
A recursive solution
private void ReduceTo1(int input, ref int totalCount)
{
totalCount++;
if (input % 2 == 0)
{
input = input / 2;
}
else
{
input = input * 3 + 1;
}
if (input != 1)
ReduceTo1(input, ref totalCount);
}
to test
int desireValue = 0;
for (int i = 1; i < 100000; i++)
{
int totalCount = 0;
ReduceTo1(i, ref totalCount);
if (totalCount >= 500)
{
desireValue = i;
break;
}
}
I want to find all multiples of 3 given a certain number, and also find the remainder.
So for example:
Given the number 10 : multiples of 3 = {3;6;9} + remainder = 1
Given the number 11 : multiples of 3 = {3;6;9} + remainder = 2
The algorithm I have so far (but not code) goes like this:
Check if X is a multiple of 3 - Yes - return multiples (no remainder);
No? is x-1 a multiple of 3 - Yes - return multiples (1 remainder);
No? is x-2 a multiple of 3 - Yes - return multples (2 remainder);
Is there a better way to do this, using less code?
Edit: 2 more things, I'm only looking for 3 - so this could be a const. Also any number smaller than 3: 2, 1 and 0 - I don't mind having additional logic for that.
IEnumerable<int> Foo(int n, int k)
{
int m = k;
while (m <= n)
{
yield return m;
m += k;
}
yield return m - n;
}
Integer division (/) and modulus (%) are your friends here:
var multiples = num / 3;
var remainder = num % 3;
x = given number
y = loop number
have y loop from 0 to x while increasing it by 3 every time.
if y > x then the remender is (x-(y-3))
You can use the divider / and the modulus %
http://msdn.microsoft.com/en-us/library/3b1ff23f.aspx
10 / 3 = 3
http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx
10 % 3 = 1
int number = 10;
int divisor = 3;
List<int> numbers;
// Find all the numbers by incrementing i by the divisor.
for(int i = 0; i < number; i += divisor)
{
numbers.Add(i);
}
// Find the remainder using modulus operator.
int remainder = number % divisor;
You can simply enumerate the output values
public static IEnumerable<int> GetMultiples(int value, int divisor) {
// Be care of negative and zero values...
if ((value <= 0) || (divisor <= 0))
yield break;
// Multiplications
for (int i = 1; i <= value / divisor; ++i)
yield return i * divisor;
// Finally, let's return remainder if it's non-zero
if ((value % divisor) != 0)
yield return value % divisor;
}
...
foreach(int item in GetMultiples(10, 3)) { // item will be 3, 6, 9, 1
...
}
Here's your exact output
private static void Main(string[] args)
{
int num = 10;
int divisor = 3;
if(num<divisor)
Console.Write(num + " is less than " + divisor);
Console.Write("Given the number " + num + " : multiples of " + divisor + " = {");
for (int i = divisor; i < num; i+=divisor)
Console.Write((i!=3) ? ";"+i : i.ToString());
Console.Write("} + remainder = " + num%divisor);
}
Output
Given the number 10 : multiples of 3 = {3;6;9} + remainder = 1
and checks if input is less than divisor
You can use operator modulo
%
But is very slowly if you use a lot...
This will give you the output you want:
int num;
Console.WriteLine("give me a number equal or above 3!");
int.TryParse(Console.ReadLine(),out num);
int i = 0;
List<int> nums = new List<int>();
i += 3;
while (i <= num)
{
nums.Add(i);
i += 3;
}
Console.Write("Numbers are: ");
foreach (int y in nums)
{
Console.Write(y + " , ");
}
Console.WriteLine("The remainder is " + (num - nums[nums.Count - 1]));
Wasn't LINQ built for EXACTLY for this?
IEnumerable<int> GetMultiples(int max)
{
return Enumerable.Range(1, max / 3)
.Select(p => p * 3)
.Concat((max %= 3) == 0 ? new int[0] : new int[] { max });
}