Issue reading user Input - c#

static void Main(string[] args)
{
var numTestCases = int.Parse(Console.ReadLine());
for (int l=0;l<numTestCases;l++)
{
var numMember = int.Parse(Console.ReadLine());
var ele = Console.ReadLine();
var gteammember = ele.Trim().Split(' ').ToList();
var oppTeamMember = Console.ReadLine().Trim().Split(' ').ToList();
Dictionary<int, long> dict = new Dictionary<int, long>();
int Count = 0;
for (int k = 0; k < oppTeamMember.Count; k++)
{
for (int j = 0; j < gteammember.Count; j++)
{
var newoppTeamMember = Convert.ToInt64(oppTeamMember[k]);
var newgteammember = Convert.ToInt64(gteammember[j]);
if (newoppTeamMember < newgteammember)
{
dict.Add(j, newgteammember);
}
}
if (dict.Count > 0)
{
var keyR = dict.OrderBy(kvp => kvp.Value).First();
Count++;
gteammember.RemoveAt(keyR.Key);
dict.Clear();
}
}
Console.WriteLine(Count);
}
}
I have a user input like
but it reads only half the number from 72 number user inputs. can someone please tell me the issue or any other way to solve this issue. I have checked the above code it works fine for small input eg 10,20 etc

Related

Loop of creation via a user input, WPF C#

The system needs a way of taking input from txtBox.
I then need the system to take the number input, 1-10. And repeat the ticket and file creation for that x amount of times.
This code also creates a file on the pc with the Lottery ticket in it.
the files have to be named LottoKupon1, LottoKupon2 and so on, this needs to match user input of course.
this is for creation of file and folder
namespace Lottery
{
internal class FolderCreater
{
static string folderName = #"C:\lotto";
public static string fileName = #"C:\lotto\LottoKupon.txt";
public static void CreateFolder()
{
if (!Directory.Exists(folderName))
{
Directory.CreateDirectory(folderName);
}
else if (!File.Exists(fileName))
{
File.Create(fileName);
}
else { }
}
}
}
This is for creation of Lottry Ticket
namespace Lottery
{
// the system needs a way of taking input
// from txtBox, int user = int.Parse(txtBox.Text.Trim()); which this line does
// i then need the system to take the number input, 1-10.
// and repeat the ticket and file creation for that x amount of times.
public partial class MainWindow : Window
{
public List<long> ListOfAllArrays = new List<long>();
int i = 1;
Random randNum = new Random();
public MainWindow()
{
InitializeComponent();
}
public void Lotto ()
{
StreamWriter sw = new StreamWriter(FolderCreater.fileName);
sw.WriteLine(" " + "Lotto " + DateTime.Now.ToString("dd/MM/yyyy\n"));
sw.WriteLine(" " + "1-uge\n" + " LYN-LOTTO\n");
Random randNum = new Random();
int[][] AllArrays = new int[10][];
for (int i = 0; i < 10; i++)
{
AllArrays[i] = new int[7];
}
int RowNr = 0;
foreach (int[] row in AllArrays)
{
RowNr++;
sw.Write(RowNr + ". ");
for (int j = 0; j < 7; j++)
{
int number = randNum.Next(1, 37);
while (row.Any(n => n == number))
{
number = randNum.Next(1, 37);
}
row[j] = number;
}
Array.Sort(row);
for(int l = 0; l < 7; l++)
{
sw.Write(row[l].ToString("00") + " ");
}
sw.Write("\n");
}
TestIfSame(AllArrays);
if (CheckBox.IsChecked == true)
{
sw.WriteLine("\n****** Joker Tal ******");
int[][] AllJokerRows = new int[2][];
for (int i = 0; i < 2; i++)
{
AllJokerRows[i] = new int[7];
}
foreach (int[] n in AllJokerRows)
{
sw.Write(" ");
for (int i = 0; i < 7; i++)
{
var JokerNumber = randNum.Next(1, 10);
n[i] = JokerNumber;
}
Array.Sort(n);
for (int u = 0; u < 7; u++)
{
sw.Write(n[u] + " ");
}
sw.Write("\n");
}
}
sw.Close();
}
public void TestIfSame(int[][] AllArrays)
{
//List<long> ListOfAllArrays = new List<long>();
for (int i = 0; i < AllArrays.Length; i++)
{
ListOfAllArrays.Add(MakesLongNumber(AllArrays[i]));
}
for (int i = 0; i < AllArrays.Length; i++)
{
long temp = ListOfAllArrays[0];
ListOfAllArrays.Remove(ListOfAllArrays[0]);
if (ListOfAllArrays.Contains(MakesLongNumber(AllArrays[i])))
{
Lotto();
}
else
{
ListOfAllArrays.Add(temp);
}
}
long MakesLongNumber(int[] row)
{
string a = "";
for (int i = 0; i < row.Length; i++)
{
a += row[i].ToString();
}
return Convert.ToInt64(a);
}
}
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
}
private void cmdOk_Click_1(object sender, RoutedEventArgs e)
{
FolderCreater.CreateFolder();
Lotto();
// add a ListBox.Items.Add(); within this needs to be the command for the Lottery ticket, so i can have it shown on a list box.
}
**This is for a Lottery assignment, its on a lower level of coding, so no answer that is way too complicated, hope you understand. please ask questions if needed.
I tried a dew things with a for loop around the first void which took user input, but i could not make it work.
the code is expected to create files and Lottery ticket depending on users input**

Arrange strings in alphabetical order

//code with problem (maybe)
numberArray = NameNumEquv;
listStringArray = NamesArray;
string[] sortedArray = new string[NamesArray.Length];
for (int arrayItemCounter = 0; arrayItemCounter < NamesArray.Length; arrayItemCounter++)
{
compareArrayCount = 1;
initialArrayCount = 0;
while (compareArrayCount < numberArray.Length)
{
for (int doubleArrayLength = 0; doubleArrayLength < numberArray[compareArrayCount].Length; doubleArrayLength++)
{
if (numberArray[initialArrayCount][doubleArrayLength] < numberArray[compareArrayCount][doubleArrayLength])
{
initialArrayCount = compareArrayCount;
break;
}
}
compareArrayCount = compareArrayCount + 1;
}
sortedArray[arrayItemCounter] = listStringArray[initialArrayCount];
List<string> tempArrayValues = new List<string>();
List<int[]> tempNumArrayValues = new List<int[]>();
for (int tempArrayCount = 0; tempArrayCount < listStringArray.Length; tempArrayCount++)
{
if (tempArrayCount != initialArrayCount)
{
tempArrayValues.Add(listStringArray[tempArrayCount]);
tempNumArrayValues.Add(numberArray[tempArrayCount]);
}
}
listStringArray = tempArrayValues.ToArray();
numberArray = tempNumArrayValues.ToArray();
tempArrayValues.Clear();
tempNumArrayValues.Clear();
}
//till here
foreach (string nums in sortedArray)
{
Console.WriteLine(nums);
}
}
public static int[] AlphaNumericConversion(string stringValue, int arrayLength)
{
string Alphabets = "abcdefghijklmnopqrstuvwxyz";
char[] alphabetArray = Alphabets.ToCharArray();
string lowerCaseConv = stringValue.ToLower();
char[] stringArray = lowerCaseConv.ToCharArray();
int[] numericalConvertedArray = new int[arrayLength];
for (int valueArrayCount = 0; valueArrayCount < numericalConvertedArray.Length; valueArrayCount++)
{
numericalConvertedArray[valueArrayCount] = 0;
}
for (int letterCounter= 0;letterCounter < stringArray.Length;letterCounter++)
{
for (int alphabetCounter = 0; alphabetCounter < Alphabets.Length; alphabetCounter++)
{
if (stringArray[letterCounter] == alphabetArray[alphabetCounter])
numericalConvertedArray[letterCounter] = alphabetCounter + 1;
}
}
return numericalConvertedArray;
}
}
}
I want to arrange strings in ascending order. It is arranging the single letter strings(a, b, c,d, e.....) in reverse alphabetical order as in Z-A and string containing 2 or more letters randomly such as "Aayush", "Ayush", "Aayusha", "Ayusha" to "Aayusha","Ayusha","Aayush","Ayush". What is wrong with the code. Don't suggest to simply use List.Sort() because I want to write it in algorithmic manner. I'm trying to understand how it works rather than using Sort().

C# Sort 2D array based on key array

I'm trying to sort 2D array of chars based on 1D array as key. I need to find a char that wasn't used in key so far and then sort it based on it.
Fe:
AEITY
EDNTB
to
TEAIY
TDENB
based on key:
TEAIY
on row 0
My code struggle with an multiple chars and provide bad results:
Fe:
AAABN
TEAIY
TDENB
to
ABANA
TIEYA
TNDBE
but instead of that i get
ABANA
AIEYT
ENDBT
based on key:
ABANA
Code i figure out:
static char[][] SortSimiliarity(char[][] arr, char [] key, int arrRow)
{
Dictionary<char, int> dcKeyList = new Dictionary<char, int>();
for (var i = 0; i < key.Length; i++)
{
var counterCurrentKey = 0;
for (var j = 0; j < key.Length; j++)
{
if(key[i] == arr[arrRow][j])
{
//Console.WriteLine("{0} == {1}", key[i], arr[arrRow][j]);
if (!dcKeyList.ContainsKey(key[i]))
{
for (var k = 0; k < key.Length; k++)
{
//Console.WriteLine("x");
var temp = arr[k][j];
arr[k][j] = arr[k][i];
arr[k][i] = temp;
}
dcKeyList.Add(key[i], 1);
}
else
{
if (dcKeyList[key[i]] == counterCurrentKey)
{
Console.WriteLine("key is {0}", dcKeyList[key[i]]);
for (var k = 0; k < key.Length; k++)
{
//Console.WriteLine("x");
var temp = arr[k][j];
arr[k][j] = arr[k][i];
arr[k][i] = temp;
}
dcKeyList[key[i]]++;
}
counterCurrentKey++;
}
}
}
}
return arr;
}
I know there is something wrong with that ELSE statement, where i compare current count of char in key loop.
Thank you for your ideas.
My problem was simple. I tried to sort 2d array based on array key which i does, but i also save same result into same 2d array, without keeping tracks on changes. That can be solved with pointer logic or with new array where you copy only your sorted results without changing the base 2D array.
static char[][] SortSimiliarity(char[][] arr, char[] key, int arrRow)
{
// init dict
Dictionary<char, int> dict = new Dictionary<char, int>();
// init new matrix
char[][] tempArray = new char[5][];
for(var i = 0; i < 5; i++)
{
tempArray[i] = new char[5];
}
// copy new sorted keys
for (var i = 0; i < key.Length; i++)
{
for (var j = 0; j < key.Length; j++)
{
if (key[i] == arr[arrRow][j])
{
if (!dict.ContainsKey(key[i]))
{
dict.Add(key[i], j);
for(var k = 0; k < key.Length; k++)
{
tempArray[k][i] = arr[k][j];
}
break;
}
else
{
if(j != dict[key[i]])
{
for (var k = 0; k < key.Length; k++)
{
tempArray[k][i] = arr[k][j];
}
dict[key[i]] = j+1;
}
}
}
}
}
return tempArray;
}

Replacing all the empty elements in an array with a String value

I have an array which can hold 10 elements:
string[] Ar = new string[10];
But it has only 5 items added to it. I need to insert The string value "NULL" to the rest of the empty slots in the array and thus making the array 'full' with string elements (that, being my objective).
This is what I've attempted as of now:
int entityCount = 5;
if (entityCount < 10)
{
for (int i = entityCount; i < 10; i++)
{
Ar[i] = "NULL";
}
}
And thus, when printed should output the values:
A, B, C, D, E, NULL, NULL, NULL, NULL, NULL
But this does not seem to do the trick, Still prints out ONLY the 5 items and not the 5 new strings.
I am not from C# background but I think this is what you want:
string[] Ar = new string[10];
for (int i = 0; i < 10; i++)
{
if(String.IsNullOrEmpty(Ar[i]))
{
Ar[i]="NULL";
}
}
for (int i = 0; i < 10; i++)
{
Console.WriteLine(Ar[i]);
}
You can read about String.IsNullOrEmpty(Ar[i]) here.
static void Main(string[] args)
{
int arraySize = 10;
string[] Ar = new string[arraySize];
Ar[0] = "A";
Ar[1] = "B";
Ar[2] = "C";
Ar[3] = "D";
for (int i = 0; i < arraySize; i++)
{
if (Ar[i]==null)
{
Ar[i] = "NULL";
}
}
for (int i = 0; i < Ar.Length; i++)
{
Console.Write(Ar[i]+" ");
}
}
}
this works fine.
int entityCount = 5;
string[] Ar = new string[10];
Ar[0] = "A";
Ar[1] = "B";
Ar[2] = "C";
Ar[3] = "D";
Ar[4] = "E";
if(entityCount < 10) {
for(int i = entityCount; i < 10; i++) {
Ar[i] = "NULL";
}
}
foreach(string s in Ar) {
Console.WriteLine(s);
}
using System;
using System.Linq;
class Program
{
private static void Main(string[] args)
{
string[] Ar = new string[10];
var item = from f in Ar
select string.IsNullOrWhiteSpace(f) ? "NULL" : f;
foreach (var i in item)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
Here item is iterator in string of array replace all with null if not contains value
string multiplayer = new string[5];
foreach (var item in multiplayers)
{
if (item == null) { Console.WriteLine("Empty"); }
Console.WriteLine(item);
}
remember string of array is not nullable here

Sorting many TValue arrays with one TKey array

I have an outer array of N inner arrays of size M. I want to sort each inner array according to another array K exactly in the same way as a built-in Array.Sort<TKey, TValue> Method (TKey[], TValue[], IComparer<TKey>) .NET method does.
The method modifies the Key array after sorting, so I can use it to sort only single inner array. To sort many arrays, I copy the Key array to another KeyBuffer array for each inner array, reusing the KeyBuffer on each sorting step and avoiding allocation and GC. Is that the most efficient way if the typical N is 10K-100K and M < 1000? Given the low size of M the copying and sorting should be done in CPU cache, - which is the fastest that I can get?
My concern is that by doing so, I am sorting the buffer and discarding the results (N-1) times, which is a kind of waste. Also I am doing actual sorting N times, but after the first sorting I already know a map of old indexes to new indexes and I could somehow reuse that mapping for other (N-1) steps.
How would you avoid unnecessary sorting and apply known mapping from the first step to other steps?
Here is the code how I do it now. The question is if it is possible to do it more efficiently.
using System;
using System.Collections.Generic;
namespace MultiSorting {
class Program {
static void Main(string[] args) {
var N = 10;
var M = 5;
var outer = new List<string[]>(N);
for (var i = 0; i < N; i++) {
string[] inner = { "a" + i, "d" + i, "c" + i, "b" + i, "e" + i };
outer.Add(inner);
}
int[] keys = { 1, 4, 3, 2, 5 };
var keysBuffer = new int[M];
for (int i = 0; i < N; i++) {
Array.Copy(keys, keysBuffer, M);
// doing sort N times, but we know the map
// old_index -> new_index from the first sorting
// plus we sort keysBuffer N times but use the result only one time
Array.Sort(keysBuffer, outer[i]);
}
keys = keysBuffer;
foreach (var key in keys) {
Console.Write(key + " "); // 1, 2, 3, 4, 5
}
Console.WriteLine("");
for (var i = 0; i < N; i++) {
foreach (var item in outer[i]) {
Console.Write(item + " "); // a{i}, b{i}, c{i}, d{i}, e{i}
}
Console.WriteLine("");
}
Console.ReadLine();
}
}
Just played with this and implemented mapping reuse directly in a for loop. I didn't expect that a simple loop instead of native built-in methods could speed up things, probably because I had underestimated algorithmic costs of sorting vs costs of array looping and I used to relax when a profiler said the job was mostly done inside .NET methods...
Naive is the code from the question, ReuseMap is what is described in words in the question, Linq is from the answer by #L.B. ...InPlace modifies input, ...Copy doesn't.
Results with N = 2000, M = 500, 10 runs, in milliseconds:
NaiveInPlace: 1005
ReuseMapInPlace: 129 (Log2(500) = 9.0, speed-up = 7.8x)
NaiveCopy: 1181
ReuseMapCopy: 304
LinqCopy: 3284
The entire test is below:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace MultiSorting {
class Program {
static void Main() {
const int n = 2;
const int m = 10;
var keys = GenerateKeys(m);
foreach (var key in keys) {
Console.Write(key + " ");
}
Console.WriteLine("");
var keysBuffer = new int[keys.Length];
Array.Copy(keys, keysBuffer, keys.Length);
Array.Sort(keysBuffer);
foreach (var key in keysBuffer) {
Console.Write(key + " ");
}
Console.WriteLine("");
// warm up, check that output is the same
List<string[]> outer = MultiSortNaiveInPlace(keys, GenerateOuter(n, m));
PrintResults(outer);
outer = MultiSortNaiveCopy(keys, GenerateOuter(n, m));
PrintResults(outer);
outer = MultiSortReuseMapInPlace(keys, GenerateOuter(n, m));
PrintResults(outer);
outer = MultiSortReuseMapCopy(keys, GenerateOuter(n, m));
PrintResults(outer);
outer = MultiSortLinqCopy(keys, GenerateOuter(n, m));
PrintResults(outer);
// tests
keys = GenerateKeys(500);
NaiveInPlace(2000, 500, keys);
ReuseMapInPlace(2000, 500, keys);
NaiveCopy(2000, 500, keys);
ReuseMapCopy(2000, 500, keys);
LinqCopy(2000, 500, keys);
Console.ReadLine();
}
private static void NaiveInPlace(int n, int m, int[] keys) {
const int rounds = 10;
var source = new List<List<string[]>>(rounds);
for (int i = 0; i < rounds; i++) {
source.Add(GenerateOuter(n, m));
}
GC.Collect();
var sw = Stopwatch.StartNew();
for (int i = 0; i < rounds; i++) {
source[i] = MultiSortNaiveInPlace(keys, source[i]);
}
sw.Stop();
Console.WriteLine("NaiveInPlace: " + sw.ElapsedMilliseconds);
}
private static void ReuseMapInPlace(int n, int m, int[] keys) {
const int rounds = 10;
var source = new List<List<string[]>>(rounds);
for (int i = 0; i < rounds; i++) {
source.Add(GenerateOuter(n, m));
}
GC.Collect();
var sw = Stopwatch.StartNew();
for (int i = 0; i < rounds; i++) {
source[i] = MultiSortReuseMapInPlace(keys, source[i]);
}
sw.Stop();
Console.WriteLine("ReuseMapInPlace: " + sw.ElapsedMilliseconds);
}
private static void NaiveCopy(int n, int m, int[] keys) {
const int rounds = 10;
var source = new List<List<string[]>>(rounds);
for (int i = 0; i < rounds; i++) {
source.Add(GenerateOuter(n, m));
}
GC.Collect();
var sw = Stopwatch.StartNew();
for (int i = 0; i < rounds; i++) {
source[i] = MultiSortNaiveCopy(keys, source[i]);
}
sw.Stop();
Console.WriteLine("NaiveCopy: " + sw.ElapsedMilliseconds);
}
private static void ReuseMapCopy(int n, int m, int[] keys) {
const int rounds = 10;
var source = new List<List<string[]>>(rounds);
for (int i = 0; i < rounds; i++) {
source.Add(GenerateOuter(n, m));
}
GC.Collect();
var sw = Stopwatch.StartNew();
for (int i = 0; i < rounds; i++) {
source[i] = MultiSortReuseMapCopy(keys, source[i]);
}
sw.Stop();
Console.WriteLine("ReuseMapCopy: " + sw.ElapsedMilliseconds);
}
private static void LinqCopy(int n, int m, int[] keys) {
const int rounds = 10;
var source = new List<List<string[]>>(rounds);
for (int i = 0; i < rounds; i++) {
source.Add(GenerateOuter(n, m));
}
GC.Collect();
var sw = Stopwatch.StartNew();
for (int i = 0; i < rounds; i++) {
source[i] = MultiSortLinqCopy(keys, source[i]);
}
sw.Stop();
Console.WriteLine("LinqCopy: " + sw.ElapsedMilliseconds);
}
private static void PrintResults(List<string[]> outer) {
for (var i = 0; i < outer.Count; i++) {
foreach (var item in outer[i]) {
Console.Write(item + " "); // a{i}, b{i}, c{i}, d{i}, e{i}
}
Console.WriteLine("");
}
}
private static int[] GenerateKeys(int m) {
var keys = new int[m];
for (int i = 0; i < m; i++) { keys[i] = i; }
var rnd = new Random();
keys = keys.OrderBy(x => rnd.Next()).ToArray();
return keys;
}
private static List<string[]> GenerateOuter(int n, int m) {
var outer = new List<string[]>(n);
for (var o = 0; o < n; o++) {
var inner = new string[m];
for (int i = 0; i < m; i++) { inner[i] = "R" + o + "C" + i; }
outer.Add(inner);
}
return outer;
}
private static List<string[]> MultiSortNaiveInPlace(int[] keys, List<string[]> outer) {
var keysBuffer = new int[keys.Length];
foreach (var inner in outer) {
Array.Copy(keys, keysBuffer, keys.Length);
// doing sort N times, but we know the map
// old_index -> new_index from the first sorting
// plus we sort keysBuffer N times but use the result only one time
Array.Sort(keysBuffer, inner);
}
return outer;
}
private static List<string[]> MultiSortNaiveCopy(int[] keys, List<string[]> outer) {
var result = new List<string[]>(outer.Count);
var keysBuffer = new int[keys.Length];
for (var n = 0; n < outer.Count(); n++) {
var inner = outer[n];
var newInner = new string[keys.Length];
Array.Copy(keys, keysBuffer, keys.Length);
Array.Copy(inner, newInner, keys.Length);
// doing sort N times, but we know the map
// old_index -> new_index from the first sorting
// plus we sort keysBuffer N times but use the result only one time
Array.Sort(keysBuffer, newInner);
result.Add(newInner);
}
return result;
}
private static List<string[]> MultiSortReuseMapInPlace(int[] keys, List<string[]> outer) {
var itemsBuffer = new string[keys.Length];
var keysBuffer = new int[keys.Length];
Array.Copy(keys, keysBuffer, keysBuffer.Length);
var map = new int[keysBuffer.Length];
for (int m = 0; m < keysBuffer.Length; m++) {
map[m] = m;
}
Array.Sort(keysBuffer, map);
for (var n = 0; n < outer.Count(); n++) {
var inner = outer[n];
for (int m = 0; m < map.Length; m++) {
itemsBuffer[m] = inner[map[m]];
}
Array.Copy(itemsBuffer, outer[n], inner.Length);
}
return outer;
}
private static List<string[]> MultiSortReuseMapCopy(int[] keys, List<string[]> outer) {
var keysBuffer = new int[keys.Length];
Array.Copy(keys, keysBuffer, keysBuffer.Length);
var map = new int[keysBuffer.Length];
for (int m = 0; m < keysBuffer.Length; m++) {
map[m] = m;
}
Array.Sort(keysBuffer, map);
var result = new List<string[]>(outer.Count);
for (var n = 0; n < outer.Count(); n++) {
var inner = outer[n];
var newInner = new string[keys.Length];
for (int m = 0; m < map.Length; m++) {
newInner[m] = inner[map[m]];
}
result.Add(newInner);
}
return result;
}
private static List<string[]> MultiSortLinqCopy(int[] keys, List<string[]> outer) {
var result = outer.Select(arr => arr.Select((item, inx) => new { item, key = keys[inx] })
.OrderBy(x => x.key)
.Select(x => x.item)
.ToArray()) // allocating
.ToList(); // allocating
return result;
}
}
}

Categories

Resources