I am trying to make a multiplication table appear on a page based on input from the user. This is my code:
<asp:GridView runat="server" ID="TableData"></asp:GridView>
List<List<int>> nestedList = new List<List<int>>();
protected void LoadTable(int val)
{
for (int y = 0; y <= val; y++)
{
List<int> list = new List<int>();
for (int x = 0; x <= val; x++)
list.Add(x * y);
nestedList.Add(list);
}
TableData.DataSource = nestedList;
TableData.DataBind();
}
But this displays as:
Capacity Count
16 14
16 14
16 14
16 14
16 14
16 14
16 14
16 14
16 14
16 14
16 14
16 14
16 14
16 14
What am I doing wrong?
For clarification, if the user enters 5, the output should be:
0 0 0 0 0 0
0 1 2 3 4 5
0 2 4 6 8 10
0 3 6 9 12 15
0 4 8 12 16 20
0 5 10 15 20 25
I am not worried about column or row headers at this time.
The problem is with your items Source.
a list< list < ?? > > is not a good choice (as i think).
For a Linear view you can use this approach
Code Snippet
var objList = new List<object>();
for (int i = 0; i < 5; i++)
{
var temp = new { operation = string.Format("{0} * {1}", i, i + 1), result = i * (i + 1) };
objList.Add(temp);
}
GridView does not support 2d list binding, consider using another methode.
For exemple, use a simple List , each string will represent a row, you can fill up each string by using a loop that goes like :
(first loop)
{
string s;
for(int x = 0; x < val; x ++)
{
s += (x * y).Tostring() + " ");
}
nestedList.Add(s);
}
Related
I have been trying to get this to work for 3 days, and I feel like I'm using the wrong approach, if anyone can correct me I will wax your car. Background, client asked to me make a simple pyramid algorithm. I want to select add everything to a list of objects and make everything on the left side true and everything on the right side false. Every other line reads the line 2 lines prior and adds multiple entries. The first time it adds a number like 1 it's one time, then it adds two 1's for each 1 until there is 4. So the first time it enters a 1 on line 1, then on line 3 it adds a 1 two times, then on line 5 it reads from line 3 and adds each of those 1's 2 times.
Here is a visual representation.
|1|
|2| |3|
|1|1| |4|5|
|2|2|3|3| |6|7|8|9|
|1|1|1|1|4|4|5|5| |10|11|12|13|14|15|16|17|
|2|2|2|2|3|3|3|3|6|6|7|7|8|8|9|9| |18|19|20|21|22|23|24|25|26|27|28|29|30|31|32|33
The order this list would be is:
1|2|3|1|1|4|5|2|2|3|3|6|7|8|9|1|1|1|1|4|4|5|5|10|11|12|13|14|15|16|17...
I keep getting close, but it fails to generate the correct output. `
for (int i = 1; i < 50; i = i * 2)
{
Response.Write(i.ToString() + " - ");
var previousLevel = (i / 2 / 2);
foreach (var oc in infoRows.Where(x => x.level == previousLevel))
{
for (int p = i; p > 0; p--)
{
Response.Write(oc.id + "*");
}
}
while (level <= i)
{
for (int r = 1; r <= i; r++)
{
InfoRow tempInforow = new InfoRow();
tempInforow.customerCode = GenerateCustomerNumber(position);
tempInforow.id = customerId;
tempInforow.sendtoidnumber = level.ToString();
tempInforow.status = 0; // GetStatus(position, totalCount);
tempInforow.position = position;
tempInforow.level = i;
infoRows.Add(tempInforow);
customerId++;
position++;
Response.Write(tempInforow.id + "-");
level++;
}
}
}
`
Essentially this generates the following:
1 - 1-
2 - 2-3-
4 - 1*1*1*1*4-5-6-7-
8 - 2*2*2*2*2*2*2*2*3*3*3*3*3*3*3*3*8-9-10-11-12-13-14-15-
16 - 4*4*4*4*4*4*4*4*4*4*4*4*4*4*4*4*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*6*6*6*6*6*6*6*6*6*6*6*6*6*6*6*6*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*16-17-18-19-20-21-22-23-24-25-26-27-28-29-30-31-
32 -
I've tried 30 different ways with switch statements, while statements, for and foreach statements, the closest I can get to this working is level 4.
Can someone suggest another way. Maybe a multidimensional array or idk what. Thank you.
Let's write the sequence down and have a look on what's going on:
# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 ...
seq 1 2 3 1 1 4 5 2 2 3 3 6 7 8 9 1 1 1 1 4 4 5 5 10 ...
^ ^ ^ ^ ^ ^
| |
if # is power of 2 (e.g. 8 == 2**3)
we should copy and double # / 4 items (here 8 / 4 == 2 items)
starting from # / 4 item (here 8 / 4 == 2, starting from item #2)
Time to implement this algorithm
Code:
using System.Linq;
...
private static List<int> Pyramid(int size) {
if (size < 0)
throw new ArgumentOutOfRangeException(nameof(size));
if (size <= 3)
return Enumerable.Range(1, size).ToList();
List<int> result = new List<int>(size) { 1, 2, 3 };
for (int value = 4; result.Count < size; )
if (BitOperations.IsPow2(result.Count + 1)) {
int chunk = (result.Count + 1) / 4;
for (int i = 0; i < chunk && result.Count < size; ++i) {
result.Add(result[chunk - 1 + i]);
if (result.Count >= size)
return result;
result.Add(result[chunk - 1 + i]);
}
}
else
result.Add(value++);
return result;
}
Demo:
// First 31 items from the pyramid
Console.Write(string.Join("|", Pyramid(31)));
Output:
1|2|3|1|1|4|5|2|2|3|3|6|7|8|9|1|1|1|1|4|4|5|5|10|11|12|13|14|15|16|17
Write some code that accepts an integer and prints the integers from 0 to that input integer in a spiral format.
For example, if I supplied 24 the output would be:
20 21 22 23 24
19 6 7 8 9
18 5 0 1 10
17 4 3 2 11
16 15 14 13 12
this is the code which i have tried but i am not able to get expected output as per the example please suggest for the same.
this is the actual output
25 24 23 22 21
10 9 8 7 20
11 2 1 6 19
12 3 4 5 18
13 14 15 16 17
class Program
{
static void Main(string[] args)
{
int n = 5;
printSpiral(n);
}
static void printSpiral(int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
int x;
x = Math.Min(Math.Min(i, j),
Math.Min(n - 1 - i, n - 1 - j));
if (i <= j)
Console.Write((n - 2 * x) *
(n - 2 * x) -
(i - x) - (j - x) + "\t");
else
Console.Write((n - 2 * x - 2) *
(n - 2 * x - 2) +
(i - x) + (j - x) + "\t");
}
Console.WriteLine();
}
}
}
I want to print numbers on label from 1-to 100
The number's sum must be dividing on 4.
Example:
print 35. because 3+5 = 8 .
8 dividing on 4.
This is code
from loop printing numbers. but how choose those numbers?
print those numbers from 1 to 100 ;
for (int i = 1; i < 100; i++)
{
//select numbers wich sum is dividing on 4
label3.Text += Convert.ToString(i) + " | ";
}
Stolen from Greg Hewgill answer's, you can use his algorithm and use remainder operator (%) like;
int sum, temp;
for (int i = 1; i < 100; i++)
{
sum = 0;
temp = i;
while (temp != 0)
{
sum += temp % 10;
temp /= 10;
}
if (sum % 4 == 0)
{
Console.WriteLine(i);
}
}
Result will be;
4
8
13
17
22
26
31
35
39
40
44
48
53
57
62
66
71
75
79
80
84
88
93
97
Here a demonstration.
You should use a nested loop for that , and use the % operator (% means the rest of division):
for (int i = 1; i < 100; i++)
{
for (int j = i; j < 100; j++)
{
//select numbers wich sum is dividing on 4
if( (i+j)%4 == 0)
{
label3.Text += Convert.ToString(i) + Convert.ToString(j) " | ";
}
}
}
I am trying to find certain coordinates of interest within a very large virtual grid. This grid does not actually exist in memory since the dimensions are huge. For the sake of this question, let's assume those dimensions to be (Width x Height) = (Int32.MaxValue x Int32.MaxValue).
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Known data about grid:
Dimensions of the grid = (Int32.MaxValue x Int32.MaxValue).
Value at any given (x, y) coordinate = Product of X and Y = (x * y).
Given the above large set of finite numbers, I need to calculate a set of coordinates whose value (x * y) is a power of e. Let's say e is 2 in this case.
Since looping through the grid is not an option, I thought about looping through:
int n = 0;
long r = 0;
List<long> powers = new List<long>();
while (r < (Int32.MaxValue * Int32.MaxValue))
{
r = Math.Pow(e, n++);
powers.Add(r);
}
This gives us a unique set of powers. I now need to find out at what coordinates each power exists. Let's take 2^3=8. As shown in the grid above, 8 exists in 4 coordinates: (8,1), (4,2), (2,4) & (1, 8).
Clearly the problem here is finding multiple factors of the number 8 but this would become impractical for larger numbers. Is there another way to achieve this and am I missing something?
Using sets won't work since the factors don't exist in memory.
Is there a creative way to factor knowing that the number in question will always be a power of e?
The best method is to factor e into it prime components. Lets say they are as follows: {a^m, b^p, c^q}. Then you build set for each power of e, for example if m=2, p=1, q=3,
e^1 = {a, a, b, c, c, c}
e^2 = (a, a, a, a, b, b, c, c, c, c, c, c}
etc. up to e^K > Int32.MaxValue * Int32.MaxValue
then for each set you need to iterate over each unique subset of these sets to form one coordinate. The other coordinate is what remains. You will need one nested loop for each of the unique primes in e. For example:
Lets say for e^2
M=m*m;
P=p*p;
Q=q*q;
c1 = 1 ;
for (i=0 ; i<=M ; i++)
{
t1 = c1 ;
for (j=0 ; j<=P ; j++)
{
t2 = c1 ;
for (k=0 ; k<=Q ; k++)
{
// c1 holds first coordinate
c2 = e*e/c1 ;
// store c1, c2
c1 *= c ;
}
c1 = t2*b ;
}
c1 = t1*a ;
}
There should be (M+1)(P+1)(Q+1) unique coordinates.
Another solution, not as sophisticated as the idea from Commodore63, but therefore maybe a little bit simpler (no need to do a prime factorization and calculating all proper subsets):
const int MaxX = 50;
const int MaxY = 50;
const int b = 6;
var maxExponent = (int)Math.Log((long)MaxX * MaxY, b);
var result = new List<Tuple<int, int>>[maxExponent + 1];
for (var i = 0; i < result.Length; ++i)
result[i] = new List<Tuple<int, int>>();
// Add the trivial case
result[0].Add(Tuple.Create(1, 1));
// Add all (x,y) with x*y = b
for (var factor = 1; factor <= (int)Math.Sqrt(b); ++factor)
if (b % factor == 0)
result[1].Add(Tuple.Create(factor, b / factor));
// Now handle the rest, meaning x > b, y <= x, x != 1, y != 1
for (var x = b; x <= MaxX; ++x) {
if (x % b != 0)
continue;
// Get the max exponent for b in x and the remaining factor
int exp = 1;
int lastFactor = x / b;
while (lastFactor >= b && lastFactor % b == 0) {
++exp;
lastFactor = lastFactor / b;
}
if (lastFactor > 1) {
// Find 1 < y < b with x*y yielding a power of b
for (var y = 2; y < b; ++y)
if (lastFactor * y == b)
result[exp + 1].Add(Tuple.Create(x, y));
} else {
// lastFactor == 1 meaning that x is a power of b
// that means that y has to be a power of b (with y <= x)
for (var k = 1; k <= exp; ++k)
result[exp + k].Add(Tuple.Create(x, (int)Math.Pow(b, k)));
}
}
// Output the result
for (var i = 0; i < result.Length; ++i) {
Console.WriteLine("Exponent {0} - Power {1}:", i, Math.Pow(b, i));
foreach (var pair in result[i]) {
Console.WriteLine(" {0}", pair);
//if (pair.Item1 != pair.Item2)
// Console.WriteLine(" ({0}, {1})", pair.Item2, pair.Item1);
}
}
I am writing an algorithm to count the number of bars have passed since the n-th peak.
Assuming that I have a list of integer which keeps track of all the occurrences of peak as below.
3, 7, 10, 13
The above tells me that the peak occurs at the index 3, 7, 10 and 13.
The length of the source data is 15.
Let n = 1
then I should be seeing a resultant list as below:
index 0 = null - there is no peak yet
index 1 = null - there is no peak yet
index 2 = null - there is no peak yet
index 3 = 0 - peak was hit here so there bars passed is 0
index 4 = 1 - peak was hit in previous bar so the bars passed is 1
index 5 = 2 - peak was already hit and the number of bars passed is 2
index 6 = 3 - peak was already hit and the number of bars passed is 3
index 7 = 0 - peak hit here again so the number of bars passed since the last 1 (n) peak is 0 and result follows as below:
index 8 = 1,
index 9 = 2,
index 10 = 0,
index 11 = 1,
index 12 = 2,
index 13 = 0,
index 14 = 1
Assume n = 2
number of bars passed since 2 most recent peaks. So the result is as below:
index 0 = null
index 1 = null
index 2 = null
index 3 = null - first peak but n = 2 so there is no 2nd peak so far...
index 4 = null
index 5 = null
index 6 = null
index 7 = 4 - second peak only hit here, so the number of days passed since the last 2 peak is 4, this is counted from the index where the first peak was hit, in this case is 3
index 8 = 5
index 9 = 6
index 10 = 3 - another peak hit here, the peak before this (n = 2) happened at index = 7, so it is counted from index = 7
index 11 = 4
index 12 = 5
index 13 = 3 - another peak hit here, the peak before this (n = 2) happened at index = 10, so it is counted from index = 10
index 14 = 4
I wrote an algorithm to accomplish this however, it's not giving me the right output. I would appreciate if someone could tell me what's wrong with my algo or propose a better way doing this.
int nth = GetNValue();// Get the N Value...
//SourceData = listData
int peakCount = 0;
int value= 0;
int barssince = 0;
List<Data> listValue = new List<Data>();
List<int> listResult = new List<int); //to hold the result..
List<int> listPeaks = GetPeakValue();
for (int index = 0; index < listData.Count; index++)
{
if (peakcount > 0)
{
barssince++;
listValue[listValue.Count - 1].Value = barssince;
}
int foundPeak = listPeaks.Find(delegate(int p) { return p == index; });
if (foundPeak != -1)//Peak FOund
{
peakcount++;
listValue.Add(new Data() { Value = barssince });
if (peakcount > nth)
{
listValue.RemoveAt(0);
}
barssince = 0;
}
value = listValue.Count >= nth ? listValue.Sum(p => p.Value) : null;
listResult.Add(value);
}
private class Data
{
public int Value { get; set; }
}
Try this:
int n = GetNValue();// Get the N Value...
List<int> listPeaks = GetPeakValue();
List<int?> result = new List<int?>(listData.Count);
for (int index = 0, peakIndex = -1, nextPeakIndex = peakIndex + n; index < listData.Count; index++)
{
if (nextPeakIndex < listPeaks.Length && index == listPeaks[nextPeakIndex])
{
peakIndex++;
nextPeakIndex++;
}
if (peakIndex < 0)
{
result.Add((int?)null);
}
else
{
result.Add((int?)(index - listPeaks[peakIndex]));
}
}
Simple algo with working code (sorry, but in Delphi):
function IsPeak(i: Integer): Boolean;//modelling
begin
Result := i in [3, 7, 10, 13, 15];
end;
var
i, N: Integer;
Q: TQueue<Integer>;
begin
N := 2;
//queue for last N peaks
Q := TQueue<Integer>.Create;
for i := 0 to 20 do begin
//insert new peak in queue
if IsPeak(i) then begin
Q.Enqueue(i);
//remove too old peak
if Q.Count > N then
Q.Dequeue;
end;
if Q.Count < N then
Memo1.Lines.Add(Format('%d null',[i]))
else //return difference with front element of the queue
Memo1.Lines.Add(Format('%d %d',[i, i - Q.Peek]))
end;
Q.Free;
Result:
0 null
1 null
2 null
3 null
4 null
5 null
6 null
7 4
8 5
9 6
10 3
11 4
12 5
13 3
14 4
15 2
16 3
17 4
18 5
19 6
20 7