How do I swap some characters of a String with values of a HashMap<String,String> in Kotlin? - list

Assuming I have a
val s: String = "14ABC5"
and have a HashMap
val b: HashMap<String,String> = hashMapOf("A" to "10", "B" to "11", "C" to "12", "D" to "13", "E" to "14", "F" to "15" )
How would I change all occurrences of A,B,C with 10, 11, 12 while keeping their order ("1", "4", "10", "11", "12", "5")?
So far I have this
val result: List<String> = s.toUpperCase().toCharArray().map{ it.toString() }.map{ it -> b.getValue(it)}
which works if ALL characters of the String exist in the HashMap but my String may contain inexistent keys as well.

You could either use getOrDefault(...), or the Kotlinesque b[it] ?: it.
By the way, if you're using the implicit lambda argument name (it), you can get rid of the it ->.

You can use the String as an iterable by default and simplify your code as follows:
s.map { it.toString() }
.map { b[it] ?: it }

Related

Sort a nested structure in Coldfusion

I am trying to sort a nested struct using StructSort. Below is a simple example of what I am trying to do. The code below does not work and returns the following error "The specified element a does not contain a simple value." Is it possible to sort a nested structure in Coldfusion, and if so how?
<cfscript>
data = {"a":{"name":100},"b":{"name":50},"c":{"name":25},"d":{"name":75}};
dataSorted= StructSort(data, function(a,b) {
return compare(a.name, b.name);
});
writeDump(dataSorted);
</cfscript>
expected output
c
b
d
a
Also made a cffiddle here: https://cffiddle.org/app/e20a782a-be90-4e65-83de-e31eb83fdf4f
Docs: https://docs.lucee.org/reference/objects/struct/sort.html
<cfscript>
data = {
"a": {"name": 100},
"b": {"name": 50},
"c": {"name": 25},
"d": {"name": 75}
};
dataSorted = data.sort("numeric", "asc", "name")
writeDump(dataSorted);
</cfscript>
Result: array ["c", "b", "d", "a"]
This worked for me on lucee 5. something. The last argument in the sort function is the pathToSubElement within a struct. Fo your example it is simply one level deep using the name property.

Scala Regex: matching a non single character input

For instance the function:
val reg = "[^ ]".r
takes in an input that would match with every character except for the empty space character.
and:
def matchReg(line: String): List[String] = reg.findAllIn(line).toList
Converts the input into a list.
However how would I edit this so that it would match with a non-single character input. Since it seems as though this splits the input such as "14" into "1" and "4" when the values of the regular expression are turned into a list. If the input is "14" I want it to output "14" rather than it being split. Thank you.
EDIT: I have written test cases to explain the type of output I am looking for
"The match" should "take list" in {
assert(matchReg("(d e f)") == List("(", "d", "e", "f", ")"))
}
it should "take numbers" in {
assert(matchReg("(12 45 -9 347 4)") == List("(", "12", "45", "-9", "347", "4", ")"))
}
it should "take operators" in {
assert(matchReg("(- 7 (* 8 9))") == List("(", "-", "7", "(", "*", "8", "9", ")", ")"))
}
With the following case, "take list" and "take operators" passes successfully if I use:
val reg = "[^ ]".r
However "take numbers" does not pass since numbers such as "347" are being split into "3" "4" and "7", when I want them to register as one single number.
This should work for you
val reg = """[^ \(\)]+|\(|\)""".r
You should add some other alternatives if you want to support also [ ] , { } or other operators
# matchReg("(d e f)")
res8: List[String] = List("(", "d", "e", "f", ")")
# matchReg("(12 45 -9 347 4)")
res9: List[String] = List("(", "12", "45", "-9", "347", "4", ")")
# matchReg("(- 7 (* 8 9))")
res10: List[String] = List("(", "-", "7", "(", "*", "8", "9", ")", ")")

How to access the arrays in private class of C++?

class bus {
private:
string arr[10] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
public:
void reservation();
};
Here, I have a private array that I want to access and make changes through the reservation() in public class.
void bus::reservaton() {
cout << "What should I write in here to change the 3rd and 7th index of the
above array to \"not empty\"" << endl;
}
Suppose, I want to make the 3rd and 7th index to "not empty", what should I write there?
Sample:-
string arr[10] = { "0", "1", "2", "not empty", "4", "5", "6", "not empty", "8", "9" };
And do I need to make any changes in the main function? If yes, then can you please help me by writing it down.
Thank you.
How to use arrays
void bus::reservation() {
arr[3] = "not empty";
arr[7] = "not empty";
}
For this, a simple assignment operator (=) would work.
For example, in the following example, the value at index 1 is changed:
std::string slist[ 3 ] { "a", "b", "c" };
slist[ 1 ] = "Changed!";
Live example: http://ideone.com/rO9hwt
BTW, you should use std::vector of std::string instead of an array. And, take a look at its member function at() for accessing the value of an index with out of bounds checking.
Live example: http://ideone.com/bcHZpY

Python list and for loop

I'm expecting this code to print spade:A spade:2 and so on until heart:K.
But it only does heart:A to heart:K.
How should I do it?
symbols = ["spade", "clover", "diamond", "heart"]
numbers = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
cards = {}
for num in numbers:
for symbol in symbols:
cards[num] = symbol
print cards
Use your itertools toolbox
import itertools
symbols = ["spade", "clover", "diamond", "heart"]
numbers = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
combinations = itertools.product(symbols, numbers)
cards = ["{}:{}".format(suit, rank) for suit,rank in combinations]
This will give you the list:
['spade:A',
'spade:2',
'spade:3',
'spade:4',
'spade:5',
'spade:6',
'spade:7',
'spade:8',
'spade:9',
'spade:10',
'spade:J',
'spade:Q',
'spade:K',
'clover:A',
'clover:2',
'clover:3',
'clover:4',
'clover:5',
'clover:6',
'clover:7',
'clover:8',
'clover:9',
'clover:10',
'clover:J',
'clover:Q',
'clover:K',
'diamond:A',
'diamond:2',
'diamond:3',
'diamond:4',
'diamond:5',
'diamond:6',
'diamond:7',
'diamond:8',
'diamond:9',
'diamond:10',
'diamond:J',
'diamond:Q',
'diamond:K',
'heart:A',
'heart:2',
'heart:3',
'heart:4',
'heart:5',
'heart:6',
'heart:7',
'heart:8',
'heart:9',
'heart:10',
'heart:J',
'heart:Q',
'heart:K']
The problem is that you are not iterating the right way and thus you are not appending in the list. The right way to do it is
symbols = ["spade", "clover", "diamond", "heart"]
numbers = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
cards = []
for j in range(len(symbols)):
for i in range(len(numbers)):
cards.append(str(symbols[j]+':'+str(numbers[i])))
print cards
with output:
['spade:A', 'spade:2', 'spade:3', 'spade:4', 'spade:5', 'spade:6', 'spade:7', 'spade:8',
'spade:9', 'spade:10', 'spade:J', 'spade:Q', 'spade:K', 'clover:A', 'clover:2',
'clover:3', 'clover:4', 'clover:5', 'clover:6', 'clover:7', 'clover:8', 'clover:9',
'clover:10', 'clover:J', 'clover:Q', 'clover:K', 'diamond:A', 'diamond:2', 'diamond:3',
'diamond:4', 'diamond:5', 'diamond:6', 'diamond:7', 'diamond:8', 'diamond:9', 'diamond:10',
'diamond:J', 'diamond:Q', 'diamond:K', 'heart:A', 'heart:2', 'heart:3', 'heart:4',
'heart:5', 'heart:6', 'heart:7', 'heart:8', 'heart:9', 'heart:10', 'heart:J', 'heart:Q', 'heart:K']
Made with Ipython Notebook in python 2.7
Hope it helps.
You are iterating the symbols just fine but when you are going over the numbers in the second loop, you are actually replacing the values set by the previous loop hence you only have values from the last loop left and everything is replaced. This means cards["A"] value is set 4 times in the loop and the last for the "heart" is retained. The same thing is happening for all the other indexes.

Rexexp to match all the numbers,alphabets,special characters in a string

I want a pattern to match a string that has everything in it(alphabets,numbers,special charactres)
public static void main(String[] args) {
String retVal=null;
try
{
String s1 = "[0-9a-zA-Z].*:[0-9a-zA-Z].*:(.*):[0-9a-zA-Z].*";
String s2 = "BNTPSDAE31G:BNTPSDAE:Healthcheck:Major";
Pattern pattern = null;
//if ( ! StringUtils.isEmpty(s1) )
if ( ( s1 != null ) && ( ! s1.matches("\\s*") ) )
{
pattern = Pattern.compile(s1);
}
//if ( ! StringUtils.isEmpty(s2) )
if ( s2 != null )
{
Matcher matcher = pattern.matcher( s2 );
if ( matcher.matches() )
{
retVal = matcher.group(1);
// A special case/kludge for Asentria. Temp alarms contain "Normal/High" etc.
// Switch Normal to return CLEAR. The default for this usage will be RAISE.
// Need to handle switches in XML. This won't work if anyone puts "normal" in their event alias.
if ("Restore".equalsIgnoreCase ( retVal ) )
{
}
}
}
}
catch( Exception e )
{
System.out.println("Error evaluating args : " );
}
System.out.println("retVal------"+retVal);
}
and output is:
Healthcheck
Hera using this [0-9a-zA-Z].* am matching only alpahbets and numbers,but i want to match the string if it has special characters also
Any help is highly appreciated
Try this:
If you want to match individual elements try this:
2.1.2 :001 > s = "asad3435##:$%adasd1213"
2.1.2 :008 > s.scan(/./)
=> ["a", "s", "a", "d", "3", "4", "3", "5", "#", "#", ":", "$", "%", "a", "d", "a", "s", "d", "1", "2", "1", "3"]
or you want match all at once try this:
2.1.2 :009 > s.scan(/[^.]+/)
=> ["asad3435##:$%adasd1213"]
Try the following regex, it works for me :)
[^:]+
You might need to put a global modifier on it to get it to match all strings.