I have to increment a number in velocity template engine.
#set ($newIndex = $oldIndex+ 1)
$newIndex
but i am getting incorrect result e.g if value of $oldIndex is 1 then i am getting 11 instead of 2
Assuming oldIndex defined as a number, it seems similar to substraction not working
Your example is not copied correctly. If a dash is next to an identifier, it becomes part of the identifier. So this example would fail, since the "-" sign is actually part of the Total2 identifier.
Add space after variable name:
#set ($newIndex = $oldIndex + 1)
It has nothing to do with spaces in this case, but rather with the initial content of $oldIndex.
The following template:
#set ($i = '1')
#set ($i = $i + 1)
$i.class.name / $i
#set ($j = 1)
#set ($j = $j + 1)
$j.class.name / $j
displays:
11 / java.lang.String
2 / java.lang.Integer
So you need to convert $oldIndex to a number, but the way to do it depends of the tools you have available in your context to do so (if you can't put $oldIndex as a number in the context in the first place). You would typically do something like #set ($oldIndex = $number.toNumber($oldIndex)) if you have the NumberTool present in your context, for instance.
There's a method that will probably work in all environments:
#set ($dummy = 1) ## creates an Integer variable
#set ($oldIndex = $dummy.valueOf($oldIndex)) ## uses Integer.valueOf() method
And that's it, $oldIndex contains an integer! Please note that the Integer.valueOf() method may throw a NumberFormatException if given something else than a number representation.
Related
I have an array:
my #e = <60.922 20.946 8.721 7.292 4.306 2.821 2.765 2.752 2.741 2.725>
I would like to divide every element in the array by the minimum, however
#e /= #e.min
produced a single element, which isn't correct.
I've read https://docs.raku.org/type/Array but I don't understand the basic elements of Raku for this.
How can I divide every item in the array by the same number?
You can use the raku hyper & compound metaoperators like this:
#a >>/=>> #a.min
>>X>> means "apply operator X over all list items (with more items on the left)"
/= means "assign result of divide operator / to replace each original left hand item"
Use / instead of /= if you want to return the list of results but leave #a unchanged functional programming style.
[Edited according to #lizmat & #Sebastian comments]
my #a = 2, 3, 5, 7, 10;
my $div = #a.min;
$_ /= $div for #a;
say #a; # [1 1.5 2.5 3.5 5]
When you iterate over an array, you get mutable elements.
put #e.map( * / #e.min );
OR
put #e.map: * / #e.min;
Sample Input:
my #e = <60.922 20.946 8.721 7.292 4.306 2.821 2.765 2.752 2.741 2.725>;
Sample Output:
22.356697 7.686606 3.200367 2.675963 1.580183 1.035229 1.014679 1.009908 1.005872 1
If you want to continue working with the resultant values, assign the output to a new variable. Or overwrite the original #e array using the .= "back-assignment" operator [ short for #e = #e.map( … ) ]. In the Raku REPL:
~$ raku
Welcome to 𝐑𝐚𝐤𝐮𝐝𝐨™ v2021.06.
Implementing the 𝐑𝐚𝐤𝐮™ programming language v6.d.
Built on MoarVM version 2021.06.
To exit type 'exit' or '^D'
> my #e = <60.922 20.946 8.721 7.292 4.306 2.821 2.765 2.752 2.741 2.725>;
[60.922 20.946 8.721 7.292 4.306 2.821 2.765 2.752 2.741 2.725]
> #e .= map( * / #e.min );
[22.356697 7.686606 3.200367 2.675963 1.580183 1.035229 1.014679 1.009908 1.005872 1]
> put #e;
22.356697 7.686606 3.200367 2.675963 1.580183 1.035229 1.014679 1.009908 1.005872 1
>
I've been trying to exercise my Perl 6 chops by looking at some golfing problems. One of them involved extracting the bits of an integer. I haven't been able to come up with a succinct way to write such an expression.
My "best" tries so far follow, using 2000 as the number. I don't care whether the most or least significant bit comes first.
A numeric expression:
map { $_ % 2 }, (2000, * div 2 ... * == 0)
A recursive anonymous subroutine:
{ $_ ?? ($_ % 2, |&?BLOCK($_ div 2)) !! () }(2000)
Converting to a string:
2000.fmt('%b') ~~ m:g/./
Of these, the first feels cleanest to me, but it would be really nice to be able to generate the bits in a single step, rather than mapping over an intermediate list.
Is there a cleaner, shorter, and/or more idiomatic way to get the bits, using a single expression? (That is, without writing a named function.)
The easiest way would be:
2000.base(2).comb
The .base method returns a string representation, and .comb splits it into characters - similar to your third method.
An imperative solution, least to most significant bit:
my $i = 2000; say (loop (; $i; $i +>= 1) { $i +& 1 })
The same thing rewritten using hyperoperators on a sequence:
say (2000, * +> 1 ...^ !*) >>+&>> 1
An alternative that is more useful when you need to change the base to anything above 36, is to use polymod with an infinite list of that base.
Most of the time you will have to reverse the order though.
say 2000.polymod(2 xx *);
# (0 0 0 0 1 0 1 1 1 1 1)
say 2000.polymod(2 xx *).reverse;
say [R,] 2000.polymod(2 xx*);
# (1 1 1 1 1 0 1 0 0 0 0)
Not too familiar with AMPL, but running into some issues with indexes...
Basically, I have some variables defined as such:
var array{i in set};
And I need to do some amount of checking the elements around a given i in some of the constraints:
subject to Constraint{i in set}:
array[i] + array[i-1] + array[i+1] <= 12;
But obviously array[0] or array[card(set) + 1] don't exist. To add a further issue, I'm trying to model a sort of problem in which array[0] or array[card(set) + 1] just shouldn't be factored into our computation at all (e.g. it shouldn't constrain the other variables). Any help appreciated :) Thanks.
In AMPL, you can create or define your own "sets" for valid indices and use them in your constraints.
So, in your case, to avoid invalid indices, you can define a set of permissible indices: param inner_i {2..(N-1)} and loop over those when creating the constraints.
The price we pay is that we have to explicitly take care of the corner cases.
Here's one way to do it: (Note, I don't have AMPL loaded, so the code is untested.)
param N > 0; #number of elements
set ELEM; # Elements
set inner_i {2..(N-1)} > 0; #valid indices
var array {ELEM} >= 0;
subject to LimitSum{i in inner_i}:
array[i-1] + array[i] + array[i+1] <= 12;
#Take care of the boundary conditions explicitly, if needed
subject to LimitSum_start:
array[1] + array[2] <= 12;
#only two elements since array[0] doesn't exist.
subject to LimitSum_last:
array[N-1] + array[N] <= 12;
#only two elements since array[N+1] doesn't exist.
Hope this helps you move forward.
You can use an if-then-else expression to conditionally include some terms:
subject to Constraint{i in set}:
array[i] + (if i != 0 then array[i-1]) + (if i != N then array[i+1]) <= 12;
where N is the last element of the set.
I saw this pseudo-code on another stackoverflow question found here Split a string to a string of valid words using Dynamic Programming.
The problem is a dynamic programming question to see if an input string can be split into words from a dictionary.
The third line, means to set an array b of size [N+1] to all false values? I'm pretty sure about that. But what I am really not sure about is the fifth line. Is that a for-loop or what? I feel like pseudo-code saying 'for i in range' would only have 2 values. What is that line saying?
def try_to_split(doc):
N = len(doc)
b = [False] * (N + 1)
b[N] = True
for i in range(N - 1, -1, -1):
for word starting at position i:
if b[i + len(word)]:
b[i] = True
break
return b
It's confusing syntax, and I'm pretty sure there's a mistake. It should be:
for i in range(N - 1, 0, -1) //0, not -1
which I believe means
for i from (N - 1) downto 0 //-1 was the step, like i-- or i -= 1
This makes sense with the algorithm, as it simply starts at the end of the string, and solves each trailing substring until it gets to the beginning. If b[0] is true at the end, then the input string can be split into words from the dictionary. for word starting at position i just checks all words in the dictionary to see if they start at that position.
If one wants to be able to reconstruct a solution, they can change b to an int array, initialize to 0s, and change the if to this:
if b[i + len(word)] != 0
b[i] = i + len(word) //len(word) works too
break
I have a variable called Rest defined as:
var Rest{I,J,T} >= 0;
where T is the set of time periods and I and J the arcs. I need to define that every value for I and J where T = 0 must be 0. I is the set of supply nodes, and J the set of demand nodes.
I've tried:
let Rest[*,*,0] default 0;
but it got me syntax error. I tried this in both the .dat and .mod file using both := and :
I also tried to put this in the .dat file
var Rest default 0:=
[*,*,0] 1 City1 0;
but it gave me the error
Error at _cmdno 3 executing "solve" command
(file amplin, line 286, offset 11443):
error processing constraint Constraint1[1,'Leveaniemi',1]:
invalid subscript Rest[1,'City1',0]
Thanks in advance!
EDIT:
I now use:
var Rest default 0 :=
[*,*,0] 1 Leveaniemi 0;
which give me the error
Error at _cmdno 3 executing "solve" command
(file amplin, line 286, offset 11438):
error processing constraint Constprocessing commands.
Executing on neos-3.neos-server.org
Error (2) in /opt/ampl/ampl -R amplin
(I am using NEOS server, Gurobi solver). What does this even mean? Also if I declare a Variable Rest like that will it cause every Rest solution to become 0? Or does the compiler interpret it as a start value?
EDIT:
I've tried to implement the solution provided by vitaut. It did not work however, as expressed in the comments below that reply. I figured that since I've defined T as:
set T := 1 2 3 ... 15;
and since I wanted to do a let statement at t = 0, I have to account for that and define Rest as:
var Rest{I,J,TimeT};
where TimeU is T union a set with only a 0 element, i.e. TimeU is interpreted as:
TimeU := 0 1 2 3 ... 15;
With these fixed however, the compiler complains that all my variables and parameters are already defined.
The correct syntax of a let command is
let {i in I, j in J} Rest[i, j, 0] := 0;
However, it will assign starting values to the variables which can change during the optimization process. If you want to make Rest[i, j, 0] always equal to zero, then you should use a constraint instead:
s.t. c{i in I, j in J} Rest[i, j, 0] = 0;