Code Monkey home page Code Monkey logo

add-up-to-100's Introduction

The problem

Write a program that outputs all possibilities to put + or - or nothing between the numbers 1, 2, ..., 9 (in this order) such that the result is always 100. For example: 1 + 2 + 34 โ€“ 5 + 67 โ€“ 8 + 9 = 100.

From

https://blog.svpino.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour

My Code

def next_options_for number, statement = nil
  next_number = number + 1
  statement   = number unless statement
  [
    "#{statement}#{next_number}",
    "#{statement} + #{next_number}",
    "#{statement} - #{next_number}",
  ].map do |x|
    {
      number:      number,
      next_number: next_number,
      statement:   x,
      value:       eval(x),
    }
  end
end

results = next_options_for 1
7.times { results = results.map { |o| next_options_for o[:next_number], o[:statement] }.flatten }
results.select { |x| x[:value] == 100 }
       .map    { |x| x[:statement] }

My Results

11 results, all equal 100

123 + 45 - 67 + 8 - 9

123 + 4 - 5 + 67 - 89

123 - 45 - 67 + 89

123 - 4 - 5 - 6 - 7 + 8 - 9

12 + 3 + 4 + 5 - 6 - 7 + 89

12 + 3 - 4 + 5 + 67 + 8 + 9

12 - 3 - 4 + 5 - 6 + 7 + 89

1 + 23 - 4 + 56 + 7 + 8 + 9

1 + 23 - 4 + 5 + 6 + 78 - 9

1 + 2 + 34 - 5 + 67 - 8 + 9

1 + 2 + 3 - 4 + 5 + 6 + 78 + 9

add-up-to-100's People

Contributors

darrencauthon avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.