This question already has an answer here:
c# parallel foreach loop finding index
(1 answer)
Closed 4 years ago.
I can't seem to get my Actions to execute in parallel. They are executing in sequence.. Could somebody help me?
Action<Type_arg1,Type_arg2>[] actions = new Action<Type_arg1,Type_arg2>[count];
for (int i = 0; i < count; i++)
actions[i] = new Action<Type_arg1,Type_arg2>(carryOutAction);
int iter = 0;
Parallel.ForEach(actions, (thisaction) =>
{
thisaction(arg1,arg2,iter);
iter++;
});
The code you have posted is actually running in parallel (or at least unordered, which is a good hint, that it is in parallel.)
PS> scriptcs
scriptcs (ctrl-c to exit or :help for help)
> var count = 20;
>
> Action[] actions = new Action[count];
>
> for (int i = 0; i < count; i++)
* {
* var contextValue = i;
* actions[i] = new Action(()=>Console.WriteLine(contextValue));
* }
>
> Parallel.ForEach(actions, (thisaction) =>
* {
* thisaction();
* });
0
6
7
8
9
11
12
14
16
17
18
19
10
13
3
1
4
2
5
15
{
"IsCompleted": true,
"LowestBreakIteration": null
}
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
This question already has answers here:
Randomize a List<T>
(28 answers)
Closed 6 years ago.
i have some list with 5 numbers (exp. 1 2 3 4 5) i want to order them in random ordering each time (page refresh) examples: (2 4 3 1 5) (1 3 5 4 2) (5 1 2 3 4)... code in C#, Thanks
var loadcards = (from card in db.GameCards
select card).Take(5).ToList();
foreach (var item in loadcards)
{
Response.Write("<script>alert('" + item.cardId + "');</script>");
}
Something like this:
int[] RandomizeOrder(int[] input)
{
Random RNG = new Random();
bool[] cellMap = new bool[input.Length];
int[] output = new int[input.Length];
for(int i = 0; i < input.Length; i++)
{
int index = RNG.Next(input.Length)
while(cellMap[index)
index = RNG.Next(input.Length);
cellMap[index] = true;
output[index] = input[i];
}
return output;
}
PS: You can remove the cellMap if none of the values is 0
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);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
using System;
using System.IO;
namespace Sudoku
{
class Game
{
private int[,] puzzle = new int[9, 9];
public void saveToFile()
{
StreamWriter str = new StreamWriter("SUDOKU.txt");
for (int i = 0; i < 9; ++i)
{
for (int j = 0; j < 9; ++j)
{
str.Write(puzzle[i, j] + " ");
}
str.Write("\t\n");
}
str.Close();
}
public void readFromFile()
{
clear();
StreamReader str = new StreamReader("SUDOKU.txt");
for (int i = 0; i < 9; ++i)
{
for (int j = 0; j < 9; ++j)
{
puzzle[i, j] = Convert.ToInt32(str.Read());
}
}
str.Close();
}
}
}
I can not download the data from the file.
Saving works fine and has a view of the txt file:
1 2 3 4 5 6 7 8 9
4 5 6 7 8 9 1 2 3
7 8 9 1 2 3 4 5 6
2 1 4 3 6 5 8 9 7
3 6 5 8 9 7 2 1 4
8 9 7 2 1 4 3 6 5
5 3 1 6 4 2 9 7 8
6 4 2 9 7 8 5 3 1
9 7 8 5 3 1 6 4 2
How it all written in my array 9x9 skipping all the gaps that would be all the data is written correctly?
Instead of using str.Read() which would require you to read single characters (or a buffer that you specified), try using str.Readline() to read a single line for each iteration of i.
public void readFromFile()
{
StreamReader str = new StreamReader("SUDOKU.txt");
for (int i = 0; i < 9; ++i)
{
string[] lineNumbers = str.ReadLine().Split(' ');
for (int j = 0; j < 9; ++j)
{
puzzle[i, j] = Convert.ToInt32(lineNumbers[j]);
}
}
str.Close();
}
This reads a single line at a time (each iteration of i), splits the line into lineNumbers by separating the current line by space characters. Each number on the current line can then be accessed by lineNumbers[j] within your inner loop (each iteration of j).
Let say i have number 1 to 24, i want to get remainder of these from 12
so with mod 12 sequence would be 1 to 11 and additionally 0 (of 12 and 24) .
But i need this 0 to be always 12.
How to achieve such a thing in one liner(without additional variables or ifs).
Right now code is something like this:
for (int i = 1; i <= 24; i++)
{
Console.WriteLine(i % 12);
}
Oneline solution (with slight overhead though: i % 12 could be computed twice):
for (int i = 1; i <= 24; i++)
{
Console.WriteLine(i % 12 == 0 ? 12 : i % 12);
}
Pure arithmetic solution is
for (int i = 1; i <= 24; i++)
{
Console.WriteLine(12 - (12 - i % 12) % 12);
}
Another arithmetic options:
for (int i = 1; i <= 24; i++)
{
Console.WriteLine((i-1) % 12 + 1);
}
This simple makes sure the 'start' is moved one placed to the left (i-1) and corrects the outcome from 0 to 11 to 1 to 12 bij adding 1 to the result