Displaying data randomly in Data Grid View in Windows Application using C# - c#

I am working on a small assignment where I need to display data (0 to 99 - make sure all the numbers are displayed) randomly in a data grid view of 10 rows and 10 columns. I am unable to figure out the logic that needs to be written for this scenario. Currently I am doing like shown below, two for loops, one for row and other columns and iterating it...
int[] arr = new int[] { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 58, 69, 60, 61, 62, 63, 64 };
char c = Convert.ToChar(arr.GetValue(new Random().Next(0, 21)));
for (int row = 0; row < 10; row++)
{
for (int col = 0; col < 10; col++)
{
if ((row + col) == 9)
{
this.dataGridView1.Rows[row].Cells[col].Value = string.Format("{0} {1}", c, ((row + 1) * 9));
}
else
{
this.dataGridView1.Rows[row].Cells[col].Value = string.Format("{0} {1}", Convert.ToChar(arr.GetValue(new Random().Next(0, 21))), row * 10 + (col));
System.Threading.Thread.Sleep(15);
}
}
}
Out put:
Expected:
Code for randomly distributing the numbers from 0 to 99.
Thanks in Advance.

By small assignment do you mean school assignment? If so, I don't want to write everything for you, but to point you in the right direction:
The first step I would take initializing an array with a size of 100, and placing the numbers 0-99 on the array. Then, I would find a method for shuffling the array (Linq's OrderBy used with the Random class may be useful to you here). Then, I would iterate through the shuffled array, and place those items inside the grid. I think you have the general grid looping idea down, with the embedded for loops... I'm not sure what the point of the Thread Sleep is, though.

Check with this if you ain't done with your coding...
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
for (int i = 0; i < 10; i++)
dt.Columns.Add("col" + i.ToString(), typeof(int));
Random r = new Random();
List<int> l = new List<int>(100);
int temp=0;
for (int i = 9; i >= 0; i--)
{
DataRow dr = dt.NewRow();
for (int j = 0; j < 10; j++)
{
temp = r.Next(99);
if (!l.Contains(temp) || (j == 0 && i == 0))
{
dr["col" + j.ToString()] = temp;
l.Add(temp);
}
else
j -= 1;
}
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}

This is what I was finally able to do it. It worked!!!
public static class ThreadSafeRandom
{
[ThreadStatic]
private static Random Local;
public static Random ThisThreadsRandom
{
get { return Local ?? (Local = new Random(unchecked(Environment.TickCount * 31 + Thread.CurrentThread.ManagedThreadId))); }
}
}
static class MyExtensions
{
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = ThreadSafeRandom.ThisThreadsRandom.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
The above code does the shuffling of numbers.
var numbers = new List<int>(Enumerable.Range(0, 100));
numbers.Shuffle();
List<int> final = numbers.GetRange(0, 100);
int[,] f = new int[10, 10];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
f[i, j] = final[(i * 10) + j];
}
}
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (f[i, j] % 9 == 0)
{
this.dataGridView1.Rows[i].Cells[j].Value = string.Format("{0} {1}", charSymbol, f[i, j]);
}
else
{
this.dataGridView1.Rows[i].Cells[j].Value = string.Format("{0} {1}", GetRandomChar(), f[i, j]);
}
}
}

Related

Digit difference sort

So I am trying to solve this task "Digit Difference Sort" on Codefights
Given an array of integers, sort its elements by the difference of their largest and smallest digits.
In the case of a tie, that with the larger index in the array should come first.
Example
For a = [152, 23, 7, 887, 243], the output should be digitDifferenceSort(a) = [7, 887, 23, 243, 152].
Here are the differences of all the numbers:
152: difference = 5 - 1 = 4;
23: difference = 3 - 2 = 1;
7: difference = 7 - 7 = 0;
887: difference = 8 - 7 = 1;
243: difference = 4 - 2 = 2.
23 and 887 have the same difference, but 887 goes after 23 in a, so in the sorted array it comes first.
I have an issue with two numbers having the same difference. Here's what I wrote so far:
int[] digitDifferenceSort(int[] a) {
return a.OrderBy(x => difference(x)).ToArray();
}
int difference(int x)
{
int min = 9, max = 0;
do
{
int tmp = x % 10;
min = Math.Min(min, tmp);
max = Math.Max(max, tmp);
} while ((x /= 10) > 0);
return max - min;
}
Didn't do much (for example the output is still [7, 23, 887, 243, 152] rather than [7, 887, 23, 243, 152])
How do I make element with larger index come first in result? What should I use instead of OrderBy?
I don't consider your difference method, i assume it works fine.
To your question: you have to keep revered order of the array (that the items with the same difference arrive will be sorted reverse). To do it, you could just reverse you input array: all items with not identical difference will be ordered correctly, and with the same differece will be ordered reversed:
int[] digitDifferenceSort(int[] a)
{
return a.Reverse().OrderBy(x => difference(x)).ToArray();
}
Following is my code for the above question digit difference sort. I am also getting output when running in Eclipse but when I paste the code on code signal it gives me a null pointer exception.
package NormalPrograms;
import java.util.ArrayList;
import java.util.Collections;
public class DigitDifferenceSort {
// For index wise sorting in descending order
public static int[] sortingnumberindexwise(int[] a, ArrayList<Integer> index) {
int k = 0;
int[] res = new int[index.size()];
int[] finalres = new int[index.size()];
for (int i = a.length - 1; i >= 0; i--) {
for (int j = 0; j < index.size(); j++) {
if (a[i] == (int) index.get(j)) {
res[k] = i;
index.remove(j);
k++;
break;
}
}
}
int g = 0;
k = 0;
for (int i = 0; i < res.length; i++) {
finalres[g] = a[res[k]];
g++;
k++;
}
return finalres;
}
public static int[] finddigitDifferenceandSort(int[] p) {
int[] finres = new int[p.length];
for (int i = 0; i < finres.length; i++) {
finres[i] = p[i];
}
// This finres array act as an temp array and reused to make final result array
int digit = 0;
ArrayList<Integer> A = new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> B = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < 10; i++) {
B.add(new ArrayList<Integer>());
}
for (int i = 0; i < p.length; i++) {
int temp = 0;
temp = p[i];
while (p[i] > 0) {
digit = p[i] % 10;
p[i] /= 10;
A.add(digit);
}
int b = Collections.max(A);
int c = Collections.min(A);
int diff = b - c;
B.get(diff).add(temp);
A.clear();
}
for (int i = 0; i < B.size(); i++) {
if (B.get(i).size() > 1) {
ArrayList<Integer> C = new ArrayList<Integer>();
for (int k = 0; k < B.get(i).size(); k++) {
C.add(B.get(i).get(k));
}
B.get(i).clear();
for (int j : sortingnumberindexwise(finres, C)) {
B.get(i).add(j);
}
} else {
continue;
}
}
int k = 0;
for (int i = 0; i < B.size(); i++) {
for (int j = 0; j < B.get(i).size(); j++) {
if (B.get(i).size() == 0)
continue;
else {
finres[k] = B.get(i).get(j);
k++;
}
}
}
return finres;
}
public static void main(String[] args) {
int[] a = { 12, 21, 1, 1, 1, 2, 2, 3 };
for (int i : finddigitDifferenceandSort(a)) {
System.out.print(i + " ");
}
}
}

c# using for loop to write out an array

I need to write out my array using a for-loop. This is my code. The reason I have to do it with a for-loop is because it is for a school project and the teacher does not accept anything else. What the code is doing right now is that first it creates an array with random numbers and make sure there are no duplicates then it makes sure it is sorted with bigger numbers first.
int[] myArray = new int[20];
Random random = new Random();
bool isUnique;
for (int i = 0; i < myArray.Length; i++) {
isUnique = false;
while (!isUnique) {
isUnique = true;
myArray[i] = random.Next(1, 100);
for (int j = 0; j < i; j++) {
if (myArray[i] == myArray[j]) {
isUnique = false;
}
}
}
}
bool isSorted;
int change;
for (int i = 0; i < myArray.Length; i++) {
isSorted = false;
while (!isSorted) {
isSorted = true;
for (int j = i + 1; j < myArray.Length; j++) {
if (myArray[i] < myArray[j]) {
change = myArray[j];
myArray[j] = myArray[i];
myArray[i] = change;
isSorted = false;
}
}
}
}
Works for me.
for (var i = 0; i < myArray.Length; i++)
{
Console.WriteLine(myArray[i]);
}
Prints your array, it's sorted fine and prints biggest to smallest.
What isn't working?
I rewrote your code to less verbose variant:
int[] myArray = new int[20];
Random random = new Random();
int randomValue = 0;
// Fill array
for (int i = 0; i < myArray.Length; i++)
{
do randomValue = random.Next(1, 100);
while (myArray.Contains(randomValue));
myArray[i] = randomValue;
}
// Sort array
myArray = myArray.OrderByDescending(x => x).ToArray();
For write array to console you should use cycle:
for (var i = 0; i < myArray.Length; i++)
Console.WriteLine(myArray[i] + " ");
But for best and less verbose result you should use this:
Console.WriteLine(string.Join(", ", myArray));
It's return this:
97, 95, 93, 92, 91, 85, 84, 78, 77, 76, 75, 68, 57, 45, 24, 22, 14, 10, 8, 4

Rechange array so it could be sorted in C#

I have been given this task to solve:
Write a program that reads an array of integers and removes from it a minimal number of elements in such a way that the remaining array is sorted in increasing order. Print the minimal number of elements that need to be removed in order for the array to become sorted.
Time limit 0.1sec.
Sample test:
Input:
1,
4,
3,
3,
6,
3,
2,
3
Output:
3
Unfortunately, my program is slower. This is my code:
using System;
static bool CheckAscending(List<int> list)
{
bool ascending = true;
for (int i = 0; i < list.Count - 1; i++)
{
if (list[i] > list[i + 1])
{
ascending = false;
}
}
return ascending;
}
static void Main()
{
int n;
n = int.Parse(Console.ReadLine());
List<int> arr = new List<int>();
List<int> sorted = new List<int>();
int maxSubsetLenght = 0;
for (int i = 0; i < n; i++)
{
arr.Add(int.Parse(Console.ReadLine()));
}
for (int i = 1; i <= (int)Math.Pow(2, n) - 1; i++)
{
int tempSubsetLenght = 0;
List<int> temp = new List<int>();
for (int j = 1; j <= n; j++)
{
if (((i >> (j - 1)) & 1) == 1)
{
temp.Add(arr[j - 1]);
tempSubsetLenght++;
}
}
if ((tempSubsetLenght > maxSubsetLenght) && (CheckAscending(temp)))
{
sorted = temp;
maxSubsetLenght = tempSubsetLenght;
}
}
Console.WriteLine(n - sorted.Count);
}
Can someone help me to make my program a bit faster. I will be glad if you could answer in the near future.
Ok I found how to soleve it and thanks #Gabor for your help :). Here is my solution:
using System;
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
List<int> numbers = new List<int>();
for (int i = 0; i < n; i++)
{
int currentNumber = int.Parse(Console.ReadLine());
numbers.Add(currentNumber);
}
int[] size = new int[numbers.Count];
// Define each number as subsequence.
for (int i = 0; i < numbers.Count; i++)
{
size[i] = 1;
}
int max = 1;
// Compare current number with the numbers before.
for (int i = 1; i < numbers.Count; i++)
{
for (int j = 0; j < i; j++)
{
if (numbers[i] >= numbers[j] && size[i] <= size[j] + 1)
{
size[i] = size[j] + 1;
// Update max increasing subsequence.
if (max < size[i])
{
max = size[i];
}
}
}
}
// Print numbers to remove as a result.
int numbersToRemove = n - max;
Console.WriteLine(numbersToRemove);
}
I think it would be helpful for other people, who have the same task to do like me.
UPDATE #2
When there is a decrease then we should delete not only the current number but all the numbers before which are more than the new minValue.
The Stopwatch is in the System.Diagnostic namespace.
// int?[] numbers = new int?[] { 8, 1, 4, 3, 3, 6, 3, 2, 3 };
int?[] numbers = new int?[] { -7, -7, -7, -100, -100, -99, 4, -90, -80, -70 };
Console.WriteLine("Array: [{0}]", String.Join(", ", numbers));
System.Diagnostics.Stopwatch watch = new Stopwatch();
watch.Start();
int minValue = Int32.MinValue;
for (int i = 0; i < numbers.Length - 1; i++)
{
var currentNumber = numbers[i];
var nextNumber = numbers[i + 1];
if (currentNumber > nextNumber)
{
if (nextNumber < minValue)
{
numbers[i + 1] = null;
}
else
{
minValue = nextNumber.Value;
for (int j = i; j >= 0; j--)
{
if (numbers[j] > minValue)
{
numbers[j] = null;
}
}
}
}
}
watch.Stop();
Console.WriteLine("Result: {0}; Time: {1} ms", numbers.Count(number => number == null), watch.ElapsedMilliseconds);
Console.WriteLine("Array: [{0}]", String.Join(", ", numbers));

Longest subsequence in array

I am trying to solve my task using a List and I know I am very close to solving it but I am stuck now. Something is not ok in the code and I can not figure out what it is. Could you please take a look and help:
/*
Write a program that reads an array of integers and removes from it a minimal number of elements in such way that the
remaining array is sorted in increasing order. Print the remaining sorted array.
Example: {6, 1, 4, 3, 0, 3, 6, 4, 5}  {1, 3, 3, 4, 5}
*/
using System;
using System.Collections.Generic;
class RemoveMinimalElements
{
static void Main()
{
int n;
n = int.Parse(Console.ReadLine());
List<int> arr = new List<int>();
List<int> sorted = new List<int>();
int maxSubsetLenght = 0;
for (int i = 0; i < n; i++)
{
arr.Add(int.Parse(Console.ReadLine()));
}
for (int i = 1; i <= (int)Math.Pow(2, n) - 1; i++)
{
int tempSubsetLenght = 0;
string tempString = "";
List<int> temp = new List<int>();
for (int j = 1; j <= n; j++)
{
int andMask = i & (1 << j);
int bit = andMask >> j;
if (bit == 1)
{
temp.Add(arr[n - 1 - j]);
tempSubsetLenght++;
}
if (tempSubsetLenght > maxSubsetLenght)
{
maxSubsetLenght = tempSubsetLenght;
for(int k =1; k < temp.Count; k ++)
{
if (temp[k] >= temp[k - 1])
{
sorted = temp;
}
}
}
}
}
for (int i = sorted.Count - 1; i > 0; i--)
{
Console.WriteLine(sorted[i]);
}
}
}
I didn't follow the code, I just tested your app.
This is my first input: 5.
Then I entered these 5 inputs 2,4,6,8,10 so
arr = {2,4,6,8,10};
And when it came to the last lines it gave me the ArguementOutOfRangeException (Index was out of range. Must be non-negative and less than the size of the collection.) because it was trying to fetch arr[item] and item is 6 so it's trying to fetch arr[6] which does not exist.
I don't know if an exhaustive search is suitable for your case, but will this work for you?
static void Main(string[] args)
{
int[] input = new[] { 6, 1, 4, 3, 0, 3, 6, 4, 5 };
int[] expectedOutput = new[] { 1, 3, 3, 4, 5 };
int[] solution = TryGetSolution(input);
Console.WriteLine("Input: " + FormatNumbers(input));
Console.WriteLine("Expected Output: " + FormatNumbers(expectedOutput));
Console.WriteLine("Output: " + FormatNumbers(solution));
Console.ReadLine();
}
private static string FormatNumbers(int[] numbers)
{
return string.Join(", ", numbers);
}
private static int[] TryGetSolution(int[] input)
{
return TryWithoutAnyItem(input);
}
private static int[] TryWithoutAnyItem(int[] items)
{
return Enumerable.Range(0, items.Length)
.Select(i => TryWithoutItem(items, i))
.Where(solution => solution != null)
.OrderByDescending(solution => solution.Length)
.FirstOrDefault();
}
private static int[] TryWithoutItem(int[] items, int withoutIndex)
{
if (IsSorted(items)) return items;
var removed = items.Take(withoutIndex).Concat(items.Skip(withoutIndex + 1));
return TryWithoutAnyItem(removed.ToArray());
}
private static bool IsSorted(IEnumerable<int> items)
{
return items.Zip(items.Skip(1), (a, b) => a.CompareTo(b)).All(c => c <= 0);
}
}
I solved it! Thank you very much for your support. I am a beginer and I am not able to use and understand more difficult stuff yet so here is what I did whit the things I already know:
/*
Write a program that reads an array of integers and removes from it a minimal number of elements in such way that the
remaining array is sorted in increasing order. Print the remaining sorted array.
Example: {6, 1, 4, 3, 0, 3, 6, 4, 5}  {1, 3, 3, 4, 5}
*/
using System;
using System.Collections.Generic;
class RemoveMinimalElements
{
static bool CheckAscending(List<int> list)
{
bool ascending = true;
for (int i = 0; i < list.Count - 1; i++)
{
if (list[i] > list[i + 1])
{
ascending = false;
}
}
return ascending;
}
static void Main()
{
int n;
n = int.Parse(Console.ReadLine());
List<int> arr = new List<int>();
List<int> sorted = new List<int>();
int maxSubsetLenght = 0;
for (int i = 0; i < n; i++)
{
arr.Add(int.Parse(Console.ReadLine()));
}
for (int i = 1; i <= (int)Math.Pow(2, n) - 1; i++)
{
int tempSubsetLenght = 0;
List<int> temp = new List<int>();
for (int j = 1; j <= n; j++)
{
if (((i >> (j - 1)) & 1) == 1)
{
temp.Add(arr[j - 1]);
tempSubsetLenght++;
}
}
if ((tempSubsetLenght > maxSubsetLenght) && (CheckAscending(temp)))
{
sorted = temp;
maxSubsetLenght = tempSubsetLenght;
}
}
for (int i = 0; i < sorted.Count; i++)
{
Console.WriteLine(sorted[i]);
}
}
}
This works for me
private static void FindLongestRisingSequence(int[] inputArray)
{
int[] array = inputArray;
List<int> list = new List<int>();
List<int> longestList = new List<int>();
int highestCount = 1;
for (int i = 0; i < array.Length; i++)
{
list.Add(array[i]);
for (int j = i+1; j < array.Length; j++)
{
if (array[i] < array[j])
{
list.Add(array[j]);
i++;
}
else
{
break;
}
i = j;
}
// Compare with in previous lists
if (highestCount < list.Count)
{
highestCount = list.Count;
longestList = new List<int>(list);
}
list.Clear();
}
Console.WriteLine();
// Print list
Console.WriteLine("The longest subsequence");
foreach (int iterator in longestList)
{
Console.Write(iterator + " ");
}
Console.WriteLine();
}

Help needed in finding coordinate count

I have an 8 X 8 matrix. Now, The below coordinates are occupied
{ 6, 3 }, { 5, 5 }, { 3, 3 }.... What needs to be done is that, I need to build straight line
through these points and needs to count how many coordinates they have touched?
My program so far stands as
private static void GetCount(int[,] Positions)
{
int rcount = 8;
int firstRow = Positions[0, 0];
for (int i = 1; i < Positions.Length/2; i++)
{
int currentRow = Positions[i, 0];
if (currentRow != firstRow)
{
rcount += 8;
firstRow = currentRow;
}
}
int cCount = 8;
int firstCol = Positions[0, 1];
for (int i = 1; i < Positions.Length / 2; i++)
{
int currentCol = Positions[i, 1];
if (currentCol != firstCol)
{
cCount += 8;
firstCol = currentCol;
}
}
int totalCount = rcount - cCount;
Console.WriteLine(totalCount);
}
And I am invoking it as
GetCount(new int[,] { { 6, 3 }, { 5, 5 }, { 3, 3 } });
The output will be 40 here. (count will be 24 for each 3 unique rows i.e. 6,5,3 and count will be 16 for 2 unique columns i.e. 3 and 5... So, the total count is 24+16 = 40)
But I am getting the output as 48.
Also is it possible to do the porgram using one single loop?
I am using C# 1.0
Edited
This does work
List<int> lstRows = new List<int>();
List<int> lstCols = new List<int>();
int count = 0;
//Get the unique rows and columns
for (int i = 0; i < marinePositions.Length / 2; i++)
{
if (!lstRows.Contains(marinePositions[i, 0])) lstRows.Add(Positions[i, 0]);
if (!lstCols.Contains(marinePositions[i, 1])) lstCols.Add(Positions[i, 1]);
}
//get row count
for (int i = 0; i < lstRows.Count; i++) count += 8;
//get column count
for (int i = 0; i < lstCols.Count; i++) count += 8;
Console.WriteLine(count);
But need a much better one.. if possible using linq/lambda and no loop
Please help
Here u go... but this in is LINQ and not C# 1.0 which is way too old.. not sure why are you using such old version of the language:
private static void GetCount(int[,] Positions)
{
List<int> x = new List<int>();
List<int> y = new List<int>();
for (int i = 0; i < Positions.Length/2; i++)
{
x.Add(Positions[i, 0]);
y.Add(Positions[i, 1]);
}
int result = (x.Distinct().Count() * 8) + (y.Distinct().Count() * 8);
Console.WriteLine(result);
}
No loops magic:
private static void GetCount(int[,] Positions)
{
var range = Enumerable.Range(0, Positions.Length / 2);
var result = (range.Select(i => Positions[i, 0]).Distinct().Count() * 8) +
(range.Select(i => Positions[i, 1]).Distinct().Count() * 8);
Console.WriteLine(result);
}
CORRECTIONS:
1-
int cCount = 8;
To:
int cCount = 0;
2-
int totalCount = rcount - cCount;
To:
int totalCount = rcount + cCount;
The program should work fine now.

Categories

Resources