text
stringlengths 2
104M
| meta
dict |
---|---|
### [Tutorials](https://www.hackerrank.com/domains/tutorials)
#### [Cracking the Coding Interview](https://www.hackerrank.com/domains/tutorials/cracking-the-coding-interview)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Arrays: Left Rotation](https://www.hackerrank.com/challenges/ctci-array-left-rotation)|Given an array and a number, d, perform d left rotations on the array.|[Python](ctci-array-left-rotation.py)|Easy
[Strings: Making Anagrams](https://www.hackerrank.com/challenges/ctci-making-anagrams)|How many characters should one delete to make two given strings anagrams of each other?|[Python](ctci-making-anagrams.py)|Easy
[Hash Tables: Ransom Note](https://www.hackerrank.com/challenges/ctci-ransom-note)|Given two sets of dictionaries, tell if one of them is a subset of the other.|[C++](ctci-ransom-note.cpp)|Easy
[Linked Lists: Detect a Cycle](https://www.hackerrank.com/challenges/ctci-linked-list-cycle)|Given a pointer to the head of a linked list, determine whether the list has a cycle.|[C++](ctci-linked-list-cycle.cpp)|Easy
[Stacks: Balanced Brackets](https://www.hackerrank.com/challenges/ctci-balanced-brackets)|Given a string containing three types of brackets, determine if it is balanced.|[C++](ctci-balanced-brackets.cpp)|Medium
[Queues: A Tale of Two Stacks](https://www.hackerrank.com/challenges/ctci-queue-using-two-stacks)|Create a queue data structure using two stacks.|[C++](ctci-queue-using-two-stacks.cpp)|Medium
[Trees: Is This a Binary Search Tree?](https://www.hackerrank.com/challenges/ctci-is-binary-search-tree)|Given the root of a binary tree, determine if it's a binary search tree.|[Python](ctci-is-binary-search-tree.py)|Medium
[Heaps: Find the Running Median](https://www.hackerrank.com/challenges/ctci-find-the-running-median)|Find the median of the elements after inputting each element.|[C++](ctci-find-the-running-median.cpp)|Hard
[Tries: Contacts](https://www.hackerrank.com/challenges/ctci-contacts)|Create a Contacts application with the two basic operations: add and find.|[Python](ctci-contacts.py)|Hard
[Sorting: Bubble Sort](https://www.hackerrank.com/challenges/ctci-bubble-sort)|Find the minimum number of conditional checks taking place in Bubble Sort|[Python](ctci-bubble-sort.py)|Easy
[Sorting: Comparator](https://www.hackerrank.com/challenges/ctci-comparator-sorting)|Write a Comparator for sorting elements in an array.|[C++](ctci-comparator-sorting.cpp)|Medium
[Merge Sort: Counting Inversions](https://www.hackerrank.com/challenges/ctci-merge-sort)|How many shifts will it take to Merge Sort an array?|[Python](ctci-merge-sort.py)|Hard
[Hash Tables: Ice Cream Parlor](https://www.hackerrank.com/challenges/ctci-ice-cream-parlor)|Help Sunny and Johnny spend all their money during each trip to the Ice Cream Parlor.|[Python](ctci-ice-cream-parlor.py)|Medium
[DFS: Connected Cell in a Grid](https://www.hackerrank.com/challenges/ctci-connected-cell-in-a-grid)|Find the largest connected region in a 2D Matrix.|[C++](ctci-connected-cell-in-a-grid.cpp)|Hard
[BFS: Shortest Reach in a Graph](https://www.hackerrank.com/challenges/ctci-bfs-shortest-reach)|Implement a Breadth First Search (BFS).|[C++](ctci-bfs-shortest-reach.cpp)|Hard
[Time Complexity: Primality](https://www.hackerrank.com/challenges/ctci-big-o)|Determine whether or not a number is prime in optimal time.|[C++](ctci-big-o.cpp)|Medium
[Recursion: Fibonacci Numbers](https://www.hackerrank.com/challenges/ctci-fibonacci-numbers)|Compute the $n^{th}$ Fibonacci number.|[C++](ctci-fibonacci-numbers.cpp)|Easy
[Recursion: Davis' Staircase](https://www.hackerrank.com/challenges/ctci-recursive-staircase)|Find the number of ways to get from the bottom of a staircase to the top if you can jump 1, 2, or 3 stairs at a time.|[C++](ctci-recursive-staircase.cpp)|Medium
[DP: Coin Change](https://www.hackerrank.com/challenges/ctci-coin-change)|Given $m$ distinct dollar coins in infinite quantities, how many ways can you make change for $n$ dollars?|[C++](ctci-coin-change.cpp)|Hard
[Bit Manipulation: Lonely Integer](https://www.hackerrank.com/challenges/ctci-lonely-integer)|Find the unique element in an array of integer pairs.|[C++](ctci-lonely-integer.cpp)|Easy
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Queues: A Tale of Two Stacks
// Create a queue data structure using two stacks.
//
// https://www.hackerrank.com/challenges/ctci-queue-using-two-stacks/problem
//
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
using namespace std;
class MyQueue {
public:
stack<int> stack_newest_on_top, stack_oldest_on_top;
void push(int x)
{
// dans cette stack, les éléments sont ordonnés selon leur ordre d'arrivée
stack_newest_on_top.push(x);
}
void pop()
{
// dans l'autre stack, les éléments sont ordonnés selon leur ordre INVERSE d'arrivée
if (stack_oldest_on_top.empty())
{
while (! stack_newest_on_top.empty())
{
int x = stack_newest_on_top.top();
stack_newest_on_top.pop();
stack_oldest_on_top.push(x);
}
}
stack_oldest_on_top.pop();
}
int front()
{
int x = -1;
if (stack_oldest_on_top.empty())
{
while (! stack_newest_on_top.empty())
{
x = stack_newest_on_top.top();
stack_newest_on_top.pop();
stack_oldest_on_top.push(x);
}
}
else
{
x = stack_oldest_on_top.top();
}
return x;
}
};
int main() {
MyQueue q1;
int q, type, x;
cin >> q;
for(int i = 0; i < q; i++) {
cin >> type;
if(type == 1) {
cin >> x;
q1.push(x);
}
else if(type == 2) {
q1.pop();
}
else cout << q1.front() << endl;
}
/* 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"
} |
// Tutorials > 10 Days of Javascript > Day 7: Regular Expressions II
// Write a JavaScript RegExp to match a name satisfying certain criteria.
//
// https://www.hackerrank.com/challenges/js10-regexp-2/problem
// challenge id: 21850
//
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
// (skeliton_head) ----------------------------------------------------------------------
function regexVar() {
/*
* Declare a RegExp object variable named 're'
* It must match a string that starts with 'Mr.', 'Mrs.', 'Ms.', 'Dr.', or 'Er.',
* followed by one or more letters.
*/
const re = /^(Mr\.|Mrs\.|Ms\.|Dr\.|Er\.)[a-zA-Z]+$/;
/*
* Do not remove the return statement
*/
return re;
}
// (skeliton_tail) ----------------------------------------------------------------------
function main() {
const re = regexVar();
const s = readLine();
console.log(!!s.match(re));
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 10 Days of Javascript > Day 5: Inheritance
// Practice using prototypes and implementing inheritance in JavaScript.
//
// https://www.hackerrank.com/challenges/js10-inheritance/problem
// challenge id: 21000
//
class Rectangle {
constructor(w, h) {
this.w = w;
this.h = h;
}
}
// (skeliton_head) ----------------------------------------------------------------------
/*
* Write code that adds an 'area' method to the Rectangle class' prototype
*/
Rectangle.prototype.area = function() {
return this.w * this.h;
}
/*
* Create a Square class that inherits from Rectangle and implement its class constructor
*/
class Square extends Rectangle {
constructor(w) {
super(w, w);
}
}
// (skeliton_tail) ----------------------------------------------------------------------
if (JSON.stringify(Object.getOwnPropertyNames(Square.prototype)) === JSON.stringify([ 'constructor' ])) {
const rec = new Rectangle(3, 4);
const sqr = new Square(3);
console.log(rec.area());
console.log(sqr.area());
} else {
console.log(-1);
console.log(-1);
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 10 Days of Javascript > Day 7: Regular Expressions III
// Regex
//
// https://www.hackerrank.com/challenges/js10-regexp-3/problem
// challenge id: 21896
//
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
// (skeliton_head) ----------------------------------------------------------------------
function regexVar() {
/*
* Declare a RegExp object variable named 're'
* It must match ALL occurrences of numbers in a string.
*/
const re = /(\d+)/g;
/*
* Do not remove the return statement
*/
return re;
}
// (skeliton_tail) ----------------------------------------------------------------------
function main() {
const re = regexVar();
const s = readLine();
const r = s.match(re);
for (const e of r) {
console.log(e);
}
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 10 Days of Javascript > Day 4: Create a Rectangle Object
// Create an object with certain properties in JavaScript.
//
// https://www.hackerrank.com/challenges/js10-objects/problem
// challenge id: 21012
//
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
// (skeliton_head) ----------------------------------------------------------------------
/*
* Complete the Rectangle function
*/
function Rectangle(a, b) {
return {
length: a,
width: b,
perimeter: (a + b) * 2,
area: a * b
};
}
// (skeliton_tail) ----------------------------------------------------------------------
function main() {
const a = +(readLine());
const b = +(readLine());
const rec = new Rectangle(a, b);
console.log(rec.length);
console.log(rec.width);
console.log(rec.perimeter);
console.log(rec.area);
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 10 Days of Javascript > Day 3: Try, Catch, and Finally
// Learn to use `try`, `catch`, and 'finally' in JavaScript.
//
// https://www.hackerrank.com/challenges/js10-try-catch-and-finally/problem
// challenge id: 20997
//
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
// (skeliton_head) ----------------------------------------------------------------------
/*
* Complete the reverseString function
* Use console.log() to print to stdout.
*/
function reverseString(s) {
try {
s = s.split("").reverse().join("");
}
catch (e) {
console.log(e.message);
}
finally {
console.log(s);
}
}
// (skeliton_tail) ----------------------------------------------------------------------
function main() {
const s = eval(readLine());
reverseString(s);
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 10 Days of Javascript > Day 5: Arrow Functions
// Practice using Arrow Functions in JavaScript.
//
// https://www.hackerrank.com/challenges/js10-arrows/problem
// challenge id: 21891
//
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
// (skeliton_head) ----------------------------------------------------------------------
/*
* Modify and return the array so that all even elements are doubled and all odd elements are tripled.
*
* Parameter(s):
* nums: An array of numbers.
*/
function modifyArray(nums) {
let ans = nums.map(x => (x % 2 == 0) ? x * 2 : x * 3);
return ans;
}
// (skeliton_tail) ----------------------------------------------------------------------
function main() {
const n = +(readLine());
const a = readLine().split(' ').map(Number);
console.log(modifyArray(a).toString().split(',').join(' '));
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 10 Days of Javascript > Day 1: Let and Const
// The const declaration creates a read-only reference to a value.
//
// https://www.hackerrank.com/challenges/js10-let-and-const/problem
// challenge id: 21020
//
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
// (skeliton_head) ----------------------------------------------------------------------
function main() {
// Write your code here. Read input using 'readLine()' and print output using 'console.log()'.
let radius = Number(readLine());
const PI = Math.PI;
// Print the area of the circle:
let area = PI * radius * radius;
console.log(area);
// Print the perimeter of the circle:
let perimeter = PI * radius * 2;
console.log(perimeter);
// (skeliton_tail) ----------------------------------------------------------------------
try {
// Attempt to redefine the value of constant variable PI
PI = 0;
// Attempt to print the value of PI
console.log(PI);
} catch(error) {
console.error("You correctly declared 'PI' as a constant.");
}
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 10 Days of Javascript > Day 6: JavaScript Dates
// Write a JavaScript function that retrieves the day of the week from a given date.
//
// https://www.hackerrank.com/challenges/js10-date/problem
// challenge id: 21015
//
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
// (skeliton_head) ----------------------------------------------------------------------
// The days of the week are: "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
function getDayName(dateString) {
let dayName;
// Write your code here
let d = new Date(dateString);
const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
dayName = dayNames[d.getDay()];
return dayName;
}
// (skeliton_tail) ----------------------------------------------------------------------
function main() {
const d = +(readLine());
for (let i = 0; i < d; i++) {
const date = readLine();
console.log(getDayName(date));
}
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 10 Days of Javascript > Day 4: Count Objects
// Iterate over the elements in an array and perform an action based on each element's properties.
//
// https://www.hackerrank.com/challenges/js10-count-objects/problem
// challenge id: 21013
//
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
// (skeliton_head) ----------------------------------------------------------------------
/*
* Return a count of the total number of objects 'o' satisfying o.x == o.y.
*
* Parameter(s):
* objects: an array of objects with integer properties 'x' and 'y'
*/
function getCount(objects) {
var count = 0;
for (const o of objects)
if (o.x == o.y) count++;
return count;
}
// (skeliton_tail) ----------------------------------------------------------------------
function main() {
const n = +(readLine());
let objects = [];
for (let i = 0; i < n; i++) {
const [a, b] = readLine().split(' ');
objects.push({x: +(a), y: +(b)});
}
console.log(getCount(objects));
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 10 Days of Javascript > Day 0: Data Types
// Get started with JavaScript data types and practice using the + operator.
//
// https://www.hackerrank.com/challenges/js10-data-types/problem
// challenge id: 20939
//
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
// (skeliton_head) ----------------------------------------------------------------------
/**
* The variables 'firstInteger', 'firstDecimal', and 'firstString' are declared for you -- do not modify them.
* Print three lines:
* 1. The sum of 'firstInteger' and the Number representation of 'secondInteger'.
* 2. The sum of 'firstDecimal' and the Number representation of 'secondDecimal'.
* 3. The concatenation of 'firstString' and 'secondString' ('firstString' must be first).
*
* Parameter(s):
* secondInteger - The string representation of an integer.
* secondDecimal - The string representation of a floating-point number.
* secondString - A string consisting of one or more space-separated words.
**/
function performOperation(secondInteger, secondDecimal, secondString) {
// Declare a variable named 'firstInteger' and initialize with integer value 4.
const firstInteger = 4;
// Declare a variable named 'firstDecimal' and initialize with floating-point value 4.0.
const firstDecimal = 4.0;
// Declare a variable named 'firstString' and initialize with the string "HackerRank".
const firstString = 'HackerRank ';
// Write code that uses console.log to print the sum of the 'firstInteger' and 'secondInteger' (converted to a Number type) on a new line.
console.log(firstInteger + Number(secondInteger));
// Write code that uses console.log to print the sum of 'firstDecimal' and 'secondDecimal' (converted to a Number type) on a new line.
console.log(firstDecimal + Number(secondDecimal));
// Write code that uses console.log to print the concatenation of 'firstString' and 'secondString' on a new line. The variable 'firstString' must be printed first.
console.log(firstString + secondString);
}
// (skeliton_tail) ----------------------------------------------------------------------
function main() {
const secondInteger = readLine();
const secondDecimal = readLine();
const secondString = readLine();
performOperation(secondInteger, secondDecimal, secondString);
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank_js(js10-hello-world.js)
add_hackerrank_js(js10-data-types.js)
add_hackerrank_js(js10-arithmetic-operators.js)
add_hackerrank_js(js10-function.js)
add_hackerrank_js(js10-let-and-const.js)
add_hackerrank_js(js10-if-else.js)
add_hackerrank_js(js10-switch.js)
add_hackerrank_js(js10-loops.js)
add_hackerrank_js(js10-arrays.js)
add_hackerrank_js(js10-try-catch-and-finally.js)
add_hackerrank_js(js10-throw.js)
add_hackerrank_js(js10-objects.js)
add_hackerrank_js(js10-count-objects.js)
add_hackerrank_js(js10-class.js)
add_hackerrank_js(js10-inheritance.js)
add_hackerrank_js(js10-template-literals.js)
add_hackerrank_js(js10-arrows.js)
add_hackerrank_js(js10-bitwise.js)
add_hackerrank_js(js10-date.js)
add_hackerrank_js(js10-regexp-1.js)
add_hackerrank_js(js10-regexp-2.js)
add_hackerrank_js(js10-regexp-3.js)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 10 Days of Javascript > Day 4: Classes
// Practice using JavaScript classes.
//
// https://www.hackerrank.com/challenges/js10-class/problem
// challenge id: 21855
//
/*
* Implement a Polygon class with the following properties:
* 1. A constructor that takes an array of integer side lengths.
* 2. A 'perimeter' method that returns the sum of the Polygon's side lengths.
*/
class Polygon {
constructor(sides) {
this.sides = sides;
}
perimeter()
{
let sum = 0;
for (const s of this.sides)
sum += s;
return sum;
}
}
// (skeliton_tail) ----------------------------------------------------------------------
const rectangle = new Polygon([10, 20, 10, 20]);
const square = new Polygon([10, 10, 10, 10]);
const pentagon = new Polygon([10, 20, 30, 40, 43]);
console.log(rectangle.perimeter());
console.log(square.perimeter());
console.log(pentagon.perimeter());
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<!--
# Tutorials > 10 Days of Javascript > Day 8: Buttons Container
# Arrange buttons in a grid.
#
# https://www.hackerrank.com/challenges/js10-buttons-container/problem
# challenge id: 21007
#
-->
<html>
<head>
<style>
.btnContainer {
width: 75%;
}
.btnContainer > .btn {
width: 30%;
height: 48px;
font-size: 24px;
}
</style>
</head>
<body>
<div id="btns" class="btnContainer">
<button id="btn1" class="btn">1</button>
<button id="btn2" class="btn">2</button>
<button id="btn3" class="btn">3</button>
<button id="btn4" class="btn">4</button>
<button id="btn5" class="btn">5</button>
<button id="btn6" class="btn">6</button>
<button id="btn7" class="btn">7</button>
<button id="btn8" class="btn">8</button>
<button id="btn9" class="btn">9</button>
</div>
<script type="text/javascript">
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
var btn3 = document.getElementById('btn3');
var btn4 = document.getElementById('btn4');
var btn5 = document.getElementById('btn5');
var btn6 = document.getElementById('btn6');
var btn7 = document.getElementById('btn7');
var btn8 = document.getElementById('btn8');
var btn9 = document.getElementById('btn9');
btn5.onclick = function() {
let tmp = btn1.innerHTML;
btn1.innerHTML = btn4.innerHTML;
btn4.innerHTML = btn7.innerHTML;
btn7.innerHTML = btn8.innerHTML;
btn8.innerHTML = btn9.innerHTML;
btn9.innerHTML = btn6.innerHTML;
btn6.innerHTML = btn3.innerHTML;
btn3.innerHTML = btn2.innerHTML;
btn2.innerHTML = tmp;
};
</script>
</body>
</html>
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 10 Days of Javascript > Day 7: Regular Expressions I
// Get started with Regular Expressions in JavaScript.
//
// https://www.hackerrank.com/challenges/js10-regexp-1/problem
// challenge id: 20996
//
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
// (skeliton_head) ----------------------------------------------------------------------
function regexVar() {
/*
* Declare a RegExp object variable named 're'
* It must match a string that starts and ends with the same vowel (i.e., {a, e, i, o, u})
*/
var re = /^([aeiou]).*\1$/;
/*
* Do not remove the return statement
*/
return re;
}
// (skeliton_tail) ----------------------------------------------------------------------
function main() {
const re = regexVar();
const s = readLine();
console.log(re.test(s));
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 10 Days of Javascript > Day 6: Bitwise Operators
// Apply everything we've learned in this bitwise AND challenge.
//
// https://www.hackerrank.com/challenges/js10-bitwise/problem
// challenge id: 21854
//
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
// (skeliton_head) ----------------------------------------------------------------------
function getMaxLessThanK(n, k) {
let m = 0;
for (let a = 1; a < n; ++a) {
for (let b = a + 1; b <= n; ++b) {
let v = a & b;
if (v < k && v > m) m = v;
}
}
return m;
}
// (skeliton_tail) ----------------------------------------------------------------------
function main() {
const q = +(readLine());
for (let i = 0; i < q; i++) {
const [n, k] = readLine().split(' ').map(Number);
console.log(getMaxLessThanK(n, k));
}
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 10 Days of Javascript > Day 0: Hello, World!
// Practice printing to stdout using JavaScript.
//
// https://www.hackerrank.com/challenges/js10-hello-world/problem
// challenge id: 20927
//
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
// (skeliton_head) ----------------------------------------------------------------------
/**
* A line of code that prints "Hello, World!" on a new line is provided in the editor.
* Write a second line of code that prints the contents of 'parameterVariable' on a new line.
*
* Parameter:
* parameterVariable - A string of text.
**/
function greeting(parameterVariable) {
// This line prints 'Hello, World!' to the console:
console.log('Hello, World!');
// Write a line of code that prints parameterVariable to stdout using console.log:
console.log(parameterVariable);
}
// (skeliton_tail) ----------------------------------------------------------------------
function main() {
const parameterVariable = readLine();
greeting(parameterVariable);
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 10 Days of Javascript > Day 3: Arrays
// Output the 2nd largest number in an array in JavaScript.
//
// https://www.hackerrank.com/challenges/js10-arrays/problem
// challenge id: 21014
//
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
// (skeliton_head) ----------------------------------------------------------------------
/**
* Return the second largest number in the array.
* @param {Number[]} nums - An array of numbers.
* @return {Number} The second largest number in the array.
**/
function getSecondLargest(nums) {
// Editorial is almost unworthy of computer science :/
let m = 0;
let mm = 0;
for (const i of nums) {
if (i > mm) { m = mm; mm = i; }
else if (i != mm && i > m) { m = i; }
}
return m;
}
// (skeliton_tail) ----------------------------------------------------------------------
function main() {
const n = +(readLine());
const nums = readLine().split(' ').map(Number);
console.log(getSecondLargest(nums));
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 10 Days of Javascript > Day 1: Functions
// Practice writing JavaScript functions.
//
// https://www.hackerrank.com/challenges/js10-function/problem
// challenge id: 21019
//
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
// (skeliton_head) ----------------------------------------------------------------------
/*
* Create the function factorial here
*/
function factorial(n)
{
let f = 1;
while (n > 1)
{
f *= n;
--n;
}
return f;
}
// (skeliton_tail) ----------------------------------------------------------------------
function main() {
const n = +(readLine());
console.log(factorial(n));
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 10 Days of Javascript > Day 3: Throw
// Practice throwing errors` in JavaScript.
//
// https://www.hackerrank.com/challenges/js10-throw/problem
// challenge id: 20998
//
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
// (skeliton_head) ----------------------------------------------------------------------
/*
* Complete the isPositive function.
* If 'a' is positive, return "YES".
* If 'a' is 0, throw an Error with the message "Zero Error"
* If 'a' is negative, throw an Error with the message "Negative Error"
*/
function isPositive(a) {
if (a == 0) throw Error("Zero Error");
if (a < 0) throw Error("Negative Error");
return "YES";
}
// (skeliton_tail) ----------------------------------------------------------------------
function main() {
const n = +(readLine());
for (let i = 0; i < n; i++) {
const a = +(readLine());
try {
console.log(isPositive(a));
} catch (e) {
console.log(e.message);
}
}
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<!--
# Tutorials > 10 Days of Javascript > Day 8: Create a Button
# Create a button.
#
# https://www.hackerrank.com/challenges/js10-create-a-button/problem
# challenge id: 21006
#
-->
<html>
<head>
<style>
#btn {
width: 96px;
height: 48px;
font-size: 24px;
}
</style>
</head>
<body>
<button id="btn">0</button>
<script type="text/javascript">
var btn = document.getElementById('btn');
btn.onclick = function() { ++btn.innerHTML; };
</script>
</body>
</html>
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 10 Days of Javascript > Day 2: Loops
// Learn For, While and Do-While loops in Javascript.
//
// https://www.hackerrank.com/challenges/js10-loops/problem
// challenge id: 20995
//
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
// (skeliton_head) ----------------------------------------------------------------------
/*
* Complete the vowelsAndConsonants function.
* Print your output using 'console.log()'.
*/
function vowelsAndConsonants(s) {
// syntax 1
for (var i = 0; i < s.length; ++i)
if ("aeuio".indexOf(s[i]) >= 0)
console.log(s[i]);
// syntax 2
for (const c of s)
if ("aeuio".indexOf(c) == -1)
console.log(c);
}
// (skeliton_tail) ----------------------------------------------------------------------
function main() {
const s = readLine();
vowelsAndConsonants(s);
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<!--
# Tutorials > 10 Days of Javascript > Day 9: Binary Calculator
# Create a calculator for base 2 arithmetic.
#
# https://www.hackerrank.com/challenges/js10-binary-calculator/problem
# challenge id: 21008
#
-->
<html>
<head>
<style>
body {
width: 33%;
}
#res {
background-color: lightgray;
border: solid;
height: 48px;
font-size: 20px;
}
.btns button {
width: 25%;
height: 36px;
font-size: 18px;
margin: 0px;
float: left;
}
.dgt {
background-color: lightgreen;
color: brown;
}
.ctl {
background-color: darkgreen;
color: white;
}
.op {
background-color: black;
color: red;
}
</style>
</head>
<body>
<div id="res"></div>
<div id="btns" class="btns">
<button id="btn0" class="dgt">0</button>
<button id="btn1" class="dgt">1</button>
<button id="btnClr" class="ctl">C</button>
<button id="btnEql" class="ctl">=</button>
<button id="btnSum" class="op">+</button>
<button id="btnSub" class="op">-</button>
<button id="btnMul" class="op">*</button>
<button id="btnDiv" class="op">/</button>
</div>
<script type="text/javascript">
btnClr.onclick = function() {
res.innerHTML = "";
};
btnEql.onclick = function() {
let s = res.innerHTML;
s = Math.floor(eval(s.replace(/([01]+)/g, '0b$1'))).toString(2);
res.innerHTML = s;
};
btn0.onclick = function() {
res.innerHTML += "0";
};
btn1.onclick = function() {
res.innerHTML += "1";
};
btnSum.onclick = function() {
res.innerHTML += "+";
};
btnSub.onclick = function() {
res.innerHTML += "-";
};
btnMul.onclick = function() {
res.innerHTML += "*";
};
btnDiv.onclick = function() {
res.innerHTML += "/";
};
</script>
</body>
</html>
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 10 Days of Javascript > Day 2: Conditional Statements: If-Else
// Learning about conditional statements.
//
// https://www.hackerrank.com/challenges/js10-if-else/problem
// challenge id: 21009
//
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
// (skeliton_head) ----------------------------------------------------------------------
function getGrade(score) {
let grade;
// Write your code here
if (score <= 30 && score >= 0)
grade = 'FEDCBA'[Math.floor(score / 5)];
else
grade = '?';
return grade;
}
// (skeliton_tail) ----------------------------------------------------------------------
function main() {
const score = +(readLine());
console.log(getGrade(score));
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 10 Days of Javascript > Day 1: Arithmetic Operators
// Learn arithmetic operators in JavaScript.
//
// https://www.hackerrank.com/challenges/js10-arithmetic-operators/problem
// challenge id: 21011
//
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
// (skeliton_head) ----------------------------------------------------------------------
/**
* Calculate the area of a rectangle.
*
* length: The length of the rectangle.
* width: The width of the rectangle.
*
* Return a number denoting the rectangle's area.
**/
function getArea(length, width) {
let area;
area = length * width;
return area;
}
/**
* Calculate the perimeter of a rectangle.
*
* length: The length of the rectangle.
* width: The width of the rectangle.
*
* Return a number denoting the perimeter of a rectangle.
**/
function getPerimeter(length, width) {
let perimeter;
perimeter = (length + width) * 2;
return perimeter;
}
// (skeliton_tail) ----------------------------------------------------------------------
function main() {
const length = +(readLine());
const width = +(readLine());
console.log(getArea(length, width));
console.log(getPerimeter(length, width));
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 10 Days of Javascript > Day 2: Conditional Statements: Switch
// Practice using Switch statements.
//
// https://www.hackerrank.com/challenges/js10-switch/problem
// challenge id: 21010
//
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
// (skeliton_head) ----------------------------------------------------------------------
function getLetter(s) {
let letter;
// Write your code here
switch (s[0]) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
letter = 'A';
break;
case 'b':
case 'c':
case 'd':
case 'f':
case 'g':
letter = 'B';
break;
case 'h':
case 'j':
case 'k':
case 'l':
case 'm':
letter = 'C';
break;
default:
letter = 'D';
break;
}
return letter;
}
// (skeliton_tail) ----------------------------------------------------------------------
function main() {
const s = readLine();
console.log(getLetter(s));
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 10 Days of Javascript > Day 5: Template Literals
// JavaScript Template Strings
//
// https://www.hackerrank.com/challenges/js10-template-literals/problem
// challenge id: 21886
//
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
// (skeliton_head) ----------------------------------------------------------------------
/*
* Determine the original side lengths and return an array:
* - The first element is the length of the shorter side
* - The second element is the length of the longer side
*
* Parameter(s):
* literals: The tagged template literal's array of strings.
* expressions: The tagged template literal's array of expression values (i.e., [area, perimeter]).
*/
function sides(literals, ...expressions) {
let area = expressions[0];
let perimeter = expressions[1];
let a = (perimeter - Math.sqrt(perimeter * perimeter - 16 * area)) / 4;
let b = (perimeter + Math.sqrt(perimeter * perimeter - 16 * area)) / 4;
return [a, b];
}
// (skeliton_tail) ----------------------------------------------------------------------
function main() {
let s1 = +(readLine());
let s2 = +(readLine());
[s1, s2] = [s1, s2].sort();
const [x, y] = sides`The area is: ${s1 * s2}.\nThe perimeter is: ${2 * (s1 + s2)}.`;
console.log((s1 === x) ? s1 : -1);
console.log((s2 === y) ? s2 : -1);
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Tutorials](https://www.hackerrank.com/domains/tutorials)
#### [10 Days of Javascript](https://www.hackerrank.com/domains/tutorials/10-days-of-javascript)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Day 0: Hello, World!](https://www.hackerrank.com/challenges/js10-hello-world)|Practice printing to stdout using JavaScript.|[Javascript](js10-hello-world.js)|Easy
[Day 0: Data Types](https://www.hackerrank.com/challenges/js10-data-types)|Get started with JavaScript data types and practice using the + operator.|[Javascript](js10-data-types.js)|Easy
[Day 1: Arithmetic Operators](https://www.hackerrank.com/challenges/js10-arithmetic-operators)|Learn arithmetic operators in JavaScript.|[Javascript](js10-arithmetic-operators.js)|Easy
[Day 1: Functions](https://www.hackerrank.com/challenges/js10-function)|Practice writing JavaScript functions.|[Javascript](js10-function.js)|Easy
[Day 1: Let and Const](https://www.hackerrank.com/challenges/js10-let-and-const)|The const declaration creates a read-only reference to a value.|[Javascript](js10-let-and-const.js)|Easy
[Day 2: Conditional Statements: If-Else](https://www.hackerrank.com/challenges/js10-if-else)|Learning about conditional statements.|[Javascript](js10-if-else.js)|Easy
[Day 2: Conditional Statements: Switch](https://www.hackerrank.com/challenges/js10-switch)|Practice using Switch statements.|[Javascript](js10-switch.js)|Easy
[Day 2: Loops](https://www.hackerrank.com/challenges/js10-loops)|Learn For, While and Do-While loops in Javascript.|[Javascript](js10-loops.js)|Easy
[Day 3: Arrays](https://www.hackerrank.com/challenges/js10-arrays)|Output the 2nd largest number in an array in JavaScript.|[Javascript](js10-arrays.js)|Easy
[Day 3: Try, Catch, and Finally](https://www.hackerrank.com/challenges/js10-try-catch-and-finally)|Learn to use `try`, `catch`, and 'finally' in JavaScript.|[Javascript](js10-try-catch-and-finally.js)|Easy
[Day 3: Throw](https://www.hackerrank.com/challenges/js10-throw)|Practice throwing errors` in JavaScript.|[Javascript](js10-throw.js)|Easy
[Day 4: Create a Rectangle Object](https://www.hackerrank.com/challenges/js10-objects)|Create an object with certain properties in JavaScript.|[Javascript](js10-objects.js)|Easy
[Day 4: Count Objects](https://www.hackerrank.com/challenges/js10-count-objects)|Iterate over the elements in an array and perform an action based on each element's properties.|[Javascript](js10-count-objects.js)|Easy
[Day 4: Classes](https://www.hackerrank.com/challenges/js10-class)|Practice using JavaScript classes.|[Javascript](js10-class.js)|Easy
[Day 5: Inheritance](https://www.hackerrank.com/challenges/js10-inheritance)|Practice using prototypes and implementing inheritance in JavaScript.|[Javascript](js10-inheritance.js)|Easy
[Day 5: Template Literals](https://www.hackerrank.com/challenges/js10-template-literals)|JavaScript Template Strings|[Javascript](js10-template-literals.js)|Easy
[Day 5: Arrow Functions](https://www.hackerrank.com/challenges/js10-arrows)|Practice using Arrow Functions in JavaScript.|[Javascript](js10-arrows.js)|Easy
[Day 6: Bitwise Operators](https://www.hackerrank.com/challenges/js10-bitwise)|Apply everything we've learned in this bitwise AND challenge.|[Javascript](js10-bitwise.js)|Easy
[Day 6: JavaScript Dates](https://www.hackerrank.com/challenges/js10-date)|Write a JavaScript function that retrieves the day of the week from a given date.|[Javascript](js10-date.js)|Easy
[Day 7: Regular Expressions I](https://www.hackerrank.com/challenges/js10-regexp-1)|Get started with Regular Expressions in JavaScript.|[Javascript](js10-regexp-1.js)|Easy
[Day 7: Regular Expressions II](https://www.hackerrank.com/challenges/js10-regexp-2)|Write a JavaScript RegExp to match a name satisfying certain criteria.|[Javascript](js10-regexp-2.js)|Easy
[Day 7: Regular Expressions III](https://www.hackerrank.com/challenges/js10-regexp-3)|Regex|[Javascript](js10-regexp-3.js)|Easy
[Day 8: Create a Button](https://www.hackerrank.com/challenges/js10-create-a-button)|Create a button.|[HTML](js10-create-a-button.html)|Easy
[Day 8: Buttons Container](https://www.hackerrank.com/challenges/js10-buttons-container)|Arrange buttons in a grid.|[HTML](js10-buttons-container.html)|Easy
[Day 9: Binary Calculator](https://www.hackerrank.com/challenges/js10-binary-calculator)|Create a calculator for base 2 arithmetic.|[HTML](js10-binary-calculator.html)|Medium
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
<!-- Enter your HTML code here -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Binary Calculator</title>
<link rel="stylesheet" href="css/binaryCalculator.css" type="text/css">
</head>
<body>
<div id="res"></div>
<div id="btns" class="btns">
<button id="btn0" class="dgt">0</button>
<button id="btn1" class="dgt">1</button>
<button id="btnClr" class="ctl">C</button>
<button id="btnEql" class="ctl">=</button>
<button id="btnSum" class="op">+</button>
<button id="btnSub" class="op">-</button>
<button id="btnMul" class="op">*</button>
<button id="btnDiv" class="op">/</button>
</div>
<script src="js/binaryCalculator.js" type="text/javascript"></script>
</body>
</html>
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
body {
width: 33%;
}
#res {
background-color: lightgray;
border: solid;
height: 48px;
font-size: 20px;
}
.btns button {
width: 25%;
height: 36px;
font-size: 18px;
margin: 0px;
float: left;
}
.dgt {
background-color: lightgreen;
color: brown;
}
.ctl {
background-color: darkgreen;
color: white;
}
.op {
background-color: black;
color: red;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
btnClr.onclick = function() {
res.innerHTML = "";
}
btnEql.onclick = function() {
let s = res.innerHTML;
s = Math.floor(eval(s.replace(/([01]+)/g, '0b$1'))).toString(2);
res.innerHTML = s;
}
btn0.onclick = function() {
res.innerHTML += "0";
}
btn1.onclick = function() {
res.innerHTML += "1";
}
btnSum.onclick = function() {
res.innerHTML += "+";
}
btnSub.onclick = function() {
res.innerHTML += "-";
}
btnMul.onclick = function() {
res.innerHTML += "*";
}
btnDiv.onclick = function() {
res.innerHTML += "/";
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/button.css" type="text/css">
</head>
<body>
<button id="btn">0</button>
<script src="js/button.js" type="text/javascript"></script>
</body>
</html>
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
#btn {
width: 96px;
height: 48px;
font-size: 24px;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
var btn = document.getElementById('btn');
btn.innerHTML = 0;
btn.onclick = function() { ++btn.innerHTML; }
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
<!-- Enter your HTML code here -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Buttons Grid</title>
<link rel="stylesheet" href="css/buttonsGrid.css" type="text/css">
</head>
<body>
<div id="btns">
<p>
<button id="btn1">1</button>
<button id="btn2">2</button>
<button id="btn3">3</button>
</p>
<p>
<button id="btn4">4</button>
<button id="btn5">5</button>
<button id="btn6">6</button>
</p>
<p>
<button id="btn7">7</button>
<button id="btn8">8</button>
<button id="btn9">9</button>
</p>
</div>
<script src="js/buttonsGrid.js" type="text/javascript"></script>
</body>
</html>
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
#btns {
width: 75%;
}
button {
width: 30%;
height: 48px;
font-size: 24px;
} | {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
var btn3 = document.getElementById('btn3');
var btn4 = document.getElementById('btn4');
var btn5 = document.getElementById('btn5');
var btn6 = document.getElementById('btn6');
var btn7 = document.getElementById('btn7');
var btn8 = document.getElementById('btn8');
var btn9 = document.getElementById('btn9');
btn5.onclick = function() {
let tmp = btn1.innerHTML;
btn1.innerHTML = btn4.innerHTML;
btn4.innerHTML = btn7.innerHTML;
btn7.innerHTML = btn8.innerHTML;
btn8.innerHTML = btn9.innerHTML;
btn9.innerHTML = btn6.innerHTML;
btn6.innerHTML = btn3.innerHTML;
btn3.innerHTML = btn2.innerHTML;
btn2.innerHTML = tmp;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 5: Normal Distribution I
# Problems based on basic statistical distributions.
#
# https://www.hackerrank.com/challenges/s10-normal-distribution-1/problem
# challenge id: 21229
#
import math
π = math.pi
def N(x, µ, σ):
""" Normal Distribution """
return math.exp(- (x - µ) ** 2 / (2 * σ * σ)) / (σ * math.sqrt(2 * π))
def Φ(x, µ, σ):
""" Cumulative Probability """
return 1 / 2 * (1 + math.erf((x - µ) / σ / math.sqrt(2)))
µ = 20
σ = 2
print("{:.3f}".format(Φ(19.5, µ, σ)))
print("{:.3f}".format(Φ(22, µ, σ) - Φ(20, µ, σ))) | {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 5: Poisson Distribution I
# Basic problem on Poisson Distribution.
#
# https://www.hackerrank.com/challenges/s10-poisson-distribution-1/problem
# challenge id: 21227
#
import math
def poisson(λ, k):
return λ ** k * math.e ** (-λ) / math.factorial(k)
λ = float(input())
k = int(input())
print("{:.3f}".format(poisson(λ, k)))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 0: Weighted Mean
# Compute the weighted mean.
#
# https://www.hackerrank.com/challenges/s10-weighted-mean/problem
# challenge id: 21217
#
n = int(input())
X = list(map(int, input().split()))
W = list(map(int, input().split()))
m = sum(x * w for x, w in zip(X, W)) / sum(W)
print("{:.1f}".format(m))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 6: The Central Limit Theorem II
# Basic problems on the Central Limit Theorem.
#
# https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-2/problem
# challenge id: 21225
#
import math
def Φ(x, µ, σ):
""" Cumulative Probability """
return 1 / 2 * (1 + math.erf((x - µ) / σ / math.sqrt(2)))
tickets = int(input()) # 250
students = int(input()) # 100
µ = float(input()) # 2.4 mean
σ = float(input()) # 2.0 standard deviation
p = Φ(tickets, students * µ, math.sqrt(students) * σ)
print("{:.4f}".format(p))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 9: Multiple Linear Regression
# Learn multiple linear regression
#
# https://www.hackerrank.com/challenges/s10-multiple-linear-regression/problem
# challenge id: 21158
#
from sklearn import linear_model
import numpy as np
# suppress a annoying warning on macOS
import warnings
warnings.filterwarnings(action="ignore", module="sklearn", message="^internal gelsd")
m, n = map(int, input().split())
X = []
Y = []
for _ in range(n):
f_y = np.array(input().split(), np.float)
X.append(f_y[:-1])
Y.append(f_y[-1])
lm = linear_model.LinearRegression()
lm.fit(X, Y)
a = lm.intercept_
b = lm.coef_
for _ in range(int(input())):
f = np.array(input().split(), np.float)
y = a + np.sum(f * b)
print(np.ceil(y * 100) / 100) # the rounding in the testcases it not good...
# print('{:.2f}'.format(y)) # this is more accurate
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 5: Poisson Distribution II
# Basic problem on Poisson Distribution.
#
# https://www.hackerrank.com/challenges/s10-poisson-distribution-2/problem
# challenge id: 21228
#
import math
def poisson(λ, k):
return λ ** k * math.e ** (-λ) / math.factorial(k)
def E(λ):
return λ + λ ** 2
λ1, λ2 = map(float, input().split())
print("{:.3f}".format(160 + 40 * E(λ1)))
print("{:.3f}".format(128 + 40 * E(λ2)))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 7: Pearson Correlation Coefficient I
# Computing Pearson correlation coefficient.
#
# https://www.hackerrank.com/challenges/s10-pearson-correlation-coefficient/problem
# challenge id: 21178
#
# Pearson: measure of the linear correlation between two variables X and Y
def pearson(n, X, Y):
mx = sum(X) / n # moyenne de la série X
my = sum(Y) / n
sx = 0
sy = 0
p = 0
for x, y in zip(X, Y):
sx += (x - mx) ** 2 # calcule l'écart-type de X
sy += (y - my) ** 2 # calcule l'écart-type de Y
p += (x - mx) * (y - my) # calcule la covariance de (X,Y)
sx = (sx / n) ** 0.5
sy = (sy / n) ** 0.5
p = p / (n * sx * sy)
return p
n = int(input())
X = list(map(float, input().split()))
Y = list(map(float, input().split()))
print('{:.3f}'.format(pearson(n, X, Y)))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 4: Geometric Distribution I
# Problems based on basic statistical distributions.
#
# https://www.hackerrank.com/challenges/s10-geometric-distribution-1/problem
# challenge id: 21244
#
def g(n, p):
return p * (1 - p) ** (n - 1)
ko, total = map(int, input().split())
n = int(input())
r = g(n, ko / total)
print("%.3f" % r)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 0: Mean, Median, and Mode
# Compute the mean, median, mode, and standard deviation.
#
# https://www.hackerrank.com/challenges/s10-basic-statistics/problem
# challenge id: 21180
#
from itertools import groupby
n = int(input())
x = list(map(int, input().split()))
# la moyenne arithmétique
m = sum(x) / len(x)
print("{:.1f}".format(m))
# la valeur médiane
x = sorted(x)
if n % 2 == 1:
m = x[n // 2]
print(m)
else:
m = (x[n // 2 - 1] + x[n // 2]) / 2
print("{:.1f}".format(m))
# la classe modale
# on trie les paires par longueur décroissante: la première sera la plus grande en valeur absolue
m = sorted([-len(list(g)), int(k)] for k, g in groupby(x))
print(m[0][1])
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 2: Basic Probability
# Calculate the probability that two dice will have a maximum sum of 9.
#
# https://www.hackerrank.com/challenges/s10-mcq-1/problem
# challenge id: 21607
#
from fractions import Fraction
n = 0
for i in range(1, 7):
for j in range(1, 7):
if i + j <= 9:
n += 1
print(Fraction(n, 6 * 6))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 3: Cards of the Same Suit
# Find the probability that 2 cards drawn from a deck (without replacement) are of the same suit.
#
# https://www.hackerrank.com/challenges/s10-mcq-5/problem
# challenge id: 21611
#
12 / 51
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 7: Spearman's Rank Correlation Coefficient
# Computing Spearman's rank correlation coefficient.
#
# https://www.hackerrank.com/challenges/s10-spearman-rank-correlation-coefficient/problem
# challenge id: 21707
#
def spearman(n, X, Y):
""" calcul du coefficient de Spearman pour des échantillons avec des valeurs uniques """
def rank(X):
r = [0] * len(X)
xs = sorted((x, i) for i, x in enumerate(X))
for j, xi in enumerate(xs):
r[xi[1]] = j + 1
return r
# somme de la différence des ranks au carré
r = sum((rx - ry) ** 2 for rx, ry in zip(rank(X), rank(Y)))
r = 1 - 6 * r / n / (n ** 2 - 1)
return r
n = int(input())
X = list(map(float, input().split()))
Y = list(map(float, input().split()))
c = spearman(n, X, Y)
print('{:.3f}'.format(c))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 8: Least Square Regression Line
# Find the line of best fit.
#
# https://www.hackerrank.com/challenges/s10-least-square-regression-line/problem
# challenge id: 21177
#
def pearson(n, X, Y):
mx = sum(X) / n # moyenne de la série X
my = sum(Y) / n
sx = 0.
sy = 0.
p = 0.
for x, y in zip(X, Y):
sx += (x - mx) ** 2 # calcule l'écart-type de X
sy += (y - my) ** 2 # calcule l'écart-type de Y
p += (x - mx) * (y - my) # calcule la covariance de (X,Y)
sx = (sx / n) ** 0.5
sy = (sy / n) ** 0.5
p = p / (n * sx * sy)
b = p * sy / sx # Y = a + b X
a = my - b * mx
return p, a, b
X, Y = [0] * 5, [0] * 5
for i in range(5):
X[i], Y[i] = map(int, input().split())
_, a, b = pearson(5, X, Y)
print("{:.3f}".format(a + b * 80))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
include(FindPythonInterp)
add_hackerrank_py(s10-basic-statistics.py)
add_hackerrank_py(s10-weighted-mean.py)
add_hackerrank_py(s10-quartiles.py)
add_hackerrank_py(s10-standard-deviation.py)
add_hackerrank_py(s10-interquartile-range.py)
add_hackerrank_py(s10-mcq-1.py)
add_hackerrank_py(s10-mcq-2.py)
add_hackerrank_py(s10-mcq-3.py)
add_hackerrank_py(s10-binomial-distribution-1.py)
add_hackerrank_py(s10-binomial-distribution-2.py)
add_hackerrank_py(s10-geometric-distribution-1.py)
add_hackerrank_py(s10-geometric-distribution-2.py)
add_hackerrank_py(s10-poisson-distribution-1.py)
add_hackerrank_py(s10-poisson-distribution-2.py)
add_hackerrank_py(s10-normal-distribution-1.py)
add_hackerrank_py(s10-normal-distribution-2.py)
add_hackerrank_py(s10-the-central-limit-theorem-1.py)
add_hackerrank_py(s10-the-central-limit-theorem-2.py)
add_hackerrank_py(s10-the-central-limit-theorem-3.py)
add_hackerrank_py(s10-pearson-correlation-coefficient.py)
add_hackerrank_py(s10-spearman-rank-correlation-coefficient.py)
add_hackerrank_py(s10-least-square-regression-line.py)
# scikit-learn does not work with Python 3.7
if(PYTHON_VERSION_STRING VERSION_LESS 3.7)
add_hackerrank_py(s10-multiple-linear-regression.py)
endif()
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 5: Normal Distribution II
# Problems based on basic statistical distributions.
#
# https://www.hackerrank.com/challenges/s10-normal-distribution-2/problem
# challenge id: 21230
#
import math
def N(x, µ, σ):
""" Normal Distribution """
π = math.pi
return math.exp(- (x - µ) ** 2 / (2 * σ * σ)) / (σ * math.sqrt(2 * π))
def Φ(x, µ, σ):
""" Cumulative Probability """
return 1 / 2 * (1 + math.erf((x - µ) / σ / math.sqrt(2)))
µ, σ = map(float, input().split())
q1 = float(input())
q2 = float(input())
# percentage of students having grade > q1
print("{:.2f}".format(100 - Φ(q1, µ, σ) * 100))
# percentage of students having grade ≥ q2
print("{:.2f}".format(100 - Φ(q2, µ, σ) * 100))
# percentage of students having grade < q2
print("{:.2f}".format(Φ(q2, µ, σ) * 100))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 8: Pearson Correlation Coefficient II
# Find the Pearson correlation coefficient
#
# https://www.hackerrank.com/challenges/s10-mcq-7/problem
# challenge id: 21709
#
# explication:
# 3*x + 4*y + 8 = 0 ⟹ y = -3/4 * x - 2 ⟹ b = -3/4 = ρ σy/σx
# 4*x + 3*y + 7 = 0 ⟹ x = -3/4 * y - 7/4 ⟹ b = -3/4 = ρ σx/σy
# (-3/4)² = ρ² ⟹ ρ = ± 3/4
# b < 0 ⟹ ρ = - 3/4
-3 / 4
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 1: Interquartile Range
# Calculate the interquartile range.
#
# https://www.hackerrank.com/challenges/s10-interquartile-range/problem
# challenge id: 21249
#
def median(x):
n = len(x)
if n % 2 == 1:
return x[n // 2]
else:
return (x[n // 2 - 1] + x[n // 2]) / 2
n = int(input())
X = list(map(int, input().split()))
F = list(map(int, input().split()))
S = []
for x, f in zip(X, F):
S.extend([x] * f)
S = sorted(S)
n = len(S)
if n % 2 == 1:
Q1 = median(S[:(n // 2)])
Q3 = median(S[(n // 2) + 1:])
else:
Q1 = median(S[:(n // 2)])
Q3 = median(S[(n // 2):])
print("{:.1f}".format(Q3 - Q1))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 4: Binomial Distribution II
# Problems based on basic statistical distributions.
#
# https://www.hackerrank.com/challenges/s10-binomial-distribution-2/problem
# challenge id: 21232
#
from math import factorial
# b(x,n,p) = C(n,p) * p^x * (1-p)^(n-x)
# x: number of successes
# n: total number of trials
# p: probability of success of 1 trial
def b(n, x, p):
return factorial(n) // factorial(n - x) // factorial(x) * (p ** x) * (1 - p) ** (n - x)
p, n = map(int, input().split())
p = p / 100 # proba qu'un piston soit ko
r = b(n, 0, p) + b(n, 1, p) + b(n, 2, p) # 0 ou 1 ou 2 rejets
print("%.3f" % r)
r = sum(b(n, i, p) for i in range(2, n + 1)) # 2 à 12 rejets
print("%.3f" % r)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 1: Standard Deviation
# Compute the standard deviation
#
# https://www.hackerrank.com/challenges/s10-standard-deviation/problem
# challenge id: 21237
#
n = int(input())
x = list(map(int, input().split()))
Σ = sum
# moyenne (mean)
µ = Σ(x) / n
# écart-type (standard deviation)
𝜎 = (Σ((i - µ) ** 2 for i in x) / n) ** 0.5
print("{:.1f}".format(𝜎))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 2: Compound Event Probability
#
#
# https://www.hackerrank.com/challenges/s10-mcq-3/problem
# challenge id: 21609
#
from fractions import Fraction
n, t = 0, 0
for i in range(1, 8):
for j in range(1, 10):
for k in range(1, 9):
red, black = 0, 0
if i <= 4:
red += 1
else:
black += 1
if j <= 5:
red += 1
else:
black += 1
if k <= 4:
red += 1
else:
black += 1
if red == 2 and black == 1:
n += 1
t += 1
print(Fraction(n, t))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 3: Conditional Probability
# Find the probability that both children are boys, given that one is a boy.
#
# https://www.hackerrank.com/challenges/s10-mcq-4/problem
# challenge id: 21610
#
1 / 3
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 6: The Central Limit Theorem I
# Basic problems on the Central Limit Theorem.
#
# https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-1/problem
# challenge id: 21224
#
import math
def Φ(x, µ, σ):
""" Cumulative Probability """
return 1 / 2 * (1 + math.erf((x - µ) / σ / math.sqrt(2)))
capacity = float(input()) # 9800 maximum load
n = int(input()) # 49 number of boxes
µ = float(input()) # 205 mean
σ = float(input()) # 15 standard deviation
p = Φ(capacity, n * µ, math.sqrt(n) * σ)
print("{:.4f}".format(p))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 2: More Dice
# Calculate the probability that two dice will roll two unique values having a sum of 6.
#
# https://www.hackerrank.com/challenges/s10-mcq-2/problem
# challenge id: 21608
#
from fractions import Fraction
n = 0
for i in range(1, 7):
for j in range(1, 7):
if i + j == 6 and i != j:
n += 1
print(Fraction(n, 6 * 6)) | {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 4: Geometric Distribution II
# Problems based on basic statistical distributions.
#
# https://www.hackerrank.com/challenges/s10-geometric-distribution-2/problem
# challenge id: 21245
#
def g(n, p):
return p * (1 - p) ** (n - 1)
ko, total = map(int, input().split())
n = int(input())
r = sum(g(n, ko / total) for n in range(1, 6))
print("%.3f" % r)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 4: Binomial Distribution I
# Problems based on basic statistical distributions.
#
# https://www.hackerrank.com/challenges/s10-binomial-distribution-1/problem
# challenge id: 21231
#
from math import factorial
# b(x,n,p) = C(n,p) * p^x * (1-p)^(n-x)
# x: number of successes
# n: total number of trials
# p: probability of success of 1 trial
def b(n, x, p):
return factorial(n) // factorial(n - x) // factorial(x) * (p ** x) * (1 - p) ** (n - x)
boys, girls = map(float, input().split())
p = boys / (boys + girls)
r = b(6, 3, p) + b(6, 4, p) + b(6, 5, p) + b(6, 6, p)
print("%.3f" % r)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 6: The Central Limit Theorem III
# Basic problems on the Central Limit Theorem.
#
# https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-3/problem
# challenge id: 21226
#
import math
n = int(input()) # 100 sample size
µ = float(input()) # 500 mean
σ = float(input()) # 80 standard deviation
percent = float(input()) # 0.95 distribution percentage we want to cover
z = float(input()) # 1.96 z-score : Φ(1.96) - Φ(-1.96) ≈ 95%
e = z * σ / math.sqrt(n)
print('{:2f}'.format(µ - e))
print('{:2f}'.format(µ + e))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Tutorials](https://www.hackerrank.com/domains/tutorials)
#### [10 Days of Statistics](https://www.hackerrank.com/domains/tutorials/10-days-of-statistics)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Day 0: Mean, Median, and Mode](https://www.hackerrank.com/challenges/s10-basic-statistics)|Compute the mean, median, mode, and standard deviation.|[Python](s10-basic-statistics.py)|Easy
[Day 0: Weighted Mean](https://www.hackerrank.com/challenges/s10-weighted-mean)|Compute the weighted mean.|[Python](s10-weighted-mean.py)|Easy
[Day 1: Quartiles](https://www.hackerrank.com/challenges/s10-quartiles)|Calculate quartiles for an array of integers|[Python](s10-quartiles.py)|Easy
[Day 1: Interquartile Range](https://www.hackerrank.com/challenges/s10-interquartile-range)|Calculate the interquartile range.|[Python](s10-interquartile-range.py)|Easy
[Day 1: Standard Deviation](https://www.hackerrank.com/challenges/s10-standard-deviation)|Compute the standard deviation|[Python](s10-standard-deviation.py)|Easy
[Day 2: Basic Probability](https://www.hackerrank.com/challenges/s10-mcq-1)|Calculate the probability that two dice will have a maximum sum of 9.|[Python](s10-mcq-1.py)|Easy
[Day 2: More Dice](https://www.hackerrank.com/challenges/s10-mcq-2)|Calculate the probability that two dice will roll two unique values having a sum of 6.|[Python](s10-mcq-2.py)|Easy
[Day 2: Compound Event Probability](https://www.hackerrank.com/challenges/s10-mcq-3)||[Python](s10-mcq-3.py)|Easy
[Day 3: Conditional Probability](https://www.hackerrank.com/challenges/s10-mcq-4)|Find the probability that both children are boys, given that one is a boy.|[text](s10-mcq-4.txt)|Easy
[Day 3: Cards of the Same Suit](https://www.hackerrank.com/challenges/s10-mcq-5)|Find the probability that 2 cards drawn from a deck (without replacement) are of the same suit.|[text](s10-mcq-5.txt)|Easy
[Day 3: Drawing Marbles](https://www.hackerrank.com/challenges/s10-mcq-6)|Find the probability that the second marble drawn is blue.|[text](s10-mcq-6.txt)|Easy
[Day 4: Binomial Distribution I](https://www.hackerrank.com/challenges/s10-binomial-distribution-1)|Problems based on basic statistical distributions.|[Python](s10-binomial-distribution-1.py)|Easy
[Day 4: Binomial Distribution II](https://www.hackerrank.com/challenges/s10-binomial-distribution-2)|Problems based on basic statistical distributions.|[Python](s10-binomial-distribution-2.py)|Easy
[Day 4: Geometric Distribution I](https://www.hackerrank.com/challenges/s10-geometric-distribution-1)|Problems based on basic statistical distributions.|[Python](s10-geometric-distribution-1.py)|Easy
[Day 4: Geometric Distribution II](https://www.hackerrank.com/challenges/s10-geometric-distribution-2)|Problems based on basic statistical distributions.|[Python](s10-geometric-distribution-2.py)|Easy
[Day 5: Poisson Distribution I](https://www.hackerrank.com/challenges/s10-poisson-distribution-1)|Basic problem on Poisson Distribution.|[Python](s10-poisson-distribution-1.py)|Easy
[Day 5: Poisson Distribution II](https://www.hackerrank.com/challenges/s10-poisson-distribution-2)|Basic problem on Poisson Distribution.|[Python](s10-poisson-distribution-2.py)|Easy
[Day 5: Normal Distribution I](https://www.hackerrank.com/challenges/s10-normal-distribution-1)|Problems based on basic statistical distributions.|[Python](s10-normal-distribution-1.py)|Easy
[Day 5: Normal Distribution II](https://www.hackerrank.com/challenges/s10-normal-distribution-2)|Problems based on basic statistical distributions.|[Python](s10-normal-distribution-2.py)|Easy
[Day 6: The Central Limit Theorem I](https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-1)|Basic problems on the Central Limit Theorem.|[Python](s10-the-central-limit-theorem-1.py)|Easy
[Day 6: The Central Limit Theorem II](https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-2)|Basic problems on the Central Limit Theorem.|[Python](s10-the-central-limit-theorem-2.py)|Easy
[Day 6: The Central Limit Theorem III](https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-3)|Basic problems on the Central Limit Theorem.|[Python](s10-the-central-limit-theorem-3.py)|Easy
[Day 7: Pearson Correlation Coefficient I](https://www.hackerrank.com/challenges/s10-pearson-correlation-coefficient)|Computing Pearson correlation coefficient.|[Python](s10-pearson-correlation-coefficient.py)|Easy
[Day 7: Spearman's Rank Correlation Coefficient](https://www.hackerrank.com/challenges/s10-spearman-rank-correlation-coefficient)|Computing Spearman's rank correlation coefficient.|[Python](s10-spearman-rank-correlation-coefficient.py)|Easy
[Day 8: Least Square Regression Line](https://www.hackerrank.com/challenges/s10-least-square-regression-line)|Find the line of best fit.|[Python](s10-least-square-regression-line.py)|Easy
[Day 8: Pearson Correlation Coefficient II](https://www.hackerrank.com/challenges/s10-mcq-7)|Find the Pearson correlation coefficient|[text](s10-mcq-7.txt)|Medium
[Day 9: Multiple Linear Regression](https://www.hackerrank.com/challenges/s10-multiple-linear-regression)|Learn multiple linear regression|[Python](s10-multiple-linear-regression.py)|Medium
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 1: Quartiles
# Calculate quartiles for an array of integers
#
# https://www.hackerrank.com/challenges/s10-quartiles/problem
# challenge id: 21248
#
def median(x):
n = len(x)
if n % 2 == 1:
return x[n // 2]
else:
return (x[n // 2 - 1] + x[n // 2]) // 2
n = int(input())
x = list(map(int, input().split()))
x = sorted(x)
Q2 = median(x)
if n % 2 == 1:
Q1 = median(x[0:(n // 2)])
Q3 = median(x[(n // 2) + 1:])
else:
Q1 = median(x[0:(n // 2)])
Q3 = median(x[(n // 2):])
print(Q1)
print(Q2)
print(Q3)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 10 Days of Statistics > Day 3: Drawing Marbles
# Find the probability that the second marble drawn is blue.
#
# https://www.hackerrank.com/challenges/s10-mcq-6/problem
# challenge id: 21612
#
2 / 3
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 30 Days of Code > Day 13: Abstract Classes
# Build on what you've already learned about Inheritance with this Abstract Classes challenge
#
# https://www.hackerrank.com/challenges/30-abstract-classes/problem
#
from abc import ABCMeta, abstractmethod
class Book(object, metaclass=ABCMeta):
def __init__(self,title,author):
self.title=title
self.author=author
@abstractmethod
def display(): pass
# (skeliton_head) ----------------------------------------------------------------------
class MyBook(Book):
def __init__(self, title, author, price):
super().__init__(title, author)
self.price = price
def display(self):
print("Title:", self.title)
print("Author:", self.author)
print("Price:", self.price)
# (skeliton_tail) ----------------------------------------------------------------------
title=input()
author=input()
price=int(input())
new_novel=MyBook(title,author,price)
new_novel.display()
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 30 Days of Code > Day 12: Inheritance
// Learn about inheritance.
//
// https://www.hackerrank.com/challenges/30-inheritance/problem
//
#include <iostream>
#include <vector>
using namespace std;
class Person{
protected:
string firstName;
string lastName;
int id;
public:
Person(string firstName, string lastName, int identification){
this->firstName = firstName;
this->lastName = lastName;
this->id = identification;
}
void printPerson(){
cout<< "Name: "<< lastName << ", "<< firstName <<"\nID: "<< id << "\n";
}
};
// (skeliton_head) ----------------------------------------------------------------------
#include <bits/stdc++.h>
class Student : public Person{
private:
vector<int> testScores;
public:
/*
* Class Constructor
*
* Parameters:
* firstName - A string denoting the Person's first name.
* lastName - A string denoting the Person's last name.
* id - An integer denoting the Person's ID number.
* scores - An array of integers denoting the Person's test scores.
*/
// Write your constructor here
Student(const string& firstName, const string& lastName, int identification, const vector<int>& scores) :
Person(firstName, lastName, identification),
testScores(scores)
{}
/*
* Function Name: calculate
* Return: A character denoting the grade.
*/
// Write your function here
char calculate() const
{
int sum = std::accumulate(testScores.begin(), testScores.end(), 0);
float avg = sum / testScores.size();
if (avg >= 90) return 'O';
if (avg >= 80) return 'E';
if (avg >= 70) return 'A';
if (avg >= 55) return 'P';
if (avg >= 40) return 'D';
return 'T';
}
};
// (skeliton_tail) ----------------------------------------------------------------------
int main() {
string firstName;
string lastName;
int id;
int numScores;
cin >> firstName >> lastName >> id >> numScores;
vector<int> scores;
for(int i = 0; i < numScores; i++){
int tmpScore;
cin >> tmpScore;
scores.push_back(tmpScore);
}
Student* s = new Student(firstName, lastName, id, scores);
s->printPerson();
cout << "Grade: " << s->calculate() << "\n";
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Day 0: Hello, World.
# Tutorials > 30 Days of Code
# Practice reading from stdin and printing to stdout.
#
# https://www.hackerrank.com/challenges/30-hello-world/problem
#
# Read a full line of input from stdin and save it to our dynamically typed variable, input_string.
input_string = input()
# Print a string literal saying "Hello, World." to stdout.
print('Hello, World.')
# TODO: Write a line of code here that prints the contents of input_string to stdout.
print(input_string)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 30 Days of Code > Day 21: Generics
// Welcome to Day 21! Review generics in this challenge!
//
// https://www.hackerrank.com/challenges/30-generics/problem
//
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// (skeliton_head) ----------------------------------------------------------------------
/**
* Name: printArray
* Print each element of the generic vector on a new line. Do not return anything.
* @param A generic vector
**/
template<typename T>
void printArray(const vector<T>& a)
{
for (auto i : a)
cout << i << endl;
}
// (skeliton_tail) ----------------------------------------------------------------------
int main() {
int n;
cin >> n;
vector<int> int_vector(n);
for (int i = 0; i < n; i++) {
int value;
cin >> value;
int_vector[i] = value;
}
cin >> n;
vector<string> string_vector(n);
for (int i = 0; i < n; i++) {
string value;
cin >> value;
string_vector[i] = value;
}
printArray<int>(int_vector);
printArray<string>(string_vector);
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 30 Days of Code > Day 14: Scope
# Learn about the scope of an identifier.
#
# https://www.hackerrank.com/challenges/30-scope/problem
#
class Difference:
def __init__(self, a):
self.__elements = a
# (skeliton_head) ----------------------------------------------------------------------
def __init__(self, a):
self.a = a
def computeDifference(self):
self.maximumDifference = max(self.a) - min(self.a)
# (skeliton_tail) ----------------------------------------------------------------------
# End of Difference class
_ = input()
a = [int(e) for e in input().split(' ')]
d = Difference(a)
d.computeDifference()
print(d.maximumDifference)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 30 Days of Code > Day 14: Scope
// Learn about the scope of an identifier.
//
// https://www.hackerrank.com/challenges/30-scope/problem
//
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Difference {
private:
vector<int> elements;
public:
int maximumDifference;
// (skeliton_head) ----------------------------------------------------------------------
Difference(const vector<int>& a)
{
maximumDifference = *std::max_element(a.begin(), a.end()) - *std::min_element(a.begin(), a.end());
}
void computeDifference() const
{}
// (skeliton_tail) ----------------------------------------------------------------------
}; // End of Difference class
int main() {
int N;
cin >> N;
vector<int> a;
for (int i = 0; i < N; i++) {
int e;
cin >> e;
a.push_back(e);
}
Difference d(a);
d.computeDifference();
cout << d.maximumDifference;
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 30 Days of Code > Day 15: Linked List
// Complete the body of a function that adds a new node to the tail of a Linked List.
//
// https://www.hackerrank.com/challenges/30-linked-list/problem
//
#include <iostream>
#include <cstddef>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int d){
data=d;
next=NULL;
}
};
class Solution{
public:
// (skeliton_head) ----------------------------------------------------------------------
Node* insert(Node *head,int data)
{
//Complete this method
if (head == NULL)
{
return new Node(data);
}
Node *node = head;
while (node->next)
{
node = node->next;
}
node->next = new Node(data);
return head;
}
// (skeliton_tail) ----------------------------------------------------------------------
void display(Node *head)
{
Node *start=head;
while(start)
{
cout<<start->data<<" ";
start=start->next;
}
}
};
int main()
{
Node* head=NULL;
Solution mylist;
int T,data;
cin>>T;
while(T-->0){
cin>>data;
head=mylist.insert(head,data);
}
mylist.display(head);
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 30 Days of Code > Day 27: Testing
# Welcome to Day 27! Review testing in this challenge!
#
# https://www.hackerrank.com/challenges/30-testing/problem
#
from random import randint
print(5)
# YES (cancelled, il faut au plus k-1 nombres <= 0)
def yes():
n = randint(50, 200)
k = randint(10, n - 5)
print(n, k)
A = [0]
for i in range(k - 2):
A.append(randint(-1000, -1))
while len(A) < n:
A.append(randint(1, 1000))
print(' '.join(map(str, A)))
# NO (il faut au moins k nombres <= 0)
def no():
n = randint(50, 200)
k = randint(10, n - 5)
print(n, k)
A = [0]
for i in range(k + 2):
A.append(randint(-1000, -1))
while len(A) < n:
A.append(randint(1, 1000))
print(' '.join(map(str, A)))
yes()
no()
yes()
no()
yes()
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 30 Days of Code > Day 24: More Linked Lists
// Welcome to Day 24! Review everything we've learned so far and learn more about Linked Lists in this challenge.
//
// https://www.hackerrank.com/challenges/30-linked-list-deletion/problem
//
#include <cstddef>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int d){
data=d;
next=NULL;
}
};
class Solution{
public:
// (skeliton_head) ----------------------------------------------------------------------
Node* removeDuplicates(Node *head)
{
//Write your code here
if (head == nullptr) return head;
Node *node = head;
while (node->next != nullptr)
{
if (node->data == node->next->data)
{
Node *old = node->next;
node->next = node->next->next;
delete old;
}
else
{
node = node->next;
}
}
return head;
}
// (skeliton_tail) ----------------------------------------------------------------------
Node* insert(Node *head,int data)
{
Node* p=new Node(data);
if(head==NULL){
head=p;
}
else if(head->next==NULL){
head->next=p;
}
else{
Node *start=head;
while(start->next!=NULL){
start=start->next;
}
start->next=p;
}
return head;
}
void display(Node *head)
{
Node *start=head;
while(start)
{
cout<<start->data<<" ";
start=start->next;
}
}
};
int main()
{
Node* head=NULL;
Solution mylist;
int T,data;
cin>>T;
while(T-->0){
cin>>data;
head=mylist.insert(head,data);
}
head=mylist.removeDuplicates(head);
mylist.display(head);
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Day 4: Class vs. Instance
# Learn the difference between class variables and instance variables.
#
# https://www.hackerrank.com/challenges/30-class-vs-instance/problem
#
class Person:
def __init__(self,initialAge):
# Add some more code to run some checks on initialAge
if initialAge < 0:
print("Age is not valid, setting age to 0.")
initialAge = 0
self.age = initialAge
def amIOld(self):
# Do some computations in here and print out the correct statement to the console
if self.age < 13:
print("You are young.")
elif self.age < 18:
print("You are a teenager.")
else:
print("You are old.")
def yearPasses(self):
# Increment the age of the person in here
self.age += 1
# (skeliton_tail) ----------------------------------------------------------------------
t = int(input())
for i in range(0, t):
age = int(input())
p = Person(age)
p.amIOld()
for j in range(0, 3):
p.yearPasses()
p.amIOld()
print("")
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 30 Days of Code > Day 23: BST Level-Order Traversal
# Implement a breadth-first search!
#
# https://www.hackerrank.com/challenges/30-binary-trees/problem
#
import sys
class Node:
def __init__(self,data):
self.right=self.left=None
self.data = data
class Solution:
def insert(self,root,data):
if root==None:
return Node(data)
else:
if data<=root.data:
cur=self.insert(root.left,data)
root.left=cur
else:
cur=self.insert(root.right,data)
root.right=cur
return root
# (skeliton_head) ----------------------------------------------------------------------
def levelOrder(self,root):
queue = []
result = []
queue.append(root)
while queue:
n = queue.pop(0)
if n:
result.append(n.data)
queue.append(n.left)
queue.append(n.right)
print(*result)
# (skeliton_tail) ----------------------------------------------------------------------
T=int(input())
myTree=Solution()
root=None
for i in range(T):
data=int(input())
root=myTree.insert(root,data)
myTree.levelOrder(root)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Day 6: Let's Review
// Characters and Strings
//
// https://www.hackerrank.com/challenges/30-review-loop/problem
//
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
string s;
cin >> s;
for (size_t i = 0; i < s.length(); ++i)
if (i % 2 == 0) cout << s[i];
cout << ' ';
for (size_t i = 0; i < s.length(); ++i)
if (i % 2 == 1) cout << s[i];
cout << endl;
}
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 30 Days of Code > Day 29: Bitwise AND
// Apply everything we've learned in this bitwise AND challenge.
//
// https://www.hackerrank.com/challenges/30-bitwise-and/problem
//
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t;
cin >> t;
while (t--)
{
int n, k;
cin >> n >> k;
int max = 0;
for (int i = 2; i < n; ++i)
{
for (int j = i + 1; j <= n; ++j)
{
int ij = i & j;
if (ij < k && ij > max) max = ij;
}
}
cout << max << endl;
}
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Day 0: Hello, World.
// Practice reading from stdin and printing to stdout.
//
// https://www.hackerrank.com/challenges/30-hello-world/problem
//
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
// (skeliton_head) ----------------------------------------------------------------------
int main() {
// Declare a variable named 'input_string' to hold our input.
char input_string[105];
// Read a full line of input from stdin and save it to our variable, input_string.
scanf("%[^\n]", input_string);
// Print a string literal saying "Hello, World." to stdout using printf.
printf("Hello, World.\n");
// TODO: Write a line of code here that prints the contents of input_string to stdout.
printf("%s\n", input_string);
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 30 Days of Code > Day 22: Binary Search Trees
# Given a binary tree, print its height.
#
# https://www.hackerrank.com/challenges/30-binary-search-trees/problem
#
class Node:
def __init__(self,data):
self.right=self.left=None
self.data = data
class Solution:
def insert(self,root,data):
if root==None:
return Node(data)
else:
if data<=root.data:
cur=self.insert(root.left,data)
root.left=cur
else:
cur=self.insert(root.right,data)
root.right=cur
return root
# (skeliton_head) ----------------------------------------------------------------------
def getHeight(self,root,height=0):
#Write your code here
h = height
if root.left is not None:
h = max(h, self.getHeight(root.left, height + 1))
if root.right is not None:
h = max(h, self.getHeight(root.right, height + 1))
return h
# (skeliton_tail) ----------------------------------------------------------------------
T=int(input())
myTree=Solution()
root=None
for i in range(T):
data=int(input())
root=myTree.insert(root,data)
height=myTree.getHeight(root)
print(height)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 30 Days of Code > Day 16: Exceptions - String to Integer
# Can you determine if a string can be converted to an integer?
#
# https://www.hackerrank.com/challenges/30-exceptions-string-to-integer/problem
#
S = input().strip()
try:
print(int(S))
except ValueError:
print("Bad String")
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 30 Days of Code > Day 26: Nested Logic
// Test your understanding of layered logic by calculating a library fine!
//
// https://www.hackerrank.com/challenges/30-nested-logic/problem
//
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int d1, m1, y1, d2, m2, y2;
cin >> d1 >> m1 >> y1;
cin >> d2 >> m2 >> y2;
int fine = 0;
if (y1 > y2)
fine = 10000; // plus d'un an de retard
else if (y1 == y2)
{
if (m1 > m2)
{
fine = (m1 - m2) * 500; // plus d'un mois de retard
}
else if (m1 == m2 && d1 > d2)
{
fine = (d1 - d2) * 15; // retard dans le même mois
}
}
cout << fine << endl;
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 30 Days of Code > Day 15: Linked List
# Complete the body of a function that adds a new node to the tail of a Linked List.
#
# https://www.hackerrank.com/challenges/30-linked-list/problem
#
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Solution:
def display(self,head):
current = head
while current:
print(current.data,end=' ')
current = current.next
# (skeliton_head) ----------------------------------------------------------------------
def insert(self,head,data):
#Complete this method
if head is None:
return Node(data)
node = head
while node.next is not None:
node = node.next
node.next = Node(data)
return head
# (skeliton_tail) ----------------------------------------------------------------------
mylist= Solution()
T=int(input())
head=None
for i in range(T):
data=int(input())
head=mylist.insert(head,data)
mylist.display(head);
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 30 Days of Code > Day 13: Abstract Classes
// Build on what you've already learned about Inheritance with this Abstract Classes challenge
//
// https://www.hackerrank.com/challenges/30-abstract-classes/problem
//
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
class Book{
protected:
string title;
string author;
public:
Book(string t,string a){
title=t;
author=a;
}
virtual void display()=0;
};
// (skeliton_head) ----------------------------------------------------------------------
class MyBook : public Book
{
int price;
public:
// Class Constructor
//
// Parameters:
// title - The book's title.
// author - The book's author.
// price - The book's price.
//
MyBook(const string& t, const string& a, int p) : Book(t, a), price(p)
{
}
// Function Name: display
// Print the title, author, and price in the specified format.
//
virtual void display() override
{
cout << "Title: " << this->Book::title << endl;
cout << "Author: " << this->Book::author << endl;
cout << "Price: " << price << endl;
}
};
// (skeliton_tail) ----------------------------------------------------------------------
int main() {
string title,author;
int price;
getline(cin,title);
getline(cin,author);
cin>>price;
MyBook novel(title,author,price);
novel.display();
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Day 7: Arrays
# Getting started with Arrays.
#
# https://www.hackerrank.com/challenges/30-arrays/problem
#
input()
print(" ".join(map(str, reversed(list(map(int, input().split()))))))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Day 2: Operators
// Start using arithmetic operators.
//
// https://www.hackerrank.com/challenges/30-operators/problem
//
#include <bits/stdc++.h>
using namespace std;
int main() {
double meal_cost;
cin >> meal_cost;
int tip_percent;
cin >> tip_percent;
int tax_percent;
cin >> tax_percent;
cout << "The total meal cost is "
<< round(meal_cost * (1 + tip_percent / 100. + tax_percent / 100.))
<< " dollars." << endl;
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Day 3: Intro to Conditional Statements
// Get started with conditional statements.
//
// https://www.hackerrank.com/challenges/30-conditional-statements/problem
//
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
if (n % 2 == 1 or (n >= 6 and n <= 20))
cout << "Weird" << endl;
else
cout << "Not Weird" << endl;
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 30 Days of Code > Day 25: Running Time and Complexity
# Determine if a number is prime in optimal time!
#
# https://www.hackerrank.com/challenges/30-running-time-and-complexity/problem
#
def est_premier(n):
""" teste si le nombre est premier """
if n <= 1:
return False
elif n == 2:
return True
elif n % 2 == 0:
return False
else:
i = 3
while i * i <= n:
if n % i == 0:
return False
i = i + 2
return True
for _ in range(int(input())):
print("Prime" if est_premier(int(input())) else "Not prime")
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank(30-arrays 30-arrays.cpp)
add_hackerrank(30-conditional-statements 30-conditional-statements.cpp)
add_hackerrank(30-data-types 30-data-types.cpp)
add_hackerrank(30-hello-world 30-hello-world.c)
add_hackerrank(30-operators 30-operators.cpp)
add_hackerrank(30-review-loop 30-review-loop.cpp)
add_hackerrank_py(30-arrays.py)
add_hackerrank_py(30-class-vs-instance.py)
add_hackerrank_py(30-data-types.py)
add_hackerrank_py(30-dictionaries-and-maps.py)
add_hackerrank_py(30-hello-world.py)
add_hackerrank_py(30-loops.py)
add_hackerrank_py(30-operators.py)
add_hackerrank_py(30-review-loop.py)
add_hackerrank_py(30-binary-numbers.py)
add_hackerrank(30-binary-numbers 30-binary-numbers.cpp)
add_hackerrank_py(30-2d-arrays.py)
add_hackerrank(30-2d-arrays 30-2d-arrays.cpp)
add_hackerrank(30-inheritance 30-inheritance.cpp)
add_hackerrank(30-generics 30-generics.cpp)
add_hackerrank(30-bitwise-and 30-bitwise-and.cpp)
add_hackerrank_py(30-scope.py)
add_hackerrank(30-scope 30-scope.cpp)
add_hackerrank_py(30-abstract-classes.py)
add_hackerrank(30-abstract-classes 30-abstract-classes.cpp)
add_hackerrank_py(30-linked-list.py)
add_hackerrank(30-linked-list 30-linked-list.cpp)
add_hackerrank_py(30-exceptions-string-to-integer.py)
add_hackerrank(30-exceptions-string-to-integer 30-exceptions-string-to-integer.cpp)
add_hackerrank(30-more-exceptions 30-more-exceptions.cpp)
add_hackerrank_py(30-queues-stacks.py)
add_hackerrank(30-running-time-and-complexity 30-running-time-and-complexity.cpp)
add_hackerrank_py(30-running-time-and-complexity.py)
add_hackerrank_py(30-binary-search-trees.py)
add_hackerrank(30-interfaces 30-interfaces.cpp)
add_hackerrank_py(30-binary-trees.py)
add_hackerrank(30-binary-trees 30-binary-trees.cpp)
add_hackerrank(30-sorting 30-sorting.cpp)
add_hackerrank(30-linked-list-deletion 30-linked-list-deletion.cpp)
add_hackerrank(30-nested-logic 30-nested-logic.cpp)
add_hackerrank_py(30-regex-patterns.py)
dirty_cpp(30-sorting)
dirty_cpp(30-arrays)
dirty_cpp(30-2d-arrays)
dirty_cpp(30-generics)
dirty_cpp(30-inheritance)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Day 8: Dictionaries and Maps
# Mapping Keys to Values using a Map or Dictionary.
#
# https://www.hackerrank.com/challenges/30-dictionaries-and-maps/problem
#
n = int(input())
d = {}
for _ in range(n):
k, v = input().split()
d[k] = v
for _ in range(n):
k = input()
if k in d:
print("{}={}".format(k, d[k]))
else:
print("Not found")
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 30 Days of Code > Day 10: Binary Numbers
# Find the maximum number of consecutive 1's in the base-2 representation of a base-10 number.
#
# https://www.hackerrank.com/challenges/30-binary-numbers/problem
#
n = int(input())
nb = 0
result = 0
while n != 0:
n, r = divmod(n, 2)
if r == 1:
nb += 1
if nb > result:
result = nb
else:
nb = 0
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 30 Days of Code > Day 9: Recursion
# Use recursion to compute the factorial of number.
#
# https://www.hackerrank.com/challenges/30-recursion/problem
#
def factorial(n):
if n < 2:
return 1
return n * factorial(n - 1)
if __name__ == "__main__":
n = int(input().strip())
result = factorial(n)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 30 Days of Code > Day 11: 2D Arrays
# Find the maximum sum of any hourglass in a 2D-Array.
#
# https://www.hackerrank.com/challenges/30-2d-arrays/problem
#
def array2D(arr):
resulat = -100
for i in range(0, 4):
for j in range(0, 4):
s = sum(arr[i][j:j + 3])
s += arr[i + 1][j + 1]
s += sum(arr[i + 2][j:j + 3])
if s > resulat:
resulat = s
return resulat
if __name__ == '__main__':
arr = []
for _ in range(6):
arr.append(list(map(int, input().split())))
result = array2D(arr)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Day 1: Data Types
# Get started with data types.
#
# https://www.hackerrank.com/challenges/30-data-types/problem
#
i = 4
d = 4.0
s = 'HackerRank '
# (skeliton_head) ----------------------------------------------------------------------
# Declare second integer, double, and String variables.
# Read and save an integer, double, and String to your variables.
i2 = int(input())
d2 = float(input())
s2 = input()
# Print the sum of both integer variables on a new line.
print(i + i2)
# Print the sum of the double variables on a new line.
print(d + d2)
# Concatenate and print the String variables on a new line
# The 's' variable above should be printed first.
print(s + s2)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Tutorials > 30 Days of Code > Day 17: More Exceptions
// Throw an exception when user sends wrong parameters to a method.
//
// https://www.hackerrank.com/challenges/30-more-exceptions/problem
//
#include <cmath>
#include <iostream>
#include <exception>
#include <stdexcept>
using namespace std;
// (skeliton_head) ----------------------------------------------------------------------
//Write your code here
class Calculator
{
public:
int power(int n, int p)
{
if (n < 0 || p < 0)
throw invalid_argument("n and p should be non-negative");
return (int) pow(n, p);
}
};
// (skeliton_tail) ----------------------------------------------------------------------
int main()
{
Calculator myCalculator=Calculator();
int T,n,p;
cin>>T;
while(T-->0){
if(scanf("%d %d",&n,&p)==2){
try{
int ans=myCalculator.power(n,p);
cout<<ans<<endl;
}
catch(exception& e){
cout<<e.what()<<endl;
}
}
}
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Day 1: Data Types
// Get started with data types.
//
// https://www.hackerrank.com/challenges/30-data-types/problem
//
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
int main() {
int i = 4;
double d = 4.0;
string s = "HackerRank ";
// (skeliton_head) ----------------------------------------------------------------------
// Declare second integer, double, and String variables.
int i2;
double d2;
string s2;
// Read and save an integer, double, and String to your variables.
cin >> i2 >> d2; getline(cin, s2);
getline(cin, s2);
// Print the sum of both integer variables on a new line.
cout << i + i2 << endl;
// Print the sum of the double variables on a new line.
cout << fixed << setprecision(1) << d + d2 << endl;
// Concatenate and print the String variables on a new line
// The 's' variable above should be printed first.
cout << s << s2 << endl;
// (skeliton_tail) ----------------------------------------------------------------------
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Day 7: Arrays
// Getting started with Arrays.
//
// https://www.hackerrank.com/challenges/30-arrays/problem
//
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> arr(n);
for(int arr_i = 0;arr_i < n;arr_i++)
{
cin >> arr[arr_i];
}
for(int arr_i = n;arr_i > 0;)
{
cout << arr[--arr_i] << " ";
}
cout << endl;
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Tutorials > 30 Days of Code > Day 18: Queues and Stacks
# Use stacks and queues to determine if a string is a palindrome.
#
# https://www.hackerrank.com/challenges/30-queues-stacks/problem
#
import sys
# (skeliton_head) ----------------------------------------------------------------------
class Solution:
def __init__(self):
self.queue = []
self.stack = []
def pushCharacter(self, ch):
self.stack.append(ch)
def popCharacter(self):
return self.stack.pop()
def enqueueCharacter(self, ch):
self.queue.append(ch)
def dequeueCharacter(self):
return self.queue.pop(0)
# (skeliton_tail) ----------------------------------------------------------------------
# read the string s
s=input()
#Create the Solution class object
obj=Solution()
l=len(s)
# push/enqueue all the characters of string s to stack
for i in range(l):
obj.pushCharacter(s[i])
obj.enqueueCharacter(s[i])
isPalindrome=True
'''
pop the top character from stack
dequeue the first character from queue
compare both the characters
'''
for i in range(l // 2):
if obj.popCharacter()!=obj.dequeueCharacter():
isPalindrome=False
break
#finally print whether string s is palindrome or not.
if isPalindrome:
print("The word, "+s+", is a palindrome.")
else:
print("The word, "+s+", is not a palindrome.")
| {
"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.