First of all, sorry for the confused title.
What I want to do is to convert {1, 4, 9} to:
{True, False, False, True, False, False, False, False, True}
That is, only the indexes from the first list will have value True, the rest will be False.
I sense there is some really simple solution, but I am quite new to both Mathematica and functional programming. I could do it iteratively, in a loop, but there has to be something that works with the list as a whole. Right? :)
Thanks for your help.
EDIT: to show that I tried to do something before I asked, here's my progress so far:
first={1,4,9}
ReplacePart[Table[False, {x, Max[first]}], {1} -> True]
(* gives {True, False, False, False, False, False, False, False, False} *)
Unfortunately, it doesn't work with {1,4,9} -> True, but would work with {1 -> True, 4 -> True, 9 -> True}. But I don't know how to get to that...
EDIT 2: got it.
ReplacePart[Table[False, {x, Max[first]}], Table[x -> True, {x, first}]]
I'd still love to see your solutions! This one seems like an ugly hack to me ... :)
Here's a simple approach:
first = {1, 4, 9};
list = ConstantArray[False, Max#first];
list[[first]] = True;
list
Out[1]= {True, False, False, True, False, False, False, False, True}
Here's the above solution written as a convenient function:
Clear[convertIndices]
convertIndices[index_List] :=
Module[{list = ConstantArray[False, Max#index]},
list[[index]] = True; list]
Usage:
convertIndices#{1, 4, 9}
Out[2]= {True, False, False, True, False, False, False, False, True}
I would use SparseArray for this operation. In my opinion it is very easy to understand, and it is also efficient, especially when a low percentage of indices are True.
true = {1, 4, 9};
SparseArray[(List /# true) -> True, Automatic, False]
Alternatively with Transpose (which looks better when pasted into Mathematica):
SparseArray[{true}\[Transpose] -> True, Automatic, False]
You can use Normal if you must convert the output to a normal array, but most operations will not require that.
Also, sacrificing practicality for terseness:
#==1 & /# SparseArray[List /# true -> 1]
Actually, I would have used Yoda's answer myself, but here's an alternative:
first = {1, 4, 9};
MemberQ[first, #] & /# Range[Max[first]]
(* ===> {True, False, False, True, False, False, False, False, True}*)
Or this one:
Or ### Outer[Equal, Range[Max[first]], first]
(* ===> {True, False, False, True, False, False, False, False, True}*)
Both have the advantage that they skip Yoda's ConstantArray initialization step.
Related
I have this JSON Object coming from an HTML.
{
"isCompany": false,
"accommodations": [
{
"id": "00000000031000006435",
"isChecked": false,
"name": "Théo",
"addressLine1": "Rue des patriotes 40 Y",
"addressLine2": "1050 Ixelles",
"nightsDeclared": 5,
"schoolNightsDeclared": 3,
"schoolNightsAttached": 0,
"taxableNights": 2.0,
"totalPayment": 0.0,
"isInProgress": true,
"isLate": false,
"isPayed": "false",
"deadline": "2021-12-31",
"initialAmount": 0.0,
"remainingAmount": 0.0
},
{
"id": "00000000031000006438",
"isChecked": false,
"name": "Théo",
"addressLine1": "Rue des Gens 45 B",
"addressLine2": "1040 Etterbeek",
"nightsDeclared": 5,
"schoolNightsDeclared": 3,
"schoolNightsAttached": 0,
"taxableNights": 2.0,
"totalPayment": 0.0,
"isInProgress": true,
"isLate": false,
"isPayed": "false",
"deadline": "2021-12-31",
"initialAmount": 0.0,
"remainingAmount": 0.0
}
]
}
I know that in Gatling, it is possible to get the accommodation id by writing this regex :
check(regex(""""accommodations":\[\{"id":"(.*?)"""").saveAs("accommodationId"))
Now my question is, what is the regex that gets the "isInProgress"?
Don't!
Using regex in this specific case could result in your code breaking on slight input changes and will result in unreadable code.
Instead deserialize and access as a dictionary?
[a['id'] for a in json.loads(json_string)['accommodations']]
Also, have you tried to simply replace id with the name of the field you want?
If you insist on using regex for this, check out online regex sites like regex101.com, regexr.com, regextester.com etc. (search for "online regex test") and try to solve this yourself. If your code does not work, ask a question again.
Ok, you have this in your regex
"id":"(.*?)"
You need just change to expected key name as isInProgress or any another. Also pay attention on " around (.*?) - since the value for id a string, they are needed, but value in isInProgress with another type.
I would like to identify the string "mystring" in a text (actually a R code), but ensuring that it is a variable name:
it should not be part of a longer variable such as "thisismystring" or "mystringisnice". I guess this can be done by excluding (?!([[:alnum:]]){1}) before and after "mystring"?
It can however be at the beginning of a line (such as "\nmystring") so we have to be careful about this type of exception
What is the best approach for that?
Edit: unit test
pattern = "\\bmystring\\b"
identical(grepl(pattern = pattern,
x = c("thisismystring","mystringisnice","\nmystring", "mystring", "mystring=", "mystring(", " mystring","mystring\n", "6mystring", "mystring0", "= mystring(", "=mystring",
"hop
mystring")),
c(FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE))
Just use the \b (word boundary) token:
\\bmystring\\b
unit test
pattern = "\\bmystring\\b"
`==`(grepl(pattern = pattern,
x = c("thisismystring","mystringisnice","\nmystring", "mystring", "mystring=", "mystring(", " mystring","mystring\n", "6mystring", "mystring0", "= mystring(", "=mystring",
"hop
mystring")),
c(FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE))
# [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
So currently I use next style:
{
BasedOnStyle: "LLVM",
IndentWidth: 4,
UseTab: false,
ColumnLimit: 150,
Standard: "Cpp11",
BreakBeforeBraces: "Attach",
BreakBeforeBinaryOperators: false,
AlwaysBreakTemplateDeclarations: true,
AllowShortLoopsOnASingleLine: false,
AllowShortIfStatementsOnASingleLine: false,
AllowAllParametersOfDeclarationOnNextLine: true,
SpacesInParentheses: true,
SpacesBeforeTrailingComments: 1,
SpaceInEmptyParentheses: false,
SpaceAfterControlStatementKeyword: true,
PointerBindsToType: true,
MaxEmptyLinesToKeep: 1,
IndentFunctionDeclarationAfterType: true,
IndentCaseLabels: true,
ExperimentalAutoDetectBinPacking: true,
DerivePointerBinding: true,
Cpp11BracedListStyle: false,
ConstructorInitializerAllOnOneLineOrOnePerLine: true,
BreakConstructorInitializersBeforeComma: true
}
and get
try {
}
catch ( ... ) {
}
While I want to get
try {
} catch ( ... ) {
}
Can any one say which Clang-Format Style Option is responsible for such behaviour?
BreakBeforeBraces should, as I understand it, affect the behavior you are concerned with. Attach looks like the correct option from it description on the style options page that you referenced. The only reason that I can see for it not working is that BreakBeforeBraces expects a BraceBreakingStyle enum. Try it without the making Attach a string.
BreakBeforeBraces: Attach
or
BreakBeforeBraces: BS_Attach
Support for try-catch-blocks has only been added recently. If you update to a current version, this should be fixed.
I know this is probably a very simple List operation in Scala, but I'm a newbie and can't figure it out. I have a query that returns a result set with a series of values, grouped by a common id. For example:
Result Set:
[{ 1, "a", 30 },
{ 1, "b", 20 },
{ 1, "c", 22 },
{ 2, "a", 32 },
{ 2, "c", 10 }]
and what I'd like to do is put this into a map as such:
1 -> [{"a", 30}, {"b", 20}, {"c", 22}]
2 -> [{"a", 32}, {"c", 10}]
I think the collect method can be used for this but can't figure it out.
I'm not sure what the types in your data structure are, but maybe you can adapt this. This assumes you have a collection of tuples:
val items =
List((1, "a", 30),
(1, "b", 20),
(1, "c", 22),
(2, "a", 32),
(2, "c", 10))
items
.groupBy{ case (a,b,c) => a }
.mapValues(_.map{ case (a,b,c) => (b,c) })
// Map(1 -> List((a,30), (b,20), (c,22)), 2 -> List((a,32), (c,10)))
Or, more succinctly:
items.groupBy(_._1).mapValues(_.map(t => (t._2, t._3)))
The collect method is something else entirely (basically, it's map that drops non-matching values). The groupBy method is what you were really looking for.
I'm trying to construct a 2D array in the form of pointers-to-pointers. This doesn't work:
bool** data = {
new bool[4] {true, true, true, true},
new bool[4] {true, false, false, true},
new bool[4] {true, false, false, true},
new bool[4] {true, true, true, true}
};
Is it possible? How should I be doing it?
EDIT:
Looks like I might be trying to do the wrong thing. I have a function that takes a 2D array of bools of an unknown size, along with integer width and height, as arguments. At present, the signature is:
foo(bool** data, int width, int height)
I want to be able to construct a literal for data, but I also need this function to work for any size of array.
You could have an array of arrays (sometimes referred to as a multi-dimensional array):
bool data[][4] = {
{true, true, true, true},
{true, false, false, true},
{true, false, false, true},
{true, true, true, true}
};
However, that isn't convertible to bool**, so if you need that conversion then this won't work.
Alternatively, an array of pointers to static arrays (which is convertible to bool**):
bool data0 = {true, true, true, true};
bool data1 = {true, false, false, true};
bool data2 = {true, false, false, true};
bool data3 = {true, true, true, true};
bool * data[] = {data0, data1, data2, data3};
or if you really want dynamic arrays (which is almost certainly a bad idea):
bool * make_array(bool a, bool b, bool c, bool d) {
bool * array = new bool[4];
array[0] = a;
array[1] = b;
array[2] = c;
array[3] = d;
return array;
}
bool * data[] = {
make_array(true, true, true, true),
make_array(true, false, false, true),
make_array(true, false, false, true),
make_array(true, true, true, true)
};
or, perhaps, you could stick with arrays, and modify your functions to take references to arrays rather than pointers, inferring the dimensions as template parameters if you need to support different dimensions. This is only possible if the dimensions are always known at compile time.
template <size_t N, size_t M>
void do_something(bool (&array)[N][M]);
do_something(data);
bool data_[][4] = {
{true, true, true, true},
{true, false, false, true},
{true, false, false, true},
{true, true, true, true}
};
bool *data[4] = { data_[0], data_[1], data_[2], data_[3] };
bool *data[] = {
(bool []){true, true, true, true}
,(bool[]) {true, false, false, true}
,(bool[]) {true, false, false, true}
,(bool[]) {true, true, true, true}
};
This is convertible to bool** as you wish. This is not an array of arrays. This is an array of pointers.
By prefacing each row with (bool []) we enable it to decay to a pointer. Each row is therefore a pointer, and can then be brought together into an array of four pointers.
Edit: You can drop the explicit 4 inside the [braces], as it can be deduced by the compiler.