Cannot convert from int to system.collections.generic.icomparer<int> - c#

New to C# Just wondering what the error is, can't understand the error. No need to correct, just want to know the mistake.
ERROR:
The best overloaded method match for 'Systems.Collections.Generic.List.BinarySearch(int,System.Collections.Generic.Icomparer)' has some invalid arguments
Argument1: Cannot convert from system.collections.generic.list to int
Argument2: Cannot convert from int to system.collections.generic.icomparer
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;enter code here
using System.Windows.Forms;
namespace LotoNumbers
{
public partial class FrmLotto : Form
{
// declare class level variables
List<int> player = new List<int>(7);
List<int> computer = new List<int>(6);
public FrmLotto()
{
InitializeComponent();
}
// event method to generate player's numbers
private void btnPlayer_Click(object sender, EventArgs e)
{
// declare and initalize local variables
string display = "";
// reset the winning number label before generating the player's numbers
lblComputerNumber.Text = "00 00 00 00 00 00";
// generate unique random numbers
GenerateRandomNumbers(player);
player.Sort();
// build display string
display = BuildDisplayString(player);
// display winning number in label
lblPlayerNumber.Text = display;
}
// method to generate computer's random numbers (the 'winning numbers')
// and determine how many winning numbers
private void btnComputer_Click(object sender, EventArgs e)
{
// declare and initalize local variables
int winCount = 0;
string display = "";
// generate unique random numbers
GenerateRandomNumbers(computer);
// sort the array in ascending order
computer.Sort();
// build display string
display = BuildDisplayString(computer);
// display winning number in label
lblComputerNumber.Text = display;
// determine if this number matches any of the players numbers
winCount = CompareTwoList(player, computer);
// display the total winning numbers
lblMatching.Text = winCount.ToString("D2");
}
private void GenerateRandomNumbers(List<int> numberList)
{
Random lucky = new Random();
// generate unique random numbers
for (int index = 0; index < numberList.Capacity; index++)
{
int temp = lucky.Next(1, 50);
if (numberList.IndexOf(temp) < 0)
{
numberList.Add(temp);
}
else
{
index--;
}
}
}
private string BuildDisplayString(List<int> numberList)
{
// declare method variable
string display = " ";
// loop through the array and build a display string
foreach (int number in numberList)
display += number.ToString("D2") + " ";
// return display string
return display;
}
private int CompareTwoList(List<int> list1, List<int> list2)
{
// declare method variable
int numberMatching = 0;
// loop through each element in the first array looking for a match in the second array
foreach (int value in list1)
{
if (player.BinarySearch(list2, value) >= 0)
numberMatching++; // a matching value is found
}
return numberMatching;
}
}
}

It looks like you want:
if (list2.BinarySearch(value) >= 0)
numberMatching++; // a matching value is found
You are calling List<int>.BinarySearch(int, IComparer<int>) at the moment. Since value is an int you are getting a type error.
Note you can also do:
int numberMatching = list2.Intersect(list1).Count();

There is no overload for List<int>.BinarySearch() which accepts a List<int> and int as the parameters. See MSDN
You need to use player.BinarySearch(value)

Related

How to add integers to an array and get a random number?

It's a favorite panel.
You can select numbers (with button click) and than I would like to add this number to an array and than get a random number from this array.
public int runs;
public int randomNumber;
public int[] favorites = new int[75];
public void RandomButton()
{
if (DataController.Instance.group == 3)
{
favorites[randomNumber] = UnityEngine.Random.Range(0, favorites.Length);
Debug.Log(favorites[randomNumber]);
}
}
public void b0()
{
for (runs = 0; runs < favorites.Length; runs++)
{
favorites[runs] = 0;
}
}
public void b1()
{
for (runs = 0; runs < favorites.Length; runs++)
{
favorites[runs] = 1;
}
}
I'm stuck , because I get random number between 0 - 75. I would like to have a random number from the "favorites" array after I click on the buttons.
What you are doing here
favorites[randomNumber] = UnityEngine.Random.Range(0, favorites.Length);
Is assign a random value between 0 and 74 to an item in your array .. depending on whatever value randomNumber has at that moment ...
What you rather want to do is actually access the value from the array using the random value as index like
randomNumber = favorites [UnityEngine.Random.Range(0, favorites.Length)];
Debug.Log(randomNumber);
However what difference will it make if you are filling your array with always the same numbers using b0 and b1?
After running these methods all elements are either 0 or 1 anyway ...
Anyway in your question you are also asking for how to Add a number.
You shouldn't use an array for this but rather a List<int> like
public List<int> favorites = new List<int>();
public void AddNumber(int newNumber)
{
favorites.Add(newNumber);
}
public void RandomButton()
{
if (DataController.Instance.group == 3)
{
randomNumber = favorites[UnityEngine.Random.Range(0, favorites.Count)];
Debug.Log(randomNumber);
}
}
if (DataController.Instance.group == 3)
{
var randomIndex = UnityEngine.Random.Range(0, favorites.Length);
Console.WriteLine(favorites[randomIndex]); // random item from your array
}
answer

Why aren't my images loading and moving as expected?

I'm working on a project where I can load a fixed set of data into a listbox. Each line of data is tied to an image in a picturebox. When I click on my load button, the data should be loaded into the listbox and each image should be loaded, and begin to move on the screen.
When I click load, initially 4 images are briefly loaded. Then the fourth disappears and only the first three of my images begin to move around the screen. However, when I create a new object the data is added to the listbox, but the image isn't the relevant new object image, instead it's my fourth image that should have loaded. So my loaded images are always one step behind, but my listbox is up to date.
I am very new to coding and struggling to understand the bigger picture at this stage. A lot of the code are examples that I've taken from places, and I vaguely understand what is going on, but not enough to troubleshoot this issue.
Does anyone have any tips on why this would be happening? Any advice or ideas on where I'm going wrong would be much appreciated.
MyClass.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Windows.Forms;
namespace ACarter_A1_New
{
class MyClass
{
//private variables
private string animalId;
private int typeId; //Animal type id
private string typeName;
private int xPosition;
private int yPosition;
private int width;
private int height;
private int xStep; //move speed
private int yStep;
private PictureBox animalPic; //Picture
//public variables
public string AnimalId { get => animalId; set => animalId = value; }
public int TypeId { get => typeId; set => typeId = value; }
public string TypeName { get => typeName; set => typeName = value; }
public int XPosition { get => xPosition; set => xPosition = value; }
public int YPosition { get => yPosition; set => yPosition = value; }
public int Width { get => width; set => width = value; }
public int Height { get => height; set => height = value; }
public int XStep { get => xStep; set => xStep = value; }
public int YStep { get => yStep; set => yStep = value; }
public PictureBox AnimalPic { get => animalPic; set => animalPic = value; }
public MyClass(string id, PictureBox iniPic, int seed)
{
AnimalId = id; //the string id is now equal to AnimalId
TypeId = seed; //the int seed is now equal to TypeId
//set up type name
switch (TypeId) //TypeId = seed
{
case 1:
TypeName = "Angry Dog"; //= seed 1
break;
case 2:
TypeName = "Sleepy Dog"; //= seed 2
break;
case 3:
TypeName = "Dirty Dog"; //= seed 3
break;
case 4:
TypeName = "Happy Dog"; //= seed 4
break;
}
AnimalPic = iniPic; //load picture
//set up picture location by (X, Y, W, H)
XPosition = seed * 20;
YPosition = seed * 10;
Width = animalPic.Width;
Height = animalPic.Height;
XStep = seed * 5; //moving speed
YStep = seed * 5 / 3;
}
//Method DrawPic(...) displays an object image on the screen
public void DrawPic(Graphics canvas)
{
Image pic; //Image variable called pic
pic = AnimalPic.Image; //that image pic is now equal to the public picturebox AnimalPic
canvas.DrawImage(pic, XPosition, YPosition, Width, Height);
}
//Method move() changes the position of the object - simulates moving
public void Move()
{
if ((XPosition + Width >= 503 || (XPosition <= 0)))
{//change direction if on the edge
XStep = -XStep;
}
XPosition = XPosition + XStep; //move one step on x direction
if ((YPosition + height >= 421 || (YPosition <= 0)))
{//change direction if on the edge
YStep = -YStep;
}
YPosition = YPosition + YStep; //move one step on Y direction
}
//Method ToString() enables the object to be displayed as a string in the Listbox
public override string ToString()
{
return AnimalId + ", " + TypeId + ", " + TypeName + ", " + "x speed: " + XStep.ToString() + ", Y speed: " + YStep.ToString();
}
}
}
FileManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
using System.Drawing;
namespace ACarter_A1_New
{
class FileManager
{
public List<MyClass> LoadAnimals(string fn)
{
StreamReader sr = new StreamReader(fn); //create a new instance of streamreader to use to read our .txt file, called sr and pass in the string fn
List<MyClass> loaddogs = new List<MyClass>(); //create a list based on the MyClass.cs class object, call the list loadDogs
//declare variables for object parameters from the MyClass class
string animalId; //we want the animalId, pic and seed info
PictureBox pic = new PictureBox();
int seed;
while (!sr.EndOfStream) //use a while loop to read through the file until the end - while not at the end, continue
{
string temp = sr.ReadLine(); //create a temp string called temp to store each read line that the sr reads
string[] values = temp.Split(','); //create a string array called value to store the information stored in temp, and split the indexed info on each line by commas
animalId = values[0]; //state that the animal id will be the first index at index 0 in our string array values
seed = int.Parse(values[1]); //state that seed will be the second index at index 1 in our string array values, we have to use int.Parse to convert int to string
//create new object, picture will be setup in form application
MyClass d = new MyClass(animalId, pic, seed); //create an object from MyClass called d, with properties for animalId, pic and seed
loaddogs.Add(d); //add what is stored in d to loaddogs list
}
sr.Dispose(); //finish using the sr streamreader
return loaddogs; //return a list loaddogs to the SaveAnimal method
}
}
}
Form1.cs - code for Loading/Creating New Object
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Collections;
namespace ACarter_A1_New
{
public partial class Form1 : Form
{
Random seed = new Random();
int animalTypeId;
int animalId;
List<MyClass> animals = new List<MyClass>();
Graphics screen;
public Form1()
{
InitializeComponent();
//setup screen and initialize animal id
screen = picScreen.CreateGraphics(); //declare and initialise the screen to equal the
animalId = 0; //declare and initalise the animalId variable
}
private void MoveAndShowAnimals() //MoveAndShowAnimals method to call the public Move() and DrawPic methods
{
try //use try/catch incase any exceptions are thrown to the code block
{
//initally the graphics screen is cleared and is the color dark olive green
screen.Clear(Color.DarkOliveGreen);
foreach (MyClass dog in animals) //foreach object that is stored in animals
{
dog.DrawPic(screen);
dog.Move();
//call the public DrawPic method from the MyClass class for each object
//call the public move method from the MyClass class for each object
}
}
catch (Exception ex)
{
MessageBox.Show("Error with MoveAndShowAnimals method" + ex);
}
}
private void btnLoadInit_Click(object sender, EventArgs e)
{
try //use try/catch incase any exceptions are thrown to the code block
{
animals.Clear(); //clear the animals list
List<MyClass> d = new List<MyClass>(); //create a new list using the MyClass class called d
lbxObjs.Items.Clear(); //clear the listbox lbxObjs
FileManager fm = new FileManager(); //create a new instance of FileManger called fm
//retrieve a list of dog information, without image
d = fm.LoadAnimals("dogs.txt"); //use the file manager fm, specifically the LoadAnimals(dogs.txt) in FileManager class and store in the list called d
//declare variables to use Id and seed
string Id;
int seed;
int count = 0; //count used to increment through in foreach loop, initialised to start at 0
// PictureBox Pic;
foreach (MyClass dog in d) //foreach loop to loop through each object "dog" that is put into the list d. The object being made up of id, seed and a picturebox
{
Id = dog.AnimalId; //specifying that the string Id is equal to the AnimalId specified in the MyClass class
seed = dog.TypeId; //specifying that the int seed is equal to the TypeId specified in the MyClass class
PictureBox Pic = null; //We need a picturebox, which initially will be null as we need the Pic to be one of four
//we can determine which pic should be first, second, third and fourth by using the count variable and if, if else statements
if (count == 0)
{
Pic = picDog1;
}
else if (count == 1)
{
Pic = picDog2;
}
else if (count == 2)
{
Pic = picDog3;
}
else if (count == 3)
{
Pic = picDog4;
}
//make an active object from retrieved file data
MyClass dogfromFile = new MyClass(Id, Pic, seed);
// use the active object and add it to the list animals which is our object list
animals.Add(dogfromFile);
MoveAndShowAnimals();
count++; //count++ increment count by 1 each time the foreach loop increments, which will be 4 times as we have four initial objects to load
}
if (animals == null) //if animal list is null, then show the error message below
{
MessageBox.Show("Error loading animals");
}
else //otherwise, clear the listbox, and add the objects that we have loaded into animals to the listbox
{
lbxObjs.Items.Clear();
lbxObjs.Items.AddRange(animals.ToArray());
/*MoveAndShowAnimals();*/ //implement the MoveAndShowAnimals() method to animate images
timer1.Enabled = true;//start the timer
}
}
catch (Exception ex) //exception ex shows a detailed error message as well as the initial message "Error loading"
{
MessageBox.Show("Error loading" + ex); //if an exception is thrown to the above code, display error loading
}
}
private void btnNewObj_Click(object sender, EventArgs e)
{
try
{
animalId++; //start animal id at 1, has been initialised to 0 already
//animalTypeId now equals the random seed which will choose from 4 objs and start at 1
string fullAnimalId = animalId.ToString(); //pass in string New Dog + the animal id to a string called fullAnimalId
animalTypeId = seed.Next(4) + 1;
PictureBox Pic = null; //initially this will be null as we need to choose from 1 of four pictureboxes. we can differentiate which picture to choose by using the animalTypeId
//which is equal to the seed number and give each seed the relevant image name, so Pic can have four variables depending on which seed is chosen
if (animalTypeId == 1)
{
Pic = picDog1;
}
else if (animalTypeId == 2)
{
Pic = picDog2;
}
else if (animalTypeId == 3)
{
Pic = picDog3;
}
else if (animalTypeId == 4)
{
Pic = picDog4;
}
//make an active object from retrieved file data
MyClass dogfromNew = new MyClass(fullAnimalId, Pic, animalTypeId);
animals.Add(dogfromNew); //add the active object to the animals object list
lbxObjs.Items.Clear(); //clear the listbox
lbxObjs.Items.AddRange(animals.ToArray()); //take the objects stored in animals list and add them to the listbox
MoveAndShowAnimals(); //call the MoveAndShowAnimals() method to animate the new images
timer1.Enabled = true; //start the timer
}
catch (Exception ex) //exception ex shows a detailed error message as well as the initial message "Error creating new object"
{
MessageBox.Show("Error creating new object" + ex);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
try
{
MoveAndShowAnimals();
}
catch (Exception)
{
MessageBox.Show("Error with timer");
}
}
dogs.txt file contents:
1,1
2,2
3,3
4,4
For anyone who's interested. The fourth image that kept disappearing was actually to do with the images themselves. I tried resizing the images and it worked first time through. I figured this out by using a smaller program that just had the load button and new object button and used different pictures, which when I compared to the images I was using, were a third of the size. So I changed the image size and in this project, and it worked first time. I'm guessing it was having trouble rendering the images so frequently that it just lagged out on the fourth. As the images were moving pretty slowly across the screen, and now are moving a lot quicker.

Using the Bubble Sort Algorithm on Windows Form C# to sort random numbers?

I am suppose to be writing a C# program in visual studios windows forms application that needs to implement the following functionalities:
Create 1,000 random numbers between 1 and 5000
Use the bubble sort algorithm and sort the 1000 numbers
This is the code that I have so far:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Prog7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnGenerate_Click(object sender, EventArgs e)
{
Random num = new Random();
string line = Environment.NewLine;
int nbr = num.Next(0, 5001);
textNumbers.Text = nbr.ToString();
for(int i = 1; i <= 1000; i++)
{
nbr = num.Next(0, 5001);
textNumbers.Text = textNumbers.Text + line + nbr.ToString();
}
}
private void SortBtn_Click(object sender, EventArgs e)
{
bool inorder = false;
while (!inorder)
{
inorder = true;
for (int i = 1; i <= 1000; i++)
{
if (swap(ref i, ref i + 1))
inorder = false;
}
}
for (int i = 1; i <= 1000; i++)
{
nbr = num.Next(0, 5001);
SortBox.Text = SortBox.Text + line + nbr.ToString();
}
}
private bool swap(ref int top, ref int bottom)
{
int temp;
if (top <= bottom)
return false;
temp = top;
top = bottom;
bottom = temp;
return true;
}
}
}
My original plan was to have the form have a button for generating the numbers and a button for sorting the numbers with two textboxes to list down the numbers.The code in my btnGenerate_Click works fine for generating the 1000 different numbers. But I am having a difficulty figuring out how I can input the bubble sort algorithm into this program. I looked up many examples online on what to do but many of the examples involve a array list which im not using. The program I have right now for SortBtn_Click obviously doesnt work. If anyone can give me suggestion on how to make it work or a easier way to create this program please let me know! I appreciate all the help anyone is willing to provide.
You can follow below steps to fix your issue:
Instead of creating new random number in SortBtn_Click function, use text present in textNumber textbox.
In SortBtn_Click function, First check textNumber is null or empty. If the string is null or empty, then throw an error.
In else part, split string and convert it into integer array.
you can split string using following code.
string[] strArr = textNumber.Text.split(Environment.NewLine);
Now convert string array into integer array.
int[] intArr = Array.ConvertAll(strArr, Int32.Parse);
Now apply bubble sort on intArr variable, store result in SortBox.Text text field
Note: As #JohnG mentioned about variables used in btnGenerate_Click (num, line, nbr) goes out of scope when execution leaves btnGenerate_click function. So you can not use those variables into other function. If you want to use those variables then declare that variables in class scope(Global declaration)

how to put string into an array C#

i need to put the contents of an text box that is a string into an array.
i have seen lots of people asking how to put each letter as an index in the array but i want the whole string in one index.
for context
i am making an application for a hotel booking for an assignment, it takes a name, room number and length of stay. it also stores room size with radio buttons. then there is another button and a textbox that when you type a room size (Single, double or triple) it will display how many people have book that room type and the name on the booking.
any help would be greatly appreciated. here is what i have done and i picture of what the application is meant to look like.
namespace Assignment2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// MessageBox.Show("Initalize");
}
string[] CusName = new string[150];
int[] RNumber = new int[150];
int[] nights = new int[150];
string[] RSize = new string[150];
string name;
bool blnnumcheck;
bool blnNightsCheck;
private void Form1_Load(object sender, EventArgs e)
{
// MessageBox.Show("Load");
}
private void TxtName_TextChanged(object sender, EventArgs e)
{
name = TxtName.Text;
}
private void btnConfirm_Click(object sender, EventArgs e)
{
string size;
int Roomnum, night;
blnNightsCheck = int.TryParse(txtLengthofStay.Text, out night);
if (!System.Text.RegularExpressions.Regex.IsMatch(TxtName.Text, "([a-zA-Z])"))
{
MessageBox.Show("Invalid Name Please try again");
}
blnnumcheck = int.TryParse(txtRoomNumber.Text, out Roomnum);
if (!blnnumcheck )
{
MessageBox.Show("Invalid Room Number Please try again" );
}
if (Roomnum >= 150)
{
MessageBox.Show("Invalid Room Number Please try again");
}
}
}
}
this what the completed one is supposed to look like
try this:
List<string> myArray = new List<string>();
myArray.Add(myTextBox.Text);
string data = "Hello, Good Morning";
string[] stringArray = new string[]{ data };
Console.WriteLine(stringArray[0]);
If you know how to create arrays, continue reading, if you don't, jump to the content below the horizontal line.
You create an int array using int[], right? So if you want to create a string array, use string[]!
Here is more code:
string[] myArray = new string[10];
//add stuff into the array
myArray[0] = "Hello";
myArray[1] = "World";
//etc
That is simple enough, right? You can do all the things you can do with an int array to a string array.
If you don't know how to create an array, start to read here
You declare an array like this:
type[] array_name = new type[length];
And you can put stuff in the array like this:
array_name[index] = some_stuff;
Thus, you can create an array of strings like this:
string[] myArray = new string[10];
//add stuff into the array
myArray[0] = "Hello";
myArray[1] = "World";
//etc
Just remember, whatever type you want an array to be, write whatever type followed by [] and give it a name!
You can loop through a 2D array like this:
for (int i = 0 ; i < maxX ; i++) { // maxX is the maximum index of the array in the first dimension
for (int j = 0 ; j < maxY ; j++) {
//you can access the array here with array[i][j]
}
}

word search puzzle game

I am trying to create a word search game. the problem is I am unable to insert words into a TableLayoutPanel. When I wrote this, I got a compile error that says "no overload for method 'placewords' takes '5' arguments.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Random r = new Random();
for (int a = 0; a < tableLayoutPanel1.ColumnCount; a++)
{
for (int b = 0; b < tableLayoutPanel1.RowCount; b++)
{
Label nl = new Label();
int x = r.Next(65, 90);
char c = (char)x;
nl.Text = c.ToString();
tableLayoutPanel1.Controls.Add(nl, a, b);
}
}
}
private void newGameToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Restart();
}
private void PlaceWords()
{
string[] words = { "byte", "char" };
Random rn = new Random();
foreach (string p in words)
{
String s = p.Trim();
bool placed = false;// continue trying to place the word in // the matrix until it fits
while (placed == false)// generate a new random row and column
{
int nRow = rn.Next(30);// generate a new random x & y direction vector
int nCol = rn.Next(30);// x direction: -1, 0, or 1
int nDirX = 0; // y direction -1, 0, or 1
int nDirY = 0; // (although direction can never be 0, 0, this is null)
while (nDirX == 0 && nDirY == 0)
{
nDirX = rn.Next(3) - 1;
nDirY = rn.Next(3) - 1;
}
placed =PlaceWords(s.ToUpper(),nRow,nCol,nDirX,nDirY);
}
}
}
Your PlaceWords method doesn't accept that many parameters, in fact, it accepts no parameters.
Further more, the way it looks, your PlaceWords is a recursive function that won't exit, leading to a stack overflow.
To fix this, you need to create a second PlaceWords function that accepts all 5 parameters, and does whatever PlaceWords does, and returns a boolean.
It looks like your nested for loops in Form1_Load should be placing random characters into tableLayoutPanel1. You then need to call PlaceWords() which will determine the location and direction to place each word in the words list. Near the end of PlaceWords you are calling PlaceWords(s.ToUpper(),nRow,nCol,nDirX,nDirY) which is supposed to actually put the word into tableLayoutPanel1. This second PlaceWords with 5 parameters should have a different name (I suggest PlaceString); it should not be trying to call the same Placewords method that it is in.
You need to then write the method PlaceString that will look like:
public bool PlaceString(string s, int nRow, int nCol, int nDirX, int nDirY)
{
/* whatever code you need to put the string into tableLayoutPanel1 */
}

Categories

Resources