text
stringlengths 2
104M
| meta
dict |
---|---|
# Alphabet Rangoli
# Let's draw rangoli.
#
# https://www.hackerrank.com/challenges/alphabet-rangoli/problem
#
def print_rangoli(size):
# your code goes here
size -= 1
for y in range(-size, size + 1):
s = ''
for x in range(-size * 2, size * 2 + 1):
if x % 2 == 0 and abs(x // 2) <= size - abs(y):
s += chr(97 + abs(x // 2) + abs(y))
else:
s += '-'
print(s)
# (skeliton_tail) ----------------------------------------------------------------------
if __name__ == '__main__':
n = int(input())
print_rangoli(n)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Python > Strings > Text Wrap
# Wrap the given text in a fixed width.
#
# https://www.hackerrank.com/challenges/text-wrap/problem
#
import textwrap
# (skeliton_head) ----------------------------------------------------------------------
def wrap(string, max_width):
return "\n".join(string[i:i + max_width] for i in range(0, len(string), max_width))
# (skeliton_tail) ----------------------------------------------------------------------
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Python](https://www.hackerrank.com/domains/python)
A step by step guide to Python, a language that is easy to pick up yet one of the most powerful.
#### [Strings](https://www.hackerrank.com/domains/python/py-strings)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[sWAP cASE](https://www.hackerrank.com/challenges/swap-case)|Swap the letter cases of a given string.|[Python](swap-case.py)|Easy
[String Split and Join](https://www.hackerrank.com/challenges/python-string-split-and-join)|Use Python's split and join methods on the input string.|[Python](python-string-split-and-join.py)|Easy
[What's Your Name?](https://www.hackerrank.com/challenges/whats-your-name)|Python string practice: Print your name in the console.|[Python](whats-your-name.py)|Easy
[Mutations](https://www.hackerrank.com/challenges/python-mutations)|Understand immutable vs mutable by making changes to a given string.|[Python](python-mutations.py)|Easy
[Find a string](https://www.hackerrank.com/challenges/find-a-string)|Find the number of occurrences of a substring in a string.|[Python](find-a-string.py)|Easy
[String Validators](https://www.hackerrank.com/challenges/string-validators)|Identify the presence of alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters in a string.|[Python](string-validators.py)|Easy
[Text Alignment](https://www.hackerrank.com/challenges/text-alignment)|Generate the Hackerrank logo with alignments in Python.|[Python](text-alignment.py)|Easy
[Text Wrap](https://www.hackerrank.com/challenges/text-wrap)|Wrap the given text in a fixed width.|[Python](text-wrap.py)|Easy
[Designer Door Mat](https://www.hackerrank.com/challenges/designer-door-mat)|Print a designer door mat.|[Python](designer-door-mat.py)|Easy
[String Formatting](https://www.hackerrank.com/challenges/python-string-formatting)|Print the formatted decimal, octal, hexadecimal, and binary values for $n$ integers.|[Python](python-string-formatting.py)|Easy
[Alphabet Rangoli](https://www.hackerrank.com/challenges/alphabet-rangoli)|Let's draw rangoli.|[Python](alphabet-rangoli.py)|Easy
[Capitalize!](https://www.hackerrank.com/challenges/capitalize)|Capitalize Each Word.|[Python](capitalize.py)|Easy
[The Minion Game](https://www.hackerrank.com/challenges/the-minion-game)|Given a string, judge the winner of the minion game.|[Python](the-minion-game.py)|Medium
[Merge the Tools!](https://www.hackerrank.com/challenges/merge-the-tools)|Split a string into subsegments of length $k$, then print each subsegment with any duplicate characters stripped out.|[Python](merge-the-tools.py)|Medium
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Python > Strings > String Validators
# Identify the presence of alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters in a string.
#
# https://www.hackerrank.com/challenges/string-validators/problem
#
if __name__ == '__main__':
s = input()
# any alphanumeric characters
print(any(c.isalnum() for c in s))
# any alphabetical characters
print(any(c.isalpha() for c in s))
# any digits
print(any(c.isdigit() for c in s))
# any lowercase characters
print(any(c.islower() for c in s))
# any uppercase characters
print(any(c.isupper() for c in s))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank_py(default-arguments.py)
add_hackerrank_py(words-score.py)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Python > Debugging > Words Score
# Calculate the total score of the list of words.
#
# https://www.hackerrank.com/challenges/words-score/problem
# challenge id: 66426
#
def is_vowel(letter):
return letter in ['a', 'e', 'i', 'o', 'u', 'y']
def score_words(words):
score = 0
for word in words:
num_vowels = 0
for letter in word:
if is_vowel(letter):
num_vowels += 1
if num_vowels % 2 == 0:
score += 2
else:
score += 1
return score
# (skeliton_tail) ----------------------------------------------------------------------
n = int(input())
words = input().split()
print(score_words(words))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Python](https://www.hackerrank.com/domains/python)
A step by step guide to Python, a language that is easy to pick up yet one of the most powerful.
#### [Debugging](https://www.hackerrank.com/domains/python/py-debugging)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Words Score](https://www.hackerrank.com/challenges/words-score)|Calculate the total score of the list of words.|[Python](words-score.py)|Medium
[Default Arguments](https://www.hackerrank.com/challenges/default-arguments)|Debug a function which uses a default value for one of its arguments.|[Python](default-arguments.py)|Medium
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Python > Debugging > Default Arguments
# Debug a function which uses a default value for one of its arguments.
#
# https://www.hackerrank.com/challenges/default-arguments/problem
# challenge id: 66403
#
class EvenStream(object):
def __init__(self):
self.current = 0
def get_next(self):
to_return = self.current
self.current += 2
return to_return
class OddStream(object):
def __init__(self):
self.current = 1
def get_next(self):
to_return = self.current
self.current += 2
return to_return
# (skeliton_head) ----------------------------------------------------------------------
def print_from_stream(n, stream=None):
if stream is None:
stream = EvenStream()
for _ in range(n):
print(stream.get_next())
# probable error of author during conversion from Python2 to Python3...
raw_input = input
# (skeliton_tail) ----------------------------------------------------------------------
queries = int(input())
for _ in range(queries):
stream_name, n = raw_input().split()
n = int(n)
if stream_name == "even":
print_from_stream(n)
else:
print_from_stream(n, OddStream())
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Python > Built-Ins > Zipped!
# Compute the average by zipping data.
#
# https://www.hackerrank.com/challenges/zipped/problem
#
n, x = map(int, input().split())
a = []
for _ in range(x):
a.append(list( map(float, input().split())))
for i in zip(*a):
print(sum(i) / x) | {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Python > Built-Ins > Any or All
# Return True, if any of the iterable is true or if all of it is true using the any() and all() expressions.
#
# https://www.hackerrank.com/challenges/any-or-all/problem
#
_, arr = input(), list(map(int, input().split()))
print(all(i >= 0 for i in arr) and any((i < 10 or i % 11 == 0) for i in arr))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Python > Built-Ins > Athlete Sort
# Sort the table on the kth attribute.
#
# https://www.hackerrank.com/challenges/python-sort-sort/problem
#
import operator
n, m = map(int, input().split())
arr = [list(map(int, input().split())) for _ in range(n)]
k = int(input())
for i in sorted(arr, key=operator.itemgetter(k)):
print(*i)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Python > Built-Ins > ginortS
# An uneasy sort.
#
# https://www.hackerrank.com/challenges/ginorts/problem
#
def ordre(c):
if c.islower(): return ord(c)
if c.isupper(): return 1000 + ord(c)
if c.isdigit():
c = int(c)
return 2000 + 10 * (1 - c % 2) + c
return 0
# Solution avec fonction d'ordre
print(*sorted(input(), key=ordre), sep='')
# Solution plus concise
# print(*sorted(input().strip(), key="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1357902468".index), sep='') | {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank_py(input.py)
add_hackerrank_py(zipped.py)
add_hackerrank_py(python-eval.py)
add_hackerrank_py(ginorts.py)
add_hackerrank_py(python-sort-sort.py)
add_hackerrank_py(any-or-all.py)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Python > Built-Ins > Python Evaluation
# Evaluate the expressions in Python using the expression eval().
#
# https://www.hackerrank.com/challenges/python-eval/problem
#
eval(input())
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Python > Built-Ins > Input()
# A Python 2 challenge: Input() is equivalent to eval(raw_input(prompt)).
#
# https://www.hackerrank.com/challenges/input/problem
#
x, y = map(int, input().split())
P = input()
print(y == eval(P, {'x':x}))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Python](https://www.hackerrank.com/domains/python)
A step by step guide to Python, a language that is easy to pick up yet one of the most powerful.
#### [Built-Ins](https://www.hackerrank.com/domains/python/py-built-ins)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Zipped!](https://www.hackerrank.com/challenges/zipped)|Compute the average by zipping data.|[Python](zipped.py)|Easy
[Input()](https://www.hackerrank.com/challenges/input)|A Python 2 challenge: Input() is equivalent to eval(raw_input(prompt)).|[Python](input.py)|Easy
[Python Evaluation](https://www.hackerrank.com/challenges/python-eval)|Evaluate the expressions in Python using the expression eval().|[Python](python-eval.py)|Easy
[Athlete Sort](https://www.hackerrank.com/challenges/python-sort-sort)|Sort the table on the kth attribute.|[Python](python-sort-sort.py)|Medium
[Any or All](https://www.hackerrank.com/challenges/any-or-all)|Return True, if any of the iterable is true or if all of it is true using the any() and all() expressions.|[Python](any-or-all.py)|Easy
[ginortS](https://www.hackerrank.com/challenges/ginorts)|An uneasy sort.|[Python](ginorts.py)|Medium
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
Finding the percentage
https://www.hackerrank.com/challenges/finding-the-percentage/problem
"""
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
print("%.02f" % (sum(student_marks[query_name]) / 3))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tuples
# Learn about tuples and compute hash(T).
#
# https://www.hackerrank.com/challenges/python-tuples/problem
#
if __name__ == '__main__':
n = int(input())
integer_list = map(int, input().split())
print(hash(tuple(integer_list)))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
List Comprehensions
https://www.hackerrank.com/challenges/list-comprehensions/problem
"""
if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
print([[i, j, k] for i in range(x + 1) for j in range(y + 1) for k in range(z + 1) if i + j + k != n])
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
Find the Runner-Up Score!
https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem
"""
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
arr = sorted(arr, reverse=True)
m = arr[0]
while arr[0] == m:
del arr[0]
print(arr[0])
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank_py(python-tuples.py)
add_hackerrank_py(finding-the-percentage.py)
add_hackerrank_py(nested-list.py)
add_hackerrank_py(python-lists.py)
add_hackerrank_py(list-comprehensions.py)
add_hackerrank_py(find-second-maximum-number-in-a-list.py)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
Nested Lists
https://www.hackerrank.com/challenges/nested-list/problem
"""
if __name__ == '__main__':
scores = dict()
for _ in range(int(input())):
name = input()
score = float(input())
if score in scores:
scores[score].append(name)
else:
scores[score] = [name]
for name in sorted(scores[sorted(scores.keys())[1]]):
print(name)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Lists
# Perform different list operations.
#
# https://www.hackerrank.com/challenges/python-lists/problem
#
if __name__ == '__main__':
N = int(input())
list = []
for _ in range(N):
cmd = input().split()
if cmd[0] == "insert":
list.insert(int(cmd[1]), int(cmd[2]))
elif cmd[0] == "print":
print(list)
elif cmd[0] == "remove":
list.remove(int(cmd[1]))
elif cmd[0] == "append":
list.append(int(cmd[1]))
elif cmd[0] == "sort":
list.sort()
elif cmd[0] == "pop":
list.pop()
elif cmd[0] == "reverse":
list.reverse()
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Python](https://www.hackerrank.com/domains/python)
A step by step guide to Python, a language that is easy to pick up yet one of the most powerful.
#### [Basic Data Types](https://www.hackerrank.com/domains/python/py-basic-data-types)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Lists](https://www.hackerrank.com/challenges/python-lists)|Perform different list operations.|[Python](python-lists.py)|Easy
[Tuples ](https://www.hackerrank.com/challenges/python-tuples)|Learn about tuples and compute hash(T).|[Python](python-tuples.py)|Easy
[List Comprehensions](https://www.hackerrank.com/challenges/list-comprehensions)|You will learn about list comprehensions.|[Python](list-comprehensions.py)|Easy
[Find the Runner-Up Score! ](https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list)|For a given list of numbers, find the second largest number.|[Python](find-second-maximum-number-in-a-list.py)|Easy
[Nested Lists](https://www.hackerrank.com/challenges/nested-list)|In a classroom of N students, find the student with the second lowest grade.|[Python](nested-list.py)|Easy
[Finding the percentage](https://www.hackerrank.com/challenges/finding-the-percentage)|Store a list of students and marks in a dictionary, and find the average marks obtained by a student.|[Python](finding-the-percentage.py)|Easy
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Coding Dojo

## Présentation
### Introduction
En japonais, le 道場 (_dōjō_) est le lieu où l'on étudie/cherche la voie.
Définition [Wikipédia](https://fr.wikipedia.org/wiki/Coding_dojo) d'un **coding dojo** :
> Le coding dojo est une rencontre entre plusieurs personnes qui souhaitent travailler sur un défi de programmation de façon collective.
> Chaque coding dojo se concentre sur un sujet particulier, et représente l'objectif de la séance. Ce sujet doit permettre d'apprendre de façon collective sur le plan **technique** et sur la **manière** de réussir le défi.
### Bénéfices attendus
* Découverte nouvelles notions de programmation
* Perfectionnement
* Apprentissage nouveaux langages
* Partage du savoir
* Compléments de formation continue
### Choix des sujets
* Pas nécessairement liés aux projets
* Mais technologies proches
### Langages, outils et IDE
- [Python](https://www.python.org)
- [C++](http://www.cplusplus.com)
- [Bash](https://www.gnu.org/software/bash/)
- Navigateur web et une connexion Internet
- [Visual Studio Code](http://code.visualstudio.com)
- [git](https://git-scm.com)
## Défis proposés
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Coding Dojo

## Présentation
### Introduction
En japonais, le 道場 (_dōjō_) est le lieu où l'on étudie/cherche la voie.
Définition [Wikipédia](https://fr.wikipedia.org/wiki/Coding_dojo) d'un **coding dojo** :
> Le coding dojo est une rencontre entre plusieurs personnes qui souhaitent travailler sur un défi de programmation de façon collective.
> Chaque coding dojo se concentre sur un sujet particulier, et représente l'objectif de la séance. Ce sujet doit permettre d'apprendre de façon collective sur le plan **technique** et sur la **manière** de réussir le défi.
### Bénéfices attendus
* Découverte nouvelles notions de programmation
* Perfectionnement
* Apprentissage nouveaux langages
* Partage du savoir
* Compléments de formation continue
### Choix des sujets
* Pas nécessairement liés aux projets
* Mais technologies proches
### Langages, outils et IDE
- [Python](https://www.python.org)
- [C++](http://www.cplusplus.com)
- [Bash](https://www.gnu.org/software/bash/)
- Navigateur web et une connexion Internet
- [Visual Studio Code](http://code.visualstudio.com)
- [git](https://git-scm.com)
## Défis proposés
### [Python](https://www.hackerrank.com/domains/python)
A step by step guide to Python, a language that is easy to pick up yet one of the most powerful.
#### [Regex and Parsing](https://www.hackerrank.com/domains/python/py-regex)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Validating Credit Card Numbers](https://www.hackerrank.com/challenges/validating-credit-card-number)|Verify whether credit card numbers are valid or not.|[Python](../python/py-regex/validating-credit-card-number.py)|Medium
### [Regex](https://www.hackerrank.com/domains/regex)
Explore the power of regular expressions
#### [Applications](https://www.hackerrank.com/domains/regex/re-applications)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[IP Address Validation](https://www.hackerrank.com/challenges/ip-address-validation)|Validate possible IP Addresses with regex.|[Python](../regex/re-applications/ip-address-validation.py)|Easy
[Detecting Valid Latitude and Longitude Pairs](https://www.hackerrank.com/challenges/detecting-valid-latitude-and-longitude)|Can you detect the Latitude and Longitude embedded in text snippets, using regular expressions?|[Python](../regex/re-applications/detecting-valid-latitude-and-longitude.py)|Easy
### [Data Structures](https://www.hackerrank.com/domains/data-structures)
Data Structures help in elegant representation of data for algorithms
#### [Linked Lists](https://www.hackerrank.com/domains/data-structures/linked-lists)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Cycle Detection](https://www.hackerrank.com/challenges/detect-whether-a-linked-list-contains-a-cycle)|Given a pointer to the head of a linked list, determine whether the linked list loops back onto itself|[C++](../data-structures/linked-lists/detect-whether-a-linked-list-contains-a-cycle.cpp)|Medium
#### [Stacks](https://www.hackerrank.com/domains/data-structures/stacks)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Maximum Element](https://www.hackerrank.com/challenges/maximum-element)|Given three types of queries, insert an element, delete an element or find the maximum element in a stack.|[C++](../data-structures/stacks/maximum-element.cpp)|Easy
[Equal Stacks](https://www.hackerrank.com/challenges/equal-stacks)|Equalize the piles!|[Python](../data-structures/stacks/equal-stacks.py)|Easy
### [Algorithms](https://www.hackerrank.com/domains/algorithms)
The true test of problem solving: when one realizes that time and memory aren't infinite.
#### [Search](https://www.hackerrank.com/domains/algorithms/search)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Missing Numbers](https://www.hackerrank.com/challenges/missing-numbers)|Find the numbers missing from a sequence given a permutation of the original sequence|[Python](../algorithms/search/missing-numbers.py)|Easy
### [C++](https://www.hackerrank.com/domains/cpp)
A general-purpose programming language with imperative, object-oriented and generic programming features.
#### [Other Concepts](https://www.hackerrank.com/domains/cpp/other-concepts)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Bit Array](https://www.hackerrank.com/challenges/bitset-1)|Calculate the number of distinct integers created from the given code.|[C++](../cpp/other-concepts/bitset-1.cpp)|Hard
### [Data Structures](https://www.hackerrank.com/domains/data-structures)
Data Structures help in elegant representation of data for algorithms
#### [Stacks](https://www.hackerrank.com/domains/data-structures/stacks)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Largest Rectangle ](https://www.hackerrank.com/challenges/largest-rectangle)|Given n buildings, find the largest rectangular area possible by joining consecutive K buildings.|[Python](../data-structures/stacks/largest-rectangle.py)|Medium
#### [Trees](https://www.hackerrank.com/domains/data-structures/trees)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Tree: Huffman Decoding ](https://www.hackerrank.com/challenges/tree-huffman-decoding)|Given a Huffman tree and an encoded binary string, you have to print the original string.|[C++](../data-structures/trees/tree-huffman-decoding.cpp)|Medium
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_subdirectory(projecteuler)
add_subdirectory(openbracket-2017)
add_subdirectory(womens-codesprint-3)
#add_subdirectory(infinitum11)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [ProjectEuler+](https://www.hackerrank.com/contests/projecteuler)
HackerRank brings you the fun of solving Projecteuler challenges with hidden test cases and time limit.
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Project Euler #110: Diophantine reciprocals II](https://www.hackerrank.com/contests/projecteuler/challenges/euler110)|euler 110|[Python](projecteuler/euler110.py)|Easy
[Project Euler #108: Diophantine reciprocals I](https://www.hackerrank.com/contests/projecteuler/challenges/euler108)|Project Euler #108: Diophantine reciprocals I|[Python](projecteuler/euler108.py)|Easy
[Project Euler #81: Path sum: two ways](https://www.hackerrank.com/contests/projecteuler/challenges/euler081)|Project Euler #81: Path sum: two ways|[C++](projecteuler/euler081.cpp)|Easy
[Project Euler #74: Digit factorial chains](https://www.hackerrank.com/contests/projecteuler/challenges/euler074)|Project Euler #74: Digit factorial chains|[C++](projecteuler/euler074.cpp)|Easy
[Project Euler #72: Counting fractions](https://www.hackerrank.com/contests/projecteuler/challenges/euler072)|Project Euler #72: Counting fractions|[Python](projecteuler/euler072.py)|Easy
[Project Euler #71: Ordered fractions](https://www.hackerrank.com/contests/projecteuler/challenges/euler071)|Project Euler #71: Ordered fractions|[Python](projecteuler/euler071.py)|Medium
[Project Euler #54: Poker hands](https://www.hackerrank.com/contests/projecteuler/challenges/euler054)|Poker Hands|[Python](projecteuler/euler054.py)|Easy
[Project Euler #31: Coin sums](https://www.hackerrank.com/contests/projecteuler/challenges/euler031)|Currency Change|[Python](projecteuler/euler031.py)|Easy
[Project Euler #28: Number spiral diagonals](https://www.hackerrank.com/contests/projecteuler/challenges/euler028)|Running around a matrix.|[Python](projecteuler/euler028.py)|Easy
[Project Euler #21: Amicable numbers](https://www.hackerrank.com/contests/projecteuler/challenges/euler021)|Proper and improper divisions.|[C++](projecteuler/euler021.cpp)|Easy
[Project Euler #20: Factorial digit sum](https://www.hackerrank.com/contests/projecteuler/challenges/euler020)|When complexities go from one extreme to the other.|[Python](projecteuler/euler020.py)|Easy
[Project Euler #18: Maximum path sum I](https://www.hackerrank.com/contests/projecteuler/challenges/euler018)|Find path with largest sum in a pyramid.|[Python](projecteuler/euler018.py)|Easy
[Project Euler #17: Number to Words](https://www.hackerrank.com/contests/projecteuler/challenges/euler017)|Read the numbers|[Python](projecteuler/euler017.py)|Easy
[Project Euler #16: Power digit sum](https://www.hackerrank.com/contests/projecteuler/challenges/euler016)|With more power comes more responsibility.|[Python](projecteuler/euler016.py)|Easy
[Project Euler #15: Lattice paths](https://www.hackerrank.com/contests/projecteuler/challenges/euler015)|Walking on grids. And not slipping.|[Python](projecteuler/euler015.py)|Easy
[Project Euler #13: Large sum](https://www.hackerrank.com/contests/projecteuler/challenges/euler013)|Summing up big things.|[Python](projecteuler/euler013.py)|Easy
[Project Euler #12: Highly divisible triangular number](https://www.hackerrank.com/contests/projecteuler/challenges/euler012)|Find smallest triangular number with atleast N divisors.|[Python](projecteuler/euler012.py)|Easy
[Project Euler #11: Largest product in a grid](https://www.hackerrank.com/contests/projecteuler/challenges/euler011)|Getting started with matrices.|[Python](projecteuler/euler011.py)|Easy
[Project Euler #10: Summation of primes](https://www.hackerrank.com/contests/projecteuler/challenges/euler010)|More prime number fun.|[Python](projecteuler/euler010.py)|Medium
[Project Euler #9: Special Pythagorean triplet](https://www.hackerrank.com/contests/projecteuler/challenges/euler009)|A what triplet, you say?|[C++](projecteuler/euler009.cpp) [Python](projecteuler/euler009.py)|Easy
[Project Euler #8: Largest product in a series](https://www.hackerrank.com/contests/projecteuler/challenges/euler008)|Playing with really really long numbers.|[Python](projecteuler/euler008.py)|Easy
[Project Euler #7: 10001st prime](https://www.hackerrank.com/contests/projecteuler/challenges/euler007)|Finding the Nth prime.|[Python](projecteuler/euler007.py)|Easy
[Project Euler #6: Sum square difference](https://www.hackerrank.com/contests/projecteuler/challenges/euler006)|Difference between sum of squares and square of sums.|[Python](projecteuler/euler006.py)|Easy
[Project Euler #5: Smallest multiple](https://www.hackerrank.com/contests/projecteuler/challenges/euler005)|Smallest number which divides all numbers from 1 to N.|[Python](projecteuler/euler005.py)|Medium
[Project Euler #4: Largest palindrome product](https://www.hackerrank.com/contests/projecteuler/challenges/euler004)|Largest palindrome of product of three digit numbers less than N.|[C++](projecteuler/euler004.cpp)|Medium
[Project Euler #3: Largest prime factor](https://www.hackerrank.com/contests/projecteuler/challenges/euler003)|Figuring out prime numbers, factors, and then both of them together!|[C++](projecteuler/euler003.cpp)|Easy
[Project Euler #2: Even Fibonacci numbers](https://www.hackerrank.com/contests/projecteuler/challenges/euler002)|Even Fibonacci numbers|[C++](projecteuler/euler002.cpp)|Easy
[Project Euler #1: Multiples of 3 and 5](https://www.hackerrank.com/contests/projecteuler/challenges/euler001)|Multiples of 3 and 5|[Python](projecteuler/euler001.py)|Easy
### [Women's CodeSprint 3](https://www.hackerrank.com/contests/womens-codesprint-3)
Our mission is to close the gender gap in computer science. Joining Women's CodeSprint 3 gives women an opportunity to showcase formidable female skill by solving real-world coding challenges, to win $11,000 in cash prizes and to get discovered by sponsoring companies looking to hire.
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[ASCII Flower](https://www.hackerrank.com/contests/womens-codesprint-3/challenges/ascii-flower)|Help Julie design draw an ASCII flower pattern spanning a given number of rows and columns.|[Python](womens-codesprint-3/ascii-flower.py)|Easy
### [Ad Infinitum 11 - Math Programming Contest](https://www.hackerrank.com/contests/infinitum11)
Welcome to Ad Infinitum (To Infinity) a programming competition, purely in the mathematics domain.
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Fibonacci GCD Again](https://www.hackerrank.com/contests/infinitum11/challenges/fibonacci-gcd-again)|Compute GCDs involving Fibonacci numbers... again.|[C++](infinitum11/fibonacci-gcd-again.cpp) [Python](infinitum11/fibonacci-gcd-again.py)|Advanced
### [OpenBracket Delaware - Online Trials](https://www.hackerrank.com/contests/openbracket-2017)
Participate and win in OpenBracket's CodeSprint to qualify for the championships!
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Hogwarts Email Address](https://www.hackerrank.com/contests/openbracket-2017/challenges/because-owlery-is-too-lazy)|You have to determine whether the given string is a valid email address or not.|[Python](openbracket-2017/because-owlery-is-too-lazy.py)|Easy
### [RookieRank](https://www.hackerrank.com/contests/rookierank)
Calling out all first timers and those new to competitive programming. RookieRank invites all levels of programmers who have never participated in a rated algorithms competition before to experience the thrill!
RookieRank begins Tuesday, July 26th, at 9am PDT. Rookies will have 48 hours (until July 28th at 9am PDT) to solve 5 algorithmic challenges.
We will have two leaderboards. One for all first time competitve programmers. These are users who are not listed on the [Algorithms Leaderboard](https://www.hackerrank.com/leaderboard).
We will have a separate leaderboard for all rated users. These are users who have participated in a rated algorithms contest before.
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Antiprime Numbers](https://www.hackerrank.com/contests/rookierank/challenges/antiprime-numbers)|For each $a_i$, find the smallest antiprime greater than or equal to $a_i$.|[Python](rookierank/antiprime-numbers.py)|Medium
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Women's CodeSprint 3 > ASCII Flower
# Help Julie design draw an ASCII flower pattern spanning a given number of rows and columns.
#
# https://www.hackerrank.com/contests/womens-codesprint-3/challenges/ascii-flower
#
flower = ['..O..',
'O.o.O',
'..O..']
r, c = map(int, input().split())
for _ in range(r):
for i in range(3):
print(flower[i] * c)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
set(HACKERRANK_CONTEST womens-codesprint-3)
add_hackerrank_py(ascii-flower.py)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Women's CodeSprint 3](https://www.hackerrank.com/contests/womens-codesprint-3)
Our mission is to close the gender gap in computer science. Joining Women's CodeSprint 3 gives women an opportunity to showcase formidable female skill by solving real-world coding challenges, to win $11,000 in cash prizes and to get discovered by sponsoring companies looking to hire.
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[ASCII Flower](https://www.hackerrank.com/contests/womens-codesprint-3/challenges/ascii-flower)|Help Julie design draw an ASCII flower pattern spanning a given number of rows and columns.|[Python](ascii-flower.py)|Easy
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank_py(antiprime-numbers.py)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# RookieRank > Antiprime Numbers
# For each $a_i$, find the smallest antiprime greater than or equal to $a_i$.
#
# https://www.hackerrank.com/contests/rookierank/challenges/antiprime-numbers
# challenge id: 23016
#
#!/bin/python3
import sys
import math
import bisect
def solve(a):
pass
def precompute():
MAX = 1000000 + 10000000
max_ds = 0
for n in range(1, MAX + 1):
cnt = 0
for d in range(1, int(math.sqrt(n)) + 1):
q, r = divmod(n, d)
if r == 0: cnt += 1
if q != d: cnt += 1
if cnt > max_ds:
max_ds = cnt
#antiprimes.append(n)
print(n)
if len(sys.argv) == 2:
precompute()
else:
for _ in range(int(input())):
solve(int(input()))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [RookieRank](https://www.hackerrank.com/contests/rookierank)
Calling out all first timers and those new to competitive programming. RookieRank invites all levels of programmers who have never participated in a rated algorithms competition before to experience the thrill!
RookieRank begins Tuesday, July 26th, at 9am PDT. Rookies will have 48 hours (until July 28th at 9am PDT) to solve 5 algorithmic challenges.
We will have two leaderboards. One for all first time competitve programmers. These are users who are not listed on the [Algorithms Leaderboard](https://www.hackerrank.com/leaderboard).
We will have a separate leaderboard for all rated users. These are users who have participated in a rated algorithms contest before.
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Antiprime Numbers](https://www.hackerrank.com/contests/rookierank/challenges/antiprime-numbers)|For each $a_i$, find the smallest antiprime greater than or equal to $a_i$.|[Python](antiprime-numbers.py)|Medium
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Ad Infinitum 11 - Math Programming Contest > Fibonacci GCD Again
// Compute GCDs involving Fibonacci numbers... again.
//
// https://www.hackerrank.com/contests/infinitum11/challenges/fibonacci-gcd-again
// challenge id: 5105
//
#include <bits/stdc++.h>
using namespace std;
// nota: il faut un type signé
typedef long long ull;
#if __cplusplus < 201700L
// c++14 code here
ull gcd(ull u, ull v)
{
while (v != 0)
{
ull r = u % v;
u = v;
v = r;
}
return u;
}
#endif
class mat2x2
{
array<ull, 4> a;
public:
mat2x2()
{
for (auto& i : a) { i = 0; }
}
ull& operator()(unsigned x, unsigned y)
{
return a[x + y * 2];
}
ull operator()(unsigned x, unsigned y) const
{
return a[x + y * 2];
}
mat2x2& operator=(const array<ull, 4>& x)
{
a = x;
return *this;
}
};
class vect2
{
array<ull, 2> a;
public:
vect2()
{
for (auto& i : a) { i = 0; }
}
ull& operator()(unsigned x)
{
return a[x];
}
ull operator()(unsigned x) const
{
return a[x];
}
vect2& operator=(const array<ull, 2>& x)
{
a = x;
return *this;
}
};
ostream& operator<<(ostream& out, const mat2x2& v)
{
out << "[[" << v(0, 0) << ", " << v(1, 0) << "], [";
out << v(1, 0) << ", " << v(1, 1) << "]]";
return out;
}
ostream& operator<<(ostream& out, const vect2& v)
{
out << "[" << v(0) << ", " << v(1) << "]";
return out;
}
// produit matriciel: A * B modulo MOD
mat2x2 multm(const mat2x2& a, const mat2x2& b, ull MOD)
{
mat2x2 p;
p(0, 0) = (a(0, 0) * b(0, 0) + a(1, 0) * b(0, 1)) % MOD;
p(1, 0) = (a(0, 0) * b(1, 0) + a(1, 0) * b(1, 1)) % MOD;
p(0, 1) = (a(0, 1) * b(0, 0) + a(1, 1) * b(0, 1)) % MOD;
p(1, 1) = (a(0, 1) * b(1, 0) + a(1, 1) * b(1, 1)) % MOD;
return p;
}
// produit matrice/vecteur: A * V module MOD
vect2 multv(const mat2x2& a, const vect2& b, ull MOD)
{
vect2 p;
p(0) = (a(0, 0) * b(0) + a(1, 0) * b(1)) % MOD;
p(1) = (a(0, 1) * b(0) + a(1, 1) * b(1)) % MOD;
return p;
}
// fast exponentiation M^k module MOD
mat2x2 power(mat2x2 M, ull k, ull MOD)
{
mat2x2 P;
P = { { 1, 0, 0, 1 } };
if (k == 0)
return P;
if (k == 1)
return M;
while (k != 0)
{
if (k % 2 == 1)
P = multm(P, M, MOD);
M = multm(M, M, MOD);
k /= 2;
}
return P;
}
// calcul de F(n)
vect2 F(ull n, ull MOD)
{
mat2x2 A, An;
vect2 F0, Fn;
A = { { 1, 1, 1, 0 } };
An = power(A, n, MOD);
F0 = { { 1, 0 } };
Fn = multv(An, F0, MOD);
Fn = { { Fn(1), Fn(0) } };
return Fn;
}
void solve()
{
ull N, M;
ull a0, a1, a2, b0, b1, b2;
int t;
ull r;
cin >> t;
while (t--)
{
cin >> N >> a0 >> a1 >> a2 >> b0 >> b1 >> b2 >> M;
// calcul de G = gcd(a0*Fn0+a1*Fn1+a2*Fn2, b0*Fn0+b1*Fn1+b2*Fn2)
// Etape 1
// a0*Fn0+a1*Fn1+a2*Fn2 = a0*Fn0+a1*Fn1+a2*(Fn0+Fn1) = (a0+a2)*Fn0+(a1+a2)*Fn1
a0 += a2;
a1 += a2;
b0 += b2;
b1 += b2;
// d'où G = gcd(a0*Fn0+a1*Fn1, b0*Fn0+b1*Fn1) (a0,a1,b0,b1 modifiés)
// Etape 2
// trouvons (a0', a1') et b0' tels que G = gcd(a0'*Fn0+b0'*Fn1, b0'*Fn0)
// par l'algorithme d'Euclide: gcd(a, b)=gcd(b, a mod b)
// on applique l'algo jusqu'à b1'=0
if (a1 == 0)
{
swap(a0, b0);
swap(a1, b1);
}
while (b1 != 0)
{
if (b1 < a1)
{
swap(a0, b0);
swap(a1, b1);
}
ull q = b1 / a1;
b0 = b0 - a0 * q;
b1 = b1 - a1 * q;
}
// Etape 3
// ici G = gcd(a0*Fn0+a1*Fn1, b0*Fn0)
if (b0 == 0)
{
// simplification!
// G = gcd(a0*Fn0+a1*Fn1, 0)
// gcd(a, 0) = a
vect2 Fn = F(N, M);
r = (a0 * Fn(0) + a1 * Fn(1)) % M;
}
else if (a1 == 0)
{
// simplification!
// G = gcd(a0*Fn0, b0*Fn0)
// = gcd(a0, b0) * Fn0
vect2 Fn = F(N, M);
r = (gcd(a0, b0) * Fn(0)) % M;
}
else
{
// cas général...
ull g = gcd(a1, F(N, a1)(0));
vect2 Fn = F(N, b0 * g);
r = gcd(a0 * Fn(0) + a1 * Fn(1), b0 * g) % M;
if (r < 0) r = -r;
}
cout << r << endl;
}
}
int main()
{
solve();
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank_py(fibonacci-gcd-again.py)
add_hackerrank(fibonacci-gcd-again fibonacci-gcd-again.cpp)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Ad Infinitum 11 - Math Programming Contest > Fibonacci GCD Again
# Compute GCDs involving Fibonacci numbers... again.
#
# https://www.hackerrank.com/contests/infinitum11/challenges/fibonacci-gcd-again
# challenge id: 5105
#
from math import gcd
def multm(A, B, MOD):
""" produit matriciel: A * B """
a00, a10, a01, a11 = A
b00, b10, b01, b11 = B
return [(a00 * b00 + a10 * b01) % MOD, (a00 * b10 + a10 * b11) % MOD,
(a01 * b00 + a11 * b01) % MOD, (a01 * b10 + a11 * b11) % MOD]
def multv(A, V, MOD):
""" produit matrice/vecteur: A * V """
a00, a10, a01, a11 = A
b0, b1 = V
return [(a00 * b0 + a10 * b1) % MOD,
(a01 * b0 + a11 * b1) % MOD]
def power(M, k, MOD):
""" fast exponentiation M^k """
P = [1, 0,
0, 1]
if k == 0:
return P
if k == 1:
return M
while k != 0:
if k % 2 == 1:
P = multm(P, M, MOD)
M = multm(M, M, MOD)
k //= 2
return P
def F(n, MOD):
A = [1, 1, 1, 0]
An = power(A, n, MOD)
F0 = [1, 0]
Fn = multv(An, F0, MOD)
return Fn[1], Fn[0]
def solve():
for _ in range(int(input())):
N, a0, a1, a2, b0, b1, b2, M = map(int, input().split())
# calcul de G = gcd(a0*Fn0+a1*Fn1+a2*Fn2, b0*Fn0+b1*Fn1+b2*Fn2)
# a0*Fn0+a1*Fn1+a2*Fn2 = a0*Fn0+a1*Fn1+a2*(Fn0+Fn1) = (a0+a2)*Fn0+(a1+a2)*Fn1
a0 += a2
a1 += a2
b0 += b2
b1 += b2
# d'où G = gcd(a0*Fn0+a1*Fn1, b0*Fn0+b1*Fn1) (a0,a1,b0,b1 modifiés)
# trouvons (a0', a1') et b0' tels que G = gcd(a0'*Fn0+b0'*Fn1, b0'*Fn0)
# par l'algorithme d'Euclide: gcd(a, b)=gcd(b, a mod b)
# on applique l'algo jusqu'à b1'=0
print(a0, a1, b0, b1)
if a1 == 0:
a0, a1, b0, b1 = b0, b1, a0, a1
while b1 != 0:
if b1 < a1:
a0, a1, b0, b1 = b0, b1, a0, a1
q = b1 // a1
b0, b1 = b0 - a0 * q, b1 - a1 * q
print(a0, a1, b0, b1)
# ici G = gcd(a0*Fn0+a1*Fn1, b0*Fn0)
if b0 == 0:
# simplification!
# G = gcd(a0*Fn0+a1*Fn1, 0)
# gcd(a, 0) = a
Fn0, Fn1 = F(N, M)
r = (a0 * Fn0 + a1 * Fn1) % M
elif a1 == 0:
# simplification!
# G = gcd(a0*Fn0, b0*Fn0)
# = gcd(a0, b0) * Fn0
Fn0, _ = F(N, M)
r = (gcd(a0, b0) * Fn0) % M
else:
# cas général...
g = gcd(a1, F(N, a1)[0])
print(g)
Fn0, Fn1 = F(N, b0 * g)
r = gcd(a0 * Fn0 + a1 * Fn1, b0 * g) % M
print(r)
#Fn0 = 77310304634413492993758144743538184801550997720924982727487206270083963211589736272393893
#Fn1 = 125090700579089545268174422433569433531336921195894847055310250098200676237081739043824861
#debug(N, Fn0, Fn1, sep='\n')
#print(gcd(a0 * Fn0 + a1 * Fn1, b0 * Fn0 + b1 * Fn1) % M)
solve() | {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Ad Infinitum 11 - Math Programming Contest](https://www.hackerrank.com/contests/infinitum11)
Welcome to Ad Infinitum (To Infinity) a programming competition, purely in the mathematics domain.
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Fibonacci GCD Again](https://www.hackerrank.com/contests/infinitum11/challenges/fibonacci-gcd-again)|Compute GCDs involving Fibonacci numbers... again.|[C++](fibonacci-gcd-again.cpp) [Python](fibonacci-gcd-again.py)|Advanced
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
set(HACKERRANK_CONTEST openbracket-2017)
add_hackerrank_py(because-owlery-is-too-lazy.py)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
#
# https://www.hackerrank.com/contests/openbracket-2017/challenges/because-owlery-is-too-lazy
#
import re
def isValid(email):
# Complete this function
if bool(re.match(r"^[a-z]{5}@hogwarts\.com$", email)):
return "Yes"
else:
return "No"
if __name__ == "__main__":
s = input().strip()
result = isValid(s)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [OpenBracket Delaware - Online Trials](https://www.hackerrank.com/contests/openbracket-2017)
Participate and win in OpenBracket's CodeSprint to qualify for the championships!
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Hogwarts Email Address](https://www.hackerrank.com/contests/openbracket-2017/challenges/because-owlery-is-too-lazy)|You have to determine whether the given string is a valid email address or not.|[Python](because-owlery-is-too-lazy.py)|Easy
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# ProjectEuler+ > Project Euler #8: Largest product in a series
# Playing with really really long numbers.
#
# https://www.hackerrank.com/contests/projecteuler/challenges/euler008
# challenge id: 2634
#
for _ in range(int(input())):
n, k = map(int, input().split())
num = list(map(int, input()))
m = 0
for i in range(n - k):
p = 1
for j in range(i, i + k):
p *= num[j]
if p > m:
m = p
print(m)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// ProjectEuler+ > Project Euler #3: Largest prime factor
// Figuring out prime numbers, factors, and then both of them together!
//
// https://www.hackerrank.com/contests/projecteuler/challenges/euler003
//
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
unsigned long largest_prime_factor(unsigned long n)
{
unsigned long i = 2;
unsigned long largest = 2;
while (i * i <= n)
{
while (n % i == 0)
{
n = n / i;
largest = i;
}
i += (i >= 3) ? 2 : 1;
}
return (n > 1) ? n : largest;
}
int main()
{
int t;
cin >> t;
while (t--)
{
unsigned long n;
cin >> n;
cout << largest_prime_factor(n) << endl;
}
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# ProjectEuler+ > Project Euler #17: Number to Words
# Read the numbers
#
# https://www.hackerrank.com/contests/projecteuler/challenges/euler017
# challenge id: 2643
#
units = ['zero', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
teens = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
def int2words(n):
"""
https://en.wikipedia.org/wiki/English_numerals
http://www.lexisrex.com/English-Numbers/
"""
assert n >= 0
if n < 20:
return units[n]
if n < 100:
w = teens[n // 10 - 2]
if n % 10 != 0:
w += "-" + units[n % 10]
return w
if n < 1000:
w = units[n // 100] + " hundred"
if n % 100 != 0:
w += " and " + int2words(n % 100)
return w
if n < 1000000:
w = int2words(n // 1000) + " thousand"
if n % 1000 != 0:
w2 = int2words(n % 1000)
if w2.find(" and ") == -1:
w += " and " + w2
else:
w += " " + w2
return w
if n < 1000000000:
q, r = divmod(n, 1000000)
w = int2words(q) + " million"
if r != 0:
w += " " + int2words(r)
return w
else:
q, r = divmod(n, 1000000000)
w = int2words(q) + " billion"
if r != 0:
w += " " + int2words(r)
return w
def euler017(n):
return int2words(n).title().replace('-', ' ').replace(' And ', ' ')
for _ in range(int(input())):
print(euler017(int(input())))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Digit factorial chains
//
// https://projecteuler.net/problem=74
// https://www.hackerrank.com/contests/projecteuler/challenges/euler074
#include <bits/stdc++.h>
const unsigned fact10[] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 };
unsigned sum_fact_digits(unsigned n)
{
unsigned sum = 0;
do {
sum += fact10[n % 10];
n /= 10;
} while (n != 0);
return sum;
}
int main()
{
unsigned nb = 0;
std::vector<unsigned char> lengths(4000000, 0);
// cas spéciaux des boucles
lengths[169] = 3;
lengths[1454] = 3;
lengths[363601] = 3;
lengths[871] = 2;
lengths[872] = 2;
lengths[45361] = 2;
lengths[45362] = 2;
for (unsigned n = 0; n < 1000000; ++n)
{
std::set<unsigned> visited;
unsigned i = n;
unsigned k = 0;
while (visited.count(i) == 0)
{
if (i >= 4000000) exit(2);
if (lengths[i] != 0)
{
k += lengths[i];
break;
}
k++;
visited.insert(i);
i = sum_fact_digits(i);
//if (i == n) std::cout << "LOOP " << n << " " << k << std::endl;
}
if (k == 60)
{
nb++;
}
if (k > 250) exit(2);
lengths[n] = (unsigned char) k;
}
if (false)
{
std::cout << nb << std::endl;
}
else
{
unsigned T;
std::cin >> T;
while (T--)
{
unsigned N, L;
bool found = false;
std::cin >> N >> L;
for (unsigned i = 0; i <= N; ++i)
{
if (lengths[i] == L)
{
std::cout << i << " ";
found = true;
}
}
if (! found)
std::cout << "-1";
std::cout << std::endl;
}
}
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# ProjectEuler+ > Project Euler #18: Maximum path sum I
# Find path with largest sum in a pyramid.
#
# https://www.hackerrank.com/contests/projecteuler/challenges/euler018
# challenge id: 2644
#
def solve(triangle):
answer = 0
# algo trivial: calcule les sommes sur tous les chemins possibles
def cherche(ligne, position, somme):
nonlocal answer
if ligne >= len(triangle):
if somme > answer:
answer = somme
else:
i = triangle[ligne][position]
cherche(ligne + 1, position, somme + i)
if ligne > 0:
i = triangle[ligne][position + 1]
cherche(ligne + 1, position + 1, somme + i)
return somme
cherche(0, 0, 0)
return answer
for _ in range(int(input())):
triangle = []
n = int(input())
for _ in range(n):
triangle.append(list(map(int, input().split())))
print(solve(triangle))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# ProjectEuler+ > Project Euler #7: 10001st prime
# Finding the Nth prime.
#
# https://www.hackerrank.com/contests/projecteuler/challenges/euler007
# challenge id: 2633
#
class Crible:
""" Crible d'Eratosthène optimisé """
def __init__(self, n_max):
self.n_max = n_max
self.maximum = n = (n_max - 3) // 2 + 1
self.crible = crible = [False] * (n + 1)
self._premiers = None
self._phi = None
i = 0
while i < n:
while i < n:
if not crible[i]:
break
i += 1
k = 3
while True:
j = k * i + 3 * (k - 1) // 2
if j >= n:
break
crible[j] = True
k += 2
i += 1
def liste(self):
if self._premiers is None:
premiers = [2]
for i in range(1, self.maximum + 1):
if not self.crible[i - 1]:
premiers.append(2 * i + 1)
self._premiers = premiers
return self._premiers
c = Crible(104743 + 1) # 10001e nombre premier
p = c.liste()
for _ in range(int(input())):
n = int(input())
print(p[n - 1])
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# ProjectEuler+ > Project Euler #11: Largest product in a grid
# Getting started with matrices.
#
# https://www.hackerrank.com/contests/projecteuler/challenges/euler011
# challenge id: 2637
#
grid = []
for _ in range(20):
row = list(map(int, input().split()))
grid.append(row)
pmax = 0
for i in range(20):
for j in range(17):
p = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3]
if p > pmax:
pmax = p
for i in range(17):
for j in range(20):
p = grid[i][j] * grid[i + 1][j] * grid[i + 2][j] * grid[i + 3][j]
if p > pmax:
pmax = p
for i in range(17):
for j in range(17):
p = grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3]
if p > pmax:
pmax = p
for i in range(3, 20):
for j in range(17):
p = grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3]
if p > pmax:
pmax = p
print(pmax)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# ProjectEuler+ > Project Euler #110: Diophantine reciprocals II
# euler 110
#
# https://www.hackerrank.com/contests/projecteuler/challenges/euler110
# challenge id: 2736
#
# cf. https://github.com/rene-d/math/blob/master/projecteuler/p110.py
from math import log, ceil
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103,
107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163,
167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227,
229, 233, 239, 241, 251, 257, 263, 269, 271]
def hcs(nf, maxe, px):
if nf <= 1:
return 1
if nf <= 3:
return primes[px]
ppow = primes[px]
best = ppow * hcs((nf + 2) // 3, 1, px + 1)
for e in range(2, maxe + 1):
ppow *= primes[px]
if ppow > best:
break
test = ppow * hcs((nf + 2 * e) // (2 * e + 1), e, px + 1)
if test < best:
best = test
return best
N = int(input())
assert ceil(log(N * 2) / log(3)) < len(primes)
print(hcs(N * 2 - 1, 10, 0))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# ProjectEuler+ > Project Euler #71: Ordered fractions
#
# https://www.hackerrank.com/contests/projecteuler/challenges/euler071
# challenge id: 2697
#
from fractions import Fraction as F
def farey_seq(x, limit):
l, r = F(0), F(1)
while l.denominator + r.denominator <= limit:
m = F(l.numerator + r.numerator, l.denominator + r.denominator)
if m < x:
l = m
else:
r = m
if r == x:
break
if l.denominator + r.denominator <= limit:
k = 1 + (limit - (l.denominator + r.denominator)) // r.denominator
l = F(l.numerator + k * r.numerator, l.denominator + k * r.denominator)
return l
# ProjectEuler problem:
# print(farey_seq(F(3, 7), 1000000).numerator)
for _ in range(int(input())):
a, b, n = map(int, input().split())
r = farey_seq(F(a, b), n)
print(r.numerator, r.denominator)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# ProjectEuler+ > Project Euler #6: Sum square difference
# Difference between sum of squares and square of sums.
#
# https://www.hackerrank.com/contests/projecteuler/challenges/euler006
# challenge id: 2632
#
for _ in range(int(input())):
n = int(input())
# (Σ𝑖)² = 𝑛² * (𝑛+1)² * 1/4
# Σ(𝑖²) = 𝑛 * (𝑛+1) * (2𝑛+1) * 1/6
sq_sum = n ** 2 * (n + 1) ** 2 // 4
sum_sq = n * (n + 1) * (2 * n + 1) // 6
print(sq_sum - sum_sq)
# autre possibilité (calcul avec Mathematica)
# = 1/12 𝑛 (𝑛+1) (3𝑛+2) (𝑛-1)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# ProjectEuler+ > Project Euler #9: Special Pythagorean triplet
# A what triplet, you say?
#
# https://www.hackerrank.com/contests/projecteuler/challenges/euler009
# challenge id: 2635
#
from math import sqrt
ok = [-1] * 3001
for a in range(1, 3001):
for b in range(a + 1, 3001):
c2 = a * a + b * b
c = int(sqrt(c2) + 0.5)
p = a + b + c
if p > 3000:
break
if c * c == c2:
ok[p] = a * b * c
for _ in range(int(input())):
n = int(input())
print(ok[n])
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# ProjectEuler+ > Project Euler #13: Large sum
# Summing up big things.
#
# https://www.hackerrank.com/contests/projecteuler/challenges/euler013
# challenge id: 2639
#
# absolument aucun intérêt quand on utilise un langage adéquat
resultat = sum(int(input()) for _ in range(int(input())))
print(str(resultat)[0:10])
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
set(HACKERRANK_CONTEST projecteuler)
add_hackerrank_py(euler001.py)
add_hackerrank_py(euler028.py)
add_hackerrank_py(euler031.py)
add_hackerrank(euler081 euler081.cpp)
add_hackerrank(euler074 euler074.cpp)
add_hackerrank_py(euler016.py)
add_hackerrank(euler009 euler009.cpp)
add_hackerrank(euler002 euler002.cpp)
add_hackerrank(euler003 euler003.cpp)
add_hackerrank(euler004 euler004.cpp)
add_hackerrank_py(euler005.py)
add_hackerrank_py(euler006.py)
add_hackerrank_py(euler007.py)
add_hackerrank_py(euler008.py)
add_hackerrank_py(euler009.py)
add_hackerrank_py(euler010.py)
add_hackerrank_py(euler011.py)
add_hackerrank_py(euler012.py)
add_hackerrank_py(euler013.py)
add_hackerrank_py(euler017.py)
add_hackerrank_py(euler015.py)
add_hackerrank_py(euler018.py)
add_hackerrank_py(euler108.py)
add_hackerrank_py(euler110.py)
add_hackerrank_py(euler072.py)
add_hackerrank_py(euler020.py)
add_hackerrank_py(euler054.py)
add_hackerrank_py(euler071.py)
add_hackerrank(euler021 euler021.cpp)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Path sum: two ways
//
// https://projecteuler.net/problem=81
// https://www.hackerrank.com/contests/projecteuler/challenges/euler081
#include <vector>
#include <queue>
#include <iostream>
#include <fstream>
#include <string>
#include <locale>
#include <cassert>
typedef unsigned long long MatrixValue;
struct Matrix : public std::vector<MatrixValue>
{
size_type n;
MatrixValue v(size_type x, size_type y) const
{
return at(x + y * n);
}
};
struct Visited : public std::vector<bool>
{
size_type n;
bool v(size_type x, size_type y) const
{
return at(x + y * n);
}
void set(size_type x, size_type y)
{
at(x + y * n) = true;
}
};
struct Cell
{
size_t x, y;
MatrixValue v;
Cell(size_t x, size_t y, MatrixValue v) : x(x), y(y), v(v)
{
}
bool operator<(const Cell& r) const
{
return v > r.v;
}
};
struct comma_is_space : std::ctype<char>
{
comma_is_space() : std::ctype<char>(get_table()) {}
static mask const* get_table()
{
static mask rc[table_size];
rc[static_cast<size_t>(',')] = std::ctype_base::space;
rc[static_cast<size_t>('\n')] = std::ctype_base::space;
return &rc[0];
}
};
bool read(Matrix& matrix)
{
matrix.n = 80;
matrix.resize(matrix.n * matrix.n);
std::ifstream f("p081_matrix.txt");
if (f.is_open())
{
size_t i = 0;
// modifie le séparateur de lecture
f.imbue(std::locale(f.getloc(), new comma_is_space));
while (!f.eof() && i < matrix.size())
f >> matrix[i++];
return i == matrix.size();
}
return false;
}
MatrixValue solve(const Matrix& matrix)
{
const size_t n = matrix.n;
Visited visited;
std::priority_queue<Cell> stack;
visited.n = n;
visited.resize(matrix.size(), false);
stack.push(Cell(0, 0, matrix.v(0, 0)));
while (! stack.empty())
{
Cell e = stack.top();
stack.pop();
if (visited.v(e.x, e.y))
continue;
visited.set(e.x, e.y);
if (e.x == n - 1 && e.y == n - 1)
return e.v;
if (e.x < n - 1)
stack.push(Cell(e.x + 1, e.y, e.v + matrix.v(e.x + 1, e.y)));
if (e.y < n - 1)
stack.push(Cell(e.x, e.y + 1, e.v + matrix.v(e.x, e.y + 1)));
}
return 0;
}
int main()
{
Matrix matrix;
if (! read(matrix))
{
// HackerRank
std::cin >> matrix.n;
matrix.resize(matrix.n * matrix.n);
for (size_t i = 0; i < matrix.n * matrix.n; ++i)
std::cin >> matrix[i];
}
std::cout << solve(matrix) << std::endl;
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# ProjectEuler+ > Project Euler #72: Counting fractions
#
# https://www.hackerrank.com/contests/projecteuler/challenges/euler072
# challenge id: 2698
#
# https://en.wikipedia.org/wiki/Farey_sequence
def totients(n):
""" retourne la liste des indicatrices d'Euler (ou totient) pour 2 <= i <= n """
phi = list(range(n + 1))
for i in range(2, n + 1):
if phi[i] == i: # i est premier
for j in range(i, n + 1, i):
phi[j] -= phi[j] // i
return phi[2:] # supprime 0 et 1
# précalcule tous les résultats possibles
MAX = 1000000
results = [0] * (MAX + 1)
for i, phi in enumerate(totients(MAX), 2):
results[i] = results[i - 1] + phi
for _ in range(int(input())):
n = int(input())
print(results[n])
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Project Euler #31: Coin sums
#
# https://www.hackerrank.com/contests/projecteuler/challenges/euler031/problem
#
coins = [1, 2, 5, 10, 20, 50, 100, 200]
cache = []
def r(objectif):
for i in range(len(cache), objectif + 1):
arr = [1, 0, 0, 0, 0, 0, 0, 0]
for j in range(1, 8):
arr[j] = arr[j - 1]
if i >= coins[j]:
arr[j] += cache[i - coins[j]][j]
cache.append(arr)
return cache[objectif][7] % 1000000007
for _ in range(int(input())):
print(r(int(input())))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# ProjectEuler+ > Project Euler #5: Smallest multiple
# Smallest number which divides all numbers from 1 to N.
#
# https://www.hackerrank.com/contests/projecteuler/challenges/euler005
#
import math
import functools
def gcd(*numbers):
""" greatest common divisor """
return functools.reduce(math.gcd, numbers)
def lcm(*numbers):
""" least common multiple """
return functools.reduce(lambda a, b: (a * b) // gcd(a, b), numbers, 1)
for _ in range(int(input())):
n = int(input())
print(lcm(*range(1, n + 1)))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Project Euler #9: Special Pythagorean triplet
// A what triplet, you say?
//
// https://www.hackerrank.com/contests/projecteuler/challenges/euler009
//
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int main()
{
const int M = 3000;
int cache[M + 1];
for (int i = 0; i <= M; ++i)
cache[i] = -1;
for (int a = 1; a < M; ++a)
{
int a_a = a * a;
for (int b = a + 1; b <= M - a; ++b)
{
int c_c = a_a + b * b;
if (c_c % 4 == 3) continue;
int c = (int) sqrt(c_c);
if (c * c != c_c) continue;
int p = a + b + c;
if (p > M) break;
int abc = a * b * c;
if (cache[p] < abc) cache[p] = abc;
}
}
int t;
scanf("%d",&t);
for(int a0 = 0; a0 < t; a0++){
int n;
scanf("%d",&n);
printf("%d\n", cache[n]);
}
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
Project Euler #1: Multiples of 3 and 5
https://www.hackerrank.com/contests/projecteuler/challenges/euler001
"""
import sys
def t(n):
""" ∑x = 1+2+..+x = x∗(x+1)/2 """
return n * (n + 1) // 2
def sum_3_5(n):
""" somme des multiples de 3, de 5, en enlevant ceux de 3*5 (déjà comptés) """
return 3 * t(n // 3) + 5 * t(n // 5) - 15 * t(n // 15)
if len(sys.argv) > 1:
for i in sys.argv[1:]:
print(i, sum_3_5(int(i) - 1))
else:
nb = int(input().strip())
for _ in range(nb):
n = int(input().strip())
print(sum_3_5(n - 1))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// ProjectEuler+ > Project Euler #21: Amicable numbers
// Proper and improper divisions.
//
// https://www.hackerrank.com/contests/projecteuler/challenges/euler021
// challenge id: 2647
//
#include <bits/stdc++.h>
using namespace std;
const unsigned MAX = 100000;
unsigned sum_of_divisors(unsigned n)
{
unsigned temp = n;
unsigned sum = 1;
for (unsigned i = 2; i < n; ++i)
{
n = temp / i;
if (temp % i == 0)
{
sum += i + n;
if (sum > MAX)
return 0;
}
}
return sum;
}
int main()
{
vector<unsigned> sod(MAX + 1, 0u);
vector<unsigned> ami(MAX + 1, 0u);
for (unsigned i = 1; i <= MAX; ++i)
sod[i] = sum_of_divisors(i);
unsigned x = 0;
for (unsigned i = 1; i <= MAX; ++i)
{
unsigned a = sod[i];
if (a != i && a != 0)
{
if (i == sod[a])
x += i;
}
ami[i] = x;
}
int t;
unsigned n;
cin >> t;
while (t--)
{
cin >> n;
cout << ami[n - 1] << endl;
}
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// ProjectEuler+ > Project Euler #2: Even Fibonacci numbers
// Even Fibonacci numbers
//
// https://www.hackerrank.com/contests/projecteuler/challenges/euler002
//
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
unsigned long n;
cin >> n;
unsigned long sum = 0;
unsigned long a = 1;
unsigned long b = 2;
while (b <= n)
{
if (b % 2 == 0)
{
sum += b;
}
unsigned long c = a + b;
a = b;
b = c;
}
cout << sum << endl;
}
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# ProjectEuler+ > Project Euler #15: Lattice paths
# Walking on grids. And not slipping.
#
# https://www.hackerrank.com/contests/projecteuler/challenges/euler015
# challenge id: 2641
#
import math
"""
Cf. https://en.wikipedia.org/wiki/Lattice_path
"""
def C(n, k):
""" Coefficient binomial """
return math.factorial(n) // math.factorial(k) // math.factorial(n - k)
for _ in range(int(input())):
m, n = map(int, input().split())
print(C(m + n, n) % 1000000007)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# ProjectEuler+ > Project Euler #20: Factorial digit sum
# When complexities go from one extreme to the other.
#
# https://www.hackerrank.com/contests/projecteuler/challenges/euler020
# challenge id: 2646
#
from math import factorial
for _ in range(int(input())):
n = int(input())
print(sum(int(d) for d in str(factorial(n))))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# ProjectEuler+ > Project Euler #12: Highly divisible triangular number
# Find smallest triangular number with atleast N divisors.
#
# https://www.hackerrank.com/contests/projecteuler/challenges/euler012
# challenge id: 2638
#
def decompose(n):
""" décomposition d'un nombre en facteurs premiers """
facteurs = {}
i = 2
while i * i <= n:
while n % i == 0:
n = n // i
facteurs[i] = facteurs.get(i, 0) + 1
if i >= 3:
i += 2
else:
i += 1
if n > 1:
facteurs[n] = facteurs.get(n, 0) + 1
return facteurs
def solve(n):
i = 2
a = decompose(i)
while True:
i += 1
b = decompose(i)
# fusionne les deux décompositions
for k, v in b.items():
a[k] = a.get(k, 0) + v
# calcule le nombre de diviseurs
f = 1
for k, v in a.items():
if k == 2:
f *= v
else:
f *= v + 1
# a-t-on un résultat ?
if f > n:
return (i * (i - 1) // 2)
a = b
for _ in range(int(input())):
n = int(input())
print(solve(n))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# ProjectEuler+ > Project Euler #54: Poker hands
# Poker Hands
#
# https://www.hackerrank.com/contests/projecteuler/challenges/euler054
# challenge id: 2680
#
# original problem:
# https://projecteuler.net/problem=54
card_order = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,
'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14}
def hand_value(hand):
hand.sort(key=lambda x: card_order[x[0]])
cards = list(card_order[x[0]] for x in hand)
if cards == [2, 3, 4, 5, 14]:
cards = [1, 2, 3, 4, 5]
is_flush = all(x[1] == hand[0][1] for x in hand)
counts = {}
for x in cards:
if x in counts:
counts[x] += 1
else:
counts[x] = 1
counts = sorted(list((v, k) for k, v in counts.items()), reverse=True)
is_straight = len(counts) == 5 and cards[4] - cards[0] == 4
# royal flush
if is_straight and is_flush and cards[0] == 10: # starting at T
return 10, 0
# straight flush
if is_straight and is_flush:
return 9, cards[4] # second key: highest card
# four of a kind
if counts[0][0] == 4:
return 8, counts[0][1], counts[1][1] # keys: the four kind, then the last card
# full house
if counts[0][0] == 3 and counts[1][0] == 2:
return 7, counts[0][1], counts[1][1]
# flush
if is_flush:
return 6, cards[4], cards[3], cards[2], cards[1], cards[0]
# straight
if is_straight:
return 5, cards[4]
# three of a kind
if counts[0][0] == 3:
a, b = counts[1][1], counts[2][1]
if a < b: a, b = b, a
return 4, counts[0][1], a, b
# two pairs
if counts[0][0] == 2 and counts[1][0] == 2:
a, b = counts[0][1], counts[1][1]
if a < b: a, b = b, a
return 3, a, b, counts[2][1]
# one pair
if counts[0][0] == 2:
a, b, c = sorted([counts[1][1], counts[2][1], counts[3][1] ], reverse=True)
return 2, counts[0][1], a, b, c
return 1, cards[4], cards[3], cards[2], cards[1], cards[0]
for _ in range(int(input())):
cards = input().split()
player1 = hand_value(cards[0:5])
player2 = hand_value(cards[5:10])
if player1 > player2:
print("Player 1")
elif player1 < player2:
print("Player 2")
else:
print("Deuce") # not in the testcases
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# ProjectEuler+ > Project Euler #108: Diophantine reciprocals I
#
# https://www.hackerrank.com/contests/projecteuler/challenges/euler108
# challenge id: 2734
#
# cf. https://github.com/rene-d/math/blob/master/projecteuler/p108.py
# cependant, les testcases 7-11 requièrent une meilleure méthode de factorisation
# version "je triche un peu" et j'économise Eratosthène, Miller-Rabin et Pollard-Brent
# __import__("sys").path.append('/var/ml/python3/lib/python3.5/site-packages')
# from sympy.ntheory import factorint
from math import gcd
import random
from itertools import compress
# https://stackoverflow.com/questions/4643647/fast-prime-factorization-module
# https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n/46635266#46635266
def primes_below(n):
""" Returns a list of primes < n for n > 2 """
sieve = bytearray([True]) * (n//2+1)
for i in range(1,int(n**0.5)//2+1):
if sieve[i]:
sieve[2*i*(i+1)::2*i+1] = bytearray((n//2-2*i*(i+1))//(2*i+1)+1)
return [2,*compress(range(3,n,2), sieve[1:])]
small_prime_set_max = 100000
small_prime_set = set(primes_below(small_prime_set_max))
def is_prime(n, precision=7):
# http://en.wikipedia.org/wiki/Miller-Rabin_primality_test#Algorithm_and_running_time
if n < 1:
raise ValueError("Out of bounds, first argument must be > 0")
elif n <= 3:
return n >= 2
elif n % 2 == 0:
return False
elif n < small_prime_set_max:
return n in small_prime_set
d = n - 1
s = 0
while d % 2 == 0:
d //= 2
s += 1
for _ in range(precision):
a = random.randrange(2, n - 2)
x = pow(a, d, n)
if x == 1 or x == n - 1: continue
for r in range(s - 1):
x = pow(x, 2, n)
if x == 1: return False
if x == n - 1: break
else:return False
return True
# https://comeoncodeon.wordpress.com/2010/09/18/pollard-rho-brent-integer-factorization/
def pollard_brent(n):
if n % 2 == 0: return 2
if n % 3 == 0: return 3
y, c, m = random.randint(1, n - 1), random.randint(1, n - 1), random.randint(1, n - 1)
g, r, q = 1, 1, 1
while g == 1:
x = y
for i in range(r):
y = (pow(y, 2, n) + c) % n
k = 0
while k < r and g == 1:
ys = y
for i in range(min(m, r - k)):
y = (pow(y, 2, n) + c) % n
q = q * abs(x-y) % n
g = gcd(q, n)
k += m
r *= 2
if g == n:
while True:
ys = (pow(ys, 2, n) + c) % n
g = gcd(abs(x - ys), n)
if g > 1: break
return g
small_primes = primes_below(1000) # might seem low, but 1000*1000 = 1000000, so this will fully factor every composite < 1000000
def prime_factors(n):
factors = []
for checker in small_primes:
while n % checker == 0:
factors.append(checker)
n //= checker
if checker > n:
break
if n < 2: return factors
while n > 1:
if is_prime(n):
factors.append(n)
break
factor = pollard_brent(n) # trial division did not fully factor, switch to pollard-brent
factors.extend(prime_factors(factor)) # recurse to factor the not necessarily prime factor returned by pollard-brent
n //= factor
return factors
def factorint(n):
factors = {}
for p in prime_factors(n):
if p in factors:
factors[p] += 1
else:
factors[p] = 1
return factors
for _ in range(int(input())):
n = int(input())
p = 1
for _, e in factorint(n).items():
p *= 2 * e + 1 # nombre de diviseurs de n²
print((p + 1) // 2)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
Project Euler #28: Number spiral diagonals
https://www.hackerrank.com/contests/projecteuler/challenges/euler028/
"""
# http://oeis.org/A114254
def A114254(n):
return 1 + 10 * n ** 2 + (16 * n ** 3 + 26 * n) // 3
nb = int(input())
for i in range(nb):
n = int(input()) // 2
print(A114254(n) % 1000000007)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [ProjectEuler+](https://www.hackerrank.com/contests/projecteuler)
HackerRank brings you the fun of solving Projecteuler challenges with hidden test cases and time limit.
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Project Euler #110: Diophantine reciprocals II](https://www.hackerrank.com/contests/projecteuler/challenges/euler110)|euler 110|[Python](euler110.py)|Easy
[Project Euler #108: Diophantine reciprocals I](https://www.hackerrank.com/contests/projecteuler/challenges/euler108)|Project Euler #108: Diophantine reciprocals I|[Python](euler108.py)|Easy
[Project Euler #81: Path sum: two ways](https://www.hackerrank.com/contests/projecteuler/challenges/euler081)|Project Euler #81: Path sum: two ways|[C++](euler081.cpp)|Easy
[Project Euler #74: Digit factorial chains](https://www.hackerrank.com/contests/projecteuler/challenges/euler074)|Project Euler #74: Digit factorial chains|[C++](euler074.cpp)|Easy
[Project Euler #72: Counting fractions](https://www.hackerrank.com/contests/projecteuler/challenges/euler072)|Project Euler #72: Counting fractions|[Python](euler072.py)|Easy
[Project Euler #71: Ordered fractions](https://www.hackerrank.com/contests/projecteuler/challenges/euler071)|Project Euler #71: Ordered fractions|[Python](euler071.py)|Medium
[Project Euler #54: Poker hands](https://www.hackerrank.com/contests/projecteuler/challenges/euler054)|Poker Hands|[Python](euler054.py)|Easy
[Project Euler #31: Coin sums](https://www.hackerrank.com/contests/projecteuler/challenges/euler031)|Currency Change|[Python](euler031.py)|Easy
[Project Euler #28: Number spiral diagonals](https://www.hackerrank.com/contests/projecteuler/challenges/euler028)|Running around a matrix.|[Python](euler028.py)|Easy
[Project Euler #21: Amicable numbers](https://www.hackerrank.com/contests/projecteuler/challenges/euler021)|Proper and improper divisions.|[C++](euler021.cpp)|Easy
[Project Euler #20: Factorial digit sum](https://www.hackerrank.com/contests/projecteuler/challenges/euler020)|When complexities go from one extreme to the other.|[Python](euler020.py)|Easy
[Project Euler #18: Maximum path sum I](https://www.hackerrank.com/contests/projecteuler/challenges/euler018)|Find path with largest sum in a pyramid.|[Python](euler018.py)|Easy
[Project Euler #17: Number to Words](https://www.hackerrank.com/contests/projecteuler/challenges/euler017)|Read the numbers|[Python](euler017.py)|Easy
[Project Euler #16: Power digit sum](https://www.hackerrank.com/contests/projecteuler/challenges/euler016)|With more power comes more responsibility.|[Python](euler016.py)|Easy
[Project Euler #15: Lattice paths](https://www.hackerrank.com/contests/projecteuler/challenges/euler015)|Walking on grids. And not slipping.|[Python](euler015.py)|Easy
[Project Euler #13: Large sum](https://www.hackerrank.com/contests/projecteuler/challenges/euler013)|Summing up big things.|[Python](euler013.py)|Easy
[Project Euler #12: Highly divisible triangular number](https://www.hackerrank.com/contests/projecteuler/challenges/euler012)|Find smallest triangular number with atleast N divisors.|[Python](euler012.py)|Easy
[Project Euler #11: Largest product in a grid](https://www.hackerrank.com/contests/projecteuler/challenges/euler011)|Getting started with matrices.|[Python](euler011.py)|Easy
[Project Euler #10: Summation of primes](https://www.hackerrank.com/contests/projecteuler/challenges/euler010)|More prime number fun.|[Python](euler010.py)|Medium
[Project Euler #9: Special Pythagorean triplet](https://www.hackerrank.com/contests/projecteuler/challenges/euler009)|A what triplet, you say?|[C++](euler009.cpp) [Python](euler009.py)|Easy
[Project Euler #8: Largest product in a series](https://www.hackerrank.com/contests/projecteuler/challenges/euler008)|Playing with really really long numbers.|[Python](euler008.py)|Easy
[Project Euler #7: 10001st prime](https://www.hackerrank.com/contests/projecteuler/challenges/euler007)|Finding the Nth prime.|[Python](euler007.py)|Easy
[Project Euler #6: Sum square difference](https://www.hackerrank.com/contests/projecteuler/challenges/euler006)|Difference between sum of squares and square of sums.|[Python](euler006.py)|Easy
[Project Euler #5: Smallest multiple](https://www.hackerrank.com/contests/projecteuler/challenges/euler005)|Smallest number which divides all numbers from 1 to N.|[Python](euler005.py)|Medium
[Project Euler #4: Largest palindrome product](https://www.hackerrank.com/contests/projecteuler/challenges/euler004)|Largest palindrome of product of three digit numbers less than N.|[C++](euler004.cpp)|Medium
[Project Euler #3: Largest prime factor](https://www.hackerrank.com/contests/projecteuler/challenges/euler003)|Figuring out prime numbers, factors, and then both of them together!|[C++](euler003.cpp)|Easy
[Project Euler #2: Even Fibonacci numbers](https://www.hackerrank.com/contests/projecteuler/challenges/euler002)|Even Fibonacci numbers|[C++](euler002.cpp)|Easy
[Project Euler #1: Multiples of 3 and 5](https://www.hackerrank.com/contests/projecteuler/challenges/euler001)|Multiples of 3 and 5|[Python](euler001.py)|Easy
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# ProjectEuler+ > Project Euler #10: Summation of primes
# More prime number fun.
#
# https://www.hackerrank.com/contests/projecteuler/challenges/euler010
# challenge id: 2636
#
class Crible:
""" Crible d'Eratosthène optimisé """
def __init__(self, n_max):
self.n_max = n_max
self.maximum = n = (n_max - 3) // 2 + 1
self.crible = crible = [False] * (n + 1)
self._premiers = None
self._phi = None
i = 0
while i < n:
while i < n:
if not crible[i]:
break
i += 1
k = 3
while True:
j = k * i + 3 * (k - 1) // 2
if j >= n:
break
crible[j] = True
k += 2
i += 1
def liste(self):
if self._premiers is None:
premiers = [2]
for i in range(1, self.maximum + 1):
if not self.crible[i - 1]:
premiers.append(2 * i + 1)
self._premiers = premiers
return self._premiers
N = 1000000
sieve = Crible(N)
primes = sieve.liste()
# precompute the answers
psum = [0] * N
i = 0
k = 0
for p in primes:
i += 1
while i < p:
psum[i] = k
i += 1
k += p
psum[i] = k
while i < N:
psum[i] = k
i += 1
for _ in range(int(input())):
n = int(input())
print(psum[n])
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Project Euler #16: Power digit sum
#
# https://www.hackerrank.com/contests/projecteuler/challenges/euler016/problem
for _ in range(int(input())):
print(sum(int(c) for c in str(2 ** int(input()))))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// ProjectEuler+ > Project Euler #4: Largest palindrome product
// Largest palindrome of product of three digit numbers less than N.
//
// https://www.hackerrank.com/contests/projecteuler/challenges/euler004
//
#include <cmath>
#include <cstdio>
#include <set>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
set<int> palindromes;
for (int a = 100; a < 1000; ++a)
{
for (int b = a; b < 1000; ++b)
{
int p = a * b;
// calcule l'«inverse» de p
int q = 0;
for (int i = p; i != 0; i /= 10)
q = 10 * q + i % 10;
if (p == q)
{
// c'est un palindrome
palindromes.insert(p);
}
}
}
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
int p = *(--palindromes.lower_bound(n));
cout << p << endl;
}
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_subdirectory(intro)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Functional Programming](https://www.hackerrank.com/domains/fp)
The art of programming with expressions and functions. Experience the challenge of programming without state. A good paradigm for those interested in Map-Reduce and parallel computing.
#### [Introduction](https://www.hackerrank.com/domains/fp/intro)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Solve Me First FP](https://www.hackerrank.com/challenges/fp-solve-me-first)|This is a special challenge to make you familiar with IO.|[Haskell](intro/fp-solve-me-first.hs)|Easy
[Hello World](https://www.hackerrank.com/challenges/fp-hello-world)|Write code to print the 'Hello World' program.|[Erlang](intro/fp-hello-world.erl) [Haskell](intro/fp-hello-world.hs)|Easy
[Hello World N Times](https://www.hackerrank.com/challenges/fp-hello-world-n-times)|Print 'hello world' n times.|[Haskell](intro/fp-hello-world-n-times.hs)|Easy
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
-- Hello World
-- Write code to print the 'Hello World' program.
--
-- https://www.hackerrank.com/challenges/fp-hello-world/problem
--
-- Enter your code here. Read input from STDIN. Print output to STDOUT
hello_world = -- Fill up this function
putStrLn "Hello World"
-- This part relates to Input/Output and can be used as it is. Do not modify this section
main = do
hello_world
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
project(fp Haskell)
add_executable(fp-solve-me-first fp-solve-me-first.hs)
add_executable(fp-hello-world fp-hello-world.hs)
add_executable(fp-hello-world-n-times fp-hello-world-n-times.hs)
add_test_hackerrank(fp-solve-me-first)
add_test_hackerrank(fp-hello-world)
add_test_hackerrank(fp-hello-world-n-times)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
% Hello World
% Write code to print the 'Hello World' program.
%
% https://www.hackerrank.com/challenges/fp-hello-world/problem
%
% Enter your code here. Read input from STDIN. Print output to STDOUT
% Your class should be named solution
-module(solution).
-export([main/0]).
hello() ->
io:fwrite("Hello World\n").
main() ->
hello().
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
-- Hello World N Times
-- Print 'hello world' n times.
--
-- https://www.hackerrank.com/challenges/fp-hello-world-n-times/problem
--
import Control.Applicative
import Control.Monad
import System.IO
hello_worlds n = replicateM_ n $ putStrLn "Hello World"
main :: IO ()
main = do
n_temp <- getLine
let n = read n_temp :: Int
-- Print "Hello World" on a new line 'n' times.
hello_worlds n
getMultipleLines :: Int -> IO [String]
getMultipleLines n
| n <= 0 = return []
| otherwise = do
x <- getLine
xs <- getMultipleLines (n-1)
let ret = (x:xs)
return ret
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
-- Solve Me First FP
-- This is a special challenge to make you familiar with IO.
--
-- https://www.hackerrank.com/challenges/fp-solve-me-first/problem
--
solveMeFirst a b = a + b
-- (template_tail) ----------------------------------------------------------------------
main = do
val1 <- readLn
val2 <- readLn
let sum = solveMeFirst val1 val2
print sum
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Functional Programming](https://www.hackerrank.com/domains/fp)
The art of programming with expressions and functions. Experience the challenge of programming without state. A good paradigm for those interested in Map-Reduce and parallel computing.
#### [Introduction](https://www.hackerrank.com/domains/fp/intro)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Solve Me First FP](https://www.hackerrank.com/challenges/fp-solve-me-first)|This is a special challenge to make you familiar with IO.|[Haskell](fp-solve-me-first.hs)|Easy
[Hello World](https://www.hackerrank.com/challenges/fp-hello-world)|Write code to print the 'Hello World' program.|[Erlang](fp-hello-world.erl) [Haskell](fp-hello-world.hs)|Easy
[Hello World N Times](https://www.hackerrank.com/challenges/fp-hello-world-n-times)|Print 'hello world' n times.|[Haskell](fp-hello-world-n-times.hs)|Easy
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_subdirectory(c-introduction)
add_subdirectory(c-conditionals-and-loops)
add_subdirectory(c-arrays-and-strings)
add_subdirectory(c-functions)
add_subdirectory(c-structs-and-enums)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [C](https://www.hackerrank.com/domains/c)
#### [Introduction](https://www.hackerrank.com/domains/c/c-introduction)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
["Hello World!" in C](https://www.hackerrank.com/challenges/hello-world-c)|This challenge will help you to learn to input some data and then output some data.|[C](c-introduction/hello-world-c.c)|Easy
[Playing With Characters](https://www.hackerrank.com/challenges/playing-with-characters)|input character, string and a sentence|[C](c-introduction/playing-with-characters.c)|Easy
[Sum and Difference of Two Numbers](https://www.hackerrank.com/challenges/sum-numbers-c)|Get started with data types.|[C](c-introduction/sum-numbers-c.c)|Easy
[Functions in C](https://www.hackerrank.com/challenges/functions-in-c)|Learn how to write functions in C++. Create a function to find the maximum of the four numbers.|[C](c-introduction/functions-in-c.c)|Easy
[Pointers in C](https://www.hackerrank.com/challenges/pointer-in-c)|Learn how to declare pointers and use them.|[C](c-introduction/pointer-in-c.c)|Easy
#### [Conditionals and Loops](https://www.hackerrank.com/domains/c/c-conditionals-and-loops)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Conditional Statements in C](https://www.hackerrank.com/challenges/conditional-statements-in-c)|Practice using chained conditional statements.|[C](c-conditionals-and-loops/conditional-statements-in-c.c)|Easy
[For Loop in C](https://www.hackerrank.com/challenges/for-loop-in-c)|Learn how to use for loop and print the output as per the given conditions|[C](c-conditionals-and-loops/for-loop-in-c.c)|Easy
[Sum of Digits of a Five Digit Number](https://www.hackerrank.com/challenges/sum-of-digits-of-a-five-digit-number)|to calculate the sum of digits of a five digit number.|[C](c-conditionals-and-loops/sum-of-digits-of-a-five-digit-number.c)|Easy
[Bitwise Operators](https://www.hackerrank.com/challenges/bitwise-operators-in-c)|Apply everything we've learned in this bitwise operators' challenge.|[C](c-conditionals-and-loops/bitwise-operators-in-c.c)|Easy
[Printing Pattern using Loops](https://www.hackerrank.com/challenges/printing-pattern-2)||[C](c-conditionals-and-loops/printing-pattern-2.c)|Medium
#### [Arrays and Strings](https://www.hackerrank.com/domains/c/c-arrays-and-strings)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[1D Arrays in C](https://www.hackerrank.com/challenges/1d-arrays-in-c)|Create an array in c and sum the elements.|[C](c-arrays-and-strings/1d-arrays-in-c.c)|Medium
[Array Reversal](https://www.hackerrank.com/challenges/reverse-array-c)|Given an array, reverse it.|[C](c-arrays-and-strings/reverse-array-c.c)|Medium
[Printing Tokens](https://www.hackerrank.com/challenges/printing-tokens-)|Given a sentence, print each word in a new line.|[C](c-arrays-and-strings/printing-tokens-.c)|Medium
[Digit Frequency](https://www.hackerrank.com/challenges/frequency-of-digits-1)|Given a very large number, count the frequency of each digit from [0-9]|[C](c-arrays-and-strings/frequency-of-digits-1.c)|Medium
[Dynamic Array in C](https://www.hackerrank.com/challenges/dynamic-array-in-c)||[C](c-arrays-and-strings/dynamic-array-in-c.c)|Medium
#### [Functions](https://www.hackerrank.com/domains/c/c-functions)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Calculate the Nth term](https://www.hackerrank.com/challenges/recursion-in-c)|Use recursion to solve this challenge.|[C](c-functions/recursion-in-c.c)|Easy
[Students Marks Sum](https://www.hackerrank.com/challenges/students-marks-sum)|An easy challenge on pointers|[C](c-functions/students-marks-sum.c)|Easy
[Sorting Array of Strings](https://www.hackerrank.com/challenges/sorting-array-of-strings)||[C](c-functions/sorting-array-of-strings.c)|Hard
[Permutations of Strings](https://www.hackerrank.com/challenges/permutations-of-strings)|Find all permutations of the string array.|[C](c-functions/permutations-of-strings.c)|Medium
[Variadic functions in C](https://www.hackerrank.com/challenges/variadic-functions-in-c)||[C](c-functions/variadic-functions-in-c.c)|Medium
[Querying the Document](https://www.hackerrank.com/challenges/querying-the-document)||[C](c-functions/querying-the-document.c)|Hard
#### [Structs and Enums](https://www.hackerrank.com/domains/c/c-structs-and-enums)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Boxes through a Tunnel](https://www.hackerrank.com/challenges/too-high-boxes)|Find the volume of short enough boxes.|[C](c-structs-and-enums/too-high-boxes.c)|Easy
[Small Triangles, Large Triangles](https://www.hackerrank.com/challenges/small-triangles-large-triangles)|Sort triangles by area|[C](c-structs-and-enums/small-triangles-large-triangles.c)|Medium
[Post Transition](https://www.hackerrank.com/challenges/post-transition)|Manage post transactions in a country|[C](c-structs-and-enums/post-transition.c)|Hard
[Structuring the Document](https://www.hackerrank.com/challenges/structuring-the-document)||[C](c-structs-and-enums/structuring-the-document.c)|Hard
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// C > Introduction > "Hello World!" in C
// This challenge will help you to learn to input some data and then output some data.
//
// https://www.hackerrank.com/challenges/hello-world-c/problem
//
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main()
{
char s[100];
scanf("%[^\n]%*c", s);
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
puts("Hello, World!");
puts(s);
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// C > Introduction > Sum and Difference of Two Numbers
// Get started with data types.
//
// https://www.hackerrank.com/challenges/sum-numbers-c/problem
//
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main()
{
int i, j;
float f, g;
if (scanf("%d %d", &i, &j) == 2 && scanf("%f %f", &f, &g) == 2)
{
printf("%d %d\n", i + j, i - j);
printf("%.1f %.1f\n", f + g, f - g);
}
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank(hello-world-c hello-world-c.c)
add_hackerrank(sum-numbers-c sum-numbers-c.c)
add_hackerrank(functions-in-c functions-in-c.c)
add_hackerrank(pointer-in-c pointer-in-c.c)
add_hackerrank(playing-with-characters playing-with-characters.c)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// C > Introduction > Functions in C
// Learn how to write functions in C++. Create a function to find the maximum of the four numbers.
//
// https://www.hackerrank.com/challenges/functions-in-c/problem
//
#include <stdio.h>
/*
Add `int max_of_four(int a, int b, int c, int d)` here.
*/
int max_of_four(int a, int b, int c, int d)
{
int m = a;
if (b > m) m = b;
if (c > m) m = c;
if (d > m) m = d;
return m;
}
int main() {
int a, b, c, d;
scanf("%d %d %d %d", &a, &b, &c, &d);
int ans = max_of_four(a, b, c, d);
printf("%d", ans);
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// C > Introduction > Pointers in C
// Learn how to declare pointers and use them.
//
// https://www.hackerrank.com/challenges/pointer-in-c/problem
//
#include <stdio.h>
void update(int *a,int *b) {
// Complete this function
int s = *a + *b;
int d = *a - *b;
if (d < 0) d = -d;
*a = s;
*b = d;
}
int main() {
int a, b;
int *pa = &a, *pb = &b;
scanf("%d %d", &a, &b);
update(pa, pb);
printf("%d\n%d", a, b);
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [C](https://www.hackerrank.com/domains/c)
#### [Introduction](https://www.hackerrank.com/domains/c/c-introduction)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
["Hello World!" in C](https://www.hackerrank.com/challenges/hello-world-c)|This challenge will help you to learn to input some data and then output some data.|[C](hello-world-c.c)|Easy
[Playing With Characters](https://www.hackerrank.com/challenges/playing-with-characters)|input character, string and a sentence|[C](playing-with-characters.c)|Easy
[Sum and Difference of Two Numbers](https://www.hackerrank.com/challenges/sum-numbers-c)|Get started with data types.|[C](sum-numbers-c.c)|Easy
[Functions in C](https://www.hackerrank.com/challenges/functions-in-c)|Learn how to write functions in C++. Create a function to find the maximum of the four numbers.|[C](functions-in-c.c)|Easy
[Pointers in C](https://www.hackerrank.com/challenges/pointer-in-c)|Learn how to declare pointers and use them.|[C](pointer-in-c.c)|Easy
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// C > Introduction > Playing With Characters
// input character, string and a sentence
//
// https://www.hackerrank.com/challenges/playing-with-characters/problem
//
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MAX_LEN 100
int main()
{
char ch;
char s[MAX_LEN];
scanf("%c", &ch);
printf("%c\n", ch);
scanf("%s", s);
printf("%s\n", s);
scanf("\n");
fgets(s, MAX_LEN, stdin);
printf("%s", s);
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
return 0;
} | {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// C > Structs and Enums > Post Transition
// Manage post transactions in a country
//
// https://www.hackerrank.com/challenges/post-transition/problem
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STRING_LENGTH 6
struct package
{
char *id;
int weight;
};
typedef struct package package;
struct post_office
{
int min_weight;
int max_weight;
package* packages;
int packages_count;
};
typedef struct post_office post_office;
struct town
{
char* name;
post_office* offices;
int offices_count;
};
typedef struct town town;
// (template_head) ----------------------------------------------------------------------
void print_all_packages(const town *t)
{
printf("%s:\n", t->name);
for (int i = 0; i < t->offices_count; ++i)
{
printf("\t%d:\n", i);
for (int j = 0; j < t->offices[i].packages_count; ++j)
{
printf("\t\t%s\n", t->offices[i].packages[j].id);
}
}
}
void send_all_acceptable_packages(town* source, int source_office_index, town* target, int target_office_index)
{
post_office *src_po = source->offices + source_office_index;
post_office *dst_po = target->offices + target_office_index;
for (int i = 0; i < src_po->packages_count; )
{
package *p = src_po->packages + i;
if (dst_po->min_weight <= p->weight && p->weight <= dst_po->max_weight)
{
// ok to send package p from src_po to dst_po
dst_po->packages = realloc(dst_po->packages, (dst_po->packages_count + 1) * sizeof(package));
dst_po->packages[dst_po->packages_count].id = p->id; // no need to reallocate
dst_po->packages[dst_po->packages_count].weight = p->weight;
dst_po->packages_count++;
memmove(src_po->packages + i,
src_po->packages + i + 1,
sizeof(package) * (src_po->packages_count - i - 1));
src_po->packages_count--;
src_po->packages = realloc(src_po->packages, sizeof(package) * (src_po->packages_count));
}
else
{
++i;
}
}
}
town town_with_most_packages(town* towns, int towns_count)
{
int max_packages = 0;
int max_i = 0;
for (int i = 0; i < towns_count; ++i)
{
int packages = 0;
for (int j = 0; j < towns[i].offices_count; ++j)
{
packages += towns[i].offices[j].packages_count;
}
if (packages >= max_packages)
{
max_packages = packages;
max_i = i;
}
}
return towns[max_i];
}
town* find_town(town* towns, int towns_count, const char* name)
{
for (int i = 0; i < towns_count; ++i)
{
if (strcmp(towns[i].name, name) == 0)
{
return towns + i;
}
}
return NULL;
}
// (template_tail) ----------------------------------------------------------------------
int main()
{
int towns_count;
scanf("%d", &towns_count);
town* towns = malloc(sizeof(town)*towns_count);
for (int i = 0; i < towns_count; i++) {
towns[i].name = malloc(sizeof(char) * MAX_STRING_LENGTH);
scanf("%s", towns[i].name);
scanf("%d", &towns[i].offices_count);
towns[i].offices = malloc(sizeof(post_office)*towns[i].offices_count);
for (int j = 0; j < towns[i].offices_count; j++) {
scanf("%d%d%d", &towns[i].offices[j].packages_count, &towns[i].offices[j].min_weight, &towns[i].offices[j].max_weight);
towns[i].offices[j].packages = malloc(sizeof(package)*towns[i].offices[j].packages_count);
for (int k = 0; k < towns[i].offices[j].packages_count; k++) {
towns[i].offices[j].packages[k].id = malloc(sizeof(char) * MAX_STRING_LENGTH);
scanf("%s", towns[i].offices[j].packages[k].id);
scanf("%d", &towns[i].offices[j].packages[k].weight);
}
}
}
int queries;
scanf("%d", &queries);
char town_name[MAX_STRING_LENGTH];
while (queries--) {
int type;
scanf("%d", &type);
fprintf(stderr, "QUERY: %d\n", type);
switch (type) {
case 1:
scanf("%s", town_name);
town* t = find_town(towns, towns_count, town_name);
print_all_packages(t);
break;
case 2:
scanf("%s", town_name);
town* source = find_town(towns, towns_count, town_name);
int source_index;
scanf("%d", &source_index);
scanf("%s", town_name);
town* target = find_town(towns, towns_count, town_name);
int target_index;
scanf("%d", &target_index);
send_all_acceptable_packages(source, source_index, target, target_index);
break;
case 3:
printf("Town with the most number of packages is %s\n", town_with_most_packages(towns, towns_count).name);
break;
}
}
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank(small-triangles-large-triangles small-triangles-large-triangles.c)
add_hackerrank(post-transition post-transition.c)
add_hackerrank(too-high-boxes too-high-boxes.c)
add_hackerrank(structuring-the-document structuring-the-document.c)
target_compile_options(small-triangles-large-triangles PRIVATE "-Wno-conversion")
target_compile_options(post-transition PRIVATE "-Wno-conversion")
target_compile_options(structuring-the-document PRIVATE "-Wno-conversion" "-Wno-unused-variable")
target_link_libraries(small-triangles-large-triangles m)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// C > Structs and Enums > Structuring the Document
//
//
// https://www.hackerrank.com/challenges/structuring-the-document/problem
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define MAX_CHARACTERS 1005
#define MAX_PARAGRAPHS 5
struct word {
char* data;
};
struct sentence {
struct word* data;
int word_count;//denotes number of words in a sentence
};
struct paragraph {
struct sentence* data ;
int sentence_count;//denotes number of sentences in a paragraph
};
struct document {
struct paragraph* data;
int paragraph_count;//denotes number of paragraphs in a document
};
// (skeliton_head) ----------------------------------------------------------------------
struct document get_document(char* text)
{
struct document doc;
struct paragraph *cur_paragraph = NULL;
struct sentence *cur_sentence = NULL;
char *new_word = NULL;
doc.data = NULL;
doc.paragraph_count = 0;
for (char *s = text; *s; ++s)
{
if (*s == ' ' || *s == '.')
{
// nouveau paragraphe
if (cur_paragraph == NULL)
{
doc.paragraph_count++;
doc.data = (struct paragraph *) realloc(doc.data, sizeof(struct paragraph) * doc.paragraph_count);
cur_paragraph = doc.data + doc.paragraph_count - 1;
cur_paragraph->data = NULL;
cur_paragraph->sentence_count = 0;
cur_sentence = NULL; // on recommence de facto une phrase
}
// nouvelle phrase
if (cur_sentence == NULL)
{
cur_paragraph->sentence_count++;
cur_paragraph->data = (struct sentence *) realloc(cur_paragraph->data, sizeof(struct sentence) * cur_paragraph->sentence_count);
cur_sentence = cur_paragraph->data + cur_paragraph->sentence_count - 1;
cur_sentence->data = NULL;
cur_sentence->word_count = 0;
}
// nouveau mot
cur_sentence->word_count++;
cur_sentence->data = (struct word *) realloc(cur_sentence->data, sizeof(struct word) * cur_sentence->word_count);
cur_sentence->data[cur_sentence->word_count - 1].data = new_word;
new_word = NULL;
if (*s == '.')
cur_sentence = NULL; // on recommencera une phrase
*s = 0;
}
else if (*s == '\n')
{
cur_sentence = NULL;
cur_paragraph = NULL;
}
else
{
if (new_word == NULL)
{
new_word = s;
}
}
}
return doc;
}
struct word kth_word_in_mth_sentence_of_nth_paragraph(struct document Doc, int k, int m, int n)
{
return Doc.data[n - 1].data[m - 1].data[k - 1];
}
struct sentence kth_sentence_in_mth_paragraph(struct document Doc, int k, int m)
{
return Doc.data[m - 1].data[k - 1];
}
struct paragraph kth_paragraph(struct document Doc, int k)
{
return Doc.data[k - 1];
}
// (skeliton_tail) ----------------------------------------------------------------------
void print_word(struct word w) {
printf("%s", w.data);
}
void print_sentence(struct sentence sen) {
for(int i = 0; i < sen.word_count; i++) {
print_word(sen.data[i]);
if (i != sen.word_count - 1) {
printf(" ");
}
}
}
void print_paragraph(struct paragraph para) {
for(int i = 0; i < para.sentence_count; i++){
print_sentence(para.data[i]);
printf(".");
}
}
void print_document(struct document doc) {
for(int i = 0; i < doc.paragraph_count; i++) {
print_paragraph(doc.data[i]);
if (i != doc.paragraph_count - 1)
printf("\n");
}
}
char* get_input_text() {
int paragraph_count;
scanf("%d", ¶graph_count);
char p[MAX_PARAGRAPHS][MAX_CHARACTERS], doc[MAX_CHARACTERS];
memset(doc, 0, sizeof(doc));
getchar();
for (int i = 0; i < paragraph_count; i++) {
scanf("%[^\n]%*c", p[i]);
strcat(doc, p[i]);
if (i != paragraph_count - 1)
strcat(doc, "\n");
}
char* returnDoc = (char*)malloc((strlen (doc)+1) * (sizeof(char)));
strcpy(returnDoc, doc);
return returnDoc;
}
int main()
{
//local debug
//freopen("tests//structuring-the-document/input/input04.txt", "r", stdin);
char* text = get_input_text();
struct document Doc = get_document(text);
int q;
scanf("%d", &q);
while (q--) {
int type;
scanf("%d", &type);
if (type == 3){
int k, m, n;
scanf("%d %d %d", &k, &m, &n);
struct word w = kth_word_in_mth_sentence_of_nth_paragraph(Doc, k, m, n);
print_word(w);
}
else if (type == 2) {
int k, m;
scanf("%d %d", &k, &m);
struct sentence sen= kth_sentence_in_mth_paragraph(Doc, k, m);
print_sentence(sen);
}
else{
int k;
scanf("%d", &k);
struct paragraph para = kth_paragraph(Doc, k);
print_paragraph(para);
}
printf("\n");
}
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// C > Structs and Enums > Boxes through a Tunnel
// Find the volume of short enough boxes.
//
// https://www.hackerrank.com/challenges/too-high-boxes/problem
//
#include <stdio.h>
#include <stdlib.h>
#define MAX_HEIGHT 41
// (skeliton_head) ----------------------------------------------------------------------
struct box
{
/**
* Define three fields of type int: length, width and height
*/
int length;
int width;
int height;
};
typedef struct box box;
int get_volume(box b) {
/**
* Return the volume of the box
*/
return b.length * b.width * b.height;
}
int is_lower_than_max_height(box b) {
/**
* Return 1 if the box's height is lower than MAX_HEIGHT and 0 otherwise
*/
return b.height < MAX_HEIGHT;
}
// (skeliton_tail) ----------------------------------------------------------------------
int main()
{
int n;
scanf("%d", &n);
box *boxes = malloc(n * sizeof(box));
for (int i = 0; i < n; i++) {
scanf("%d%d%d", &boxes[i].length, &boxes[i].width, &boxes[i].height);
}
for (int i = 0; i < n; i++) {
if (is_lower_than_max_height(boxes[i])) {
printf("%d\n", get_volume(boxes[i]));
}
}
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// C > Structs and Enums > Small Triangles, Large Triangles
// Sort triangles by area
//
// https://www.hackerrank.com/challenges/small-triangles-large-triangles/problem
//
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct triangle
{
int a;
int b;
int c;
};
typedef struct triangle triangle;
// (skeliton_head) ----------------------------------------------------------------------
double heron(const triangle *tr)
{
double p = (tr->a + tr->b + tr->c) / 2.;
return sqrt(p * (p - tr->a) * (p - tr->b) * (p - tr->c));
}
int cmp(const triangle* tr1, const triangle* tr2)
{
double s1 = heron(tr1);
double s2 = heron(tr2);
if (s1 < s2) return -1;
else if (s1 > s2) return 1;
else return 0;
/*
if (tr1->a < tr2->a) return -1;
else if (tr1->a > tr2->a) return 1;
if (tr1->b < tr2->b) return -1;
else if (tr1->b > tr2->b) return 1;
return tr1->c - tr2->c;
*/
}
void sort_by_area(triangle* tr, int n) {
/**
* Sort an array a of the length n
*/
qsort(tr, n, sizeof(triangle), (int(*)(const void*, const void*)) cmp);
}
// (skeliton_tail) ----------------------------------------------------------------------
int main()
{
int n;
scanf("%d", &n);
triangle *tr = malloc(n * sizeof(triangle));
for (int i = 0; i < n; i++) {
scanf("%d%d%d", &tr[i].a, &tr[i].b, &tr[i].c);
}
sort_by_area(tr, n);
for (int i = 0; i < n; i++) {
//printf("%d %d %d %lf\n", tr[i].a, tr[i].b, tr[i].c, heron(tr + i));
printf("%d %d %d\n", tr[i].a, tr[i].b, tr[i].c);
}
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [C](https://www.hackerrank.com/domains/c)
#### [Structs and Enums](https://www.hackerrank.com/domains/c/c-structs-and-enums)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Boxes through a Tunnel](https://www.hackerrank.com/challenges/too-high-boxes)|Find the volume of short enough boxes.|[C](too-high-boxes.c)|Easy
[Small Triangles, Large Triangles](https://www.hackerrank.com/challenges/small-triangles-large-triangles)|Sort triangles by area|[C](small-triangles-large-triangles.c)|Medium
[Post Transition](https://www.hackerrank.com/challenges/post-transition)|Manage post transactions in a country|[C](post-transition.c)|Hard
[Structuring the Document](https://www.hackerrank.com/challenges/structuring-the-document)||[C](structuring-the-document.c)|Hard
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// C > Functions > Sorting Array of Strings
//
//
// https://www.hackerrank.com/challenges/sorting-array-of-strings/problem
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// (skeliton_head) ----------------------------------------------------------------------
int lexicographic_sort(const char* a, const char* b)
{
return strcmp(a, b);
}
int lexicographic_sort_reverse(const char* a, const char* b)
{
return strcmp(b, a);
}
int sort_by_number_of_distinct_characters(const char* a, const char* b)
{
int distincts[256];
int d1 = 0, d2 = 0;
memset(distincts, 0, sizeof(distincts));
for (const char *i = a; *i; ++i) distincts[*i] = 1;
for (int i = 0; i < 128; ++i) d1 += distincts[i];
memset(distincts, 0, sizeof(distincts));
for (const char *i = b; *i; ++i) distincts[*i] = 1;
for (int i = 0; i < 128; ++i) d2 += distincts[i];
if (d1 != d2) return d1 - d2;
return strcmp(a, b);
}
int sort_by_length(const char* a, const char* b)
{
int d = strlen(a) - strlen(b);
if (d != 0) return d;
return strcmp(a, b);
}
void string_sort(char** arr, int len, int (*cmp_func)(const char* a, const char* b))
{
for (int i = 0; i < len; i++)
{
for (int j = i + 1; j < len; j++)
{
if (cmp_func(arr[i], arr[j]) > 0)
{
char *tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
}
// (skeliton_tail) ----------------------------------------------------------------------
int main()
{
int n;
scanf("%d", &n);
char** arr;
arr = (char**)malloc(n * sizeof(char*));
for(int i = 0; i < n; i++){
*(arr + i) = malloc(1024 * sizeof(char));
scanf("%s", *(arr + i));
*(arr + i) = realloc(*(arr + i), strlen(*(arr + i)) + 1);
}
string_sort(arr, n, lexicographic_sort);
for(int i = 0; i < n; i++)
printf("%s\n", arr[i]);
printf("\n");
string_sort(arr, n, lexicographic_sort_reverse);
for(int i = 0; i < n; i++)
printf("%s\n", arr[i]);
printf("\n");
string_sort(arr, n, sort_by_length);
for(int i = 0; i < n; i++)
printf("%s\n", arr[i]);
printf("\n");
string_sort(arr, n, sort_by_number_of_distinct_characters);
for(int i = 0; i < n; i++)
printf("%s\n", arr[i]);
printf("\n");
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// C > Functions > Querying the Document
//
//
// https://www.hackerrank.com/challenges/querying-the-document/problem
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<assert.h>
#define MAX_CHARACTERS 1005
#define MAX_PARAGRAPHS 5
// (skeliton_head) ----------------------------------------------------------------------
char* kth_word_in_mth_sentence_of_nth_paragraph(char**** document, int k, int m, int n) {
return document[n - 1][m - 1][k - 1];
}
char** kth_sentence_in_mth_paragraph(char**** document, int k, int m) {
return document[m - 1][k - 1];
}
char*** kth_paragraph(char**** document, int k) {
return document[k - 1];
}
char**** get_document(char* text)
{
char ****doc = NULL;
int i_paragraph = 0;
int i_sentence = 0;
int i_word = 0;
doc = (char ****) malloc(sizeof(char ***));
doc[0] = (char ***) malloc(sizeof(char **));
doc[0][0] = (char **) malloc(sizeof(char *));
char *word = NULL;
for (char *s = text; *s; ++s)
{
if (*s == ' ' || *s == '.')
{
fprintf(stderr, "add word p%d s%d w%d: %.*s\n", i_paragraph, i_sentence, i_word, (int)(s - word), word);
doc[i_paragraph][i_sentence][i_word] = word;
i_word++;
doc[i_paragraph][i_sentence] = (char **) realloc(doc[i_paragraph][i_sentence], sizeof(char *) * (i_word + 1));
if (*s == '.' && s[1] != '\n')
{
i_word = 0;
i_sentence++;
doc[i_paragraph] = (char ***) realloc(doc[i_paragraph], sizeof(char **) * (i_sentence + 1));
doc[i_paragraph][i_sentence] = (char **) malloc(sizeof(char *));
}
*s = 0;
word = NULL;
}
else if (*s == '\n')
{
*s = 0;
word = NULL;
i_word = 0;
i_sentence = 0;
i_paragraph++;
doc = (char ****) realloc(doc, sizeof(char ***) * (i_paragraph + 1));
doc[i_paragraph] = (char ***) malloc(sizeof(char **));
doc[i_paragraph][0] = (char **) malloc(sizeof(char *));
}
else
{
if (word == NULL)
{
word = s;
//printf("new word: %s\n", word);
}
}
}
return doc;
}
// (skeliton_tail) ----------------------------------------------------------------------
char* get_input_text() {
int paragraph_count;
scanf("%d", ¶graph_count);
char p[MAX_PARAGRAPHS][MAX_CHARACTERS], doc[MAX_CHARACTERS];
memset(doc, 0, sizeof(doc));
getchar();
for (int i = 0; i < paragraph_count; i++) {
scanf("%[^\n]%*c", p[i]);
strcat(doc, p[i]);
if (i != paragraph_count - 1)
strcat(doc, "\n");
}
char* returnDoc = (char*)malloc((strlen (doc)+1) * (sizeof(char)));
strcpy(returnDoc, doc);
return returnDoc;
}
void print_word(char* word) {
printf("%s", word);
}
void print_sentence(char** sentence) {
int word_count;
scanf("%d", &word_count);
for(int i = 0; i < word_count; i++){
printf("%s", sentence[i]);
if( i != word_count - 1)
printf(" ");
}
}
void print_paragraph(char*** paragraph) {
int sentence_count;
scanf("%d", &sentence_count);
for (int i = 0; i < sentence_count; i++) {
print_sentence(*(paragraph + i));
printf(".");
}
}
int main()
{
char* text = get_input_text();
char**** document = get_document(text);
int q;
scanf("%d", &q);
while (q--) {
int type;
scanf("%d", &type);
if (type == 3){
int k, m, n;
scanf("%d %d %d", &k, &m, &n);
char* word = kth_word_in_mth_sentence_of_nth_paragraph(document, k, m, n);
print_word(word);
}
else if (type == 2){
int k, m;
scanf("%d %d", &k, &m);
char** sentence = kth_sentence_in_mth_paragraph(document, k, m);
print_sentence(sentence);
}
else{
int k;
scanf("%d", &k);
char*** paragraph = kth_paragraph(document, k);
print_paragraph(paragraph);
}
printf("\n");
}
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank(recursion-in-c recursion-in-c.c)
add_hackerrank(students-marks-sum students-marks-sum.c)
add_hackerrank(sorting-array-of-strings sorting-array-of-strings.c)
add_hackerrank(variadic-functions-in-c variadic-functions-in-c.c)
add_hackerrank(permutations-of-strings permutations-of-strings.c)
add_hackerrank(querying-the-document querying-the-document.c)
target_compile_options(querying-the-document PRIVATE "-Wno-conversion")
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// C > Functions > Variadic functions in C
//
//
// https://www.hackerrank.com/challenges/variadic-functions-in-c/problem
//
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MIN_ELEMENT 1
#define MAX_ELEMENT 1000000
// (skeliton_head) ----------------------------------------------------------------------
int sum (int count, ...)
{
va_list ap;
int val = 0;
va_start(ap, count);
for(int i = 0; i < count; i++)
val += va_arg(ap, int);
va_end(ap);
return val;
}
int min(int count, ...)
{
va_list ap;
int val = 0;
va_start(ap, count);
for(int i = 0; i < count; i++)
{
int x = va_arg(ap, int);
if (x < val || i == 0) val = x;
}
va_end(ap);
return val;
}
int max(int count, ...)
{
va_list ap;
int val = 0;
va_start(ap, count);
for(int i = 0; i < count; i++)
{
int x = va_arg(ap, int);
if (x > val || i == 0) val = x;
}
va_end(ap);
return val;
}
// (skeliton_tail) ----------------------------------------------------------------------
int test_implementations_by_sending_three_elements() {
srand(time(NULL));
int elements[3];
elements[0] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[1] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[2] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
fprintf(stderr, "Sending following three elements:\n");
for (int i = 0; i < 3; i++) {
fprintf(stderr, "%d\n", elements[i]);
}
int elements_sum = sum(3, elements[0], elements[1], elements[2]);
int minimum_element = min(3, elements[0], elements[1], elements[2]);
int maximum_element = max(3, elements[0], elements[1], elements[2]);
fprintf(stderr, "Your output is:\n");
fprintf(stderr, "Elements sum is %d\n", elements_sum);
fprintf(stderr, "Minimum element is %d\n", minimum_element);
fprintf(stderr, "Maximum element is %d\n\n", maximum_element);
int expected_elements_sum = 0;
for (int i = 0; i < 3; i++) {
if (elements[i] < minimum_element) {
return 0;
}
if (elements[i] > maximum_element) {
return 0;
}
expected_elements_sum += elements[i];
}
return elements_sum == expected_elements_sum;
}
int test_implementations_by_sending_five_elements() {
srand(time(NULL));
int elements[5];
elements[0] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[1] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[2] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[3] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[4] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
fprintf(stderr, "Sending following five elements:\n");
for (int i = 0; i < 5; i++) {
fprintf(stderr, "%d\n", elements[i]);
}
int elements_sum = sum(5, elements[0], elements[1], elements[2], elements[3], elements[4]);
int minimum_element = min(5, elements[0], elements[1], elements[2], elements[3], elements[4]);
int maximum_element = max(5, elements[0], elements[1], elements[2], elements[3], elements[4]);
fprintf(stderr, "Your output is:\n");
fprintf(stderr, "Elements sum is %d\n", elements_sum);
fprintf(stderr, "Minimum element is %d\n", minimum_element);
fprintf(stderr, "Maximum element is %d\n\n", maximum_element);
int expected_elements_sum = 0;
for (int i = 0; i < 5; i++) {
if (elements[i] < minimum_element) {
return 0;
}
if (elements[i] > maximum_element) {
return 0;
}
expected_elements_sum += elements[i];
}
return elements_sum == expected_elements_sum;
}
int test_implementations_by_sending_ten_elements() {
srand(time(NULL));
int elements[10];
elements[0] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[1] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[2] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[3] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[4] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[5] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[6] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[7] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[8] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[9] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
fprintf(stderr, "Sending following ten elements:\n");
for (int i = 0; i < 10; i++) {
fprintf(stderr, "%d\n", elements[i]);
}
int elements_sum = sum(10, elements[0], elements[1], elements[2], elements[3], elements[4],
elements[5], elements[6], elements[7], elements[8], elements[9]);
int minimum_element = min(10, elements[0], elements[1], elements[2], elements[3], elements[4],
elements[5], elements[6], elements[7], elements[8], elements[9]);
int maximum_element = max(10, elements[0], elements[1], elements[2], elements[3], elements[4],
elements[5], elements[6], elements[7], elements[8], elements[9]);
fprintf(stderr, "Your output is:\n");
fprintf(stderr, "Elements sum is %d\n", elements_sum);
fprintf(stderr, "Minimum element is %d\n", minimum_element);
fprintf(stderr, "Maximum element is %d\n\n", maximum_element);
int expected_elements_sum = 0;
for (int i = 0; i < 10; i++) {
if (elements[i] < minimum_element) {
return 0;
}
if (elements[i] > maximum_element) {
return 0;
}
expected_elements_sum += elements[i];
}
return elements_sum == expected_elements_sum;
}
int main ()
{
int number_of_test_cases;
scanf("%d", &number_of_test_cases);
while (number_of_test_cases--) {
if (test_implementations_by_sending_three_elements()) {
printf("Correct Answer\n");
} else {
printf("Wrong Answer\n");
}
if (test_implementations_by_sending_five_elements()) {
printf("Correct Answer\n");
} else {
printf("Wrong Answer\n");
}
if (test_implementations_by_sending_ten_elements()) {
printf("Correct Answer\n");
} else {
printf("Wrong Answer\n");
}
}
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// C > Functions > Permutations of Strings
// Find all permutations of the string array.
//
// https://www.hackerrank.com/challenges/permutations-of-strings/problem
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int next_permutation(int n, char **s)
{
/**
* Complete this method
* Return 0 when there is no next permutation and 1 otherwise
* Modify array s to its next permutation
*/
if (n <= 1)
return 0;
// 1. Find the largest index k such that a[k] < a[k + 1]
int i = n - 1;
while (i > 0 && strcmp(s[i - 1], s[i]) >= 0)
i--;
// If no such index exists, the permutation is the last permutation
if (i == 0)
return 0;
// 2. Find the largest index l greater than k such that a[k] < a[l]
int j = n - 1;
while (strcmp(s[j], s[i - 1]) <= 0)
j--;
// 3. Swap the value of a[k] with that of a[l].
char *temp = s[i - 1];
s[i - 1] = s[j];
s[j] = temp;
// 4. Reverse the sequence from a[k + 1] up to and including the final element a[n]
j = n - 1;
while (i < j)
{
temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
return 1;
}
// (skeliton_tail) ----------------------------------------------------------------------
int main()
{
char **s;
int n;
scanf("%d", &n);
s = calloc(n, sizeof(char*));
for (int i = 0; i < n; i++)
{
s[i] = calloc(11, sizeof(char));
scanf("%s", s[i]);
}
do
{
for (int i = 0; i < n; i++)
printf("%s%c", s[i], i == n - 1 ? '\n' : ' ');
} while (next_permutation(n, s));
for (int i = 0; i < n; i++)
free(s[i]);
free(s);
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.