Groff Eqn - How to do higher roots (cube root, etc) - groff

Does someone know how to do higher roots (cube roots, 4th roots, etc) in groff eqn? Been searching around the docs and cant seem to find the answer

In simple cases you can use a subscripted number before the root sign:
"" sup 3 sqrt x
but this does not look too good depending on the equation:
1 over { "" sup 3 { sqrt {ax sup 2 +bx+c} } }
An alternative is to use left-justified pile, which also has a large gap:
1 over { lpile { { size -8 3 } above { sqrt {ax sup 2 +bx+c} } } }
so often the best is to use the eqn local motion commands, up, back, size to play with the position to get the wanted result:
1 over { { up 90 size -8 3 } back 30 { sqrt {ax sup 2 +bx+c} } }

I would recommend using eqn macros like this
.EQ
define exp % "" sup fwd 30 %
define cube % "" sup fwd 30 3 sqrt %
define root % { "" sup fwd 30 $1 sqrt $2 } %
exp 3 sqrt 11
cube 11
root(3,11)
.EN

Related

Kotlin. Function does not exit recursion after return

I need to decompose the number l into prime factors. For this I use recursion. And when l = 1, the function must exit their recursion and return the string in which the prime factors are located, however, the function continues to work and already according to a principle incomprehensible to me. Please explain what is the problem with my code?
fun factors(l: Int): String {
return if (l == 1) {
answer
} else {
for (i in 2..l) {
if (l % i == 0) {
answer += "$i "
factors(l / i)
}
}
return factors(l)
}
}
Let's first mention some issues in your current code:
You're mixing semantics, here. What is the contract of your function? Does it return a value, or does it modify a global variable? Pick one, don't do both.
You should not use a global variable because it's way harder to follow. Instead, construct your values locally from the current information + whatever the recursive call returns to you
You're already using an if expression with the syntax return if (condition) { ... } else { ... }. This means each branch of the if should just end with an expression, you don't need to use return again. That said, in this case the first branch is rather a special case that you want to get out of the way before doing the bulk of the general work. In this kind of situation, I would rather use a statement like if (condition) { return X } at the beginning and then have the rest of the body of the function unnested, instead of using an if expression (but that is a personal preference).
It is strange to compute the list of factors as a string. You likely want to avoid duplicates and maybe sort them, so a List<Int> or a Set<Int> would likely be more appropriate. You can always format after the fact using things like joinToString(" ")
I'm not sure I get the math correctly, but it seems you really will be getting all factors here, not just the prime factors.
Now, the actual cause of the behaviour you're seeing is that you're calling your function recursively with the same number at the end: return factors(l). This means that calling factors(l) with any l > 1 will end up calling itself with the same value over and over. Recursive calls need to change some arguments to the function if you don't want it to be infinite.
fun factors(value: Int, list: MutableList<Int> = mutableListOf()): MutableList<Int> {
if (value > 1) {
for (i in 2..value) {
if (value % i == 0) {
list.add(i)
list.addAll(factors(value / i))
break
}
}
}
return list
}
(2..25).forEach {
val factors = factors(it)
val result = factors.reduce { acc, i -> acc * i }.toString() + " = " + factors.joinToString(" × ")
println(result)
}
Edit: this version is based on #Joffrey's comment below. Plus I decided to wrap the recursive function, now called fn, into a function in order to have a clean parameter list for factors():
fun factors(value: Int): List<Int> {
fun fn(value: Int, list: MutableList<Int>) {
if (value > 1) {
for (i in 2..value) {
if (value % i == 0) {
list.add(i)
fn(value / i, list)
break
}
}
}
}
val list = mutableListOf<Int>()
fn(value, list)
return list
}
Output:
2 = 2
3 = 3
4 = 2 × 2
5 = 5
6 = 2 × 3
7 = 7
8 = 2 × 2 × 2
9 = 3 × 3
10 = 2 × 5
11 = 11
12 = 2 × 2 × 3
13 = 13
14 = 2 × 7
15 = 3 × 5
16 = 2 × 2 × 2 × 2
17 = 17
18 = 2 × 3 × 3
19 = 19
20 = 2 × 2 × 5
21 = 3 × 7
22 = 2 × 11
23 = 23
24 = 2 × 2 × 2 × 3
25 = 5 × 5

Find all numbers adding up to given number and range to use

This is not homework, but a real world application I'm getting stumped on.
The best way I can explain my problem is as follows:
Imagine you have 3 pig pens A, B, and C and 10 pigs to be kept.
The pens have restrictions in that each pen must contain at least 1 pig and A.pigs <= B.pigs <= C.pigs. List all the possible pen configurations.
The REAL application can have anywhere between 1 and 7 pens, and anywhere between numPens and numPens*30 pigs and no pen may contain more than 30 pigs. So essentially this translates into "what numbers between 1 and 30 (repeats allowed) add up to X using Y numbers"
This could be solved simply with nested loops, but thats a terrible inefficient solution especially knowing the scope of the real application:
var cnt = 0
val target = 10
for (a in 1..30) {
for (b in a..30) {
val c = target - a - b
cnt++
if (a <= b && b <= c && a + b + c == target) {
println("$a $b $c")
}
}
}
println(cnt)
output:
1 1 8
1 2 7
1 3 6
1 4 5
2 2 6
2 3 5
2 4 4
3 3 4
465
I'm sure there is a recursive solution to this problem. But I'm having trouble even finding the starting point for this one.
It seems easy to start with an array of [1, 1, 8] where each index represents a pen. Just put all the pigs in 1 pen and move them around 1 at a time while following the constraints.
Subtract from C, add to B as much as you can while keeping constraints gets us [1, 2, 7], [1, 3, 6], [1, 4, 5] but at that point I'm stuck code wise.
What I have currently:
fun main(vararg args: String) {
val list = arrayOf(1, 1, 8)
list.forEach { print("$it\t") }
println()
rec(list, list.lastIndex - 1)
}
fun rec(list: Array<Int>, index: Int) {
if (index == list.lastIndex || index < 0) {
return
}
while (list[index] + 1 <= list[index + 1] - 1) {
list[index]++
list[index + 1]--
list.forEach { print("$it\t") }
println()
}
}
Obviously I need to call rec somewhere within itself and probably need some conditionals to call rec correctly (possibly adding more parameters to it). The question is where and how? Normally not bad with recursion, but this one is stumping me.
Solution:
I got so hung up on the idea I needed recursion. This loop seems to work pretty well.
for (a in 1..30) {
// we know a and c must be at least b, so cap range
var b = a
while(b < min(target - a - b, 30)){
val c = target - a - b
cnt++
if (a <= b && b <= c && a + b + c == target) {
println("$a $b $c")
}
b++
}
}
Some inefficiencies to note:
Once you know a and b, the only value for c that could make a solution would be 10-a-b, so you don't need the innermost loop at all.
Since a<=b, the second loop should start at a, not 1.
You can also limit the top of the second loop's range based on the value of a

How to build lazy lists with defined generators and is there a "takeWhile" alternative?

I am reading through perl6intro on lazy lists and it leaves me confused about certain things.
Take this example:
sub foo($x) {
$x**2
}
my $alist = (1,2, &foo ... ^ * > 100);
will give me (1 2 4 16 256), it will square the same number until it exceeds 100. I want this to give me (1 4 9 16 25 .. ), so instead of squaring the same number, to advance a number x by 1 (or another given "step"), foo x, and so on.
Is it possible to achieve this in this specific case?
Another question I have on lazy lists is the following:
In Haskell, there is a takeWhile function, does something similar exist in Perl6?
I want this to give me (1 4 9 16 25 .. )
The easiest way to get that sequence, would be:
my #a = (1..*).map(* ** 2); # using a Whatever-expression
my #a = (1..*).map(&foo); # using your `foo` function
...or if you prefer to write it in a way that resembles a Haskell/Python list comprehension:
my #a = ($_ ** 2 for 1..*); # using an in-line expression
my #a = (foo $_ for 1..*); # using your `foo` function
While it is possible to go out of one's way to express this sequence via the ... operator (as Brad Gilbert's answer and raiph's answer demonstrate), it doesn't really make sense, as the purpose of that operator is to generate sequences where each element is derived from the previous element(s) using a consistent rule.
Use the best tool for each job:
If a sequence is easiest to express iteratively (e.g. Fibonacci sequence):
Use the ... operator.
If a sequence is easiest to express as a closed formula (e.g. sequence of squares):
Use map or for.
Here is how you could write a Perl 6 equivalent of Haskell's takewhile.
sub take-while ( &condition, Iterable \sequence ){
my \iterator = sequence.iterator;
my \generator = gather loop {
my \value = iterator.pull-one;
last if value =:= IterationEnd or !condition(value);
take value;
}
# should propagate the laziness of the sequence
sequence.is-lazy
?? generator.lazy
!! generator
}
I should probably also show an implementation of dropwhile.
sub drop-while ( &condition, Iterable \sequence ){
my \iterator = sequence.iterator;
GATHER: my \generator = gather {
# drop initial values
loop {
my \value = iterator.pull-one;
# if the iterator is out of values, stop everything
last GATHER if value =:= IterationEnd;
unless condition(value) {
# need to take this so it doesn't get lost
take value;
# continue onto next loop
last;
}
}
# take everything else
loop {
my \value = iterator.pull-one;
last if value =:= IterationEnd;
take value
}
}
sequence.is-lazy
?? generator.lazy
!! generator
}
These are only just-get-it-working examples.
It could be argued that these are worth adding as methods to lists/iterables.
You could (but probably shouldn't) implement these with the sequence generator syntax.
sub take-while ( &condition, Iterable \sequence ){
my \iterator = sequence.iterator;
my \generator = { iterator.pull-one } …^ { !condition $_ }
sequence.is-lazy ?? generator.lazy !! generator
}
sub drop-while ( &condition, Iterable \sequence ){
my \end-condition = sequence.is-lazy ?? * !! { False };
my \iterator = sequence.iterator;
my $first;
loop {
$first := iterator.pull-one;
last if $first =:= IterationEnd;
last unless condition($first);
}
# I could have shoved the loop above into a do block
# and placed it where 「$first」 is below
$first, { iterator.pull-one } … end-condition
}
If they were added to Perl 6/Rakudo, they would likely be implemented with Iterator classes.
( I might just go and add them. )
A direct implementation of what you are asking for is something like:
do {
my $x = 0;
{ (++$x)² } …^ * > 100
}
Which can be done with state variables:
{ ( ++(state $x = 0) )² } …^ * > 100
And a state variable that isn't used outside of declaring it doesn't need a name.
( A scalar variable starts out as an undefined Any, which becomes 0 in a numeric context )
{ (++( $ ))² } …^ * > 100
{ (++$)² } …^ * > 100
If you need to initialize the anonymous state variable, you can use the defined-or operator // combined with the equal meta-operator =.
{ (++( $ //= 5))² } …^ * > 100
In some simple cases you don't have to tell the sequence generator how to calculate the next values.
In such cases the ending condition can also be simplified.
say 1,2,4 ...^ 100
# (1 2 4 8 16 32 64)
The only other time you can safely simplify the ending condition is if you know that it will stop on the value.
say 1, { $_ * 2 } ... 64;
# (1 2 4 8 16 32 64)
say 1, { $_ * 2 } ... 3;
# (1 2 4 8 16 32 64 128 256 512 ...)
I want this to give me (1 4 9 16 25 .. )
my #alist = {(++$)²} ... Inf;
say #alist[^10]; # (1 4 9 16 25 36 49 64 81 100)
The {…} is an arbitrary block of code. It is invoked for each value of a sequence when used as the LHS of the ... sequence operator.
The (…)² evaluates to the square of the expression inside the parens. (I could have written (…) ** 2 to mean the same thing.)
The ++$ returns 1, 2, 3, 4, 5, 6 … by combining a pre-increment ++ (add one) with a $ variable.
In Haskell, there is a takeWhile function, does something similar exist in Perl6?
Replace the Inf from the above sequence with the desired end condition:
my #alist = {(++$)²} ... * > 70; # stop at step that goes past 70
say #alist; # [1 4 9 16 25 36 49 64 81]
my #alist = {(++$)²} ...^ * > 70; # stop at step before step past 70
say #alist; # [1 4 9 16 25 36 49 64]
Note how the ... and ...^ variants of the sequence operator provide the two variations on the stop condition. I note in your original question you have ... ^ * > 70, not ...^ * > 70. Because the ^ in the latter is detached from the ... it has a different meaning. See Brad's comment.

Check brackets are balanced/matching

I have some MS Word documents which I have transferred the entire contents into a SQL table.
The contents contain a number of square brackets and curly brackets e.g.
[{a} as at [b],] {c,} {d,} etc
and I need to do a check to make sure that the brackets are balanced/matching, e.g. the below contents should return false:
- [{a} as at [b], {c,} {d,}
- ][{a} as at [b], {c,} {d,}
- [{a} as at [b],] {c,} }{d,
What I've done so far is extracted all the brackets and stored their info into a SQL table like below:
(paragraph number, bracket type, bracket position, bracket level)
3 [ 8 1
3 ] 18 0
3 [ 23 1
3 ] 35 0
7 [ 97 1
7 ] 109 0
7 [ 128 1
7 { 129 2
7 } 165 1
7 [ 173 2
7 ] 187 1
7 ] 189 0
7 { 192 1
7 } 214 0
7 { 216 1
7 } 255 0
7 { 257 1
7 } 285 0
7 { 291 1
7 } 326 0
7 { 489 1
7 } 654 0
I am unsure how the algorithm will work to do the check on whether the brackets are balanced in each paragraph, and give an error message when they are not.
Any advice would be appreciated!
EDIT:
Code will need to work for the following scenario too;
(paragraph number, bracket type, bracket position, bracket level)
15 [ 543 1
15 { 544 2
15 } 556 1
15 [ 560 2
15 ] 580 1
15 ] 581 0
15 [ 610 1
15 ] 624 0
15 [ 817 1
15 ] 829 0
does this have to be on sql server ?
a simple solution would be to use a general purpose language and use a stack.
Read the string character by character
if you encounter a opening brace push it to stack.
if you encounter a closing brace pop.
All brackets are matched if
after reading the paragraph completely the stack is empty.
UNLESS one of the below happens during the process
you had to pop an empty stack
the popped bracket does not match the closing bracket
its not a good idea to use regex to match brackets, they are not meant to be used like that
I'm not sure which tool you have available, but here is a tested JavaScript function which validates that all (possibly nested) square brackets and curly braces are properly matched:
function isBalanced(text) {
var re = /\[[^[\]{}]*\]|\{[^[\]{}]*\}/g;
while (text.search(re) !== -1) { text = text.replace(re, ''); }
return !(/[[\]{}]/.test(text))
}
It works by matching and removing innermost balanced pairs in an iterative manner until there are no more matching pairs left. Once this is complete, a test is made to see if any square bracket or curly braces remain. If any remain, then the function returns false, otherwise it returns true. You should be able to implement this function in just about any language.
Note that this assumes that the square and curly brace pairs are not interleaved like so: [..{..]..}
Hope this helps.
Addendum: Extended version for: (), {}, [] and <>
The above method can be easily extended to handle testing all four matching bracket types: (), {}, [] and <>, like so:
/*#!(?#!js\/g re Rev:20150530_121324)
# Innermost bracket matching pair from 4 global alternatives:
\( [^(){}[\]<>]* \) # Either g1of4. Innermost parentheses.
| \{ [^(){}[\]<>]* \} # Or g2of4. Innermost curly braces.
| \[ [^(){}[\]<>]* \] # Or g3of4. Innermost square brackets.
| \< [^(){}[\]<>]* \> # Or g4of4. Innermost angle brackets.
!#*/
function isBalanced(text) {
var re = /\([^(){}[\]<>]*\)|\{[^(){}[\]<>]*\}|\[[^(){}[\]<>]*\]|\<[^(){}[\]<>]*\>/g;
while (text.search(re) !== -1) { text = text.replace(re, ''); }
return !(/[(){}[\]<>]/.test(text));
}
Note the regex has been documented in an extended mode C comment.
Edit 20150530: Extended to handle a mix of all four matching bracket types: (), {}, [] and <>.
I agree with user mzzzzb. I've been working on a coding challenge that is somewhat similar and came up with the following solution in JavaScript:
function isBalanced(str) {
const stack = [];
const pairs = { ')': '(', ']': '[', '}': '{' };
return str.split('').reduce((res, e) => {
// if its opening, put in stack
if (['(', '{', '['].includes(e)) stack.push(e);
// if closing, compare thru stack
else if ([')', '}', ']'].includes(e)) {
if (stack.pop() !== pairs[e]) return false;
}
return res;
// stack must also be empty
}, true) && stack.length === 0;
}

ANTLR Reading blocks of values

I have been working on this for more than 2 days without success. It will be a common problem, but I can't find a solution. I did do a search!
Problem:
I have some data that I want to read in say, 5 values per line. I know how many I want to read from a value read previously. For example, 6 values to read, spread over 2 lines...
6
10 20 30 40 50
60
so after every 5 variables I want to read a new line. If there are 0 variables, I want to skip the bit to do with this, and if I want to read an exact multiple of 5 variables, then I want to avoid duplicating the NL call.
I tried this...
varblock[ Integer count ]
#init{
Integer varIndex = 0;
}
: { count > 0 }? ( dp=NUMBER { count--; varIndex++; }
{ ( varIndex \% 5 ) == 0 }? NL { varIndex = 0; }
)+ { varIndex > 0 }? => NL
|
;
But I get...
failed predicate: { ( varIndex \% 5 ) == 0 }?
It might be that I misunderstand predicates. I have several other predicates in my grammar that seem to work, but they are not of this type. There, I am trying to skip bits of the grammar depending on the version of the input file.
Thanks.
NL is just a line feed that is expected at the end of the input lines.
NL : ( '\n' | '\r' )+ ;
In other lines we read several other things such as...
"IPE270" "BS 7191 GR 355C" 0.0 0 0
and the values such as STRING, FLOAT, or NUMBER must be on those lines in expected sequences. So if we encounter a NL before we have read the requisite data values, there is a syntax error. So, perhaps the answer to your question is "Yes".
Perhaps I just (over?) simplified the example.
SOLVED:
It was a problem of brackets. I looked at the generated parser code to get a clue.
varblock[ Integer count ]
#init{
Integer index = 0;
}
: ( { count > 0 }? => ( NUMBER { count--; index++; }
| { (index \% 5) == 0 }? => NL ) )+ { index > 0 }? => NL
|
;
This reads values up to 5 per line.