Select random record from combobox - c#-4.0

How to select random item from a combo box, without selecting what is there already in the combobox.

I guess you want something like this:
Random random = new Random();
int newIndex = -1;
do {
newIndex = random.Next(comboBox.Items.Count);
} while (newIndex == comobBox.SelectedIndex && comboBox.Items.Count > 1);
comobBox.SelectedIndex = random.Next(comboBox.Items.Count);

Basically Combo box has items in string so if you can describe me some clear then we may help more anyway here is sample code
n you can do it
ComboBox b = new ComboBox();
Random rt = new Random();
string myText = "";
myText = b.Items[rt.Next(0, b.Items.Count - 1)].ToString();

You should use the Random class to get a random number between 0 and the max amount of items in the combobox. You should get this number repeatedly until you get one that doesn't match what is already selected within the combobox, like so:
Random random = new Random();
int newSelectedIndex = comboBox.SelectedIndex;
while (newSelectedIndex == comboBox.SelectedIndex) {
newSelectedIndex = random.Next(0, comboBox.Items.Count);
}
comboBox.SelectedIndex = newSelectedIndex;
// Item
// comboBox.Items[newSelectedIndex];
This may not work C/P'd, as I wrote it from the top of my head and don't have an IDE to test right now, but I hope you get the idea.
IMPORTANT: If you only have 1 item which is also selected, this may get into an endless loop...

Related

Loop with no duplicate values

Description of the problem.
Choose a number between 0 and 4 (the randomly number will indicate how many values from the list will be displayed)
Get random values from list, so that they are unique and display as a result.
My code does not work, please let me know how to fix it. I will be grateful for your help.
import groovy.json.JsonOutput
import java.util.Random
Random random = new Random()
def num = ["0","1","2","3","4"]
def randomNum = random.nextInt(num.size())
def min = 0;
def max = num[randomNum];
def list = ["Toy", "Mouse", "Cup","Book","Tiger"]
while(max > min) {
def randomValue = random.nextInt(list.size())
def theValue = list[randomValue] + '"'+ "," +
max++;
}
The result that I would like to achieve is for example:
Toy","Cup (if 2 is randomly selected)
Toy","Tiger","Book" (if 3 is randomly selected)
the available number is from 0 to 4 as many as there are possible
elements to choose from 0 - Toy, 1 - Mouse 2- Cup 3- Book 4 - tiger.
First, a number, e.g. 2, is drawn and then 2 elements are selected
randomly from the list of values.
You could do something like this:
Random random = new Random()
def list = ["Toy", "Mouse", "Cup","Book","Tiger"]
// this allows zero to be selected... if that is a violation
// of the requirement, adjust this....
int numberOfElementsToSelect = random.nextInt(list.size())
def results = []
numberOfElementsToSelect.times {
results << list.remove(random.nextInt(list.size()))
}
println results
println results.join(',')
EDIT:
Works great, I have one more question what to do to exit the script
without showing any results in case the value is empty
If you want to exit the script without showing results, you could do something like this:
Random random = new Random()
def list = ["Toy", "Mouse", "Cup","Book","Tiger"]
// this allows zero to be selected... if that is a violation
// of the requirement, adjust this....
int numberOfElementsToSelect = random.nextInt(list.size())
def results = []
numberOfElementsToSelect.times {
results << list.remove(random.nextInt(list.size()))
}
if(results) {
// do what you want with the results, like...
println results.join(',')
} else {
// do something else, could be exit the script...
System.exit(-2)
}

Android: Passing Checked items from a ListView to another activity with a ListView

I am trying to pass checked items from one listview to another listview in a separate activity. Ideally, the user would click all of the items they wanted, then click a button; then, the button would take all of the items from the rows clicked to the new activity. The problem that I keep having is when I click on the row; all of the information shows up on the next activity instead of the individual rows there were selected.
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adapterTwo.setCheckBox(position);
adapterTwo.notifyDataSetChanged();
}
});
practiceFinal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String entry = "";
String judge ="";
Integer points = 0;
Integer work = 0;
Integer design = 0;
Integer doc = 0;
Integer pres= 0;
Integer safety= 0;
Integer diff = 0;
String ribbon ="";
Intent intent = new Intent(CSS.this, FinalCSS.class);
for (Team hold: adapterTwo.getTeamArrayList())
{
if (hold.isChecked())
{
}
else
{
entry += " "+ hold.getEntryNumber();
judge += hold.getTeamJudgeNumber();
points+= hold.getTotalPoints();
work+= hold.getWorkmanship();
design += hold.getDesign();
doc += hold.getDocumnetation();
pres+= hold.getPresentation();
safety += hold.getSafety();
diff += hold.getDifficulty();
ribbon += hold.getRibbon();
intent.putExtra( "KeyEntry", entry);
intent.putExtra("KeyJudge", judge);
intent.putExtra("KeyPoints", points);
intent.putExtra("KeyWork", work);
intent.putExtra("KeyDesign", design);
intent.putExtra("KeyDoc",doc);
intent.putExtra("KeyPres", pres);
intent.putExtra("KeySafety", safety);
intent.putExtra("KeyRibbon", ribbon);
intent.putExtra("KeyDiff", diff);
}
}
startActivity(intent);
}
});
listView = findViewById(R.id.listViewFinal);
teamsList= new ArrayList<>();
String entry = getIntent().getStringExtra("KeyEntry");
String judge=getIntent().getStringExtra("KeyJudge");
Integer points= getIntent().getIntExtra("KeyPoints",0);
Integer workmanship=getIntent().getIntExtra("KeyWork",0);
Integer design=getIntent().getIntExtra("KeyDesign",0);
Integer documentation =getIntent().getIntExtra("KeyDoc",0);
Integer pres = getIntent().getIntExtra("KeyPres",0);
Integer difficulty =getIntent().getIntExtra("KeyDiff",0);
Integer safety =getIntent().getIntExtra("KeySafety",0);
String ribbon= getIntent().getStringExtra("KeyRibbon");
Team teams = null;
teams = new Team(judge,entry,points, workmanship,design,documentation,pres,difficulty,safety,ribbon,true);
teamsList.add(teams);
Team teamsT = null;
teamsT = new Team(judge,entry,points, workmanship,design,documentation,pres,difficulty,safety,ribbon,true);
teamsList.add(teamsT);
TeamAdapterTwo adapterTwo = new TeamAdapterTwo(FinalCSS.this, teamsList);
listView.setAdapter(adapterTwo);
Second ActivityFirst ActivitySecond Activity
You are concatenate the information on a global variable. Thus, if we trace the points attribute evolution, we have:
points = 0
points += 1 (points = 1)
points += 2 (points = 3)
points += 3 (points = 6)
points += 4 (points = 10)
Moreover, intent.putExtra erase the old value associated to a key, so at each iteration of the loop, you are replacing the old value of points by the new one. Therefore, at the end, you will give points = 10 to the second Activity.
You have two options:
Create a unique key for each hold but it will not be easy for the second Activity to know this unique key.
Instead of put an integer as extra, put an array of integers (I recommend this way)
However, you seem to have an other issue because the final value of points is the sum of all lines rather than the sum of the checked ones.

AS3 "Advanced" string manipulation

I'm making an air dictionary and I have a(nother) problem. The main app is ready to go and works perfectly but when I tested it I noticed that it could be better. A bit of context: the language (ancient egyptian) I'm translating from does not use punctuation so a phrase canlooklikethis. Add to that the sheer complexity of the glyph system (6000+ glyphs).
Right know my app works like this :
user choose the glyphs composing his/r word.
app transforms those glyphs to alphanumerical values (A1 - D36 - X1A, etc).
the code compares the code (say : A5AD36) to a list of xml values.
if the word is found (A5AD36 = priestess of Bast), the user gets the translation. if not, s/he gets all the possible words corresponding to the two glyphs (A5A & D36).
If the user knows the string is a word, no problem. But if s/he enters a few words, s/he'll have a few more choices than hoped (exemple : query = A1A5AD36 gets A1 - A5A - D36 - A5AD36).
What I would like to do is this:
query = A1A5AD36 //word/phrase to be translated;
varArray = [A1, A5A, D36] //variables containing the value of the glyphs.
Corresponding possible words from the xml : A1, A5A, D36, A5AD36.
Possible phrases: A1 A5A D36 / A1 A5AD36 / A1A5A D36 / A1A5AD36.
Possible phrases with only legal words: A1 A5A D36 / A1 A5AD36.
I'm not I really clear but to things simple, I'd like to get all the possible phrases containing only legal words and filter out the other ones.
(example with english : TOBREAKFAST. Legal = to break fast / to breakfast. Illegal = tobreak fast.
I've managed to get all the possible words, but not the rest. Right now, when I run my app, I have an array containing A1 - A5A - D36 - A5AD36. But I'm stuck going forward.
Does anyone have an idea ? Thank you :)
function fnSearch(e: Event): void {
var val: int = sp.length; //sp is an array filled with variables containing the code for each used glyph.
for (var i: int = 0; i < val; i++) { //repeat for every glyph use.
var X: String = ""; //variable created to compare with xml dictionary
for (var i2: int = 0; i2 < val; i2++) { // if it's the first time, use the first glyph-code, else the one after last used.
if (X == "") {
X = sp[i];
} else {
X = X + sp[i2 + i];
}
xmlresult = myXML.mot.cd; //xmlresult = alphanumerical codes corresponding to words from XMLList already imported
trad = myXML.mot.td; //same with traductions.
for (var i3: int = 0; i3 < xmlresult.length(); i3++) { //check if element X is in dictionary
var codeElement: XML = xmlresult[i3]; //variable to compare with X
var tradElement: XML = trad[i3]; //variable corresponding to codeElement
if (X == codeElement.toString()) { //if codeElement[i3] is legal, add it to array of legal words.
checkArray.push(codeElement); //checkArray is an array filled with legal words.
}
}
}
}
var iT2: int = 500 //iT2 set to unreachable value for next lines.
for (var iT: int = 0; iT < checkArray.length; iT++) { //check if the word searched by user is in the results.
if (checkArray[iT] == query) {
iT2 = iT
}
}
if (iT2 != 500) { //if complete query is found, put it on top of the array so it appears on top of the results.
var oldFirst: String = checkArray[0];
checkArray[0] = checkArray[iT2];
checkArray[iT2] = oldFirst;
}
results.visible = true; //make result list visible
loadingResults.visible = false; //loading screen
fnPossibleResults(null); //update result list.
}
I end up with an array of variables containing the glyph-codes (sp) and another with all the possible legal words (checkArray). What I don't know how to do is mix those two to make legal phrases that way :
If there was only three glyphs, I could probably find a way, but user can enter 60 glyphs max.

How to Multiply Data Gridview two columns and show the result in another column

I have a gridview (Order) with three columns:
Price
Quantity
Total
I want to multiply Price with Quantity and show the result in Total column of dataGridview.
Remember: my dataGridview isn't bind with any table.
I am trying this code to achieve my goal but this isn't working means value isn't being returned:
private void totalcal()
{
// is the foreach condition true? Remember my gridview isn't bound to any tbl
foreach (DataGridViewRow row in gvSale.Rows)
{
int a = Convert.ToInt32(row.Cells[3].Value) * Convert.ToInt32(row.Cells[4].Value); // value is null why??
row.Cells[5].Value = a;
}
}
This is the method which I am calling on a button click. (It is not working reason define inside of my code above)
And plus I want to know which is the suitable Datagridview event for this calculation?? I don't want to calculate the total on button click
try
int.Parse(row.Cells[3].Value.toString()) * int.Parse(row.Cells[4].Value.toString())
insted of
Convert.ToInt32(row.Cells[3].Value) * Convert.ToInt32(row.Cells[4].Value)
And you know you can call this method anytime, if you dont want it to be with button click. Call it after gvSale's row populating operations finished.
EDIT
I guess you want the calculations to be done while the user is entering Price or Quanitity. For that you need to write a EditingControlShowing method for your datagridview. Here's a piece of code. I tested it actually and got it working.
Add this code in your main class definition after InitializeComponent(); line
gvSale.EditingControlShowing += new System.Windows.Forms.DataGridViewEditingControlShowingEventHandler(this.gvSale_EditingControlShowing);
And then add this methods :
TextBox tb = new TextBox(); // this is just a textbox to use in editing control
int Price_Index = 3; // set this to your Price Column Index
int Quantity_Index = 4; // set this to your Quantity Column Index
int Total_Index = 5; // set this to your Total Column Index
private void gvSale_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (gvSale.CurrentCell.ColumnIndex == Price_Index || gvSale.CurrentCell.ColumnIndex == Quantity_Index)
{
tb = e.Control as TextBox;
tb.KeyUp += new KeyEventHandler(Calculate_Total);
}
}
private void Calculate_Total(object sender, KeyEventArgs e)
{
int Price_Value = 0;
int Quantity_Value = 0;
int.TryParse(gvSale.CurrentCell.ColumnIndex != Price_Index ? gvSale.CurrentRow.Cells[Price_Index].Value.ToString() : tb.Text, out Price_Value);
int.TryParse(gvSale.CurrentCell.ColumnIndex != Quantity_Index ? gvSale.CurrentRow.Cells[Quantity_Index].Value.ToString() : tb.Text, out Quantity_Value);
gvSale.CurrentRow.Cells[Total_Index].Value = Price_Value * Quantity_Value;
}

Count the number of frequency for different characters in a string

i am currently tried to create a small program were the user enter a string in a text area, clicks on a button and the program counts the frequency of different characters in the string and shows the result on another text area.
E.g. Step 1:- User enter:- aaabbbbbbcccdd
Step 2:- User click the button
Step 3:- a 3
b 6
c 3
d 1
This is what I've done so far....
public partial class Form1 : Form
{
Dictionary<string, int> dic = new Dictionary<string, int>();
string s = "";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
s = textBox1.Text;
int count = 0;
for (int i = 0; i < s.Length; i++ )
{
textBox2.Text = Convert.ToString(s[i]);
if (dic.Equals(s[i]))
{
count++;
}
else
{
dic.Add(Convert.ToString(s[i]), count++);
}
}
}
}
}
Any ideas or help how can I countinue because till now the program is giving a run time error when there are same charachter!!
Thank You
var lettersAndCounts = s.GroupBy(c=>c).Select(group => new {
Letter= group.Key,
Count = group.Count()
});
Instead of dic.Equals use dic.ContainsKey. However, i would use this little linq query:
Dictionary<string, int> dict = textBox1.Text
.GroupBy(c => c)
.ToDictionary(g => g.Key.ToString(), g => g.Count());
You are attempting to compare the entire dictionary to a string, that doesn't tell you if there is a key in the dictionary that corresponds to the string. As the dictionary never is equal to the string, your code will always think that it should add a new item even if one already exists, and that is the cause of the runtime error.
Use the ContainsKey method to check if the string exists as a key in the dictionary.
Instead of using a variable count, you would want to increase the numbers in the dictionary, and initialise new items with a count of one:
string key = s[i].ToString();
textBox2.Text = key;
if (dic.ContainsKey(key)) {
dic[key]++;
} else {
dic.Add(key, 1);
}
I'm going to suggest a different and somewhat simpler approach for doing this. Assuming you are using English strings, you can create an array with capacity = 26. Then depending on the character you encounter you would increment the appropriate index in the array. For example, if the character is 'a' increment count at index 0, if the character is 'b' increment the count at index 1, etc...
Your implementation will look something like this:
int count[] = new int [26] {0};
for(int i = 0; i < s.length; i++)
{
count[Char.ToLower(s[i]) - int('a')]++;
}
When this finishes you will have the number of 'a's in count[0] and the number of 'z's in count[25].

Resources