Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions diag_trav.pl
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
#!/usr/bin/perl
use 5.016;
use DDP;
use List::Util qw /min max/;
# Given a matrix of M x N elements (M rows, N columns), return all elements
#of the matrix in diagonal order as shown in the below image.

# Example:

# Input:
# [
# [ 1, 2, 3 ],
# [ 4, 5, 6 ],
# [ 7, 8, 9 ]
# ]
# Output: [1,2,4,7,5,3,6,8,9]
#my @matrix = ([1,2,3,4],[5,6,7,8],[9,10,11,12]);
my @matrix = ([1,2,3],[4,5,6]);
# 1 2 3 4
# 5 6 7 8
# 9 10 11 12

# 13 14 15 16
my $A = $#matrix;
my $B = scalar(@{$matrix[0]}) - 1;
sub diag_down {
my $matrix = shift;
my ($i, $j) = @_;
my @res;
push @res, $matrix->[$i][$j];

while ($i != $#matrix and $j != 0) {
$i++;
$j--;
push @res, $matrix->[$i][$j];
}
return \@res;
}

my @res;
my $ans;
my $flag = 1;
for my $i (0..$B) {
$ans = diag_down(\@matrix, 0, $i);
if ($flag) {
$ans = [reverse @{$ans}];
$flag = 0;
} else {
$flag = 1;
}
push @res, @{$ans};
}

for my $i (1..$A) {
$ans = diag_down(\@matrix, $i, $B);
if ($flag) {
$ans = [reverse @{$ans}];
$flag = 0;
} else {
$flag = 1;
}
push @res, @{$ans};
}
# my $ans = diag_down(\@matrix, 0,1);
# p $ans;

p @res;
# 0,0 up
# 0,1 down
# 0,2

# 1,2
# 2,2
44 changes: 44 additions & 0 deletions diag_trav.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#!/usr/bin/python
class Solution:
def diag_down(self, i, j):
res = []
res.append(self.matrix[i][j])
while (i != self.A - 1 and j != 0):
i = i + 1
j = j - 1
res.append(self.matrix[i][j])
return res

def findDiagonalOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
self.matrix = matrix
if (len(matrix) == 0):
return matrix
self.A = len(matrix)
self.B = len(matrix[0])
res = []
flag = True
for i in range(self.B):
ans = self.diag_down(0, i);
if (flag):
ans = ans[::-1]
flag = False
else:
flag = True
res += ans
for i in range(1,self.A):
ans = self.diag_down(i,self.B - 1)
if (flag):
ans = ans[::-1]
flag = False
else:
flag = True
res += ans
return res

s = Solution()

print(s.findDiagonalOrder([[2,3]]))
Empty file added file.txt
Empty file.
22 changes: 22 additions & 0 deletions happy_number.pl
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/perl
use 5.016;
use DDP;
use List::Util qw/sum/;
my $num = <>;
chomp $num;

my %seen;
my $res = 1;
while () {
if (exists $seen{$num}) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а зачем if exists?
не лучше бы просто if ($seen) ?

$res = 0;
last;
}
$seen{$num}++;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тут лучше ставить $seen{$num} = 1, так как ++ только путает читателя. Ведь нам не нужно же количество?

$num = sum map {$_**2} split //, $num;
p $num;
sleep(1);
last if ($num == 1);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

скобки лишние, я бы убрал

}

say $res;
73 changes: 73 additions & 0 deletions hash/minimum_index_sum_of_two_lists.pl
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
#!/usr/bin/perl
#Suppose Andy and Doris want to choose a restaurant for dinner, and
#they both have a list of favorite restaurants represented by strings.
#You need to help them find out their common interest with the
#least list index sum. If there is a choice tie between answers,
#output all of them with no order requirement. You could assume there always exists an answer.

# Input:
# ["Shogun", "Tapioca Express", "Burger King", "KFC"]
# ["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
# Output: ["Shogun"]
# Explanation: The only restaurant they both like is "Shogun".

# Input:
# ["Shogun", "Tapioca Express", "Burger King", "KFC"]
# ["KFC", "Shogun", "Burger King"]
# Output: ["Shogun"]
# Explanation: The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1).
use 5.016;
use DDP;
use List::Util qw/min/;
use Test::More;

#строим 2 ассоциативных массива, по исходному.
#$arr1{"Shogun"} == "1", $arr1{"Tapioca Express"}
#$arr2{"KFC"} == "1", $arr2{"Shogun"} == 1
#строим пересечение и в значении ставим сумму индексов.

# my @arr1 = ("Shogun", "Tapioca Express", "Burger King", "KFC", "1");
# my @arr2 = ("Burger King", "The Grill at Torrey Pines", "Tapioca Express", "Shogun", "1");

my (%arr1, %arr2);
for (1..10) {
$arr1{int rand 20} = 1;
$arr2{int rand 20} = 1;
}

my @arr1 = keys %arr1;
my @arr2 = keys %arr2;
say '@arr1:';
p @arr1;
say '@arr2:';
p @arr2;
sub func {
my ($arr1, $arr2) = @_;
my @hash1 = map {$arr1->[$_] => $_} (0..$#$arr1); #O(N)
my @hash2 = map {$arr2->[$_] => $_} (0..$#$arr2); #O(N)
my %hash1 = @hash1; #O(1)
my %hash2 = @hash2; #O(1)
say '%hash1:';
p %hash1;
say '%hash2:';
p %hash2;

my %interest = map {$_ => $hash1{$_} + $hash2{$_}} grep {exists $hash2{$_}} keys %hash1; #O(N log N)
say 'interest';
p %interest;

my %answer;
my $min = $#arr1 + $#arr2; #O(1)
for (keys %interest) { #O (N log N)
$answer{$interest{$_}} //= [];
push @{$answer{$interest{$_}}}, $_;
$min = $interest{$_} if $interest{$_} < $min;
}
say '%answer';
p %answer;
say '$res:';
my $res = $answer{$min}; #O(1)
p $res;
}

func(\@arr1, \@arr2);
16 changes: 16 additions & 0 deletions partition.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#!/usr/bin/python3
class Solution:
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(sorted(nums)[0:len(nums) // 2])

s = Solution()

print(s.arrayPairSum([1,2,3,4]))




44 changes: 44 additions & 0 deletions pascal.pl
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#!/usr/bin/perl
use 5.016;
use DDP;
# Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.


# In Pascal's triangle, each number is the sum of the two numbers directly above it.

# Example:

# Input: 5
# Output:
# [
# [1],
# [1,1],
# [1,2,1],
# [1,3,3,1],
# [1,4,6,4,1]
# ]




my $count = <>;
my $level = [1];
sub next_level {
my $arr = shift;
my @res;
my $first = 0;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

переменная first запутывает...

for my $i (@{$arr}) {
push @res, $i + $first;
$first = $i;
}
push @res, @{$arr}[-1];
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лучше написать тупым и очевидным образом. Ведь код в первую очередь для человека:

sub next_level {
    my ($level) = @_;
    
    my @next_level;
    
    push @next_level, 1;
    
    for (my $i = 0; $i < @$level - 1; ++$i) {
        push @next_level, $level->[$i] + $level->[$i + 1];
    }
    
    push @next_level, 1;
    
    return \@next_level;
}

return \@res;
}
my @res;
push @res, $level;
for (1..$count - 1) {
Copy link
Collaborator

@nurzhan-saktaganov nurzhan-saktaganov Jul 3, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лучше явно вынести все в функции имхо: main, next_level, get_first_n_rows
про вынос в main -- ко всем

$level = next_level($level);
push @res, $level;
}

p @res;
52 changes: 52 additions & 0 deletions pivot.pl
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#!/usr/bin/perl
# Given an array of integers nums, write a method that returns the "pivot" index of this array.

# We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.

# If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.

# Example 1:

# Input:
# nums = [1, 7, 3, 6, 5, 6]
# Output: 3
# Explanation:
# The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
# Also, 3 is the first index where this occurs.

# Example 2:

# Input:
# nums = [1, 2, 3]
# Output: -1
# Explanation:
# There is no index that satisfies the conditions in the problem statement.

use 5.016;
use DDP;
use integer;
my @a = @{[0,1]};
p @a;

sub return_pivod(@) {
my @arr = @_;
return -1 unless (@arr);
Copy link
Collaborator

@nurzhan-saktaganov nurzhan-saktaganov Jul 3, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Как минимум должно быть 3 элемента.

return -1 if @arr < 3;


my $pivot = 0;
my $sum_left = 0;
my $sum_right = 0;
for (1..$#arr) {
$sum_right += $arr[$_];
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe? :)

use List::Util qw(sum);
...
my $sum_right = sum(@arr) - $arr[0]; 

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Хотяяя, пивотом могут быть индексы 1 <= pivot <= len(arr) - 2?

Так как крайние элементы им быть не могут.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Эту задачу надо дополнительно обсудить, после твоего ответа.

}
while ($sum_left != $sum_right) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я бы в коде сделал акцент на том, что перебирается каждая позиция пивота.
И для каждой позиции проверятся равность суммы.

use strict;
use warnings;

use List::Util qw(sum);

sub find_pivot {
    my @a = @_;
    
    return -1 if @a < 3;
    
    my $sum_l = $a[0];
    my $sum_r = sum(@a) - sum(@a[0,1]);
    
    for my $i (1..$#a - 1) {
        return $i if $sum_l == $sum_r;
        $sum_l += $a[$i];
        $sum_r -= $a[$i + 1];
    }
    return -1;
}

my @a = (1, 7, 3, 6, 5, 6);

print find_pivot(@a) . "\n";

last if $pivot + 1 > $#arr;
$sum_left += $arr[$pivot];
$sum_right -= $arr[$pivot + 1];
$pivot++;

}
return $pivot > $#arr ? -1 : $pivot;
}

say return_pivod(@a);
reverse
26 changes: 26 additions & 0 deletions pivot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#!/usr/bin/python3
nums = [0,1]
class Solution:
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if (len(nums) == 0):
return -1
pivot = 0
sum_left = 0
sum_right = sum(nums[1:])
while(sum_left != sum_right):
if (pivot + 1 > len(nums) - 1):
break
sum_left += nums[pivot]
sum_right -= nums[pivot + 1]
pivot = pivot + 1

if (sum_right != sum_left):
pivot = -1
return pivot

p = Solution()
print (p.pivotIndex(nums))
23 changes: 23 additions & 0 deletions reverse.pl
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#!/usr/bin/perl
use 5.016;
use DDP;
my $str = <>;
# Write a function that takes a string as input and returns the string reversed.

# Example:
# Given s = "hello", return "olleh".
chomp $str;
my @string = split //,$str;
p @string;

my $i = 0;
my $j = $#string;
while ($i < $j) {
my $tmp = $string[$i];
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 за in place reverse.

$string[$i] = $string[$j];
$string[$j] = $tmp;
$i++;
$j--;
}

p @string;
10 changes: 10 additions & 0 deletions single_number.pl
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/usr/bin/perl
use 5.016;
use DDP;
my @arr1 = (1, 2, 2, 1);
my @arr2 = (2, 2);
my $res = 0;
my %hash;
@hash{@arr1} = ();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Эта строка лишняя

my @intersect = grep {!$hash{$_}++} @arr2;
p @intersect;
Loading