How to calculate alternating sum of digits of an integer in Perl 6? - raku

A number is divisible by 11 if its alternating sum of digits is
divisible by 11.
So, e.g. if number is 1595, +1 -5 +9 -5 == 0, so 1595 is divisible by 11. How to implement such a sum? Here is my solution, but it's too complex and works only if the number of digits is even.
my $number = 1595;
say [+] $number.comb.map({$^a - $^b});
What's the best way to do it?

say [+] 1595.comb Z* (1, -1, 1 ... *)
To break it down: .comb returns a list of characters, and Z* multiplies that list element-wise with the sequence on the RHS.
This sequence is a geometric sequence, which the ... series operator can deduce from the three elements. Since the zip operator Z stops at the shortest sequence, we don't have to take care to terminate the sequence on the RHS.
Another way to write the same thing is:
say [+] 1595.comb Z* (1, -* ... *)
Where -* is the explicit negation of the previous value, applied to the initial element to generate the next one.
You could also write that as
say [+] 1595.comb Z* (1, &prefix:<-> ... *)

The cross that Moritz uses is interesting (and quite pleasing) but you can also take chunks of a list. This is close to what you were trying initially. I think you were going toward rotor:
my $number = 1595;
say [+] $number.comb.rotor(2, :partial).map: { $^a.[0] - ($^a.[1] // 0) }
Notice that you get one argument to your block. That's the list. It's a bit ugly because the odd digit case makes $^a.[1] Nil which would give a warning.
Now that I've played with this a bit more I handle that with a signature so I can give $b a default. This is much better:
my $number = 1595;
say [+] $number
.comb
.rotor(2, :partial)
.map: -> ( $a, $b = 0 ) { $a - $b }
But you don't even need the rotor because the map will grab as many positional parameters as it needs (h/t to timotimo in the comments). This means you were really close and merely missed the signature:
my $number = 1595;
say [+] $number
.comb
.map: -> ( $a, $b = 0 ) { $a - $b }
The solution you have in the comment doesn't quite work for the odd number of digits cases:
say [+] $number.comb.rotor(2, :partial).map({[-] $_});
And, I know this problem wasn't really about divisors but I'm quite pleased that Perl 6 has a "divisible by" operator, the %%:
$ perl6
> 121 %% 11
True
> 122 %% 11
False
> 1595 %% 11
True
> 1596 %% 11
False

say [+] 1595.comb >>*>> (1,-1)
Similar to the Z* version but using the hyper meta operator looping effect on the right hand side (if the left hand side has less than 2 digits you are fine).

Here's my solution.
say [+] 15956.comb.kv.map( (-1) ** * * * ); # 6
And a more explicit version.
say [+] 15956.comb.kv.map({ $^b * (-1) ** $^a }); # 6
UPD: Yet another solution.
say - [+] 15956.comb(2)>>.comb.map({[R-] $_}); # 6

Related

Raku pop() order of execution

Isn't order of execution generally from left to right in Raku?
my #a = my #b = [9 , 3];
say (#a[1] - #a[0]) == (#b[1] R- #b[0]); # False {as expected}
say (#a.pop() - #a.pop()) == (#b.pop() R- #b.pop()); # True {Huh?!?}
This is what I get in Rakudo(tm) v2020.12 and 2021.07.
The first 2 lines make sense, but the third I can not fathom.
It is.
But you should realize that the minus infix operator is just a subroutine under the hood, taking 2 parameters that are evaluated left to right. So when you're saying:
$a - $b
you are in fact calling the infix:<-> sub:
infix:<->($a,$b);
The R meta-operator basically creates a wrap around the infix:<-> sub that reverses the arguments:
my &infix:<R->($a,$b) = &infix:<->.wrap: -> $a, $b { nextwith $b, $a }
So, if you do a:
$a R- $b
you are in fact doing a:
infix:<R->($a,$b)
which is then basically a:
infix:<->($b,$a)
Note that in the call to infix:<R-> in your example, $a become 3, and $b becomes 9 because the order of the arguments is processed left to right. This then calls infix:<->(3,9), producing the -6 value that you would also get without the R.
It may be a little counter-intuitive, but I consider this behaviour as correct. Although the documentation could probably use some additional explanation on this behaviour.
Let me emulate what I assumed was happening in line 3 of my code prefaced with #a is the same as #b is 9, 3 (big number then little number)
(#a.pop() - #a.pop()) == (#b.pop() R- #b.pop())
(3 - 9) == (3 R- 9)
( -6 ) == ( 6 )
False
...That was my expectation. But what raku seems to be doing is
(#a.pop() - #a.pop()) == (#b.pop() R- #b.pop())
#R meta-op swaps 1st `#b.pop()` with 2nd `#b.pop()`
(#a.pop() - #a.pop()) == (#b.pop() - #b.pop())
(3 - 9) == (3 - 9)
( -6 ) == ( -6 )
True
The R in R- swaps functions first, then calls the for values. Since they are the same function, the R in R- has no practical effect.
Side Note: In fuctional programming a 'pure' function will return the same value every time you call it with the same parameters. But pop is not 'pure'. Every call can produce different results. It needs to be used with care.
The R meta op not only reverses the operator, it will also reverse the order in which the operands will be evaluated.
sub term:<a> { say 'a'; '3' }
sub term:<b> { say 'b'; '9' }
say a ~ b;
a
b
ab
Note that a happened first.
If we use R, then b happens first instead.
say a R~ b;
b
a
ba
The problem is that in your code all of the pop calls are getting their data from the same source.
my #data = < a b a b >;
sub term:<l> { my $v = #data.shift; say "l=$v"; return $v }
sub term:<r> { my $v = #data.shift; say "r=$v"; return $v }
say l ~ r;
l=a
r=b
ab
say l R~ r;
r=a
l=b
ab
A way to get around that is to use the reduce meta operator with a list
[-](#a.pop, #a.pop) == [R-](#a.pop, #a.pop)
Or in some other way make sure the pop operations happen in the order you expect.
You could also just use the values directly from the array without using pop.
[-]( #a[0,1] ) == [R-]( #a[2,3] )
Let me emulate what happens by writing the logic one way for #a then manually reversing the operands for #b instead of using R:
my #a = my #b = [9 , 3];
sub apop { #a.pop }
sub bpop { #b.pop }
say apop - apop; # -6
say bpop - bpop; # -6 (operands *manually* reversed)
This not only appeals to my sense of intuition about what's going on, I'm thus far confused why you were confused and why Liz has said "It may be a little counter-intuitive" and you've said it is plain unintuitive!

Minimum of empty Seq is infinite, Why?

I'm working on this weeks PerlWChallenge.
You are given an array of integers #A. Write a script to create an
array that represents the smaller element to the left of each
corresponding index. If none found then use 0.
Here's my approach:
my #A = (7, 8, 3, 12, 10);
my $L = #A.elems - 1;
say gather for 1 .. $L -> $i { take #A[ 0..$i-1 ].grep( * < #A[$i] ).min };
Which kinda works and outputs:
(7 Inf 3 3)
The Infinity obviously comes from the empty grep. Checking:
> raku -e "().min.say"
Inf
But why is the minimum of an empty Seq Infinity? If anything it should be -Infinity. Or zero?
It's probably a good idea to test for the empty sequence anyway.
I ended up using
take .min with #A[ 0..$i-1 ].grep( * < #A[$i] ) or 0
or
take ( #A[ 0..$i-1 ].grep( * < #A[$i] ) or 0 ).min
Generally, Inf works out quite well in the face of further operations. For example, consider a case where we have a list of lists, and we want to find the minimum across all of them. We can do this:
my #a = [3,1,3], [], [-5,10];
say #a>>.min.min
And it will just work, since (1, Inf, -5).min comes out as -5. Were min to instead have -Inf as its value, then it'd get this wrong. It will also behave reasonably in comparisons, e.g. if #a.min > #b.min { }; by contrast, an undefined value will warn.
TL;DR say min displays Inf.
min is, or at least behaves like, a reduction.
Per the doc for reduction of a List:
When the list contains no elements, an exception is thrown, unless &with is an operator with a known identity value (e.g., the identity value of infix:<+> is 0).
Per the doc for min:
a comparison Callable can be specified with the named argument :by
by is min's spelling of with.
To easily see the "identity value" of an operator/function, call it without any arguments:
say min # Inf
Imo the underlying issue here is one of many unsolved wide challenges of documenting Raku. Perhaps comments here in this SO about doc would best focus on the narrow topic of solving the problem just for min (and maybe max and minmax).
I think, there is inspiration from
infimum
(the greatest lower bound). Let we have the set of integers (or real
numbers) and add there the greatest element Inf and the lowest -Inf.
Then infimum of the empty set (as the subset of the previous set) is the
greatest element Inf. (Every element satisfies that is smaller than
any element of the empty set and Inf is the greatest element that
satisfies this.) Minimum and infimum of any nonempty finite set of real
numbers are equal.
Similarly, min in Raku works as infimum for some Range.
1 ^.. 10
andthen .min; #1
but 1 is not from 1 ^.. 10, so 1 is not minimum, but it is infimum
of the range.
It is useful for some algorithm, see the answer by Jonathan
Worthington or
q{3 1 3
-2
--
-5 10
}.lines
andthen .map: *.comb( /'-'?\d+/ )».Int # (3, 1, 3), (-2,), (), (-5, 10)
andthen .map: *.min # 1,-2,Inf,-5
andthen .produce: &[min]
andthen .fmt: '%2d',',' # 1,-2,-2,-5
this (from the docs) makes sense to me
method min(Range:D:)
Returns the start point of the range.
say (1..5).min; # OUTPUT: «1␤»
say (1^..^5).min; # OUTPUT: «1␤»
and I think the infinimum idea is quite a good mnemonic for the excludes case which also could be 5.1^.. , 5.0001^.. etc.

Questions on the prime number calculating code in Raku

I've come across this code at RosettaCode
constant #primes = 2, 3, { first * %% none(#_), (#_[* - 1], * + 2 ... Inf) } ... Inf;
say #primes[^10];
Inside the explicit generator block:
1- What or which sequence do the #_ s refer to?
2- What does the first * refer to?
3- What do the * in #_[* - 1] and the next * refer to?
4- How does the sequence (#_[* - 1], * + 2 ... Inf) serve the purpose of finding prime numbers?
Thank you.
The outer sequence operator can be understood as: start the sequence with 2 and 3, then run the code in the block to work out each of the following values, and keep going until infinity.
The sequence operator will pass that block as many arguments as it asks for. For example, the Fibonacci sequence is expressed as 1, 1, * + * ... Inf, where * + * is shorthand for a lambda -> $a, $b { $a + $b }; since this wishes for two parameters, it will be given the previous two values in the sequence.
When we use #_ in a block, it's as if we write a lambda like -> *#_ { }, which is a slurpy. When used with ..., it means that we wish to be passed all the previous values in the sequence.
The sub first takes a predicate (something we evaluate that returns true or false) and a list of values to search, and returns the first value matching the predicate. (Tip for reading things like this: whenever we do a call like function-name arg1, arg2 then we are always parsing a term for the argument, meaning that we know the * cannot be a multiplication operator here.)
The predicate we give to first is * %% none(#_). This is a closure that takes one argument and checks that it is divisible by none of the previous values in the sequence - for if it were, it could not be a prime number!
What follows, #_[* - 1], * + 2 ... Inf, is the sequence of values to search through until we find the next prime. This takes the form: first value, how to get the next value, and to keep going until infinity.
The first value is the last prime that we found. Once again, * - 1 is a closure that takes an argument and subtracts 1 from it. When we pass code to an array indexer, it is invoked with the number of elements. Thus #arr[* - 1] is the Raku idiom for "the last thing in the array", #arr[* - 2] would be "the second to last thing in the array", etc.
The * + 2 calculates the next value in the sequence, and is a closure that takes an argument and adds 2 to it. While we could in fact just do a simple range #_[* - 1] .. Inf and get a correct result, it's wasteful to check all the even numbers, thus the * + 2 is there to produce a sequence of odd numbers.
So, intuitively, this all means: the next prime is the first (odd) value that none of the previous primes divide into.

Given no modulus or if even/odd function, how would one check for an odd or even number?

I have recently sat a computing exam in university in which we were never taught beforehand about the modulus function or any other check for odd/even function and we have no access to external documentation except our previous lecture notes. Is it possible to do this without these and how?
Bitwise AND (&)
Extract the last bit of the number using the bitwise AND operator. If the last bit is 1, then it's odd, else it's even. This is the simplest and most efficient way of testing it. Examples in some languages:
C / C++ / C#
bool is_even(int value) {
return (value & 1) == 0;
}
Java
public static boolean is_even(int value) {
return (value & 1) == 0;
}
Python
def is_even(value):
return (value & 1) == 0
I assume this is only for integer numbers as the concept of odd/even eludes me for floating point values.
For these integer numbers, the check of the Least Significant Bit (LSB) as proposed by Rotem is the most straightforward method, but there are many other ways to accomplish that.
For example, you could use the integer division operation as a test. This is one of the most basic operation which is implemented in virtually every platform. The result of an integer division is always another integer. For example:
>> x = int64( 13 ) ;
>> x / 2
ans =
7
Here I cast the value 13 as a int64 to make sure MATLAB treats the number as an integer instead of double data type.
Also here the result is actually rounded towards infinity to the next integral value. This is MATLAB specific implementation, other platform might round down but it does not matter for us as the only behavior we look for is the rounding, whichever way it goes. The rounding allow us to define the following behavior:
If a number is even: Dividing it by 2 will produce an exact result, such that if we multiply this result by 2, we obtain the original number.
If a number is odd: Dividing it by 2 will result in a rounded result, such that multiplying it by 2 will yield a different number than the original input.
Now you have the logic worked out, the code is pretty straightforward:
%% sample input
x = int64(42) ;
y = int64(43) ;
%% define the checking function
% uses only multiplication and division operator, no high level function
is_even = #(x) int64(x) == (int64(x)/2)*2 ;
And obvisouly, this will yield:
>> is_even(x)
ans =
1
>> is_even(y)
ans =
0
I found out from a fellow student how to solve this simplistically with maths instead of functions.
Using (-1)^n :
If n is odd then the outcome is -1
If n is even then the outcome is 1
This is some pretty out-of-the-box thinking, but it would be the only way to solve this without previous knowledge of complex functions including mod.

Perl6-ish expression for the bits of an integer

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)