I am preparing a tutorial to solve the generating parentheses problem. (LeetCode #22) LeetCode mentions three different solutions but the third one looks confusing to me. I think that 3rd solution can be improved by dynamic programming. I wrote these two solutions but I am not sure about the time/space complexities. Could you please explain how we can find the complexities and compare two solutions? Thanks.
// Recursion
public static List<String> generateParentheses(int n) {
List<String> list = new ArrayList<String>();
if(n == 0){
list.add("");
}
for(int k = 0; k < n; k++){
for(String left : generateParentheses(k)){
for(String inside : generateParentheses(n-k-1)){
list.add(left + "(" + inside + ")");
}
}
}
return list;
}
// DP
public static List<String> generateParentheses(int n) {
Map<Integer,List<String>> solutions = new HashMap<Integer,List<String>>();
solutions.put(0, Arrays.asList(""));
for(int k = 1; k <= n; k++){
List<String> list = new ArrayList<String>();
for(int i = 0; i < k; i++){
for(String left : solutions.get(i)){
for(String inside : solutions.get(k-i-1)){
list.add(left + "(" + inside + ")");
}
}
}
solutions.put(k, list);
}
return solutions.get(n);
}
Related
i have a table full of object(type) when i click "liste des vihicules" i'de like to go to a table full of obeject(vehicule) with this condition:
vihicule.nom_type=type.nom_type
to do this i used this code
////go to vehicule list
#RequestMapping(value="/liste/{nom_type}")
public String listvih(#PathVariable(value = "nom_type") String nom_type, Model model) {
List<Vihicule> l = vihiculeRepository.findAll();
List<Vihicule> l1= null;
for(int i=0; i<l.size(); i++)
{ if(l.get(i).getNom_type()==nom_type)
{
l1.add(i, l.get(i));
}
}
model.addAttribute("v", l1);
return "liste";
}
but it always show an emty table. what could be the problem, please help
update: i did some changes in the code and now everything work fine
#RequestMapping(value="/liste/{nom_type}")
public String listvih(#PathVariable(value = "nom_type") String nom_type, Model model) {
List<Vihicule> l =vihiculeRepository.findAll();
List<Vihicule> l1 = new ArrayList<Vihicule>();
for(int i=0;i<l.size();i++)
{
if(l.get(i).getNom_type().equals(nom_type))
{int j=0;
l1.add(j, l.get(i));
j++;
}
}
model.addAttribute("v",l1);
return "liste";
}
Is it possible to render in one progressbar the progress of 2 nested tasks?
I mean, if I have to read lines from several files in several directories. I have this snippet code:
EDIT:
final int steps = directories.size();
Task<Integer> task2 = new Task<Integer>() {
/**
*/
#Override
protected Integer call() throws Exception {
int len = files.length;
updateProgress(0, len);
for(int i = 0; i < files.length; i++) {
final String filename = files[i].getName();
final String file = files[i].getPath();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
}
String currentLine = null;
while ((currentLine = br.readLine()) != null) {
readlines(currentLine, filename);
}
} catch (IOException xs) {
xs.getMessage();
}
System.out.println("******* Working on: " + file + " ******************************");
updateProgress(i + 1, files.length);
}
System.out.println("done: " + directoryName);
return len;
}
};
task2.setOnRunning(r -> {
DoubleBinding totalProgress = null;
for(int i = 0; i < steps; i++) {
DoubleBinding increment = task2.progressProperty().divide(steps);
if (totalProgress == null) {
totalProgress = increment;
} else {
totalProgress = totalProgress.add(increment);
}
}
progressBar.progressProperty().bind(totalProgress);
status.textProperty().bind(task2.stateProperty().asString());
statusProcess.textProperty().bind(Bindings.when(totalProgress.isEqualTo(-1))
.then("0.00")
.otherwise(task2.progressProperty().multiply(100.00).asString("%.02f %%")));
console.textProperty().bind(task2.messageProperty());
});
new Thread(task2).start();
I am enable to access progress bar but as long as I have directories, the progress bar will restart to 0 and will check for files into the next directory and then populate the progress bar until 1 and then restart to 0 if there is another directory.
How can I do if I want to display these 2 tasks in one as I don't want to restart from 0 when the next directory is reading. If I have for example 4 directories, I expect to see a moving the progressbar until its quarter and so on.
Is anybody as an idea what I am doing wrong?
You can do something like
progressBar.progressProperty().bind(Bindings.createDoubleBinding(
() -> Math.max(0, task1.getProgress()) / 2 + Math.max(0, task2.getProgress()) /2 ,
task1.progressProperty(), task2.progressProperty());
If you can easily estimate or compute the relative times each task will take, you can weight the progress of each task accordingly, instead of simply averaging them as in the code above.
Do you think following code can be optimized more?
I am using two for loops, which I think it can be reduced to something better. Any suggestions are welcome.
public ArrayList<Integer> rotateArray(ArrayList<Integer> A, int B) {
ArrayList<Integer> ret = new ArrayList<Integer>();
B = B % A.size();
boolean flag = false;
for (int i = B; i < A.size(); i++) {
ret.add(A.get(i));
}
for (int i = 0; i < B; i++) {
ret.add(A.get(i));
}
return ret;
}
}
If you are rather asking for an algorithm, of course there are better ways to achieve it. Think on the lines of :
You are given a function that takes input three parameters :
an array,
a start index
and an end index
and then returns the same array after reversing the elements between these start and end indices.
Something like :
func([1,2,3,4,5],2,4) ==> 1,2,5,4,3
how would you use this function to achieve the required output?
I want to check if an IP address is in a certain range, matching by "*" only. For example, "202.121.189.8" is in "202.121.189.*".
The scenario is that I have a list of banned IPs, some of them contains "*", so I wrote a function, it works fine so far:
static bool IsInRange(string ip, List<string> ipList)
{
if (ipList.Contains(ip))
{
return true;
}
var ipSets = ip.Split('.');
foreach (var item in ipList)
{
var itemSets = item.Split('.');
for (int i = 0; i < 4; i++)
{
if (itemSets[i] == "*")
{
bool isMatch = true;
for (int j = 0; j < i; j++)
{
if (ipSets[i - j - 1] != itemSets[i - j - 1])
{
isMatch = false;
}
}
if (isMatch)
{
return true;
}
}
}
}
return false;
}
Test code:
string ip = "202.121.189.8";
List<string> ipList = new List<string>() { "202.121.168.25", "202.121.189.*" };
Console.WriteLine(IsInRange(ip, ipList));
But I think what i wrote is very stupid, and I want to optimize it, does anyone have an idea how to simplify this function? not to use so many "for....if...".
A good idea would be to represent the banned subnets in a form of a pair: mask + base address. So your check will look like that:
banned = (ip & mask == baseaddress & mask);
For 11.22.33.* the base address will be 11*0x1000000 + 22*0x10000 + 33*0x100, mask will be 0xffffff00.
For single address 55.44.33.22 the address will be 55*0x1000000 + 44*0x10000 * 33*0x100 + 22, mask will be 0xffffffff.
You'll need to convert the address to a 32-bit int as a separate procedure.
After that all, your code will look like that:
int numip = ip2int(ip);
bool isIpBanned = banList.Any(item =>
numip & item.mask == item.baseaddress & item.mask);
By the way, this way you'll be able to represent even bans on smaller subsets.
int ip2int(string ip) // error checking omitted
{
var parts = ip.Split('.');
int result = 0;
foreach (var p in parts)
result = result * 0x100 + int.Parse(p);
}
class BanItem { public int baseaddres; public int mask; }
BanItem ip2banItem(string ip)
{
BanItem bi = new BanItem() { baseaddres = 0, mask = 0 };
var parts = ip.Split('.');
foreach (var p in parts)
{
bi.baseaddress *= 0x100;
bi.mask *= 0x100;
if (p != "*")
{
bi.mask += 0xff;
bi.baseaddress += int.Parse(p);
}
}
return bi;
}
banList = banIps.Select(ip2banItem).ToList();
I think you should keep a separate list for IP with * and those without asterick.
say IpList1 contains IP's without *
and
IpList2 --those contain * ..actually what we will be storing is the part before .* in this list. for e.g. 202.121.189.* would be stored as 202.121.189 only..
Thus for a given IP addrerss you just need to check for that IP address in IpList1,if it is not found over there then
for each Ip in IPList 2 you need to check whether it is a substring of input IP or not.
Thus no requirement of complex for and if loops.
Written In Java (Untested):
static boolean IsInRange(String ip, Vector<String> ipList) {
int indexOfStar = 0;
for (int i=0; i<ipList.size(); i++) {
if (ipList.contains("*")) {
indexOfStar = ipList.indexOf("*");
if ((ip.substring(0, indexOfStar)).equals(ipList.get(i).substring(0, indexOfStar))) {
return true;
}
}
}
return false;
}
I would use a space filling curve like in the xkcd comic: http://xkcd.com/195/. It's the function H(x,y) = (H(x),H(y)) and it reduces the 2 dimension to 1 dimension. It would also show that you are a real b*** coder.
I have some issues with Arduino about how to match text.
I have:
String tmp = +CLIP: "+37011111111",145,"",,"",0
And I am trying to match:
if (tmp.startsWith("+CLIP:")) {
mySerial.println("ATH0");
}
But this is not working, and I have no idea why.
I tried substring, but the result is the same. I don't know how to use it or nothing happens.
Where is the error?
bool Contains(String s, String search) {
int max = s.length() - search.length();
for (int i = 0; i <= max; i++) {
if (s.substring(i) == search) return true; // or i
}
return false; //or -1
}
Otherwise you could simply do:
if (readString.indexOf("+CLIP:") >=0)
I'd also recommend visiting:
https://www.arduino.cc/en/Reference/String
I modified the code from gotnull. Thanks to him to put me on the track.
I just limited the search string, otherwise the substring function was not returning always the correct answer (when substrign was not ending the string). Because substring search always to the end of the string.
int StringContains(String s, String search) {
int max = s.length() - search.length();
int lgsearch = search.length();
for (int i = 0; i <= max; i++) {
if (s.substring(i, i + lgsearch) == search) return i;
}
return -1;
}
//+CLIP: "43660417XXXX",145,"",0,"",0
if (strstr(command.c_str(), "+CLIP:")) { //Someone is calling
GSM.print(F("ATA\n\r"));
Number = command.substring(command.indexOf('"') + 1);
Number = Number.substring(0, Number.indexOf('"'));
//Serial.println(Number);
} //End of if +CLIP:
This is how I'm doing it. Hope it helps.
if (tmp.startsWith(String("+CLIP:"))) {
mySerial.println("ATH0");
}
You can't put the string with quotes only you need to cast the variable :)