Using regex to access values from a map in keys - regex

val m = Map("a"->2,"ab"->3,"c"->4)
scala> m.get("a");
scala> println(res.get)
2
scala> m.get(/a\.*/)
// or something similar.
Can i get a list of all key-value pairs where key contains "a" without having to iterate over the entire map , by doing something as simple as specifying a regex in the key value?
Thanks in advance!

No, you cannot do that without iterating over the entire map. In fact, I can't even think of a single data structure that would allow it, say nothing of the API.
Of course, iterating is pretty simple:
m.filterKeys(_ matches "a.*")

Related

parse URL params in Perl

I am working on some tutorials to explain things like GET/POST's and need to parse the URI manually. The follow perl code works, but I am trying to do two things:
list each key/value
be able to look up one specific value
What I do NOT care about is replacing the special chars to spaces or anything, the one value I need to get should be a number. In other languages I have used, the regular expression in question should group each key/value into one grouping with a part 1/part 2, does Perl do the same? If so, how do I put that into a map?
my #paramList = split /(?:\?|&|;)([^=]+)=([^&|;]+)/, $ENV{'REQUEST_URI'};
if(#paramList)
{
print "<h1>The Params</h1><ul>";
foreach my $i (#paramList) {
if($i) {
print "<li>$i</li>";
}
}
print "<ul>";
}
Per the request, here is a basic example of the input:
REQUEST_URI = /cgi-bin/printenv_html.pl?customer_name=fdas&phone_number=fdsa&email_address=fads%40fd.com&taxi=van&extras=tip&pickup_time=2020-01-14T20%3A45&pickup_place=&dropoff_place=Airport&comments=
goal is the following where the left of the equal is the key, and the right is the value:
customer_name=fdas
phone_number=fdsa
email_address=fads%40fd.com
taxi=van
extras=tip
pickup_time=2020-01-14T20%3A45
pickup_place=
dropoff_place=Airport
comments=
How about feeding your list of key-value pairs into a hash?
my %paramList = $ENV{'REQUEST_URI'} =~ /(?:\?|&|;)([^=]+)=([^&|;]+)/g;
(no reason for the split as far as I can tell)
This relies crucially on there being an even-sized list of matches, where each "before-=" thing becomes a key in the hash, with the value being its pairing "after-=" thing.
In order to also get "pairs" without a value (like comments=) change + in the last pattern to *

How to get the most frequent element of a list?

Let's say I have a list:
std::list<std::string> list ("the", "the", "friend", "hello", "the");
In this case, the most common element in the list is "the". Is there a way to get this element in C++??
Thanks!
A general algorithm to solve your problem is to build a dictionary of word frequencies. Here is a pseudo code algorithm, that does exactly that:
let L be the input sequence of strings (can be a list, doesn't matter)
let F be an empty dictionary that maps string to a number
for each string S in L
if not F contains S then
F[S] = 0
F[S] += 1
Once the dictionary is constructed, all you need to do is to find the mapping with the highest value, and return the key.
The C++ standard library provides associative containers (aka dictionaries, aka maps), and an algorithm for searching for the greatest element within a container.

Checking if a string contains a character in Scala

I have a collection of Strings and I'm checking if they're correctly masked or not.
They're in a map and so I'm iterating over it, pulling out the text value and then checking. I'm trying various different combinations but none of which are giving me the finished result that I need. I have gotten it working by iterating over each character but that feels very java-esque.
My collection is something like:
"text"-> "text"
"text"-> "**xt"
"text"-> "****"
in the first two cases I need to confirm that the value is not all starred out and then add them to another list that can be returned.
Edit
My question: I need to check if the value contains anything other an '*', how might I accomplish this in the most efficient scala-esque way?
My attempt at regex also failed giving many false positives and it seems like such a simple task. I'm not sure if regex is the way to go, I also wondered if there was a method I could apply to .contains or use pattern matching
!string.matches("\\*+") will tell you if the string contains characters other than *.
If I understand correctly, you want to find the keys in your map for which the value is not just stars. You can do this with a regex :
val reg = "\\*+".r
yourMap.filter{ case (k,v) => !reg.matches(v) }.keys
If you're not confortable with a regex, you can use a forall statement:
yourMap.filter{ case(k,v) => v.forall(_ == '*') }.keys
Perhaps I misunderstood your question, but if you started with a Map you could try something like:
val myStrings = Map("1"-> "text", "2"-> "**xt", "3"-> "****")
val newStrings = myStrings.filterNot( _._2.contains("*") )
This would give you a Map with just Map(1 -> "text").
Try:
val myStrings = Map("1"-> "text", "2"-> "**xt", "3"-> "****")
val goodStrings = myStrings.filter(_._2.exists(_ !='*'))
This finds all cases where the value in the map contains something other than an asterisk. It will remove all empty and asterisk-only strings. For something this simple, i.e. one check, a regex is overkill: you're just looking for strings that contain any non-asterisk character.
If you only need the values and not the whole map, use:
val goodStrings = myStrings.values.filter(_.exists(_ !='*'))

replace (key, value) in a string with boost regex

I have a map (collection of pairs) of strings I have to replace in a string.
For example if I have map { {"foo", "foo2"}, {"bar", "bar2"} }
the final result for string "foo barman football bar" should be: "foo2 bar2man foo2tball bar2".
There are a number of questions/answers already but none of them mention the biggest problem here. If the map has "circular" replacement { {"foo", "bar"}, {"bar", "foo"} }
the result should be: "bar fooman bartball foo".
Another problem could be { {"foo", "fo"}, {"fo", "f"} }
The algorithm should replace an instance only once.
Sorry for not providing SSCCE ... I am still looking how to approach it.
Option 1:
Sort the map by key size (descending) - this will eliminate inclusion problems.
Then based on idea that comes from the classic swap approach. Go through the map and replace all occurrences of key with something unique. In my case ? could not be used so ?1 for the first key ?2 for the second key etc.
Now on second pass replace ?1 with the value 1, ?2 with value 2 etc.
Cons:
1. you have to have easy way to define swap key that do no match with any of the keys or values.
2. Seems performance expensive
Option 2:
Create a general match pattern say ((key1|key2|key3...)(.*?))*.
Enumerate the matches and for every key match replace the key with the value.
Regenerate the result.
Cons:
1. Creating the matching tree could be memory expensive
2. preparing general pattern could be a hassle

In scala, how to pass a default value to List.find?

I would like to find an element in a list that matches a predicate and to get a default value if no elements matches the predicate. I want to do this idiomatically, without defining additional variables (one liner).
Is there something similar to getOrElse of HashMap?
This is yet another example of why Option is great!
The find method returns an Option, and Option has a method getOrElse that does exactly what you want.
scala> List(1,2,3).find(_ > 4).getOrElse(0)
res0: Int = 0
When nothing is found, find returns None, which means the "else" value will be returned.