Basic round robin in Perl difference between (++ / +1) - perl

Recently I was trying to make a simple round robin with Perl , and I found a behaviour that I don't understand clearly.
Here the behaviour:
my $a = {index => 0};
for (0 .. 10) {
$a->{index} = ($a->{index}++) % 2;
warn $a->{index};
}
The output of this code will be:
0,0,0,..,0
But if I do the "same" code replacing $a->{index}++ by $a->{index}+1 , the round robin will be fine, example
my $a = {index => 0};
for (0 .. 10) {
$a->{index} = ($a->{index}+1) % 2;
warn $a->{index};
}
The output will be:
1,0,1,0,1,0,1,0...
Someone can explain me the difference between ++ / +1 in this case? I find this really "ugly", because if I don't assign the result to any variable in the case "++" the code will work as expected unless I put the sum inside ().
This code will do a round robin correctly:
my $a = {index => 0};
for (0 .. 10) {
warn $a->{index}++ % 2;
}
With () in the sum, the code will output: 1,2,3,4,5,6,7,8,9
my $a = {index => 0};
for (0 .. 10) {
warn ($a->{index}++) % 2;
}

$a->{index}+1 returns $a->{index}+1, while
$a->{index}++ returns $a->{index} before it was changed.
++$a->{index} returns $a->{index}+1, but it makes no sense to use it in that expression since it needlessly changes $a->{index}.
$a->{index} = ($a->{index}+1) % 2;
Say $a->{index} is initially 0.
$a->{index}+1 returns 1.
Then you assign 1 % 2, which is 1 to $a->{index}.
$a->{index} = $a->{index}++ % 2;
Say $a->{index} is initially 0.
$a->{index}++ sets $a->{index} to 1 and returns 0 (the old value).
Then you assign 0 % 2, which is 0 to $a->{index}.
Options:
$a->{index} = ( $a->{index} + 1 ) % 2;
if ($a->{index}) {
...
}
or
$a->{index} = $a->{index} ? 0 : 1;
if ($a->{index}) {
...
}
or
$a->{index} = !$a->{index};
if ($a->{index}) {
...
}
or
if (++$a->{index} % 2) {
...
}
or
if ($a->{index}++ % 2) {
...
}
Note that the last two options leaves an ever-increasing value in $a->{index} rather than 0 or 1.
Note that the last two options differ in whether the condition will be true or false on the first pass.

Related

Sum of Printed For Loop in Swift

For a project, I'm trying to find the sum of the multiples of both 3 and 5 under 10,000 using Swift. Insert NoobJokes.
Printing the multiples of both 3 and 5 was fairly easy using a ForLoop, but I'm wondering how I can..."sum" all of the items that I printed.
for i in 0...10000 {
if i % 3 == 0 || i % 5 == 0 {
print(i)
}
}
(468 individual numbers printed; how can they be summed?)
Just a little walk through about the process. First you will need a variable which can hold the value of your sum, whenever loop will get execute. You can define an optional variable of type Int or initialize it with a default value same as I have done in the first line. Every time the loop will execute, i which is either multiple of 3 or 5 will be added to the totalSum and after last iteration you ll get your result.
var totalSum = 0
for i in 0...10000 {
if i % 3 == 0 || i % 5 == 0
{
print(i)
totalSum = totalSum + i
}
}
print (totalSum)
In Swift you can do it without a repeat loop:
let numberOfDivisiblesBy3And5 = (0...10000).filter{ $0 % 3 == 0 || $0 % 5 == 0 }.count
Or to get the sum of the items:
let sumOfDivisiblesBy3And5 = (0...10000).filter{ $0 % 3 == 0 || $0 % 5 == 0 }.reduce(0, {$0 + $1})
range : to specify the range of numbers for operation to act on.
here we are using filter method to filter out numbers that are multiple of 3 and 5 and then sum the filtered values.
(reduce(0,+) does the job)
let sum = (3...n).filter({($0 % 3) * ($0 % 5) == 0}).reduce(0,+)
You just need to sum the resulting i like below
var sum = 0
for i in 0...10000 {
if i % 3 == 0 || i % 5 == 0 {
sum = sum + i
print(i)
}
}
Now sum contains the Sum of the values
Try this:
var sum = 0
for i in 0...10000 {
if i % 3 == 0 || i % 5 == 0 {
sum = sum + i
print(i)
}
}
print(sum)
In the Bottom line, this should to be working.
var sum = 0
for i in 0...10000 {
if i % 3 == 0 || i % 5 == 0 {
sum += i
print(i)
}
}
print(sum)

perl - algorithm to replace multiple if statements using mod

I have a perl script that parses a large files. It works but it is slow and I see a pattern that i'd like to take advantage of, but i don't know how to write it.
there is a section where i count a number of objectIds, and have to return a value Spaces. The mininum number of *objectIds is 3 and increases in odd increments, my output starts at 3 and increases in multiples of three.
So i have a chain of 30 statements like this
if($objectIds == 3)
{
$spaces = 3;
}
if($objectIds == 5)
{
$spaces = 6;
}
if($objectIds == 7)
{
$spaces = 9;
}
I see that the difference is incrementing by a modulo of 1, i.e. (3 % 3 = 0), (6 % 5 = 1), (9 % 7 = 2), but i can't for the life of me figure out how to optimize this.
This formula should calculate and replace your ifs,
# $spaces = $objectIds + ($objectIds-3)/2;
# $spaces = (2*$objectIds + $objectIds-3)/2;
# $spaces = 3*($objectIds -1)/2;
$spaces = ($objectIds -1) * 3/2;
The first optimisation I see is to use elsif :
if($objectIds == 3)
{
$spaces = 3;
}
elsif($objectIds == 5)
{
$spaces = 6;
}
elsif($objectIds == 7)
{
$spaces = 9;
}

ios how to check if division remainder is integer

any of you knows how can I check if the division remainder is integer or zero?
if ( integer ( 3/2))
You should use the modulo operator like this
// a,b are ints
if ( a % b == 0) {
// remainder 0
} else
{
// b does not divide a evenly
}
It sounds like what you are looking for is the modulo operator %, which will give you the remainder of an operation.
3 % 2 // yields 1
3 % 1 // yields 0
3 % 4 // yields 1
However, if you want to actually perform the division first, you may need something a bit more complex, such as the following:
//Perform the division, then take the remainder modulo 1, which will
//yield any decimal values, which then you can compare to 0 to determine if it is
//an integer
if((a / b) % 1 > 0))
{
//All non-integer values go here
}
else
{
//All integer values go here
}
Walkthrough
(3 / 2) // yields 1.5
1.5 % 1 // yields 0.5
0.5 > 0 // true
swift 3:
if a.truncatingRemainder(dividingBy: b) == 0 {
//All integer values go here
}else{
//All non-integer values go here
}
You can use the below code to know which type of instance it is.
var val = 3/2
var integerType = Mirror(reflecting: val)
if integerType.subjectType == Int.self {
print("Yes, the value is an integer")
}else{
print("No, the value is not an integer")
}
let me know if the above was useful.
Swift 5
if numberOne.isMultiple(of: numberTwo) { ... }
Swift 4 or less
if numberOne % numberTwo == 0 { ... }
Swift 2.0
print(Int(Float(9) % Float(4))) // result 1

simple loop in coffeescript

I have this code:
count = $content.find('.post').length;
for x in [1...count]
/*
prev_el_height += $("#content .post:nth-child(" + x + ")").height();
*/
prev_el_height += $content.find(".post:nth-child(" + x + ")").height();
I expected this to turn into
for (x = 1; x < count; x++) { prev_el ... }
but it turns into this:
for (x = 1; 1 <= count ? x < count : x > count; 1 <= count ? x++ : x--) {
Can somebody please explain why?
EDIT: How do I get my expected syntax to output?
In CoffeeScript, you need to use the by keyword to specify the step of a loop. In your case:
for x in [1...count] by 1
...
You're asking to loop from 1 to count, but you're assuming that count will always be greater-than-or-equal-to one; the generated code doesn't make that assumption.
So if count is >= 1 then the loop counter is incremented each time:
for (x = 1; x < count; x++) { /* ... */ }
But if count is < 1 then the loop counter is decremented each time:
for (x = 1; x > count; x--) { /* ... */ }
Well, you want x to go from 1 to count. The code is checking whether count is bigger or smaller than 1.
If count is bigger than 1, then it has to increment x while it is smaller than count.
If count is smaller than 1, then it has to decrement x while it is bigger than count.
For future reference:
$('#content .post').each ->
prev_el_height += $(this).height()
Has the same effect, assuming :nth-child is equivalent to .eq(), and x going past the number the elements is a typo.

How can I create combinations of several lists without hardcoding loops?

I have data that looks like this:
my #homopol = (
["T","C","CC","G"], # part1
["T","TT","C","G","A"], #part2
["C","CCC","G"], #part3 ...upto part K=~50
);
my #prob = ([1.00,0.63,0.002,1.00,0.83],
[0.72,0.03,1.00, 0.85,1.00],
[1.00,0.97,0.02]);
# Note also that the dimension of #homopol is always exactly the same with #prob.
# Although number of elements can differ from 'part' to 'part'.
What I want to do is to
Generate all combinations of elements in part1 through out partK
Find the product of the corresponding elements in #prob.
Hence at the end we hope to get this output:
T-T-C 1 x 0.72 x 1 = 0.720
T-T-CCC 1 x 0.72 x 0.97 = 0.698
T-T-G 1 x 0.72 x 0.02 = 0.014
...
G-G-G 1 x 0.85 x 0.02 = 0.017
G-A-C 1 x 1 x 1 = 1.000
G-A-CCC 1 x 1 x 0.97 = 0.970
G-A-G 1 x 1 x 0.02 = 0.020
The problem is that the following code of mine does that by hardcoding
the loops. Since the number of parts of #homopol is can be varied and large
(e.g. ~K=50), we need a flexible and compact way to get the same result. Is there any?
I was thinking to use Algorithm::Loops, but not sure how to achieve that.
use strict;
use Data::Dumper;
use Carp;
my #homopol = (["T","C","CC","G"],
["T","TT","C","G","A"],
["C","CCC","G"]);
my #prob = ([1.00,0.63,0.002,1.00,0.83],
[0.72,0.03,1.00, 0.85,1.00],
[1.00,0.97,0.02]);
my $i_of_part1 = -1;
foreach my $base_part1 ( #{ $homopol[0] } ) {
$i_of_part1++;
my $probpart1 = $prob[0]->[$i_of_part1];
my $i_of_part2 =-1;
foreach my $base_part2 ( #{ $homopol[1] } ) {
$i_of_part2++;
my $probpart2 = $prob[1]->[$i_of_part2];
my $i_of_part3 = -1;
foreach my $base_part3 ( #{ $homopol[2] } ) {
$i_of_part3++;
my $probpart3 = $prob[2]->[$i_of_part3];
my $nstr = $base_part1."".$base_part2."".$base_part3;
my $prob_prod = sprintf("%.3f",$probpart1 * $probpart2 *$probpart3);
print "$base_part1-$base_part2-$base_part3 \t";
print "$probpart1 x $probpart2 x $probpart3 = $prob_prod\n";
}
}
}
I would recommend Set::CrossProduct, which will create an iterator to yield the cross product of all of your sets. Because it uses an iterator, it does not need to generate every combination in advance; rather, it yields each one on demand.
use strict;
use warnings;
use Set::CrossProduct;
my #homopol = (
[qw(T C CC G)],
[qw(T TT C G A)],
[qw(C CCC G)],
);
my #prob = (
[1.00,0.63,0.002,1.00],
[0.72,0.03,1.00, 0.85,1.00],
[1.00,0.97,0.02],
);
# Prepare by storing the data in a list of lists of pairs.
my #combined;
for my $i (0 .. $#homopol){
push #combined, [];
push #{$combined[-1]}, [$homopol[$i][$_], $prob[$i][$_]]
for 0 .. #{$homopol[$i]} - 1;
};
my $iterator = Set::CrossProduct->new([ #combined ]);
while( my $tuple = $iterator->get ){
my #h = map { $_->[0] } #$tuple;
my #p = map { $_->[1] } #$tuple;
my $product = 1;
$product *= $_ for #p;
print join('-', #h), ' ', join(' x ', #p), ' = ', $product, "\n";
}
A solution using Algorithm::Loops without changing the input data would look something like:
use Algorithm::Loops;
# Turns ([a, b, c], [d, e], ...) into ([0, 1, 2], [0, 1], ...)
my #lists_of_indices = map { [ 0 .. #$_ ] } #homopol;
NestedLoops( [ #lists_of_indices ], sub {
my #indices = #_;
my $prob_prod = 1; # Multiplicative identity
my #base_string;
my #prob_string;
for my $n (0 .. $#indices) {
push #base_string, $hompol[$n][ $indices[$n] ];
push #prob_string, sprintf("%.3f", $prob[$n][ $indices[$n] ]);
$prob_prod *= $prob[$n][ $indices[$n] ];
}
print join "-", #base_string; print "\t";
print join "x", #prob_string; print " = ";
printf "%.3f\n", $prob_prod;
});
But I think that you could actually make the code clearer by changing the structure to one more like
[
{ T => 1.00, C => 0.63, CC => 0.002, G => 0.83 },
{ T => 0.72, TT => 0.03, ... },
...
]
because without the parallel data structures you can simply iterate over the available base sequences, instead of iterating over indices and then looking up those indices in two different places.
Why don't you use recursion? Pass the depth as a parameter and let the function call itself with depth+1 inside the loop.
you could do it by creating an array of indicies the same length as the #homopol array (N say), to keep track of which combination you are looking at. In fact this array is just like a
number in base N, with the elements being the digits. Iterate in the same way as you would write down consectutive numbers in base N, e.g (0 0 0 ... 0), (0 0 0 ... 1), ...,(0 0 0 ... N-1), (0 0 0 ... 1 0), ....
Approach 1: Calculation from indices
Compute the product of lengths in homopol (length1 * length2 * ... * lengthN). Then, iterate i from zero to the product. Now, the indices you want are i % length1, (i / length1)%length2, (i / length1 / length2) % length3, ...
Approach 2: Recursion
I got beaten to it, see nikie's answer. :-)