|
Since you have removed the two messages below, I will respond to this one. Please note well: this is your homework assignment and you are expected to do the work. Designing and writing your own code is what a developer's job is all about. Trying to get other people to do it for you is not acceptable - in any occupation.
|
|
|
|
|
He didn't - they went to moderation - I suspect it's become sentient and is considering him a Help Vampire ...
I'll tidy up the spare.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
Might be due to the spam filter - I've fallen victim to it before. However, this question reminds me of a question I saw in the "Unanswered Questions" section today which I can't seem to find anymore. +1 for the homework statement as this problem has obviously been given no thought by the poster. Given effort I'd try to help as would most of CP I assume.
|
|
|
|
|
We do not do your HomeWork.
HomeWork is not set to test your skills at begging other people to do your work, it is set to make you think and to help your teacher to check your understanding of the courses you have taken and also the problems you have at applying them.
Any failure of you will help your teacher spot your weaknesses and set remedial actions.
So, give it a try, reread your lessons and start working. If you are stuck on a specific problem, show your code and explain this exact problem, we might help.
As programmer, your job is to create algorithms that solve specific problems and you can't rely on someone else to eternally do it for you, so there is a time where you will have to learn how to. And the sooner, the better.
When you just ask for the solution, it is like trying to learn to drive a car by having someone else training.
Creating an algorithm is basically finding the maths and make necessary adaptation to fit your actual problem.
Pavlex4 wrote: How to make program that from given numbers calculate give value or if he can't calculate that value he should find closest to that value? Build an algorithm that try every possible combinations of the numbers and allowed operations and remember best result.
Patrice
“Everything should be made as simple as possible, but no simpler.” Albert Einstein
|
|
|
|
|
 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[^]
|
|
|
|