|
Very nice article. I've bookmarked it. But in my case, if I do it non recursively then I'll get 0 marks because question clearly says USE RECURSION.
|
|
|
|
|
smells a lot like homework, and we don't do other people's homework...
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
Thank you guys.
I'm very excited right now because I've just finished the question, and I did it all by myself . It took 1/2 hour to think, 1 hour to write and 1 hour to correct it using hit and trial..But finally I succeeded. I'm attaching code below, it is in java but it will still run in C# because all syntax-es are same.
public class PermutationIterator
{
private String s;
private int index = 0;
private PermutationIterator tailIterator = null;
public PermutationIterator(String s)
{
this.s = s;
if(s.length() > 0)
tailIterator = new PermutationIterator(s.substring(1));
}
public boolean hasMorePermutations()
{
if(tailIterator == null)
return false;
if(s.length() == 1)
return true;
return index != s.length() - 1 || tailIterator.hasMorePermutations();
}
public String nextPermutation()
{
if(s.length() == 1)
{
tailIterator = null;
return s;
}
if(!tailIterator.hasMorePermutations())
tailIterator = new PermutationIterator(s.substring(0, ++index) +
s.substring(index + 1));
return s.charAt(index) + tailIterator.nextPermutation();
}
}
It is still less readable because I just used hit trial thing to correct array out of bound exceptions. I've started to love recursion..There are only few things in world that gives to pain and pleasure and one of them is recursion , lol I just made that up..
Anyways, if you could improve my code and I would really appreciate it.
Thanks
Shivam K
|
|
|
|
|
I haven't checked it at all, however it looks sufficiently clean for me to trust you either have it right or could easily get it right.
one comment: I would put some parentheses in this line, to make it even more obvious:
return index != s.length() - 1 || tailIterator.hasMorePermutations();
( )
Now here is something to think about: assume there could be some duplicate characters (say street), now generate all permutations without any duplicates. I'm not claiming this is easy! I could offer a hint if you were to need one.
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
It sounds interesting and more practical. Give me hint, I'll try to work on it.
Shivam
|
|
|
|
|
think of a way to get all permutations in a simple ordered fashion, before you tackle the duplicates! It is very cheap, however it may well influence a lot of your code...
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
It still very hard to do. Let say you have string "aaabbbccc", you will get 9! combination..then you need to find repetitions using linear search for each of the element..it's gonna take too much time..is there any way of handling repetition within code so that it can be ignored and final result we get is list of length (9!/3!3!3!).
|
|
|
|
|
Shivamkalra wrote: It still very hard to do
not really.
all you need to do is, at each nesting level, not choose a letter you have already chosen at that level (in a previous iteration).
Now think. very hard, if you must.
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
oh ya, that's actually easy and makes sense too. I found a good way..if u arrange letter so that repeated letters are together then it will even easier to skips letters in each iteration ex. "aabbcc".
This way you can skip alternating alphabet in each recursion..this is really interesting..I'm gonna give it a try right now.
Thanks
Shivam
|
|
|
|
|
Shivamkalra wrote: tailIterator = new PermutationIterator(s.substring(0, ++index) + s.substring(index + 1));
While fine in C#, I don't like it a bit; in other languages (e.g.C, C++) this statement's result would be undefined, as the big + operator is commutative (*) and nothing forces the left operator to be evaluated before the right one, so the right operand can't be sure the auto-increment has already been executed. Again, C# guarantees it, but a casual reader could port it to another language and inadvertently introduce something that goes wrong on some compilers or under some circumstances!
[ADDED]
(*) well, not fully commutative like an arithmetic addition, however both string operands could be evaluated in any order before they get concatenated.
[/ADDED]
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
modified on Friday, February 25, 2011 11:34 PM
|
|
|
|
|
I have written a service and it will start and run, but it terminates itself at variable times.
In the event viewer it only says that the service has terminated unexpectedly. Is there a best practice way to log this or capture this failure? I can't seem to figure out what is causing this failure, it does not fail when I launch the exe in debug mode.
Thanks for reading, here is my main thread code if that will help.
using System;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Net;
using System.Collections;
using Microsoft.Win32;
namespace WindowsService
{
class WindowsService : ServiceBase
{
public WindowsService()
{
this.ServiceName = "Emailer";
this.EventLog.Log = "Emailer Application";
this.CanHandlePowerEvent = true;
this.CanHandleSessionChangeEvent = true;
this.CanPauseAndContinue = true;
this.CanShutdown = true;
this.CanStop = true;
}
static void Main()
{
ServiceBase.Run(new WindowsService());
Thread workerThread = new Thread(new ThreadStart(workThread));
workerThread.Start();
string logDate = dataLogging.Logging.returnDate(false, true);
}
static void workThread()
{
while (true)
{
try
{
RegistryKey scheduleEmailer = Registry.LocalMachine;
RegistryKey emailerKey = scheduleEmailer.OpenSubKey(@"SOFTWARE\s\ScheduleEmailer");
string dayOfWeek = emailerKey.GetValue("dayOfWeek").ToString();
string hourInArmyTime = emailerKey.GetValue("hourInArmyTime").ToString();
string minuteFloor = emailerKey.GetValue("minuteFloor").ToString();
string minuteCeiling = emailerKey.GetValue("minuteCeiling").ToString();
string isRunning = "false";
if ((DateTime.Now.DayOfWeek.ToString() == dayOfWeek) && (DateTime.Now.Hour == Convert.ToInt32(hourInArmyTime)) && (isRunning == "false"))
{
if ((DateTime.Now.Minute > Convert.ToInt32(minuteFloor)) && (DateTime.Now.Minute < Convert.ToInt32(minuteCeiling)) )
{
isRunning = "true";
htmParser.ScheduleParser.emailer();
string date = dataLogging.Logging.returnDate(false, true);
dataLogging.Logging.log(@"c:\program files\AllinOneService\logs\" + date + "_emaillog.txt", "*** Scheduled email has been sent out at minute " + DateTime.Now.Minute.ToString() + " . ***" + " ... Sleeping for 300 seconds" + System.Environment.NewLine, true);
Thread.Sleep(300000);
isRunning = "false";
}
}
string date2 = dataLogging.Logging.returnDate(false, true);
dataLogging.Logging.log(@"c:\program files\AllinOneService\logs\" + date2 + "_emaillog.txt", "Email wait loop occurring at minute " + DateTime.Now.Minute.ToString() + " . Registry is set to " + dayOfWeek + " " + hourInArmyTime + " " + minuteFloor + " to " + minuteCeiling + ". Comparing to " + DateTime.Now.DayOfWeek + " " + DateTime.Now.Hour + " " + DateTime.Now.Minute + " ... Sleeping for 60 seconds" + System.Environment.NewLine, true);
Thread.Sleep(60000);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
throw;
}
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
Main();
}
protected override void OnStop()
{
MessageBox.Show("Service is stopped");
base.OnStop();
}
protected override void OnPause()
{
base.OnPause();
}
protected override void OnContinue()
{
base.OnContinue();
}
protected override void OnShutdown()
{
MessageBox.Show("Service is shutdown");
base.OnShutdown();
}
protected override void OnCustomCommand(int command)
{
base.OnCustomCommand(command);
}
protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus)
{
return base.OnPowerEvent(powerStatus);
}
protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
base.OnSessionChange(changeDescription);
}
public static void scheduleEmail()
{
htmParser.ScheduleParser.emailer();
}
}
}
modified on Friday, February 25, 2011 6:32 PM
|
|
|
|
|
You need to add exception handling to your code and when an exception is throwing, Write the details to the event log.
I think someone voted the question a one because you didn't wrap the code in pre tags. Use the "code block" wrapper when submitting Q&A.
Rob
"You get that on the big jobs."
|
|
|
|
|
Hi Rob,
I edited the code, thank you.
So just to make sure I understand what you wrote, with all of my try/catches I should write the exception (ex.message) to the event log?
I have never done that, but I can google how to do that if you concur with my understanding.
|
|
|
|
|
That is right. Writing to the System.Diagnostics.EventLog is a good starting point.
catch (Exception ex)
{
EventLog myLog = new EventLog();
myLog.Source = "My Server";
myLog.WriteEntry(ex.ToString());
throw new MyServerException(3, ex, 0);
}
There are better, more configurable approaches but this will be just good enough for what you want to do.
"You get that on the big jobs."
|
|
|
|
|
Great, thank you so much Rob, I will try this on Monday
|
|
|
|
|
Here is what it said in the event log, it works fine in debug mode. Am I doing something wrong, I can't image that writing a service should be this difficult or no one would ever use services.
System.Runtime.InteropServices.COMException (0x80004004): Operation aborted (Exception from HRESULT: 0x80004004 (E_ABORT))
at Microsoft.Office.Interop.Outlook._MailItem.get_GetInspector()
at C_Outlook.sendEmail(String emailTo, String emailFrom, String emailCC, String emailBCC, String emailSubject, String emailMessage)
at htmParser.ScheduleParser.emailer()
|
|
|
|
|
Looks like that error message is due to outlook security. I don't see any good c# examples on how to use Outlook Redemption either.
|
|
|
|
|
You are using the wrong security account for your service. Read this
"You get that on the big jobs."
|
|
|
|
|
Danger danger. If there is any opportunity to avoid using Outlook, I would take it. Can't help you there other than to suggest using the the classes within the System.Net.Mail instead.
"You get that on the big jobs."
|
|
|
|
|
I will try that, although I'm pretty sure the firewall is going to block anything else
Thank you for your help with this.
|
|
|
|
|
I have Question
1-how to applay undo/redo for draw panel
2-how to draw string on panel with keypress event
3-how to make image that i draw it in panel not dipeared
even click another buttun to draw another ship
|
|
|
|
|
I have Question
1-how to applay undo/redo for draw panel
2-how to draw string on panel with keypress event
3-how to make image that i draw it in panel not dipeared
even click another buttun to draw another ship
|
|
|
|
|
The answer can be found here, on the second link on the page.
I wasn't, now I am, then I won't be anymore.
|
|
|
|
|
Please do not post the same question more than once: delete your other version before it gets a reply!
I'm not going to answer your questions directly: I don't think you are quite ready to go that far, from your questions so far. Instead, some basics which should help you to do some of it, and will set you on the right path.
At present, you are using CreateGraphics to get the Graphics object for drawing, probably in a timer event, or a loop. Am I right?
Don't do that. Instead, handle the Panel.Paint event. (Click on the panel in the designer, select events in the Properties pane - the lightning bolt button - and double click the Paint event).
In the handler routine, you have two parameters:
void panel_Paint(object sender, PaintEventArgs e)
{
}
The sender is the panel that need to be painted, and e is the information you need to know about how to paint it.
Convert the sender to a Panel, and get the Graphics object from e :
void panel_Paint(object sender, PaintEventArgs e)
{
Panel myPanel = sender as Panel;
if (myPanel != null)
{
Graphics g = e.Graphics;
}
}
Don't worry about the conversion code: it just means you can use the same method for more than one Panel if you need to.
You can now use g to draw on the Panel, and it will not disappear.
So, that solves question 3!
How do you draw text? Simple:
g.DrawString("Hello", new Font("Arial",16), Brushes.Black, new Point(0,0));
How do you make the Panel draw when you want? Simple:
myPanel.Invalidate();
Call that when you have changed the information that you want to draw - the position of the text, for example. (Don't call it in the Paint handler, that won't work!)
So that solves question 2!
Question 1 is probably way too complex at the moment - which makes me think you have asked the wrong question! If it is still a problem, try asking in more detail about what you are trying to do.
Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together.
Digital man: "You are, in short, an idiot with the IQ of an ant and the intellectual capacity of a hose pipe."
|
|
|
|
|
Hi,
Is there a way to know from the browser object, whether the mouse is on a link (clickable data) or not? What I mean is, when we move the mouse on the content displayed, we can see that the mouse cursor changes if its a link. Normally we get the hand cursor.
I would like to know, is there a way (through query or event or something) to know this information (mouse is on clickable data) from the browser object? Do we have any means to obtain this?
Also, how does it actually work? My understanding is, whenever the mouse moves on a link, the browser object informs the OS which in turn inoforms the mouse driver to re-draw the mouse arrow cursor to a hand cursor. Is my understanding correct?
Any inputs/pointers on this is really appreciated.
Thanks in advance.
|
|
|
|
|