Randomizing List with Guid - c#

I have a problem about my c# project. In the program I have a list
private static void FillData(List<Question> questions)
{
AddQuestion(questions,
"DotA isimli MOBA oyununun açılımı nedir? ",
2,
"Defense of the Arkham",
"Defence of the Ancients",
"Defense of the Ancients",
"Dance of the Architectures"
);
like that and i wanna make that list randomizely showned in every opening with shuffle. In the example my teacher used
private static void Shuffle(Soru[] array)
{
int length = array.Length;
for (int i = 0; i < length; i++)
{
int index = i + ((int) (_random.NextDouble() * (length - i)));
Soru soru = array[index];
array[index] = array[i];
array[i] = soru;
}
this and i wanna make that in Guid.NewGuid(). Can anyone help me with replacing that with Guid?
(edited from comments) This is what I tried so far:
private static void Shuffle(List<Question> List)
{
List = List.OrderBy(o => Guid.NewGuid().ToString()).ToList();
foreach (Question question in ....) { Console.WriteLine(question);
}
but I can't fullfill foreach loop. And yes I want to use Guid instead of random.

The problem is that you only modified the input parameter to hold a reference of another List. As it is not passed as reference, in the place where you have called it will hold the reference of the original List.
You could try this way:
private static void Shuffle(List<Question> List)
{
var randomOrderList = List.OrderBy(o => Guid.NewGuid().ToString()).ToList();
for (int i = 0; i < List.Count; i++)
{
List[i] = randomOrderList[i];
}
}

Related

Return all powers of 2 less then n in C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
For a given number n, I need to return all powers of 2 less than n, as a string in a way that elements are separated with "-". If n < 2, it needs to return an empty string.
For example:
n = 20 => 1-2-4-8-16
n = 8 => 1-2-4
I'm a beginner, so any help would be much appreciated! :)
EDIT: this is not working
using System;
class N
{
static int[] powerof2(int n)
{
int[] array = new int[n];
if (n < 2)
return new int[0];
for (int i = 0; i < 8 * sizeof(uint); i++)
{
int curr = 1 << i;
if (curr > n)
break;
array[i] = curr;
}
return array;
public override string ToString()
{
for (int i = 0; i < array.length; i++)
return (array[i] + "-");
}
}
static public void Main ()
{
int n = 10;
Console.WriteLine(powerof2(n).ToString());
}
}
You need to run the for loop with the following rule
for (int i = 1; i < n; i *= 2)
Whole solution
class Program
{
static void powerof2(int n)
{
if (n < 2)
Console.WriteLine(string.Empty);
for (int i = 1; i < n; i *= 2)
{
if (i > 1)
Console.Write("-");
Console.Write(i);
}
}
static void Main(string[] args)
{
powerof2(20);
}
Using iterator methods makes this case trivial (Fiddle):
using System;
using System.Collections.Generic;
public class Program
{
public static IEnumerable<int> GetPowersOf2(int maxN)
{
for (int p = 1; p < maxN; p *= 2)
{
yield return p;
}
}
public static void Main(string[] args)
{
IEnumerable<int> powersOf2LessThan20 = GetPowersOf2(20);
Console.WriteLine(string.Join("-", powersOf2LessThan20));
}
}
I suppose this is what you're looking for:
class Program
{
public static string Pow2LessThan(ulong n)
{
if (n < 2)
return "";
// start with 2^0
string res = "1";
// try further
int p = 1;
ulong cnum = 2;
while (cnum < n)
{
res += "-" + cnum.ToString();
++p;
cnum = (ulong)(1 << p);
}
return res;
}
static void Main(string[] args)
{
ulong n = 20;
Console.WriteLine(Pow2LessThan(n));
Console.ReadLine();
}
}
The reason that it's not working is: you never access the class N in any way. The call should be
Console.WriteLine(N.powerof2(n).ToString());
^^
With that modification, you'll be notified that the method powerof2() is inaccessible due to its protection level. You need to make it at least internal like so:
internal static int[] powerof2(int n)
Next, note that you're missing a } for that method.
return array;
}
With that fixed, the compiler will tell you that you can't access array inside ToString(), because the scope of array is limited to powerof2(). Make the array a field of the class like
static int[] array;
Now, the compiler complains about array.length in ToString(). Fix that by capitalizing Length.
Mistake number 6: ToString() will return in the first iteration of the loop. It will not return anything if array.Length is 0. The function should look a little bit like this:
public override string ToString()
{
string result = "";
for (int i = 0; i < array.Length; i++)
result += array[i] + "-";
return result;
}
Now, this will still not work, because the main method calls ToString() on the return value of powerof2(), which is of type int[] and not of type N. That's because your stuff is static. Make it non-static instead and create an instance of N.
static public void Main ()
{
var n = new N();
n.powerof2(10);
Console.WriteLine(n.ToString());
}
With 7 issues fixed, the output is now 1-2-4-8-0-0-0-0-0-0-, so there's still stuff to fix. Maybe you get a little bit of a feeling why everyone proposes a totally different solution.
What else to fix:
the output of course is still incorrect.
if someone inputs 4000000000 as the number, you certainly don't want to allocate 4 GB of RAM in the array.
Why allocate an array at all and not construct the string right away?
Why 8*sizeof(uint)? You can't shift more often than sizeof(uint).
class Program
{
static string powerof2(int n)
{
var str="1" ;
if (n < 2)
return "" ;
else
{
var i=1;
while(Math.Pow(i, 2)<n)
{
str+="-" +Math.Pow(2, i);
i++;
}
return str;
}
}
static void Main(string[] args)
{
powerof2(50);
}
}

c# comparing list of IDs

I have a List<Keyword> where Keyword class is:
public string keyword;
public List<int> ids;
public int hidden;
public int live;
public bool worked;
Keyword has its own keyword, a set of 20 ids, live by default is set to 1 and hidden to 0.
I just need to iterate over the whole main List to invalidate those keywords whose number of same ids is greater than 6, so comparing every pair, if the second one has more than 6 ids repeated respect to the first one, hidden is set to 1 and live to 0.
The algorithm is very basic but it takes too long when the main list has many elements.
I'm trying to guess if there could be any method I could use to increase the speed.
The basic algorithm I use is:
foreach (Keyword main_keyword in lista_de_keywords_live)
{
if (main_keyword.worked) {
continue;
}
foreach (Keyword keyword_to_compare in lista_de_keywords_live)
{
if (keyword_to_compare.worked || keyword_to_compare.id == main_keyword.id) continue;
n_ids_same = 0;
foreach (int id in main_keyword.ids)
{
if (keyword_to_compare._lista_models.IndexOf(id) >= 0)
{
if (++n_ids_same >= 6) break;
}
}
if (n_ids_same >= 6)
{
keyword_to_compare.hidden = 1;
keyword_to_compare.live = 0;
keyword_to_compare.worked = true;
}
}
}
The code below is an example of how you would use a HashSet for your problem. However, I would not recommend using it in this scenario. On the other hand, the idea of sorting the ids to make the comparison faster still.
Run it in a Console Project to try it out.
Notice that once I'm done adding new ids to a keyword, I sort them. This makes the comparison faster later on.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace KeywordExample
{
public class Keyword
{
public List<int> ids;
public int hidden;
public int live;
public bool worked;
public Keyword()
{
ids = new List<int>();
hidden = 0;
live = 1;
worked = false;
}
public override string ToString()
{
StringBuilder s = new StringBuilder();
if (ids.Count > 0)
{
s.Append(ids[0]);
for (int i = 1; i < ids.Count; i++)
{
s.Append(',' + ids[i].ToString());
}
}
return s.ToString();
}
}
public class KeywordComparer : EqualityComparer<Keyword>
{
public override bool Equals(Keyword k1, Keyword k2)
{
int equals = 0;
int i = 0;
int j = 0;
//based on sorted ids
while (i < k1.ids.Count && j < k2.ids.Count)
{
if (k1.ids[i] < k2.ids[j])
{
i++;
}
else if (k1.ids[i] > k2.ids[j])
{
j++;
}
else
{
equals++;
i++;
j++;
}
}
return equals >= 6;
}
public override int GetHashCode(Keyword keyword)
{
return 0;//notice that using the same hash for all keywords gives you an O(n^2) time complexity though.
}
}
class Program
{
static void Main(string[] args)
{
List<Keyword> listOfKeywordsLive = new List<Keyword>();
//add some values
Random random = new Random();
int n = 10;
int sizeOfMaxId = 20;
for (int i = 0; i < n; i++)
{
var newKeyword = new Keyword();
for (int j = 0; j < 20; j++)
{
newKeyword.ids.Add(random.Next(sizeOfMaxId) + 1);
}
newKeyword.ids.Sort(); //sorting the ids
listOfKeywordsLive.Add(newKeyword);
}
//solution here
HashSet<Keyword> set = new HashSet<Keyword>(new KeywordComparer());
set.Add(listOfKeywordsLive[0]);
for (int i = 1; i < listOfKeywordsLive.Count; i++)
{
Keyword keywordToCompare = listOfKeywordsLive[i];
if (!set.Add(keywordToCompare))
{
keywordToCompare.hidden = 1;
keywordToCompare.live = 0;
keywordToCompare.worked = true;
}
}
//print all keywords to check
Console.WriteLine(set.Count + "/" + n + " inserted");
foreach (var keyword in set)
{
Console.WriteLine(keyword);
}
}
}
}
The obvious source of inefficiency is the way you calculate intersection of two lists (of ids). The algorithm is O(n^2). This is by the way problem that relational databases solve for every join and your approach would be called loop join. The main efficient strategies are hash join and merge join. For your scenario the latter approach may be better I guess, but you can also try HashSets if you like.
The second source of inefficiency is repeating everything twice. As (a join b) is equal to (b join a), you do not need two cycles over the whole List<Keyword>. Actually, you only need to loop over the non duplicate ones.
Using some code from here, you can write the algorithm like:
Parallel.ForEach(list, k => k.ids.Sort());
List<Keyword> result = new List<Keyword>();
foreach (var k in list)
{
if (result.Any(r => r.ids.IntersectSorted(k.ids, Comparer<int>.Default)
.Skip(5)
.Any()))
{
k.hidden = 1;
k.live = 0;
k.worked = true;
}
else
{
result.Add(k);
}
}
If you replace the linq with just the index manipulation approach (see the link above), it would be a tiny bit faster I guess.

Separate functions without duplicating code

I am currently working on a program to traverse through a list of numbers with two different functions to find the sum and a specific value. Here is the code that I have implemented
class Program
{
static int i, sum;
static List<int> store = new List<int>();
static void Main(string[] args)
{
for (i = 0; i < 100; i++)
{
store.Add(i);
}
i = 0;
TraverseList();
Console.ReadLine();
}
static void TraverseList()
{
while (i < store.Count)
{
FindValue();
FindSum();
i++;
}
Console.WriteLine("The sum is {0}", sum);
}
static void FindValue()
{
if (store[i] == 40)
{
Console.WriteLine("Value is 40");
}
}
static void FindSum()
{
sum = sum + store[i];
}
}
I was thinking of separating FindSum and FindValue into two different functions and not calling them in TraverseList. Is there any other way of doing it rather the duplicating the common code of list traversal in those two functions as I have done here
class Program
{
static int i, sum;
static List<int> store = new List<int>();
static void Main(string[] args)
{
for (i = 0; i < 100; i++)
{
store.Add(i);
}
i = 0;
FindValue();
i = 0;
FindSum();
Console.ReadLine();
}
static void FindValue()
{
while (i < store.Count)
{
if (store[i] == 40)
{
Console.WriteLine("Value is 40");
}
i++;
}
}
static void FindSum()
{
while (i < store.Count)
{
sum = sum + store[i];
i++;
}
Console.WriteLine("The sum is {0}", sum);
}
}
To find the sum of a series of numbers you can use the simple LINQ function:
List<int> numbers = new List<int>();
int sum = numbers.Sum();
I am not sure what you mean by find a value. If you want to check if one of the numbers in a series is equal to a certain value you can use the LINQ function Any:
int myValue = 40;
bool hasMyValue = numbers.Any(i => i == myValue);
This uses a lambda expression which executes a function and passes each element in the collection to the function. The function returns true or false to indicate that the element is a match for the Any test.
If instead you want to check for how many numbers in a sequence match a certain value you can instead use the Count function like so:
int numberOfMatches = numbers.Count(i => i == myValue);
First thing - I would use foreach instead of while, regarding the duplicate code (assuming you are not using Linq) - I think it's fine
A taste how Linq can simplify your code:
var FindSum = store.Sum();
var FindValue = store.FindAll(x => x == 40);
I cannot stress enough how bad it is to have i and sum as class members. Especially i. It will make your code very fragile, and hard to work with. Try to make each method as isolated from the rest of the code as possible.
Try something like this instead:
static void Main( string[] args )
{
List<int> store = new List<int>();
for( int i = 0; i < 100; i++ )
store.Add( i );
FindValue( store );
FindSum( store );
Console.ReadLine();
}
static void FindValue( List<int> list )
{
for( int i = 0; i < list.Count; i++ )
{
if( list[i] == 40 )
Console.WriteLine( "Value is 40" );
}
}
static void FindSum( List<int> list )
{
int sum = 0;
for( int i = 0; i < list.Count; i++ )
sum += list[i];
Console.WriteLine( "The sum is {0}", sum );
}
It is perfectly fine (and normal) to duplicate the looping, it's just a single line. You could also use a foreach here.
Also, disregard everyone telling you to use LINQ. You're obviously new to programming and you should learn the basics first.

Stuck with two dimensional array

I'm trying to create a booking service and I've been stuck on this part for many hours and I just can't figure out what I'm doing wrong.
So I've got a Two Dimensional array and when trying to print out some stuff when testing and trying to figure out what's wrong, all I get is System.String[] which doesn't really make me any wiser. I want to be able to access the details in i.e. m_nameMatrix[0,0] to check whether the seat is reserved or not.
Here's a snippet from my form code:
private void UpdateGUI(string customerName, double price)
{
string selectedItem = cmdDisplayOptions.Items[cmdDisplayOptions.SelectedIndex].ToString();
rbtnReserve.Checked = true;
lstSeats.Items.Clear();
lstSeats.Items.AddRange(m_seatMngr.GetSeatInfoStrings(selectedItem));
}
And here are two methods from my 2nd class:
public string[] GetSeatInfoStrings(string selectedItem)
{
int count = GetNumOfSeats(selectedItem);
if (count <= 0)
{
return new string[0];
}
string[] strSeatInfoStrings = new string[count];
for (int index = 0; index <= count; index++)
{
strSeatInfoStrings[index] = GetSeatInfoAt(index);
}
return strSeatInfoStrings;
}
public string GetSeatInfoAt(int index)
{
int row = (int)Math.Floor((double)(index / m_totNumOfCols));
int col = index % m_totNumOfCols;
string seatInfo = m_nameMatrix.GetValue(row, col).ToString();
return seatInfo;
}
I'm not actually getting an exception so it might be my logical thinking that's been taking a hit due to hours and hours of trying to figure it out.
EDIT:
public void ReserveSeat(string name, double price, int index)
{
int row = (int)Math.Floor((double)(index / m_totNumOfCols));
int col = index % m_totNumOfCols;
string reserved = string.Format("{0,3} {1,3} {2, 8} {3, 8} {4,22:f2}",
row + 1, col + 1, "Reserved", name, price);
m_nameMatrix[row, col] = reserved;
}
This line:
for (int index = 0; index <= count; index++)
should be:
for (int index = 0; index < count; index++)
Why? Lets say I have an array with 2 objects in it. count would be 2. However, the indexes are 0 and 1. So you have to use a less than operator.
If you're getting "System.String[]" in your messagebox, it's because you're trying to print a string[] directly, rather than the various strings it contains:
string[] data = GetSeatInfoStrings("foo");
MessageBox.Show(data);
Instead, you need to show the contents of data:
string[] data = GetSeatInfoStrings("foo");
MessageBox.Show(string.Join("\n", data));
See here for the documentation.
Suppose you had a method called ReturnArray():
class Class2
{
public string[] ReturnArray()
{
string[] str = new string[] { "hello", "hi" };
return str;
}
}
If you called ReturnArray in your main class like this:
Class2 class2 = new Class2();
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(class2.ReturnArray());
}
it will return System.String[] because MessageBox.Show(...) takes a string as an argument, in this case.
So you'll also get the same result by using MessageBox.Show(class2.ReturnArray().ToString());
Instead, you may want to do something like this:
Class2 class2 = new Class2();
private void button1_Click(object sender, EventArgs e)
{
string[] strArray = class2.ReturnArray();
listBox1.Items.AddRange(strArray);
}

mergesort - with an insignificant change throws SystemInvalidOperationException

A very strange thing occured in my program. Here is the simplified code.
class Program
{
static void Main(string[] args)
{
ArrayList numbers = new ArrayList();
numbers.Add(1);
numbers.Add(3);
numbers.Add(4);
numbers.Add(2);
var it = Sorts.MergeSort((ArrayList)numbers.Clone());
Sorts.PrintArray(it, "mergesort");
Console.WriteLine("DONE");
Console.ReadLine();
}
}
public static class Sorts
{
public static ArrayList BubbleSort(ArrayList numbers)
{
bool sorted = true;
for (int i = 0; i < numbers.Count; i++)
{
for (int j = 1; j < numbers.Count; j++)
{
if ((int)numbers[j - 1] > (int)numbers[j])
{
int tmp = (int)numbers[j - 1];
numbers[j - 1] = numbers[j];
numbers[j] = tmp;
sorted = false;
}
}
if (sorted)
{
return numbers;
}
}
return numbers;
}
public static ArrayList MergeSort(ArrayList numbers, int switchLimit = 3)
{
//if I use this if - everything works
if (numbers.Count <= 1)
{
// return numbers;
}
//the moment I use this condition - it throws SystemInvalidOperationException in function Merge in the line of a "for"-loop
if (numbers.Count <=switchLimit)
{
return Sorts.BubbleSort(numbers);
}
ArrayList ret = new ArrayList();
int middle = numbers.Count / 2;
ArrayList L = numbers.GetRange(0, middle);
ArrayList R = numbers.GetRange(middle, numbers.Count - middle);
L = MergeSort(L);
R = MergeSort(R);
return Merge(L, R);
}
private static ArrayList Merge(ArrayList L, ArrayList R)
{
ArrayList ret = new ArrayList();
int l = 0;
int r = 0;
for (int i = 0; i < L.Count + R.Count; i++)
{
if (l == L.Count)
{
ret.Add(R[r++]);
}
else if (r == R.Count)
{
ret.Add(L[l++]);
}
else if ((int)L[l] < (int)R[r])
{
ret.Add(L[l++]);
}
else
{
ret.Add(R[r++]);
}
}
return ret;
}
//---------------------------------------------------------------------------------
public static void PrintArray(ArrayList arr, string txt = "", int sleep = 0)
{
Console.WriteLine("{1}({0}): ", arr.Count, txt);
for (int i = 0; i < arr.Count; i++)
{
Console.WriteLine(arr[i].ToString().PadLeft(10));
}
Console.WriteLine();
System.Threading.Thread.Sleep(sleep);
}
}
There is a problem with my Sorts.MergeSort function.
When I use it normally (take a look at the first if-condition in a function - all works perfectly.
But the moment when I want it to switch to bubblesort with smaller input (the second if-condition in the function) it throws me an SystemInvalidOperationException. I have no idea where is the problem.
Do you see it?
Thanks. :)
Remark: bubblesort itself works - so there shouldn't be a problem in that sort...
The problem is with your use of GetRange:
This method does not create copies of the elements. The new ArrayList is only a view window into the source ArrayList. However, all subsequent changes to the source ArrayList must be done through this view window ArrayList. If changes are made directly to the source ArrayList, the view window ArrayList is invalidated and any operations on it will return an InvalidOperationException.
You're creating two views onto the original ArrayList and trying to work with both of them - but when one view modifies the underlying list, the other view is effectively invalidated.
If you change the code to create copies of the sublists - or if you work directly with the original list within specified bounds - then I believe it'll work fine.
(As noted in comments, I'd also strongly recommend that you use generic collections.)
Here's a short but complete program which demonstrates the problem you're running into:
using System;
using System.Collections;
class Program
{
static void Main()
{
ArrayList list = new ArrayList();
list.Add("a");
list.Add("b");
ArrayList view1 = list.GetRange(0, 1);
ArrayList view2 = list.GetRange(1, 1);
view1[0] = "c";
Console.WriteLine(view2[0]); // Throws an exception
}
}
on this line R = MergeSort(R); you alter the range of numbers represented by L. This invalidates L. Sorry I have to go so can't explain any further now.

Categories