selecting unique random number to each row and column in table using php - unique

If I select range the number 1 to 2 , the output will come in matrix format 2X2 as,
1st row =>1and2
2nd row =>2and1
(OR)
1st row =>2and1
2nd row =>1and2
If I select range the number 1 to 3 , the output will come in matrix format 3X3 as,
1 2 3,
2 3 1,
3 1 2
(OR)
2 1 3,
3 2 1,
1 3 2
whatever the output may come, But each cell value shouldn't come again in the same row and column.
If I select range the number 1 to 4 , the output will come in matrix 4X4 format as,
4 2 1 3,
1 4 3 2,
2 3 2 4,
3 1 4 1
I need to shuffle the range. I wish to clear this concept using php. Pls. anyone help.....

Since one answer is always known; [a, b, c] => [ [ a, b, c], [ b, c, a ], [ c, a, b ] ], basically a repeating array_shift.
$startValue = 1;
$endValue = 3;
$arr = [];
for($idx = $startValue; $idx < $endValue + 1; ++$idx)
array_push($arr, $idx);
$result = [ $arr ];
$row = $arr;
while(count($result) < count($arr)) {
array_push($row, array_shift($row));
array_push($result, $row);
}
print_r($result);
Result:
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 2
[1] => 3
[2] => 1
)
[2] => Array
(
[0] => 3
[1] => 1
[2] => 2
)
)

Related

Shuffle the rows of specific columns of table in Perl

I have a table file and I want to shuffle the rows of specific columns in Perl.
For example, I have this array:
a 1
b 2
c 3
d 4
e 5
f 6
and I want to shuffle the second column to get something like this:
a 2
b 1
c 3
d 4
e 5
f 6
Using List::Util::shuffle might be a good idea. I used a Schwartzian transform to create a list of random numbers, sort them, and insert the column data based on the array index.
use strict;
use warnings;
use feature 'say';
my #col;
while (<DATA>) {
push #col, [ split ];
}
my #shuffled = map { $col[$_->[0]][1] } # map to #col values
sort { $a->[1] <=> $b->[1] } # sort based on rand() value
map { [ $_, rand() ] } # each index mapped into array of index and rand()
0 .. $#col; # list of indexes of #col
for my $index (0 .. $#col) {
say join " ", $col[$index][0], $shuffled[$index];
}
__DATA__
a 1
b 2
c 3
d 4
e 5
f 6
I can use this script to do the job:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw/shuffle/;
my #c = split /,/, $ARGV[0];
$_-- for #c;
shift;
my #lines;
my #v;
while ( <> ) {
my #items = split;
$v[$.-1] = [#items[#c]];
$lines[$.-1] = [#items];
}
my #order = shuffle (0..$#lines);
for my $l (0..$#lines) {
my #items = #{ $lines[$l] };
#items[#c] = #{ $lines[$order[$l]] }[#c];
print "#items\n";
}
This script uses List::Util which is part of Perl core modules since perl v5.7.3: corelist List::Util
It can be launched with perl shuffle.pl 2 test.txt
Demo code for a case when external modules are not permitted.
use strict;
use warnings;
use feature 'say';
my %data;
while( <DATA> ) {
my($l,$d) = split;
$data{$l} = $d;
}
say '- Loaded --------------------';
say "$_ => $data{$_}" for sort keys %data;
for( 0..5 ) {
#data{ keys %data} = #{ shuffle([values %data]) };
say "-- $_ " . '-' x 24;
say "$_ => $data{$_}" for sort keys %data;
}
sub shuffle {
my $data = shift;
my($seen, $r, $i);
my $n = $#$data;
for ( 0..$n ) {
do {
$i = int(rand($n+1));
} while defined $seen->{$i};
$seen->{$i} = 1;
$r->[$_] = $data->[$i];
}
return $r;
}
__DATA__
a 1
b 2
c 3
d 4
e 5
f 6
Output
- Loaded --------------------
a => 1
b => 2
c => 3
d => 4
e => 5
f => 6
-- 0 ------------------------
a => 5
b => 4
c => 2
d => 6
e => 1
f => 3
-- 1 ------------------------
a => 3
b => 6
c => 2
d => 4
e => 1
f => 5
-- 2 ------------------------
a => 4
b => 5
c => 6
d => 1
e => 3
f => 2
-- 3 ------------------------
a => 6
b => 4
c => 1
d => 2
e => 3
f => 5
-- 4 ------------------------
a => 3
b => 4
c => 6
d => 5
e => 1
f => 2
-- 5 ------------------------
a => 6
b => 5
c => 3
d => 4
e => 2
f => 1

How to group by in Entity Framework Core with no repetitive group?

I want to perform a group by in Entity Framework core with no repetitive groups.
Lets suppose I have two columns
Column A Column B
1 1
2 1
2 1
4 5
5 4
If a group by is performed for two columns Entity framework core the result is pretty obvious.
Column A Column B
1 1
2 1
4 5
5 4
But i want to perform a group by which works both ways A->B and B->A hence the result would be
Column A Column B
1 1
2 1
5 4
Any idea how to do that in Entity Framework Core?
My original attempt was to use Union
var user = _context.Transactions
.Where(p => !p.IsDeleted && (p.ReceiverUserId == userId) &&
(p.SenderUserId != null))
.Include(p => p.SenderUser)
.GroupBy(p => p.SenderUserId)
.Select(p => new TempModel { Id = p.FirstOrDefault().SenderUser.Id, User = p.FirstOrDefault().SenderUser, CreatedDate = p.FirstOrDefault().CreatedDate });
var user2 = _context.Transactions
.Where(p => !p.IsDeleted && (p.SenderUserId == userId) &&
(p.ReceiverUserId != null))
.Include(p => p.ReceiverUser)
.GroupBy(p => p.ReceiverUserId)
.Select(p => new TempModel { Id = p.FirstOrDefault().ReceiverUser.Id, User = p.FirstOrDefault().ReceiverUser, CreatedDate = p.FirstOrDefault().CreatedDate});
var finalQuery = user.Union(user2);
var finalQuery2 = finalQuery.GroupBy(p => p.Id);
var finalQuery1 = finalQuery2.OrderByDescending(p => p.FirstOrDefault().CreatedDate);
finalQuery.GroupBy(p => p.Id); <- this line gives error
You should sort these columns by descending: 4-5 => 5-4; 5-4 => 5-4;
5-5 => 5-5 and then group by or distinc by them:
var answer = db.Table.Select(x => new
{
ColumnA = x.ColumnA > x.ColumnB ? x.ColumnA : x.ColumnB,
ColumnB = x.ColumnA > x.ColumnB ? x.ColumnB : x.ColumnA
}).Distinct().ToList();

Rails Multiplying value of afcolumn using ActiveRecord

I want to multiply a value of an specific column considering the user id.
Assume I have a table users with user 1 (id 1) and user 2 (id 2), and a table animals which has name and mensal_cost.
Ok, then I added two animals for user 1 (id 1) and 1 animal for user 2 (id 2)
I want to know how I can using ActiveRecord calculates the mensal_cost income after 3 months increasing the same base value, it means I have to multiply the actual value by 3.
I'm trying something like this:
Animal.where(user_id: ?).sum('3*mensal_cost')
Since I don't know how many users can exist, I must write a call which will list for each user id the amount after 3 months.
Ok, you nearly had it on your own - just the minor details can be like this:
user_ids = [id1, id2]
full_sum = 3 * Animal.where(:user_id => user_ids).sum(:mensal_cost)
Note: don't forget you can multiply by three after summing and it'll be the same as summing each one multiplied by 3 eg
(3 * 2) + (3 * 3) + (3 * 4) == 3 * (2 + 3 + 4)
or you can iterate through the users to get their individual sums like so:
mensal_sums = {}
user_ids = [id1, id2]
user_ids.each do |user_id|
mensal_sums[user_id] = 3 * Animal.where(:user_id => user_id).sum(:mensal_cost)
end
puts mensal_sums
=> {id1 => 63, id2 => 27}
EDIT
and one where you want the user name as well:
mensal_sums = {}
users = User.find([id1, id2])
users.each do |user|
mensal_sums[user.id] = {:user_name => user.name,
:sum => (3 * user.animals.sum(:mensal_cost)) }
end
puts mensal_sums
=> {id1 => {:user_name => "Bob Jones", :sum => 63},
id2 => {:user_name => "cJane Brown", :sum =>27}
}
I just figured out the solution:
Animal.group('user_id').sum('3*mensal_cost')
the group was the key :D

how to define dynamic nested loop python function

a = [1]
b = [2,3]
c = [4,5,6]
d = [a,b,c]
for x0 in d[0]:
for x1 in d[1]:
for x2 in d[2]:
print(x0,x1,x2)
Result:
1 2 4
1 2 5
1 2 6
1 3 4
1 3 5
1 3 6
Perfect, now my question is how to define this to function, considering ofcourse there could be more lists with values. The idea is to get function, which would dynamicaly produce same result.
Is there a way to explain to python: "do 8 nested loops for example"?
You can use itertools to calculate the products for you and can use the * operator to convert your list into arguments for the itertools.product() function.
import itertools
a = [1]
b = [2,3]
c = [4,5,6]
args = [a,b,c]
for combination in itertools.product(*args):
print combination
Output is
(1, 2, 4)
(1, 2, 5)
(1, 2, 6)
(1, 3, 4)
(1, 3, 5)
(1, 3, 6)

Sum of all even values of an array?AS3

I need to sum all the even values from my array, so here is an example of it:
Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
[4] => 4
[5] => 6
[6] => 6
)
looking a way to sum all from same value:
Array
(
[1] => 4
[4] => 1
[6] => 2
)
Any ideas?
var buckets:Object = {};
var data:Array = [1, 1, 1, 1, 4, 6, 6];
for(var i=0; i<data.length; ++i) {
if(!buckets[data[i]]) {
buckets[data[i]] = 1;
} else {
buckets[data[i]]++;
}
}
trace(buckets);
Try this:
var sum:uint = 0; //Setting the sum value to 0;
for(var i:uint = 0; i < nameOfArray.length; i++){ //Loops trough the array
if(nameOfArray[i] % 2 == 0 ){ //If the number is an even number
sum+=nameOfArray[i]; //Add that even number to the sum variable
}
}
trace(sum) // Prints out the sum
You could create a map & loop through your array, adding the values into you're map. If you don't know what a map is, it is basically a collection type. It is created using a pair, using a unique key & a value associated with it. In your case, the unique key will be the number value in the array and the value will be the number of times it appears (frequency).