Skip to content

Instantly share code, notes, and snippets.

@ryukinix
Created August 4, 2017 01:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryukinix/06cd20381b11492be2d45f39a279f617 to your computer and use it in GitHub Desktop.
Save ryukinix/06cd20381b11492be2d45f39a279f617 to your computer and use it in GitHub Desktop.
Minha solução para um problema de matemática durante uma entrevista de emprego (Brick Abode)
# coding: utf-8
# Triangle
# Triangle: Determine whether a triangle can be built from a given set of edges
# A zero-indexed array A consisting of N integers is given. A triplet (P, Q,
# R) is triangular if 0 ≤ P < Q < R < N and:
#
# A[P] + A[Q] > A[R], <=> A[P] <= A[P] + A[Q]
# A[Q] + A[R] > A[P], <=> A[P] <= A[Q] + A[R]
# A[R] + A[P] > A[Q]. <=> A[R] <= A[P] + A[R]
#
# For example, consider array A such that:
# A[0] = 10 A[1] = 2 A[2] = 5 A[3] = 1 A[4] = 8 A[5] = 20
# Triplet (0, 2, 4) is triangular.
# Write a function:
# int solution(int A[], int N);
# that, given a zero-indexed array A consisting of N integers, returns 1 if
# there exists a triangular triplet for this array and returns 0 otherwise.
# For example, given array A such that:
# A[0] = 10 A[1] = 2 A[2] = 5 A[3] = 1 A[4] = 8 A[5] = 20
# the function should return 1, as explained above. Given array A such that:
# A[0] = 10 A[1] = 50 A[2] = 5 A[3] = 1
# the function should return 0.
#
import itertools
test_case_1 = [10, 2, 5, 1, 8, 20]
# [1, 2, 5, 8, 10, 20]
test_case_2 = [10, 50, 5, 1]
def is_triangle(triple):
a, b, c = triple
if a + b > c and b + c > a and a + c > b:
return True
return False
def solution(l):
triplet = itertools.combinations(l, 3) # O(n!)
for comb in triplet:
if is_triangle(comb):
return True
return False
def solution_fast(l):
A = sorted(l) # sort -> O(n*log(n))
n = len(l)
for i in range(n - 2): # O(n)
if (A[i] + A[i+1]) > A[i+2]:
return True
return False
# def solution_oneline(l):
# return any(a + b > c for a, b, c in (sorted(l))) # doesn't compile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment