|
 Here is the code,but how to not use all values to make expression and how to if computer cannot find target number to make expression for closest to target value?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Expression_Evaluator
{
class Program
{
static int[] ReadInput(out int value)
{
Console.Write("Enter integer numbers to use (space-separated): ");
string s = Console.ReadLine();
string[] parts = s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
int[] a = new int[parts.Length];
for (int i = 0; i < a.Length; i++)
a[i] = int.Parse(parts[i]);
Console.Write("Enter integer value to calculate: ");
value = int.Parse(Console.ReadLine());
return a;
}
static void SolveAndPrint(int[] numbers, int targetValue)
{
int targetKey = (targetValue << numbers.Length) + (1 << numbers.Length) - 1;
HashSet<int> solvedKeys = new HashSet<int>();
Dictionary<int, int> keyToLeftParent = new Dictionary<int, int>();
Dictionary<int, int> keyToRightParent = new Dictionary<int, int>();
Dictionary<int, char> keyToOperator = new Dictionary<int, char>();
Queue<int> queue = new Queue<int>();
for (int i = 0; i < numbers.Length; i++)
{
int key = (numbers[i] << numbers.Length) + (1 << i);
solvedKeys.Add(key);
queue.Enqueue(key);
}
while (queue.Count > 0 && !solvedKeys.Contains(targetKey))
{
int curKey = queue.Dequeue();
int curMask = curKey & ((1 << numbers.Length) - 1);
int curValue = curKey >> numbers.Length;
int[] keys = new int[solvedKeys.Count];
solvedKeys.CopyTo(keys);
for (int i = 0; i < keys.Length; i++)
{
int mask = keys[i] & ((1 << numbers.Length) - 1);
int value = keys[i] >> numbers.Length;
if ((mask & curMask) == 0)
{
for (int op = 0; op < 6; op++)
{
char opSign = '\0';
int newValue = 0;
switch (op)
{
case 0:
newValue = curValue + value;
opSign = '+';
break;
case 1:
newValue = curValue - value;
opSign = '-';
break;
case 2:
newValue = value - curValue;
opSign = '-';
break;
case 3:
newValue = curValue * value;
opSign = '*';
break;
case 4:
newValue = -1;
if (value != 0 && curValue % value == 0)
newValue = curValue / value;
opSign = ' ';
break;
case 5:
newValue = -1;
if (curValue != 0 && value % curValue == 0)
newValue = value / curValue;
opSign = ' ';
break;
}
if (newValue >= 0)
{
int newMask = (curMask | mask);
int newKey = (newValue << numbers.Length) + newMask;
if (!solvedKeys.Contains(newKey))
{
solvedKeys.Add(newKey);
if (op == 2 || op == 5)
{
keyToLeftParent.Add(newKey, keys[i]);
keyToRightParent.Add(newKey, curKey);
}
else
{
keyToLeftParent.Add(newKey, curKey);
keyToRightParent.Add(newKey, keys[i]);
}
keyToOperator.Add(newKey, opSign);
solvedKeys.Add(newKey);
queue.Enqueue(newKey);
}
}
}
}
}
}
if (!solvedKeys.Contains(targetKey))
Console.WriteLine("Solution has not been found.");
else
{
PrintExpression(keyToLeftParent, keyToRightParent, keyToOperator, targetKey, numbers.Length);
Console.WriteLine("={0}", targetValue);
}
}
static void PrintExpression(Dictionary<int, int> keyToLeftParent, Dictionary<int, int> keyToRightParent, Dictionary<int, char> keyToOperator,
int key, int numbersCount)
{
if (!keyToOperator.ContainsKey(key))
Console.Write("{0}", key >> numbersCount);
else
{
Console.Write("(");
PrintExpression(keyToLeftParent, keyToRightParent, keyToOperator,
keyToLeftParent[key], numbersCount);
Console.Write(keyToOperator[key]);
PrintExpression(keyToLeftParent, keyToRightParent, keyToOperator,
keyToRightParent[key], numbersCount);
Console.Write(")");
}
}
static void Main(string[] args)
{
while (true)
{
int value;
int[] numbers = ReadInput(out value);
SolveAndPrint(numbers, value);
Console.Write("More? (y/n) ");
if (Console.ReadLine().ToLower() != "y")
break;
}
}
}
}
modified 11-Dec-16 12:34pm.
|
|
|
|
|
Pavlex4 wrote: how to not use all values to make expression After each single operation, you have to check if the last result is a better solution against the 3 targets. If a better solution, save it, then , continue search.
Patrice
“Everything should be made as simple as possible, but no simpler.” Albert Einstein
|
|
|
|
|
I have problem with database ,I am using cyrillic words inside it and when I start program instead of random word it shows "????????????"
|
|
|
|
|
Check your data: the chances are you have set your SQL column as VARCHAR, which doesn't hold Unicode data, or - gawd forbid - you used string concatenation to load the DB with your data.
You need a NVARCHAR column for Unicode, and should always use parameterised queries.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
It was set to nvarchar(13)
|
|
|
|
|
And? How did you insert the data, how did you fetch it? How did you display it?
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
First I create table like this:
CREATE TABLE table1
(
Reci nvarchar(13)
);
And inserted data like this:
INSERT INTO table1 VALUES ('заступниство');
INSERT INTO table1 VALUES ('затровавање');
INSERT INTO table1 VALUES ('заустављати');
INSERT INTO table1 VALUES ('заварљивост');
INSERT INTO table1 VALUES ('земљорадник');
INSERT INTO table1 VALUES ('земљорадња');
INSERT INTO table1 VALUES ('згњецавање');
INSERT INTO table1 VALUES ('згусњавање');
INSERT INTO table1 VALUES ('злонамерност');
INSERT INTO table1 VALUES ('злостављати');
INSERT INTO table1 VALUES ('зверокрадица');
.........
I display it like this:
string cs= @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Pavle\Documents\Visual Studio 2015\Projects\Test slagalica\Test slagalica\Slagalica-DB-Cirilica.mdf;Integrated Security=True";
string queryString = "SELECT * FROM table1 WHERE LEN(Reci) >=10 AND LEN(Reci) <=12 ORDER BY NEWID()";
using (SqlConnection connection = new SqlConnection(cs))
{
SqlCommand mycommand = new SqlCommand(queryString, connection);
try
{
connection.Open();
string word = (string)mycommand.ExecuteScalar();
label14.Text = word;
promesana_rec = new string(word.ToUpper().OrderBy(r => random.Next()).ToArray());
textBox2.Text = promesana_rec.ToUpper();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
|
|
|
|
|
And there is your problem: those are not Unicode strings: they are VARCHAR strings, which are basically ASCII and hold eight bit characters instead of 16 bit Unicode values. NVARCHAR strings are prefixed with N:
INSERT INTO table1 (Reci) VALUES (N'заступниство');
Do yourself couple of favours as well:
1) Add two more columns to your table:
CREATE TABLE table1
(
ID [INT] IDENTITY(1,1) NOT NULL,
Reci nvarchar(13) NOT NULL,
WordLen INT NOT NULL
); Storing the word length once is a lot more efficient than processing the string length twice each time you want to retrieve it, for a minimal extra storage overhead.
2) If you only want one word, only retrieve one word:
SELECT TOP 1 Reci FROM Table1 ... Otherwise you fetch all records that match, wether you need them or not.
3) Get into the habit of listing the columns you are going to insert / select - it can save a lot of frustration later when you accidentally insert to the wrong columns because you forgot the order...
4) SqlCommand objects should also be Disposed, not just SqlConnections.
5) Don't hard code connection strings - store them in a settings file so you don't have to recompile to change the DB source.
6) Be aware that ATTACH is a special "developer" mode: you should normally let SQL handle the DB completely, and not try to ATTACH it. ATTACH only works in Express editions for just that reason...
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
When I add (N) before word it started working!!!
Thank you very much!!!
|
|
|
|
|
You're welcome!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
How to check if entered textbox value exist in SQL server Database?If it exist it should print "the entered value exist in database.
|
|
|
|
|
|
Can it be done like this:
using (SqlConnection connection = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM table1 WHERE Reci='" + textBox1.Text + "'", connection);
try
{
connection.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
int j = ds.Tables[0].Rows.Count;
if (j == 0)
{
MessageBox.Show("word" + textBox1.Text + "already exists!");
ds.Clear();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
|
|
|
|
|
Do not use string concatenation to insert values into SQL statements!
Learn to use parameterized statements.
And that is not a reasonable use case for a DataAdapter; ExecuteScalar will suffice.
modified 10-Dec-16 10:51am.
|
|
|
|
|
The basic idea is correct but few things to notice:
- you're missing using block for the SqlCommand
- you don't close the connection
- most importantly you don't use SqlParameter which leaves you open to SQL injections.
Concerning those topics, please go through Properly executing database operations[^]
Another thing is that you fetch the data into a dataset using a data adapter. While this approach does work, it contains unnecessary phases if you just need to know if the value exist or not. For that purpose SqlCommand.ExecuteScalar Method (System.Data.SqlClient)[^] should be sufficient.
As a side note, you probably should check that the input is valid. If you expect just a single word then check for whitespace and so on.
|
|
|
|
|
How to make that when user enter word using given random letters from labels in textbox,user cannot enter letter that does not exist in given letters???
For example if in label is one 'A' he can type it only once,if in labels are two 'D' he can type it only twice.
|
|
|
|
|
Trap the KeyPressed event on the textbox and write code accordingly.
|
|
|
|
|
I don't know how to make this!!!
|
|
|
|
|
Google the phrase:
c# textbox kepress event
|
|
|
|
|
I know that but I don't know how to check what characters user typed!!!
|
|
|
|
|
You don't have to!
That is why we have documentation, but you will need to learn to read that. There's an event that is fired when the user presses a key, and it will provide you with two things; the key that was pressed, and the option to cancel that.
Now go research
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Just picking one of the answers from Google which gives examples
[^]
|
|
|
|
|
WPF or Windows Forms?
I had to code a "numerics" only TextBox in WPF the other day (PreviewKeyDown event):
private void uxRunCount_PreviewKeyDown( object sender, System.Windows.Input.KeyEventArgs e ) {
bool ok = IsNumeric( e.Key );
if ( !ok ) {
e.Handled = true;
}
}
private bool IsNumeric( Key key ) {
if ( key == Key.Back || key == Key.Delete ) { return true; }
if ( key == Key.Tab || key == Key.Return ) { return true; }
if ( key >= Key.D0 && key <= Key.D9 ) { return true; }
if ( key >= Key.NumPad0 && key <= Key.NumPad9 ) { return true; }
return false;
}
|
|
|
|
|
When you write a KeyPress handler for the TextBox, you get two parameters:
private void myTextBox_KeyPress(object sender, KeyPressEventArgs e)
sender is the text box that generate the event.
e is the information on the key press.
This information includes the key pressed:
char keyPressedByUser = e.KeyChar; And Handled which is a bool which the TextBox looks at when you are finished to decide if it should treat the key as input or not. If you set it to true the Textbox will ignore the user input. If you leave it at false the TextBox will insert the character to the textbox.
You also have the Text property of the TextBox which means you can get the data currently in it.
From that and your labels, you should be able to work out how to restrict the user input just as you wanted.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
Something like this?
var allowedKeys = promesana_rec.Select(ch => (Keys)Convert.ToInt32(char.ToUpper(ch)));
e.SuppressKeyPress = !allowedKeys.Contains(e.KeyCode) && new[] { Keys.None, Keys.Shift }.Contains(e.Modifiers);
|
|
|
|