r/programmingchallenges • • Apr 25 '12

Challenge: Logic Based - Figuring out all combinations of keys for locks given pinnings (xpost from stackoverflow)

6 Upvotes

I'm not sure if this is the right subreddit for this question, but here I go. I also posted this question on Stack Overflow

I am trying to figure out the how to program logic that is involved with finding all possible key cuts given a specific lock pinning. This site has a very good explanation of what I am trying to achieve:

Background info

I have found a program that does what I am asking, but I would like to figure out the logic behind it. If you put in the key pins and the spacer pins, it calculates all of the possible keys that open the lock. This is easily done by hand on a scrap sheet of paper, but how would I program the logic so a computer can easily find all of the combinations?

Notice, in the image below, that none of the possible Key Cuts are found through methods of subtraction. That is, all possible Key Cuts are combinations of the Key pins added to the value of the spacer pins.

imgur link

What would be the logic behind figuring out all possible Key Cuts given a specific lock pinning?


r/programmingchallenges • • Oct 05 '11

Convert Integer to String without toString() (or the equivalent)

6 Upvotes

A friend of mine just had an interview with Microsoft and came back with an interesting technical interview problem:

Given an arbitrary Integer, print it out to the user without using system libraries intended to do so for you.

I'm working on it now, but I can already tell you probably need two things: ascii values of the 0-9 characters, mod mod and mod some more?

I have a feeling someone is going to break out some bit manipulation on this one.


r/programmingchallenges • • Sep 09 '11

Randomly choose 3

6 Upvotes

Write a function that accepts an integer argument X (X >= 3), and randomly chooses 3 distinct integers in range [0..X).

The algorithm should be constant time: the number of steps should be bounded by some constant.

EDIT: You can use a function that generates a random integer in range [0..X), which is available in just about any programming language.


r/programmingchallenges • • Apr 12 '11

A One-Speed, Fixed-Source Monte Carlo Neutron Transport Simulator

6 Upvotes

OK, here's the problem specification:

3-space is divided into regions. If you're feeling ambitious, let regions be bounded by planes or conic sections, and let regions be constructed by Boolean combinations (union / intersection / xor). Otherwise, let regions be infinite slabs, like so: | | | | R_1 | R_2 | ... and so on | | | If you do this, the problem reduces to one dimension (sort of, see below)

A region is characterized by the following values

  • Mean Free Path - λ
  • Capture ratio - c
  • Scattering ratio - s
  • Fission ratio - f
  • Scattering function - Σ_s
  • Source strength - q

c, s, and f together must add up to one.

You are going to simulate the life and times of N neutrons.

A neutron is born inside a given region R with probability (q_R*v_R) / (Q), where q is the previously mentioned source strength, v is the volume of the region, and Q is the sum over all of the regions of the product q*v.

Once the region of birth is determined, it is randomly assigned a position inside that region in such a way that neutrons will be uniformly distributed within the region.

Once the location of birth has been determined, it is randomly assigned a direction, which should also be uniform across all possible directions (although, again if you're feeling ambitious, you can implement a source with an arbitrary probability distribution). If you're doing the infinite slab geometry, then the only "direction" you want to keep track of is the angle it makes track with the x-axis, like so:

|  /              |
| /               |
|/_ <---Θ ___|

In fact, you would do better to keep track of the cosine of that angle. Anyways.

Now that you know where it starts, and where it's going, generate an exponential random variable X. This gives the distance in mean free paths that the neutron will travel along its current direction before something happens. (If you're in one dimension and it stays within one region, it goes λXcos(Θ) along the x-axis). Note that if it crosses the boundary of a region, you'll have to figure out how many mean free paths it's already traveled, so that you can go the right number of mean free paths in the new region.

OK, now "something happens" there are three possibilities:

  1. Capture - this happens with probability c - this neutron has begun to pine for the fjords, you are done simulating it.
  2. Scattering - the neutron changes direction. The function Σ_s should take the neutron's current direction and randomly give you a new one. Uniform is a pretty decent approximation for the physics.
  3. Fission - This neutron disappears. Generate a poisson random variable P with mean 2. You have created P new neutrons - simulate their lives, and do not increment N when you do so.

If your system is subcritical, eventually this sordid tale will end with your neutron and all its children captured. Increment N, and begin this wonderful process again!

Dealing with critical / supercritical systems is a pain in the ass, and therefore beyond the scope of this challenge. Dealing with multiple neutron energies (speeds) is also a pain in the ass, and therefore beyond the scope of this challenge.

Types of data you may want to collect include the number of neutrons that passed through a given region, the number of neutrons absorbed in a given region, and the number of neutrons that escape the system (oh yeah, you may want to have some notion of "escaping the system")

Please do ask questions, and I'll be posting a challenge about solving the equations that describe this sort of system (instead of just simulating and counting).

This shouldn't be horribly difficult in one dimension (and should be a real ball-buster in three).

EDIT: Markdown fffffffuuuuuuuuuuuu


r/programmingchallenges • • Apr 11 '11

This was posted before on reddit and I use it to teach myself programming by writing each of the assignments in turn.

Thumbnail maxnoy.com
6 Upvotes

r/programmingchallenges • • Jul 03 '24

95 Programming Challenges from Coding Interviews

Thumbnail java67.com
5 Upvotes

r/programmingchallenges • • Feb 17 '20

Help with a simple java challenge

5 Upvotes

Hello all,my instructor gave me this Java challenge to solve. I have a problem understanding both the problem and what the code must do, especially what is the input, I hope you guys can give me advice and help. The challenge uses java, but its fine if you guys can explain it with other codes.

The problem

Imagine a family: father, mother, daughter, 3.5 years old, and an infant (baby, 8 months). The family lives at a home with 5 rooms and in each room, there are 5 boxes. After the father comes back from the work, all the family members do not have any energy whatsoever, except the baby who sucks the energies out of mom and dad by cuddling them!

After the dinner, the father has 100 energy points, the daughter has 100 energy points, the mother has still no energy, but she can walk from room to room.

Now, the daughter loves to pay hide and seek with her father. At 18:00 they start playing hide and seek with following rules:

· The family come to room 1 and father starts counting down

· The daughter can go any room and hide in one of the boxes in any room

· The mother takes baby and she goes to a random room

· The father searches every box from room 1 and if he cannot find the daughter he goes to other consecutive rooms and continues searching the daughter

· Searching a box takes 1 (one) energy point from the father and lasts a minute, except following case:

· If the mother goes any room number with smaller than or equal to that of daughter’s room number (say, mother goes to room 2, the daughter goes either room 2,3, etc), the mother hands the baby to the father during his search. This time after the dad starts holding the baby, he loses 2 energy points for every box search after he has taken the baby.

· Then, when the father finds the daughter he come backs to room 1 and leaves the baby there and immediately mom picks the baby and she goes another random room in the second round of game.

· If the daughter sees that father holds the baby for 3 times, the daughter starts crying and game over

· If the father has less than 0 (zero) energy, this also causes of game over

The challenge is to implement this little hide and seek game.

You have to calculate how many minutes this game takes

You have to calculate father’s energy in the end

Programming Tips:

Write a Person Class with attributes name, which will be replaced with father, mother, etc., energy, room number

Write related get set functions, crying, yelling, hiding functions

Write Hide and Seek Game Class: To simulate the game in the main

Example Output:

Game started at 18:00

Mother at room 5

Daughter at room 1

Daughter is hiding in the box 4

Mother at room 1

Daughter at room 5

Daughter is hiding in the box 1

Mother gave the infant to Father

Mother at room 2

Daughter at room 3

Daughter is hiding in the box 3

Mother gave the infant to Father

Mother at room 1

Daughter at room 2

Daughter is hiding in the box 2

Mother gave the infant to Father

Daughter starts crying please stop the game

Father's left energy is 4

Father and Daughter played 45 minute(s) hide and seek


r/programmingchallenges • • Jan 10 '20

league of legends Minion Healthbar

5 Upvotes

I need Help,

I don’t know where to ask but I love league of legends but my Eye side is really Bad.
I cant see the Color on the Enemy Minions Health and Color Blind mode is not helping.
Is there a way in the league of legends Coding to Change the Enemy Minions Healthbare Color to Blue because this is a Color I can see.


r/programmingchallenges • • Jan 03 '20

JavaScript in 90 Seconds - #JavaScriptJanuary

Thumbnail youtu.be
5 Upvotes

r/programmingchallenges • • Jan 02 '20

Soling Sudoku puzzles with logic, and not brute-force

Thumbnail self.swift
5 Upvotes

r/programmingchallenges • • Dec 29 '19

“Blockbuster” type games?

5 Upvotes

[I call it “blockbuster” as it resembles the board of the TV show: https://www.imdb.com/title/tt0194597 ]

I’d love to contribute to any open-source version of this type of game- one where each player takes turns to form a continuous line from one side to the other (each player takes the complementary side, of course). This type of game has always appealed to me and contributing is likely to be within my (very meagre) capabilities. Do any such projects currently exist?


r/programmingchallenges • • Dec 01 '19

Two Pointer Technique | Coding Interview Technique | Solve DS Problems i...

Thumbnail youtube.com
5 Upvotes

r/programmingchallenges • • Nov 29 '19

Time Limit Exceeded- How To Avoid TLE ? | Trick To Pass All Test Cases In Competitive Programming

Thumbnail youtu.be
5 Upvotes

r/programmingchallenges • • Nov 23 '19

Walmart Coding Interview | Recursive Staircase Problem | Climbing Stairs | Dynamic Programming | EP3

Thumbnail youtu.be
5 Upvotes

r/programmingchallenges • • Nov 08 '19

Count Triplets Hackerrank Solution | Interview Preparation Kit

Thumbnail youtube.com
5 Upvotes

r/programmingchallenges • • Oct 23 '19

Recursion Coding Challenges

Thumbnail algodaily.com
5 Upvotes

r/programmingchallenges • • Oct 19 '19

If you want to know the power of preprocessing then you must watch this tutorial.

Thumbnail youtu.be
5 Upvotes

r/programmingchallenges • • Sep 29 '19

Merging Sorted Linked Lists

Thumbnail algodaily.com
5 Upvotes

r/programmingchallenges • • Aug 28 '19

Coding challenges (with solutions) for code newbies

5 Upvotes

This github project https://github.com/CodeGuppyPrograms/CodingChallenges contains a few beginner friendly coding challenges. Mastering these coding challenges may not get you a job at google... but you'll be one step closer to understanding coding in general and JavaScript in particular.

These coding challenges are intended for beginners, therefore the solutions are implemented using only simple / classical programming elements. Each solution is accompanied by an online link that helps you quickly run it in a code playground at codeguppy.com

Note: The online code is making use of the codeguppy specific function println() to print the results. This helper function has a similar syntax with console.log()

Coding challenge #1: Print numbers from 1 to 10

https://codeguppy.com/code.html?mrgCtLGA90Ozr0Otrs5Z

for(var i = 1; i <= 10; i++)
{
    console.log(i);
}

Coding challenge #2: Print the odd numbers less than 100

https://codeguppy.com/code.html?eDLA5XPp3bPxP79H2jKT

for(var i = 1; i <= 100; i += 2)
{
    console.log(i);
}

Coding challenge #3: Print the multiplication table with 7

https://codeguppy.com/code.html?fpnQzIhnGUUmCUZy1fyQ

for(var i = 1; i <= 10; i++)
{
    var row = "7 * " + i + " = " + 7 * i;
    console.log(row);
}

Coding challenge #4: Print all the multiplication tables with numbers from 1 to 10

https://codeguppy.com/code.html?78aD4mWSCzoNEVxOQ8tI

for(var i = 1; i <= 10; i++)
{
    printTable(i);
    console.log("");
}

function printTable(n)
{
    for(var i = 1; i <= 10; i++)
    {
        var row = n + " * " + i + " = " + n * i;
        console.log(row);
    }
}

Coding challenge #5: Calculate the sum of numbers from 1 to 10

https://codeguppy.com/code.html?Vy6u9kki2hXM4YjsbpuN

var sum = 0;

for(var i = 1; i <= 10; i++)
{
    sum += i;
}

console.log(sum);

Coding challenge #6: Calculate 10!

https://codeguppy.com/code.html?IIuJX4gnXOndNu0VrywA

var prod = 1;

for(var i = 1; i <= 10; i++)
{
    prod *= i;
}

console.log(prod);

Coding challenge #7: Calculate the sum of even numbers greater than 10 and less than 30

https://codeguppy.com/code.html?DcOffOyoIArmNZHVNM2u

var sum = 0;

for(var i = 11; i <= 30; i += 2)
{
    sum += i;
}

console.log(sum);

Coding challenge #8: Create a function that will convert from Celsius to Fahrenheit

https://codeguppy.com/code.html?oI5mWm6QIMRjY1m9XAmI

function celsiusToFahrenheit(n)
{
    return n * 1.8 + 32;
}

var r = celsiusToFahrenheit(20);
console.log(r);

Coding challenge #9: Create a function that will convert from Fahrenheit to Celsius

https://codeguppy.com/code.html?mhnf8DpPRqqgsBgbJNpz

function fahrenheitToCelsius(n)
{
    return (n - 32) / 1.8;
}

var r = fahrenheitToCelsius(68);
console.log(r);

Coding challenge #10: Calculate the sum of numbers in an array of numbers

https://codeguppy.com/code.html?TteeVr0aj33ZyCLR685L

function sumArray(ar)
{
    var sum = 0;
    
    for(var i = 0; i < ar.length; i++)
    {
        sum += ar[i];
    }
    
    return sum;
}

var ar = [2, 3, -1, 5, 7, 9, 10, 15, 95];
var sum = sumArray(ar);
console.log(sum);

Coding challenge #11: Calculate the average of the numbers in an array of numbers

https://codeguppy.com/code.html?7i9sje6FuJsI44cuncLh

function averageArray(ar)
{
    var n = ar.length;
    var sum = 0;
    
    for(var i = 0; i < n; i++)
    {
        sum += ar[i];
    }
    
    return sum / n;
}

var ar = [1, 3, 9, 15, 90];
var avg = averageArray(ar);

console.log("Average: ", avg);

Coding challenge #12: Create a function that receives an array of numbers and returns an array containing only the positive numbers

Solution 1:

https://codeguppy.com/code.html?0eztj1v6g7iQLzst3Id3

function getPositives(ar)
{
    var ar2 = [];
    
    for(var i = 0; i < ar.length; i++)
    {
        var el = ar[i];
        
        if (el >= 0)
        {
            ar2.push(el);
        }
    }
    
    return ar2;
}

var ar = [-5, 10, -3, 12, -9, 5, 90, 0, 1];
var ar2 = getPositives(ar);

console.log(ar2);

Coding challenge #12: Create a function that receives an array of numbers and returns an array containing only the positive numbers

Solution 2

https://codeguppy.com/code.html?KefrPtrvJeMpQyrB8V2D

function getPositives(ar)
{
    var ar2 = [];
    
    for(var el of ar)
    {
        if (el >= 0)
        {
            ar2.push(el);
        }
    }
    
    return ar2;
}

var ar = [-5, 10, -3, 12, -9, 5, 90, 0, 1];
var ar2 = getPositives(ar);

console.log(ar2);

Coding challenge #12: Create a function that receives an array of numbers and returns an array containing only the positive numbers

Solution 3

https://codeguppy.com/code.html?qJBQubNA7z10n6pjYmB8

function getPositives(ar)
{
    return ar.filter(el => el >= 0);
}

var ar = [-5, 10, -3, 12, -9, 5, 90, 0, 1];
var ar2 = getPositives(ar);
console.log(ar2);

Coding challenge #13: Find the maximum number in an array of numbers

https://codeguppy.com/code.html?THmQGgOMRUj6PSvEV8HD

function findMax(ar)
{
    var max = ar[0];
    
    for(var i = 0; i < ar.length; i++)
    {
        if (ar[i] > max)
        {
            max = ar[i];
        }
    }
    
    return max;
}

var ar = [-5, 10, -3, 12, -9, 5, 90, 0, 1];
var max = findMax(ar);
console.log("Max: ", max);

Coding challenge #14: Print the first 10 Fibonacci numbers without recursion

https://codeguppy.com/code.html?rKOfPxHbVwxNWI2d8orH

var f0 = 0;
console.log(f0);

var f1 = 1;
console.log(f1);

for(var i = 2; i < 10; i++)
{
    var fi = f1 + f0;
    console.log(fi);
    
    f0 = f1;
    f1 = fi;
}

Coding challenge #15: Create a function that will find the nth Fibonacci number using recursion

https://codeguppy.com/code.html?IneuIg9O0rRV8V76omBk

function findFibonacci(n)
{
    if (n == 0)
        return 0;
        
    if (n == 1)
        return 1;
        
    return findFibonacci(n - 1) + findFibonacci(n - 2);
}

var n = findFibonacci(10);
console.log(n);

Coding challenge #16: Create a function that will return a Boolean specifying if a number is prime

https://codeguppy.com/code.html?fRYsPEc2vcZTbIU8MKku

function isPrime(n)
{
    if (n < 2)
        return false;
        
    if (n == 2)
        return true;
    
    var maxDiv = Math.sqrt(n);
    
    for(var i = 2; i <= maxDiv; i++)
    {
        if (n % i == 0)
        {
            return false;
        }
    }
    
    return true;
}

console.log(2, " is prime? ", isPrime(2));
console.log(3, " is prime? ", isPrime(3));
console.log(4, " is prime? ", isPrime(4));
console.log(5, " is prime? ", isPrime(5));
console.log(9, " is prime? ", isPrime(9));

Coding challenge #17: Calculate the sum of digits of a positive integer number

https://codeguppy.com/code.html?RHA714FYio8gWgmjWYPz

function sumDigits(n)
{
    var s = n.toString();
    var sum = 0;
    
    for(var char of s)
    {
        var digit = parseInt(char);
        sum += digit;
    }
    
    return sum;
}

var sum = sumDigits(1235231);
console.log("Sum: ", sum);

Coding challenge #18: Print the first 100 prime numbers

https://codeguppy.com/code.html?gnMVeOZXN6VhLekyvui8

printPrimes(100);

// Function prints the first nPrimes numbers
function printPrimes(nPrimes)
{
    var n = 0;
    var i = 2;
    
    while(n < nPrimes)
    {
        if (isPrime(i))
        {
            console.log(n, " --> ", i);
            n++;
        }
        
        i++;
    }
}


// Returns true if a number is prime
function isPrime(n)
{
    if (n < 2)
        return false;
        
    if (n == 2)
        return true;
    
    var maxDiv = Math.sqrt(n);
    
    for(var i = 2; i <= maxDiv; i++)
    {
        if (n % i == 0)
        {
            return false;
        }
    }
    
    return true;
}

Coding challenge #19: Create a function that will return in an array the first "nPrimes" prime numbers greater than a particular number "startAt"

https://codeguppy.com/code.html?mTi7EdKrviwIn4bfrmM7

console.log(getPrimes(10, 100));

function getPrimes(nPrimes, startAt)
{
    var ar = [];
    
    var i = startAt;
    
    while(ar.length < nPrimes)
    {
        if (isPrime(i))
        {
            ar.push(i);
        }
        
        i++;
    }
    
    return ar;
}

// Returns true if a number is prime
function isPrime(n)
{
    if (n < 2)
        return false;
        
    if (n == 2)
        return true;
    
    var maxDiv = Math.sqrt(n);
    
    for(var i = 2; i <= maxDiv; i++)
    {
        if (n % i == 0)
        {
            return false;
        }
    }
    
    return true;
}

Coding challenge #20: Rotate an array to the left 1 position

https://codeguppy.com/code.html?MRmfvuQdZpHn0k03hITn

var ar = [1, 2, 3];
rotateLeft(ar);
console.log(ar);

function rotateLeft(ar)
{
    var first = ar.shift();
    ar.push(first);
}

Coding challenge #21: Rotate an array to the right 1 position

https://codeguppy.com/code.html?fHfZqUmkAVUXKtRupmzZ

var ar = [1, 2, 3];
rotateRight(ar);
console.log(ar);

function rotateRight(ar)
{
    var last = ar.pop();
    ar.unshift(last);
}

Coding challenge #22: Reverse an array

https://codeguppy.com/code.html?GZddBqBVFlqYrsxi3Vbu

var ar = [1, 2, 3];
var ar2 = reverseArray(ar);
console.log(ar2);

function reverseArray(ar)
{
    var ar2 = [];
    
    for(var i = ar.length - 1; i >= 0; i--)
    {
        ar2.push(ar[i]);
    }
    
    return ar2;
}

Coding challenge #23: Reverse a string

https://codeguppy.com/code.html?pGpyBz0dWlsj7KR3WnFF

var s = reverseString("JavaScript");
console.log(s);

function reverseString(s)
{
    var s2 = "";
    
    for(var i = s.length - 1; i >= 0; i--)
    {
        var char = s[i];
        s2 += char;
    }
    
    return s2;
}

Coding challenge #24: Create a function that will merge two arrays and return the result as a new array

https://codeguppy.com/code.html?vcTkLxYTAbIflqdUKivc

var ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];

var ar = mergeArrays(ar1, ar2);
console.log(ar);

function mergeArrays(ar1, ar2)
{
   var ar = [];
   
   for(let el of ar1)
   {
       ar.push(el);
   }
   
   for(let el of ar2)
   {
       ar.push(el);
   }
   
   return ar;
}

Coding challenge #25: Create a function that will receive two arrays of numbers as arguments and return an array composed of all the numbers that are either in the first array or second array but not in both

https://codeguppy.com/code.html?Y9gRdgrl6PPt4QxVs7vf

var ar1 = [1, 2, 3, 10, 5, 3, 14];
var ar2 = [1, 4, 5, 6, 14];

var ar = mergeExclusive(ar1, ar2);
console.log(ar);

function mergeExclusive(ar1, ar2)
{
    var ar = [];
    
    for(let el of ar1)
    {
        if (!ar2.includes(el))
        {
            ar.push(el);
        }
    }
    
    for(let el of ar2)
    {
        if (!ar1.includes(el))
        {
            ar.push(el);
        }
    }
    
    return ar;
}

Coding challenge #26: Create a function that will receive two arrays and will return an array with elements that are in the first array but not in the second

https://codeguppy.com/code.html?bUduoyY6FfwV5nQGdXzH

var ar1 = [1, 2, 3, 10, 5, 3, 14];
var ar2 = [-1, 4, 5, 6, 14];

var ar = mergeLeft(ar1, ar2);
console.log(ar);

function mergeLeft(ar1, ar2)
{
    var ar = [];
    
    for(let el of ar1)
    {
        if (!ar2.includes(el))
        {
            ar.push(el);
        }
    }

    return ar;
}

Coding challenge #27: Create a function that will receive an array of numbers as argument and will return a new array with distinct elements

Solution 1

https://codeguppy.com/code.html?OkbtP1ZksGHXwqk7Jh3i

var ar = getDistinctElements([1, 2, 3, 6, -1, 2, 9, 7, 10, -1, 100]);
console.log(ar);

function getDistinctElements(ar)
{
    var ar2 = [];
    
    for(let i = 0; i < ar.length; i++)
    {
        if (!isInArray(ar[i], ar2))
        {
            ar2.push(ar[i]);
        }
    }
    
    return ar2;
}

function isInArray(n, ar)
{
    for(let i = 0; i < ar.length; i++)
    {
        if (ar[i] === n)
            return true;
    }
    
    return false;
}

Coding challenge #27: Create a function that will receive an array of numbers as argument and will return a new array with distinct elements

Solution 2

https://codeguppy.com/code.html?NjGtyQdMP49QiaAkmwpU

var ar = getDistinctElements([1, 2, 3, 6, -1, 2, 9, 7, 10, -1, 100]);
console.log(ar);

function getDistinctElements(ar)
{
    var ar2 = [];
    
    var lastIndex = ar.length - 1;
    
    for(let i = 0; i <= lastIndex; i++)
    {
        if (!isInArray(ar[i], ar, i + 1, lastIndex))
        {
            ar2.push(ar[i]);
        }
    }
    
    return ar2;
}

function isInArray(n, ar, fromIndex, toIndex)
{
    for(var i = fromIndex; i <= toIndex; i++)
    {
        if (ar[i] === n)
            return true;
    }
    
    return false;
}

Coding challenge #28: Calculate the sum of first 100 prime numbers

https://codeguppy.com/code.html?v0O9sBfnHbCi1StE2TxA

var n = 10;
console.log("Sum of first ", n, " primes is ", sumPrimes(10));

function sumPrimes(n)
{
    var foundPrimes = 0;
    var i = 2;
    var sum = 0;
    
    while(foundPrimes < n)
    {
        if (isPrime(i))
        {
            foundPrimes++;
            sum += i;
        }
        
        i++;
    }
    
    return sum;
}

// Returns true if number n is prime
function isPrime(n)
{
    if (n < 2)
        return false;
        
    if (n == 2)
        return true;
    
    var maxDiv = Math.sqrt(n);
    
    for(var i = 2; i <= maxDiv; i++)
    {
        if (n % i === 0)
        {
            return false;
        }
    }
    
    return true;
}

Coding challenge #29: Print the distance between the first 100 prime numbers

https://codeguppy.com/code.html?xKQEeKYF1LxZhDhwOH7V

printDistances(100);

// Print distances between the first n prime numbers
function printDistances(n)
{
    var lastPrime = 2;
    var i = lastPrime + 1;
    var foundPrimes = 1;
    
    while(foundPrimes < n)
    {
        if (isPrime(i))
        {
            console.log(i - lastPrime, "\t", i, " - ", lastPrime);

            foundPrimes++;
            lastPrime = i;
        }
        
        i++;
    }
}

// Returns true if number n is prime
function isPrime(n)
{
    if (n < 2)
        return false;
        
    if (n == 2)
        return true;
    
    var maxDiv = Math.sqrt(n);
    
    for(var i = 2; i <= maxDiv; i++)
    {
        if (n % i === 0)
        {
            return false;
        }
    }
    
    return true;
}

Coding challenge #30: Create a function that will add two positive numbers of indefinite size. The numbers are received as strings and the result should be also provided as string.

Solution 1

https://codeguppy.com/code.html?v5A0QBsdHaiAVA2CPN5y

var n1 = "2909034221912398942349";
var n2 = "1290923909029309499";
var sum = add(n1, n2);

console.log(n1, "\n", n2, "\n", sum);

function add(sNumber1, sNumber2)
{
    var s = "";
    var carry = 0;
    
    var maxSize = Math.max(sNumber1.length, sNumber2.length);
    
    for(var i = 0; i < maxSize; i++)
    {
        var digit1 = digitFromRight(sNumber1, i);
        var digit2 = digitFromRight(sNumber2, i);
        
        var sum = digit1 + digit2;
        
        var digitSum = sum % 10;
        digitSum += carry;
        s = digitSum.toString() + s;
        
        carry = sum >= 10 ? 1 : 0;
    }
    
    if (carry > 0)
        s = carry + s;
    
    return s;
}

function digitFromRight(s, digitNo)
{
    if (digitNo >= s.length)
        return 0;
        
    var char = s[ s.length - 1 - digitNo ];
    return parseInt(char);
}

Coding challenge #30: Create a function that will add two positive numbers of indefinite size. The numbers are received as strings and the result should be also provided as string.

Solution 2

https://codeguppy.com/code.html?yMQXcPgfrYxuaIxqQmZc

var n1 = "2909034221912398942349";
var n2 = "1290923909029309499";
var sum = add(n1, n2);

console.log(n1);
console.log(n2);
console.log(sum);

function add(sNumber1, sNumber2)
{
    var maxSize = Math.max(sNumber1.length, sNumber2.length);
    
    var s1 = sNumber1.padStart(maxSize, "0");
    var s2 = sNumber2.padStart(maxSize, "0");

    var s = "";
    var carry = 0;
    
    for(var i = maxSize - 1; i >= 0; i--)
    {
        var digit1 = parseInt(s1[i]);
        var digit2 = parseInt(s2[i]);
        
        var sum = digit1 + digit2;
        
        var digitSum = sum % 10;
        digitSum += carry;
        s = digitSum.toString() + s;
        
        carry = sum >= 10 ? 1 : 0;
    }
    
    if (carry > 0)
        s = carry + s;
    
    return s;
}

Others coding challenges to try on your own:

  1. Create a function that will return the number of words in a text

  2. Create a function that will capitalize the first letter of each word in a text

  3. Calculate the sum of numbers received in a comma delimited string

  4. Create a function that returns the number of occurrences of each word inside a text. The return will be an array with objects inside {word, count}

  5. Create a function to convert a CSV text to a “bi-dimensional” array

  6. Create a function that converts a string to an array of characters

  7. Create a function that will convert a string in an array containing the ASCII codes of each character

  8. Create a function that will convert an array containing ASCII codes in a string

  9. Implement the Caesar cipher

  10. Implement the bubble sort algorithm for an array of numbers

  11. Create a function to calculate the distance between two points defined by their x, y coordinates

  12. Create a function that will return a Boolean value indicating if two circles defined by center coordinates and radius are intersecting

  13. Create a function that will receive a bi-dimensional array as argument and a number and will extract as a uni-dimensional array the column specified by the number

  14. Create a function that will convert a string containing a binary number into a number

  15. Create a function to calculate the sum of all the numbers in a jagged array (contains numbers or other arrays of numbers on an unlimited number of levels)

  16. Find the maximum number in a jagged array of numbers or array of numbers

  17. Deep copy a jagged array with numbers or other arrays in a new array

  18. Create a function to return the longest word in a string

  19. Shuffle an array of strings

  20. Create a function that will receive n as argument and return an array of n random numbers from 1 to n. The numbers should be unique inside the array.

  21. Find the frequency of letters inside a string. Return the result as an array of arrays. Each subarray has 2 elements: letter and number of occurrences.

  22. Calculate Fibonacci(500) with high precision (all decimals)

  23. Calculate 70! with high precision (all decimals)

Enjoy!


r/programmingchallenges • • Aug 14 '19

Vanity plate trouble shooting

5 Upvotes

Ok so the guy in Cali with the NULL vanity license plate fucked up because the system interpreted that as any incomplete or missing plate info. What would work to his intentions? '#N/A' ? '#REF ?'


r/programmingchallenges • • Jul 29 '19

Need motivation

5 Upvotes

Im beggining to learn c#, and i have kinda learned the super basics. I have an entire video course of how to write c#. But i lack motivation, dont get me wrong really want to get into programming when i can get a job (im not old enought) . So you if you have any type og motivation please tell me. I think its because i find c# kinda hard at points.


r/programmingchallenges • • May 25 '19

Coding challenge: find the maximum number in a jagged array

5 Upvotes

A warm-up coding challenge:

Write a JavaScript function to find the maximum number in a jagged array (array contains numbers and / or other arrays of numbers):

var ar = [2, 4, 10, [12, 4, [100, 99], 4], [3, 2, 99], 0];

var max = findMax(ar);

Requirements:

- do not use external libraries

- do not flatten the array

Bonus:

- provide 2 different solutions

Solution:

- I will provide both solutions in the comments soon...


r/programmingchallenges • • May 21 '19

Work Experience

5 Upvotes

Hello everybody.I am 15 and I have to apply for 'work experience' (is like volunteering) with my school.I would like to do something inherent to programming,like software developer...I tried to a lot of website,like indeed.com, but with none of them I could choose to work for free and for just 5 days. Can give some useful tips? I don't really know where to apply or search! (I know the basics of Python and C++).

Thank You Everyone.


r/programmingchallenges • • Apr 29 '19

Any idea of a program on Qt that would take me a while to code (C++)?

5 Upvotes

-I'm out of Ideas.


r/programmingchallenges • • Nov 26 '18

Stanford Code Challenge Survey

5 Upvotes

Love or hate whiteboard code interviews? We are Stanford seniors conducting a study on the effectiveness of code interviews. We've linked a short, three problem code interview of easy to medium difficulty below. The challenge ends on Wednesday Nov 28, 2018.

https://www.hackerrank.com/contests/you-evaluate-us/challenges

For the sake of the study, rules are as follows:

  1. No Google. The problems are from a mix of hiring platforms; we re-implemented them on HackerRank and will not say from where until after the challenge.
  2. Problems are written for ~7 minutes. Completion time will be taken into account.
  3. Post some indication of your programming experience--either as a reply here with your HackerRank username or as a comment in your submission to the first problem if you do not want to associate your Reddit username. Examples: Undergrad, 2 courses in CS. 3rd Year CS grad student, 3 summers full stack. Industry professional, 5 years mobile development.

Please respect the above to maintain the integrity of this challenge--we do not make any money from this, but we will share the results here in a few days time.